@flowengage/react-chatbot 1.4.9 → 1.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(e&&(t=e(e=0)),t),s=(e,n)=>{let r={};for(var i in e)t(r,i,{get:e[i],enumerable:!0});return n||t(r,Symbol.toStringTag,{value:`Module`}),r},c=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},l=(n,r,a)=>(a=n==null?{}:e(i(n)),c(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n)),u=e=>a.call(e,`module.exports`)?e[`module.exports`]:c(t({},`__esModule`,{value:!0}),e);let d=require(`react`);d=l(d);let f=require(`react/jsx-runtime`);var p=e=>{if(!e||typeof e!=`object`)throw Error(`FlowEngage config is required`);if(!e.siteId||typeof e.siteId!=`string`)throw Error(`[FlowEngage] config.siteId is required. Pass it as <FlowEngageProvider siteId="your-site-id" /> or config={{ siteId: 'your-site-id' }}.`);let t=(e.apiBaseUrl||`https://be-flowengage.oslabs.app`).replace(/\/+$/,``);return{siteId:e.siteId.trim(),apiBaseUrl:t}},m={chatId:`flowengage.chatId`,isOpen:`flowengage.isOpen`,activeScreen:`flowengage.activeScreen`,isHumanHandled:`flowengage.isHumanHandled`,agentName:`flowengage.agentName`,agentHeadshot:`flowengage.agentHeadshot`,visitorEmail:`flowengage.visitorEmail`},h=1e4,g=12e4,_=6e4,v=480*60,y=3e4,b=typeof window<`u`,x=e=>e?`flowengage.visitorEmail.${e}`:null,S=()=>{if(!b)return`server-chat-id`;let e=window.localStorage.getItem(m.chatId);if(e)return e;let t=typeof crypto<`u`&&crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`;return window.localStorage.setItem(m.chatId,t),t},ee=()=>b?{isOpen:!1,activeScreen:window.sessionStorage.getItem(m.activeScreen)||`ai`,isHumanHandled:window.sessionStorage.getItem(m.isHumanHandled)===`true`,agentName:window.sessionStorage.getItem(m.agentName),agentHeadshot:window.sessionStorage.getItem(m.agentHeadshot),visitorEmail:``}:{isOpen:!1,activeScreen:`ai`,isHumanHandled:!1,agentName:null,agentHeadshot:null,visitorEmail:``},te=e=>{b&&Object.entries(e).forEach(([e,t])=>{let n=m[e];if(n){if(t==null||t===!1){window.sessionStorage.removeItem(n);return}window.sessionStorage.setItem(n,String(t))}})},C=e=>{if(!b||!e)return``;let t=x(e),n=window.localStorage.getItem(t);if(!n){let e=window.sessionStorage.getItem(m.visitorEmail);e&&(window.localStorage.setItem(t,e),window.sessionStorage.removeItem(m.visitorEmail),n=e)}return n||``},ne=(e,t)=>{if(!b)return;let n=x(t);if(!n)return;let r=typeof e==`string`?e.trim():``;if(!r){window.localStorage.removeItem(n),window.sessionStorage.removeItem(m.visitorEmail);return}window.localStorage.setItem(n,r),window.sessionStorage.removeItem(m.visitorEmail)},re=async e=>{let t=await e.json().catch(()=>({}));if(!e.ok){let n=Error(t.message||t.error||`Request failed with status ${e.status}`);throw n.status=e.status,n}return t},ie=async(e,t={})=>{try{return await fetch(e,{mode:`cors`,...t})}catch(t){let n=Error(`Network error reaching ${e}. Check: (1) backend is running, (2) CORS allows this origin, (3) siteId is correct. Original: ${t.message}`);throw n.status=0,n.cause=t,n}},ae=async({apiBaseUrl:e,siteId:t})=>{let n=typeof window<`u`?window.location.origin:`http://localhost`,r=`${e}/api/widget/chatbot-loader?${new URLSearchParams({siteId:t,origin:n}).toString()}`;console.log(`[FlowEngageAPI] bootstrap request`,{apiBaseUrl:e,siteId:t,origin:n,url:r});let i=await re(await ie(r,{method:`GET`}));return console.log(`[FlowEngageAPI] bootstrap success`,i),i.data},oe=({apiBaseUrl:e,userId:t,siteId:n})=>{let r=(t,n)=>{let r=`${e}${t}`,i=JSON.stringify(n);if(typeof navigator<`u`&&navigator.sendBeacon)try{let e=new Blob([i],{type:`application/json`});return navigator.sendBeacon(r,e)}catch{}return typeof fetch<`u`?(fetch(r,{method:`POST`,mode:`cors`,keepalive:!0,headers:{"Content-Type":`application/json`},body:i}).catch(()=>{}),!0):!1},i=async(r,i={})=>re(await ie(`${e}${r}`,{...i,headers:{"Content-Type":`application/json`,"x-user-id":t,...n?{"x-site-id":n}:{},...i.headers||{}}}));return{async loadHistory(e,t=`en`,n=``){return i(`/api/ai/chat`,{method:`POST`,body:JSON.stringify({session_id:e,user_query:``,lang:t,category:n})})},async sendAiMessage(e,t,n=`en`,r=``,a=null){return i(`/api/ai/chat`,{method:`POST`,body:JSON.stringify({session_id:e,user_query:t,lang:n,category:r,...a||{}})})},async checkHumanHandled(e){return i(`/api/ai/check_human_handled`,{method:`POST`,body:JSON.stringify({session_id:e})})},async setChatMode(e,t){return i(`/api/ai/set_chat_mode`,{method:`POST`,body:JSON.stringify({session_id:e,mode:t})})},async toggleVoice(e){return i(`/api/ai/voice/toggle`,{method:`POST`,body:JSON.stringify({session_id:e})})},async syncVoice(e,r){return i(`/api/ai/voice/sync`,{method:`POST`,body:JSON.stringify({session_id:e,messages:r,...t?{userId:String(t)}:{},...n?{siteId:String(n)}:{}})})},async trackVisitor(e){return i(`/api/visitors/track`,{method:`POST`,body:JSON.stringify(e)})},async updateChatStatus(e,t){return i(`/api/chat/status`,{method:`POST`,body:JSON.stringify({chatId:e,type:t})})},async startConversation(e,t=`en`){return i(`/api/chat/status`,{method:`POST`,body:JSON.stringify({chatId:e,type:`open`,lang:t})})},async endConversation(e){return i(`/api/chat/status`,{method:`POST`,body:JSON.stringify({chatId:e,type:`closed`})})},async acceptCall(e,t){return i(`/api/calls/${e}/accept`,{method:`POST`,body:JSON.stringify({session_id:t,site_id:n})})},async rejectCall(e,t){return i(`/api/calls/${e}/reject`,{method:`POST`,body:JSON.stringify({session_id:t,site_id:n})})},async getIceServersConfig(){return re(await ie(`${e}/api/calls/ice-config`,{method:`GET`,headers:{"x-user-id":t,...n?{"x-site-id":n}:{}}}))},async endWebRTCCall(e,t){return i(`/api/calls/${e}/end`,{method:`POST`,body:JSON.stringify({session_id:t,site_id:n,endedBy:`customer`})})},async markCustomerUnavailable(e,t){return i(`/api/calls/${e}/customer-unavailable`,{method:`POST`,body:JSON.stringify({session_id:t,site_id:n})})},beaconEndWebRTCCall(e,t){return r(`/api/calls/${e}/end`,{session_id:t,site_id:n,endedBy:`customer`})},beaconCustomerUnavailable(e,t){return r(`/api/calls/${e}/customer-unavailable`,{session_id:t,site_id:n})},beaconSyncVoice(r,i){if(typeof navigator>`u`||!navigator.sendBeacon)return!1;let a={session_id:r,messages:i,...t?{userId:String(t)}:{},...n?{siteId:String(n)}:{}},o=new Blob([JSON.stringify(a)],{type:`application/json`});return navigator.sendBeacon(`${e}/api/ai/voice/sync`,o)}}},se=Object.create(null);se.open=`0`,se.close=`1`,se.ping=`2`,se.pong=`3`,se.message=`4`,se.upgrade=`5`,se.noop=`6`;var ce=Object.create(null);Object.keys(se).forEach(e=>{ce[se[e]]=e});var le={type:`error`,data:`parser error`},ue=typeof Blob==`function`||typeof Blob<`u`&&Object.prototype.toString.call(Blob)===`[object BlobConstructor]`,de=typeof ArrayBuffer==`function`,fe=e=>typeof ArrayBuffer.isView==`function`?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,pe=({type:e,data:t},n,r)=>ue&&t instanceof Blob?n?r(t):me(t,r):de&&(t instanceof ArrayBuffer||fe(t))?n?r(t):me(new Blob([t]),r):r(se[e]+(t||``)),me=(e,t)=>{let n=new FileReader;return n.onload=function(){let e=n.result.split(`,`)[1];t(`b`+(e||``))},n.readAsDataURL(e)};function he(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}var ge;function _e(e,t){if(ue&&e.data instanceof Blob)return e.data.arrayBuffer().then(he).then(t);if(de&&(e.data instanceof ArrayBuffer||fe(e.data)))return t(he(e.data));pe(e,!1,e=>{ge||=new TextEncoder,t(ge.encode(e))})}var ve=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,ye=typeof Uint8Array>`u`?[]:new Uint8Array(256);for(let e=0;e<64;e++)ye[ve.charCodeAt(e)]=e;var be=e=>{let t=e.length*.75,n=e.length,r,i=0,a,o,s,c;e[e.length-1]===`=`&&(t--,e[e.length-2]===`=`&&t--);let l=new ArrayBuffer(t),u=new Uint8Array(l);for(r=0;r<n;r+=4)a=ye[e.charCodeAt(r)],o=ye[e.charCodeAt(r+1)],s=ye[e.charCodeAt(r+2)],c=ye[e.charCodeAt(r+3)],u[i++]=a<<2|o>>4,u[i++]=(o&15)<<4|s>>2,u[i++]=(s&3)<<6|c&63;return l},xe=typeof ArrayBuffer==`function`,Se=(e,t)=>{if(typeof e!=`string`)return{type:`message`,data:we(e,t)};let n=e.charAt(0);return n===`b`?{type:`message`,data:Ce(e.substring(1),t)}:ce[n]?e.length>1?{type:ce[n],data:e.substring(1)}:{type:ce[n]}:le},Ce=(e,t)=>xe?we(be(e),t):{base64:!0,data:e},we=(e,t)=>{switch(t){case`blob`:return e instanceof Blob?e:new Blob([e]);default:return e instanceof ArrayBuffer?e:e.buffer}},Te=``,Ee=(e,t)=>{let n=e.length,r=Array(n),i=0;e.forEach((e,a)=>{pe(e,!1,e=>{r[a]=e,++i===n&&t(r.join(Te))})})},De=(e,t)=>{let n=e.split(Te),r=[];for(let e=0;e<n.length;e++){let i=Se(n[e],t);if(r.push(i),i.type===`error`)break}return r};function Oe(){return new TransformStream({transform(e,t){_e(e,n=>{let r=n.length,i;if(r<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,r);else if(r<65536){i=new Uint8Array(3);let e=new DataView(i.buffer);e.setUint8(0,126),e.setUint16(1,r)}else{i=new Uint8Array(9);let e=new DataView(i.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(r))}e.data&&typeof e.data!=`string`&&(i[0]|=128),t.enqueue(i),t.enqueue(n)})}})}var ke;function Ae(e){return e.reduce((e,t)=>e+t.length,0)}function je(e,t){if(e[0].length===t)return e.shift();let n=new Uint8Array(t),r=0;for(let i=0;i<t;i++)n[i]=e[0][r++],r===e[0].length&&(e.shift(),r=0);return e.length&&r<e[0].length&&(e[0]=e[0].slice(r)),n}function w(e,t){ke||=new TextDecoder;let n=[],r=0,i=-1,a=!1;return new TransformStream({transform(o,s){for(n.push(o);;){if(r===0){if(Ae(n)<1)break;let e=je(n,1);a=(e[0]&128)==128,i=e[0]&127,r=i<126?3:i===126?1:2}else if(r===1){if(Ae(n)<2)break;let e=je(n,2);i=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),r=3}else if(r===2){if(Ae(n)<8)break;let e=je(n,8),t=new DataView(e.buffer,e.byteOffset,e.length),a=t.getUint32(0);if(a>2**21-1){s.enqueue(le);break}i=a*2**32+t.getUint32(4),r=3}else{if(Ae(n)<i)break;let e=je(n,i);s.enqueue(Se(a?e:ke.decode(e),t)),r=0}if(i===0||i>e){s.enqueue(le);break}}}})}function T(e){if(e)return Me(e)}function Me(e){for(var t in T.prototype)e[t]=T.prototype[t];return e}T.prototype.on=T.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks[`$`+e]=this._callbacks[`$`+e]||[]).push(t),this},T.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},T.prototype.off=T.prototype.removeListener=T.prototype.removeAllListeners=T.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var n=this._callbacks[`$`+e];if(!n)return this;if(arguments.length==1)return delete this._callbacks[`$`+e],this;for(var r,i=0;i<n.length;i++)if(r=n[i],r===t||r.fn===t){n.splice(i,1);break}return n.length===0&&delete this._callbacks[`$`+e],this},T.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=Array(arguments.length-1),n=this._callbacks[`$`+e],r=1;r<arguments.length;r++)t[r-1]=arguments[r];if(n){n=n.slice(0);for(var r=0,i=n.length;r<i;++r)n[r].apply(this,t)}return this},T.prototype.emitReserved=T.prototype.emit,T.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks[`$`+e]||[]},T.prototype.hasListeners=function(e){return!!this.listeners(e).length};var Ne=typeof Promise==`function`&&typeof Promise.resolve==`function`?e=>Promise.resolve().then(e):(e,t)=>t(e,0),Pe=typeof self<`u`?self:typeof window<`u`?window:Function(`return this`)(),Fe=`arraybuffer`;function Ie(e,...t){return t.reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{})}var Le=Pe.setTimeout,Re=Pe.clearTimeout;function ze(e,t){t.useNativeTimers?(e.setTimeoutFn=Le.bind(Pe),e.clearTimeoutFn=Re.bind(Pe)):(e.setTimeoutFn=Pe.setTimeout.bind(Pe),e.clearTimeoutFn=Pe.clearTimeout.bind(Pe))}var Be=1.33;function Ve(e){return typeof e==`string`?E(e):Math.ceil((e.byteLength||e.size)*Be)}function E(e){let t=0,n=0;for(let r=0,i=e.length;r<i;r++)t=e.charCodeAt(r),t<128?n+=1:t<2048?n+=2:t<55296||t>=57344?n+=3:(r++,n+=4);return n}function D(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function O(e){let t=``;for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+=`&`),t+=encodeURIComponent(n)+`=`+encodeURIComponent(e[n]));return t}function He(e){let t={},n=e.split(`&`);for(let e=0,r=n.length;e<r;e++){let r=n[e].split(`=`);t[decodeURIComponent(r[0])]=decodeURIComponent(r[1])}return t}var Ue=class extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type=`TransportError`}},We=class extends T{constructor(e){super(),this.writable=!1,ze(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,n){return super.emitReserved(`error`,new Ue(e,t,n)),this}open(){return this.readyState=`opening`,this.doOpen(),this}close(){return(this.readyState===`opening`||this.readyState===`open`)&&(this.doClose(),this.onClose()),this}send(e){this.readyState===`open`&&this.write(e)}onOpen(){this.readyState=`open`,this.writable=!0,super.emitReserved(`open`)}onData(e){let t=Se(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved(`packet`,e)}onClose(e){this.readyState=`closed`,super.emitReserved(`close`,e)}pause(e){}createUri(e,t={}){return e+`://`+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){let e=this.opts.hostname;return e.indexOf(`:`)===-1?e:`[`+e+`]`}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?`:`+this.opts.port:``}_query(e){let t=O(e);return t.length?`?`+t:``}},Ge=class extends We{constructor(){super(...arguments),this._polling=!1}get name(){return`polling`}doOpen(){this._poll()}pause(e){this.readyState=`pausing`;let t=()=>{this.readyState=`paused`,e()};if(this._polling||!this.writable){let e=0;this._polling&&(e++,this.once(`pollComplete`,function(){--e||t()})),this.writable||(e++,this.once(`drain`,function(){--e||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved(`poll`)}onData(e){De(e,this.socket.binaryType).forEach(e=>{if(this.readyState===`opening`&&e.type===`open`&&this.onOpen(),e.type===`close`)return this.onClose({description:`transport closed by the server`}),!1;this.onPacket(e)}),this.readyState!==`closed`&&(this._polling=!1,this.emitReserved(`pollComplete`),this.readyState===`open`&&this._poll())}doClose(){let e=()=>{this.write([{type:`close`}])};this.readyState===`open`?e():this.once(`open`,e)}write(e){this.writable=!1,Ee(e,e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved(`drain`)})})}uri(){let e=this.opts.secure?`https`:`http`,t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=D()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}},Ke=!1;try{Ke=typeof XMLHttpRequest<`u`&&`withCredentials`in new XMLHttpRequest}catch{}var qe=Ke;function Je(){}var Ye=class extends Ge{constructor(e){if(super(e),typeof location<`u`){let t=location.protocol===`https:`,n=location.port;n||=t?`443`:`80`,this.xd=typeof location<`u`&&e.hostname!==location.hostname||n!==e.port}}doWrite(e,t){let n=this.request({method:`POST`,data:e});n.on(`success`,t),n.on(`error`,(e,t)=>{this.onError(`xhr post error`,e,t)})}doPoll(){let e=this.request();e.on(`data`,this.onData.bind(this)),e.on(`error`,(e,t)=>{this.onError(`xhr poll error`,e,t)}),this.pollXhr=e}},Xe=class e extends T{constructor(e,t,n){super(),this.createRequest=e,ze(this,n),this._opts=n,this._method=n.method||`GET`,this._uri=t,this._data=n.data===void 0?null:n.data,this._create()}_create(){var t;let n=Ie(this._opts,`agent`,`pfx`,`key`,`passphrase`,`cert`,`ca`,`ciphers`,`rejectUnauthorized`,`autoUnref`);n.xdomain=!!this._opts.xd;let r=this._xhr=this.createRequest(n);try{r.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let e in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(e)&&r.setRequestHeader(e,this._opts.extraHeaders[e])}}catch{}if(this._method===`POST`)try{r.setRequestHeader(`Content-type`,`text/plain;charset=UTF-8`)}catch{}try{r.setRequestHeader(`Accept`,`*/*`)}catch{}(t=this._opts.cookieJar)==null||t.addCookies(r),`withCredentials`in r&&(r.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(r.timeout=this._opts.requestTimeout),r.onreadystatechange=()=>{var e;r.readyState===3&&((e=this._opts.cookieJar)==null||e.parseCookies(r.getResponseHeader(`set-cookie`))),r.readyState===4&&(r.status===200||r.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof r.status==`number`?r.status:0)},0))},r.send(this._data)}catch(e){this.setTimeoutFn(()=>{this._onError(e)},0);return}typeof document<`u`&&(this._index=e.requestsCount++,e.requests[this._index]=this)}_onError(e){this.emitReserved(`error`,e,this._xhr),this._cleanup(!0)}_cleanup(t){if(!(this._xhr===void 0||this._xhr===null)){if(this._xhr.onreadystatechange=Je,t)try{this._xhr.abort()}catch{}typeof document<`u`&&delete e.requests[this._index],this._xhr=null}}_onLoad(){let e=this._xhr.responseText;e!==null&&(this.emitReserved(`data`,e),this.emitReserved(`success`),this._cleanup())}abort(){this._cleanup()}};if(Xe.requestsCount=0,Xe.requests={},typeof document<`u`){if(typeof attachEvent==`function`)attachEvent(`onunload`,Ze);else if(typeof addEventListener==`function`){let e=`onpagehide`in Pe?`pagehide`:`unload`;addEventListener(e,Ze,!1)}}function Ze(){for(let e in Xe.requests)Xe.requests.hasOwnProperty(e)&&Xe.requests[e].abort()}var Qe=(function(){let e=et({xdomain:!1});return e&&e.responseType!==null})(),$e=class extends Ye{constructor(e){super(e);let t=e&&e.forceBase64;this.supportsBinary=Qe&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new Xe(et,this.uri(),e)}};function et(e){let t=e.xdomain;try{if(typeof XMLHttpRequest<`u`&&(!t||qe))return new XMLHttpRequest}catch{}if(!t)try{return new Pe[[`Active`,`Object`].join(`X`)](`Microsoft.XMLHTTP`)}catch{}}var tt=typeof navigator<`u`&&typeof navigator.product==`string`&&navigator.product.toLowerCase()===`reactnative`,nt=class extends We{get name(){return`websocket`}doOpen(){let e=this.uri(),t=this.opts.protocols,n=tt?{}:Ie(this.opts,`agent`,`perMessageDeflate`,`pfx`,`key`,`passphrase`,`cert`,`ca`,`ciphers`,`rejectUnauthorized`,`localAddress`,`protocolVersion`,`origin`,`maxPayload`,`family`,`checkServerIdentity`);this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,n)}catch(e){return this.emitReserved(`error`,e)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:`websocket connection closed`,context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError(`websocket error`,e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let n=e[t],r=t===e.length-1;pe(n,this.supportsBinary,e=>{try{this.doWrite(n,e)}catch{}r&&Ne(()=>{this.writable=!0,this.emitReserved(`drain`)},this.setTimeoutFn)})}}doClose(){this.ws!==void 0&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){let e=this.opts.secure?`wss`:`ws`,t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=D()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}},rt=Pe.WebSocket||Pe.MozWebSocket,it={websocket:class extends nt{createSocket(e,t,n){return tt?new rt(e,t,n):t?new rt(e,t):new rt(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends We{get name(){return`webtransport`}doOpen(){try{this._transport=new WebTransport(this.createUri(`https`),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved(`error`,e)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError(`webtransport error`,e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{let t=w(2**53-1,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),r=Oe();r.readable.pipeTo(e.writable),this._writer=r.writable.getWriter();let i=()=>{n.read().then(({done:e,value:t})=>{e||(this.onPacket(t),i())}).catch(e=>{})};i();let a={type:`open`};this.query.sid&&(a.data=`{"sid":"${this.query.sid}"}`),this._writer.write(a).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let n=e[t],r=t===e.length-1;this._writer.write(n).then(()=>{r&&Ne(()=>{this.writable=!0,this.emitReserved(`drain`)},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)==null||e.close()}},polling:$e},at=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,ot=[`source`,`protocol`,`authority`,`userInfo`,`user`,`password`,`host`,`port`,`relative`,`path`,`directory`,`file`,`query`,`anchor`];function st(e){if(e.length>8e3)throw`URI too long`;let t=e,n=e.indexOf(`[`),r=e.indexOf(`]`);n!=-1&&r!=-1&&(e=e.substring(0,n)+e.substring(n,r).replace(/:/g,`;`)+e.substring(r,e.length));let i=at.exec(e||``),a={},o=14;for(;o--;)a[ot[o]]=i[o]||``;return n!=-1&&r!=-1&&(a.source=t,a.host=a.host.substring(1,a.host.length-1).replace(/;/g,`:`),a.authority=a.authority.replace(`[`,``).replace(`]`,``).replace(/;/g,`:`),a.ipv6uri=!0),a.pathNames=ct(a,a.path),a.queryKey=lt(a,a.query),a}function ct(e,t){let n=t.replace(/\/{2,9}/g,`/`).split(`/`);return(t.slice(0,1)==`/`||t.length===0)&&n.splice(0,1),t.slice(-1)==`/`&&n.splice(n.length-1,1),n}function lt(e,t){let n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,r){t&&(n[t]=r)}),n}var ut=typeof addEventListener==`function`&&typeof removeEventListener==`function`,dt=[];ut&&addEventListener(`offline`,()=>{dt.forEach(e=>e())},!1);var ft=class e extends T{constructor(e,t){if(super(),this.binaryType=Fe,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&typeof e==`object`&&(t=e,e=null),e){let n=st(e);t.hostname=n.host,t.secure=n.protocol===`https`||n.protocol===`wss`,t.port=n.port,n.query&&(t.query=n.query)}else t.host&&(t.hostname=st(t.host).host);ze(this,t),this.secure=t.secure==null?typeof location<`u`&&location.protocol===`https:`:t.secure,t.hostname&&!t.port&&(t.port=this.secure?`443`:`80`),this.hostname=t.hostname||(typeof location<`u`?location.hostname:`localhost`),this.port=t.port||(typeof location<`u`&&location.port?location.port:this.secure?`443`:`80`),this.transports=[],this._transportsByName={},t.transports.forEach(e=>{let t=e.prototype.name;this.transports.push(t),this._transportsByName[t]=e}),this.opts=Object.assign({path:`/engine.io`,agent:!1,withCredentials:!1,upgrade:!0,timestampParam:`t`,rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,``)+(this.opts.addTrailingSlash?`/`:``),typeof this.opts.query==`string`&&(this.opts.query=He(this.opts.query)),ut&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener(`beforeunload`,this._beforeunloadEventListener,!1)),this.hostname!==`localhost`&&(this._offlineEventListener=()=>{this._onClose(`transport close`,{description:`network connection lost`})},dt.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){let t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);let n=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](n)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved(`error`,`No transports available`)},0);return}let t=this.opts.rememberUpgrade&&e.priorWebsocketSuccess&&this.transports.indexOf(`websocket`)!==-1?`websocket`:this.transports[0];this.readyState=`opening`;let n=this.createTransport(t);n.open(),this.setTransport(n)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on(`drain`,this._onDrain.bind(this)).on(`packet`,this._onPacket.bind(this)).on(`error`,this._onError.bind(this)).on(`close`,e=>this._onClose(`transport close`,e))}onOpen(){this.readyState=`open`,e.priorWebsocketSuccess=this.transport.name===`websocket`,this.emitReserved(`open`),this.flush()}_onPacket(e){if(this.readyState===`opening`||this.readyState===`open`||this.readyState===`closing`)switch(this.emitReserved(`packet`,e),this.emitReserved(`heartbeat`),e.type){case`open`:this.onHandshake(JSON.parse(e.data));break;case`ping`:this._sendPacket(`pong`),this.emitReserved(`ping`),this.emitReserved(`pong`),this._resetPingTimeout();break;case`error`:let t=Error(`server error`);t.code=e.data,this._onError(t);break;case`message`:this.emitReserved(`data`,e.data),this.emitReserved(`message`,e.data);break}}onHandshake(e){this.emitReserved(`handshake`,e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),this.readyState!==`closed`&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);let e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose(`ping timeout`)},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved(`drain`):this.flush()}flush(){if(this.readyState!==`closed`&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){let e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved(`flush`)}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name===`polling`&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let t=0;t<this.writeBuffer.length;t++){let n=this.writeBuffer[t].data;if(n&&(e+=Ve(n)),t>0&&e>this._maxPayload)return this.writeBuffer.slice(0,t);e+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;let e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,Ne(()=>{this._onClose(`ping timeout`)},this.setTimeoutFn)),e}write(e,t,n){return this._sendPacket(`message`,e,t,n),this}send(e,t,n){return this._sendPacket(`message`,e,t,n),this}_sendPacket(e,t,n,r){if(typeof t==`function`&&(r=t,t=void 0),typeof n==`function`&&(r=n,n=null),this.readyState===`closing`||this.readyState===`closed`)return;n||={},n.compress=!1!==n.compress;let i={type:e,data:t,options:n};this.emitReserved(`packetCreate`,i),this.writeBuffer.push(i),r&&this.once(`flush`,r),this.flush()}close(){let e=()=>{this._onClose(`forced close`),this.transport.close()},t=()=>{this.off(`upgrade`,t),this.off(`upgradeError`,t),e()},n=()=>{this.once(`upgrade`,t),this.once(`upgradeError`,t)};return(this.readyState===`opening`||this.readyState===`open`)&&(this.readyState=`closing`,this.writeBuffer.length?this.once(`drain`,()=>{this.upgrading?n():e()}):this.upgrading?n():e()),this}_onError(t){if(e.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState===`opening`)return this.transports.shift(),this._open();this.emitReserved(`error`,t),this._onClose(`transport error`,t)}_onClose(e,t){if(this.readyState===`opening`||this.readyState===`open`||this.readyState===`closing`){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners(`close`),this.transport.close(),this.transport.removeAllListeners(),ut&&(this._beforeunloadEventListener&&removeEventListener(`beforeunload`,this._beforeunloadEventListener,!1),this._offlineEventListener)){let e=dt.indexOf(this._offlineEventListener);e!==-1&&dt.splice(e,1)}this.readyState=`closed`,this.id=null,this.emitReserved(`close`,e,t),this.writeBuffer=[],this._prevBufferLen=0}}};ft.protocol=4;var pt=class extends ft{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState===`open`&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),n=!1;ft.priorWebsocketSuccess=!1;let r=()=>{n||(t.send([{type:`ping`,data:`probe`}]),t.once(`packet`,e=>{if(!n)if(e.type===`pong`&&e.data===`probe`){if(this.upgrading=!0,this.emitReserved(`upgrading`,t),!t)return;ft.priorWebsocketSuccess=t.name===`websocket`,this.transport.pause(()=>{n||this.readyState!==`closed`&&(l(),this.setTransport(t),t.send([{type:`upgrade`}]),this.emitReserved(`upgrade`,t),t=null,this.upgrading=!1,this.flush())})}else{let e=Error(`probe error`);e.transport=t.name,this.emitReserved(`upgradeError`,e)}}))};function i(){n||(n=!0,l(),t.close(),t=null)}let a=e=>{let n=Error(`probe error: `+e);n.transport=t.name,i(),this.emitReserved(`upgradeError`,n)};function o(){a(`transport closed`)}function s(){a(`socket closed`)}function c(e){t&&e.name!==t.name&&i()}let l=()=>{t.removeListener(`open`,r),t.removeListener(`error`,a),t.removeListener(`close`,o),this.off(`close`,s),this.off(`upgrading`,c)};t.once(`open`,r),t.once(`error`,a),t.once(`close`,o),this.once(`close`,s),this.once(`upgrading`,c),this._upgrades.indexOf(`webtransport`)!==-1&&e!==`webtransport`?this.setTimeoutFn(()=>{n||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){let t=[];for(let n=0;n<e.length;n++)~this.transports.indexOf(e[n])&&t.push(e[n]);return t}},mt=class extends pt{constructor(e,t={}){let n=typeof e==`object`?e:t;(!n.transports||n.transports&&typeof n.transports[0]==`string`)&&(n.transports=(n.transports||[`polling`,`websocket`,`webtransport`]).map(e=>it[e]).filter(e=>!!e)),super(e,n)}};mt.protocol;function ht(e,t=``,n){let r=e;n||=typeof location<`u`&&location,e??=n.protocol+`//`+n.host,typeof e==`string`&&(e.charAt(0)===`/`&&(e=e.charAt(1)===`/`?n.protocol+e:n.host+e),/^(https?|wss?):\/\//.test(e)||(e=n===void 0?`https://`+e:n.protocol+`//`+e),r=st(e)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port=`80`:/^(http|ws)s$/.test(r.protocol)&&(r.port=`443`)),r.path=r.path||`/`;let i=r.host.indexOf(`:`)===-1?r.host:`[`+r.host+`]`;return r.id=r.protocol+`://`+i+`:`+r.port+t,r.href=r.protocol+`://`+i+(n&&n.port===r.port?``:`:`+r.port),r}var gt=typeof ArrayBuffer==`function`,_t=e=>typeof ArrayBuffer.isView==`function`?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,vt=Object.prototype.toString,yt=typeof Blob==`function`||typeof Blob<`u`&&vt.call(Blob)===`[object BlobConstructor]`,bt=typeof File==`function`||typeof File<`u`&&vt.call(File)===`[object FileConstructor]`;function xt(e){return gt&&(e instanceof ArrayBuffer||_t(e))||yt&&e instanceof Blob||bt&&e instanceof File}function St(e,t){if(!e||typeof e!=`object`)return!1;if(Array.isArray(e)){for(let t=0,n=e.length;t<n;t++)if(St(e[t]))return!0;return!1}if(xt(e))return!0;if(e.toJSON&&typeof e.toJSON==`function`&&arguments.length===1)return St(e.toJSON(),!0);for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&St(e[t]))return!0;return!1}function Ct(e){let t=[],n=e.data,r=e;return r.data=wt(n,t),r.attachments=t.length,{packet:r,buffers:t}}function wt(e,t){if(!e)return e;if(xt(e)){let n={_placeholder:!0,num:t.length};return t.push(e),n}else if(Array.isArray(e)){let n=Array(e.length);for(let r=0;r<e.length;r++)n[r]=wt(e[r],t);return n}else if(typeof e==`object`&&!(e instanceof Date)){let n={};for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=wt(e[r],t));return n}return e}function Tt(e,t){return e.data=Et(e.data,t),delete e.attachments,e}function Et(e,t){if(!e)return e;if(e&&e._placeholder===!0){if(typeof e.num==`number`&&e.num>=0&&e.num<t.length)return t[e.num];throw Error(`illegal attachments`)}else if(Array.isArray(e))for(let n=0;n<e.length;n++)e[n]=Et(e[n],t);else if(typeof e==`object`)for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=Et(e[n],t));return e}var Dt=s({Decoder:()=>At,Encoder:()=>kt,PacketType:()=>k,isPacketValid:()=>Lt,protocol:()=>5}),Ot=[`connect`,`connect_error`,`disconnect`,`disconnecting`,`newListener`,`removeListener`],k;(function(e){e[e.CONNECT=0]=`CONNECT`,e[e.DISCONNECT=1]=`DISCONNECT`,e[e.EVENT=2]=`EVENT`,e[e.ACK=3]=`ACK`,e[e.CONNECT_ERROR=4]=`CONNECT_ERROR`,e[e.BINARY_EVENT=5]=`BINARY_EVENT`,e[e.BINARY_ACK=6]=`BINARY_ACK`})(k||={});var kt=class{constructor(e){this.replacer=e}encode(e){return(e.type===k.EVENT||e.type===k.ACK)&&St(e)?this.encodeAsBinary({type:e.type===k.EVENT?k.BINARY_EVENT:k.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=``+e.type;return(e.type===k.BINARY_EVENT||e.type===k.BINARY_ACK)&&(t+=e.attachments+`-`),e.nsp&&e.nsp!==`/`&&(t+=e.nsp+`,`),e.id!=null&&(t+=e.id),e.data!=null&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){let t=Ct(e),n=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(n),r}},At=class e extends T{constructor(e){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},typeof e==`function`?{reviver:e}:e)}add(e){let t;if(typeof e==`string`){if(this.reconstructor)throw Error(`got plaintext data when reconstructing a packet`);t=this.decodeString(e);let n=t.type===k.BINARY_EVENT;n||t.type===k.BINARY_ACK?(t.type=n?k.EVENT:k.ACK,this.reconstructor=new jt(t),t.attachments===0&&super.emitReserved(`decoded`,t)):super.emitReserved(`decoded`,t)}else if(xt(e)||e.base64)if(this.reconstructor)t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved(`decoded`,t));else throw Error(`got binary data when not reconstructing a packet`);else throw Error(`Unknown type: `+e)}decodeString(t){let n=0,r={type:Number(t.charAt(0))};if(k[r.type]===void 0)throw Error(`unknown packet type `+r.type);if(r.type===k.BINARY_EVENT||r.type===k.BINARY_ACK){let e=n+1;for(;t.charAt(++n)!==`-`&&n!=t.length;);let i=t.substring(e,n);if(i!=Number(i)||t.charAt(n)!==`-`)throw Error(`Illegal attachments`);let a=Number(i);if(!Nt(a)||a<0)throw Error(`Illegal attachments`);if(a>this.opts.maxAttachments)throw Error(`too many attachments`);r.attachments=a}if(t.charAt(n+1)===`/`){let e=n+1;for(;++n&&!(t.charAt(n)===`,`||n===t.length););r.nsp=t.substring(e,n)}else r.nsp=`/`;let i=t.charAt(n+1);if(i!==``&&Number(i)==i){let e=n+1;for(;++n;){let e=t.charAt(n);if(e==null||Number(e)!=e){--n;break}if(n===t.length)break}r.id=Number(t.substring(e,n+1))}if(t.charAt(++n)){let i=this.tryParse(t.substr(n));if(e.isPayloadValid(r.type,i))r.data=i;else throw Error(`invalid payload`)}return r}tryParse(e){try{return JSON.parse(e,this.opts.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case k.CONNECT:return Ft(t);case k.DISCONNECT:return t===void 0;case k.CONNECT_ERROR:return typeof t==`string`||Ft(t);case k.EVENT:case k.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]==`number`||typeof t[0]==`string`&&Ot.indexOf(t[0])===-1);case k.ACK:case k.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&=(this.reconstructor.finishedReconstruction(),null)}},jt=class{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){let e=Tt(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function Mt(e){return typeof e==`string`}var Nt=Number.isInteger||function(e){return typeof e==`number`&&isFinite(e)&&Math.floor(e)===e};function Pt(e){return e===void 0||Nt(e)}function Ft(e){return Object.prototype.toString.call(e)===`[object Object]`}function It(e,t){switch(e){case k.CONNECT:return t===void 0||Ft(t);case k.DISCONNECT:return t===void 0;case k.EVENT:return Array.isArray(t)&&(typeof t[0]==`number`||typeof t[0]==`string`&&Ot.indexOf(t[0])===-1);case k.ACK:return Array.isArray(t);case k.CONNECT_ERROR:return typeof t==`string`||Ft(t);default:return!1}}function Lt(e){return Mt(e.nsp)&&Pt(e.id)&&It(e.type,e.data)}function Rt(e,t,n){return e.on(t,n),function(){e.off(t,n)}}var zt=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),Bt=class extends T{constructor(e,t,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;let e=this.io;this.subs=[Rt(e,`open`,this.onopen.bind(this)),Rt(e,`packet`,this.onpacket.bind(this)),Rt(e,`error`,this.onerror.bind(this)),Rt(e,`close`,this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState===`open`&&this.onopen(),this)}open(){return this.connect()}send(...e){return e.unshift(`message`),this.emit.apply(this,e),this}emit(e,...t){if(zt.hasOwnProperty(e))throw Error(`"`+e.toString()+`" is a reserved event name`);if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;let n={type:k.EVENT,data:t};if(n.options={},n.options.compress=this.flags.compress!==!1,typeof t[t.length-1]==`function`){let e=this.ids++,r=t.pop();this._registerAckCallback(e,r),n.id=e}let r=this.io.engine?.transport?.writable,i=this.connected&&!this.io.engine?._hasPingExpired();return this.flags.volatile&&!r||(i?(this.notifyOutgoingListeners(n),this.packet(n)):this.sendBuffer.push(n)),this.flags={},this}_registerAckCallback(e,t){let n=this.flags.timeout??this._opts.ackTimeout;if(n===void 0){this.acks[e]=t;return}let r=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,Error(`operation has timed out`))},n),i=(...e)=>{this.io.clearTimeoutFn(r),t.apply(this,e)};i.withError=!0,this.acks[e]=i}emitWithAck(e,...t){return new Promise((n,r)=>{let i=(e,t)=>e?r(e):n(t);i.withError=!0,t.push(i),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]==`function`&&(t=e.pop());let n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((e,...r)=>(this._queue[0],e===null?(this._queue.shift(),t&&t(null,...r)):n.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)),n.pending=!1,this._drainQueue())),this._queue.push(n),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||this._queue.length===0)return;let t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){typeof this.auth==`function`?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:k.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved(`connect_error`,e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved(`disconnect`,e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(t=>String(t.id)===e)){let t=this.acks[e];delete this.acks[e],t.withError&&t.call(this,Error(`socket has been disconnected`))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case k.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved(`connect_error`,Error(`It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)`));break;case k.EVENT:case k.BINARY_EVENT:this.onevent(e);break;case k.ACK:case k.BINARY_ACK:this.onack(e);break;case k.DISCONNECT:this.ondisconnect();break;case k.CONNECT_ERROR:this.destroy();let t=Error(e.data.message);t.data=e.data.data,this.emitReserved(`connect_error`,t);break}}onevent(e){let t=e.data||[];e.id!=null&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){let t=this._anyListeners.slice();for(let n of t)n.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]==`string`&&(this._lastOffset=e[e.length-1])}ack(e){let t=this,n=!1;return function(...r){n||(n=!0,t.packet({type:k.ACK,id:e,data:r}))}}onack(e){let t=this.acks[e.id];typeof t==`function`&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved(`connect`)}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose(`io server disconnect`)}destroy(){this.subs&&=(this.subs.forEach(e=>e()),void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:k.DISCONNECT}),this.destroy(),this.connected&&this.onclose(`io client disconnect`),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){let t=this._anyListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){let t=this._anyOutgoingListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){let t=this._anyOutgoingListeners.slice();for(let n of t)n.apply(this,e.data)}}};function Vt(e){e||={},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}Vt.prototype.duration=function(){var e=this.ms*this.factor**+ this.attempts++;if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=Math.floor(t*10)&1?e+n:e-n}return Math.min(e,this.max)|0},Vt.prototype.reset=function(){this.attempts=0},Vt.prototype.setMin=function(e){this.ms=e},Vt.prototype.setMax=function(e){this.max=e},Vt.prototype.setJitter=function(e){this.jitter=e};var Ht=class extends T{constructor(e,t){super(),this.nsps={},this.subs=[],e&&typeof e==`object`&&(t=e,e=void 0),t||={},t.path=t.path||`/socket.io`,this.opts=t,ze(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(t.randomizationFactor??.5),this.backoff=new Vt({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState=`closed`,this.uri=e;let n=t.parser||Dt;this.encoder=new n.Encoder,this.decoder=new n.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)==null||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)==null||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)==null||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(~this._readyState.indexOf(`open`))return this;this.engine=new mt(this.uri,this.opts);let t=this.engine,n=this;this._readyState=`opening`,this.skipReconnect=!1;let r=Rt(t,`open`,function(){n.onopen(),e&&e()}),i=t=>{this.cleanup(),this._readyState=`closed`,this.emitReserved(`error`,t),e?e(t):this.maybeReconnectOnOpen()},a=Rt(t,`error`,i);if(!1!==this._timeout){let e=this._timeout,n=this.setTimeoutFn(()=>{r(),i(Error(`timeout`)),t.close()},e);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}return this.subs.push(r),this.subs.push(a),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState=`open`,this.emitReserved(`open`);let e=this.engine;this.subs.push(Rt(e,`ping`,this.onping.bind(this)),Rt(e,`data`,this.ondata.bind(this)),Rt(e,`error`,this.onerror.bind(this)),Rt(e,`close`,this.onclose.bind(this)),Rt(this.decoder,`decoded`,this.ondecoded.bind(this)))}onping(){this.emitReserved(`ping`)}ondata(e){try{this.decoder.add(e)}catch(e){this.onclose(`parse error`,e)}}ondecoded(e){Ne(()=>{this.emitReserved(`packet`,e)},this.setTimeoutFn)}onerror(e){this.emitReserved(`error`,e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new Bt(this,e,t),this.nsps[e]=n),n}_destroy(e){let t=Object.keys(this.nsps);for(let e of t)if(this.nsps[e].active)return;this._close()}_packet(e){let t=this.encoder.encode(e);for(let n=0;n<t.length;n++)this.engine.write(t[n],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose(`forced close`)}disconnect(){return this._close()}onclose(e,t){var n;this.cleanup(),(n=this.engine)==null||n.close(),this.backoff.reset(),this._readyState=`closed`,this.emitReserved(`close`,e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;let e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved(`reconnect_failed`),this._reconnecting=!1;else{let t=this.backoff.duration();this._reconnecting=!0;let n=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved(`reconnect_attempt`,e.backoff.attempts),!e.skipReconnect&&e.open(t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved(`reconnect_error`,t)):e.onreconnect()}))},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){let e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved(`reconnect`,e)}},Ut={};function Wt(e,t){typeof e==`object`&&(t=e,e=void 0),t||={};let n=ht(e,t.path||`/socket.io`),r=n.source,i=n.id,a=n.path,o=Ut[i]&&a in Ut[i].nsps,s=t.forceNew||t[`force new connection`]||!1===t.multiplex||o,c;return s?c=new Ht(r,t):(Ut[i]||(Ut[i]=new Ht(r,t)),c=Ut[i]),n.query&&!t.query&&(t.query=n.queryKey),c.socket(n.path,t)}Object.assign(Wt,{Manager:Ht,Socket:Bt,io:Wt,connect:Wt});var Gt=({apiBaseUrl:e,userId:t,chatId:n,siteId:r})=>Wt(e,{transports:[`polling`,`websocket`],upgrade:!0,rememberUpgrade:!1,auth:{userId:t,chatId:n,siteId:r},query:{chatId:n,siteId:r}}),Kt=({socket:e,chatId:t})=>{if(!e||!t||typeof window>`u`)return()=>{};let n=window.location.pathname+window.location.search,r=Date.now(),i=null,a=null,o=()=>{console.log(`[FlowEngageTracking] visitor:session_start`,{chatId:t,path:n}),e.emit(`visitor:session_start`,{chatId:t,path:n,title:document.title,referrer:document.referrer,userAgent:navigator.userAgent,timestamp:Date.now()})},s=()=>{console.log(`[FlowEngageTracking] visitor:page_enter`,{chatId:t,path:n}),e.emit(`visitor:page_enter`,{chatId:t,path:n,title:document.title,timestamp:Date.now()})},c=(n,r)=>{console.log(`[FlowEngageTracking] visitor:page_leave`,{chatId:t,path:n,duration:Math.max(0,Math.floor((Date.now()-r)/1e3))}),e.emit(`visitor:page_leave`,{chatId:t,path:n,duration:Math.max(0,Math.floor((Date.now()-r)/1e3)),timestamp:Date.now()})},l=()=>{console.log(`[FlowEngageTracking] visitor:heartbeat`,{chatId:t,path:n}),e.emit(`visitor:heartbeat`,{chatId:t,path:n,title:document.title,timestamp:Date.now()})},u=()=>{i&&window.clearInterval(i),i=window.setInterval(l,h)},d=()=>{i&&=(window.clearInterval(i),null)},f=r=>{console.log(`[FlowEngageTracking] visitor:visibility`,{chatId:t,state:r}),e.emit(`visitor:visibility`,{chatId:t,state:r,path:n,title:document.title,timestamp:Date.now()})},p=()=>{if(document.hidden){a&&window.clearTimeout(a),a=window.setTimeout(()=>{a=null,d(),f(`hidden`)},g);return}a&&=(window.clearTimeout(a),null),f(`visible`),l(),u()},m=()=>{let e=window.location.pathname+window.location.search;if(e===n){console.log(`[FlowEngageTracking] route unchanged`,{currentPath:n});return}console.log(`[FlowEngageTracking] route changed`,{from:n,to:e}),c(n,r),n=e,r=Date.now(),s()},_=window.history.pushState.bind(window.history),v=window.history.replaceState.bind(window.history);window.history.pushState=(...e)=>{_(...e),m()},window.history.replaceState=(...e)=>{v(...e),m()};let y=()=>{c(n,r),e.emit(`visitor:session_end`,{chatId:t,timestamp:Date.now()})};return window.addEventListener(`popstate`,m),window.addEventListener(`hashchange`,m),window.addEventListener(`beforeunload`,y),window.addEventListener(`visibilitychange`,p),o(),document.hidden?a=window.setTimeout(()=>{a=null,d(),f(`hidden`)},g):(l(),u()),{notifyRouteChange:m,cleanup:()=>{a&&=(window.clearTimeout(a),null),d(),window.history.pushState=_,window.history.replaceState=v,window.removeEventListener(`popstate`,m),window.removeEventListener(`hashchange`,m),window.removeEventListener(`beforeunload`,y),window.removeEventListener(`visibilitychange`,p)}}},qt=(0,d.createContext)(null),Jt=()=>{let e=(0,d.useContext)(qt);if(!e)throw Error(`useFlowEngage must be used inside FlowEngageProvider`);return e};function Yt(){if(typeof window>`u`)return!1;try{let e=window.localStorage?.getItem(`FE_DEBUG_VOICE`);if(e===`0`||e===`false`)return!1;if(e===`1`||e===`true`)return!0}catch{}return window.__FE_DEBUG_VOICE_TOOLS__===!1?!1:window.__FE_DEBUG_VOICE_TOOLS__===!0}function Xt(e){if(!e||typeof e.closest!=`function`)return!1;try{return!!e.closest(`#flowengage-root, .flowengage-shell, .flowengage-widget-root`)}catch{return!1}}function Zt(...e){Yt()&&console.log(`[FlowEngage:shadowNavigate]`,...e)}var Qt=`fe_pending_nav_section`,$t=15e3;function en(){if(typeof window>`u`||typeof document>`u`)return;let e;try{e=JSON.parse(sessionStorage.getItem(Qt)||`null`)}catch{return}if(!e)return;try{sessionStorage.removeItem(Qt)}catch{}let{sectionText:t,ts:n}=e;if(!t)return;if(Date.now()-n>$t){Zt(`initNavigationHighlight: pending section expired, skipping:`,t);return}Zt(`initNavigationHighlight: replaying section highlight:`,t);let r=0,i=()=>{r+=1;let e=nn(null,t);if(e){rn(e),Zt(`initNavigationHighlight: highlighted on attempt`,r);return}r<8?setTimeout(i,300):Zt(`initNavigationHighlight: could not find element after 8 attempts:`,t)};setTimeout(i,250)}var tn=()=>{if(typeof document>`u`||document.getElementById(`fe-highlight-styles`))return;let e=document.createElement(`style`);e.id=`fe-highlight-styles`,e.textContent=`
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(e&&(t=e(e=0)),t),s=(e,n)=>{let r={};for(var i in e)t(r,i,{get:e[i],enumerable:!0});return n||t(r,Symbol.toStringTag,{value:`Module`}),r},c=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},l=(n,r,a)=>(a=n==null?{}:e(i(n)),c(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n)),u=e=>a.call(e,`module.exports`)?e[`module.exports`]:c(t({},`__esModule`,{value:!0}),e);let d=require(`react`);d=l(d);let f=require(`react/jsx-runtime`);var p=e=>{if(!e||typeof e!=`object`)throw Error(`FlowEngage config is required`);if(!e.siteId||typeof e.siteId!=`string`)throw Error(`[FlowEngage] config.siteId is required. Pass it as <FlowEngageProvider siteId="your-site-id" /> or config={{ siteId: 'your-site-id' }}.`);let t=(e.apiBaseUrl||`https://be-flowengage.oslabs.app`).replace(/\/+$/,``);return{siteId:e.siteId.trim(),apiBaseUrl:t}},m=(e,t)=>{if(e==null||e===``)return t;let n=Number.parseInt(String(e),10);return Number.isFinite(n)&&n>0?n:t},h=m(void 0,1e4),g=m(void 0,15e3),_={chatId:`flowengage.chatId`,isOpen:`flowengage.isOpen`,activeScreen:`flowengage.activeScreen`,isHumanHandled:`flowengage.isHumanHandled`,agentName:`flowengage.agentName`,agentHeadshot:`flowengage.agentHeadshot`,visitorEmail:`flowengage.visitorEmail`},v=6e4,y=480*60,b=3e4,x=typeof window<`u`,S=e=>e?`flowengage.visitorEmail.${e}`:null,ee=()=>{if(!x)return null;let e=window.localStorage.getItem(_.chatId);return e&&String(e).trim()?String(e).trim():null},te=()=>{if(x)try{window.localStorage.removeItem(_.chatId)}catch{}},C=()=>x?typeof crypto<`u`&&crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`:`server-chat-id`,ne=()=>x?{isOpen:!1,activeScreen:window.sessionStorage.getItem(_.activeScreen)||`ai`,isHumanHandled:window.sessionStorage.getItem(_.isHumanHandled)===`true`,agentName:window.sessionStorage.getItem(_.agentName),agentHeadshot:window.sessionStorage.getItem(_.agentHeadshot),visitorEmail:``}:{isOpen:!1,activeScreen:`ai`,isHumanHandled:!1,agentName:null,agentHeadshot:null,visitorEmail:``},re=e=>{x&&Object.entries(e).forEach(([e,t])=>{let n=_[e];if(n){if(t==null||t===!1){window.sessionStorage.removeItem(n);return}window.sessionStorage.setItem(n,String(t))}})},ie=e=>{if(!x||!e)return``;let t=S(e),n=window.localStorage.getItem(t);if(!n){let e=window.sessionStorage.getItem(_.visitorEmail);e&&(window.localStorage.setItem(t,e),window.sessionStorage.removeItem(_.visitorEmail),n=e)}return n||``},ae=(e,t)=>{if(!x)return;let n=S(t);if(!n)return;let r=typeof e==`string`?e.trim():``;if(!r){window.localStorage.removeItem(n),window.sessionStorage.removeItem(_.visitorEmail);return}window.localStorage.setItem(n,r),window.sessionStorage.removeItem(_.visitorEmail)},oe=async e=>{let t=await e.json().catch(()=>({}));if(!e.ok){let n=Error(t.message||t.error||`Request failed with status ${e.status}`);throw n.status=e.status,n}return t},se=async(e,t={})=>{try{return await fetch(e,{mode:`cors`,...t})}catch(t){let n=Error(`Network error reaching ${e}. Check: (1) backend is running, (2) CORS allows this origin, (3) siteId is correct. Original: ${t.message}`);throw n.status=0,n.cause=t,n}},ce=async({apiBaseUrl:e,userId:t,siteId:n,priorChatId:r=null})=>{let i=`${e}/api/visitors/resolve-session`,a={siteId:n};return r&&String(r).trim()&&(a.priorChatId=String(r).trim()),oe(await se(i,{method:`POST`,mode:`cors`,headers:{"Content-Type":`application/json`,"x-user-id":t==null?``:String(t),...n?{"x-site-id":n}:{}},body:JSON.stringify(a)}))},le=async({apiBaseUrl:e,siteId:t})=>{let n=typeof window<`u`?window.location.origin:`http://localhost`,r=`${e}/api/widget/chatbot-loader?${new URLSearchParams({siteId:t,origin:n}).toString()}`;console.log(`[FlowEngageAPI] bootstrap request`,{apiBaseUrl:e,siteId:t,origin:n,url:r});let i=await oe(await se(r,{method:`GET`}));return console.log(`[FlowEngageAPI] bootstrap success`,i),i.data},ue=({apiBaseUrl:e,userId:t,siteId:n})=>{let r=(t,n)=>{let r=`${e}${t}`,i=JSON.stringify(n);if(typeof navigator<`u`&&navigator.sendBeacon)try{let e=new Blob([i],{type:`application/json`});return navigator.sendBeacon(r,e)}catch{}return typeof fetch<`u`?(fetch(r,{method:`POST`,mode:`cors`,keepalive:!0,headers:{"Content-Type":`application/json`},body:i}).catch(()=>{}),!0):!1},i=async(r,i={})=>oe(await se(`${e}${r}`,{...i,headers:{"Content-Type":`application/json`,"x-user-id":t,...n?{"x-site-id":n}:{},...i.headers||{}}})),a=async(r,i,a={})=>{let o={"x-user-id":t,...n?{"x-site-id":n}:{},...a.headers||{}};return oe(await se(`${e}${r}`,{...a,body:i,headers:o}))};return{async loadHistory(e,t=`en`,n=``){return i(`/api/ai/chat`,{method:`POST`,body:JSON.stringify({session_id:e,user_query:``,lang:t,category:n})})},async sendAiMessage(e,t,n=`en`,r=``,a=null,o={}){return i(`/api/ai/chat`,{method:`POST`,body:JSON.stringify({session_id:e,user_query:t,lang:n,category:r,...o||{},...a||{}})})},async uploadChatFile(e){let t=new FormData;return t.append(`file`,e),a(`/api/upload`,t,{method:`POST`})},async checkHumanHandled(e){return i(`/api/ai/check_human_handled`,{method:`POST`,body:JSON.stringify({session_id:e})})},async setChatMode(e,t){return i(`/api/ai/set_chat_mode`,{method:`POST`,body:JSON.stringify({session_id:e,mode:t})})},async toggleVoice(e){return i(`/api/ai/voice/toggle`,{method:`POST`,body:JSON.stringify({session_id:e})})},async syncVoice(e,r){return i(`/api/ai/voice/sync`,{method:`POST`,body:JSON.stringify({session_id:e,messages:r,...t?{userId:String(t)}:{},...n?{siteId:String(n)}:{}})})},async trackVisitor(e){return i(`/api/visitors/track`,{method:`POST`,body:JSON.stringify(e)})},async updateChatStatus(e,t){return i(`/api/chat/status`,{method:`POST`,body:JSON.stringify({chatId:e,type:t})})},async startConversation(e,t=`en`){return i(`/api/chat/status`,{method:`POST`,body:JSON.stringify({chatId:e,type:`open`,lang:t})})},async endConversation(e){return i(`/api/chat/status`,{method:`POST`,body:JSON.stringify({chatId:e,type:`closed`})})},async acceptCall(e,t){return i(`/api/calls/${e}/accept`,{method:`POST`,body:JSON.stringify({session_id:t,site_id:n})})},async rejectCall(e,t){return i(`/api/calls/${e}/reject`,{method:`POST`,body:JSON.stringify({session_id:t,site_id:n})})},async getIceServersConfig(){return oe(await se(`${e}/api/calls/ice-config`,{method:`GET`,headers:{"x-user-id":t,...n?{"x-site-id":n}:{}}}))},async endWebRTCCall(e,t){return i(`/api/calls/${e}/end`,{method:`POST`,body:JSON.stringify({session_id:t,site_id:n,endedBy:`customer`})})},async markCustomerUnavailable(e,t){return i(`/api/calls/${e}/customer-unavailable`,{method:`POST`,body:JSON.stringify({session_id:t,site_id:n})})},beaconEndWebRTCCall(e,t){return r(`/api/calls/${e}/end`,{session_id:t,site_id:n,endedBy:`customer`})},beaconCustomerUnavailable(e,t){return r(`/api/calls/${e}/customer-unavailable`,{session_id:t,site_id:n})},beaconSyncVoice(r,i){if(typeof navigator>`u`||!navigator.sendBeacon)return!1;let a={session_id:r,messages:i,...t?{userId:String(t)}:{},...n?{siteId:String(n)}:{}},o=new Blob([JSON.stringify(a)],{type:`application/json`});return navigator.sendBeacon(`${e}/api/ai/voice/sync`,o)}}},de=Object.create(null);de.open=`0`,de.close=`1`,de.ping=`2`,de.pong=`3`,de.message=`4`,de.upgrade=`5`,de.noop=`6`;var fe=Object.create(null);Object.keys(de).forEach(e=>{fe[de[e]]=e});var pe={type:`error`,data:`parser error`},me=typeof Blob==`function`||typeof Blob<`u`&&Object.prototype.toString.call(Blob)===`[object BlobConstructor]`,he=typeof ArrayBuffer==`function`,ge=e=>typeof ArrayBuffer.isView==`function`?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,_e=({type:e,data:t},n,r)=>me&&t instanceof Blob?n?r(t):ve(t,r):he&&(t instanceof ArrayBuffer||ge(t))?n?r(t):ve(new Blob([t]),r):r(de[e]+(t||``)),ve=(e,t)=>{let n=new FileReader;return n.onload=function(){let e=n.result.split(`,`)[1];t(`b`+(e||``))},n.readAsDataURL(e)};function ye(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}var be;function xe(e,t){if(me&&e.data instanceof Blob)return e.data.arrayBuffer().then(ye).then(t);if(he&&(e.data instanceof ArrayBuffer||ge(e.data)))return t(ye(e.data));_e(e,!1,e=>{be||=new TextEncoder,t(be.encode(e))})}var Se=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,Ce=typeof Uint8Array>`u`?[]:new Uint8Array(256);for(let e=0;e<64;e++)Ce[Se.charCodeAt(e)]=e;var we=e=>{let t=e.length*.75,n=e.length,r,i=0,a,o,s,c;e[e.length-1]===`=`&&(t--,e[e.length-2]===`=`&&t--);let l=new ArrayBuffer(t),u=new Uint8Array(l);for(r=0;r<n;r+=4)a=Ce[e.charCodeAt(r)],o=Ce[e.charCodeAt(r+1)],s=Ce[e.charCodeAt(r+2)],c=Ce[e.charCodeAt(r+3)],u[i++]=a<<2|o>>4,u[i++]=(o&15)<<4|s>>2,u[i++]=(s&3)<<6|c&63;return l},Te=typeof ArrayBuffer==`function`,Ee=(e,t)=>{if(typeof e!=`string`)return{type:`message`,data:Oe(e,t)};let n=e.charAt(0);return n===`b`?{type:`message`,data:De(e.substring(1),t)}:fe[n]?e.length>1?{type:fe[n],data:e.substring(1)}:{type:fe[n]}:pe},De=(e,t)=>Te?Oe(we(e),t):{base64:!0,data:e},Oe=(e,t)=>{switch(t){case`blob`:return e instanceof Blob?e:new Blob([e]);default:return e instanceof ArrayBuffer?e:e.buffer}},ke=``,Ae=(e,t)=>{let n=e.length,r=Array(n),i=0;e.forEach((e,a)=>{_e(e,!1,e=>{r[a]=e,++i===n&&t(r.join(ke))})})},je=(e,t)=>{let n=e.split(ke),r=[];for(let e=0;e<n.length;e++){let i=Ee(n[e],t);if(r.push(i),i.type===`error`)break}return r};function Me(){return new TransformStream({transform(e,t){xe(e,n=>{let r=n.length,i;if(r<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,r);else if(r<65536){i=new Uint8Array(3);let e=new DataView(i.buffer);e.setUint8(0,126),e.setUint16(1,r)}else{i=new Uint8Array(9);let e=new DataView(i.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(r))}e.data&&typeof e.data!=`string`&&(i[0]|=128),t.enqueue(i),t.enqueue(n)})}})}var Ne;function Pe(e){return e.reduce((e,t)=>e+t.length,0)}function w(e,t){if(e[0].length===t)return e.shift();let n=new Uint8Array(t),r=0;for(let i=0;i<t;i++)n[i]=e[0][r++],r===e[0].length&&(e.shift(),r=0);return e.length&&r<e[0].length&&(e[0]=e[0].slice(r)),n}function Fe(e,t){Ne||=new TextDecoder;let n=[],r=0,i=-1,a=!1;return new TransformStream({transform(o,s){for(n.push(o);;){if(r===0){if(Pe(n)<1)break;let e=w(n,1);a=(e[0]&128)==128,i=e[0]&127,r=i<126?3:i===126?1:2}else if(r===1){if(Pe(n)<2)break;let e=w(n,2);i=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),r=3}else if(r===2){if(Pe(n)<8)break;let e=w(n,8),t=new DataView(e.buffer,e.byteOffset,e.length),a=t.getUint32(0);if(a>2**21-1){s.enqueue(pe);break}i=a*2**32+t.getUint32(4),r=3}else{if(Pe(n)<i)break;let e=w(n,i);s.enqueue(Ee(a?e:Ne.decode(e),t)),r=0}if(i===0||i>e){s.enqueue(pe);break}}}})}function T(e){if(e)return Ie(e)}function Ie(e){for(var t in T.prototype)e[t]=T.prototype[t];return e}T.prototype.on=T.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks[`$`+e]=this._callbacks[`$`+e]||[]).push(t),this},T.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},T.prototype.off=T.prototype.removeListener=T.prototype.removeAllListeners=T.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var n=this._callbacks[`$`+e];if(!n)return this;if(arguments.length==1)return delete this._callbacks[`$`+e],this;for(var r,i=0;i<n.length;i++)if(r=n[i],r===t||r.fn===t){n.splice(i,1);break}return n.length===0&&delete this._callbacks[`$`+e],this},T.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=Array(arguments.length-1),n=this._callbacks[`$`+e],r=1;r<arguments.length;r++)t[r-1]=arguments[r];if(n){n=n.slice(0);for(var r=0,i=n.length;r<i;++r)n[r].apply(this,t)}return this},T.prototype.emitReserved=T.prototype.emit,T.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks[`$`+e]||[]},T.prototype.hasListeners=function(e){return!!this.listeners(e).length};var Le=typeof Promise==`function`&&typeof Promise.resolve==`function`?e=>Promise.resolve().then(e):(e,t)=>t(e,0),E=typeof self<`u`?self:typeof window<`u`?window:Function(`return this`)(),Re=`arraybuffer`;function ze(e,...t){return t.reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{})}var Be=E.setTimeout,Ve=E.clearTimeout;function He(e,t){t.useNativeTimers?(e.setTimeoutFn=Be.bind(E),e.clearTimeoutFn=Ve.bind(E)):(e.setTimeoutFn=E.setTimeout.bind(E),e.clearTimeoutFn=E.clearTimeout.bind(E))}var Ue=1.33;function We(e){return typeof e==`string`?D(e):Math.ceil((e.byteLength||e.size)*Ue)}function D(e){let t=0,n=0;for(let r=0,i=e.length;r<i;r++)t=e.charCodeAt(r),t<128?n+=1:t<2048?n+=2:t<55296||t>=57344?n+=3:(r++,n+=4);return n}function O(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function Ge(e){let t=``;for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+=`&`),t+=encodeURIComponent(n)+`=`+encodeURIComponent(e[n]));return t}function Ke(e){let t={},n=e.split(`&`);for(let e=0,r=n.length;e<r;e++){let r=n[e].split(`=`);t[decodeURIComponent(r[0])]=decodeURIComponent(r[1])}return t}var qe=class extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type=`TransportError`}},Je=class extends T{constructor(e){super(),this.writable=!1,He(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,n){return super.emitReserved(`error`,new qe(e,t,n)),this}open(){return this.readyState=`opening`,this.doOpen(),this}close(){return(this.readyState===`opening`||this.readyState===`open`)&&(this.doClose(),this.onClose()),this}send(e){this.readyState===`open`&&this.write(e)}onOpen(){this.readyState=`open`,this.writable=!0,super.emitReserved(`open`)}onData(e){let t=Ee(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved(`packet`,e)}onClose(e){this.readyState=`closed`,super.emitReserved(`close`,e)}pause(e){}createUri(e,t={}){return e+`://`+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){let e=this.opts.hostname;return e.indexOf(`:`)===-1?e:`[`+e+`]`}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?`:`+this.opts.port:``}_query(e){let t=Ge(e);return t.length?`?`+t:``}},Ye=class extends Je{constructor(){super(...arguments),this._polling=!1}get name(){return`polling`}doOpen(){this._poll()}pause(e){this.readyState=`pausing`;let t=()=>{this.readyState=`paused`,e()};if(this._polling||!this.writable){let e=0;this._polling&&(e++,this.once(`pollComplete`,function(){--e||t()})),this.writable||(e++,this.once(`drain`,function(){--e||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved(`poll`)}onData(e){je(e,this.socket.binaryType).forEach(e=>{if(this.readyState===`opening`&&e.type===`open`&&this.onOpen(),e.type===`close`)return this.onClose({description:`transport closed by the server`}),!1;this.onPacket(e)}),this.readyState!==`closed`&&(this._polling=!1,this.emitReserved(`pollComplete`),this.readyState===`open`&&this._poll())}doClose(){let e=()=>{this.write([{type:`close`}])};this.readyState===`open`?e():this.once(`open`,e)}write(e){this.writable=!1,Ae(e,e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved(`drain`)})})}uri(){let e=this.opts.secure?`https`:`http`,t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=O()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}},Xe=!1;try{Xe=typeof XMLHttpRequest<`u`&&`withCredentials`in new XMLHttpRequest}catch{}var Ze=Xe;function Qe(){}var $e=class extends Ye{constructor(e){if(super(e),typeof location<`u`){let t=location.protocol===`https:`,n=location.port;n||=t?`443`:`80`,this.xd=typeof location<`u`&&e.hostname!==location.hostname||n!==e.port}}doWrite(e,t){let n=this.request({method:`POST`,data:e});n.on(`success`,t),n.on(`error`,(e,t)=>{this.onError(`xhr post error`,e,t)})}doPoll(){let e=this.request();e.on(`data`,this.onData.bind(this)),e.on(`error`,(e,t)=>{this.onError(`xhr poll error`,e,t)}),this.pollXhr=e}},et=class e extends T{constructor(e,t,n){super(),this.createRequest=e,He(this,n),this._opts=n,this._method=n.method||`GET`,this._uri=t,this._data=n.data===void 0?null:n.data,this._create()}_create(){var t;let n=ze(this._opts,`agent`,`pfx`,`key`,`passphrase`,`cert`,`ca`,`ciphers`,`rejectUnauthorized`,`autoUnref`);n.xdomain=!!this._opts.xd;let r=this._xhr=this.createRequest(n);try{r.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let e in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(e)&&r.setRequestHeader(e,this._opts.extraHeaders[e])}}catch{}if(this._method===`POST`)try{r.setRequestHeader(`Content-type`,`text/plain;charset=UTF-8`)}catch{}try{r.setRequestHeader(`Accept`,`*/*`)}catch{}(t=this._opts.cookieJar)==null||t.addCookies(r),`withCredentials`in r&&(r.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(r.timeout=this._opts.requestTimeout),r.onreadystatechange=()=>{var e;r.readyState===3&&((e=this._opts.cookieJar)==null||e.parseCookies(r.getResponseHeader(`set-cookie`))),r.readyState===4&&(r.status===200||r.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof r.status==`number`?r.status:0)},0))},r.send(this._data)}catch(e){this.setTimeoutFn(()=>{this._onError(e)},0);return}typeof document<`u`&&(this._index=e.requestsCount++,e.requests[this._index]=this)}_onError(e){this.emitReserved(`error`,e,this._xhr),this._cleanup(!0)}_cleanup(t){if(!(this._xhr===void 0||this._xhr===null)){if(this._xhr.onreadystatechange=Qe,t)try{this._xhr.abort()}catch{}typeof document<`u`&&delete e.requests[this._index],this._xhr=null}}_onLoad(){let e=this._xhr.responseText;e!==null&&(this.emitReserved(`data`,e),this.emitReserved(`success`),this._cleanup())}abort(){this._cleanup()}};if(et.requestsCount=0,et.requests={},typeof document<`u`){if(typeof attachEvent==`function`)attachEvent(`onunload`,tt);else if(typeof addEventListener==`function`){let e=`onpagehide`in E?`pagehide`:`unload`;addEventListener(e,tt,!1)}}function tt(){for(let e in et.requests)et.requests.hasOwnProperty(e)&&et.requests[e].abort()}var nt=(function(){let e=it({xdomain:!1});return e&&e.responseType!==null})(),rt=class extends $e{constructor(e){super(e);let t=e&&e.forceBase64;this.supportsBinary=nt&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new et(it,this.uri(),e)}};function it(e){let t=e.xdomain;try{if(typeof XMLHttpRequest<`u`&&(!t||Ze))return new XMLHttpRequest}catch{}if(!t)try{return new E[[`Active`,`Object`].join(`X`)](`Microsoft.XMLHTTP`)}catch{}}var at=typeof navigator<`u`&&typeof navigator.product==`string`&&navigator.product.toLowerCase()===`reactnative`,ot=class extends Je{get name(){return`websocket`}doOpen(){let e=this.uri(),t=this.opts.protocols,n=at?{}:ze(this.opts,`agent`,`perMessageDeflate`,`pfx`,`key`,`passphrase`,`cert`,`ca`,`ciphers`,`rejectUnauthorized`,`localAddress`,`protocolVersion`,`origin`,`maxPayload`,`family`,`checkServerIdentity`);this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,n)}catch(e){return this.emitReserved(`error`,e)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:`websocket connection closed`,context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError(`websocket error`,e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let n=e[t],r=t===e.length-1;_e(n,this.supportsBinary,e=>{try{this.doWrite(n,e)}catch{}r&&Le(()=>{this.writable=!0,this.emitReserved(`drain`)},this.setTimeoutFn)})}}doClose(){this.ws!==void 0&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){let e=this.opts.secure?`wss`:`ws`,t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=O()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}},st=E.WebSocket||E.MozWebSocket,ct={websocket:class extends ot{createSocket(e,t,n){return at?new st(e,t,n):t?new st(e,t):new st(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends Je{get name(){return`webtransport`}doOpen(){try{this._transport=new WebTransport(this.createUri(`https`),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved(`error`,e)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError(`webtransport error`,e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{let t=Fe(2**53-1,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),r=Me();r.readable.pipeTo(e.writable),this._writer=r.writable.getWriter();let i=()=>{n.read().then(({done:e,value:t})=>{e||(this.onPacket(t),i())}).catch(e=>{})};i();let a={type:`open`};this.query.sid&&(a.data=`{"sid":"${this.query.sid}"}`),this._writer.write(a).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let n=e[t],r=t===e.length-1;this._writer.write(n).then(()=>{r&&Le(()=>{this.writable=!0,this.emitReserved(`drain`)},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)==null||e.close()}},polling:rt},lt=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,ut=[`source`,`protocol`,`authority`,`userInfo`,`user`,`password`,`host`,`port`,`relative`,`path`,`directory`,`file`,`query`,`anchor`];function dt(e){if(e.length>8e3)throw`URI too long`;let t=e,n=e.indexOf(`[`),r=e.indexOf(`]`);n!=-1&&r!=-1&&(e=e.substring(0,n)+e.substring(n,r).replace(/:/g,`;`)+e.substring(r,e.length));let i=lt.exec(e||``),a={},o=14;for(;o--;)a[ut[o]]=i[o]||``;return n!=-1&&r!=-1&&(a.source=t,a.host=a.host.substring(1,a.host.length-1).replace(/;/g,`:`),a.authority=a.authority.replace(`[`,``).replace(`]`,``).replace(/;/g,`:`),a.ipv6uri=!0),a.pathNames=ft(a,a.path),a.queryKey=pt(a,a.query),a}function ft(e,t){let n=t.replace(/\/{2,9}/g,`/`).split(`/`);return(t.slice(0,1)==`/`||t.length===0)&&n.splice(0,1),t.slice(-1)==`/`&&n.splice(n.length-1,1),n}function pt(e,t){let n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,r){t&&(n[t]=r)}),n}var mt=typeof addEventListener==`function`&&typeof removeEventListener==`function`,ht=[];mt&&addEventListener(`offline`,()=>{ht.forEach(e=>e())},!1);var gt=class e extends T{constructor(e,t){if(super(),this.binaryType=Re,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&typeof e==`object`&&(t=e,e=null),e){let n=dt(e);t.hostname=n.host,t.secure=n.protocol===`https`||n.protocol===`wss`,t.port=n.port,n.query&&(t.query=n.query)}else t.host&&(t.hostname=dt(t.host).host);He(this,t),this.secure=t.secure==null?typeof location<`u`&&location.protocol===`https:`:t.secure,t.hostname&&!t.port&&(t.port=this.secure?`443`:`80`),this.hostname=t.hostname||(typeof location<`u`?location.hostname:`localhost`),this.port=t.port||(typeof location<`u`&&location.port?location.port:this.secure?`443`:`80`),this.transports=[],this._transportsByName={},t.transports.forEach(e=>{let t=e.prototype.name;this.transports.push(t),this._transportsByName[t]=e}),this.opts=Object.assign({path:`/engine.io`,agent:!1,withCredentials:!1,upgrade:!0,timestampParam:`t`,rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,``)+(this.opts.addTrailingSlash?`/`:``),typeof this.opts.query==`string`&&(this.opts.query=Ke(this.opts.query)),mt&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener(`beforeunload`,this._beforeunloadEventListener,!1)),this.hostname!==`localhost`&&(this._offlineEventListener=()=>{this._onClose(`transport close`,{description:`network connection lost`})},ht.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){let t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);let n=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](n)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved(`error`,`No transports available`)},0);return}let t=this.opts.rememberUpgrade&&e.priorWebsocketSuccess&&this.transports.indexOf(`websocket`)!==-1?`websocket`:this.transports[0];this.readyState=`opening`;let n=this.createTransport(t);n.open(),this.setTransport(n)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on(`drain`,this._onDrain.bind(this)).on(`packet`,this._onPacket.bind(this)).on(`error`,this._onError.bind(this)).on(`close`,e=>this._onClose(`transport close`,e))}onOpen(){this.readyState=`open`,e.priorWebsocketSuccess=this.transport.name===`websocket`,this.emitReserved(`open`),this.flush()}_onPacket(e){if(this.readyState===`opening`||this.readyState===`open`||this.readyState===`closing`)switch(this.emitReserved(`packet`,e),this.emitReserved(`heartbeat`),e.type){case`open`:this.onHandshake(JSON.parse(e.data));break;case`ping`:this._sendPacket(`pong`),this.emitReserved(`ping`),this.emitReserved(`pong`),this._resetPingTimeout();break;case`error`:let t=Error(`server error`);t.code=e.data,this._onError(t);break;case`message`:this.emitReserved(`data`,e.data),this.emitReserved(`message`,e.data);break}}onHandshake(e){this.emitReserved(`handshake`,e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),this.readyState!==`closed`&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);let e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose(`ping timeout`)},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved(`drain`):this.flush()}flush(){if(this.readyState!==`closed`&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){let e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved(`flush`)}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name===`polling`&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let t=0;t<this.writeBuffer.length;t++){let n=this.writeBuffer[t].data;if(n&&(e+=We(n)),t>0&&e>this._maxPayload)return this.writeBuffer.slice(0,t);e+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;let e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,Le(()=>{this._onClose(`ping timeout`)},this.setTimeoutFn)),e}write(e,t,n){return this._sendPacket(`message`,e,t,n),this}send(e,t,n){return this._sendPacket(`message`,e,t,n),this}_sendPacket(e,t,n,r){if(typeof t==`function`&&(r=t,t=void 0),typeof n==`function`&&(r=n,n=null),this.readyState===`closing`||this.readyState===`closed`)return;n||={},n.compress=!1!==n.compress;let i={type:e,data:t,options:n};this.emitReserved(`packetCreate`,i),this.writeBuffer.push(i),r&&this.once(`flush`,r),this.flush()}close(){let e=()=>{this._onClose(`forced close`),this.transport.close()},t=()=>{this.off(`upgrade`,t),this.off(`upgradeError`,t),e()},n=()=>{this.once(`upgrade`,t),this.once(`upgradeError`,t)};return(this.readyState===`opening`||this.readyState===`open`)&&(this.readyState=`closing`,this.writeBuffer.length?this.once(`drain`,()=>{this.upgrading?n():e()}):this.upgrading?n():e()),this}_onError(t){if(e.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState===`opening`)return this.transports.shift(),this._open();this.emitReserved(`error`,t),this._onClose(`transport error`,t)}_onClose(e,t){if(this.readyState===`opening`||this.readyState===`open`||this.readyState===`closing`){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners(`close`),this.transport.close(),this.transport.removeAllListeners(),mt&&(this._beforeunloadEventListener&&removeEventListener(`beforeunload`,this._beforeunloadEventListener,!1),this._offlineEventListener)){let e=ht.indexOf(this._offlineEventListener);e!==-1&&ht.splice(e,1)}this.readyState=`closed`,this.id=null,this.emitReserved(`close`,e,t),this.writeBuffer=[],this._prevBufferLen=0}}};gt.protocol=4;var _t=class extends gt{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState===`open`&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),n=!1;gt.priorWebsocketSuccess=!1;let r=()=>{n||(t.send([{type:`ping`,data:`probe`}]),t.once(`packet`,e=>{if(!n)if(e.type===`pong`&&e.data===`probe`){if(this.upgrading=!0,this.emitReserved(`upgrading`,t),!t)return;gt.priorWebsocketSuccess=t.name===`websocket`,this.transport.pause(()=>{n||this.readyState!==`closed`&&(l(),this.setTransport(t),t.send([{type:`upgrade`}]),this.emitReserved(`upgrade`,t),t=null,this.upgrading=!1,this.flush())})}else{let e=Error(`probe error`);e.transport=t.name,this.emitReserved(`upgradeError`,e)}}))};function i(){n||(n=!0,l(),t.close(),t=null)}let a=e=>{let n=Error(`probe error: `+e);n.transport=t.name,i(),this.emitReserved(`upgradeError`,n)};function o(){a(`transport closed`)}function s(){a(`socket closed`)}function c(e){t&&e.name!==t.name&&i()}let l=()=>{t.removeListener(`open`,r),t.removeListener(`error`,a),t.removeListener(`close`,o),this.off(`close`,s),this.off(`upgrading`,c)};t.once(`open`,r),t.once(`error`,a),t.once(`close`,o),this.once(`close`,s),this.once(`upgrading`,c),this._upgrades.indexOf(`webtransport`)!==-1&&e!==`webtransport`?this.setTimeoutFn(()=>{n||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){let t=[];for(let n=0;n<e.length;n++)~this.transports.indexOf(e[n])&&t.push(e[n]);return t}},vt=class extends _t{constructor(e,t={}){let n=typeof e==`object`?e:t;(!n.transports||n.transports&&typeof n.transports[0]==`string`)&&(n.transports=(n.transports||[`polling`,`websocket`,`webtransport`]).map(e=>ct[e]).filter(e=>!!e)),super(e,n)}};vt.protocol;function yt(e,t=``,n){let r=e;n||=typeof location<`u`&&location,e??=n.protocol+`//`+n.host,typeof e==`string`&&(e.charAt(0)===`/`&&(e=e.charAt(1)===`/`?n.protocol+e:n.host+e),/^(https?|wss?):\/\//.test(e)||(e=n===void 0?`https://`+e:n.protocol+`//`+e),r=dt(e)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port=`80`:/^(http|ws)s$/.test(r.protocol)&&(r.port=`443`)),r.path=r.path||`/`;let i=r.host.indexOf(`:`)===-1?r.host:`[`+r.host+`]`;return r.id=r.protocol+`://`+i+`:`+r.port+t,r.href=r.protocol+`://`+i+(n&&n.port===r.port?``:`:`+r.port),r}var bt=typeof ArrayBuffer==`function`,xt=e=>typeof ArrayBuffer.isView==`function`?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,St=Object.prototype.toString,Ct=typeof Blob==`function`||typeof Blob<`u`&&St.call(Blob)===`[object BlobConstructor]`,wt=typeof File==`function`||typeof File<`u`&&St.call(File)===`[object FileConstructor]`;function Tt(e){return bt&&(e instanceof ArrayBuffer||xt(e))||Ct&&e instanceof Blob||wt&&e instanceof File}function Et(e,t){if(!e||typeof e!=`object`)return!1;if(Array.isArray(e)){for(let t=0,n=e.length;t<n;t++)if(Et(e[t]))return!0;return!1}if(Tt(e))return!0;if(e.toJSON&&typeof e.toJSON==`function`&&arguments.length===1)return Et(e.toJSON(),!0);for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&Et(e[t]))return!0;return!1}function Dt(e){let t=[],n=e.data,r=e;return r.data=Ot(n,t),r.attachments=t.length,{packet:r,buffers:t}}function Ot(e,t){if(!e)return e;if(Tt(e)){let n={_placeholder:!0,num:t.length};return t.push(e),n}else if(Array.isArray(e)){let n=Array(e.length);for(let r=0;r<e.length;r++)n[r]=Ot(e[r],t);return n}else if(typeof e==`object`&&!(e instanceof Date)){let n={};for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=Ot(e[r],t));return n}return e}function kt(e,t){return e.data=At(e.data,t),delete e.attachments,e}function At(e,t){if(!e)return e;if(e&&e._placeholder===!0){if(typeof e.num==`number`&&e.num>=0&&e.num<t.length)return t[e.num];throw Error(`illegal attachments`)}else if(Array.isArray(e))for(let n=0;n<e.length;n++)e[n]=At(e[n],t);else if(typeof e==`object`)for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=At(e[n],t));return e}var jt=s({Decoder:()=>Pt,Encoder:()=>Nt,PacketType:()=>k,isPacketValid:()=>Vt,protocol:()=>5}),Mt=[`connect`,`connect_error`,`disconnect`,`disconnecting`,`newListener`,`removeListener`],k;(function(e){e[e.CONNECT=0]=`CONNECT`,e[e.DISCONNECT=1]=`DISCONNECT`,e[e.EVENT=2]=`EVENT`,e[e.ACK=3]=`ACK`,e[e.CONNECT_ERROR=4]=`CONNECT_ERROR`,e[e.BINARY_EVENT=5]=`BINARY_EVENT`,e[e.BINARY_ACK=6]=`BINARY_ACK`})(k||={});var Nt=class{constructor(e){this.replacer=e}encode(e){return(e.type===k.EVENT||e.type===k.ACK)&&Et(e)?this.encodeAsBinary({type:e.type===k.EVENT?k.BINARY_EVENT:k.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=``+e.type;return(e.type===k.BINARY_EVENT||e.type===k.BINARY_ACK)&&(t+=e.attachments+`-`),e.nsp&&e.nsp!==`/`&&(t+=e.nsp+`,`),e.id!=null&&(t+=e.id),e.data!=null&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){let t=Dt(e),n=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(n),r}},Pt=class e extends T{constructor(e){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},typeof e==`function`?{reviver:e}:e)}add(e){let t;if(typeof e==`string`){if(this.reconstructor)throw Error(`got plaintext data when reconstructing a packet`);t=this.decodeString(e);let n=t.type===k.BINARY_EVENT;n||t.type===k.BINARY_ACK?(t.type=n?k.EVENT:k.ACK,this.reconstructor=new Ft(t),t.attachments===0&&super.emitReserved(`decoded`,t)):super.emitReserved(`decoded`,t)}else if(Tt(e)||e.base64)if(this.reconstructor)t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved(`decoded`,t));else throw Error(`got binary data when not reconstructing a packet`);else throw Error(`Unknown type: `+e)}decodeString(t){let n=0,r={type:Number(t.charAt(0))};if(k[r.type]===void 0)throw Error(`unknown packet type `+r.type);if(r.type===k.BINARY_EVENT||r.type===k.BINARY_ACK){let e=n+1;for(;t.charAt(++n)!==`-`&&n!=t.length;);let i=t.substring(e,n);if(i!=Number(i)||t.charAt(n)!==`-`)throw Error(`Illegal attachments`);let a=Number(i);if(!Lt(a)||a<0)throw Error(`Illegal attachments`);if(a>this.opts.maxAttachments)throw Error(`too many attachments`);r.attachments=a}if(t.charAt(n+1)===`/`){let e=n+1;for(;++n&&!(t.charAt(n)===`,`||n===t.length););r.nsp=t.substring(e,n)}else r.nsp=`/`;let i=t.charAt(n+1);if(i!==``&&Number(i)==i){let e=n+1;for(;++n;){let e=t.charAt(n);if(e==null||Number(e)!=e){--n;break}if(n===t.length)break}r.id=Number(t.substring(e,n+1))}if(t.charAt(++n)){let i=this.tryParse(t.substr(n));if(e.isPayloadValid(r.type,i))r.data=i;else throw Error(`invalid payload`)}return r}tryParse(e){try{return JSON.parse(e,this.opts.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case k.CONNECT:return zt(t);case k.DISCONNECT:return t===void 0;case k.CONNECT_ERROR:return typeof t==`string`||zt(t);case k.EVENT:case k.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]==`number`||typeof t[0]==`string`&&Mt.indexOf(t[0])===-1);case k.ACK:case k.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&=(this.reconstructor.finishedReconstruction(),null)}},Ft=class{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){let e=kt(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function It(e){return typeof e==`string`}var Lt=Number.isInteger||function(e){return typeof e==`number`&&isFinite(e)&&Math.floor(e)===e};function Rt(e){return e===void 0||Lt(e)}function zt(e){return Object.prototype.toString.call(e)===`[object Object]`}function Bt(e,t){switch(e){case k.CONNECT:return t===void 0||zt(t);case k.DISCONNECT:return t===void 0;case k.EVENT:return Array.isArray(t)&&(typeof t[0]==`number`||typeof t[0]==`string`&&Mt.indexOf(t[0])===-1);case k.ACK:return Array.isArray(t);case k.CONNECT_ERROR:return typeof t==`string`||zt(t);default:return!1}}function Vt(e){return It(e.nsp)&&Rt(e.id)&&Bt(e.type,e.data)}function Ht(e,t,n){return e.on(t,n),function(){e.off(t,n)}}var Ut=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),Wt=class extends T{constructor(e,t,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;let e=this.io;this.subs=[Ht(e,`open`,this.onopen.bind(this)),Ht(e,`packet`,this.onpacket.bind(this)),Ht(e,`error`,this.onerror.bind(this)),Ht(e,`close`,this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState===`open`&&this.onopen(),this)}open(){return this.connect()}send(...e){return e.unshift(`message`),this.emit.apply(this,e),this}emit(e,...t){if(Ut.hasOwnProperty(e))throw Error(`"`+e.toString()+`" is a reserved event name`);if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;let n={type:k.EVENT,data:t};if(n.options={},n.options.compress=this.flags.compress!==!1,typeof t[t.length-1]==`function`){let e=this.ids++,r=t.pop();this._registerAckCallback(e,r),n.id=e}let r=this.io.engine?.transport?.writable,i=this.connected&&!this.io.engine?._hasPingExpired();return this.flags.volatile&&!r||(i?(this.notifyOutgoingListeners(n),this.packet(n)):this.sendBuffer.push(n)),this.flags={},this}_registerAckCallback(e,t){let n=this.flags.timeout??this._opts.ackTimeout;if(n===void 0){this.acks[e]=t;return}let r=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,Error(`operation has timed out`))},n),i=(...e)=>{this.io.clearTimeoutFn(r),t.apply(this,e)};i.withError=!0,this.acks[e]=i}emitWithAck(e,...t){return new Promise((n,r)=>{let i=(e,t)=>e?r(e):n(t);i.withError=!0,t.push(i),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]==`function`&&(t=e.pop());let n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((e,...r)=>(this._queue[0],e===null?(this._queue.shift(),t&&t(null,...r)):n.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)),n.pending=!1,this._drainQueue())),this._queue.push(n),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||this._queue.length===0)return;let t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){typeof this.auth==`function`?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:k.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved(`connect_error`,e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved(`disconnect`,e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(t=>String(t.id)===e)){let t=this.acks[e];delete this.acks[e],t.withError&&t.call(this,Error(`socket has been disconnected`))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case k.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved(`connect_error`,Error(`It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)`));break;case k.EVENT:case k.BINARY_EVENT:this.onevent(e);break;case k.ACK:case k.BINARY_ACK:this.onack(e);break;case k.DISCONNECT:this.ondisconnect();break;case k.CONNECT_ERROR:this.destroy();let t=Error(e.data.message);t.data=e.data.data,this.emitReserved(`connect_error`,t);break}}onevent(e){let t=e.data||[];e.id!=null&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){let t=this._anyListeners.slice();for(let n of t)n.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]==`string`&&(this._lastOffset=e[e.length-1])}ack(e){let t=this,n=!1;return function(...r){n||(n=!0,t.packet({type:k.ACK,id:e,data:r}))}}onack(e){let t=this.acks[e.id];typeof t==`function`&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved(`connect`)}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose(`io server disconnect`)}destroy(){this.subs&&=(this.subs.forEach(e=>e()),void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:k.DISCONNECT}),this.destroy(),this.connected&&this.onclose(`io client disconnect`),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){let t=this._anyListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){let t=this._anyOutgoingListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){let t=this._anyOutgoingListeners.slice();for(let n of t)n.apply(this,e.data)}}};function Gt(e){e||={},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}Gt.prototype.duration=function(){var e=this.ms*this.factor**+ this.attempts++;if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=Math.floor(t*10)&1?e+n:e-n}return Math.min(e,this.max)|0},Gt.prototype.reset=function(){this.attempts=0},Gt.prototype.setMin=function(e){this.ms=e},Gt.prototype.setMax=function(e){this.max=e},Gt.prototype.setJitter=function(e){this.jitter=e};var Kt=class extends T{constructor(e,t){super(),this.nsps={},this.subs=[],e&&typeof e==`object`&&(t=e,e=void 0),t||={},t.path=t.path||`/socket.io`,this.opts=t,He(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(t.randomizationFactor??.5),this.backoff=new Gt({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState=`closed`,this.uri=e;let n=t.parser||jt;this.encoder=new n.Encoder,this.decoder=new n.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)==null||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)==null||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)==null||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(~this._readyState.indexOf(`open`))return this;this.engine=new vt(this.uri,this.opts);let t=this.engine,n=this;this._readyState=`opening`,this.skipReconnect=!1;let r=Ht(t,`open`,function(){n.onopen(),e&&e()}),i=t=>{this.cleanup(),this._readyState=`closed`,this.emitReserved(`error`,t),e?e(t):this.maybeReconnectOnOpen()},a=Ht(t,`error`,i);if(!1!==this._timeout){let e=this._timeout,n=this.setTimeoutFn(()=>{r(),i(Error(`timeout`)),t.close()},e);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}return this.subs.push(r),this.subs.push(a),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState=`open`,this.emitReserved(`open`);let e=this.engine;this.subs.push(Ht(e,`ping`,this.onping.bind(this)),Ht(e,`data`,this.ondata.bind(this)),Ht(e,`error`,this.onerror.bind(this)),Ht(e,`close`,this.onclose.bind(this)),Ht(this.decoder,`decoded`,this.ondecoded.bind(this)))}onping(){this.emitReserved(`ping`)}ondata(e){try{this.decoder.add(e)}catch(e){this.onclose(`parse error`,e)}}ondecoded(e){Le(()=>{this.emitReserved(`packet`,e)},this.setTimeoutFn)}onerror(e){this.emitReserved(`error`,e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new Wt(this,e,t),this.nsps[e]=n),n}_destroy(e){let t=Object.keys(this.nsps);for(let e of t)if(this.nsps[e].active)return;this._close()}_packet(e){let t=this.encoder.encode(e);for(let n=0;n<t.length;n++)this.engine.write(t[n],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose(`forced close`)}disconnect(){return this._close()}onclose(e,t){var n;this.cleanup(),(n=this.engine)==null||n.close(),this.backoff.reset(),this._readyState=`closed`,this.emitReserved(`close`,e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;let e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved(`reconnect_failed`),this._reconnecting=!1;else{let t=this.backoff.duration();this._reconnecting=!0;let n=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved(`reconnect_attempt`,e.backoff.attempts),!e.skipReconnect&&e.open(t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved(`reconnect_error`,t)):e.onreconnect()}))},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){let e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved(`reconnect`,e)}},qt={};function Jt(e,t){typeof e==`object`&&(t=e,e=void 0),t||={};let n=yt(e,t.path||`/socket.io`),r=n.source,i=n.id,a=n.path,o=qt[i]&&a in qt[i].nsps,s=t.forceNew||t[`force new connection`]||!1===t.multiplex||o,c;return s?c=new Kt(r,t):(qt[i]||(qt[i]=new Kt(r,t)),c=qt[i]),n.query&&!t.query&&(t.query=n.queryKey),c.socket(n.path,t)}Object.assign(Jt,{Manager:Kt,Socket:Wt,io:Jt,connect:Jt});var Yt=({apiBaseUrl:e,userId:t,chatId:n,siteId:r})=>Jt(e,{transports:[`polling`,`websocket`],upgrade:!0,rememberUpgrade:!1,auth:{userId:t,chatId:n,siteId:r},query:{chatId:n,siteId:r}}),Xt=({socket:e,chatId:t})=>{if(!e||!t||typeof window>`u`)return()=>{};let n=window.location.pathname+window.location.search,r=Date.now(),i=null,a=null,o=()=>{console.log(`[FlowEngageTracking] visitor:session_start`,{chatId:t,path:n}),e.emit(`visitor:session_start`,{chatId:t,path:n,title:document.title,referrer:document.referrer,userAgent:navigator.userAgent,timestamp:Date.now()})},s=()=>{console.log(`[FlowEngageTracking] visitor:page_enter`,{chatId:t,path:n}),e.emit(`visitor:page_enter`,{chatId:t,path:n,title:document.title,timestamp:Date.now()})},c=(n,r)=>{console.log(`[FlowEngageTracking] visitor:page_leave`,{chatId:t,path:n,duration:Math.max(0,Math.floor((Date.now()-r)/1e3))}),e.emit(`visitor:page_leave`,{chatId:t,path:n,duration:Math.max(0,Math.floor((Date.now()-r)/1e3)),timestamp:Date.now()})},l=()=>{console.log(`[FlowEngageTracking] visitor:heartbeat`,{chatId:t,path:n}),e.emit(`visitor:heartbeat`,{chatId:t,path:n,title:document.title,timestamp:Date.now()})},u=()=>{i&&window.clearInterval(i),i=window.setInterval(l,h)},d=()=>{i&&=(window.clearInterval(i),null)},f=r=>{console.log(`[FlowEngageTracking] visitor:visibility`,{chatId:t,state:r}),e.emit(`visitor:visibility`,{chatId:t,state:r,path:n,title:document.title,timestamp:Date.now()})},p=()=>{if(document.hidden){a&&window.clearTimeout(a),a=window.setTimeout(()=>{a=null,d(),f(`hidden`)},g);return}a&&=(window.clearTimeout(a),null),f(`visible`),l(),u()},m=()=>{let e=window.location.pathname+window.location.search;if(e===n){console.log(`[FlowEngageTracking] route unchanged`,{currentPath:n});return}console.log(`[FlowEngageTracking] route changed`,{from:n,to:e}),c(n,r),n=e,r=Date.now(),s()},_=window.history.pushState.bind(window.history),v=window.history.replaceState.bind(window.history);window.history.pushState=(...e)=>{_(...e),m()},window.history.replaceState=(...e)=>{v(...e),m()};let y=()=>{c(n,r),e.emit(`visitor:session_end`,{chatId:t,timestamp:Date.now()})};return window.addEventListener(`popstate`,m),window.addEventListener(`hashchange`,m),window.addEventListener(`beforeunload`,y),window.addEventListener(`visibilitychange`,p),o(),document.hidden?a=window.setTimeout(()=>{a=null,d(),f(`hidden`)},g):(l(),u()),{notifyRouteChange:m,cleanup:()=>{a&&=(window.clearTimeout(a),null),d(),window.history.pushState=_,window.history.replaceState=v,window.removeEventListener(`popstate`,m),window.removeEventListener(`hashchange`,m),window.removeEventListener(`beforeunload`,y),window.removeEventListener(`visibilitychange`,p)}}},Zt=(0,d.createContext)(null),Qt=()=>{let e=(0,d.useContext)(Zt);if(!e)throw Error(`useFlowEngage must be used inside FlowEngageProvider`);return e};function $t(){if(typeof window>`u`)return!1;try{let e=window.localStorage?.getItem(`FE_DEBUG_VOICE`);if(e===`0`||e===`false`)return!1;if(e===`1`||e===`true`)return!0}catch{}return window.__FE_DEBUG_VOICE_TOOLS__===!1?!1:window.__FE_DEBUG_VOICE_TOOLS__===!0}function en(e){if(!e||typeof e.closest!=`function`)return!1;try{return!!e.closest(`#flowengage-root, .flowengage-shell, .flowengage-widget-root`)}catch{return!1}}function tn(...e){$t()&&console.log(`[FlowEngage:shadowNavigate]`,...e)}var nn=`fe_pending_nav_section`,rn=15e3;function an(){if(typeof window>`u`||typeof document>`u`)return;let e;try{e=JSON.parse(sessionStorage.getItem(nn)||`null`)}catch{return}if(!e)return;try{sessionStorage.removeItem(nn)}catch{}let{sectionText:t,ts:n}=e;if(!t)return;if(Date.now()-n>rn){tn(`initNavigationHighlight: pending section expired, skipping:`,t);return}tn(`initNavigationHighlight: replaying section highlight:`,t);let r=0,i=()=>{r+=1;let e=sn(null,t);if(e){cn(e),tn(`initNavigationHighlight: highlighted on attempt`,r);return}r<8?setTimeout(i,300):tn(`initNavigationHighlight: could not find element after 8 attempts:`,t)};setTimeout(i,250)}var on=()=>{if(typeof document>`u`||document.getElementById(`fe-highlight-styles`))return;let e=document.createElement(`style`);e.id=`fe-highlight-styles`,e.textContent=`
2
2
  .fe-highlight-section {
3
3
  outline: 3px solid #7c3aed !important;
4
4
  box-shadow: 0 0 15px rgba(124, 58, 237, 0.6) !important;
@@ -22,8 +22,8 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
22
22
  box-shadow: none !important;
23
23
  transition: outline-color 0.25s ease, box-shadow 0.25s ease !important;
24
24
  }
25
- `,document.head.appendChild(e)};function nn(e,t){if(typeof document>`u`)return null;if(e){let n=document.getElementById(e)||document.querySelector(`[data-section="${e}"]`);if(n)return n;t||=e.replace(/[-_]+/g,` `).trim()}if(!t)return null;let n=t.toLowerCase().trim(),r=n.split(/\s+/).filter(e=>e.length>2),i=Array.from(document.querySelectorAll(`h1, h2, h3, h4, h5, h6, [data-section]`)).filter(e=>!Xt(e));for(let e of i)if(e.textContent.replace(/\s+/g,` `).toLowerCase().trim()===n)return e;for(let e of i){let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.startsWith(n)||t.endsWith(n))return e}let a=[];for(let e of i){let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();t.includes(n)&&a.push({el:e,len:t.length})}if(a.length)return a.sort((e,t)=>e.len-t.len),a[0].el;for(let e of i){let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.length>3&&n.includes(t))return e}if(r.length>0){let e=null,t=0;for(let n of i){let i=n.textContent.replace(/\s+/g,` `).toLowerCase(),a=0;for(let e of r)i.includes(e)&&a++;let o=a/r.length;o>t&&o>=.6&&(t=o,e=n)}if(e)return e}let o=Array.from(document.querySelectorAll(`main [role='group']`)).filter(e=>!Xt(e)),s=[];for(let e of o){let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();t.length<15||t.length>8e3||t.includes(n)&&s.push({el:e,len:t.length})}if(s.length)return s.sort((e,t)=>e.len-t.len),s[0].el;if(r.length>0){let e=Array.from(document.querySelectorAll(`main a[href], article a[href], .views-row a[href], h2 a[href], h3 a[href], .card a[href], [class*='teaser'] a[href]`)).filter(e=>{if(Xt(e))return!1;try{let t=e.getAttribute(`href`)||``;if(!t||t===`#`||t.startsWith(`javascript:`))return!1}catch{return!1}let t=e.textContent.replace(/\s+/g,` `).trim();return t.length>=3&&t.length<=220}),t=null,n=0;for(let i of e){let e=i.textContent.replace(/\s+/g,` `).toLowerCase(),a=0;for(let t of r)e.includes(t)&&a++;let o=a/r.length;o>n&&o>=.5&&(n=o,t=i)}if(t)return t.closest(`article`)||t.closest(`.views-row`)||t}let c=document.querySelectorAll(`section, article, .card, [class*='feature'], [class*='service']`);for(let e of c){if(Xt(e))continue;let t=e.querySelector(`h1, h2, h3, h4, h5, h6`);if(t){let r=t.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(r.includes(n)||n.includes(r))return e}}let l=document.querySelectorAll(`li, strong, blockquote, dt`);for(let e of l){if(Xt(e))continue;let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.includes(n)&&t.length<500)return e.tagName===`STRONG`&&e.parentElement?.tagName===`LI`?e.parentElement:e}let u=Array.from(document.querySelectorAll(`a[href]`)).filter(e=>!Xt(e));u.sort((e,t)=>(e.textContent||``).trim().length-(t.textContent||``).trim().length);for(let e of u){let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.includes(n)&&t.length<500)return e}let d=document.querySelectorAll(`p`);for(let e of d){if(Xt(e))continue;let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.includes(n)&&t.length<800)return e}return null}function rn(e,{speaking:t=!1,scroll:n=!0}={}){if(!e||typeof document>`u`)return;tn();let r=document.querySelectorAll(`.fe-highlight-section`);for(let t of r)t!==e&&(t.classList.remove(`fe-highlight-section`,`fe-highlight-speaking`),t.classList.add(`fe-highlight-exiting`),setTimeout(()=>t.classList.remove(`fe-highlight-exiting`),300));if(e.classList.remove(`fe-highlight-exiting`),e.classList.add(`fe-highlight-section`),t?e.classList.add(`fe-highlight-speaking`):e.classList.remove(`fe-highlight-speaking`),n)try{e.scrollIntoView({behavior:`smooth`,block:`center`})}catch{try{e.scrollIntoView(!0)}catch{}}}function an(){typeof document>`u`||document.querySelectorAll(`.fe-highlight-section, .fe-highlight-exiting`).forEach(e=>e.classList.remove(`fe-highlight-section`,`fe-highlight-speaking`,`fe-highlight-exiting`))}function on(e){if(typeof window>`u`)return e;try{let t=new URL(String(e).trim(),window.location.href);return!/^https?:$/i.test(t.protocol)||t.origin===window.location.origin?t.href:new URL(t.pathname+t.search+t.hash,window.location.origin).href}catch{return e}}async function sn(e){if(typeof window>`u`)return!1;try{let t=new URL(String(e).trim(),window.location.href);return t.origin===window.location.origin?(await fetch(t.href,{method:`HEAD`,mode:`same-origin`,cache:`no-store`})).ok:!1}catch{return!1}}async function cn(e,{siteId:t,apiBaseUrl:n}){if(!e)return!1;if(!t||!n)return console.warn(`[FlowEngage] shouldProceedWithNavigation: missing siteId or apiBaseUrl`),!1;let r=String(n).replace(/\/$/,``),i=new URLSearchParams({siteId:String(t),url:String(e).trim()});try{let t=await(await fetch(`${r}/api/widget/navigate-allowed?${i.toString()}`)).json().catch(()=>({}));return t.success?t.allowed?!0:t.hasIndex===!1?sn(e):!1:!1}catch(e){return console.warn(`[FlowEngage] navigate-allowed check failed:`,e?.message),!1}}function ln(e){if(!(!e||typeof sessionStorage>`u`))try{sessionStorage.setItem(Qt,JSON.stringify({sectionText:e,ts:Date.now()}))}catch{}}async function un(e,t={}){if(typeof window>`u`)return!1;let{sectionText:n}=t;try{let t=on(e),r=new URL(t,window.location.origin);if(Zt(`input:`,e,`→ normalized:`,t,`href:`,r.href),r.hash&&r.pathname===window.location.pathname){let e=r.hash.slice(1),t=document.getElementById(e);if(t)return Zt(`branch: hash scroll (same path)`),t.scrollIntoView({behavior:`smooth`,block:`start`}),!0}if(r.pathname===window.location.pathname&&r.search===window.location.search&&!r.hash)return Zt(`branch: already on page (no nav)`),!1;let i=r.pathname+r.search+r.hash,a=window.next?.router;if(a?.push)return Zt(`branch: Next.js Pages router.push`,i),new Promise(e=>{let t=()=>{a.events?.off(`routeChangeComplete`,t),e(!0)};a.events?.on(`routeChangeComplete`,t),a.push(i),setTimeout(t,5e3)});let o=window.__NEXT_ROUTER__;return o?.push?(Zt(`branch: __NEXT_ROUTER__.push`,i),o.push(i),!0):(n?(ln(n),Zt(`branch: location.assign (full navigation, section stored):`,n)):Zt(`branch: location.assign (full navigation)`,r.href),window.location.assign(r.href),!0)}catch(t){console.warn(`[FlowEngage] shadowNavigate error:`,t),n&&ln(n);try{window.location.href=on(e)}catch{window.location.href=e}return!0}}var dn=e=>!e||typeof e!=`string`?e:e.replace(/<human_assistance_request>[\s\S]*?<\/human_assistance_request>/gi,``).replace(/<human_assistance_request>/gi,``).replace(/<\/human_assistance_request>/gi,``).replace(/<navigate[^>]*\/>/gi,``).replace(/<navigate[^>]*>[\s\S]*?<\/navigate>/gi,``).replace(/<[a-z]+(?:_[a-z]+)+[^>]*>[\s\S]*?<\/[a-z]+(?:_[a-z]+)+>/gi,``).replace(/<[a-z]+(?:_[a-z]+)+[^>]*\/>/gi,``).trim(),fn=(e=[])=>e.map(e=>({...e,message:dn(e.message),isPending:!1,id:e.messageId||`${e.sender}-${e.timestamp||Date.now()}-${Math.random()}`})),pn=(e,t)=>e?typeof e==`string`?e:e.message||e.error||e.reason||t:t,mn=(e={})=>{if(!e?.candidate)return null;if(typeof e.candidate==`object`)return e.candidate;let t=e.sdpMid!==void 0&&e.sdpMid!==null&&e.sdpMid!==``,n=e.sdpMLineIndex!==void 0&&e.sdpMLineIndex!==null;return!t&&!n?null:{candidate:e.candidate,...t?{sdpMid:e.sdpMid}:{},...n?{sdpMLineIndex:e.sdpMLineIndex}:{}}},hn=e=>{if(!e)return null;let t=typeof e==`object`?e:{candidate:e};return{hasCandidate:!!t.candidate,sdpMid:t.sdpMid??null,sdpMLineIndex:t.sdpMLineIndex??null,candidatePreview:typeof t.candidate==`string`?t.candidate.slice(0,80):null}},gn=(e=[],t=`Agent`)=>{for(let t of e)if(typeof t==`string`&&t.trim())return t.trim();return t},_n=(e=[],t,n=6)=>!t?.message||e.slice(-n).some(e=>e.sender===`system`&&e.message===t.message)?e:[...e,t];function vn({siteId:e,config:t,children:n,language:r=`en`}){let i=(0,d.useMemo)(()=>e?{...t||{},siteId:e}:t||null,[e,t]),[a,o]=(0,d.useState)(`booting`),[s,c]=(0,d.useState)(null),[l,u]=(0,d.useState)(null),[m,h]=(0,d.useState)(``),[g,b]=(0,d.useState)([]),[x,re]=(0,d.useState)(ee().isOpen),[ie,se]=(0,d.useState)(ee().activeScreen),[ce,le]=(0,d.useState)(ee().isHumanHandled),[ue,de]=(0,d.useState)(ee().agentName),[fe,pe]=(0,d.useState)(ee().agentHeadshot),[me,he]=(0,d.useState)(()=>C(i?.siteId)),[ge,_e]=(0,d.useState)(!1),[ve,ye]=(0,d.useState)(!1),[be,xe]=(0,d.useState)(`idle`),[Se,Ce]=(0,d.useState)(!1),[we,Te]=(0,d.useState)(!1),[Ee,De]=(0,d.useState)(``),[Oe,ke]=(0,d.useState)(!1),[Ae,je]=(0,d.useState)(!1),[w,T]=(0,d.useState)(null),[Me,Ne]=(0,d.useState)(null),[Pe,Fe]=(0,d.useState)(`idle`),[Ie,Le]=(0,d.useState)(null),[Re,ze]=(0,d.useState)(!1),[Be,Ve]=(0,d.useState)(``),E=(0,d.useRef)(null),D=(0,d.useRef)(null),O=(0,d.useRef)(``),He=(0,d.useRef)(null),Ue=(0,d.useRef)(null),We=(0,d.useRef)(null),Ge=(0,d.useRef)(null),Ke=(0,d.useRef)(null),qe=(0,d.useRef)([]),Je=(0,d.useRef)(null),Ye=(0,d.useRef)(null),Xe=(0,d.useRef)(!1),Ze=(0,d.useRef)(!1),Qe=(0,d.useRef)(``),$e=(0,d.useRef)(ue),et=(0,d.useRef)([]),tt=(0,d.useRef)(!1),nt=(0,d.useRef)({notifyRouteChange:()=>{},cleanup:()=>{}}),rt=(0,d.useCallback)((e={})=>{let t=!!e.is_human_handled;return le(t),t?(se(`agent`),e.agent_info?.name&&de(e.agent_info.name),e.agent_info?.headshot&&pe(e.agent_info.headshot),t):(se(`ai`),t)},[]),it=(0,d.useMemo)(()=>{let e=l?.widgetSettings?.call?.maxDurationSeconds??i?.widgetSettings?.call?.maxDurationSeconds??i?.callMaxDurationSeconds,t=Number(e);return Number.isFinite(t)&&t>0?t:v},[i,l]);(0,d.useEffect)(()=>{He.current=w},[w]),(0,d.useEffect)(()=>{$e.current=ue},[ue]);let at=()=>{Ve(``)},ot=e=>{let t=typeof e==`string`?e.trim().toLowerCase():``;return he(t),ne(t,i?.siteId),t};(0,d.useEffect)(()=>{let e=i?.siteId;e&&he(C(e))},[i?.siteId]);let st=(e=`unspecified`)=>{console.log(`[FlowEngageCall] cleanup:start`,{reason:e,chatId:O.current,activeCallId:Je.current,acceptingCallId:Ye.current,hasPeerConnection:!!Ue.current,hasLocalStream:!!We.current,hasRemoteAudio:!!Ge.current,queuedIceCount:qe.current.length}),Ue.current&&=(Ue.current.close(),null),We.current&&=(We.current.getTracks().forEach(e=>e.stop()),null),Ge.current&&=(Ge.current.srcObject=null,Ge.current.remove(),null),Ke.current=null,qe.current=[],Je.current=null,Ye.current=null,Xe.current=!1,ze(!1),T(null),Ne(null),Fe(`idle`),Le(null),console.log(`[FlowEngageCall] cleanup:complete`,{reason:e,chatId:O.current})},ct=(e=new Date().toISOString())=>{let t=E.current,n=Je.current||Ke.current?.callId;if(!t?.connected||!n||Xe.current){console.log(`[FlowEngageProvider] skipping call:connected emit`,{callId:n,chatId:O.current,socketConnected:!!t?.connected,alreadyReported:Xe.current});return}console.log(`[FlowEngageProvider] emitting call:connected`,{callId:n,chatId:O.current,connectedAt:e}),Xe.current=!0,t.emit(`call:connected`,{callId:n,chatId:O.current,connectedAt:e})},lt=(e={})=>{if(!e.callId)return;let t=Ye.current===e.callId,n=Je.current===e.callId,r=He.current?.callId===e.callId;if(!(!t&&!n&&!r)){if(console.log(`[FlowEngageProvider] syncing accepted call state`,{callId:e.callId,chatId:e.chatId||O.current,isAcceptingHere:t,isAlreadyActive:n,isIncomingHere:r}),T(null),t||n){Je.current=e.callId,Ne(e.callId),Fe(e=>e===`connected`?e:`connecting`),re(!0);return}Fe(`idle`)}},ut=(e={})=>{if(!e.callId)return;let t=Ye.current===e.callId,n=Je.current===e.callId,r=He.current?.callId===e.callId;if(!(!t&&!n&&!r)){if(console.log(`[FlowEngageProvider] syncing ended incoming call state`,{callId:e.callId,chatId:e.chatId||O.current,isAcceptingHere:t,isAlreadyActive:n,isIncomingHere:r,reason:e.reason||e.status||null}),n){st();return}Ye.current=null,Ke.current=null,qe.current=[],T(null),Fe(`idle`)}},dt=async(e={})=>{let t=Ue.current,n=E.current,r=e.sdpOffer||e.offer?.sdp;if(!t||!n?.connected||!r||!e.callId){console.log(`[FlowEngageProvider] deferring remote offer until peer/socket ready`,{callId:e.callId,chatId:O.current,hasPeerConnection:!!t,socketConnected:!!n?.connected,hasOffer:!!r}),Ke.current=e;return}if(console.log(`[FlowEngageProvider] applying remote offer`,{callId:e.callId,chatId:O.current,offerLength:r.length,signalingState:t.signalingState,iceConnectionState:t.iceConnectionState,connectionState:t.connectionState}),await t.setRemoteDescription(new RTCSessionDescription({type:`offer`,sdp:r})),qe.current.length>0){console.log(`[FlowEngageProvider] flushing queued agent ICE candidates after remote offer`,{callId:e.callId,chatId:O.current,queuedCount:qe.current.length});for(let e of qe.current)await t.addIceCandidate(new RTCIceCandidate(e));qe.current=[]}let i=await t.createAnswer();await t.setLocalDescription(i),console.log(`[FlowEngageCall] local-answer:created`,{callId:e.callId,chatId:O.current,answerLength:i.sdp?.length||0,signalingState:t.signalingState,iceConnectionState:t.iceConnectionState,connectionState:t.connectionState}),console.log(`[FlowEngageCall] local-answer:emitting`,{callId:e.callId,chatId:O.current}),n.emit(`call:answer`,{callId:e.callId,sdpAnswer:i.sdp,chatId:O.current})};(0,d.useEffect)(()=>{te({isOpen:x,activeScreen:ie,isHumanHandled:ce,agentName:ue,agentHeadshot:fe})},[x,ie,ce,ue,fe]),(0,d.useEffect)(()=>{let e=!0;return(async()=>{try{console.log(`[FlowEngageProvider] boot start`,{resolvedConfig:i,language:r});let t=p(i);console.log(`[FlowEngageProvider] config validated`,t);let n=await ae(t);if(!e)return;let a=S();O.current=a;let s=oe({apiBaseUrl:t.apiBaseUrl,userId:n.userId,siteId:t.siteId});D.current=s,u({...n,apiBaseUrl:t.apiBaseUrl}),h(a);let c=n?.widgetSettings?.branding?.fallbackAgentName||`Agent`;console.log(`[FlowEngageProvider] bootstrap resolved`,{bootstrapData:n,resolvedChatId:a});let l=Gt({apiBaseUrl:t.apiBaseUrl,userId:n.userId,chatId:a,siteId:t.siteId});E.current=l,l.on(`connect`,()=>{console.log(`[FlowEngageProvider] socket connected`),xe(`connected`)}),l.on(`disconnect`,()=>{console.log(`[FlowEngageProvider] socket disconnected`),xe(`disconnected`)}),l.on(`aiTyping`,()=>{console.log(`[FlowEngageProvider] received aiTyping`,{chatId:O.current}),ye(!0)}),l.on(`ai:typing`,()=>{console.log(`[FlowEngageProvider] received ai:typing`,{chatId:O.current}),ye(!0)}),l.on(`messageReceived`,e=>{let t=e.message||e,n={...t,message:dn(t.message)};ye(!1),_e(!1),b(e=>[...e.filter(e=>!e.isPending),{...n,isPending:!1,id:n.messageId||`${n.sender}-${Date.now()}-${Math.random()}`}])}),l.on(`conversationStarted`,e=>{console.log(`[FlowEngageProvider] conversationStarted`,e),e?.message&&b(t=>[...t,{id:`system-start-${Date.now()}`,sender:`system`,message:e.message,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`message:new`,e=>{let t=e.message||e,n={...t,message:dn(t.message)};ye(!1),(n.sender===`agent`||n.agent_name||n.sender===`ai`||n.sender===`bot`)&&_e(!1),b(e=>n.sender===`bot`||n.sender===`ai`?[...e,{...n,isPending:!1,id:n.messageId||`${n.sender}-${Date.now()}-${Math.random()}`}]:e.some(e=>e.id===n.messageId||e.sender===n.sender&&e.message===n.message&&e.isPending)?e.map(e=>e.sender===n.sender&&e.message===n.message&&e.isPending?{...n,isPending:!1,id:n.messageId||e.id}:e):[...e,{...n,isPending:!1,id:n.messageId||`${n.sender}-${Date.now()}-${Math.random()}`}]),(n.sender===`agent`||n.agent_name)&&(le(!0),se(`agent`),de(gn([n.agent_name,n.agentName,n.metadata?.agentName],c)),n.sender_headshot&&pe(n.sender_headshot),re(!0))});let d=(e={})=>{let t=gn([e.agent?.name,e.agentName,e.agent_name,$e.current],c);le(!0),se(`agent`),de(t),pe(e.agent?.headshot||null),re(!0),b(e=>_n(e,{id:`agent-joined-${Date.now()}`,sender:`system`,message:`${t} has joined the chat.`,timestamp:new Date().toISOString(),isPending:!1}))},f=(e={})=>{let t=gn([e.agent?.name,e.agentName,e.agent_name,$e.current],c);le(!1),se(`ai`),b(e=>_n(e,{id:`agent-left-${Date.now()}`,sender:`system`,message:`${t} has left the chat.`,timestamp:new Date().toISOString(),isPending:!1}))};l.on(`agent:joined`,d),l.on(`agentJoined`,d),l.on(`agent:left`,f),l.on(`agentLeft`,f),l.on(`conversationEnded`,e=>{je(!0);let t=e?.message||`This conversation has ended. Thank you for reaching out!`;b(e=>[...e,{id:`conversation-ended-${Date.now()}`,sender:`system`,message:t,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`chat:history_update`,e=>{b(fn(e.chat_history||[]))}),l.on(`typing:start`,e=>{console.log(`[FlowEngageProvider] received typing:start`,{chatId:e?.chatId||O.current,sender:e?.sender}),e.sender===`agent`&&_e(!0)}),l.on(`typing:stop`,e=>{console.log(`[FlowEngageProvider] received typing:stop`,{chatId:e?.chatId||O.current,sender:e?.sender}),e.sender===`agent`&&_e(!1)}),l.on(`call:incoming`,(e={})=>{let t=gn([e.agentName,e.ownerName,e.agent?.name,$e.current],`Agent`);console.log(`[FlowEngageProvider] received call:incoming`,{callId:e.callId,chatId:O.current,agentName:t}),at(),Xe.current=!1,T({callId:e.callId,from:e.from||`owner`,agentId:e.agentId||null,agentName:t}),de(e=>gn([t,e],`Agent`)),Fe(`incoming`),Le(null),re(!0)}),l.on(`call:offer`,async(e={})=>{console.log(`[FlowEngageProvider] received call:offer`,{callId:e.callId,chatId:e.chatId||O.current,offerLength:(e.sdpOffer||e.offer?.sdp||``).length}),Ke.current=e;try{await dt(e)}catch(e){console.error(`[FlowEngageProvider] failed to apply remote offer`,e)}}),l.on(`call:ice-candidate-from-agent`,async(e={})=>{if(!e.candidate){console.log(`[FlowEngageProvider] skipping agent ICE candidate`,{callId:e.callId,chatId:e.chatId||O.current,hasPeerConnection:!!Ue.current,hasCandidate:!!e.candidate});return}try{let t=mn(e);if(!t){console.warn(`[FlowEngageProvider] ignoring invalid ICE candidate payload`,e);return}if(console.log(`[FlowEngageProvider] adding agent ICE candidate`,{callId:e.callId,chatId:e.chatId||O.current,candidate:hn(t),hasRemoteDescription:!!Ue.current?.remoteDescription}),!Ue.current||!Ue.current.remoteDescription){console.log(`[FlowEngageProvider] queueing agent ICE candidate until peer/remote description is ready`,{callId:e.callId,chatId:e.chatId||O.current,queueSize:qe.current.length+1}),qe.current.push(t);return}await Ue.current.addIceCandidate(new RTCIceCandidate(t))}catch(e){console.error(`[FlowEngageProvider] failed to add ICE candidate`,e)}}),l.on(`call:ended`,()=>{at(),console.log(`[FlowEngageCall] socket:event call:ended`,{chatId:O.current,activeCallId:Je.current}),st(`socket:call_ended`)}),l.on(`call:accepted`,(e={})=>{console.log(`[FlowEngageProvider] received call:accepted`,{callId:e.callId,chatId:e.chatId||O.current}),lt(e)}),l.on(`call:accepted_by_other`,(e={})=>{console.log(`[FlowEngageProvider] received call:accepted_by_other`,{callId:e.callId,chatId:e.chatId||O.current}),lt(e)}),l.on(`call:rejected`,(e={})=>{console.log(`[FlowEngageProvider] received call:rejected`,{callId:e.callId,chatId:e.chatId||O.current,reason:e.reason}),ut(e)}),l.on(`call:missed`,(e={})=>{console.log(`[FlowEngageProvider] received call:missed`,{callId:e.callId,chatId:e.chatId||O.current,reason:e.reason}),ut(e)}),l.on(`call:failed`,(e={})=>{console.log(`[FlowEngageProvider] received call:failed`,{callId:e.callId,chatId:e.chatId||O.current,reason:e.reason}),ut(e)}),l.on(`call:connected`,(e={})=>{if(!e.callId)return;let t=Ye.current===e.callId,n=Je.current===e.callId,r=Ke.current?.callId===e.callId,i=He.current?.callId===e.callId;if(console.log(`[FlowEngageProvider] received call:connected`,{callId:e.callId,chatId:e.chatId||O.current,connectedAt:e.connectedAt,status:e.status,isAcceptingHere:t,isAlreadyActive:n,isPendingOfferHere:r,isIncomingHere:i}),!t&&!n&&!r){i&&(T(null),Fe(`idle`));return}Xe.current=!0,Ye.current=null,Je.current=e.callId,Ne(e.callId),T(null),Fe(`connected`),Le(e.connectedAt||new Date().toISOString()),re(!0)}),l.on(`call:unavailable`,(e={})=>{console.warn(`[FlowEngageCall] socket:event call:unavailable`,{chatId:e.chatId||O.current,callId:e.callId,reason:e.reason||e.message||null,raw:e}),st(`socket:call_unavailable`),Ve(pn(e,`This visitor is not available for a call right now.`)),re(!0)}),l.on(`call:error`,(e={})=>{console.error(`[FlowEngageCall] socket:event call:error`,{chatId:e.chatId||O.current,callId:e.callId,reason:e.reason||e.message||null,raw:e}),st(`socket:call_error`),Ve(pn(e,`We couldn't connect the call right now.`)),re(!0)}),l.on(`visitor:navigate`,async({url:e,section:n,highlight:r}={})=>{if(e){if(console.log(`[FlowEngageProvider] visitor:navigate`,{url:e,section:n,highlight:r}),!await cn(e,{siteId:t.siteId,apiBaseUrl:t.apiBaseUrl})){console.warn(`[FlowEngageProvider] visitor:navigate blocked (not indexed)`,e);return}un(e).then(e=>{let t=n||r;t&&setTimeout(()=>{let e=nn(null,t);e&&rn(e)},e?300:150)})}}),l.on(`visitor:highlight`,({sectionId:e,sectionText:t}={})=>{if(!e&&!t)return;console.log(`[FlowEngageProvider] visitor:highlight`,{sectionId:e,sectionText:t});let n=nn(e||null,t||null);n&&rn(n)}),l.on(`visitor:clear_highlight`,()=>{an()}),nt.current=Kt({socket:l,chatId:a}),console.log(`[FlowEngageProvider] tracking started`,{chatId:a});let m=await s.loadHistory(a,r);if(console.log(`[FlowEngageProvider] history loaded`,m),!e||(b(fn(m.chat_history||[])),le(!!m.is_human_handled),se(m.is_human_handled?`agent`:ie),await new Promise(e=>setTimeout(e,500)),!e))return;o(`ready`),console.log(`[FlowEngageProvider] status ready`)}catch(t){if(!e)return;console.error(`[FlowEngageProvider] boot failed`,t),c(t),o(`error`)}})(),()=>{e=!1,nt.current?.cleanup?.(),st(),E.current?.disconnect()}},[i,r]),(0,d.useEffect)(()=>()=>{if(Oe&&!tt.current&&et.current.length>0){let e=O.current,t=et.current,n=D.current;n&&e&&t.length>0&&(console.log(`[FlowEngageProvider] safety-net: syncing voice transcript on unmount`),n.beaconSyncVoice(e,t)||n.syncVoice(e,t).catch(()=>{}),tt.current=!0)}},[Oe,l]),(0,d.useEffect)(()=>{if(!D.current||!m||a!==`ready`)return;let e=window.setInterval(async()=>{try{let e=await D.current.checkHumanHandled(m);le(!!e.is_human_handled),e.is_human_handled&&(se(`agent`),e.agent_info?.name&&de(gn([e.agent_info.name],`Agent`)),e.agent_info?.headshot&&pe(e.agent_info.headshot)),rt(e)}catch{}},1e4);return()=>window.clearInterval(e)},[m,a,rt]);let ft=async()=>{if(!(!w?.callId||!D.current||!E.current||!m)){at(),Ye.current=w.callId,console.log(`[FlowEngageProvider] acceptCall started`,{callId:w?.callId,chatId:m,socketConnected:!!E.current?.connected,hasPendingOffer:!!Ke.current});try{let e=await navigator.mediaDevices.getUserMedia({audio:!0});console.log(`[FlowEngageProvider] microphone stream acquired`,{callId:w.callId,chatId:m,trackCount:e.getTracks().length}),We.current=e;let t=[{urls:`stun:stun.l.google.com:19302`}];try{let e=await D.current.getIceServersConfig();e?.data?.iceServers?.length&&(t=e.data.iceServers)}catch(e){console.warn(`[FlowEngageProvider] ice-config fetch failed, using STUN default`,e)}let n=new RTCPeerConnection({iceServers:t});Ue.current=n,console.log(`[FlowEngageCall] peer-connection:created`,{callId:w.callId,chatId:m,iceServers:1}),n.onconnectionstatechange=()=>{let e=n.connectionState;if(console.log(`[FlowEngageProvider] peer connection state changed`,{callId:w.callId,chatId:m,connectionState:e,iceConnectionState:n.iceConnectionState,signalingState:n.signalingState}),e===`connected`){let e=new Date().toISOString();Fe(`connected`),Le(t=>t||e),ct(e);return}if(e===`connecting`){Fe(e=>e===`connected`?e:`connecting`);return}(e===`failed`||e===`disconnected`||e===`closed`)&&console.warn(`[FlowEngageCall] peer-connection:terminal-state`,{callId:w.callId,chatId:m,connectionState:e,iceConnectionState:n.iceConnectionState,signalingState:n.signalingState})},n.oniceconnectionstatechange=()=>{let e=n.iceConnectionState;if(console.log(`[FlowEngageProvider] ICE connection state changed`,{callId:w.callId,chatId:m,iceConnectionState:e,connectionState:n.connectionState,signalingState:n.signalingState}),e===`connected`||e===`completed`){let e=new Date().toISOString();Fe(`connected`),Le(t=>t||e),ct(e);return}if(e===`checking`||e===`new`){Fe(e=>e===`connected`?e:`connecting`);return}(e===`failed`||e===`disconnected`||e===`closed`)&&console.warn(`[FlowEngageCall] ice-connection:terminal-state`,{callId:w.callId,chatId:m,iceConnectionState:e,connectionState:n.connectionState,signalingState:n.signalingState})},n.onsignalingstatechange=()=>{console.log(`[FlowEngageCall] signaling-state:changed`,{callId:w.callId,chatId:m,signalingState:n.signalingState,connectionState:n.connectionState,iceConnectionState:n.iceConnectionState})},n.onicegatheringstatechange=()=>{console.log(`[FlowEngageCall] ice-gathering-state:changed`,{callId:w.callId,chatId:m,iceGatheringState:n.iceGatheringState})},e.getTracks().forEach(t=>{console.log(`[FlowEngageCall] local-track:added`,{callId:w.callId,chatId:m,kind:t.kind,enabled:t.enabled,readyState:t.readyState,muted:t.muted,label:t.label}),n.addTrack(t,e)}),n.onicecandidate=e=>{if(!e.candidate||!E.current?.connected){console.log(`[FlowEngageProvider] local ICE candidate skipped`,{callId:w.callId,chatId:m,hasCandidate:!!e.candidate,socketConnected:!!E.current?.connected});return}let t=e.candidate;console.log(`[FlowEngageProvider] emitting local ICE candidate`,{callId:w.callId,chatId:m,candidate:hn(t)}),E.current.emit(`call:ice-candidate`,{callId:w.callId,candidate:t.candidate,sdpMid:t.sdpMid,sdpMLineIndex:t.sdpMLineIndex,chatId:m,from:`customer`})},n.ontrack=e=>{console.log(`[FlowEngageProvider] remote audio track received`,{callId:w.callId,chatId:m,streamCount:e.streams?.length||0});let[t]=e.streams||[],[n]=t?.getAudioTracks?.()||[];if(console.log(`[FlowEngageCall] remote-track:details`,{callId:w.callId,chatId:m,trackKind:e.track?.kind||null,trackEnabled:e.track?.enabled??null,trackMuted:e.track?.muted??null,trackReadyState:e.track?.readyState??null,streamId:t?.id||null,audioTrackCount:t?.getAudioTracks?.().length||0,firstAudioTrackState:n?{enabled:n.enabled,muted:n.muted,readyState:n.readyState,label:n.label}:null}),!Ge.current){let e=document.createElement(`audio`);e.id=`flowengage-remote-audio`,e.autoplay=!0,e.playsInline=!0,e.onplay=()=>{console.log(`[FlowEngageCall] remote-audio:onplay`,{callId:w.callId,chatId:m})},e.onpause=()=>{console.warn(`[FlowEngageCall] remote-audio:onpause`,{callId:w.callId,chatId:m,currentTime:e.currentTime})},e.onended=()=>{console.warn(`[FlowEngageCall] remote-audio:onended`,{callId:w.callId,chatId:m,currentTime:e.currentTime})},e.onerror=t=>{console.error(`[FlowEngageCall] remote-audio:onerror`,{callId:w.callId,chatId:m,error:e.error?{code:e.error.code,message:e.error.message}:null,raw:t})},Ge.current=e,document.body.appendChild(e)}Ge.current.srcObject=e.streams[0];let r=w?.callId,i=r&&(Ye.current===r||Je.current===r);if(!Xe.current&&i){let e=new Date().toISOString();Fe(`connected`),Le(t=>t||e),Je.current=r,Ne(r),ct(e)}Ge.current.srcObject=t||null;let a=Ge.current.play?.();a?.catch&&a.catch(e=>{console.error(`[FlowEngageCall] remote-audio:play-failed`,{callId:w.callId,chatId:m,message:e?.message,name:e?.name,raw:e})})};let r=Ke.current;r&&(console.log(`[FlowEngageProvider] found pending remote offer during accept`,{callId:r.callId||w.callId,chatId:m}),await dt({...r,callId:r.callId||w.callId})),await D.current.acceptCall(w.callId,m),console.log(`[FlowEngageProvider] acceptCall API succeeded`,{callId:w.callId,chatId:m}),Je.current=w.callId,Ne(w.callId),Fe(e=>e===`connected`||Xe.current?`connected`:`connecting`),T(null),re(!0)}catch(e){if(console.error(`[FlowEngageProvider] acceptCall failed`,e),Ye.current=null,st(`accept_call_failed`),e?.status===404||e?.status===409||e?.status===422){Ve(pn(e,`This visitor call is no longer available.`));return}if(e?.name===`NotAllowedError`||e?.name===`PermissionDeniedError`){try{await D.current.rejectCall(w.callId,m)}catch(e){console.error(`[FlowEngageProvider] failed to reject call after microphone denial`,e)}Ve(`Microphone access was denied. Please allow microphone access to accept the call.`);return}Ve(`We couldn't connect the call right now. Please try again.`)}}},pt=async()=>{if(!w?.callId||!D.current||!m){st(`reject_call_without_server_context`);return}at();try{await D.current.rejectCall(w.callId,m)}catch(e){console.error(`[FlowEngageProvider] rejectCall failed`,e),Ve(pn(e,`We couldn't decline the call cleanly.`))}finally{st(`reject_call_finally`)}},mt=(0,d.useRef)(pt);mt.current=pt,(0,d.useEffect)(()=>{if(!w?.callId||Me)return;let e=w.callId,t=window.setTimeout(()=>{He.current?.callId===e&&mt.current()},y);return()=>window.clearTimeout(t)},[w?.callId,Me]);let ht=async()=>{if(!Me||!D.current||!m){st(`end_call_without_server_context`);return}at();try{await D.current.endWebRTCCall(Me,m)}catch(e){console.error(`[FlowEngageProvider] endWebRTCCall failed`,e),Ve(pn(e,`The call ended locally, but the server could not be updated.`))}finally{st(`end_call_finally`)}},gt=()=>{let e=We.current?.getAudioTracks?.()||[],t=Ue.current?.getSenders?.().map(e=>e.track).filter(e=>e?.kind===`audio`)||[],n=[...e,...t].filter(Boolean);if(n.length===0){console.warn(`[FlowEngageProvider] no local audio tracks available for mute`);return}let r=!Re;n.forEach(e=>{e.enabled=!r}),console.log(`[FlowEngageProvider] toggled local mute`,{nextMuted:r,trackCount:n.length}),ze(r)},_t=async(e={})=>{let t=e.notifyChatInitiated===!0;if(re(!0),!(!t||!D.current||!m||typeof window>`u`)){try{await D.current.trackVisitor({chatId:m,currentPagePath:window.location.pathname||`/`})}catch{}try{await D.current.updateChatStatus(m,`open`)}catch{}}},vt=async e=>{let t=ot(e);if(!t||!D.current||!O.current)return t;try{await D.current.trackVisitor({chatId:O.current,currentPagePath:typeof window<`u`&&window.location.pathname||`/`,email:t})}catch(e){console.error(`[FlowEngageProvider] failed to persist visitor email`,e)}return t},yt=()=>{if(!m||!E.current?.connected||Ze.current){console.log(`[FlowEngageProvider] skipped typing:start emit`,{chatId:m,socketConnected:!!E.current?.connected,alreadyTyping:Ze.current});return}Ze.current=!0,console.log(`[FlowEngageProvider] emitting typing:start`,{chatId:m,sender:`user`}),E.current.emit(`typing:start`,{chatId:m,sender:`user`})},bt=()=>{if(!m||!E.current?.connected||!Ze.current){console.log(`[FlowEngageProvider] skipped typing:stop emit`,{chatId:m,socketConnected:!!E.current?.connected,wasTyping:Ze.current});return}Ze.current=!1,console.log(`[FlowEngageProvider] emitting typing:stop`,{chatId:m,sender:`user`}),E.current.emit(`typing:stop`,{chatId:m,sender:`user`})},xt=(e=``)=>{let t=typeof e==`string`?e:``;if(!m||!E.current?.connected){console.log(`[FlowEngageProvider] skipped typing:update emit`,{chatId:m,socketConnected:!!E.current?.connected,textLength:t.length});return}Qe.current!==t&&(Qe.current=t,console.log(`[FlowEngageProvider] emitting typing:update`,{chatId:m,sender:`user`,textLength:t.length}),E.current.emit(`typing:update`,{chatId:m,sender:`user`,text:t}))},St=async(e,t=``,n=null)=>{if(!(typeof e==`string`&&e.trim())||!D.current||!m||a!==`ready`||Ae)return;bt();let i=`pending-user-${Date.now()}`,o={id:i,sender:`user`,message:e,timestamp:new Date().toISOString(),isPending:!0,...n||{}};b(e=>[...e,o]);let s=ce;if(s)try{s=rt(await D.current.checkHumanHandled(m))}catch{}if(s&&E.current?.connected){E.current.emit(`customer:message`,{chatId:m,content:e,sender:`user`,email:me||void 0,...n||{}});return}Ce(!0);try{let i=await D.current.sendAiMessage(m,e,r,t,{...n||{},...me?{email:me}:{}});b(fn(i.chat_history||[])),le(!!i.is_human_handled),se(i.is_human_handled?`agent`:`ai`),ye(!1),await D.current.updateChatStatus(m,`messageSent`)}catch(e){b(e=>e.filter(e=>e.id!==i)),ye(!1),e.status===429?(Te(!0),De(e.message),window.setTimeout(()=>{Te(!1),De(``)},_)):c(e)}finally{Ce(!1)}},Ct=async e=>{if(!(!D.current||!m)){try{let t=e?`voice`:`text`;await D.current.setChatMode(m,t)}catch(e){console.error(`[FlowEngageProvider] setVoiceMode failed`,e)}ke(e),e&&(tt.current=!1)}},wt=async e=>{if(tt.current)return;if(tt.current=!0,!D.current||!m||!e?.length){ke(!1);return}let t=()=>{let t=fn(e);b(e=>{if(!e.length)return t;let n=e[e.length-1],r=t[0];return n&&r&&n.sender===r.sender&&n.message===r.message?e:[...e,...t]})};try{let n=await D.current.syncVoice(m,e);if(n?.chat_history?.length)b(fn(n.chat_history));else if(n?.success)try{let e=await D.current.loadHistory(m,r);e?.chat_history?.length?b(fn(e.chat_history)):t()}catch{t()}else t()}catch{t()}finally{ke(!1)}},Tt=async()=>{if(!(!D.current||!m)){Oe&&!tt.current&&et.current.length>0&&await wt(et.current);try{await D.current.endConversation(m)}catch{try{await D.current.updateChatStatus(m,`ended`)}catch{}}je(!0),b(e=>[...e,{id:`conversation-ended-${Date.now()}`,sender:`system`,message:`This conversation has ended. Thank you for reaching out!`,timestamp:new Date().toISOString(),isPending:!1}])}};(0,d.useEffect)(()=>{if(Pe!==`connected`||!Me||!m||!Ie||!it)return;let e=new Date(Ie).getTime(),t=Number.isFinite(e)?Date.now()-e:0,n=Math.max(0,it*1e3-t),r=window.setTimeout(()=>{Ve(`The call ended because it reached the time limit.`),ht()},n);return()=>window.clearTimeout(r)},[Me,Ie,Pe,m,ht,it]),(0,d.useEffect)(()=>{let e=()=>{let e=O.current,t=D.current;if(!t||!e)return;if(Je.current){t.beaconEndWebRTCCall(Je.current,e);return}let n=Ye.current||He.current?.callId;n&&t.beaconCustomerUnavailable(n,e)};return window.addEventListener(`pagehide`,e),window.addEventListener(`beforeunload`,e),()=>{window.removeEventListener(`pagehide`,e),window.removeEventListener(`beforeunload`,e)}},[]);let Et=(0,d.useMemo)(()=>({status:a,error:s,runtimeConfig:l,resolvedConfig:i,chatId:m,chatHistory:g,isOpen:x,activeScreen:ie,isHumanHandled:ce,agentName:ue,agentHeadshot:fe,visitorEmail:me,isAgentTyping:ge,isAiTyping:ve,connectionStatus:be,isLoading:Se,isVoiceMode:Oe,isRateLimited:we,rateLimitMessage:Ee,isConversationEnded:Ae,incomingCall:w,activeCallId:Me,callConnectionState:Pe,callConnectedAt:Ie,isCallMuted:Re,webRTCError:Be,language:r,historyRef:et,hasSyncedRef:tt,dismissCallError:at,captureVisitorEmail:vt,startTyping:yt,stopTyping:bt,updateTypingDraft:xt,notifyRouteChange:()=>nt.current?.notifyRouteChange?.(),openWidget:_t,closeWidget:()=>re(!1),toggleWidget:()=>{if(x){re(!1);return}_t({notifyChatInitiated:!0})},sendMessage:St,setVoiceMode:Ct,onMessageSync:wt,endConversation:Tt,acceptCall:ft,rejectCall:pt,endWebRTCCall:ht,toggleCallMute:gt}),[a,s,l,i,m,g,x,ie,ce,ue,fe,me,ge,ve,be,Se,Oe,we,Ee,Ae,w,Me,Pe,Ie,Re,Be,r,vt,yt,bt,xt,ft,pt,ht,gt,_t,St,Ct,wt,Tt,at]);return(0,f.jsx)(qt.Provider,{value:Et,children:n})}var yn=(0,d.createContext)({});function bn(e){let t=(0,d.useRef)(null);return t.current===null&&(t.current=e()),t.current}var xn=typeof window<`u`?d.useLayoutEffect:d.useEffect,Sn=(0,d.createContext)(null);function Cn(e,t){e.indexOf(t)===-1&&e.push(t)}function wn(e,t){let n=e.indexOf(t);n>-1&&e.splice(n,1)}var Tn=(e,t,n)=>n>t?t:n<e?e:n;function En(e,t){return t?`${e}. For more information and steps for solving, visit https://motion.dev/troubleshooting/${t}`:e}var Dn=()=>{},On=()=>{};typeof process<`u`&&process.env.NODE_ENV!==`production`&&(Dn=(e,t,n)=>{!e&&typeof console<`u`&&console.warn(En(t,n))},On=(e,t,n)=>{if(!e)throw Error(En(t,n))});var kn={},An=e=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(e);function jn(e){return typeof e==`object`&&!!e}var Mn=e=>/^0[^.\s]+$/u.test(e);function Nn(e){let t;return()=>(t===void 0&&(t=e()),t)}var Pn=e=>e,Fn=(e,t)=>n=>t(e(n)),In=(...e)=>e.reduce(Fn),Ln=(e,t,n)=>{let r=t-e;return r===0?1:(n-e)/r},Rn=class{constructor(){this.subscriptions=[]}add(e){return Cn(this.subscriptions,e),()=>wn(this.subscriptions,e)}notify(e,t,n){let r=this.subscriptions.length;if(r)if(r===1)this.subscriptions[0](e,t,n);else for(let i=0;i<r;i++){let r=this.subscriptions[i];r&&r(e,t,n)}}getSize(){return this.subscriptions.length}clear(){this.subscriptions.length=0}},zn=e=>e*1e3,Bn=e=>e/1e3;function Vn(e,t){return t?1e3/t*e:0}var Hn=new Set;function Un(e,t,n){e||Hn.has(t)||(console.warn(En(t,n)),Hn.add(t))}var Wn=(e,t,n)=>(((1-3*n+3*t)*e+(3*n-6*t))*e+3*t)*e,Gn=1e-7,Kn=12;function qn(e,t,n,r,i){let a,o,s=0;do o=t+(n-t)/2,a=Wn(o,r,i)-e,a>0?n=o:t=o;while(Math.abs(a)>Gn&&++s<Kn);return o}function Jn(e,t,n,r){if(e===t&&n===r)return Pn;let i=t=>qn(t,0,1,e,n);return e=>e===0||e===1?e:Wn(i(e),t,r)}var Yn=e=>t=>t<=.5?e(2*t)/2:(2-e(2*(1-t)))/2,Xn=e=>t=>1-e(1-t),Zn=Jn(.33,1.53,.69,.99),Qn=Xn(Zn),$n=Yn(Qn),er=e=>e>=1?1:(e*=2)<1?.5*Qn(e):.5*(2-2**(-10*(e-1))),tr=e=>1-Math.sin(Math.acos(e)),nr=Xn(tr),rr=Yn(tr),ir=Jn(.42,0,1,1),ar=Jn(0,0,.58,1),or=Jn(.42,0,.58,1),sr=e=>Array.isArray(e)&&typeof e[0]!=`number`,cr=e=>Array.isArray(e)&&typeof e[0]==`number`,lr={linear:Pn,easeIn:ir,easeInOut:or,easeOut:ar,circIn:tr,circInOut:rr,circOut:nr,backIn:Qn,backInOut:$n,backOut:Zn,anticipate:er},ur=e=>typeof e==`string`,dr=e=>{if(cr(e)){On(e.length===4,`Cubic bezier arrays must contain four numerical values.`,`cubic-bezier-length`);let[t,n,r,i]=e;return Jn(t,n,r,i)}else if(ur(e))return On(lr[e]!==void 0,`Invalid easing type '${e}'`,`invalid-easing-type`),lr[e];return e},fr=[`setup`,`read`,`resolveKeyframes`,`preUpdate`,`update`,`preRender`,`render`,`postRender`],pr={value:null,addProjectionMetrics:null};function mr(e,t){let n=new Set,r=new Set,i=!1,a=!1,o=new WeakSet,s={delta:0,timestamp:0,isProcessing:!1},c=0;function l(t){o.has(t)&&(u.schedule(t),e()),c++,t(s)}let u={schedule:(e,t=!1,a=!1)=>{let s=a&&i?n:r;return t&&o.add(e),s.add(e),e},cancel:e=>{r.delete(e),o.delete(e)},process:e=>{if(s=e,i){a=!0;return}i=!0;let o=n;n=r,r=o,n.forEach(l),t&&pr.value&&pr.value.frameloop[t].push(c),c=0,n.clear(),i=!1,a&&(a=!1,u.process(e))}};return u}var hr=40;function gr(e,t){let n=!1,r=!0,i={delta:0,timestamp:0,isProcessing:!1},a=()=>n=!0,o=fr.reduce((e,n)=>(e[n]=mr(a,t?n:void 0),e),{}),{setup:s,read:c,resolveKeyframes:l,preUpdate:u,update:d,preRender:f,render:p,postRender:m}=o,h=()=>{let a=kn.useManualTiming,o=a?i.timestamp:performance.now();n=!1,a||(i.delta=r?1e3/60:Math.max(Math.min(o-i.timestamp,hr),1)),i.timestamp=o,i.isProcessing=!0,s.process(i),c.process(i),l.process(i),u.process(i),d.process(i),f.process(i),p.process(i),m.process(i),i.isProcessing=!1,n&&t&&(r=!1,e(h))},g=()=>{n=!0,r=!0,i.isProcessing||e(h)};return{schedule:fr.reduce((e,t)=>{let r=o[t];return e[t]=(e,t=!1,i=!1)=>(n||g(),r.schedule(e,t,i)),e},{}),cancel:e=>{for(let t=0;t<fr.length;t++)o[fr[t]].cancel(e)},state:i,steps:o}}var{schedule:A,cancel:_r,state:vr,steps:yr}=gr(typeof requestAnimationFrame<`u`?requestAnimationFrame:Pn,!0),br;function xr(){br=void 0}var Sr={now:()=>(br===void 0&&Sr.set(vr.isProcessing||kn.useManualTiming?vr.timestamp:performance.now()),br),set:e=>{br=e,queueMicrotask(xr)}},Cr={layout:0,mainThread:0,waapi:0},wr=e=>t=>typeof t==`string`&&t.startsWith(e),Tr=wr(`--`),Er=wr(`var(--`),Dr=e=>Er(e)?Or.test(e.split(`/*`)[0].trim()):!1,Or=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu;function kr(e){return typeof e==`string`?e.split(`/*`)[0].includes(`var(--`):!1}var Ar={test:e=>typeof e==`number`,parse:parseFloat,transform:e=>e},jr={...Ar,transform:e=>Tn(0,1,e)},Mr={...Ar,default:1},Nr=e=>Math.round(e*1e5)/1e5,Pr=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function Fr(e){return e==null}var Ir=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,Lr=(e,t)=>n=>!!(typeof n==`string`&&Ir.test(n)&&n.startsWith(e)||t&&!Fr(n)&&Object.prototype.hasOwnProperty.call(n,t)),Rr=(e,t,n)=>r=>{if(typeof r!=`string`)return r;let[i,a,o,s]=r.match(Pr);return{[e]:parseFloat(i),[t]:parseFloat(a),[n]:parseFloat(o),alpha:s===void 0?1:parseFloat(s)}},zr=e=>Tn(0,255,e),Br={...Ar,transform:e=>Math.round(zr(e))},Vr={test:Lr(`rgb`,`red`),parse:Rr(`red`,`green`,`blue`),transform:({red:e,green:t,blue:n,alpha:r=1})=>`rgba(`+Br.transform(e)+`, `+Br.transform(t)+`, `+Br.transform(n)+`, `+Nr(jr.transform(r))+`)`};function Hr(e){let t=``,n=``,r=``,i=``;return e.length>5?(t=e.substring(1,3),n=e.substring(3,5),r=e.substring(5,7),i=e.substring(7,9)):(t=e.substring(1,2),n=e.substring(2,3),r=e.substring(3,4),i=e.substring(4,5),t+=t,n+=n,r+=r,i+=i),{red:parseInt(t,16),green:parseInt(n,16),blue:parseInt(r,16),alpha:i?parseInt(i,16)/255:1}}var Ur={test:Lr(`#`),parse:Hr,transform:Vr.transform},Wr=e=>({test:t=>typeof t==`string`&&t.endsWith(e)&&t.split(` `).length===1,parse:parseFloat,transform:t=>`${t}${e}`}),Gr=Wr(`deg`),Kr=Wr(`%`),j=Wr(`px`),qr=Wr(`vh`),Jr=Wr(`vw`),Yr={...Kr,parse:e=>Kr.parse(e)/100,transform:e=>Kr.transform(e*100)},Xr={test:Lr(`hsl`,`hue`),parse:Rr(`hue`,`saturation`,`lightness`),transform:({hue:e,saturation:t,lightness:n,alpha:r=1})=>`hsla(`+Math.round(e)+`, `+Kr.transform(Nr(t))+`, `+Kr.transform(Nr(n))+`, `+Nr(jr.transform(r))+`)`},Zr={test:e=>Vr.test(e)||Ur.test(e)||Xr.test(e),parse:e=>Vr.test(e)?Vr.parse(e):Xr.test(e)?Xr.parse(e):Ur.parse(e),transform:e=>typeof e==`string`?e:e.hasOwnProperty(`red`)?Vr.transform(e):Xr.transform(e),getAnimatableNone:e=>{let t=Zr.parse(e);return t.alpha=0,Zr.transform(t)}},Qr=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function $r(e){return isNaN(e)&&typeof e==`string`&&(e.match(Pr)?.length||0)+(e.match(Qr)?.length||0)>0}var ei=`number`,ti=`color`,ni=`var`,ri=`var(`,ii="${}",ai=/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 oi(e){let t=e.toString(),n=[],r={color:[],number:[],var:[]},i=[],a=0;return{values:n,split:t.replace(ai,e=>(Zr.test(e)?(r.color.push(a),i.push(ti),n.push(Zr.parse(e))):e.startsWith(ri)?(r.var.push(a),i.push(ni),n.push(e)):(r.number.push(a),i.push(ei),n.push(parseFloat(e))),++a,ii)).split(ii),indexes:r,types:i}}function si(e){return oi(e).values}function ci({split:e,types:t}){let n=e.length;return r=>{let i=``;for(let a=0;a<n;a++)if(i+=e[a],r[a]!==void 0){let e=t[a];e===ei?i+=Nr(r[a]):e===ti?i+=Zr.transform(r[a]):i+=r[a]}return i}}function li(e){return ci(oi(e))}var ui=e=>typeof e==`number`?0:Zr.test(e)?Zr.getAnimatableNone(e):e,di=(e,t)=>typeof e==`number`?t?.trim().endsWith(`/`)?e:0:ui(e);function fi(e){let t=oi(e);return ci(t)(t.values.map((e,n)=>di(e,t.split[n])))}var pi={test:$r,parse:si,createTransformer:li,getAnimatableNone:fi};function mi(e,t,n){return n<0&&(n+=1),n>1&&--n,n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*(2/3-n)*6:e}function hi({hue:e,saturation:t,lightness:n,alpha:r}){e/=360,t/=100,n/=100;let i=0,a=0,o=0;if(!t)i=a=o=n;else{let r=n<.5?n*(1+t):n+t-n*t,s=2*n-r;i=mi(s,r,e+1/3),a=mi(s,r,e),o=mi(s,r,e-1/3)}return{red:Math.round(i*255),green:Math.round(a*255),blue:Math.round(o*255),alpha:r}}function gi(e,t){return n=>n>0?t:e}var M=(e,t,n)=>e+(t-e)*n,_i=(e,t,n)=>{let r=e*e,i=n*(t*t-r)+r;return i<0?0:Math.sqrt(i)},vi=[Ur,Vr,Xr],yi=e=>vi.find(t=>t.test(e));function bi(e){let t=yi(e);if(Dn(!!t,`'${e}' is not an animatable color. Use the equivalent color code instead.`,`color-not-animatable`),!t)return!1;let n=t.parse(e);return t===Xr&&(n=hi(n)),n}var xi=(e,t)=>{let n=bi(e),r=bi(t);if(!n||!r)return gi(e,t);let i={...n};return e=>(i.red=_i(n.red,r.red,e),i.green=_i(n.green,r.green,e),i.blue=_i(n.blue,r.blue,e),i.alpha=M(n.alpha,r.alpha,e),Vr.transform(i))},Si=new Set([`none`,`hidden`]);function Ci(e,t){return Si.has(e)?n=>n<=0?e:t:n=>n>=1?t:e}function wi(e,t){return n=>M(e,t,n)}function Ti(e){return typeof e==`number`?wi:typeof e==`string`?Dr(e)?gi:Zr.test(e)?xi:ki:Array.isArray(e)?Ei:typeof e==`object`?Zr.test(e)?xi:Di:gi}function Ei(e,t){let n=[...e],r=n.length,i=e.map((e,n)=>Ti(e)(e,t[n]));return e=>{for(let t=0;t<r;t++)n[t]=i[t](e);return n}}function Di(e,t){let n={...e,...t},r={};for(let i in n)e[i]!==void 0&&t[i]!==void 0&&(r[i]=Ti(e[i])(e[i],t[i]));return e=>{for(let t in r)n[t]=r[t](e);return n}}function Oi(e,t){let n=[],r={color:0,var:0,number:0};for(let i=0;i<t.values.length;i++){let a=t.types[i],o=e.indexes[a][r[a]];n[i]=e.values[o]??0,r[a]++}return n}var ki=(e,t)=>{let n=pi.createTransformer(t),r=oi(e),i=oi(t);return r.indexes.var.length===i.indexes.var.length&&r.indexes.color.length===i.indexes.color.length&&r.indexes.number.length>=i.indexes.number.length?Si.has(e)&&!i.values.length||Si.has(t)&&!r.values.length?Ci(e,t):In(Ei(Oi(r,i),i.values),n):(Dn(!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.`,`complex-values-different`),gi(e,t))};function Ai(e,t,n){return typeof e==`number`&&typeof t==`number`&&typeof n==`number`?M(e,t,n):Ti(e)(e,t)}var ji=e=>{let t=({timestamp:t})=>e(t);return{start:(e=!0)=>A.update(t,e),stop:()=>_r(t),now:()=>vr.isProcessing?vr.timestamp:Sr.now()}},Mi=(e,t,n=10)=>{let r=``,i=Math.max(Math.round(t/n),2);for(let t=0;t<i;t++)r+=Math.round(e(t/(i-1))*1e4)/1e4+`, `;return`linear(${r.substring(0,r.length-2)})`},Ni=2e4;function Pi(e){let t=0,n=e.next(t);for(;!n.done&&t<2e4;)t+=50,n=e.next(t);return t>=2e4?1/0:t}function Fi(e,t=100,n){let r=n({...e,keyframes:[0,t]}),i=Math.min(Pi(r),Ni);return{type:`keyframes`,ease:e=>r.next(i*e).value/t,duration:Bn(i)}}var Ii={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 Li(e,t){return e*Math.sqrt(1-t*t)}var Ri=12;function zi(e,t,n){let r=n;for(let n=1;n<Ri;n++)r-=e(r)/t(r);return r}var Bi=.001;function Vi({duration:e=Ii.duration,bounce:t=Ii.bounce,velocity:n=Ii.velocity,mass:r=Ii.mass}){let i,a;Dn(e<=zn(Ii.maxDuration),`Spring duration must be 10 seconds or less`,`spring-duration-limit`);let o=1-t;o=Tn(Ii.minDamping,Ii.maxDamping,o),e=Tn(Ii.minDuration,Ii.maxDuration,Bn(e)),o<1?(i=t=>{let r=t*o,i=r*e,a=r-n,s=Li(t,o),c=Math.exp(-i);return Bi-a/s*c},a=t=>{let r=t*o*e,a=r*n+n,s=o**2*t**2*e,c=Math.exp(-r),l=Li(t**2,o);return(-i(t)+Bi>0?-1:1)*((a-s)*c)/l}):(i=t=>{let r=Math.exp(-t*e),i=(t-n)*e+1;return-Bi+r*i},a=t=>Math.exp(-t*e)*((n-t)*(e*e)));let s=5/e,c=zi(i,a,s);if(e=zn(e),isNaN(c))return{stiffness:Ii.stiffness,damping:Ii.damping,duration:e};{let t=c**2*r;return{stiffness:t,damping:o*2*Math.sqrt(r*t),duration:e}}}var Hi=[`duration`,`bounce`],Ui=[`stiffness`,`damping`,`mass`];function Wi(e,t){return t.some(t=>e[t]!==void 0)}function Gi(e){let t={velocity:Ii.velocity,stiffness:Ii.stiffness,damping:Ii.damping,mass:Ii.mass,isResolvedFromDuration:!1,...e};if(!Wi(e,Ui)&&Wi(e,Hi))if(t.velocity=0,e.visualDuration){let n=e.visualDuration,r=2*Math.PI/(n*1.2),i=r*r,a=2*Tn(.05,1,1-(e.bounce||0))*Math.sqrt(i);t={...t,mass:Ii.mass,stiffness:i,damping:a}}else{let n=Vi({...e,velocity:0});t={...t,...n,mass:Ii.mass},t.isResolvedFromDuration=!0}return t}function Ki(e=Ii.visualDuration,t=Ii.bounce){let n=typeof e==`object`?e:{visualDuration:e,keyframes:[0,1],bounce:t},{restSpeed:r,restDelta:i}=n,a=n.keyframes[0],o=n.keyframes[n.keyframes.length-1],s={done:!1,value:a},{stiffness:c,damping:l,mass:u,duration:d,velocity:f,isResolvedFromDuration:p}=Gi({...n,velocity:-Bn(n.velocity||0)}),m=f||0,h=l/(2*Math.sqrt(c*u)),g=o-a,_=Bn(Math.sqrt(c/u)),v=Math.abs(g)<5;r||=v?Ii.restSpeed.granular:Ii.restSpeed.default,i||=v?Ii.restDelta.granular:Ii.restDelta.default;let y,b,x,S,ee,te;if(h<1)x=Li(_,h),S=(m+h*_*g)/x,y=e=>o-Math.exp(-h*_*e)*(S*Math.sin(x*e)+g*Math.cos(x*e)),ee=h*_*S+g*x,te=h*_*g-S*x,b=e=>Math.exp(-h*_*e)*(ee*Math.sin(x*e)+te*Math.cos(x*e));else if(h===1){y=e=>o-Math.exp(-_*e)*(g+(m+_*g)*e);let e=m+_*g;b=t=>Math.exp(-_*t)*(_*e*t-m)}else{let e=_*Math.sqrt(h*h-1);y=t=>{let n=Math.exp(-h*_*t),r=Math.min(e*t,300);return o-n*((m+h*_*g)*Math.sinh(r)+e*g*Math.cosh(r))/e};let t=(m+h*_*g)/e,n=h*_*t-g*e,r=h*_*g-t*e;b=t=>{let i=Math.exp(-h*_*t),a=Math.min(e*t,300);return i*(n*Math.sinh(a)+r*Math.cosh(a))}}let C={calculatedDuration:p&&d||null,velocity:e=>zn(b(e)),next:e=>{if(!p&&h<1){let t=Math.exp(-h*_*e),n=Math.sin(x*e),a=Math.cos(x*e),c=o-t*(S*n+g*a),l=zn(t*(ee*n+te*a));return s.done=Math.abs(l)<=r&&Math.abs(o-c)<=i,s.value=s.done?o:c,s}let t=y(e);if(p)s.done=e>=d;else{let n=zn(b(e));s.done=Math.abs(n)<=r&&Math.abs(o-t)<=i}return s.value=s.done?o:t,s},toString:()=>{let e=Math.min(Pi(C),Ni),t=Mi(t=>C.next(e*t).value,e,30);return e+`ms `+t},toTransition:()=>{}};return C}Ki.applyToOptions=e=>{let t=Fi(e,100,Ki);return e.ease=t.ease,e.duration=zn(t.duration),e.type=`keyframes`,e};var qi=5;function Ji(e,t,n){let r=Math.max(t-qi,0);return Vn(n-e(r),t-r)}function Yi({keyframes:e,velocity:t=0,power:n=.8,timeConstant:r=325,bounceDamping:i=10,bounceStiffness:a=500,modifyTarget:o,min:s,max:c,restDelta:l=.5,restSpeed:u}){let d=e[0],f={done:!1,value:d},p=e=>s!==void 0&&e<s||c!==void 0&&e>c,m=e=>s===void 0?c:c===void 0||Math.abs(s-e)<Math.abs(c-e)?s:c,h=n*t,g=d+h,_=o===void 0?g:o(g);_!==g&&(h=_-d);let v=e=>-h*Math.exp(-e/r),y=e=>_+v(e),b=e=>{let t=v(e),n=y(e);f.done=Math.abs(t)<=l,f.value=f.done?_:n},x,S,ee=e=>{p(f.value)&&(x=e,S=Ki({keyframes:[f.value,m(f.value)],velocity:Ji(y,e,f.value),damping:i,stiffness:a,restDelta:l,restSpeed:u}))};return ee(0),{calculatedDuration:null,next:e=>{let t=!1;return!S&&x===void 0&&(t=!0,b(e),ee(e)),x!==void 0&&e>=x?S.next(e-x):(!t&&b(e),f)}}}function Xi(e,t,n){let r=[],i=n||kn.mix||Ai,a=e.length-1;for(let n=0;n<a;n++){let a=i(e[n],e[n+1]);t&&(a=In(Array.isArray(t)?t[n]||Pn:t,a)),r.push(a)}return r}function Zi(e,t,{clamp:n=!0,ease:r,mixer:i}={}){let a=e.length;if(On(a===t.length,`Both input and output ranges must be the same length`,`range-length`),a===1)return()=>t[0];if(a===2&&t[0]===t[1])return()=>t[1];let o=e[0]===e[1];e[0]>e[a-1]&&(e=[...e].reverse(),t=[...t].reverse());let s=Xi(t,r,i),c=s.length,l=n=>{if(o&&n<e[0])return t[0];let r=0;if(c>1)for(;r<e.length-2&&!(n<e[r+1]);r++);let i=Ln(e[r],e[r+1],n);return s[r](i)};return n?t=>l(Tn(e[0],e[a-1],t)):l}function Qi(e,t){let n=e[e.length-1];for(let r=1;r<=t;r++){let i=Ln(0,t,r);e.push(M(n,1,i))}}function $i(e){let t=[0];return Qi(t,e.length-1),t}function ea(e,t){return e.map(e=>e*t)}function ta(e,t){return e.map(()=>t||or).splice(0,e.length-1)}function na({duration:e=300,keyframes:t,times:n,ease:r=`easeInOut`}){let i=sr(r)?r.map(dr):dr(r),a={done:!1,value:t[0]},o=Zi(ea(n&&n.length===t.length?n:$i(t),e),t,{ease:Array.isArray(i)?i:ta(t,i)});return{calculatedDuration:e,next:t=>(a.value=o(t),a.done=t>=e,a)}}var ra=e=>e!==null;function ia(e,{repeat:t,repeatType:n=`loop`},r,i=1){let a=e.filter(ra),o=i<0||t&&n!==`loop`&&t%2==1?0:a.length-1;return!o||r===void 0?a[o]:r}var aa={decay:Yi,inertia:Yi,tween:na,keyframes:na,spring:Ki};function oa(e){typeof e.type==`string`&&(e.type=aa[e.type])}var sa=class{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(e=>{this.resolve=e})}notifyFinished(){this.resolve()}then(e,t){return this.finished.then(e,t)}},ca=e=>e/100,la=class extends sa{constructor(e){super(),this.state=`idle`,this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.delayState={done:!1,value:void 0},this.stop=()=>{let{motionValue:e}=this.options;e&&e.updatedAt!==Sr.now()&&this.tick(Sr.now()),this.isStopped=!0,this.state!==`idle`&&(this.teardown(),this.options.onStop?.())},Cr.mainThread++,this.options=e,this.initAnimation(),this.play(),e.autoplay===!1&&this.pause()}initAnimation(){let{options:e}=this;oa(e);let{type:t=na,repeat:n=0,repeatDelay:r=0,repeatType:i,velocity:a=0}=e,{keyframes:o}=e,s=t||na;process.env.NODE_ENV!==`production`&&s!==na&&On(o.length<=2,`Only two keyframes currently supported with spring and inertia animations. Trying to animate ${o}`,`spring-two-frames`),s!==na&&typeof o[0]!=`number`&&(this.mixKeyframes=In(ca,Ai(o[0],o[1])),o=[0,100]);let c=s({...e,keyframes:o});i===`mirror`&&(this.mirroredGenerator=s({...e,keyframes:[...o].reverse(),velocity:-a})),c.calculatedDuration===null&&(c.calculatedDuration=Pi(c));let{calculatedDuration:l}=c;this.calculatedDuration=l,this.resolvedDuration=l+r,this.totalDuration=this.resolvedDuration*(n+1)-r,this.generator=c}updateTime(e){let t=Math.round(e-this.startTime)*this.playbackSpeed;this.holdTime===null?this.currentTime=t:this.currentTime=this.holdTime}tick(e,t=!1){let{generator:n,totalDuration:r,mixKeyframes:i,mirroredGenerator:a,resolvedDuration:o,calculatedDuration:s}=this;if(this.startTime===null)return n.next(0);let{delay:c=0,keyframes:l,repeat:u,repeatType:d,repeatDelay:f,type:p,onUpdate:m,finalKeyframe:h}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,e):this.speed<0&&(this.startTime=Math.min(e-r/this.speed,this.startTime)),t?this.currentTime=e:this.updateTime(e);let g=this.currentTime-c*(this.playbackSpeed>=0?1:-1),_=this.playbackSpeed>=0?g<0:g>r;this.currentTime=Math.max(g,0),this.state===`finished`&&this.holdTime===null&&(this.currentTime=r);let v=this.currentTime,y=n;if(u){let e=Math.min(this.currentTime,r)/o,t=Math.floor(e),n=e%1;!n&&e>=1&&(n=1),n===1&&t--,t=Math.min(t,u+1),t%2&&(d===`reverse`?(n=1-n,f&&(n-=f/o)):d===`mirror`&&(y=a)),v=Tn(0,1,n)*o}let b;_?(this.delayState.value=l[0],b=this.delayState):b=y.next(v),i&&!_&&(b.value=i(b.value));let{done:x}=b;!_&&s!==null&&(x=this.playbackSpeed>=0?this.currentTime>=r:this.currentTime<=0);let S=this.holdTime===null&&(this.state===`finished`||this.state===`running`&&x);return S&&p!==Yi&&(b.value=ia(l,this.options,h,this.speed)),m&&m(b.value),S&&this.finish(),b}then(e,t){return this.finished.then(e,t)}get duration(){return Bn(this.calculatedDuration)}get iterationDuration(){let{delay:e=0}=this.options||{};return this.duration+Bn(e)}get time(){return Bn(this.currentTime)}set time(e){e=zn(e),this.currentTime=e,this.startTime===null||this.holdTime!==null||this.playbackSpeed===0?this.holdTime=e:this.driver&&(this.startTime=this.driver.now()-e/this.playbackSpeed),this.driver?this.driver.start(!1):(this.startTime=0,this.state=`paused`,this.holdTime=e,this.tick(e))}getGeneratorVelocity(){let e=this.currentTime;if(e<=0)return this.options.velocity||0;if(this.generator.velocity)return this.generator.velocity(e);let t=this.generator.next(e).value;return Ji(e=>this.generator.next(e).value,e,t)}get speed(){return this.playbackSpeed}set speed(e){let t=this.playbackSpeed!==e;t&&this.driver&&this.updateTime(Sr.now()),this.playbackSpeed=e,t&&this.driver&&(this.time=Bn(this.currentTime))}play(){if(this.isStopped)return;let{driver:e=ji,startTime:t}=this.options;this.driver||=e(e=>this.tick(e)),this.options.onPlay?.();let n=this.driver.now();this.state===`finished`?(this.updateFinished(),this.startTime=n):this.holdTime===null?this.startTime||=t??n:this.startTime=n-this.holdTime,this.state===`finished`&&this.speed<0&&(this.startTime+=this.calculatedDuration),this.holdTime=null,this.state=`running`,this.driver.start()}pause(){this.state=`paused`,this.updateTime(Sr.now()),this.holdTime=this.currentTime}complete(){this.state!==`running`&&this.play(),this.state=`finished`,this.holdTime=null}finish(){this.notifyFinished(),this.teardown(),this.state=`finished`,this.options.onComplete?.()}cancel(){this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),this.options.onCancel?.()}teardown(){this.state=`idle`,this.stopDriver(),this.startTime=this.holdTime=null,Cr.mainThread--}stopDriver(){this.driver&&=(this.driver.stop(),void 0)}sample(e){return this.startTime=0,this.tick(e,!0)}attachTimeline(e){return this.options.allowFlatten&&(this.options.type=`keyframes`,this.options.ease=`linear`,this.initAnimation()),this.driver?.stop(),e.observe(this)}};function ua(e){for(let t=1;t<e.length;t++)e[t]??(e[t]=e[t-1])}var da=e=>e*180/Math.PI,fa=e=>ma(da(Math.atan2(e[1],e[0]))),pa={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:e=>(Math.abs(e[0])+Math.abs(e[3]))/2,rotate:fa,rotateZ:fa,skewX:e=>da(Math.atan(e[1])),skewY:e=>da(Math.atan(e[2])),skew:e=>(Math.abs(e[1])+Math.abs(e[2]))/2},ma=e=>(e%=360,e<0&&(e+=360),e),ha=fa,ga=e=>Math.sqrt(e[0]*e[0]+e[1]*e[1]),_a=e=>Math.sqrt(e[4]*e[4]+e[5]*e[5]),va={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:ga,scaleY:_a,scale:e=>(ga(e)+_a(e))/2,rotateX:e=>ma(da(Math.atan2(e[6],e[5]))),rotateY:e=>ma(da(Math.atan2(-e[2],e[0]))),rotateZ:ha,rotate:ha,skewX:e=>da(Math.atan(e[4])),skewY:e=>da(Math.atan(e[1])),skew:e=>(Math.abs(e[1])+Math.abs(e[4]))/2};function ya(e){return e.includes(`scale`)?1:0}function ba(e,t){if(!e||e===`none`)return ya(t);let n=e.match(/^matrix3d\(([-\d.e\s,]+)\)$/u),r,i;if(n)r=va,i=n;else{let t=e.match(/^matrix\(([-\d.e\s,]+)\)$/u);r=pa,i=t}if(!i)return ya(t);let a=r[t],o=i[1].split(`,`).map(Sa);return typeof a==`function`?a(o):o[a]}var xa=(e,t)=>{let{transform:n=`none`}=getComputedStyle(e);return ba(n,t)};function Sa(e){return parseFloat(e.trim())}var Ca=[`transformPerspective`,`x`,`y`,`z`,`translateX`,`translateY`,`translateZ`,`scale`,`scaleX`,`scaleY`,`rotate`,`rotateX`,`rotateY`,`rotateZ`,`skew`,`skewX`,`skewY`],wa=new Set(Ca),Ta=e=>e===Ar||e===j,Ea=new Set([`x`,`y`,`z`]),Da=Ca.filter(e=>!Ea.has(e));function Oa(e){let t=[];return Da.forEach(n=>{let r=e.getValue(n);r!==void 0&&(t.push([n,r.get()]),r.set(n.startsWith(`scale`)?1:0))}),t}var ka={width:({x:e},{paddingLeft:t=`0`,paddingRight:n=`0`,boxSizing:r})=>{let i=e.max-e.min;return r===`border-box`?i:i-parseFloat(t)-parseFloat(n)},height:({y:e},{paddingTop:t=`0`,paddingBottom:n=`0`,boxSizing:r})=>{let i=e.max-e.min;return r===`border-box`?i:i-parseFloat(t)-parseFloat(n)},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:(e,{transform:t})=>ba(t,`x`),y:(e,{transform:t})=>ba(t,`y`)};ka.translateX=ka.x,ka.translateY=ka.y;var Aa=new Set,ja=!1,Ma=!1,Na=!1;function Pa(){if(Ma){let e=Array.from(Aa).filter(e=>e.needsMeasurement),t=new Set(e.map(e=>e.element)),n=new Map;t.forEach(e=>{let t=Oa(e);t.length&&(n.set(e,t),e.render())}),e.forEach(e=>e.measureInitialState()),t.forEach(e=>{e.render();let t=n.get(e);t&&t.forEach(([t,n])=>{e.getValue(t)?.set(n)})}),e.forEach(e=>e.measureEndState()),e.forEach(e=>{e.suspendedScrollY!==void 0&&window.scrollTo(0,e.suspendedScrollY)})}Ma=!1,ja=!1,Aa.forEach(e=>e.complete(Na)),Aa.clear()}function Fa(){Aa.forEach(e=>{e.readKeyframes(),e.needsMeasurement&&(Ma=!0)})}function Ia(){Na=!0,Fa(),Pa(),Na=!1}var La=class{constructor(e,t,n,r,i,a=!1){this.state=`pending`,this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...e],this.onComplete=t,this.name=n,this.motionValue=r,this.element=i,this.isAsync=a}scheduleResolve(){this.state=`scheduled`,this.isAsync?(Aa.add(this),ja||(ja=!0,A.read(Fa),A.resolveKeyframes(Pa))):(this.readKeyframes(),this.complete())}readKeyframes(){let{unresolvedKeyframes:e,name:t,element:n,motionValue:r}=this;if(e[0]===null){let i=r?.get(),a=e[e.length-1];if(i!==void 0)e[0]=i;else if(n&&t){let r=n.readValue(t,a);r!=null&&(e[0]=r)}e[0]===void 0&&(e[0]=a),r&&i===void 0&&r.set(e[0])}ua(e)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(e=!1){this.state=`complete`,this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,e),Aa.delete(this)}cancel(){this.state===`scheduled`&&(Aa.delete(this),this.state=`pending`)}resume(){this.state===`pending`&&this.scheduleResolve()}},Ra=e=>e.startsWith(`--`);function za(e,t,n){Ra(t)?e.style.setProperty(t,n):e.style[t]=n}var Ba={};function Va(e,t){let n=Nn(e);return()=>Ba[t]??n()}var Ha=Va(()=>window.ScrollTimeline!==void 0,`scrollTimeline`),Ua=Va(()=>{try{document.createElement(`div`).animate({opacity:0},{easing:`linear(0, 1)`})}catch{return!1}return!0},`linearEasing`),Wa=([e,t,n,r])=>`cubic-bezier(${e}, ${t}, ${n}, ${r})`,Ga={linear:`linear`,ease:`ease`,easeIn:`ease-in`,easeOut:`ease-out`,easeInOut:`ease-in-out`,circIn:Wa([0,.65,.55,1]),circOut:Wa([.55,0,1,.45]),backIn:Wa([.31,.01,.66,-.59]),backOut:Wa([.33,1.53,.69,.99])};function Ka(e,t){if(e)return typeof e==`function`?Ua()?Mi(e,t):`ease-out`:cr(e)?Wa(e):Array.isArray(e)?e.map(e=>Ka(e,t)||Ga.easeOut):Ga[e]}function qa(e,t,n,{delay:r=0,duration:i=300,repeat:a=0,repeatType:o=`loop`,ease:s=`easeOut`,times:c}={},l=void 0){let u={[t]:n};c&&(u.offset=c);let d=Ka(s,i);Array.isArray(d)&&(u.easing=d),pr.value&&Cr.waapi++;let f={delay:r,duration:i,easing:Array.isArray(d)?`linear`:d,fill:`both`,iterations:a+1,direction:o===`reverse`?`alternate`:`normal`};l&&(f.pseudoElement=l);let p=e.animate(u,f);return pr.value&&p.finished.finally(()=>{Cr.waapi--}),p}function Ja(e){return typeof e==`function`&&`applyToOptions`in e}function Ya({type:e,...t}){return Ja(e)&&Ua()?e.applyToOptions(t):(t.duration??=300,t.ease??=`easeOut`,t)}var Xa=class extends sa{constructor(e){if(super(),this.finishedTime=null,this.isStopped=!1,this.manualStartTime=null,!e)return;let{element:t,name:n,keyframes:r,pseudoElement:i,allowFlatten:a=!1,finalKeyframe:o,onComplete:s}=e;this.isPseudoElement=!!i,this.allowFlatten=a,this.options=e,On(typeof e.type!=`string`,`Mini animate() doesn't support "type" as a string.`,`mini-spring`);let c=Ya(e);this.animation=qa(t,n,r,c,i),c.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!i){let e=ia(r,this.options,o,this.speed);this.updateMotionValue&&this.updateMotionValue(e),za(t,n,e),this.animation.cancel()}s?.(),this.notifyFinished()}}play(){this.isStopped||(this.manualStartTime=null,this.animation.play(),this.state===`finished`&&this.updateFinished())}pause(){this.animation.pause()}complete(){this.animation.finish?.()}cancel(){try{this.animation.cancel()}catch{}}stop(){if(this.isStopped)return;this.isStopped=!0;let{state:e}=this;e===`idle`||e===`finished`||(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){let e=this.options?.element;!this.isPseudoElement&&e?.isConnected&&this.animation.commitStyles?.()}get duration(){let e=this.animation.effect?.getComputedTiming?.().duration||0;return Bn(Number(e))}get iterationDuration(){let{delay:e=0}=this.options||{};return this.duration+Bn(e)}get time(){return Bn(Number(this.animation.currentTime)||0)}set time(e){let t=this.finishedTime!==null;this.manualStartTime=null,this.finishedTime=null,this.animation.currentTime=zn(e),t&&this.animation.pause()}get speed(){return this.animation.playbackRate}set speed(e){e<0&&(this.finishedTime=null),this.animation.playbackRate=e}get state(){return this.finishedTime===null?this.animation.playState:`finished`}get startTime(){return this.manualStartTime??Number(this.animation.startTime)}set startTime(e){this.manualStartTime=this.animation.startTime=e}attachTimeline({timeline:e,rangeStart:t,rangeEnd:n,observe:r}){return this.allowFlatten&&this.animation.effect?.updateTiming({easing:`linear`}),this.animation.onfinish=null,e&&Ha()?(this.animation.timeline=e,t&&(this.animation.rangeStart=t),n&&(this.animation.rangeEnd=n),Pn):r(this)}},Za={anticipate:er,backInOut:$n,circInOut:rr};function Qa(e){return e in Za}function $a(e){typeof e.ease==`string`&&Qa(e.ease)&&(e.ease=Za[e.ease])}var eo=10,to=class extends Xa{constructor(e){$a(e),oa(e),super(e),e.startTime!==void 0&&e.autoplay!==!1&&(this.startTime=e.startTime),this.options=e}updateMotionValue(e){let{motionValue:t,onUpdate:n,onComplete:r,element:i,...a}=this.options;if(!t)return;if(e!==void 0){t.set(e);return}let o=new la({...a,autoplay:!1}),s=Math.max(eo,Sr.now()-this.startTime),c=Tn(0,eo,s-eo),l=o.sample(s).value,{name:u}=this.options;i&&u&&za(i,u,l),t.setWithVelocity(o.sample(Math.max(0,s-c)).value,l,c),o.stop()}},no=(e,t)=>t===`zIndex`?!1:!!(typeof e==`number`||Array.isArray(e)||typeof e==`string`&&(pi.test(e)||e===`0`)&&!e.startsWith(`url(`));function ro(e){let t=e[0];if(e.length===1)return!0;for(let n=0;n<e.length;n++)if(e[n]!==t)return!0}function io(e,t,n,r){let i=e[0];if(i===null)return!1;if(t===`display`||t===`visibility`)return!0;let a=e[e.length-1],o=no(i,t),s=no(a,t);return Dn(o===s,`You are trying to animate ${t} from "${i}" to "${a}". "${o?a:i}" is not an animatable value.`,`value-not-animatable`),!o||!s?!1:ro(e)||(n===`spring`||Ja(n))&&r}function ao(e){e.duration=0,e.type=`keyframes`}var oo=new Set([`opacity`,`clipPath`,`filter`,`transform`]),so=/^(?:oklch|oklab|lab|lch|color|color-mix|light-dark)\(/;function co(e){for(let t=0;t<e.length;t++)if(typeof e[t]==`string`&&so.test(e[t]))return!0;return!1}var lo=new Set([`color`,`backgroundColor`,`outlineColor`,`fill`,`stroke`,`borderColor`,`borderTopColor`,`borderRightColor`,`borderBottomColor`,`borderLeftColor`]),uo=Nn(()=>Object.hasOwnProperty.call(Element.prototype,`animate`));function fo(e){let{motionValue:t,name:n,repeatDelay:r,repeatType:i,damping:a,type:o,keyframes:s}=e;if(!(t?.owner?.current instanceof HTMLElement))return!1;let{onUpdate:c,transformTemplate:l}=t.owner.getProps();return uo()&&n&&(oo.has(n)||lo.has(n)&&co(s))&&(n!==`transform`||!l)&&!c&&!r&&i!==`mirror`&&a!==0&&o!==`inertia`}var po=40,mo=class extends sa{constructor({autoplay:e=!0,delay:t=0,type:n=`keyframes`,repeat:r=0,repeatDelay:i=0,repeatType:a=`loop`,keyframes:o,name:s,motionValue:c,element:l,...u}){super(),this.stop=()=>{this._animation&&(this._animation.stop(),this.stopTimeline?.()),this.keyframeResolver?.cancel()},this.createdAt=Sr.now();let d={autoplay:e,delay:t,type:n,repeat:r,repeatDelay:i,repeatType:a,name:s,motionValue:c,element:l,...u};this.keyframeResolver=new(l?.KeyframeResolver||La)(o,(e,t,n)=>this.onKeyframesResolved(e,t,d,!n),s,c,l),this.keyframeResolver?.scheduleResolve()}onKeyframesResolved(e,t,n,r){this.keyframeResolver=void 0;let{name:i,type:a,velocity:o,delay:s,isHandoff:c,onUpdate:l}=n;this.resolvedAt=Sr.now();let u=!0;io(e,i,a,o)||(u=!1,(kn.instantAnimations||!s)&&l?.(ia(e,n,t)),e[0]=e[e.length-1],ao(n),n.repeat=0);let d={startTime:r?this.resolvedAt&&this.resolvedAt-this.createdAt>po?this.resolvedAt:this.createdAt:void 0,finalKeyframe:t,...n,keyframes:e},f=u&&!c&&fo(d),p=d.motionValue?.owner?.current,m;if(f)try{m=new to({...d,element:p})}catch{m=new la(d)}else m=new la(d);m.finished.then(()=>{this.notifyFinished()}).catch(Pn),this.pendingTimeline&&=(this.stopTimeline=m.attachTimeline(this.pendingTimeline),void 0),this._animation=m}get finished(){return this._animation?this.animation.finished:this._finished}then(e,t){return this.finished.finally(e).then(()=>{})}get animation(){return this._animation||(this.keyframeResolver?.resume(),Ia()),this._animation}get duration(){return this.animation.duration}get iterationDuration(){return this.animation.iterationDuration}get time(){return this.animation.time}set time(e){this.animation.time=e}get speed(){return this.animation.speed}get state(){return this.animation.state}set speed(e){this.animation.speed=e}get startTime(){return this.animation.startTime}attachTimeline(e){return this._animation?this.stopTimeline=this.animation.attachTimeline(e):this.pendingTimeline=e,()=>this.stop()}play(){this.animation.play()}pause(){this.animation.pause()}complete(){this.animation.complete()}cancel(){this._animation&&this.animation.cancel(),this.keyframeResolver?.cancel()}};function ho(e,t,n,r=0,i=1){let a=Array.from(e).sort((e,t)=>e.sortNodePosition(t)).indexOf(t),o=e.size,s=(o-1)*r;return typeof n==`function`?n(a,o):i===1?a*r:s-a*r}var go=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function _o(e){let t=go.exec(e);if(!t)return[,];let[,n,r,i]=t;return[`--${n??r}`,i]}var vo=4;function yo(e,t,n=1){On(n<=vo,`Max CSS variable fallback depth detected in property "${e}". This may indicate a circular fallback dependency.`,`max-css-var-depth`);let[r,i]=_o(e);if(!r)return;let a=window.getComputedStyle(t).getPropertyValue(r);if(a){let e=a.trim();return An(e)?parseFloat(e):e}return Dr(i)?yo(i,t,n+1):i}var bo={type:`spring`,stiffness:500,damping:25,restSpeed:10},xo=e=>({type:`spring`,stiffness:550,damping:e===0?2*Math.sqrt(550):30,restSpeed:10}),So={type:`keyframes`,duration:.8},Co={type:`keyframes`,ease:[.25,.1,.35,1],duration:.3},wo=(e,{keyframes:t})=>t.length>2?So:wa.has(e)?e.startsWith(`scale`)?xo(t[1]):bo:Co;function To(e,t){if(e?.inherit&&t){let{inherit:n,...r}=e;return{...t,...r}}return e}function Eo(e,t){let n=e?.[t]??e?.default??e;return n===e?n:To(n,e)}var Do=new Set([`when`,`delay`,`delayChildren`,`staggerChildren`,`staggerDirection`,`repeat`,`repeatType`,`repeatDelay`,`from`,`elapsed`]);function Oo(e){for(let t in e)if(!Do.has(t))return!0;return!1}var ko=(e,t,n,r={},i,a)=>o=>{let s=Eo(r,e)||{},c=s.delay||r.delay||0,{elapsed:l=0}=r;l-=zn(c);let u={keyframes:Array.isArray(n)?n:[null,n],ease:`easeOut`,velocity:t.getVelocity(),...s,delay:-l,onUpdate:e=>{t.set(e),s.onUpdate&&s.onUpdate(e)},onComplete:()=>{o(),s.onComplete&&s.onComplete()},name:e,motionValue:t,element:a?void 0:i};Oo(s)||Object.assign(u,wo(e,u)),u.duration&&=zn(u.duration),u.repeatDelay&&=zn(u.repeatDelay),u.from!==void 0&&(u.keyframes[0]=u.from);let d=!1;if((u.type===!1||u.duration===0&&!u.repeatDelay)&&(ao(u),u.delay===0&&(d=!0)),(kn.instantAnimations||kn.skipAnimations||i?.shouldSkipAnimations)&&(d=!0,ao(u),u.delay=0),u.allowFlatten=!s.type&&!s.ease,d&&!a&&t.get()!==void 0){let e=ia(u.keyframes,s);if(e!==void 0){A.update(()=>{u.onUpdate(e),u.onComplete()});return}}return s.isSync?new la(u):new mo(u)};function Ao(e){let t=[{},{}];return e?.values.forEach((e,n)=>{t[0][n]=e.get(),t[1][n]=e.getVelocity()}),t}function jo(e,t,n,r){if(typeof t==`function`){let[i,a]=Ao(r);t=t(n===void 0?e.custom:n,i,a)}if(typeof t==`string`&&(t=e.variants&&e.variants[t]),typeof t==`function`){let[i,a]=Ao(r);t=t(n===void 0?e.custom:n,i,a)}return t}function Mo(e,t,n){let r=e.getProps();return jo(r,t,n===void 0?r.custom:n,e)}var No=new Set([`width`,`height`,`top`,`left`,`right`,`bottom`,...Ca]),Po=30,Fo=e=>!isNaN(parseFloat(e)),Io={current:void 0},Lo=class{constructor(e,t={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=e=>{let t=Sr.now();if(this.updatedAt!==t&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(e),this.current!==this.prev&&(this.events.change?.notify(this.current),this.dependents))for(let e of this.dependents)e.dirty()},this.hasAnimated=!1,this.setCurrent(e),this.owner=t.owner}setCurrent(e){this.current=e,this.updatedAt=Sr.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=Fo(this.current))}setPrevFrameValue(e=this.current){this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt}onChange(e){return process.env.NODE_ENV!==`production`&&Un(!1,`value.onChange(callback) is deprecated. Switch to value.on("change", callback).`),this.on(`change`,e)}on(e,t){this.events[e]||(this.events[e]=new Rn);let n=this.events[e].add(t);return e===`change`?()=>{n(),A.read(()=>{this.events.change.getSize()||this.stop()})}:n}clearListeners(){for(let e in this.events)this.events[e].clear()}attach(e,t){this.passiveEffect=e,this.stopPassiveEffect=t}set(e){this.passiveEffect?this.passiveEffect(e,this.updateAndNotify):this.updateAndNotify(e)}setWithVelocity(e,t,n){this.set(t),this.prev=void 0,this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt-n}jump(e,t=!0){this.updateAndNotify(e),this.prev=e,this.prevUpdatedAt=this.prevFrameValue=void 0,t&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}dirty(){this.events.change?.notify(this.current)}addDependent(e){this.dependents||=new Set,this.dependents.add(e)}removeDependent(e){this.dependents&&this.dependents.delete(e)}get(){return Io.current&&Io.current.push(this),this.current}getPrevious(){return this.prev}getVelocity(){let e=Sr.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>Po)return 0;let t=Math.min(this.updatedAt-this.prevUpdatedAt,Po);return Vn(parseFloat(this.current)-parseFloat(this.prevFrameValue),t)}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.dependents?.clear(),this.events.destroy?.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}};function Ro(e,t){return new Lo(e,t)}var zo=e=>Array.isArray(e);function Bo(e,t,n){e.hasValue(t)?e.getValue(t).set(n):e.addValue(t,Ro(n))}function Vo(e){return zo(e)?e[e.length-1]||0:e}function Ho(e,t){let{transitionEnd:n={},transition:r={},...i}=Mo(e,t)||{};i={...i,...n};for(let t in i)Bo(e,t,Vo(i[t]))}var Uo=e=>!!(e&&e.getVelocity);function Wo(e){return!!(Uo(e)&&e.add)}function Go(e,t){let n=e.getValue(`willChange`);if(Wo(n))return n.add(t);if(!n&&kn.WillChange){let n=new kn.WillChange(`auto`);e.addValue(`willChange`,n),n.add(t)}}function Ko(e){return e.replace(/([A-Z])/g,e=>`-${e.toLowerCase()}`)}var qo=`data-`+Ko(`framerAppearId`);function Jo(e){return e.props[qo]}function Yo({protectedKeys:e,needsAnimating:t},n){let r=e.hasOwnProperty(n)&&t[n]!==!0;return t[n]=!1,r}function Xo(e,t,{delay:n=0,transitionOverride:r,type:i}={}){let{transition:a,transitionEnd:o,...s}=t,c=e.getDefaultTransition();a=a?To(a,c):c;let l=a?.reduceMotion;r&&(a=r);let u=[],d=i&&e.animationState&&e.animationState.getState()[i];for(let t in s){let r=e.getValue(t,e.latestValues[t]??null),i=s[t];if(i===void 0||d&&Yo(d,t))continue;let o={delay:n,...Eo(a||{},t)},c=r.get();if(c!==void 0&&!r.isAnimating()&&!Array.isArray(i)&&i===c&&!o.velocity){A.update(()=>r.set(i));continue}let f=!1;if(window.MotionHandoffAnimation){let n=Jo(e);if(n){let e=window.MotionHandoffAnimation(n,t,A);e!==null&&(o.startTime=e,f=!0)}}Go(e,t);let p=l??e.shouldReduceMotion;r.start(ko(t,r,i,p&&No.has(t)?{type:!1}:o,e,f));let m=r.animation;m&&u.push(m)}if(o){let t=()=>A.update(()=>{o&&Ho(e,o)});u.length?Promise.all(u).then(t):t()}return u}function Zo(e,t,n={}){let r=Mo(e,t,n.type===`exit`?e.presenceContext?.custom:void 0),{transition:i=e.getDefaultTransition()||{}}=r||{};n.transitionOverride&&(i=n.transitionOverride);let a=r?()=>Promise.all(Xo(e,r,n)):()=>Promise.resolve(),o=e.variantChildren&&e.variantChildren.size?(r=0)=>{let{delayChildren:a=0,staggerChildren:o,staggerDirection:s}=i;return Qo(e,t,r,a,o,s,n)}:()=>Promise.resolve(),{when:s}=i;if(s){let[e,t]=s===`beforeChildren`?[a,o]:[o,a];return e().then(()=>t())}else return Promise.all([a(),o(n.delay)])}function Qo(e,t,n=0,r=0,i=0,a=1,o){let s=[];for(let c of e.variantChildren)c.notify(`AnimationStart`,t),s.push(Zo(c,t,{...o,delay:n+(typeof r==`function`?0:r)+ho(e.variantChildren,c,r,i,a)}).then(()=>c.notify(`AnimationComplete`,t)));return Promise.all(s)}function $o(e,t,n={}){e.notify(`AnimationStart`,t);let r;if(Array.isArray(t)){let i=t.map(t=>Zo(e,t,n));r=Promise.all(i)}else if(typeof t==`string`)r=Zo(e,t,n);else{let i=typeof t==`function`?Mo(e,t,n.custom):t;r=Promise.all(Xo(e,i,n))}return r.then(()=>{e.notify(`AnimationComplete`,t)})}var es={test:e=>e===`auto`,parse:e=>e},ts=e=>t=>t.test(e),ns=[Ar,j,Kr,Gr,Jr,qr,es],rs=e=>ns.find(ts(e));function is(e){return typeof e==`number`?e===0:e===null?!0:e===`none`||e===`0`||Mn(e)}var as=new Set([`brightness`,`contrast`,`saturate`,`opacity`]);function os(e){let[t,n]=e.slice(0,-1).split(`(`);if(t===`drop-shadow`)return e;let[r]=n.match(Pr)||[];if(!r)return e;let i=n.replace(r,``),a=as.has(t)?1:0;return r!==n&&(a*=100),t+`(`+a+i+`)`}var ss=/\b([a-z-]*)\(.*?\)/gu,cs={...pi,getAnimatableNone:e=>{let t=e.match(ss);return t?t.map(os).join(` `):e}},ls={...pi,getAnimatableNone:e=>{let t=pi.parse(e);return pi.createTransformer(e)(t.map(e=>typeof e==`number`?0:typeof e==`object`?{...e,alpha:1}:e))}},us={...Ar,transform:Math.round},ds={borderWidth:j,borderTopWidth:j,borderRightWidth:j,borderBottomWidth:j,borderLeftWidth:j,borderRadius:j,borderTopLeftRadius:j,borderTopRightRadius:j,borderBottomRightRadius:j,borderBottomLeftRadius:j,width:j,maxWidth:j,height:j,maxHeight:j,top:j,right:j,bottom:j,left:j,inset:j,insetBlock:j,insetBlockStart:j,insetBlockEnd:j,insetInline:j,insetInlineStart:j,insetInlineEnd:j,padding:j,paddingTop:j,paddingRight:j,paddingBottom:j,paddingLeft:j,paddingBlock:j,paddingBlockStart:j,paddingBlockEnd:j,paddingInline:j,paddingInlineStart:j,paddingInlineEnd:j,margin:j,marginTop:j,marginRight:j,marginBottom:j,marginLeft:j,marginBlock:j,marginBlockStart:j,marginBlockEnd:j,marginInline:j,marginInlineStart:j,marginInlineEnd:j,fontSize:j,backgroundPositionX:j,backgroundPositionY:j,rotate:Gr,rotateX:Gr,rotateY:Gr,rotateZ:Gr,scale:Mr,scaleX:Mr,scaleY:Mr,scaleZ:Mr,skew:Gr,skewX:Gr,skewY:Gr,distance:j,translateX:j,translateY:j,translateZ:j,x:j,y:j,z:j,perspective:j,transformPerspective:j,opacity:jr,originX:Yr,originY:Yr,originZ:j,zIndex:us,fillOpacity:jr,strokeOpacity:jr,numOctaves:us},fs={...ds,color:Zr,backgroundColor:Zr,outlineColor:Zr,fill:Zr,stroke:Zr,borderColor:Zr,borderTopColor:Zr,borderRightColor:Zr,borderBottomColor:Zr,borderLeftColor:Zr,filter:cs,WebkitFilter:cs,mask:ls,WebkitMask:ls},ps=e=>fs[e],ms=new Set([cs,ls]);function hs(e,t){let n=ps(e);return ms.has(n)||(n=pi),n.getAnimatableNone?n.getAnimatableNone(t):void 0}var gs=new Set([`auto`,`none`,`0`]);function _s(e,t,n){let r=0,i;for(;r<e.length&&!i;){let t=e[r];typeof t==`string`&&!gs.has(t)&&oi(t).values.length&&(i=e[r]),r++}if(i&&n)for(let r of t)e[r]=hs(n,i)}var vs=class extends La{constructor(e,t,n,r,i){super(e,t,n,r,i,!0)}readKeyframes(){let{unresolvedKeyframes:e,element:t,name:n}=this;if(!t||!t.current)return;super.readKeyframes();for(let n=0;n<e.length;n++){let r=e[n];if(typeof r==`string`&&(r=r.trim(),Dr(r))){let i=yo(r,t.current);i!==void 0&&(e[n]=i),n===e.length-1&&(this.finalKeyframe=r)}}if(this.resolveNoneKeyframes(),!No.has(n)||e.length!==2)return;let[r,i]=e,a=rs(r),o=rs(i);if(kr(r)!==kr(i)&&ka[n]){this.needsMeasurement=!0;return}if(a!==o)if(Ta(a)&&Ta(o))for(let t=0;t<e.length;t++){let n=e[t];typeof n==`string`&&(e[t]=parseFloat(n))}else ka[n]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){let{unresolvedKeyframes:e,name:t}=this,n=[];for(let t=0;t<e.length;t++)(e[t]===null||is(e[t]))&&n.push(t);n.length&&_s(e,n,t)}measureInitialState(){let{element:e,unresolvedKeyframes:t,name:n}=this;if(!e||!e.current)return;n===`height`&&(this.suspendedScrollY=window.pageYOffset),this.measuredOrigin=ka[n](e.measureViewportBox(),window.getComputedStyle(e.current)),t[0]=this.measuredOrigin;let r=t[t.length-1];r!==void 0&&e.getValue(n,r).jump(r,!1)}measureEndState(){let{element:e,name:t,unresolvedKeyframes:n}=this;if(!e||!e.current)return;let r=e.getValue(t);r&&r.jump(this.measuredOrigin,!1);let i=n.length-1,a=n[i];n[i]=ka[t](e.measureViewportBox(),window.getComputedStyle(e.current)),a!==null&&this.finalKeyframe===void 0&&(this.finalKeyframe=a),this.removedTransforms?.length&&this.removedTransforms.forEach(([t,n])=>{e.getValue(t).set(n)}),this.resolveNoneKeyframes()}};function ys(e,t,n){if(e==null)return[];if(e instanceof EventTarget)return[e];if(typeof e==`string`){let r=document;t&&(r=t.current);let i=n?.[e]??r.querySelectorAll(e);return i?Array.from(i):[]}return Array.from(e).filter(e=>e!=null)}var bs=(e,t)=>t&&typeof e==`number`?t.transform(e):e;function xs(e){return jn(e)&&`offsetHeight`in e&&!(`ownerSVGElement`in e)}var{schedule:Ss,cancel:Cs}=gr(queueMicrotask,!1),ws={x:!1,y:!1};function Ts(){return ws.x||ws.y}function Es(e){return e===`x`||e===`y`?ws[e]?null:(ws[e]=!0,()=>{ws[e]=!1}):ws.x||ws.y?null:(ws.x=ws.y=!0,()=>{ws.x=ws.y=!1})}function Ds(e,t){let n=ys(e),r=new AbortController;return[n,{passive:!0,...t,signal:r.signal},()=>r.abort()]}function Os(e){return!(e.pointerType===`touch`||Ts())}function ks(e,t,n={}){let[r,i,a]=Ds(e,n);return r.forEach(e=>{let n=!1,r=!1,a,o=()=>{e.removeEventListener(`pointerleave`,u)},s=e=>{a&&=(a(e),void 0),o()},c=e=>{n=!1,window.removeEventListener(`pointerup`,c),window.removeEventListener(`pointercancel`,c),r&&(r=!1,s(e))},l=()=>{n=!0,window.addEventListener(`pointerup`,c,i),window.addEventListener(`pointercancel`,c,i)},u=e=>{if(e.pointerType!==`touch`){if(n){r=!0;return}s(e)}};e.addEventListener(`pointerenter`,n=>{if(!Os(n))return;r=!1;let o=t(e,n);typeof o==`function`&&(a=o,e.addEventListener(`pointerleave`,u,i))},i),e.addEventListener(`pointerdown`,l,i)}),a}var As=(e,t)=>t?e===t?!0:As(e,t.parentElement):!1,js=e=>e.pointerType===`mouse`?typeof e.button!=`number`||e.button<=0:e.isPrimary!==!1,Ms=new Set([`BUTTON`,`INPUT`,`SELECT`,`TEXTAREA`,`A`]);function Ns(e){return Ms.has(e.tagName)||e.isContentEditable===!0}var Ps=new Set([`INPUT`,`SELECT`,`TEXTAREA`]);function Fs(e){return Ps.has(e.tagName)||e.isContentEditable===!0}var Is=new WeakSet;function Ls(e){return t=>{t.key===`Enter`&&e(t)}}function Rs(e,t){e.dispatchEvent(new PointerEvent(`pointer`+t,{isPrimary:!0,bubbles:!0}))}var zs=(e,t)=>{let n=e.currentTarget;if(!n)return;let r=Ls(()=>{if(Is.has(n))return;Rs(n,`down`);let e=Ls(()=>{Rs(n,`up`)});n.addEventListener(`keyup`,e,t),n.addEventListener(`blur`,()=>Rs(n,`cancel`),t)});n.addEventListener(`keydown`,r,t),n.addEventListener(`blur`,()=>n.removeEventListener(`keydown`,r),t)};function Bs(e){return js(e)&&!Ts()}var Vs=new WeakSet;function Hs(e,t,n={}){let[r,i,a]=Ds(e,n),o=e=>{let r=e.currentTarget;if(!Bs(e)||Vs.has(e))return;Is.add(r),n.stopPropagation&&Vs.add(e);let a=t(r,e),o=(e,t)=>{window.removeEventListener(`pointerup`,s),window.removeEventListener(`pointercancel`,c),Is.has(r)&&Is.delete(r),Bs(e)&&typeof a==`function`&&a(e,{success:t})},s=e=>{o(e,r===window||r===document||n.useGlobalTarget||As(r,e.target))},c=e=>{o(e,!1)};window.addEventListener(`pointerup`,s,i),window.addEventListener(`pointercancel`,c,i)};return r.forEach(e=>{(n.useGlobalTarget?window:e).addEventListener(`pointerdown`,o,i),xs(e)&&(e.addEventListener(`focus`,e=>zs(e,i)),!Ns(e)&&!e.hasAttribute(`tabindex`)&&(e.tabIndex=0))}),a}function Us(e){return jn(e)&&`ownerSVGElement`in e}var Ws=new WeakMap,Gs,Ks=(e,t,n)=>(r,i)=>i&&i[0]?i[0][e+`Size`]:Us(r)&&`getBBox`in r?r.getBBox()[t]:r[n],qs=Ks(`inline`,`width`,`offsetWidth`),Js=Ks(`block`,`height`,`offsetHeight`);function Ys({target:e,borderBoxSize:t}){Ws.get(e)?.forEach(n=>{n(e,{get width(){return qs(e,t)},get height(){return Js(e,t)}})})}function Xs(e){e.forEach(Ys)}function Zs(){typeof ResizeObserver>`u`||(Gs=new ResizeObserver(Xs))}function Qs(e,t){Gs||Zs();let n=ys(e);return n.forEach(e=>{let n=Ws.get(e);n||(n=new Set,Ws.set(e,n)),n.add(t),Gs?.observe(e)}),()=>{n.forEach(e=>{let n=Ws.get(e);n?.delete(t),n?.size||Gs?.unobserve(e)})}}var $s=new Set,ec;function tc(){ec=()=>{let e={get width(){return window.innerWidth},get height(){return window.innerHeight}};$s.forEach(t=>t(e))},window.addEventListener(`resize`,ec)}function nc(e){return $s.add(e),ec||tc(),()=>{$s.delete(e),!$s.size&&typeof ec==`function`&&(window.removeEventListener(`resize`,ec),ec=void 0)}}function rc(e,t){return typeof e==`function`?nc(e):Qs(e,t)}function ic(e){return Us(e)&&e.tagName===`svg`}var ac=[...ns,Zr,pi],oc=e=>ac.find(ts(e)),sc=()=>({translate:0,scale:1,origin:0,originPoint:0}),cc=()=>({x:sc(),y:sc()}),lc=()=>({min:0,max:0}),uc=()=>({x:lc(),y:lc()}),dc=new WeakMap;function fc(e){return typeof e==`object`&&!!e&&typeof e.start==`function`}function pc(e){return typeof e==`string`||Array.isArray(e)}var mc=[`animate`,`whileInView`,`whileFocus`,`whileHover`,`whileTap`,`whileDrag`,`exit`],hc=[`initial`,...mc];function gc(e){return fc(e.animate)||hc.some(t=>pc(e[t]))}function _c(e){return!!(gc(e)||e.variants)}function vc(e,t,n){for(let r in t){let i=t[r],a=n[r];if(Uo(i))e.addValue(r,i);else if(Uo(a))e.addValue(r,Ro(i,{owner:e}));else if(a!==i)if(e.hasValue(r)){let t=e.getValue(r);t.liveStyle===!0?t.jump(i):t.hasAnimated||t.set(i)}else{let t=e.getStaticValue(r);e.addValue(r,Ro(t===void 0?i:t,{owner:e}))}}for(let r in n)t[r]===void 0&&e.removeValue(r);return t}var yc={current:null},bc={current:!1},xc=typeof window<`u`;function Sc(){if(bc.current=!0,xc)if(window.matchMedia){let e=window.matchMedia(`(prefers-reduced-motion)`),t=()=>yc.current=e.matches;e.addEventListener(`change`,t),t()}else yc.current=!1}var Cc=[`AnimationStart`,`AnimationComplete`,`Update`,`BeforeLayoutMeasure`,`LayoutMeasure`,`LayoutAnimationStart`,`LayoutAnimationComplete`],wc={};function Tc(e){wc=e}function Ec(){return wc}var Dc=class{scrapeMotionValuesFromProps(e,t,n){return{}}constructor({parent:e,props:t,presenceContext:n,reducedMotionConfig:r,skipAnimations:i,blockInitialAnimation:a,visualState:o},s={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.shouldSkipAnimations=!1,this.values=new Map,this.KeyframeResolver=La,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.hasBeenMounted=!1,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=Sr.now();this.renderScheduledAt<e&&(this.renderScheduledAt=e,A.render(this.render,!1,!0))};let{latestValues:c,renderState:l}=o;this.latestValues=c,this.baseTarget={...c},this.initialValues=t.initial?{...c}:{},this.renderState=l,this.parent=e,this.props=t,this.presenceContext=n,this.depth=e?e.depth+1:0,this.reducedMotionConfig=r,this.skipAnimationsConfig=i,this.options=s,this.blockInitialAnimation=!!a,this.isControllingVariants=gc(t),this.isVariantNode=_c(t),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(e&&e.current);let{willChange:u,...d}=this.scrapeMotionValuesFromProps(t,{},this);for(let e in d){let t=d[e];c[e]!==void 0&&Uo(t)&&t.set(c[e])}}mount(e){if(this.hasBeenMounted)for(let e in this.initialValues)this.values.get(e)?.jump(this.initialValues[e]),this.latestValues[e]=this.initialValues[e];this.current=e,dc.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)),this.reducedMotionConfig===`never`?this.shouldReduceMotion=!1:this.reducedMotionConfig===`always`?this.shouldReduceMotion=!0:(bc.current||Sc(),this.shouldReduceMotion=yc.current),process.env.NODE_ENV!==`production`&&Un(this.shouldReduceMotion!==!0,`You have Reduced Motion enabled on your device. Animations may not appear as expected.`,`reduced-motion-disabled`),this.shouldSkipAnimations=this.skipAnimationsConfig??!1,this.parent?.addChild(this),this.update(this.props,this.presenceContext),this.hasBeenMounted=!0}unmount(){this.projection&&this.projection.unmount(),_r(this.notifyUpdate),_r(this.render),this.valueSubscriptions.forEach(e=>e()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),this.parent?.removeChild(this);for(let e in 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}addChild(e){this.children.add(e),this.enteringChildren??=new Set,this.enteringChildren.add(e)}removeChild(e){this.children.delete(e),this.enteringChildren&&this.enteringChildren.delete(e)}bindToMotionValue(e,t){if(this.valueSubscriptions.has(e)&&this.valueSubscriptions.get(e)(),t.accelerate&&oo.has(e)&&this.current instanceof HTMLElement){let{factory:n,keyframes:r,times:i,ease:a,duration:o}=t.accelerate,s=new Xa({element:this.current,name:e,keyframes:r,times:i,ease:a,duration:zn(o)}),c=n(s);this.valueSubscriptions.set(e,()=>{c(),s.cancel()});return}let n=wa.has(e);n&&this.onBindTransform&&this.onBindTransform();let r=t.on(`change`,t=>{this.latestValues[e]=t,this.props.onUpdate&&A.preRender(this.notifyUpdate),n&&this.projection&&(this.projection.isTransformDirty=!0),this.scheduleRender()}),i;typeof window<`u`&&window.MotionCheckAppearSync&&(i=window.MotionCheckAppearSync(this,e,t)),this.valueSubscriptions.set(e,()=>{r(),i&&i(),t.owner&&t.stop()})}sortNodePosition(e){return!this.current||!this.sortInstanceNodePosition||this.type!==e.type?0:this.sortInstanceNodePosition(this.current,e.current)}updateFeatures(){let e=`animation`;for(e in wc){let t=wc[e];if(!t)continue;let{isEnabled:n,Feature:r}=t;if(!this.features[e]&&r&&n(this.props)&&(this.features[e]=new r(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):uc()}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<Cc.length;t++){let n=Cc[t];this.propEventSubscriptions[n]&&(this.propEventSubscriptions[n](),delete this.propEventSubscriptions[n]);let r=e[`on`+n];r&&(this.propEventSubscriptions[n]=this.on(n,r))}this.prevMotionValues=vc(this,this.scrapeMotionValuesFromProps(e,this.prevProps||{},this),this.prevMotionValues),this.handleChildMotionValue&&this.handleChildMotionValue()}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 n=this.values.get(e);t!==n&&(n&&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 n=this.values.get(e);return n===void 0&&t!==void 0&&(n=Ro(t===null?void 0:t,{owner:this}),this.addValue(e,n)),n}readValue(e,t){let n=this.latestValues[e]!==void 0||!this.current?this.latestValues[e]:this.getBaseTargetFromProps(this.props,e)??this.readValueFromInstance(this.current,e,this.options);return n!=null&&(typeof n==`string`&&(An(n)||Mn(n))?n=parseFloat(n):!oc(n)&&pi.test(t)&&(n=hs(e,t)),this.setBaseTarget(e,Uo(n)?n.get():n)),Uo(n)?n.get():n}setBaseTarget(e,t){this.baseTarget[e]=t}getBaseTarget(e){let{initial:t}=this.props,n;if(typeof t==`string`||typeof t==`object`){let r=jo(this.props,t,this.presenceContext?.custom);r&&(n=r[e])}if(t&&n!==void 0)return n;let r=this.getBaseTargetFromProps(this.props,e);return r!==void 0&&!Uo(r)?r:this.initialValues[e]!==void 0&&n===void 0?void 0:this.baseTarget[e]}on(e,t){return this.events[e]||(this.events[e]=new Rn),this.events[e].add(t)}notify(e,...t){this.events[e]&&this.events[e].notify(...t)}scheduleRenderMicrotask(){Ss.render(this.render)}},Oc=class extends Dc{constructor(){super(...arguments),this.KeyframeResolver=vs}sortInstanceNodePosition(e,t){return e.compareDocumentPosition(t)&2?1:-1}getBaseTargetFromProps(e,t){let n=e.style;return n?n[t]:void 0}removeValueFromRenderState(e,{vars:t,style:n}){delete t[e],delete n[e]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);let{children:e}=this.props;Uo(e)&&(this.childSubscription=e.on(`change`,e=>{this.current&&(this.current.textContent=`${e}`)}))}},kc=class{constructor(e){this.isMounted=!1,this.node=e}update(){}};function Ac({top:e,left:t,right:n,bottom:r}){return{x:{min:t,max:n},y:{min:e,max:r}}}function jc({x:e,y:t}){return{top:t.min,right:e.max,bottom:t.max,left:e.min}}function Mc(e,t){if(!t)return e;let n=t({x:e.left,y:e.top}),r=t({x:e.right,y:e.bottom});return{top:n.y,left:n.x,bottom:r.y,right:r.x}}function Nc(e){return e===void 0||e===1}function Pc({scale:e,scaleX:t,scaleY:n}){return!Nc(e)||!Nc(t)||!Nc(n)}function Fc(e){return Pc(e)||Ic(e)||e.z||e.rotate||e.rotateX||e.rotateY||e.skewX||e.skewY}function Ic(e){return Lc(e.x)||Lc(e.y)}function Lc(e){return e&&e!==`0%`}function Rc(e,t,n){return n+t*(e-n)}function zc(e,t,n,r,i){return i!==void 0&&(e=Rc(e,i,r)),Rc(e,n,r)+t}function Bc(e,t=0,n=1,r,i){e.min=zc(e.min,t,n,r,i),e.max=zc(e.max,t,n,r,i)}function Vc(e,{x:t,y:n}){Bc(e.x,t.translate,t.scale,t.originPoint),Bc(e.y,n.translate,n.scale,n.originPoint)}var Hc=.999999999999,Uc=1.0000000000001;function Wc(e,t,n,r=!1){let i=n.length;if(!i)return;t.x=t.y=1;let a,o;for(let s=0;s<i;s++){a=n[s],o=a.projectionDelta;let{visualElement:i}=a.options;i&&i.props.style&&i.props.style.display===`contents`||(r&&a.options.layoutScroll&&a.scroll&&a!==a.root&&(Gc(e.x,-a.scroll.offset.x),Gc(e.y,-a.scroll.offset.y)),o&&(t.x*=o.x.scale,t.y*=o.y.scale,Vc(e,o)),r&&Fc(a.latestValues)&&Jc(e,a.latestValues,a.layout?.layoutBox))}t.x<Uc&&t.x>Hc&&(t.x=1),t.y<Uc&&t.y>Hc&&(t.y=1)}function Gc(e,t){e.min+=t,e.max+=t}function Kc(e,t,n,r,i=.5){Bc(e,t,n,M(e.min,e.max,i),r)}function qc(e,t){return typeof e==`string`?parseFloat(e)/100*(t.max-t.min):e}function Jc(e,t,n){let r=n??e;Kc(e.x,qc(t.x,r.x),t.scaleX,t.scale,t.originX),Kc(e.y,qc(t.y,r.y),t.scaleY,t.scale,t.originY)}function Yc(e,t){return Ac(Mc(e.getBoundingClientRect(),t))}function Xc(e,t,n){let r=Yc(e,n),{scroll:i}=t;return i&&(Gc(r.x,i.offset.x),Gc(r.y,i.offset.y)),r}var Zc={x:`translateX`,y:`translateY`,z:`translateZ`,transformPerspective:`perspective`},Qc=Ca.length;function $c(e,t,n){let r=``,i=!0;for(let a=0;a<Qc;a++){let o=Ca[a],s=e[o];if(s===void 0)continue;let c=!0;if(typeof s==`number`)c=s===(o.startsWith(`scale`)?1:0);else{let e=parseFloat(s);c=o.startsWith(`scale`)?e===1:e===0}if(!c||n){let e=bs(s,ds[o]);if(!c){i=!1;let t=Zc[o]||o;r+=`${t}(${e}) `}n&&(t[o]=e)}}return r=r.trim(),n?r=n(t,i?``:r):i&&(r=`none`),r}function el(e,t,n){let{style:r,vars:i,transformOrigin:a}=e,o=!1,s=!1;for(let e in t){let n=t[e];if(wa.has(e)){o=!0;continue}else if(Tr(e)){i[e]=n;continue}else{let t=bs(n,ds[e]);e.startsWith(`origin`)?(s=!0,a[e]=t):r[e]=t}}if(t.transform||(o||n?r.transform=$c(t,e.transform,n):r.transform&&=`none`),s){let{originX:e=`50%`,originY:t=`50%`,originZ:n=0}=a;r.transformOrigin=`${e} ${t} ${n}`}}function tl(e,{style:t,vars:n},r,i){let a=e.style,o;for(o in t)a[o]=t[o];for(o in i?.applyProjectionStyles(a,r),n)a.setProperty(o,n[o])}function nl(e,t){return t.max===t.min?0:e/(t.max-t.min)*100}var rl={correct:(e,t)=>{if(!t.target)return e;if(typeof e==`string`)if(j.test(e))e=parseFloat(e);else return e;return`${nl(e,t.target.x)}% ${nl(e,t.target.y)}%`}},il={correct:(e,{treeScale:t,projectionDelta:n})=>{let r=e,i=pi.parse(e);if(i.length>5)return r;let a=pi.createTransformer(e),o=typeof i[0]==`number`?0:1,s=n.x.scale*t.x,c=n.y.scale*t.y;i[0+o]/=s,i[1+o]/=c;let l=M(s,c,.5);return typeof i[2+o]==`number`&&(i[2+o]/=l),typeof i[3+o]==`number`&&(i[3+o]/=l),a(i)}},al={borderRadius:{...rl,applyTo:[`borderTopLeftRadius`,`borderTopRightRadius`,`borderBottomLeftRadius`,`borderBottomRightRadius`]},borderTopLeftRadius:rl,borderTopRightRadius:rl,borderBottomLeftRadius:rl,borderBottomRightRadius:rl,boxShadow:il};function ol(e,{layout:t,layoutId:n}){return wa.has(e)||e.startsWith(`origin`)||(t||n!==void 0)&&(!!al[e]||e===`opacity`)}function sl(e,t,n){let r=e.style,i=t?.style,a={};if(!r)return a;for(let t in r)(Uo(r[t])||i&&Uo(i[t])||ol(t,e)||n?.getValue(t)?.liveStyle!==void 0)&&(a[t]=r[t]);return a}function cl(e){return window.getComputedStyle(e)}var ll=class extends Oc{constructor(){super(...arguments),this.type=`html`,this.renderInstance=tl}readValueFromInstance(e,t){if(wa.has(t))return this.projection?.isProjecting?ya(t):xa(e,t);{let n=cl(e),r=(Tr(t)?n.getPropertyValue(t):n[t])||0;return typeof r==`string`?r.trim():r}}measureInstanceViewportBox(e,{transformPagePoint:t}){return Yc(e,t)}build(e,t,n){el(e,t,n.transformTemplate)}scrapeMotionValuesFromProps(e,t,n){return sl(e,t,n)}},ul={offset:`stroke-dashoffset`,array:`stroke-dasharray`},dl={offset:`strokeDashoffset`,array:`strokeDasharray`};function fl(e,t,n=1,r=0,i=!0){e.pathLength=1;let a=i?ul:dl;e[a.offset]=`${-r}`,e[a.array]=`${t} ${n}`}var pl=[`offsetDistance`,`offsetPath`,`offsetRotate`,`offsetAnchor`];function ml(e,{attrX:t,attrY:n,attrScale:r,pathLength:i,pathSpacing:a=1,pathOffset:o=0,...s},c,l,u){if(el(e,s,l),c){e.style.viewBox&&(e.attrs.viewBox=e.style.viewBox);return}e.attrs=e.style,e.style={};let{attrs:d,style:f}=e;d.transform&&(f.transform=d.transform,delete d.transform),(f.transform||d.transformOrigin)&&(f.transformOrigin=d.transformOrigin??`50% 50%`,delete d.transformOrigin),f.transform&&(f.transformBox=u?.transformBox??`fill-box`,delete d.transformBox);for(let e of pl)d[e]!==void 0&&(f[e]=d[e],delete d[e]);t!==void 0&&(d.x=t),n!==void 0&&(d.y=n),r!==void 0&&(d.scale=r),i!==void 0&&fl(d,i,a,o,!1)}var hl=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`]),gl=e=>typeof e==`string`&&e.toLowerCase()===`svg`;function _l(e,t,n,r){tl(e,t,void 0,r);for(let n in t.attrs)e.setAttribute(hl.has(n)?n:Ko(n),t.attrs[n])}function vl(e,t,n){let r=sl(e,t,n);for(let n in e)if(Uo(e[n])||Uo(t[n])){let t=Ca.indexOf(n)===-1?n:`attr`+n.charAt(0).toUpperCase()+n.substring(1);r[t]=e[n]}return r}var yl=class extends Oc{constructor(){super(...arguments),this.type=`svg`,this.isSVGTag=!1,this.measureInstanceViewportBox=uc}getBaseTargetFromProps(e,t){return e[t]}readValueFromInstance(e,t){if(wa.has(t)){let e=ps(t);return e&&e.default||0}return t=hl.has(t)?t:Ko(t),e.getAttribute(t)}scrapeMotionValuesFromProps(e,t,n){return vl(e,t,n)}build(e,t,n){ml(e,t,this.isSVGTag,n.transformTemplate,n.style)}renderInstance(e,t,n,r){_l(e,t,n,r)}mount(e){this.isSVGTag=gl(e.tagName),super.mount(e)}},bl=hc.length;function xl(e){if(!e)return;if(!e.isControllingVariants){let t=e.parent&&xl(e.parent)||{};return e.props.initial!==void 0&&(t.initial=e.props.initial),t}let t={};for(let n=0;n<bl;n++){let r=hc[n],i=e.props[r];(pc(i)||i===!1)&&(t[r]=i)}return t}function Sl(e,t){if(!Array.isArray(t))return!1;let n=t.length;if(n!==e.length)return!1;for(let r=0;r<n;r++)if(t[r]!==e[r])return!1;return!0}var Cl=[...mc].reverse(),wl=mc.length;function Tl(e){return t=>Promise.all(t.map(({animation:t,options:n})=>$o(e,t,n)))}function El(e){let t=Tl(e),n=kl(),r=!0,i=!1,a=t=>(n,r)=>{let i=Mo(e,r,t===`exit`?e.presenceContext?.custom:void 0);if(i){let{transition:e,transitionEnd:t,...r}=i;n={...n,...r,...t}}return n};function o(n){t=n(e)}function s(o){let{props:s}=e,c=xl(e.parent)||{},l=[],u=new Set,d={},f=1/0;for(let t=0;t<wl;t++){let p=Cl[t],m=n[p],h=s[p]===void 0?c[p]:s[p],g=pc(h),_=p===o?m.isActive:null;_===!1&&(f=t);let v=h===c[p]&&h!==s[p]&&g;if(v&&(r||i)&&e.manuallyAnimateOnMount&&(v=!1),m.protectedKeys={...d},!m.isActive&&_===null||!h&&!m.prevProp||fc(h)||typeof h==`boolean`)continue;if(p===`exit`&&m.isActive&&_!==!0){m.prevResolvedValues&&(d={...d,...m.prevResolvedValues});continue}let y=Dl(m.prevProp,h),b=y||p===o&&m.isActive&&!v&&g||t>f&&g,x=!1,S=Array.isArray(h)?h:[h],ee=S.reduce(a(p),{});_===!1&&(ee={});let{prevResolvedValues:te={}}=m,C={...te,...ee},ne=t=>{b=!0,u.has(t)&&(x=!0,u.delete(t)),m.needsAnimating[t]=!0;let n=e.getValue(t);n&&(n.liveStyle=!1)};for(let e in C){let t=ee[e],n=te[e];if(d.hasOwnProperty(e))continue;let r=!1;r=zo(t)&&zo(n)?!Sl(t,n):t!==n,r?t==null?u.add(e):ne(e):t!==void 0&&u.has(e)?ne(e):m.protectedKeys[e]=!0}m.prevProp=h,m.prevResolvedValues=ee,m.isActive&&(d={...d,...ee}),(r||i)&&e.blockInitialAnimation&&(b=!1);let re=v&&y;b&&(!re||x)&&l.push(...S.map(t=>{let n={type:p};if(typeof t==`string`&&(r||i)&&!re&&e.manuallyAnimateOnMount&&e.parent){let{parent:r}=e,i=Mo(r,t);if(r.enteringChildren&&i){let{delayChildren:t}=i.transition||{};n.delay=ho(r.enteringChildren,e,t)}}return{animation:t,options:n}}))}if(u.size){let t={};if(typeof s.initial!=`boolean`){let n=Mo(e,Array.isArray(s.initial)?s.initial[0]:s.initial);n&&n.transition&&(t.transition=n.transition)}u.forEach(n=>{let r=e.getBaseTarget(n),i=e.getValue(n);i&&(i.liveStyle=!0),t[n]=r??null}),l.push({animation:t})}let p=!!l.length;return r&&(s.initial===!1||s.initial===s.animate)&&!e.manuallyAnimateOnMount&&(p=!1),r=!1,i=!1,p?t(l):Promise.resolve()}function c(t,r){if(n[t].isActive===r)return Promise.resolve();e.variantChildren?.forEach(e=>e.animationState?.setActive(t,r)),n[t].isActive=r;let i=s(t);for(let e in n)n[e].protectedKeys={};return i}return{animateChanges:s,setActive:c,setAnimateFunction:o,getState:()=>n,reset:()=>{n=kl(),i=!0}}}function Dl(e,t){return typeof t==`string`?t!==e:Array.isArray(t)?!Sl(t,e):!1}function Ol(e=!1){return{isActive:e,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function kl(){return{animate:Ol(!0),whileInView:Ol(),whileHover:Ol(),whileTap:Ol(),whileDrag:Ol(),whileFocus:Ol(),exit:Ol()}}function Al(e,t){e.min=t.min,e.max=t.max}function jl(e,t){Al(e.x,t.x),Al(e.y,t.y)}function Ml(e,t){e.translate=t.translate,e.scale=t.scale,e.originPoint=t.originPoint,e.origin=t.origin}var Nl=1e-4,Pl=1-Nl,Fl=1+Nl,Il=.01,Ll=0-Il,Rl=0+Il;function zl(e){return e.max-e.min}function Bl(e,t,n){return Math.abs(e-t)<=n}function Vl(e,t,n,r=.5){e.origin=r,e.originPoint=M(t.min,t.max,e.origin),e.scale=zl(n)/zl(t),e.translate=M(n.min,n.max,e.origin)-e.originPoint,(e.scale>=Pl&&e.scale<=Fl||isNaN(e.scale))&&(e.scale=1),(e.translate>=Ll&&e.translate<=Rl||isNaN(e.translate))&&(e.translate=0)}function Hl(e,t,n,r){Vl(e.x,t.x,n.x,r?r.originX:void 0),Vl(e.y,t.y,n.y,r?r.originY:void 0)}function Ul(e,t,n,r=0){e.min=(r?M(n.min,n.max,r):n.min)+t.min,e.max=e.min+zl(t)}function Wl(e,t,n,r){Ul(e.x,t.x,n.x,r?.x),Ul(e.y,t.y,n.y,r?.y)}function Gl(e,t,n,r=0){let i=r?M(n.min,n.max,r):n.min;e.min=t.min-i,e.max=e.min+zl(t)}function Kl(e,t,n,r){Gl(e.x,t.x,n.x,r?.x),Gl(e.y,t.y,n.y,r?.y)}function ql(e,t,n,r,i){return e-=t,e=Rc(e,1/n,r),i!==void 0&&(e=Rc(e,1/i,r)),e}function Jl(e,t=0,n=1,r=.5,i,a=e,o=e){if(Kr.test(t)&&(t=parseFloat(t),t=M(o.min,o.max,t/100)-o.min),typeof t!=`number`)return;let s=M(a.min,a.max,r);e===a&&(s-=t),e.min=ql(e.min,t,n,s,i),e.max=ql(e.max,t,n,s,i)}function Yl(e,t,[n,r,i],a,o){Jl(e,t[n],t[r],t[i],t.scale,a,o)}var Xl=[`x`,`scaleX`,`originX`],Zl=[`y`,`scaleY`,`originY`];function Ql(e,t,n,r){Yl(e.x,t,Xl,n?n.x:void 0,r?r.x:void 0),Yl(e.y,t,Zl,n?n.y:void 0,r?r.y:void 0)}function $l(e){return e.translate===0&&e.scale===1}function eu(e){return $l(e.x)&&$l(e.y)}function tu(e,t){return e.min===t.min&&e.max===t.max}function nu(e,t){return tu(e.x,t.x)&&tu(e.y,t.y)}function ru(e,t){return Math.round(e.min)===Math.round(t.min)&&Math.round(e.max)===Math.round(t.max)}function iu(e,t){return ru(e.x,t.x)&&ru(e.y,t.y)}function au(e){return zl(e.x)/zl(e.y)}function ou(e,t){return e.translate===t.translate&&e.scale===t.scale&&e.originPoint===t.originPoint}function su(e){return[e(`x`),e(`y`)]}function cu(e,t,n){let r=``,i=e.x.translate/t.x,a=e.y.translate/t.y,o=n?.z||0;if((i||a||o)&&(r=`translate3d(${i}px, ${a}px, ${o}px) `),(t.x!==1||t.y!==1)&&(r+=`scale(${1/t.x}, ${1/t.y}) `),n){let{transformPerspective:e,rotate:t,rotateX:i,rotateY:a,skewX:o,skewY:s}=n;e&&(r=`perspective(${e}px) ${r}`),t&&(r+=`rotate(${t}deg) `),i&&(r+=`rotateX(${i}deg) `),a&&(r+=`rotateY(${a}deg) `),o&&(r+=`skewX(${o}deg) `),s&&(r+=`skewY(${s}deg) `)}let s=e.x.scale*t.x,c=e.y.scale*t.y;return(s!==1||c!==1)&&(r+=`scale(${s}, ${c})`),r||`none`}var lu=[`borderTopLeftRadius`,`borderTopRightRadius`,`borderBottomLeftRadius`,`borderBottomRightRadius`],uu=lu.length,du=e=>typeof e==`string`?parseFloat(e):e,fu=e=>typeof e==`number`||j.test(e);function pu(e,t,n,r,i,a){i?(e.opacity=M(0,n.opacity??1,hu(r)),e.opacityExit=M(t.opacity??1,0,gu(r))):a&&(e.opacity=M(t.opacity??1,n.opacity??1,r));for(let i=0;i<uu;i++){let a=lu[i],o=mu(t,a),s=mu(n,a);o===void 0&&s===void 0||(o||=0,s||=0,o===0||s===0||fu(o)===fu(s)?(e[a]=Math.max(M(du(o),du(s),r),0),(Kr.test(s)||Kr.test(o))&&(e[a]+=`%`)):e[a]=s)}(t.rotate||n.rotate)&&(e.rotate=M(t.rotate||0,n.rotate||0,r))}function mu(e,t){return e[t]===void 0?e.borderRadius:e[t]}var hu=_u(0,.5,nr),gu=_u(.5,.95,Pn);function _u(e,t,n){return r=>r<e?0:r>t?1:n(Ln(e,t,r))}function vu(e,t,n){let r=Uo(e)?e:Ro(e);return r.start(ko(``,r,t,n)),r.animation}function yu(e,t,n,r={passive:!0}){return e.addEventListener(t,n,r),()=>e.removeEventListener(t,n)}var bu=(e,t)=>e.depth-t.depth,xu=class{constructor(){this.children=[],this.isDirty=!1}add(e){Cn(this.children,e),this.isDirty=!0}remove(e){wn(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort(bu),this.isDirty=!1,this.children.forEach(e)}};function Su(e,t){let n=Sr.now(),r=({timestamp:i})=>{let a=i-n;a>=t&&(_r(r),e(a-t))};return A.setup(r,!0),()=>_r(r)}function Cu(e){return Uo(e)?e.get():e}var wu=class{constructor(){this.members=[]}add(e){Cn(this.members,e);for(let t=this.members.length-1;t>=0;t--){let n=this.members[t];if(n===e||n===this.lead||n===this.prevLead)continue;let r=n.instance;(!r||r.isConnected===!1)&&!n.snapshot&&(wn(this.members,n),n.unmount())}e.scheduleRender()}remove(e){if(wn(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){for(let t=this.members.indexOf(e)-1;t>=0;t--){let e=this.members[t];if(e.isPresent!==!1&&e.instance?.isConnected!==!1)return this.promote(e),!0}return!1}promote(e,t){let n=this.lead;if(e!==n&&(this.prevLead=n,this.lead=e,e.show(),n)){n.updateSnapshot(),e.scheduleRender();let{layoutDependency:r}=n.options,{layoutDependency:i}=e.options;(r===void 0||r!==i)&&(e.resumeFrom=n,t&&(n.preserveOpacity=!0),n.snapshot&&(e.snapshot=n.snapshot,e.snapshot.latestValues=n.animationValues||n.latestValues),e.root?.isUpdating&&(e.isLayoutDirty=!0)),e.options.crossfade===!1&&n.hide()}}exitAnimationComplete(){this.members.forEach(e=>{e.options.onExitComplete?.(),e.resumingFrom?.options.onExitComplete?.()})}scheduleRender(){this.members.forEach(e=>e.instance&&e.scheduleRender(!1))}removeLeadSnapshot(){this.lead?.snapshot&&(this.lead.snapshot=void 0)}},Tu={hasAnimatedSinceResize:!0,hasEverUpdated:!1},Eu={nodes:0,calculatedTargetDeltas:0,calculatedProjections:0},Du=[``,`X`,`Y`,`Z`],Ou=1e3,ku=0;function Au(e,t,n,r){let{latestValues:i}=t;i[e]&&(n[e]=i[e],t.setStaticValue(e,0),r&&(r[e]=0))}function ju(e){if(e.hasCheckedOptimisedAppear=!0,e.root===e)return;let{visualElement:t}=e.options;if(!t)return;let n=Jo(t);if(window.MotionHasOptimisedAnimation(n,`transform`)){let{layout:t,layoutId:r}=e.options;window.MotionCancelOptimisedAnimation(n,`transform`,A,!(t||r))}let{parent:r}=e;r&&!r.hasCheckedOptimisedAppear&&ju(r)}function Mu({attachResizeListener:e,defaultParent:t,measureScroll:n,checkIsScrollRoot:r,resetTransform:i}){return class{constructor(e={},n=t?.()){this.id=ku++,this.animationId=0,this.animationCommitId=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.layoutVersion=0,this.updateScheduled=!1,this.scheduleUpdate=()=>this.update(),this.projectionUpdateScheduled=!1,this.checkUpdateFailed=()=>{this.isUpdating&&(this.isUpdating=!1,this.clearAllSnapshots())},this.updateProjection=()=>{this.projectionUpdateScheduled=!1,pr.value&&(Eu.nodes=Eu.calculatedTargetDeltas=Eu.calculatedProjections=0),this.nodes.forEach(Fu),this.nodes.forEach(Wu),this.nodes.forEach(Gu),this.nodes.forEach(Iu),pr.addProjectionMetrics&&pr.addProjectionMetrics(Eu)},this.resolvedRelativeTargetAt=0,this.linkedParentVersion=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=e,this.root=n?n.root||n:this,this.path=n?[...n.path,n]:[],this.parent=n,this.depth=n?n.depth+1:0;for(let e=0;e<this.path.length;e++)this.path[e].shouldResetTransform=!0;this.root===this&&(this.nodes=new xu)}addEventListener(e,t){return this.eventHandlers.has(e)||this.eventHandlers.set(e,new Rn),this.eventHandlers.get(e).add(t)}notifyListeners(e,...t){let n=this.eventHandlers.get(e);n&&n.notify(...t)}hasListeners(e){return this.eventHandlers.has(e)}mount(t){if(this.instance)return;this.isSVG=Us(t)&&!ic(t),this.instance=t;let{layoutId:n,layout:r,visualElement:i}=this.options;if(i&&!i.current&&i.mount(t),this.root.nodes.add(this),this.parent&&this.parent.children.add(this),this.root.hasTreeAnimated&&(r||n)&&(this.isLayoutDirty=!0),e){let n,r=0,i=()=>this.root.updateBlockedByResize=!1;A.read(()=>{r=window.innerWidth}),e(t,()=>{let e=window.innerWidth;e!==r&&(r=e,this.root.updateBlockedByResize=!0,n&&n(),n=Su(i,250),Tu.hasAnimatedSinceResize&&(Tu.hasAnimatedSinceResize=!1,this.nodes.forEach(Uu)))})}n&&this.root.registerSharedNode(n,this),this.options.animate!==!1&&i&&(n||r)&&this.addEventListener(`didUpdate`,({delta:e,hasLayoutChanged:t,hasRelativeLayoutChanged:n,layout:r})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}let a=this.options.transition||i.getDefaultTransition()||Qu,{onLayoutAnimationStart:o,onLayoutAnimationComplete:s}=i.getProps(),c=!this.targetLayout||!iu(this.targetLayout,r),l=!t&&n;if(this.options.layoutRoot||this.resumeFrom||l||t&&(c||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);let t={...Eo(a,`layout`),onPlay:o,onComplete:s};(i.shouldReduceMotion||this.options.layoutRoot)&&(t.delay=0,t.type=!1),this.startAnimation(t),this.setAnimationOrigin(e,l)}else t||Uu(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=r})}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,this.eventHandlers.clear(),_r(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(Ku),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&&ju(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,(typeof t.latestValues.x==`string`||typeof t.latestValues.y==`string`)&&(t.isLayoutDirty=!0),t.updateScroll(`snapshot`),t.options.layoutRoot&&t.willUpdate(!1)}let{layoutId:t,layout:n}=this.options;if(t===void 0&&!n)return;let r=this.getTransformTemplate();this.prevTransformTemplateValue=r?r(this.latestValues,``):void 0,this.updateSnapshot(),e&&this.notifyListeners(`willUpdate`)}update(){if(this.updateScheduled=!1,this.isUpdateBlocked()){let e=this.updateBlockedByResize;this.unblockUpdate(),this.updateBlockedByResize=!1,this.clearAllSnapshots(),e&&this.nodes.forEach(zu),this.nodes.forEach(Ru);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(Bu);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(Vu),this.nodes.forEach(Hu),this.nodes.forEach(Nu),this.nodes.forEach(Pu)):this.nodes.forEach(Bu),this.clearAllSnapshots();let e=Sr.now();vr.delta=Tn(0,1e3/60,e-vr.timestamp),vr.timestamp=e,vr.isProcessing=!0,yr.update.process(vr),yr.preRender.process(vr),yr.render.process(vr),vr.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,Ss.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(Lu),this.sharedNodes.forEach(qu)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,A.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){A.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!zl(this.snapshot.measuredBox.x)&&!zl(this.snapshot.measuredBox.y)&&(this.snapshot=void 0))}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.layoutVersion++,this.layoutCorrected||=uc(),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&&this.instance){let t=r(this.instance);this.scroll={animationId:this.root.animationId,phase:e,isRoot:t,offset:n(this.instance),wasRoot:this.scroll?this.scroll.isRoot:t}}}resetTransform(){if(!i)return;let e=this.isLayoutDirty||this.shouldResetTransform||this.options.alwaysMeasureLayout,t=this.projectionDelta&&!eu(this.projectionDelta),n=this.getTransformTemplate(),r=n?n(this.latestValues,``):void 0,a=r!==this.prevTransformTemplateValue;e&&this.instance&&(t||Fc(this.latestValues)||a)&&(i(this.instance,r),this.shouldResetTransform=!1,this.scheduleRender())}measure(e=!0){let t=this.measurePageBox(),n=this.removeElementScroll(t);return e&&(n=this.removeTransform(n)),nd(n),{animationId:this.root.animationId,measuredBox:t,layoutBox:n,latestValues:{},source:this.id}}measurePageBox(){let{visualElement:e}=this.options;if(!e)return uc();let t=e.measureViewportBox();if(!(this.scroll?.wasRoot||this.path.some(id))){let{scroll:e}=this.root;e&&(Gc(t.x,e.offset.x),Gc(t.y,e.offset.y))}return t}removeElementScroll(e){let t=uc();if(jl(t,e),this.scroll?.wasRoot)return t;for(let n=0;n<this.path.length;n++){let r=this.path[n],{scroll:i,options:a}=r;r!==this.root&&i&&a.layoutScroll&&(i.wasRoot&&jl(t,e),Gc(t.x,i.offset.x),Gc(t.y,i.offset.y))}return t}applyTransform(e,t=!1,n){let r=n||uc();jl(r,e);for(let e=0;e<this.path.length;e++){let n=this.path[e];!t&&n.options.layoutScroll&&n.scroll&&n!==n.root&&(Gc(r.x,-n.scroll.offset.x),Gc(r.y,-n.scroll.offset.y)),Fc(n.latestValues)&&Jc(r,n.latestValues,n.layout?.layoutBox)}return Fc(this.latestValues)&&Jc(r,this.latestValues,this.layout?.layoutBox),r}removeTransform(e){let t=uc();jl(t,e);for(let e=0;e<this.path.length;e++){let n=this.path[e];if(!Fc(n.latestValues))continue;let r;n.instance&&(Pc(n.latestValues)&&n.updateSnapshot(),r=uc(),jl(r,n.measurePageBox())),Ql(t,n.latestValues,n.snapshot?.layoutBox,r)}return Fc(this.latestValues)&&Ql(t,this.latestValues),t}setTargetDelta(e){this.targetDelta=e,this.root.scheduleUpdateProjection(),this.isProjectionDirty=!0}setOptions(e){this.options={...this.options,...e,crossfade:e.crossfade===void 0?!0: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!==vr.timestamp&&this.relativeParent.resolveTargetDelta(!0)}resolveTargetDelta(e=!1){let t=this.getLead();this.isProjectionDirty||=t.isProjectionDirty,this.isTransformDirty||=t.isTransformDirty,this.isSharedProjectionDirty||=t.isSharedProjectionDirty;let n=!!this.resumingFrom||this!==t;if(!(e||n&&this.isSharedProjectionDirty||this.isProjectionDirty||this.parent?.isProjectionDirty||this.attemptToResolveRelativeTarget||this.root.updateBlockedByResize))return;let{layout:r,layoutId:i}=this.options;if(!this.layout||!(r||i))return;this.resolvedRelativeTargetAt=vr.timestamp;let a=this.getClosestProjectingParent();a&&this.linkedParentVersion!==a.layoutVersion&&!a.options.layoutRoot&&this.removeRelativeTarget(),!this.targetDelta&&!this.relativeTarget&&(this.options.layoutAnchor!==!1&&a&&a.layout?this.createRelativeTarget(a,this.layout.layoutBox,a.layout.layoutBox):this.removeRelativeTarget()),!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=uc(),this.targetWithTransforms=uc()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),Wl(this.target,this.relativeTarget,this.relativeParent.target,this.options.layoutAnchor||void 0)):this.targetDelta?(this.resumingFrom?this.applyTransform(this.layout.layoutBox,!1,this.target):jl(this.target,this.layout.layoutBox),Vc(this.target,this.targetDelta)):jl(this.target,this.layout.layoutBox),this.attemptToResolveRelativeTarget&&(this.attemptToResolveRelativeTarget=!1,this.options.layoutAnchor!==!1&&a&&!!a.resumingFrom==!!this.resumingFrom&&!a.options.layoutScroll&&a.target&&this.animationProgress!==1?this.createRelativeTarget(a,this.target,a.target):this.relativeParent=this.relativeTarget=void 0),pr.value&&Eu.calculatedTargetDeltas++)}getClosestProjectingParent(){if(!(!this.parent||Pc(this.parent.latestValues)||Ic(this.parent.latestValues)))return this.parent.isProjecting()?this.parent:this.parent.getClosestProjectingParent()}isProjecting(){return!!((this.relativeTarget||this.targetDelta||this.options.layoutRoot)&&this.layout)}createRelativeTarget(e,t,n){this.relativeParent=e,this.linkedParentVersion=e.layoutVersion,this.forceRelativeParentToResolveTarget(),this.relativeTarget=uc(),this.relativeTargetOrigin=uc(),Kl(this.relativeTargetOrigin,t,n,this.options.layoutAnchor||void 0),jl(this.relativeTarget,this.relativeTargetOrigin)}removeRelativeTarget(){this.relativeParent=this.relativeTarget=void 0}calcProjection(){let e=this.getLead(),t=!!this.resumingFrom||this!==e,n=!0;if((this.isProjectionDirty||this.parent?.isProjectionDirty)&&(n=!1),t&&(this.isSharedProjectionDirty||this.isTransformDirty)&&(n=!1),this.resolvedRelativeTargetAt===vr.timestamp&&(n=!1),n)return;let{layout:r,layoutId:i}=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||i))return;jl(this.layoutCorrected,this.layout.layoutBox);let a=this.treeScale.x,o=this.treeScale.y;Wc(this.layoutCorrected,this.treeScale,this.path,t),e.layout&&!e.target&&(this.treeScale.x!==1||this.treeScale.y!==1)&&(e.target=e.layout.layoutBox,e.targetWithTransforms=uc());let{target:s}=e;if(!s){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(Ml(this.prevProjectionDelta.x,this.projectionDelta.x),Ml(this.prevProjectionDelta.y,this.projectionDelta.y)),Hl(this.projectionDelta,this.layoutCorrected,s,this.latestValues),(this.treeScale.x!==a||this.treeScale.y!==o||!ou(this.projectionDelta.x,this.prevProjectionDelta.x)||!ou(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners(`projectionUpdate`,s)),pr.value&&Eu.calculatedProjections++}hide(){this.isVisible=!1}show(){this.isVisible=!0}scheduleRender(e=!0){if(this.options.visualElement?.scheduleRender(),e){let e=this.getStack();e&&e.scheduleRender()}this.resumingFrom&&!this.resumingFrom.instance&&(this.resumingFrom=void 0)}createProjectionDeltas(){this.prevProjectionDelta=cc(),this.projectionDelta=cc(),this.projectionDeltaWithTransform=cc()}setAnimationOrigin(e,t=!1){let n=this.snapshot,r=n?n.latestValues:{},i={...this.latestValues},a=cc();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!t;let o=uc(),s=(n?n.source:void 0)!==(this.layout?this.layout.source:void 0),c=this.getStack(),l=!c||c.members.length<=1,u=!!(s&&!l&&this.options.crossfade===!0&&!this.path.some(Zu));this.animationProgress=0;let d;this.mixTargetDelta=t=>{let n=t/1e3;Ju(a.x,e.x,n),Ju(a.y,e.y,n),this.setTargetDelta(a),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(Kl(o,this.layout.layoutBox,this.relativeParent.layout.layoutBox,this.options.layoutAnchor||void 0),Xu(this.relativeTarget,this.relativeTargetOrigin,o,n),d&&nu(this.relativeTarget,d)&&(this.isProjectionDirty=!1),d||=uc(),jl(d,this.relativeTarget)),s&&(this.animationValues=i,pu(i,r,this.latestValues,n,u,l)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=n},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(e){this.notifyListeners(`animationStart`),this.currentAnimation?.stop(),this.resumingFrom?.currentAnimation?.stop(),this.pendingAnimation&&=(_r(this.pendingAnimation),void 0),this.pendingAnimation=A.update(()=>{Tu.hasAnimatedSinceResize=!0,Cr.layout++,this.motionValue||=Ro(0),this.motionValue.jump(0,!1),this.currentAnimation=vu(this.motionValue,[0,1e3],{...e,velocity:0,isSync:!0,onUpdate:t=>{this.mixTargetDelta(t),e.onUpdate&&e.onUpdate(t)},onStop:()=>{Cr.layout--},onComplete:()=>{Cr.layout--,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(Ou),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){let e=this.getLead(),{targetWithTransforms:t,target:n,layout:r,latestValues:i}=e;if(!(!t||!n||!r)){if(this!==e&&this.layout&&r&&rd(this.options.animationType,this.layout.layoutBox,r.layoutBox)){n=this.target||uc();let t=zl(this.layout.layoutBox.x);n.x.min=e.target.x.min,n.x.max=n.x.min+t;let r=zl(this.layout.layoutBox.y);n.y.min=e.target.y.min,n.y.max=n.y.min+r}jl(t,n),Jc(t,i),Hl(this.projectionDeltaWithTransform,this.layoutCorrected,t,i)}}registerSharedNode(e,t){this.sharedNodes.has(e)||this.sharedNodes.set(e,new wu),this.sharedNodes.get(e).add(t);let n=t.options.initialPromotionConfig;t.promote({transition:n?n.transition:void 0,preserveFollowOpacity:n&&n.shouldPreserveFollowOpacity?n.shouldPreserveFollowOpacity(t):void 0})}isLead(){let e=this.getStack();return e?e.lead===this:!0}getLead(){let{layoutId:e}=this.options;return e&&this.getStack()?.lead||this}getPrevLead(){let{layoutId:e}=this.options;return e?this.getStack()?.prevLead:void 0}getStack(){let{layoutId:e}=this.options;if(e)return this.root.sharedNodes.get(e)}promote({needsReset:e,transition:t,preserveFollowOpacity:n}={}){let r=this.getStack();r&&r.promote(this,n),e&&(this.projectionDelta=void 0,this.needsReset=!0),t&&this.setOptions({transition:t})}relegate(){let e=this.getStack();return e?e.relegate(this):!1}resetSkewAndRotation(){let{visualElement:e}=this.options;if(!e)return;let t=!1,{latestValues:n}=e;if((n.z||n.rotate||n.rotateX||n.rotateY||n.rotateZ||n.skewX||n.skewY)&&(t=!0),!t)return;let r={};n.z&&Au(`z`,e,r,this.animationValues);for(let t=0;t<Du.length;t++)Au(`rotate${Du[t]}`,e,r,this.animationValues),Au(`skew${Du[t]}`,e,r,this.animationValues);e.render();for(let t in r)e.setStaticValue(t,r[t]),this.animationValues&&(this.animationValues[t]=r[t]);e.scheduleRender()}applyProjectionStyles(e,t){if(!this.instance||this.isSVG)return;if(!this.isVisible){e.visibility=`hidden`;return}let n=this.getTransformTemplate();if(this.needsReset){this.needsReset=!1,e.visibility=``,e.opacity=``,e.pointerEvents=Cu(t?.pointerEvents)||``,e.transform=n?n(this.latestValues,``):`none`;return}let r=this.getLead();if(!this.projectionDelta||!this.layout||!r.target){this.options.layoutId&&(e.opacity=this.latestValues.opacity===void 0?1:this.latestValues.opacity,e.pointerEvents=Cu(t?.pointerEvents)||``),this.hasProjected&&!Fc(this.latestValues)&&(e.transform=n?n({},``):`none`,this.hasProjected=!1);return}e.visibility=``;let i=r.animationValues||r.latestValues;this.applyTransformsToTarget();let a=cu(this.projectionDeltaWithTransform,this.treeScale,i);n&&(a=n(i,a)),e.transform=a;let{x:o,y:s}=this.projectionDelta;e.transformOrigin=`${o.origin*100}% ${s.origin*100}% 0`,r.animationValues?e.opacity=r===this?i.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:i.opacityExit:e.opacity=r===this?i.opacity===void 0?``:i.opacity:i.opacityExit===void 0?0:i.opacityExit;for(let t in al){if(i[t]===void 0)continue;let{correct:n,applyTo:o,isCSSVariable:s}=al[t],c=a===`none`?i[t]:n(i[t],r);if(o){let t=o.length;for(let n=0;n<t;n++)e[o[n]]=c}else s?this.options.visualElement.renderState.vars[t]=c:e[t]=c}this.options.layoutId&&(e.pointerEvents=r===this?Cu(t?.pointerEvents)||``:`none`)}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(e=>e.currentAnimation?.stop()),this.root.nodes.forEach(Ru),this.root.sharedNodes.clear()}}}function Nu(e){e.updateLayout()}function Pu(e){let t=e.resumeFrom?.snapshot||e.snapshot;if(e.isLead()&&e.layout&&t&&e.hasListeners(`didUpdate`)){let{layoutBox:n,measuredBox:r}=e.layout,{animationType:i}=e.options,a=t.source!==e.layout.source;if(i===`size`)su(e=>{let r=a?t.measuredBox[e]:t.layoutBox[e],i=zl(r);r.min=n[e].min,r.max=r.min+i});else if(i===`x`||i===`y`){let e=i===`x`?`y`:`x`;Al(a?t.measuredBox[e]:t.layoutBox[e],n[e])}else rd(i,t.layoutBox,n)&&su(r=>{let i=a?t.measuredBox[r]:t.layoutBox[r],o=zl(n[r]);i.max=i.min+o,e.relativeTarget&&!e.currentAnimation&&(e.isProjectionDirty=!0,e.relativeTarget[r].max=e.relativeTarget[r].min+o)});let o=cc();Hl(o,n,t.layoutBox);let s=cc();a?Hl(s,e.applyTransform(r,!0),t.measuredBox):Hl(s,n,t.layoutBox);let c=!eu(o),l=!1;if(!e.resumeFrom){let r=e.getClosestProjectingParent();if(r&&!r.resumeFrom){let{snapshot:i,layout:a}=r;if(i&&a){let o=e.options.layoutAnchor||void 0,s=uc();Kl(s,t.layoutBox,i.layoutBox,o);let c=uc();Kl(c,n,a.layoutBox,o),iu(s,c)||(l=!0),r.options.layoutRoot&&(e.relativeTarget=c,e.relativeTargetOrigin=s,e.relativeParent=r)}}}e.notifyListeners(`didUpdate`,{layout:n,snapshot:t,delta:s,layoutDelta:o,hasLayoutChanged:c,hasRelativeLayoutChanged:l})}else if(e.isLead()){let{onExitComplete:t}=e.options;t&&t()}e.options.transition=void 0}function Fu(e){pr.value&&Eu.nodes++,e.parent&&(e.isProjecting()||(e.isProjectionDirty=e.parent.isProjectionDirty),e.isSharedProjectionDirty||=!!(e.isProjectionDirty||e.parent.isProjectionDirty||e.parent.isSharedProjectionDirty),e.isTransformDirty||=e.parent.isTransformDirty)}function Iu(e){e.isProjectionDirty=e.isSharedProjectionDirty=e.isTransformDirty=!1}function Lu(e){e.clearSnapshot()}function Ru(e){e.clearMeasurements()}function zu(e){e.isLayoutDirty=!0,e.updateLayout()}function Bu(e){e.isLayoutDirty=!1}function Vu(e){e.isAnimationBlocked&&e.layout&&!e.isLayoutDirty&&(e.snapshot=e.layout,e.isLayoutDirty=!0)}function Hu(e){let{visualElement:t}=e.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify(`BeforeLayoutMeasure`),e.resetTransform()}function Uu(e){e.finishAnimation(),e.targetDelta=e.relativeTarget=e.target=void 0,e.isProjectionDirty=!0}function Wu(e){e.resolveTargetDelta()}function Gu(e){e.calcProjection()}function Ku(e){e.resetSkewAndRotation()}function qu(e){e.removeLeadSnapshot()}function Ju(e,t,n){e.translate=M(t.translate,0,n),e.scale=M(t.scale,1,n),e.origin=t.origin,e.originPoint=t.originPoint}function Yu(e,t,n,r){e.min=M(t.min,n.min,r),e.max=M(t.max,n.max,r)}function Xu(e,t,n,r){Yu(e.x,t.x,n.x,r),Yu(e.y,t.y,n.y,r)}function Zu(e){return e.animationValues&&e.animationValues.opacityExit!==void 0}var Qu={duration:.45,ease:[.4,0,.1,1]},$u=e=>typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(e),ed=$u(`applewebkit/`)&&!$u(`chrome/`)?Math.round:Pn;function td(e){e.min=ed(e.min),e.max=ed(e.max)}function nd(e){td(e.x),td(e.y)}function rd(e,t,n){return e===`position`||e===`preserve-aspect`&&!Bl(au(t),au(n),.2)}function id(e){return e!==e.root&&e.scroll?.wasRoot}var ad=Mu({attachResizeListener:(e,t)=>yu(e,`resize`,t),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body?.scrollLeft||0,y:document.documentElement.scrollTop||document.body?.scrollTop||0}),checkIsScrollRoot:()=>!0}),od={current:void 0},sd=Mu({measureScroll:e=>({x:e.scrollLeft,y:e.scrollTop}),defaultParent:()=>{if(!od.current){let e=new ad({});e.mount(window),e.setOptions({layoutScroll:!0}),od.current=e}return od.current},resetTransform:(e,t)=>{e.style.transform=t===void 0?`none`:t},checkIsScrollRoot:e=>window.getComputedStyle(e).position===`fixed`}),cd=(0,d.createContext)({transformPagePoint:e=>e,isStatic:!1,reducedMotion:`never`});function ld(e=!0){let t=(0,d.useContext)(Sn);if(t===null)return[!0,null];let{isPresent:n,onExitComplete:r,register:i}=t,a=(0,d.useId)();(0,d.useEffect)(()=>{if(e)return i(a)},[e]);let o=(0,d.useCallback)(()=>e&&r&&r(a),[a,r,e]);return!n&&r?[!1,o]:[!0]}var ud=(0,d.createContext)({strict:!1}),dd={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`]},fd=!1;function pd(){if(fd)return;let e={};for(let t in dd)e[t]={isEnabled:e=>dd[t].some(t=>!!e[t])};Tc(e),fd=!0}function md(){return pd(),Ec()}function hd(e){let t=md();for(let n in e)t[n]={...t[n],...e[n]};Tc(t)}var gd=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.propagate.ignoreStrict.viewport`.split(`.`));function _d(e){return e.startsWith(`while`)||e.startsWith(`drag`)&&e!==`draggable`||e.startsWith(`layout`)||e.startsWith(`onTap`)||e.startsWith(`onPan`)||e.startsWith(`onLayout`)||gd.has(e)}var vd=s({default:()=>yd}),yd,bd=o((()=>{throw yd={},Error(`Could not resolve "@emotion/is-prop-valid" imported by "framer-motion". Is it installed?`)})),xd=e=>!_d(e);function Sd(e){typeof e==`function`&&(xd=t=>t.startsWith(`on`)?!_d(t):e(t))}try{Sd((bd(),u(vd)).default)}catch{}function Cd(e,t,n){let r={};for(let i in e)i===`values`&&typeof e.values==`object`||Uo(e[i])||(xd(i)||n===!0&&_d(i)||!t&&!_d(i)||e.draggable&&i.startsWith(`onDrag`))&&(r[i]=e[i]);return r}var wd=(0,d.createContext)({});function Td(e,t){if(gc(e)){let{initial:t,animate:n}=e;return{initial:t===!1||pc(t)?t:void 0,animate:pc(n)?n:void 0}}return e.inherit===!1?{}:t}function Ed(e){let{initial:t,animate:n}=Td(e,(0,d.useContext)(wd));return(0,d.useMemo)(()=>({initial:t,animate:n}),[Dd(t),Dd(n)])}function Dd(e){return Array.isArray(e)?e.join(` `):e}var Od=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function kd(e,t,n){for(let r in t)!Uo(t[r])&&!ol(r,n)&&(e[r]=t[r])}function Ad({transformTemplate:e},t){return(0,d.useMemo)(()=>{let n=Od();return el(n,t,e),Object.assign({},n.vars,n.style)},[t])}function jd(e,t){let n=e.style||{},r={};return kd(r,n,e),Object.assign(r,Ad(e,t)),r}function Md(e,t){let n={},r=jd(e,t);return e.drag&&e.dragListener!==!1&&(n.draggable=!1,r.userSelect=r.WebkitUserSelect=r.WebkitTouchCallout=`none`,r.touchAction=e.drag===!0?`none`:`pan-${e.drag===`x`?`y`:`x`}`),e.tabIndex===void 0&&(e.onTap||e.onTapStart||e.whileTap)&&(n.tabIndex=0),n.style=r,n}var Nd=()=>({...Od(),attrs:{}});function Pd(e,t,n,r){let i=(0,d.useMemo)(()=>{let n=Nd();return ml(n,t,gl(r),e.transformTemplate,e.style),{...n.attrs,style:{...n.style}}},[t]);if(e.style){let t={};kd(t,e.style,e),i.style={...t,...i.style}}return i}var Fd=[`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 Id(e){return typeof e!=`string`||e.includes(`-`)?!1:!!(Fd.indexOf(e)>-1||/[A-Z]/u.test(e))}function Ld(e,t,n,{latestValues:r},i,a=!1,o){let s=(o??Id(e)?Pd:Md)(t,r,i,e),c=Cd(t,typeof e==`string`,a),l=e===d.Fragment?{}:{...c,...s,ref:n},{children:u}=t,f=(0,d.useMemo)(()=>Uo(u)?u.get():u,[u]);return(0,d.createElement)(e,{...l,children:f})}function Rd({scrapeMotionValuesFromProps:e,createRenderState:t},n,r,i){return{latestValues:zd(n,r,i,e),renderState:t()}}function zd(e,t,n,r){let i={},a=r(e,{});for(let e in a)i[e]=Cu(a[e]);let{initial:o,animate:s}=e,c=gc(e),l=_c(e);t&&l&&!c&&e.inherit!==!1&&(o===void 0&&(o=t.initial),s===void 0&&(s=t.animate));let u=n?n.initial===!1:!1;u||=o===!1;let d=u?s:o;if(d&&typeof d!=`boolean`&&!fc(d)){let t=Array.isArray(d)?d:[d];for(let n=0;n<t.length;n++){let r=jo(e,t[n]);if(r){let{transitionEnd:e,transition:t,...n}=r;for(let e in n){let t=n[e];if(Array.isArray(t)){let e=u?t.length-1:0;t=t[e]}t!==null&&(i[e]=t)}for(let t in e)i[t]=e[t]}}}return i}var Bd=e=>(t,n)=>{let r=(0,d.useContext)(wd),i=(0,d.useContext)(Sn),a=()=>Rd(e,t,r,i);return n?a():bn(a)},Vd=Bd({scrapeMotionValuesFromProps:sl,createRenderState:Od}),Hd=Bd({scrapeMotionValuesFromProps:vl,createRenderState:Nd}),Ud=Symbol.for(`motionComponentSymbol`);function Wd(e,t,n){let r=(0,d.useRef)(n);(0,d.useInsertionEffect)(()=>{r.current=n});let i=(0,d.useRef)(null);return(0,d.useCallback)(n=>{n&&e.onMount?.(n);let a=r.current;if(typeof a==`function`)if(n){let e=a(n);typeof e==`function`&&(i.current=e)}else i.current?(i.current(),i.current=null):a(n);else a&&(a.current=n);t&&(n?t.mount(n):t.unmount())},[t])}var Gd=(0,d.createContext)({});function Kd(e){return e&&typeof e==`object`&&Object.prototype.hasOwnProperty.call(e,`current`)}function qd(e,t,n,r,i,a){let{visualElement:o}=(0,d.useContext)(wd),s=(0,d.useContext)(ud),c=(0,d.useContext)(Sn),l=(0,d.useContext)(cd),u=l.reducedMotion,f=l.skipAnimations,p=(0,d.useRef)(null),m=(0,d.useRef)(!1);r||=s.renderer,!p.current&&r&&(p.current=r(e,{visualState:t,parent:o,props:n,presenceContext:c,blockInitialAnimation:c?c.initial===!1:!1,reducedMotionConfig:u,skipAnimations:f,isSVG:a}),m.current&&p.current&&(p.current.manuallyAnimateOnMount=!0));let h=p.current,g=(0,d.useContext)(Gd);h&&!h.projection&&i&&(h.type===`html`||h.type===`svg`)&&Jd(p.current,n,i,g);let _=(0,d.useRef)(!1);(0,d.useInsertionEffect)(()=>{h&&_.current&&h.update(n,c)});let v=n[qo],y=(0,d.useRef)(!!v&&typeof window<`u`&&!window.MotionHandoffIsComplete?.(v)&&window.MotionHasOptimisedAnimation?.(v));return xn(()=>{m.current=!0,h&&(_.current=!0,window.MotionIsMounted=!0,h.updateFeatures(),h.scheduleRenderMicrotask(),y.current&&h.animationState&&h.animationState.animateChanges())}),(0,d.useEffect)(()=>{h&&(!y.current&&h.animationState&&h.animationState.animateChanges(),y.current&&=(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(v)}),!1),h.enteringChildren=void 0)}),h}function Jd(e,t,n,r){let{layoutId:i,layout:a,drag:o,dragConstraints:s,layoutScroll:c,layoutRoot:l,layoutAnchor:u,layoutCrossfade:d}=t;e.projection=new n(e.latestValues,t[`data-framer-portal-id`]?void 0:Yd(e.parent)),e.projection.setOptions({layoutId:i,layout:a,alwaysMeasureLayout:!!o||s&&Kd(s),visualElement:e,animationType:typeof a==`string`?a:`both`,initialPromotionConfig:r,crossfade:d,layoutScroll:c,layoutRoot:l,layoutAnchor:u})}function Yd(e){if(e)return e.options.allowProjection===!1?Yd(e.parent):e.projection}function Xd(e,{forwardMotionProps:t=!1,type:n}={},r,i){r&&hd(r);let a=n?n===`svg`:Id(e),o=a?Hd:Vd;function s(n,s){let c,l={...(0,d.useContext)(cd),...n,layoutId:Zd(n)},{isStatic:u}=l,p=Ed(n),m=o(n,u);if(!u&&typeof window<`u`){Qd(l,r);let t=$d(l);c=t.MeasureLayout,p.visualElement=qd(e,m,l,i,t.ProjectionNode,a)}return(0,f.jsxs)(wd.Provider,{value:p,children:[c&&p.visualElement?(0,f.jsx)(c,{visualElement:p.visualElement,...l}):null,Ld(e,n,Wd(m,p.visualElement,s),m,u,t,a)]})}s.displayName=`motion.${typeof e==`string`?e:`create(${e.displayName??e.name??``})`}`;let c=(0,d.forwardRef)(s);return c[Ud]=e,c}function Zd({layoutId:e}){let t=(0,d.useContext)(yn).id;return t&&e!==void 0?t+`-`+e:e}function Qd(e,t){let n=(0,d.useContext)(ud).strict;if(process.env.NODE_ENV!==`production`&&t&&n){let t="You have rendered a `motion` component within a `LazyMotion` component. This will break tree shaking. Import and render a `m` component instead.";e.ignoreStrict?Dn(!1,t,`lazy-strict-mode`):On(!1,t,`lazy-strict-mode`)}}function $d(e){let{drag:t,layout:n}=md();if(!t&&!n)return{};let r={...t,...n};return{MeasureLayout:t?.isEnabled(e)||n?.isEnabled(e)?r.MeasureLayout:void 0,ProjectionNode:r.ProjectionNode}}function ef(e,t){if(typeof Proxy>`u`)return Xd;let n=new Map,r=(n,r)=>Xd(n,r,e,t);return new Proxy((e,t)=>(process.env.NODE_ENV!==`production`&&Un(!1,`motion() is deprecated. Use motion.create() instead.`),r(e,t)),{get:(i,a)=>a===`create`?r:(n.has(a)||n.set(a,Xd(a,void 0,e,t)),n.get(a))})}var tf=(e,t)=>t.isSVG??Id(e)?new yl(t):new ll(t,{allowProjection:e!==d.Fragment}),nf=class extends kc{constructor(e){super(e),e.animationState||=El(e)}updateAnimationControlsSubscription(){let{animate:e}=this.node.getProps();fc(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(){this.node.animationState.reset(),this.unmountControls?.()}},rf=0,af={animation:{Feature:nf},exit:{Feature:class extends kc{constructor(){super(...arguments),this.id=rf++,this.isExitComplete=!1}update(){if(!this.node.presenceContext)return;let{isPresent:e,onExitComplete:t}=this.node.presenceContext,{isPresent:n}=this.node.prevPresenceContext||{};if(!this.node.animationState||e===n)return;if(e&&n===!1){if(this.isExitComplete){let{initial:e,custom:t}=this.node.getProps();if(typeof e==`string`){let n=Mo(this.node,e,t);if(n){let{transition:e,transitionEnd:t,...r}=n;for(let e in r)this.node.getValue(e)?.jump(r[e])}}this.node.animationState.reset(),this.node.animationState.animateChanges()}else this.node.animationState.setActive(`exit`,!1);this.isExitComplete=!1;return}let r=this.node.animationState.setActive(`exit`,!e);t&&!e&&r.then(()=>{this.isExitComplete=!0,t(this.id)})}mount(){let{register:e,onExitComplete:t}=this.node.presenceContext||{};t&&t(this.id),e&&(this.unmount=e(this.id))}unmount(){}}}};function of(e){return{point:{x:e.pageX,y:e.pageY}}}var sf=e=>t=>js(t)&&e(t,of(t));function cf(e,t,n,r){return yu(e,t,sf(n),r)}var lf=({current:e})=>e?e.ownerDocument.defaultView:null,uf=(e,t)=>Math.abs(e-t);function df(e,t){let n=uf(e.x,t.x),r=uf(e.y,t.y);return Math.sqrt(n**2+r**2)}var ff=new Set([`auto`,`scroll`]),pf=class{constructor(e,t,{transformPagePoint:n,contextWindow:r=window,dragSnapToOrigin:i=!1,distanceThreshold:a=3,element:o}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.lastRawMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.scrollPositions=new Map,this.removeScrollListeners=null,this.onElementScroll=e=>{this.handleScroll(e.target)},this.onWindowScroll=()=>{this.handleScroll(window)},this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;this.lastRawMoveEventInfo&&(this.lastMoveEventInfo=mf(this.lastRawMoveEventInfo,this.transformPagePoint));let e=gf(this.lastMoveEventInfo,this.history),t=this.startEvent!==null,n=df(e.offset,{x:0,y:0})>=this.distanceThreshold;if(!t&&!n)return;let{point:r}=e,{timestamp:i}=vr;this.history.push({...r,timestamp:i});let{onStart:a,onMove:o}=this.handlers;t||(a&&a(this.lastMoveEvent,e),this.startEvent=this.lastMoveEvent),o&&o(this.lastMoveEvent,e)},this.handlePointerMove=(e,t)=>{this.lastMoveEvent=e,this.lastRawMoveEventInfo=t,this.lastMoveEventInfo=mf(t,this.transformPagePoint),A.update(this.updatePoint,!0)},this.handlePointerUp=(e,t)=>{this.end();let{onEnd:n,onSessionEnd:r,resumeAnimation:i}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&i&&i(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;let a=gf(e.type===`pointercancel`?this.lastMoveEventInfo:mf(t,this.transformPagePoint),this.history);this.startEvent&&n&&n(e,a),r&&r(e,a)},!js(e))return;this.dragSnapToOrigin=i,this.handlers=t,this.transformPagePoint=n,this.distanceThreshold=a,this.contextWindow=r||window;let s=mf(of(e),this.transformPagePoint),{point:c}=s,{timestamp:l}=vr;this.history=[{...c,timestamp:l}];let{onSessionStart:u}=t;u&&u(e,gf(s,this.history)),this.removeListeners=In(cf(this.contextWindow,`pointermove`,this.handlePointerMove),cf(this.contextWindow,`pointerup`,this.handlePointerUp),cf(this.contextWindow,`pointercancel`,this.handlePointerUp)),o&&this.startScrollTracking(o)}startScrollTracking(e){let t=e.parentElement;for(;t;){let e=getComputedStyle(t);(ff.has(e.overflowX)||ff.has(e.overflowY))&&this.scrollPositions.set(t,{x:t.scrollLeft,y:t.scrollTop}),t=t.parentElement}this.scrollPositions.set(window,{x:window.scrollX,y:window.scrollY}),window.addEventListener(`scroll`,this.onElementScroll,{capture:!0}),window.addEventListener(`scroll`,this.onWindowScroll),this.removeScrollListeners=()=>{window.removeEventListener(`scroll`,this.onElementScroll,{capture:!0}),window.removeEventListener(`scroll`,this.onWindowScroll)}}handleScroll(e){let t=this.scrollPositions.get(e);if(!t)return;let n=e===window,r=n?{x:window.scrollX,y:window.scrollY}:{x:e.scrollLeft,y:e.scrollTop},i={x:r.x-t.x,y:r.y-t.y};i.x===0&&i.y===0||(n?this.lastMoveEventInfo&&(this.lastMoveEventInfo.point.x+=i.x,this.lastMoveEventInfo.point.y+=i.y):this.history.length>0&&(this.history[0].x-=i.x,this.history[0].y-=i.y),this.scrollPositions.set(e,r),A.update(this.updatePoint,!0))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),_r(this.updatePoint)}};function mf(e,t){return t?{point:t(e.point)}:e}function hf(e,t){return{x:e.x-t.x,y:e.y-t.y}}function gf({point:e},t){return{point:e,delta:hf(e,vf(t)),offset:hf(e,_f(t)),velocity:yf(t,.1)}}function _f(e){return e[0]}function vf(e){return e[e.length-1]}function yf(e,t){if(e.length<2)return{x:0,y:0};let n=e.length-1,r=null,i=vf(e);for(;n>=0&&(r=e[n],!(i.timestamp-r.timestamp>zn(t)));)n--;if(!r)return{x:0,y:0};r===e[0]&&e.length>2&&i.timestamp-r.timestamp>zn(t)*2&&(r=e[1]);let a=Bn(i.timestamp-r.timestamp);if(a===0)return{x:0,y:0};let o={x:(i.x-r.x)/a,y:(i.y-r.y)/a};return o.x===1/0&&(o.x=0),o.y===1/0&&(o.y=0),o}function bf(e,{min:t,max:n},r){return t!==void 0&&e<t?e=r?M(t,e,r.min):Math.max(e,t):n!==void 0&&e>n&&(e=r?M(n,e,r.max):Math.min(e,n)),e}function xf(e,t,n){return{min:t===void 0?void 0:e.min+t,max:n===void 0?void 0:e.max+n-(e.max-e.min)}}function Sf(e,{top:t,left:n,bottom:r,right:i}){return{x:xf(e.x,n,i),y:xf(e.y,t,r)}}function Cf(e,t){let n=t.min-e.min,r=t.max-e.max;return t.max-t.min<e.max-e.min&&([n,r]=[r,n]),{min:n,max:r}}function wf(e,t){return{x:Cf(e.x,t.x),y:Cf(e.y,t.y)}}function Tf(e,t){let n=.5,r=zl(e),i=zl(t);return i>r?n=Ln(t.min,t.max-r,e.min):r>i&&(n=Ln(e.min,e.max-i,t.min)),Tn(0,1,n)}function Ef(e,t){let n={};return t.min!==void 0&&(n.min=t.min-e.min),t.max!==void 0&&(n.max=t.max-e.min),n}var Df=.35;function Of(e=Df){return e===!1?e=0:e===!0&&(e=Df),{x:kf(e,`left`,`right`),y:kf(e,`top`,`bottom`)}}function kf(e,t,n){return{min:Af(e,t),max:Af(e,n)}}function Af(e,t){return typeof e==`number`?e:e[t]||0}var jf=new WeakMap,Mf=class{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=uc(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=e}start(e,{snapToCursor:t=!1,distanceThreshold:n}={}){let{presenceContext:r}=this.visualElement;if(r&&r.isPresent===!1)return;let i=e=>{t&&this.snapToCursor(of(e).point),this.stopAnimation()},a=(e,t)=>{let{drag:n,dragPropagation:r,onDragStart:i}=this.getProps();if(n&&!r&&(this.openDragLock&&this.openDragLock(),this.openDragLock=Es(n),!this.openDragLock))return;this.latestPointerEvent=e,this.latestPanInfo=t,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),su(e=>{let t=this.getAxisMotionValue(e).get()||0;if(Kr.test(t)){let{projection:n}=this.visualElement;if(n&&n.layout){let r=n.layout.layoutBox[e];r&&(t=zl(r)*(parseFloat(t)/100))}}this.originPoint[e]=t}),i&&A.update(()=>i(e,t),!1,!0),Go(this.visualElement,`transform`);let{animationState:a}=this.visualElement;a&&a.setActive(`whileDrag`,!0)},o=(e,t)=>{this.latestPointerEvent=e,this.latestPanInfo=t;let{dragPropagation:n,dragDirectionLock:r,onDirectionLock:i,onDrag:a}=this.getProps();if(!n&&!this.openDragLock)return;let{offset:o}=t;if(r&&this.currentDirection===null){this.currentDirection=If(o),this.currentDirection!==null&&i&&i(this.currentDirection);return}this.updateAxis(`x`,t.point,o),this.updateAxis(`y`,t.point,o),this.visualElement.render(),a&&A.update(()=>a(e,t),!1,!0)},s=(e,t)=>{this.latestPointerEvent=e,this.latestPanInfo=t,this.stop(e,t),this.latestPointerEvent=null,this.latestPanInfo=null},c=()=>{let{dragSnapToOrigin:e}=this.getProps();(e||this.constraints)&&this.startAnimation({x:0,y:0})},{dragSnapToOrigin:l}=this.getProps();this.panSession=new pf(e,{onSessionStart:i,onStart:a,onMove:o,onSessionEnd:s,resumeAnimation:c},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:l,distanceThreshold:n,contextWindow:lf(this.visualElement),element:this.visualElement.current})}stop(e,t){let n=e||this.latestPointerEvent,r=t||this.latestPanInfo,i=this.isDragging;if(this.cancel(),!i||!r||!n)return;let{velocity:a}=r;this.startAnimation(a);let{onDragEnd:o}=this.getProps();o&&A.postRender(()=>o(n,r))}cancel(){this.isDragging=!1;let{projection:e,animationState:t}=this.visualElement;e&&(e.isAnimationBlocked=!1),this.endPanSession();let{dragPropagation:n}=this.getProps();!n&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),t&&t.setActive(`whileDrag`,!1)}endPanSession(){this.panSession&&this.panSession.end(),this.panSession=void 0}updateAxis(e,t,n){let{drag:r}=this.getProps();if(!n||!Ff(e,r,this.currentDirection))return;let i=this.getAxisMotionValue(e),a=this.originPoint[e]+n[e];this.constraints&&this.constraints[e]&&(a=bf(a,this.constraints[e],this.elastic[e])),i.set(a)}resolveConstraints(){let{dragConstraints:e,dragElastic:t}=this.getProps(),n=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):this.visualElement.projection?.layout,r=this.constraints;e&&Kd(e)?this.constraints||=this.resolveRefConstraints():e&&n?this.constraints=Sf(n.layoutBox,e):this.constraints=!1,this.elastic=Of(t),r!==this.constraints&&!Kd(e)&&n&&this.constraints&&!this.hasMutatedConstraints&&su(e=>{this.constraints!==!1&&this.getAxisMotionValue(e)&&(this.constraints[e]=Ef(n.layoutBox[e],this.constraints[e]))})}resolveRefConstraints(){let{dragConstraints:e,onMeasureDragConstraints:t}=this.getProps();if(!e||!Kd(e))return!1;let n=e.current;On(n!==null,"If `dragConstraints` is set as a React ref, that ref must be passed to another component's `ref` prop.",`drag-constraints-ref`);let{projection:r}=this.visualElement;if(!r||!r.layout)return!1;let i=Xc(n,r.root,this.visualElement.getTransformPagePoint()),a=wf(r.layout.layoutBox,i);if(t){let e=t(jc(a));this.hasMutatedConstraints=!!e,e&&(a=Ac(e))}return a}startAnimation(e){let{drag:t,dragMomentum:n,dragElastic:r,dragTransition:i,dragSnapToOrigin:a,onDragTransitionEnd:o}=this.getProps(),s=this.constraints||{},c=su(o=>{if(!Ff(o,t,this.currentDirection))return;let c=s&&s[o]||{};(a===!0||a===o)&&(c={min:0,max:0});let l=r?200:1e6,u=r?40:1e7,d={type:`inertia`,velocity:n?e[o]:0,bounceStiffness:l,bounceDamping:u,timeConstant:750,restDelta:1,restSpeed:10,...i,...c};return this.startAxisValueAnimation(o,d)});return Promise.all(c).then(o)}startAxisValueAnimation(e,t){let n=this.getAxisMotionValue(e);return Go(this.visualElement,e),n.start(ko(e,n,0,t,this.visualElement,!1))}stopAnimation(){su(e=>this.getAxisMotionValue(e).stop())}getAxisMotionValue(e){let t=`_drag${e.toUpperCase()}`,n=this.visualElement.getProps();return n[t]||this.visualElement.getValue(e,(n.initial?n.initial[e]:void 0)||0)}snapToCursor(e){su(t=>{let{drag:n}=this.getProps();if(!Ff(t,n,this.currentDirection))return;let{projection:r}=this.visualElement,i=this.getAxisMotionValue(t);if(r&&r.layout){let{min:n,max:a}=r.layout.layoutBox[t],o=i.get()||0;i.set(e[t]-M(n,a,.5)+o)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;let{drag:e,dragConstraints:t}=this.getProps(),{projection:n}=this.visualElement;if(!Kd(t)||!n||!this.constraints)return;this.stopAnimation();let r={x:0,y:0};su(e=>{let t=this.getAxisMotionValue(e);if(t&&this.constraints!==!1){let n=t.get();r[e]=Tf({min:n,max:n},this.constraints[e])}});let{transformTemplate:i}=this.visualElement.getProps();this.visualElement.current.style.transform=i?i({},``):`none`,n.root&&n.root.updateScroll(),n.updateLayout(),this.constraints=!1,this.resolveConstraints(),su(t=>{if(!Ff(t,e,null))return;let n=this.getAxisMotionValue(t),{min:i,max:a}=this.constraints[t];n.set(M(i,a,r[t]))}),this.visualElement.render()}addListeners(){if(!this.visualElement.current)return;jf.set(this.visualElement,this);let e=this.visualElement.current,t=cf(e,`pointerdown`,t=>{let{drag:n,dragListener:r=!0}=this.getProps(),i=t.target,a=i!==e&&Fs(i);n&&r&&!a&&this.start(t)}),n,r=()=>{let{dragConstraints:t}=this.getProps();Kd(t)&&t.current&&(this.constraints=this.resolveRefConstraints(),n||=Pf(e,t.current,()=>this.scalePositionWithinConstraints()))},{projection:i}=this.visualElement,a=i.addEventListener(`measure`,r);i&&!i.layout&&(i.root&&i.root.updateScroll(),i.updateLayout()),A.read(r);let o=yu(window,`resize`,()=>this.scalePositionWithinConstraints()),s=i.addEventListener(`didUpdate`,(({delta:e,hasLayoutChanged:t})=>{this.isDragging&&t&&(su(t=>{let n=this.getAxisMotionValue(t);n&&(this.originPoint[t]+=e[t].translate,n.set(n.get()+e[t].translate))}),this.visualElement.render())}));return()=>{o(),t(),a(),s&&s(),n&&n()}}getProps(){let e=this.visualElement.getProps(),{drag:t=!1,dragDirectionLock:n=!1,dragPropagation:r=!1,dragConstraints:i=!1,dragElastic:a=Df,dragMomentum:o=!0}=e;return{...e,drag:t,dragDirectionLock:n,dragPropagation:r,dragConstraints:i,dragElastic:a,dragMomentum:o}}};function Nf(e){let t=!0;return()=>{if(t){t=!1;return}e()}}function Pf(e,t,n){let r=rc(e,Nf(n)),i=rc(t,Nf(n));return()=>{r(),i()}}function Ff(e,t,n){return(t===!0||t===e)&&(n===null||n===e)}function If(e,t=10){let n=null;return Math.abs(e.y)>t?n=`y`:Math.abs(e.x)>t&&(n=`x`),n}var Lf=class extends kc{constructor(e){super(e),this.removeGroupControls=Pn,this.removeListeners=Pn,this.controls=new Mf(e)}mount(){let{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Pn}update(){let{dragControls:e}=this.node.getProps(),{dragControls:t}=this.node.prevProps||{};e!==t&&(this.removeGroupControls(),e&&(this.removeGroupControls=e.subscribe(this.controls)))}unmount(){this.removeGroupControls(),this.removeListeners(),this.controls.isDragging||this.controls.endPanSession()}},Rf=e=>(t,n)=>{e&&A.update(()=>e(t,n),!1,!0)},zf=class extends kc{constructor(){super(...arguments),this.removePointerDownListener=Pn}onPointerDown(e){this.session=new pf(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:lf(this.node)})}createPanHandlers(){let{onPanSessionStart:e,onPanStart:t,onPan:n,onPanEnd:r}=this.node.getProps();return{onSessionStart:Rf(e),onStart:Rf(t),onMove:Rf(n),onEnd:(e,t)=>{delete this.session,r&&A.postRender(()=>r(e,t))}}}mount(){this.removePointerDownListener=cf(this.node.current,`pointerdown`,e=>this.onPointerDown(e))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}},Bf=!1,Vf=class extends d.Component{componentDidMount(){let{visualElement:e,layoutGroup:t,switchLayoutGroup:n,layoutId:r}=this.props,{projection:i}=e;i&&(t.group&&t.group.add(i),n&&n.register&&r&&n.register(i),Bf&&i.root.didUpdate(),i.addEventListener(`animationComplete`,()=>{this.safeToRemove()}),i.setOptions({...i.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),Tu.hasEverUpdated=!0}getSnapshotBeforeUpdate(e){let{layoutDependency:t,visualElement:n,drag:r,isPresent:i}=this.props,{projection:a}=n;return a?(a.isPresent=i,e.layoutDependency!==t&&a.setOptions({...a.options,layoutDependency:t}),Bf=!0,r||e.layoutDependency!==t||t===void 0||e.isPresent!==i?a.willUpdate():this.safeToRemove(),e.isPresent!==i&&(i?a.promote():a.relegate()||A.postRender(()=>{let e=a.getStack();(!e||!e.members.length)&&this.safeToRemove()})),null):null}componentDidUpdate(){let{visualElement:e,layoutAnchor:t}=this.props,{projection:n}=e;n&&(n.options.layoutAnchor=t,n.root.didUpdate(),Ss.postRender(()=>{!n.currentAnimation&&n.isLead()&&this.safeToRemove()}))}componentWillUnmount(){let{visualElement:e,layoutGroup:t,switchLayoutGroup:n}=this.props,{projection:r}=e;Bf=!0,r&&(r.scheduleCheckAfterUnmount(),t&&t.group&&t.group.remove(r),n&&n.deregister&&n.deregister(r))}safeToRemove(){let{safeToRemove:e}=this.props;e&&e()}render(){return null}};function Hf(e){let[t,n]=ld(),r=(0,d.useContext)(yn);return(0,f.jsx)(Vf,{...e,layoutGroup:r,switchLayoutGroup:(0,d.useContext)(Gd),isPresent:t,safeToRemove:n})}var Uf={pan:{Feature:zf},drag:{Feature:Lf,ProjectionNode:sd,MeasureLayout:Hf}};function Wf(e,t,n){let{props:r}=e;e.animationState&&r.whileHover&&e.animationState.setActive(`whileHover`,n===`Start`);let i=r[`onHover`+n];i&&A.postRender(()=>i(t,of(t)))}var Gf=class extends kc{mount(){let{current:e}=this.node;e&&(this.unmount=ks(e,(e,t)=>(Wf(this.node,t,`Start`),e=>Wf(this.node,e,`End`))))}unmount(){}},Kf=class extends kc{constructor(){super(...arguments),this.isActive=!1}onFocus(){let e=!1;try{e=this.node.current.matches(`:focus-visible`)}catch{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=In(yu(this.node.current,`focus`,()=>this.onFocus()),yu(this.node.current,`blur`,()=>this.onBlur()))}unmount(){}};function qf(e,t,n){let{props:r}=e;if(e.current instanceof HTMLButtonElement&&e.current.disabled)return;e.animationState&&r.whileTap&&e.animationState.setActive(`whileTap`,n===`Start`);let i=r[`onTap`+(n===`End`?``:n)];i&&A.postRender(()=>i(t,of(t)))}var Jf=class extends kc{mount(){let{current:e}=this.node;if(!e)return;let{globalTapTarget:t,propagate:n}=this.node.props;this.unmount=Hs(e,(e,t)=>(qf(this.node,t,`Start`),(e,{success:t})=>qf(this.node,e,t?`End`:`Cancel`)),{useGlobalTarget:t,stopPropagation:n?.tap===!1})}unmount(){}},Yf=new WeakMap,Xf=new WeakMap,Zf=e=>{let t=Yf.get(e.target);t&&t(e)},Qf=e=>{e.forEach(Zf)};function $f({root:e,...t}){let n=e||document;Xf.has(n)||Xf.set(n,{});let r=Xf.get(n),i=JSON.stringify(t);return r[i]||(r[i]=new IntersectionObserver(Qf,{root:e,...t})),r[i]}function ep(e,t,n){let r=$f(t);return Yf.set(e,n),r.observe(e),()=>{Yf.delete(e),r.unobserve(e)}}var tp={some:0,all:1},np=class extends kc{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.stopObserver?.();let{viewport:e={}}=this.node.getProps(),{root:t,margin:n,amount:r=`some`,once:i}=e,a={root:t?t.current:void 0,rootMargin:n,threshold:typeof r==`number`?r:tp[r]};this.stopObserver=ep(this.node.current,a,e=>{let{isIntersecting:t}=e;if(this.isInView===t||(this.isInView=t,i&&!t&&this.hasEnteredView))return;t&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive(`whileInView`,t);let{onViewportEnter:n,onViewportLeave:r}=this.node.getProps(),a=t?n:r;a&&a(e)})}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>`u`)return;let{props:e,prevProps:t}=this.node;[`amount`,`margin`,`root`].some(rp(e,t))&&this.startObserver()}unmount(){this.stopObserver?.(),this.hasEnteredView=!1,this.isInView=!1}};function rp({viewport:e={}},{viewport:t={}}={}){return n=>e[n]!==t[n]}var ip={inView:{Feature:np},tap:{Feature:Jf},focus:{Feature:Kf},hover:{Feature:Gf}},ap={layout:{ProjectionNode:sd,MeasureLayout:Hf}},op=ef({...af,...ip,...Uf,...ap},tf);function sp(e,t){return t.forEach(function(t){t&&typeof t!=`string`&&!Array.isArray(t)&&Object.keys(t).forEach(function(n){if(n!==`default`&&!(n in e)){var r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,r.get?r:{enumerable:!0,get:function(){return t[n]}})}})}),Object.freeze(e)}var cp=Object.defineProperty,lp=(e,t,n)=>t in e?cp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,up=(e,t,n)=>lp(e,typeof t==`symbol`?t:t+``,n),dp=class{constructor(){up(this,`_locking`),up(this,`_locks`),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){this._locks+=1;let e,t=new Promise(t=>e=()=>{--this._locks,t()}),n=this._locking.then(()=>e);return this._locking=this._locking.then(()=>t),n}};function fp(e,t){if(!e)throw Error(t)}var pp=34028234663852886e22,mp=-34028234663852886e22,hp=4294967295,gp=2147483647,_p=-2147483648;function vp(e){if(typeof e!=`number`)throw Error(`invalid int 32: `+typeof e);if(!Number.isInteger(e)||e>gp||e<_p)throw Error(`invalid int 32: `+e)}function yp(e){if(typeof e!=`number`)throw Error(`invalid uint 32: `+typeof e);if(!Number.isInteger(e)||e>hp||e<0)throw Error(`invalid uint 32: `+e)}function bp(e){if(typeof e!=`number`)throw Error(`invalid float 32: `+typeof e);if(Number.isFinite(e)&&(e>pp||e<mp))throw Error(`invalid float 32: `+e)}var xp=Symbol(`@bufbuild/protobuf/enum-type`);function Sp(e){let t=e[xp];return fp(t,`missing enum type on enum object`),t}function Cp(e,t,n,r){e[xp]=wp(t,n.map(t=>({no:t.no,name:t.name,localName:e[t.no]})))}function wp(e,t,n){let r=Object.create(null),i=Object.create(null),a=[];for(let e of t){let t=Ep(e);a.push(t),r[e.name]=t,i[e.no]=t}return{typeName:e,values:a,findName(e){return r[e]},findNumber(e){return i[e]}}}function Tp(e,t,n){let r={};for(let e of t){let t=Ep(e);r[t.localName]=t.no,r[t.no]=t.localName}return Cp(r,e,t),r}function Ep(e){return`localName`in e?e:Object.assign(Object.assign({},e),{localName:e.name})}var Dp=class{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){let n=this.getType().runtime.bin,r=n.makeReadOptions(t);return n.readMessage(this,r.readerFactory(e),e.byteLength,r),this}fromJson(e,t){let n=this.getType(),r=n.runtime.json,i=r.makeReadOptions(t);return r.readMessage(n,e,i,this),this}fromJsonString(e,t){let n;try{n=JSON.parse(e)}catch(e){throw Error(`cannot decode ${this.getType().typeName} from JSON: ${e instanceof Error?e.message:String(e)}`)}return this.fromJson(n,t)}toBinary(e){let t=this.getType().runtime.bin,n=t.makeWriteOptions(e),r=n.writerFactory();return t.writeMessage(this,r,n),r.finish()}toJson(e){let t=this.getType().runtime.json,n=t.makeWriteOptions(e);return t.writeMessage(this,n)}toJsonString(e){let t=this.toJson(e);return JSON.stringify(t,null,e?.prettySpaces??0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}};function Op(e,t,n,r){let i=r?.localName??t.substring(t.lastIndexOf(`.`)+1),a={[i]:function(t){e.util.initFields(this),e.util.initPartial(t,this)}}[i];return Object.setPrototypeOf(a.prototype,new Dp),Object.assign(a,{runtime:e,typeName:t,fields:e.util.newFieldList(n),fromBinary(e,t){return new a().fromBinary(e,t)},fromJson(e,t){return new a().fromJson(e,t)},fromJsonString(e,t){return new a().fromJsonString(e,t)},equals(t,n){return e.util.equals(a,t,n)}}),a}function kp(){let e=0,t=0;for(let n=0;n<28;n+=7){let r=this.buf[this.pos++];if(e|=(r&127)<<n,!(r&128))return this.assertBounds(),[e,t]}let n=this.buf[this.pos++];if(e|=(n&15)<<28,t=(n&112)>>4,!(n&128))return this.assertBounds(),[e,t];for(let n=3;n<=31;n+=7){let r=this.buf[this.pos++];if(t|=(r&127)<<n,!(r&128))return this.assertBounds(),[e,t]}throw Error(`invalid varint`)}function Ap(e,t,n){for(let r=0;r<28;r+=7){let i=e>>>r,a=!(!(i>>>7)&&t==0),o=(a?i|128:i)&255;if(n.push(o),!a)return}let r=e>>>28&15|(t&7)<<4,i=!!(t>>3);if(n.push((i?r|128:r)&255),i){for(let e=3;e<31;e+=7){let r=t>>>e,i=!!(r>>>7),a=(i?r|128:r)&255;if(n.push(a),!i)return}n.push(t>>>31&1)}}var jp=4294967296;function Mp(e){let t=e[0]===`-`;t&&(e=e.slice(1));let n=1e6,r=0,i=0;function a(t,a){let o=Number(e.slice(t,a));i*=n,r=r*n+o,r>=jp&&(i+=r/jp|0,r%=jp)}return a(-24,-18),a(-18,-12),a(-12,-6),a(-6),t?Lp(r,i):Ip(r,i)}function Np(e,t){let n=Ip(e,t),r=n.hi&2147483648;r&&(n=Lp(n.lo,n.hi));let i=Pp(n.lo,n.hi);return r?`-`+i:i}function Pp(e,t){if({lo:e,hi:t}=Fp(e,t),t<=2097151)return String(jp*t+e);let n=e&16777215,r=(e>>>24|t<<8)&16777215,i=t>>16&65535,a=n+r*6777216+i*6710656,o=r+i*8147497,s=i*2,c=1e7;return a>=c&&(o+=Math.floor(a/c),a%=c),o>=c&&(s+=Math.floor(o/c),o%=c),s.toString()+Rp(o)+Rp(a)}function Fp(e,t){return{lo:e>>>0,hi:t>>>0}}function Ip(e,t){return{lo:e|0,hi:t|0}}function Lp(e,t){return t=~t,e?e=~e+1:t+=1,Ip(e,t)}var Rp=e=>{let t=String(e);return`0000000`.slice(t.length)+t};function zp(e,t){if(e>=0){for(;e>127;)t.push(e&127|128),e>>>=7;t.push(e)}else{for(let n=0;n<9;n++)t.push(e&127|128),e>>=7;t.push(1)}}function Bp(){let e=this.buf[this.pos++],t=e&127;if(!(e&128)||(e=this.buf[this.pos++],t|=(e&127)<<7,!(e&128))||(e=this.buf[this.pos++],t|=(e&127)<<14,!(e&128))||(e=this.buf[this.pos++],t|=(e&127)<<21,!(e&128)))return this.assertBounds(),t;e=this.buf[this.pos++],t|=(e&15)<<28;for(let t=5;e&128&&t<10;t++)e=this.buf[this.pos++];if(e&128)throw Error(`invalid varint`);return this.assertBounds(),t>>>0}function Vp(){let e=new DataView(new ArrayBuffer(8));if(typeof BigInt==`function`&&typeof e.getBigInt64==`function`&&typeof e.getBigUint64==`function`&&typeof e.setBigInt64==`function`&&typeof e.setBigUint64==`function`&&(typeof process!=`object`||typeof process.env!=`object`||process.env.BUF_BIGINT_DISABLE!==`1`)){let t=BigInt(`-9223372036854775808`),n=BigInt(`9223372036854775807`),r=BigInt(`0`),i=BigInt(`18446744073709551615`);return{zero:BigInt(0),supported:!0,parse(e){let r=typeof e==`bigint`?e:BigInt(e);if(r>n||r<t)throw Error(`int64 invalid: ${e}`);return r},uParse(e){let t=typeof e==`bigint`?e:BigInt(e);if(t>i||t<r)throw Error(`uint64 invalid: ${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,n){return e.setInt32(0,t,!0),e.setInt32(4,n,!0),e.getBigInt64(0,!0)},uDec(t,n){return e.setInt32(0,t,!0),e.setInt32(4,n,!0),e.getBigUint64(0,!0)}}}let t=e=>fp(/^-?[0-9]+$/.test(e),`int64 invalid: ${e}`),n=e=>fp(/^[0-9]+$/.test(e),`uint64 invalid: ${e}`);return{zero:`0`,supported:!1,parse(e){return typeof e!=`string`&&(e=e.toString()),t(e),e},uParse(e){return typeof e!=`string`&&(e=e.toString()),n(e),e},enc(e){return typeof e!=`string`&&(e=e.toString()),t(e),Mp(e)},uEnc(e){return typeof e!=`string`&&(e=e.toString()),n(e),Mp(e)},dec(e,t){return Np(e,t)},uDec(e,t){return Pp(e,t)}}}var Hp=Vp(),N;(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`})(N||={});var Up;(function(e){e[e.BIGINT=0]=`BIGINT`,e[e.STRING=1]=`STRING`})(Up||={});function Wp(e,t,n){if(t===n)return!0;if(e==N.BYTES){if(!(t instanceof Uint8Array)||!(n instanceof Uint8Array)||t.length!==n.length)return!1;for(let e=0;e<t.length;e++)if(t[e]!==n[e])return!1;return!0}switch(e){case N.UINT64:case N.FIXED64:case N.INT64:case N.SFIXED64:case N.SINT64:return t==n}return!1}function Gp(e,t){switch(e){case N.BOOL:return!1;case N.UINT64:case N.FIXED64:case N.INT64:case N.SFIXED64:case N.SINT64:return t==0?Hp.zero:`0`;case N.DOUBLE:case N.FLOAT:return 0;case N.BYTES:return new Uint8Array;case N.STRING:return``;default:return 0}}function Kp(e,t){switch(e){case N.BOOL:return t===!1;case N.STRING:return t===``;case N.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return t==0}}var qp;(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`})(qp||={});var Jp=class{constructor(e){this.stack=[],this.textEncoder=e??new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let t=0;t<this.chunks.length;t++)e+=this.chunks[t].length;let t=new Uint8Array(e),n=0;for(let e=0;e<this.chunks.length;e++)t.set(this.chunks[e],n),n+=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(yp(e);e>127;)this.buf.push(e&127|128),e>>>=7;return this.buf.push(e),this}int32(e){return vp(e),zp(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){bp(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){yp(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){vp(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return vp(e),e=(e<<1^e>>31)>>>0,zp(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),r=Hp.enc(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),r=Hp.uEnc(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(t)}int64(e){let t=Hp.enc(e);return Ap(t.lo,t.hi,this.buf),this}sint64(e){let t=Hp.enc(e),n=t.hi>>31;return Ap(t.lo<<1^n,(t.hi<<1|t.lo>>>31)^n,this.buf),this}uint64(e){let t=Hp.uEnc(e);return Ap(t.lo,t.hi,this.buf),this}},Yp=class{constructor(e,t){this.varint64=kp,this.uint32=Bp,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=t??new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,n=e&7;if(t<=0||n<0||n>5)throw Error(`illegal tag: field no `+t+` wire type `+n);return[t,n]}skip(e,t){let n=this.pos;switch(e){case qp.Varint:for(;this.buf[this.pos++]&128;);break;case qp.Bit64:this.pos+=4;case qp.Bit32:this.pos+=4;break;case qp.LengthDelimited:let n=this.uint32();this.pos+=n;break;case qp.StartGroup:for(;;){let[e,n]=this.tag();if(n===qp.EndGroup){if(t!==void 0&&e!==t)throw Error(`invalid end group tag`);break}this.skip(n,e)}break;default:throw Error(`cant skip wire type `+e)}return this.assertBounds(),this.buf.subarray(n,this.pos)}assertBounds(){if(this.pos>this.len)throw RangeError(`premature EOF`)}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return Hp.dec(...this.varint64())}uint64(){return Hp.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),n=-(e&1);return e=(e>>>1|(t&1)<<31)^n,t=t>>>1^n,Hp.dec(e,t)}bool(){let[e,t]=this.varint64();return e!==0||t!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return Hp.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return Hp.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 Xp(e,t,n,r){let i;return{typeName:t,extendee:n,get field(){if(!i){let n=typeof r==`function`?r():r;n.name=t.split(`.`).pop(),n.jsonName=`[${t}]`,i=e.util.newFieldList([n]).list()[0]}return i},runtime:e}}function Zp(e){let t=e.field.localName,n=Object.create(null);return n[t]=Qp(e),[n,()=>n[t]]}function Qp(e){let t=e.field;if(t.repeated)return[];if(t.default!==void 0)return t.default;switch(t.kind){case`enum`:return t.T.values[0].no;case`scalar`:return Gp(t.T,t.L);case`message`:let e=t.T,n=new e;return e.fieldWrapper?e.fieldWrapper.unwrapField(n):n;case`map`:throw`map fields are not allowed to be extensions`}}function $p(e,t){if(!t.repeated&&(t.kind==`enum`||t.kind==`scalar`)){for(let n=e.length-1;n>=0;--n)if(e[n].no==t.no)return[e[n]];return[]}return e.filter(e=>e.no===t.no)}var em=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`.split(``),tm=[];for(let e=0;e<em.length;e++)tm[em[e].charCodeAt(0)]=e;tm[45]=em.indexOf(`+`),tm[95]=em.indexOf(`/`);var nm={dec(e){let t=e.length*3/4;e[e.length-2]==`=`?t-=2:e[e.length-1]==`=`&&--t;let n=new Uint8Array(t),r=0,i=0,a,o=0;for(let t=0;t<e.length;t++){if(a=tm[e.charCodeAt(t)],a===void 0)switch(e[t]){case`=`:i=0;case`
26
- `:case`\r`:case` `:case` `:continue;default:throw Error(`invalid base64 string.`)}switch(i){case 0:o=a,i=1;break;case 1:n[r++]=o<<2|(a&48)>>4,o=a,i=2;break;case 2:n[r++]=(o&15)<<4|(a&60)>>2,o=a,i=3;break;case 3:n[r++]=(o&3)<<6|a,i=0;break}}if(i==1)throw Error(`invalid base64 string.`);return n.subarray(0,r)},enc(e){let t=``,n=0,r,i=0;for(let a=0;a<e.length;a++)switch(r=e[a],n){case 0:t+=em[r>>2],i=(r&3)<<4,n=1;break;case 1:t+=em[i|r>>4],i=(r&15)<<2,n=2;break;case 2:t+=em[i|r>>6],t+=em[r&63],n=0;break}return n&&(t+=em[i],t+=`=`,n==1&&(t+=`=`)),t}};function rm(e,t,n){om(t,e);let r=t.runtime.bin.makeReadOptions(n),i=$p(e.getType().runtime.bin.listUnknownFields(e),t.field),[a,o]=Zp(t);for(let e of i)t.runtime.bin.readField(a,r.readerFactory(e.data),t.field,e.wireType,r);return o()}function im(e,t,n,r){om(t,e);let i=t.runtime.bin.makeReadOptions(r),a=t.runtime.bin.makeWriteOptions(r);if(am(e,t)){let n=e.getType().runtime.bin.listUnknownFields(e).filter(e=>e.no!=t.field.no);e.getType().runtime.bin.discardUnknownFields(e);for(let t of n)e.getType().runtime.bin.onUnknownField(e,t.no,t.wireType,t.data)}let o=a.writerFactory(),s=t.field;!s.opt&&!s.repeated&&(s.kind==`enum`||s.kind==`scalar`)&&(s=Object.assign(Object.assign({},t.field),{opt:!0})),t.runtime.bin.writeField(s,n,o,a);let c=i.readerFactory(o.finish());for(;c.pos<c.len;){let[t,n]=c.tag(),r=c.skip(n,t);e.getType().runtime.bin.onUnknownField(e,t,n,r)}}function am(e,t){let n=e.getType();return t.extendee.typeName===n.typeName&&!!n.runtime.bin.listUnknownFields(e).find(e=>e.no==t.field.no)}function om(e,t){fp(e.extendee.typeName==t.getType().typeName,`extension ${e.typeName} can only be applied to message ${e.extendee.typeName}`)}function sm(e,t){let n=e.localName;if(e.repeated)return t[n].length>0;if(e.oneof)return t[e.oneof.localName].case===n;switch(e.kind){case`enum`:case`scalar`:return e.opt||e.req?t[n]!==void 0:e.kind==`enum`?t[n]!==e.T.values[0].no:!Kp(e.T,t[n]);case`message`:return t[n]!==void 0;case`map`:return Object.keys(t[n]).length>0}}function cm(e,t){let n=e.localName,r=!e.opt&&!e.req;if(e.repeated)t[n]=[];else if(e.oneof)t[e.oneof.localName]={case:void 0};else switch(e.kind){case`map`:t[n]={};break;case`enum`:t[n]=r?e.T.values[0].no:void 0;break;case`scalar`:t[n]=r?Gp(e.T,e.L):void 0;break;case`message`:t[n]=void 0;break}}function lm(e,t){if(typeof e!=`object`||!e||!Object.getOwnPropertyNames(Dp.prototype).every(t=>t in e&&typeof e[t]==`function`))return!1;let n=e.getType();return n===null||typeof n!=`function`||!(`typeName`in n)||typeof n.typeName!=`string`?!1:t===void 0?!0:n.typeName==t.typeName}function um(e,t){return lm(t)||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}N.DOUBLE,N.FLOAT,N.INT64,N.UINT64,N.INT32,N.UINT32,N.BOOL,N.STRING,N.BYTES;var dm={ignoreUnknownFields:!1},fm={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function pm(e){return e?Object.assign(Object.assign({},dm),e):dm}function mm(e){return e?Object.assign(Object.assign({},fm),e):fm}var hm=Symbol(),gm=Symbol();function _m(){return{makeReadOptions:pm,makeWriteOptions:mm,readMessage(e,t,n,r){if(t==null||Array.isArray(t)||typeof t!=`object`)throw Error(`cannot decode message ${e.typeName} from JSON: ${vm(t)}`);r??=new e;let i=new Map,a=n.typeRegistry;for(let[o,s]of Object.entries(t)){let t=e.fields.findJsonName(o);if(t){if(t.oneof){if(s===null&&t.kind==`scalar`)continue;let n=i.get(t.oneof);if(n!==void 0)throw Error(`cannot decode message ${e.typeName} from JSON: multiple keys for oneof "${t.oneof.name}" present: "${n}", "${o}"`);i.set(t.oneof,o)}ym(r,s,t,n,e)}else{let t=!1;if(a?.findExtension&&o.startsWith(`[`)&&o.endsWith(`]`)){let i=a.findExtension(o.substring(1,o.length-1));if(i&&i.extendee.typeName==e.typeName){t=!0;let[e,a]=Zp(i);ym(e,s,i.field,n,i),im(r,i,a(),n)}}if(!t&&!n.ignoreUnknownFields)throw Error(`cannot decode message ${e.typeName} from JSON: key "${o}" is unknown`)}}return r},writeMessage(e,t){let n=e.getType(),r={},i;try{for(i of n.fields.byNumber()){if(!sm(i,e)){if(i.req)throw`required field not set`;if(!t.emitDefaultValues||!Cm(i))continue}let n=i.oneof?e[i.oneof.localName].value:e[i.localName],a=wm(i,n,t);a!==void 0&&(r[t.useProtoFieldName?i.name:i.jsonName]=a)}let a=t.typeRegistry;if(a?.findExtensionFor)for(let i of n.runtime.bin.listUnknownFields(e)){let o=a.findExtensionFor(n.typeName,i.no);if(o&&am(e,o)){let n=rm(e,o,t),i=wm(o.field,n,t);i!==void 0&&(r[o.field.jsonName]=i)}}}catch(e){let t=i?`cannot encode field ${n.typeName}.${i.name} to JSON`:`cannot encode message ${n.typeName} to JSON`,r=e instanceof Error?e.message:String(e);throw Error(t+(r.length>0?`: ${r}`:``))}return r},readScalar(e,t,n){return xm(e,t,n??Up.BIGINT,!0)},writeScalar(e,t,n){if(t!==void 0&&(n||Kp(e,t)))return Em(e,t)},debug:vm}}function vm(e){if(e===null)return`null`;switch(typeof e){case`object`:return Array.isArray(e)?`array`:`object`;case`string`:return e.length>100?`string`:`"${e.split(`"`).join(`\\"`)}"`;default:return String(e)}}function ym(e,t,n,r,i){let a=n.localName;if(n.repeated){if(fp(n.kind!=`map`),t===null)return;if(!Array.isArray(t))throw Error(`cannot decode field ${i.typeName}.${n.name} from JSON: ${vm(t)}`);let o=e[a];for(let e of t){if(e===null)throw Error(`cannot decode field ${i.typeName}.${n.name} from JSON: ${vm(e)}`);switch(n.kind){case`message`:o.push(n.T.fromJson(e,r));break;case`enum`:let t=Sm(n.T,e,r.ignoreUnknownFields,!0);t!==gm&&o.push(t);break;case`scalar`:try{o.push(xm(n.T,e,n.L,!0))}catch(t){let r=`cannot decode field ${i.typeName}.${n.name} from JSON: ${vm(e)}`;throw t instanceof Error&&t.message.length>0&&(r+=`: ${t.message}`),Error(r)}break}}}else if(n.kind==`map`){if(t===null)return;if(typeof t!=`object`||Array.isArray(t))throw Error(`cannot decode field ${i.typeName}.${n.name} from JSON: ${vm(t)}`);let o=e[a];for(let[e,a]of Object.entries(t)){if(a===null)throw Error(`cannot decode field ${i.typeName}.${n.name} from JSON: map value null`);let s;try{s=bm(n.K,e)}catch(e){let r=`cannot decode map key for field ${i.typeName}.${n.name} from JSON: ${vm(t)}`;throw e instanceof Error&&e.message.length>0&&(r+=`: ${e.message}`),Error(r)}switch(n.V.kind){case`message`:o[s]=n.V.T.fromJson(a,r);break;case`enum`:let e=Sm(n.V.T,a,r.ignoreUnknownFields,!0);e!==gm&&(o[s]=e);break;case`scalar`:try{o[s]=xm(n.V.T,a,Up.BIGINT,!0)}catch(e){let r=`cannot decode map value for field ${i.typeName}.${n.name} from JSON: ${vm(t)}`;throw e instanceof Error&&e.message.length>0&&(r+=`: ${e.message}`),Error(r)}break}}}else switch(n.oneof&&(e=e[n.oneof.localName]={case:a},a=`value`),n.kind){case`message`:let o=n.T;if(t===null&&o.typeName!=`google.protobuf.Value`)return;let s=e[a];lm(s)?s.fromJson(t,r):(e[a]=s=o.fromJson(t,r),o.fieldWrapper&&!n.oneof&&(e[a]=o.fieldWrapper.unwrapField(s)));break;case`enum`:let c=Sm(n.T,t,r.ignoreUnknownFields,!1);switch(c){case hm:cm(n,e);break;case gm:break;default:e[a]=c;break}break;case`scalar`:try{let r=xm(n.T,t,n.L,!1);switch(r){case hm:cm(n,e);break;default:e[a]=r;break}}catch(e){let r=`cannot decode field ${i.typeName}.${n.name} from JSON: ${vm(t)}`;throw e instanceof Error&&e.message.length>0&&(r+=`: ${e.message}`),Error(r)}break}}function bm(e,t){if(e===N.BOOL)switch(t){case`true`:t=!0;break;case`false`:t=!1;break}return xm(e,t,Up.BIGINT,!0).toString()}function xm(e,t,n,r){if(t===null)return r?Gp(e,n):hm;switch(e){case N.DOUBLE:case N.FLOAT:if(t===`NaN`)return NaN;if(t===`Infinity`)return 1/0;if(t===`-Infinity`)return-1/0;if(t===``||typeof t==`string`&&t.trim().length!==t.length||typeof t!=`string`&&typeof t!=`number`)break;let r=Number(t);if(Number.isNaN(r)||!Number.isFinite(r))break;return e==N.FLOAT&&bp(r),r;case N.INT32:case N.FIXED32:case N.SFIXED32:case N.SINT32:case N.UINT32:let i;if(typeof t==`number`?i=t:typeof t==`string`&&t.length>0&&t.trim().length===t.length&&(i=Number(t)),i===void 0)break;return e==N.UINT32||e==N.FIXED32?yp(i):vp(i),i;case N.INT64:case N.SFIXED64:case N.SINT64:if(typeof t!=`number`&&typeof t!=`string`)break;let a=Hp.parse(t);return n?a.toString():a;case N.FIXED64:case N.UINT64:if(typeof t!=`number`&&typeof t!=`string`)break;let o=Hp.uParse(t);return n?o.toString():o;case N.BOOL:if(typeof t!=`boolean`)break;return t;case N.STRING:if(typeof t!=`string`)break;return t;case N.BYTES:if(t===``)return new Uint8Array;if(typeof t!=`string`)break;return nm.dec(t)}throw Error()}function Sm(e,t,n,r){if(t===null)return e.typeName==`google.protobuf.NullValue`?0:r?e.values[0].no:hm;switch(typeof t){case`number`:if(Number.isInteger(t))return t;break;case`string`:let r=e.findName(t);if(r!==void 0)return r.no;if(n)return gm;break}throw Error(`cannot decode enum ${e.typeName} from JSON: ${vm(t)}`)}function Cm(e){return e.repeated||e.kind==`map`?!0:!(e.oneof||e.kind==`message`||e.opt||e.req)}function wm(e,t,n){if(e.kind==`map`){fp(typeof t==`object`&&!!t);let r={},i=Object.entries(t);switch(e.V.kind){case`scalar`:for(let[t,n]of i)r[t.toString()]=Em(e.V.T,n);break;case`message`:for(let[e,t]of i)r[e.toString()]=t.toJson(n);break;case`enum`:let t=e.V.T;for(let[e,a]of i)r[e.toString()]=Tm(t,a,n.enumAsInteger);break}return n.emitDefaultValues||i.length>0?r:void 0}if(e.repeated){fp(Array.isArray(t));let r=[];switch(e.kind){case`scalar`:for(let n=0;n<t.length;n++)r.push(Em(e.T,t[n]));break;case`enum`:for(let i=0;i<t.length;i++)r.push(Tm(e.T,t[i],n.enumAsInteger));break;case`message`:for(let e=0;e<t.length;e++)r.push(t[e].toJson(n));break}return n.emitDefaultValues||r.length>0?r:void 0}switch(e.kind){case`scalar`:return Em(e.T,t);case`enum`:return Tm(e.T,t,n.enumAsInteger);case`message`:return um(e.T,t).toJson(n)}}function Tm(e,t,n){return fp(typeof t==`number`),e.typeName==`google.protobuf.NullValue`?null:n?t:e.findNumber(t)?.name??t}function Em(e,t){switch(e){case N.INT32:case N.SFIXED32:case N.SINT32:case N.FIXED32:case N.UINT32:return fp(typeof t==`number`),t;case N.FLOAT:case N.DOUBLE:return fp(typeof t==`number`),Number.isNaN(t)?`NaN`:t===1/0?`Infinity`:t===-1/0?`-Infinity`:t;case N.STRING:return fp(typeof t==`string`),t;case N.BOOL:return fp(typeof t==`boolean`),t;case N.UINT64:case N.FIXED64:case N.INT64:case N.SFIXED64:case N.SINT64:return fp(typeof t==`bigint`||typeof t==`string`||typeof t==`number`),t.toString();case N.BYTES:return fp(t instanceof Uint8Array),nm.enc(t)}}var Dm=Symbol(`@bufbuild/protobuf/unknown-fields`),Om={readUnknownFields:!0,readerFactory:e=>new Yp(e)},km={writeUnknownFields:!0,writerFactory:()=>new Jp};function Am(e){return e?Object.assign(Object.assign({},Om),e):Om}function jm(e){return e?Object.assign(Object.assign({},km),e):km}function Mm(){return{makeReadOptions:Am,makeWriteOptions:jm,listUnknownFields(e){return e[Dm]??[]},discardUnknownFields(e){delete e[Dm]},writeUnknownFields(e,t){let n=e[Dm];if(n)for(let e of n)t.tag(e.no,e.wireType).raw(e.data)},onUnknownField(e,t,n,r){let i=e;Array.isArray(i[Dm])||(i[Dm]=[]),i[Dm].push({no:t,wireType:n,data:r})},readMessage(e,t,n,r,i){let a=e.getType(),o=i?t.len:t.pos+n,s,c;for(;t.pos<o&&([s,c]=t.tag(),!(i===!0&&c==qp.EndGroup));){let n=a.fields.find(s);if(!n){let n=t.skip(c,s);r.readUnknownFields&&this.onUnknownField(e,s,c,n);continue}Nm(e,t,n,c,r)}if(i&&(c!=qp.EndGroup||s!==n))throw Error(`invalid end group tag`)},readField:Nm,writeMessage(e,t,n){let r=e.getType();for(let i of r.fields.byNumber()){if(!sm(i,e)){if(i.req)throw Error(`cannot encode field ${r.typeName}.${i.name} to binary: required field not set`);continue}Rm(i,i.oneof?e[i.oneof.localName].value:e[i.localName],t,n)}return n.writeUnknownFields&&this.writeUnknownFields(e,t),t},writeField(e,t,n,r){t!==void 0&&Rm(e,t,n,r)}}}function Nm(e,t,n,r,i){let{repeated:a,localName:o}=n;switch(n.oneof&&(e=e[n.oneof.localName],e.case!=o&&delete e.value,e.case=o,o=`value`),n.kind){case`scalar`:case`enum`:let s=n.kind==`enum`?N.INT32:n.T,c=Lm;if(n.kind==`scalar`&&n.L>0&&(c=Im),a){let n=e[o];if(r==qp.LengthDelimited&&s!=N.STRING&&s!=N.BYTES){let e=t.uint32()+t.pos;for(;t.pos<e;)n.push(c(t,s))}else n.push(c(t,s))}else e[o]=c(t,s);break;case`message`:let l=n.T;a?e[o].push(Pm(t,new l,i,n)):lm(e[o])?Pm(t,e[o],i,n):(e[o]=Pm(t,new l,i,n),l.fieldWrapper&&!n.oneof&&!n.repeated&&(e[o]=l.fieldWrapper.unwrapField(e[o])));break;case`map`:let[u,d]=Fm(n,t,i);e[o][u]=d;break}}function Pm(e,t,n,r){let i=t.getType().runtime.bin,a=r?.delimited;return i.readMessage(t,e,a?r.no:e.uint32(),n,a),t}function Fm(e,t,n){let r=t.uint32(),i=t.pos+r,a,o;for(;t.pos<i;){let[r]=t.tag();switch(r){case 1:a=Lm(t,e.K);break;case 2:switch(e.V.kind){case`scalar`:o=Lm(t,e.V.T);break;case`enum`:o=t.int32();break;case`message`:o=Pm(t,new e.V.T,n,void 0);break}break}}if(a===void 0&&(a=Gp(e.K,Up.BIGINT)),typeof a!=`string`&&typeof a!=`number`&&(a=a.toString()),o===void 0)switch(e.V.kind){case`scalar`:o=Gp(e.V.T,Up.BIGINT);break;case`enum`:o=e.V.T.values[0].no;break;case`message`:o=new e.V.T;break}return[a,o]}function Im(e,t){let n=Lm(e,t);return typeof n==`bigint`?n.toString():n}function Lm(e,t){switch(t){case N.STRING:return e.string();case N.BOOL:return e.bool();case N.DOUBLE:return e.double();case N.FLOAT:return e.float();case N.INT32:return e.int32();case N.INT64:return e.int64();case N.UINT64:return e.uint64();case N.FIXED64:return e.fixed64();case N.BYTES:return e.bytes();case N.FIXED32:return e.fixed32();case N.SFIXED32:return e.sfixed32();case N.SFIXED64:return e.sfixed64();case N.SINT64:return e.sint64();case N.UINT32:return e.uint32();case N.SINT32:return e.sint32()}}function Rm(e,t,n,r){fp(t!==void 0);let i=e.repeated;switch(e.kind){case`scalar`:case`enum`:let a=e.kind==`enum`?N.INT32:e.T;if(i)if(fp(Array.isArray(t)),e.packed)Hm(n,a,e.no,t);else for(let r of t)Vm(n,a,e.no,r);else Vm(n,a,e.no,t);break;case`message`:if(i){fp(Array.isArray(t));for(let i of t)Bm(n,r,e,i)}else Bm(n,r,e,t);break;case`map`:fp(typeof t==`object`&&!!t);for(let[i,a]of Object.entries(t))zm(n,r,e,i,a);break}}function zm(e,t,n,r,i){e.tag(n.no,qp.LengthDelimited),e.fork();let a=r;switch(n.K){case N.INT32:case N.FIXED32:case N.UINT32:case N.SFIXED32:case N.SINT32:a=Number.parseInt(r);break;case N.BOOL:fp(r==`true`||r==`false`),a=r==`true`;break}switch(Vm(e,n.K,1,a),n.V.kind){case`scalar`:Vm(e,n.V.T,2,i);break;case`enum`:Vm(e,N.INT32,2,i);break;case`message`:fp(i!==void 0),e.tag(2,qp.LengthDelimited).bytes(i.toBinary(t));break}e.join()}function Bm(e,t,n,r){let i=um(n.T,r);n.delimited?e.tag(n.no,qp.StartGroup).raw(i.toBinary(t)).tag(n.no,qp.EndGroup):e.tag(n.no,qp.LengthDelimited).bytes(i.toBinary(t))}function Vm(e,t,n,r){fp(r!==void 0);let[i,a]=Um(t);e.tag(n,i)[a](r)}function Hm(e,t,n,r){if(!r.length)return;e.tag(n,qp.LengthDelimited).fork();let[,i]=Um(t);for(let t=0;t<r.length;t++)e[i](r[t]);e.join()}function Um(e){let t=qp.Varint;switch(e){case N.BYTES:case N.STRING:t=qp.LengthDelimited;break;case N.DOUBLE:case N.FIXED64:case N.SFIXED64:t=qp.Bit64;break;case N.FIXED32:case N.SFIXED32:case N.FLOAT:t=qp.Bit32;break}let n=N[e].toLowerCase();return[t,n]}function Wm(){return{setEnumType:Cp,initPartial(e,t){if(e===void 0)return;let n=t.getType();for(let r of n.fields.byMember()){let n=r.localName,i=t,a=e;if(a[n]!=null)switch(r.kind){case`oneof`:let e=a[n].case;if(e===void 0)continue;let t=r.findField(e),o=a[n].value;t&&t.kind==`message`&&!lm(o,t.T)?o=new t.T(o):t&&t.kind===`scalar`&&t.T===N.BYTES&&(o=Km(o)),i[n]={case:e,value:o};break;case`scalar`:case`enum`:let s=a[n];r.T===N.BYTES&&(s=r.repeated?s.map(Km):Km(s)),i[n]=s;break;case`map`:switch(r.V.kind){case`scalar`:case`enum`:if(r.V.T===N.BYTES)for(let[e,t]of Object.entries(a[n]))i[n][e]=Km(t);else Object.assign(i[n],a[n]);break;case`message`:let e=r.V.T;for(let t of Object.keys(a[n])){let r=a[n][t];e.fieldWrapper||(r=new e(r)),i[n][t]=r}break}break;case`message`:let c=r.T;if(r.repeated)i[n]=a[n].map(e=>lm(e,c)?e:new c(e));else{let e=a[n];c.fieldWrapper?c.typeName===`google.protobuf.BytesValue`?i[n]=Km(e):i[n]=e:i[n]=lm(e,c)?e:new c(e)}break}}},equals(e,t,n){return t===n?!0:!t||!n?!1:e.fields.byMember().every(e=>{let r=t[e.localName],i=n[e.localName];if(e.repeated){if(r.length!==i.length)return!1;switch(e.kind){case`message`:return r.every((t,n)=>e.T.equals(t,i[n]));case`scalar`:return r.every((t,n)=>Wp(e.T,t,i[n]));case`enum`:return r.every((e,t)=>Wp(N.INT32,e,i[t]))}throw Error(`repeated cannot contain ${e.kind}`)}switch(e.kind){case`message`:let t=r,n=i;return e.T.fieldWrapper&&(t!==void 0&&!lm(t)&&(t=e.T.fieldWrapper.wrapField(t)),n!==void 0&&!lm(n)&&(n=e.T.fieldWrapper.wrapField(n))),e.T.equals(t,n);case`enum`:return Wp(N.INT32,r,i);case`scalar`:return Wp(e.T,r,i);case`oneof`:if(r.case!==i.case)return!1;let a=e.findField(r.case);if(a===void 0)return!0;switch(a.kind){case`message`:return a.T.equals(r.value,i.value);case`enum`:return Wp(N.INT32,r.value,i.value);case`scalar`:return Wp(a.T,r.value,i.value)}throw Error(`oneof cannot contain ${a.kind}`);case`map`:let o=Object.keys(r).concat(Object.keys(i));switch(e.V.kind){case`message`:let t=e.V.T;return o.every(e=>t.equals(r[e],i[e]));case`enum`:return o.every(e=>Wp(N.INT32,r[e],i[e]));case`scalar`:let n=e.V.T;return o.every(e=>Wp(n,r[e],i[e]))}break}})},clone(e){let t=e.getType(),n=new t,r=n;for(let n of t.fields.byMember()){let t=e[n.localName],i;if(n.repeated)i=t.map(Gm);else if(n.kind==`map`){i=r[n.localName];for(let[e,n]of Object.entries(t))i[e]=Gm(n)}else i=n.kind==`oneof`?n.findField(t.case)?{case:t.case,value:Gm(t.value)}:{case:void 0}:Gm(t);r[n.localName]=i}for(let n of t.runtime.bin.listUnknownFields(e))t.runtime.bin.onUnknownField(r,n.no,n.wireType,n.data);return n}}}function Gm(e){if(e===void 0)return e;if(lm(e))return e.clone();if(e instanceof Uint8Array){let t=new Uint8Array(e.byteLength);return t.set(e),t}return e}function Km(e){return e instanceof Uint8Array?e:new Uint8Array(e)}function qm(e,t,n){return{syntax:e,json:_m(),bin:Mm(),util:Object.assign(Object.assign({},Wm()),{newFieldList:t,initFields:n}),makeMessageType(e,t,n){return Op(this,e,t,n)},makeEnum:Tp,makeEnumType:wp,getEnumType:Sp,makeExtension(e,t,n){return Xp(this,e,t,n)}}}var Jm=class{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._normalizer(this._fields),this.all}byNumber(){return this.numbersAsc||=this.list().concat().sort((e,t)=>e.no-t.no),this.numbersAsc}byMember(){if(!this.members){this.members=[];let e=this.members,t;for(let n of this.list())n.oneof?n.oneof!==t&&(t=n.oneof,e.push(t)):e.push(n)}return this.members}};function Ym(e,t){let n=Qm(e);return t?n:rh(nh(n))}function Xm(e){return Ym(e,!1)}var Zm=Qm;function Qm(e){let t=!1,n=[];for(let r=0;r<e.length;r++){let i=e.charAt(r);switch(i){case`_`:t=!0;break;case`0`:case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:n.push(i),t=!1;break;default:t&&(t=!1,i=i.toUpperCase()),n.push(i);break}}return n.join(``)}var $m=new Set([`constructor`,`toString`,`toJSON`,`valueOf`]),eh=new Set([`getType`,`clone`,`equals`,`fromBinary`,`fromJson`,`fromJsonString`,`toBinary`,`toJson`,`toJsonString`,`toObject`]),th=e=>`${e}\$`,nh=e=>eh.has(e)?th(e):e,rh=e=>$m.has(e)?th(e):e,ih=class{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=Xm(e)}addField(e){fp(e.oneof===this,`field ${e.name} not one of ${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]}};function ah(e,t){let n=[],r;for(let t of typeof e==`function`?e():e){let e=t;if(e.localName=Ym(t.name,t.oneof!==void 0),e.jsonName=t.jsonName??Zm(t.name),e.repeated=t.repeated??!1,t.kind==`scalar`&&(e.L=t.L??Up.BIGINT),e.delimited=t.delimited??!1,e.req=t.req??!1,e.opt=t.opt??!1,t.packed===void 0&&(e.packed=t.kind==`enum`||t.kind==`scalar`&&t.T!=N.BYTES&&t.T!=N.STRING),t.oneof!==void 0){let n=typeof t.oneof==`string`?t.oneof:t.oneof.name;(!r||r.name!=n)&&(r=new ih(n)),e.oneof=r,r.addField(e)}n.push(e)}return n}var P=qm(`proto3`,e=>new Jm(e,e=>ah(e)),e=>{for(let t of e.getType().fields.byMember()){if(t.opt)continue;let n=t.localName,r=e;if(t.repeated){r[n]=[];continue}switch(t.kind){case`oneof`:r[n]={case:void 0};break;case`enum`:r[n]=0;break;case`map`:r[n]={};break;case`scalar`:r[n]=Gp(t.T,t.L);break}}}),oh=class e extends Dp{constructor(e){super(),this.seconds=Hp.zero,this.nanos=0,P.util.initPartial(e,this)}fromJson(e,t){if(typeof e!=`string`)throw Error(`cannot decode google.protobuf.Timestamp from JSON: ${P.json.debug(e)}`);let n=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!n)throw Error(`cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string`);let r=Date.parse(n[1]+`-`+n[2]+`-`+n[3]+`T`+n[4]+`:`+n[5]+`:`+n[6]+(n[8]?n[8]:`Z`));if(Number.isNaN(r))throw Error(`cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string`);if(r<Date.parse(`0001-01-01T00:00:00Z`)||r>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=Hp.parse(r/1e3),this.nanos=0,n[7]&&(this.nanos=parseInt(`1`+n[7]+`0`.repeat(9-n[7].length))-1e9),this}toJson(e){let t=Number(this.seconds)*1e3;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 n=`Z`;if(this.nanos>0){let e=(this.nanos+1e9).toString().substring(1);n=e.substring(3)===`000000`?`.`+e.substring(0,3)+`Z`:e.substring(6)===`000`?`.`+e.substring(0,6)+`Z`:`.`+e+`Z`}return new Date(t).toISOString().replace(`.000Z`,n)}toDate(){return new Date(Number(this.seconds)*1e3+Math.ceil(this.nanos/1e6))}static now(){return e.fromDate(new Date)}static fromDate(t){let n=t.getTime();return new e({seconds:Hp.parse(Math.floor(n/1e3)),nanos:n%1e3*1e6})}static fromBinary(t,n){return new e().fromBinary(t,n)}static fromJson(t,n){return new e().fromJson(t,n)}static fromJsonString(t,n){return new e().fromJsonString(t,n)}static equals(t,n){return P.util.equals(e,t,n)}};oh.runtime=P,oh.typeName=`google.protobuf.Timestamp`,oh.fields=P.util.newFieldList(()=>[{no:1,name:`seconds`,kind:`scalar`,T:3},{no:2,name:`nanos`,kind:`scalar`,T:5}]);var sh=P.makeMessageType(`livekit.MetricsBatch`,()=>[{no:1,name:`timestamp_ms`,kind:`scalar`,T:3},{no:2,name:`normalized_timestamp`,kind:`message`,T:oh},{no:3,name:`str_data`,kind:`scalar`,T:9,repeated:!0},{no:4,name:`time_series`,kind:`message`,T:ch,repeated:!0},{no:5,name:`events`,kind:`message`,T:uh,repeated:!0}]),ch=P.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:lh,repeated:!0},{no:5,name:`rid`,kind:`scalar`,T:13}]),lh=P.makeMessageType(`livekit.MetricSample`,()=>[{no:1,name:`timestamp_ms`,kind:`scalar`,T:3},{no:2,name:`normalized_timestamp`,kind:`message`,T:oh},{no:3,name:`value`,kind:`scalar`,T:2}]),uh=P.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:oh},{no:7,name:`normalized_end_timestamp`,kind:`message`,T:oh,opt:!0},{no:8,name:`metadata`,kind:`scalar`,T:9},{no:9,name:`rid`,kind:`scalar`,T:13}]),dh=P.makeEnum(`livekit.BackupCodecPolicy`,[{no:0,name:`PREFER_REGRESSION`},{no:1,name:`SIMULCAST`},{no:2,name:`REGRESSION`}]),fh=P.makeEnum(`livekit.TrackType`,[{no:0,name:`AUDIO`},{no:1,name:`VIDEO`},{no:2,name:`DATA`}]),ph=P.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`}]),mh=P.makeEnum(`livekit.VideoQuality`,[{no:0,name:`LOW`},{no:1,name:`MEDIUM`},{no:2,name:`HIGH`},{no:3,name:`OFF`}]),hh=P.makeEnum(`livekit.ConnectionQuality`,[{no:0,name:`POOR`},{no:1,name:`GOOD`},{no:2,name:`EXCELLENT`},{no:3,name:`LOST`}]),gh=P.makeEnum(`livekit.ClientConfigSetting`,[{no:0,name:`UNSET`},{no:1,name:`DISABLED`},{no:2,name:`ENABLED`}]),_h=P.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`}]),vh=P.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`}]),yh=P.makeEnum(`livekit.SubscriptionError`,[{no:0,name:`SE_UNKNOWN`},{no:1,name:`SE_CODEC_UNSUPPORTED`},{no:2,name:`SE_TRACK_NOTFOUND`}]),bh=P.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`}]),xh=P.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:Sh,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:rg}]),Sh=P.makeMessageType(`livekit.Codec`,()=>[{no:1,name:`mime`,kind:`scalar`,T:9},{no:2,name:`fmtp_line`,kind:`scalar`,T:9}]),Ch=P.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:P.getEnumType(ph),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}]),wh=P.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:P.getEnumType(Th)},{no:4,name:`tracks`,kind:`message`,T:kh,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:Ch},{no:12,name:`region`,kind:`scalar`,T:9},{no:13,name:`is_publisher`,kind:`scalar`,T:8},{no:14,name:`kind`,kind:`enum`,T:P.getEnumType(Eh)},{no:15,name:`attributes`,kind:`map`,K:9,V:{kind:`scalar`,T:9}},{no:16,name:`disconnect_reason`,kind:`enum`,T:P.getEnumType(_h)},{no:18,name:`kind_details`,kind:`enum`,T:P.getEnumType(Dh),repeated:!0},{no:19,name:`data_tracks`,kind:`message`,T:Ah,repeated:!0}]),Th=P.makeEnum(`livekit.ParticipantInfo.State`,[{no:0,name:`JOINING`},{no:1,name:`JOINED`},{no:2,name:`ACTIVE`},{no:3,name:`DISCONNECTED`}]),Eh=P.makeEnum(`livekit.ParticipantInfo.Kind`,[{no:0,name:`STANDARD`},{no:1,name:`INGRESS`},{no:2,name:`EGRESS`},{no:3,name:`SIP`},{no:4,name:`AGENT`},{no:7,name:`CONNECTOR`},{no:8,name:`BRIDGE`}]),Dh=P.makeEnum(`livekit.ParticipantInfo.KindDetail`,[{no:0,name:`CLOUD_AGENT`},{no:1,name:`FORWARDED`},{no:2,name:`CONNECTOR_WHATSAPP`},{no:3,name:`CONNECTOR_TWILIO`},{no:4,name:`BRIDGE_RTSP`}]),F=P.makeEnum(`livekit.Encryption.Type`,[{no:0,name:`NONE`},{no:1,name:`GCM`},{no:2,name:`CUSTOM`}]),Oh=P.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:Mh,repeated:!0},{no:5,name:`video_layer_mode`,kind:`enum`,T:P.getEnumType(Nh)},{no:6,name:`sdp_cid`,kind:`scalar`,T:9}]),kh=P.makeMessageType(`livekit.TrackInfo`,()=>[{no:1,name:`sid`,kind:`scalar`,T:9},{no:2,name:`type`,kind:`enum`,T:P.getEnumType(fh)},{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:P.getEnumType(ph)},{no:10,name:`layers`,kind:`message`,T:Mh,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:Oh,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:P.getEnumType(F)},{no:17,name:`stream`,kind:`scalar`,T:9},{no:18,name:`version`,kind:`message`,T:rg},{no:19,name:`audio_features`,kind:`enum`,T:P.getEnumType(bh),repeated:!0},{no:20,name:`backup_codec_policy`,kind:`enum`,T:P.getEnumType(dh)}]),Ah=P.makeMessageType(`livekit.DataTrackInfo`,()=>[{no:1,name:`pub_handle`,kind:`scalar`,T:13},{no:2,name:`sid`,kind:`scalar`,T:9},{no:3,name:`name`,kind:`scalar`,T:9},{no:4,name:`encryption`,kind:`enum`,T:P.getEnumType(F)}]),jh=P.makeMessageType(`livekit.DataTrackSubscriptionOptions`,()=>[{no:1,name:`target_fps`,kind:`scalar`,T:13,opt:!0}]),Mh=P.makeMessageType(`livekit.VideoLayer`,()=>[{no:1,name:`quality`,kind:`enum`,T:P.getEnumType(mh)},{no:2,name:`width`,kind:`scalar`,T:13},{no:3,name:`height`,kind:`scalar`,T:13},{no:4,name:`bitrate`,kind:`scalar`,T:13},{no:5,name:`ssrc`,kind:`scalar`,T:13},{no:6,name:`spatial_layer`,kind:`scalar`,T:5},{no:7,name:`rid`,kind:`scalar`,T:9},{no:8,name:`repair_ssrc`,kind:`scalar`,T:13}]),Nh=P.makeEnum(`livekit.VideoLayer.Mode`,[{no:0,name:`MODE_UNUSED`},{no:1,name:`ONE_SPATIAL_LAYER_PER_STREAM`},{no:2,name:`MULTIPLE_SPATIAL_LAYERS_PER_STREAM`},{no:3,name:`ONE_SPATIAL_LAYER_PER_STREAM_INCOMPLETE_RTCP_SR`}]),Ph=P.makeMessageType(`livekit.DataPacket`,()=>[{no:1,name:`kind`,kind:`enum`,T:P.getEnumType(Fh)},{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:Bh,oneof:`value`},{no:3,name:`speaker`,kind:`message`,T:Rh,oneof:`value`},{no:6,name:`sip_dtmf`,kind:`message`,T:Vh,oneof:`value`},{no:7,name:`transcription`,kind:`message`,T:Hh,oneof:`value`},{no:8,name:`metrics`,kind:`message`,T:sh,oneof:`value`},{no:9,name:`chat_message`,kind:`message`,T:Wh,oneof:`value`},{no:10,name:`rpc_request`,kind:`message`,T:Gh,oneof:`value`},{no:11,name:`rpc_ack`,kind:`message`,T:Kh,oneof:`value`},{no:12,name:`rpc_response`,kind:`message`,T:qh,oneof:`value`},{no:13,name:`stream_header`,kind:`message`,T:sg,oneof:`value`},{no:14,name:`stream_chunk`,kind:`message`,T:cg,oneof:`value`},{no:15,name:`stream_trailer`,kind:`message`,T:lg,oneof:`value`},{no:18,name:`encrypted_packet`,kind:`message`,T:Ih,oneof:`value`},{no:16,name:`sequence`,kind:`scalar`,T:13},{no:17,name:`participant_sid`,kind:`scalar`,T:9}]),Fh=P.makeEnum(`livekit.DataPacket.Kind`,[{no:0,name:`RELIABLE`},{no:1,name:`LOSSY`}]),Ih=P.makeMessageType(`livekit.EncryptedPacket`,()=>[{no:1,name:`encryption_type`,kind:`enum`,T:P.getEnumType(F)},{no:2,name:`iv`,kind:`scalar`,T:12},{no:3,name:`key_index`,kind:`scalar`,T:13},{no:4,name:`encrypted_value`,kind:`scalar`,T:12}]),Lh=P.makeMessageType(`livekit.EncryptedPacketPayload`,()=>[{no:1,name:`user`,kind:`message`,T:Bh,oneof:`value`},{no:3,name:`chat_message`,kind:`message`,T:Wh,oneof:`value`},{no:4,name:`rpc_request`,kind:`message`,T:Gh,oneof:`value`},{no:5,name:`rpc_ack`,kind:`message`,T:Kh,oneof:`value`},{no:6,name:`rpc_response`,kind:`message`,T:qh,oneof:`value`},{no:7,name:`stream_header`,kind:`message`,T:sg,oneof:`value`},{no:8,name:`stream_chunk`,kind:`message`,T:cg,oneof:`value`},{no:9,name:`stream_trailer`,kind:`message`,T:lg,oneof:`value`}]),Rh=P.makeMessageType(`livekit.ActiveSpeakerUpdate`,()=>[{no:1,name:`speakers`,kind:`message`,T:zh,repeated:!0}]),zh=P.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}]),Bh=P.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}]),Vh=P.makeMessageType(`livekit.SipDTMF`,()=>[{no:3,name:`code`,kind:`scalar`,T:13},{no:4,name:`digit`,kind:`scalar`,T:9}]),Hh=P.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:Uh,repeated:!0}]),Uh=P.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}]),Wh=P.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}]),Gh=P.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}]),Kh=P.makeMessageType(`livekit.RpcAck`,()=>[{no:1,name:`request_id`,kind:`scalar`,T:9}]),qh=P.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:Jh,oneof:`value`}]),Jh=P.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}]),Yh=P.makeMessageType(`livekit.ParticipantTracks`,()=>[{no:1,name:`participant_sid`,kind:`scalar`,T:9},{no:2,name:`track_sids`,kind:`scalar`,T:9,repeated:!0}]),Xh=P.makeMessageType(`livekit.ServerInfo`,()=>[{no:1,name:`edition`,kind:`enum`,T:P.getEnumType(Zh)},{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}]),Zh=P.makeEnum(`livekit.ServerInfo.Edition`,[{no:0,name:`Standard`},{no:1,name:`Cloud`}]),Qh=P.makeMessageType(`livekit.ClientInfo`,()=>[{no:1,name:`sdk`,kind:`enum`,T:P.getEnumType($h)},{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}]),$h=P.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`}]),eg=P.makeMessageType(`livekit.ClientConfiguration`,()=>[{no:1,name:`video`,kind:`message`,T:tg},{no:2,name:`screen`,kind:`message`,T:tg},{no:3,name:`resume_connection`,kind:`enum`,T:P.getEnumType(gh)},{no:4,name:`disabled_codecs`,kind:`message`,T:ng},{no:5,name:`force_relay`,kind:`enum`,T:P.getEnumType(gh)}]),tg=P.makeMessageType(`livekit.VideoConfiguration`,()=>[{no:1,name:`hardware_encoder`,kind:`enum`,T:P.getEnumType(gh)}]),ng=P.makeMessageType(`livekit.DisabledCodecs`,()=>[{no:1,name:`codecs`,kind:`message`,T:Sh,repeated:!0},{no:2,name:`publish`,kind:`message`,T:Sh,repeated:!0}]),rg=P.makeMessageType(`livekit.TimedVersion`,()=>[{no:1,name:`unix_micro`,kind:`scalar`,T:3},{no:2,name:`ticks`,kind:`scalar`,T:5}]),ig=P.makeEnum(`livekit.DataStream.OperationType`,[{no:0,name:`CREATE`},{no:1,name:`UPDATE`},{no:2,name:`DELETE`},{no:3,name:`REACTION`}]),ag=P.makeMessageType(`livekit.DataStream.TextHeader`,()=>[{no:1,name:`operation_type`,kind:`enum`,T:P.getEnumType(ig)},{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`}),og=P.makeMessageType(`livekit.DataStream.ByteHeader`,()=>[{no:1,name:`name`,kind:`scalar`,T:9}],{localName:`DataStream_ByteHeader`}),sg=P.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:P.getEnumType(F)},{no:8,name:`attributes`,kind:`map`,K:9,V:{kind:`scalar`,T:9}},{no:9,name:`text_header`,kind:`message`,T:ag,oneof:`content_header`},{no:10,name:`byte_header`,kind:`message`,T:og,oneof:`content_header`}],{localName:`DataStream_Header`}),cg=P.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`}),lg=P.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`}),ug=P.makeMessageType(`livekit.SubscribedAudioCodec`,()=>[{no:1,name:`codec`,kind:`scalar`,T:9},{no:2,name:`enabled`,kind:`scalar`,T:8}]),dg=P.makeEnum(`livekit.SignalTarget`,[{no:0,name:`PUBLISHER`},{no:1,name:`SUBSCRIBER`}]),fg=P.makeEnum(`livekit.StreamState`,[{no:0,name:`ACTIVE`},{no:1,name:`PAUSED`}]),pg=P.makeEnum(`livekit.CandidateProtocol`,[{no:0,name:`UDP`},{no:1,name:`TCP`},{no:2,name:`TLS`}]),mg=P.makeMessageType(`livekit.SignalRequest`,()=>[{no:1,name:`offer`,kind:`message`,T:Ag,oneof:`message`},{no:2,name:`answer`,kind:`message`,T:Ag,oneof:`message`},{no:3,name:`trickle`,kind:`message`,T:wg,oneof:`message`},{no:4,name:`add_track`,kind:`message`,T:_g,oneof:`message`},{no:5,name:`mute`,kind:`message`,T:Tg,oneof:`message`},{no:6,name:`subscription`,kind:`message`,T:Mg,oneof:`message`},{no:7,name:`track_setting`,kind:`message`,T:Fg,oneof:`message`},{no:8,name:`leave`,kind:`message`,T:Rg,oneof:`message`},{no:10,name:`update_layers`,kind:`message`,T:Bg,oneof:`message`},{no:11,name:`subscription_permission`,kind:`message`,T:e_,oneof:`message`},{no:12,name:`sync_state`,kind:`message`,T:r_,oneof:`message`},{no:13,name:`simulate`,kind:`message`,T:o_,oneof:`message`},{no:14,name:`ping`,kind:`scalar`,T:3,oneof:`message`},{no:15,name:`update_metadata`,kind:`message`,T:Vg,oneof:`message`},{no:16,name:`ping_req`,kind:`message`,T:s_,oneof:`message`},{no:17,name:`update_audio_track`,kind:`message`,T:Ig,oneof:`message`},{no:18,name:`update_video_track`,kind:`message`,T:Lg,oneof:`message`},{no:19,name:`publish_data_track_request`,kind:`message`,T:vg,oneof:`message`},{no:20,name:`unpublish_data_track_request`,kind:`message`,T:bg,oneof:`message`},{no:21,name:`update_data_subscription`,kind:`message`,T:Ng,oneof:`message`}]),hg=P.makeMessageType(`livekit.SignalResponse`,()=>[{no:1,name:`join`,kind:`message`,T:Eg,oneof:`message`},{no:2,name:`answer`,kind:`message`,T:Ag,oneof:`message`},{no:3,name:`offer`,kind:`message`,T:Ag,oneof:`message`},{no:4,name:`trickle`,kind:`message`,T:wg,oneof:`message`},{no:5,name:`update`,kind:`message`,T:jg,oneof:`message`},{no:6,name:`track_published`,kind:`message`,T:Og,oneof:`message`},{no:8,name:`leave`,kind:`message`,T:Rg,oneof:`message`},{no:9,name:`mute`,kind:`message`,T:Tg,oneof:`message`},{no:10,name:`speakers_changed`,kind:`message`,T:Ug,oneof:`message`},{no:11,name:`room_update`,kind:`message`,T:Wg,oneof:`message`},{no:12,name:`connection_quality`,kind:`message`,T:Kg,oneof:`message`},{no:13,name:`stream_state_update`,kind:`message`,T:Jg,oneof:`message`},{no:14,name:`subscribed_quality_update`,kind:`message`,T:Zg,oneof:`message`},{no:15,name:`subscription_permission_update`,kind:`message`,T:t_,oneof:`message`},{no:16,name:`refresh_token`,kind:`scalar`,T:9,oneof:`message`},{no:17,name:`track_unpublished`,kind:`message`,T:kg,oneof:`message`},{no:18,name:`pong`,kind:`scalar`,T:3,oneof:`message`},{no:19,name:`reconnect`,kind:`message`,T:Dg,oneof:`message`},{no:20,name:`pong_resp`,kind:`message`,T:c_,oneof:`message`},{no:21,name:`subscription_response`,kind:`message`,T:d_,oneof:`message`},{no:22,name:`request_response`,kind:`message`,T:f_,oneof:`message`},{no:23,name:`track_subscribed`,kind:`message`,T:m_,oneof:`message`},{no:24,name:`room_moved`,kind:`message`,T:n_,oneof:`message`},{no:25,name:`media_sections_requirement`,kind:`message`,T:y_,oneof:`message`},{no:26,name:`subscribed_audio_codec_update`,kind:`message`,T:Qg,oneof:`message`},{no:27,name:`publish_data_track_response`,kind:`message`,T:yg,oneof:`message`},{no:28,name:`unpublish_data_track_response`,kind:`message`,T:xg,oneof:`message`},{no:29,name:`data_track_subscriber_handles`,kind:`message`,T:Sg,oneof:`message`}]),gg=P.makeMessageType(`livekit.SimulcastCodec`,()=>[{no:1,name:`codec`,kind:`scalar`,T:9},{no:2,name:`cid`,kind:`scalar`,T:9},{no:4,name:`layers`,kind:`message`,T:Mh,repeated:!0},{no:5,name:`video_layer_mode`,kind:`enum`,T:P.getEnumType(Nh)}]),_g=P.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:P.getEnumType(fh)},{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:P.getEnumType(ph)},{no:9,name:`layers`,kind:`message`,T:Mh,repeated:!0},{no:10,name:`simulcast_codecs`,kind:`message`,T:gg,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:P.getEnumType(F)},{no:15,name:`stream`,kind:`scalar`,T:9},{no:16,name:`backup_codec_policy`,kind:`enum`,T:P.getEnumType(dh)},{no:17,name:`audio_features`,kind:`enum`,T:P.getEnumType(bh),repeated:!0}]),vg=P.makeMessageType(`livekit.PublishDataTrackRequest`,()=>[{no:1,name:`pub_handle`,kind:`scalar`,T:13},{no:2,name:`name`,kind:`scalar`,T:9},{no:3,name:`encryption`,kind:`enum`,T:P.getEnumType(F)}]),yg=P.makeMessageType(`livekit.PublishDataTrackResponse`,()=>[{no:1,name:`info`,kind:`message`,T:Ah}]),bg=P.makeMessageType(`livekit.UnpublishDataTrackRequest`,()=>[{no:1,name:`pub_handle`,kind:`scalar`,T:13}]),xg=P.makeMessageType(`livekit.UnpublishDataTrackResponse`,()=>[{no:1,name:`info`,kind:`message`,T:Ah}]),Sg=P.makeMessageType(`livekit.DataTrackSubscriberHandles`,()=>[{no:1,name:`sub_handles`,kind:`map`,K:13,V:{kind:`message`,T:Cg}}]),Cg=P.makeMessageType(`livekit.DataTrackSubscriberHandles.PublishedDataTrack`,()=>[{no:1,name:`publisher_identity`,kind:`scalar`,T:9},{no:2,name:`publisher_sid`,kind:`scalar`,T:9},{no:3,name:`track_sid`,kind:`scalar`,T:9}],{localName:`DataTrackSubscriberHandles_PublishedDataTrack`}),wg=P.makeMessageType(`livekit.TrickleRequest`,()=>[{no:1,name:`candidateInit`,kind:`scalar`,T:9},{no:2,name:`target`,kind:`enum`,T:P.getEnumType(dg)},{no:3,name:`final`,kind:`scalar`,T:8}]),Tg=P.makeMessageType(`livekit.MuteTrackRequest`,()=>[{no:1,name:`sid`,kind:`scalar`,T:9},{no:2,name:`muted`,kind:`scalar`,T:8}]),Eg=P.makeMessageType(`livekit.JoinResponse`,()=>[{no:1,name:`room`,kind:`message`,T:xh},{no:2,name:`participant`,kind:`message`,T:wh},{no:3,name:`other_participants`,kind:`message`,T:wh,repeated:!0},{no:4,name:`server_version`,kind:`scalar`,T:9},{no:5,name:`ice_servers`,kind:`message`,T:Hg,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:eg},{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:Xh},{no:13,name:`sif_trailer`,kind:`scalar`,T:12},{no:14,name:`enabled_publish_codecs`,kind:`message`,T:Sh,repeated:!0},{no:15,name:`fast_publish`,kind:`scalar`,T:8}]),Dg=P.makeMessageType(`livekit.ReconnectResponse`,()=>[{no:1,name:`ice_servers`,kind:`message`,T:Hg,repeated:!0},{no:2,name:`client_configuration`,kind:`message`,T:eg},{no:3,name:`server_info`,kind:`message`,T:Xh},{no:4,name:`last_message_seq`,kind:`scalar`,T:13}]),Og=P.makeMessageType(`livekit.TrackPublishedResponse`,()=>[{no:1,name:`cid`,kind:`scalar`,T:9},{no:2,name:`track`,kind:`message`,T:kh}]),kg=P.makeMessageType(`livekit.TrackUnpublishedResponse`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9}]),Ag=P.makeMessageType(`livekit.SessionDescription`,()=>[{no:1,name:`type`,kind:`scalar`,T:9},{no:2,name:`sdp`,kind:`scalar`,T:9},{no:3,name:`id`,kind:`scalar`,T:13},{no:4,name:`mid_to_track_id`,kind:`map`,K:9,V:{kind:`scalar`,T:9}}]),jg=P.makeMessageType(`livekit.ParticipantUpdate`,()=>[{no:1,name:`participants`,kind:`message`,T:wh,repeated:!0}]),Mg=P.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:Yh,repeated:!0}]),Ng=P.makeMessageType(`livekit.UpdateDataSubscription`,()=>[{no:1,name:`updates`,kind:`message`,T:Pg,repeated:!0}]),Pg=P.makeMessageType(`livekit.UpdateDataSubscription.Update`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`subscribe`,kind:`scalar`,T:8},{no:3,name:`options`,kind:`message`,T:jh}],{localName:`UpdateDataSubscription_Update`}),Fg=P.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:P.getEnumType(mh)},{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}]),Ig=P.makeMessageType(`livekit.UpdateLocalAudioTrack`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`features`,kind:`enum`,T:P.getEnumType(bh),repeated:!0}]),Lg=P.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}]),Rg=P.makeMessageType(`livekit.LeaveRequest`,()=>[{no:1,name:`can_reconnect`,kind:`scalar`,T:8},{no:2,name:`reason`,kind:`enum`,T:P.getEnumType(_h)},{no:3,name:`action`,kind:`enum`,T:P.getEnumType(zg)},{no:4,name:`regions`,kind:`message`,T:l_}]),zg=P.makeEnum(`livekit.LeaveRequest.Action`,[{no:0,name:`DISCONNECT`},{no:1,name:`RESUME`},{no:2,name:`RECONNECT`}]),Bg=P.makeMessageType(`livekit.UpdateVideoLayers`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`layers`,kind:`message`,T:Mh,repeated:!0}]),Vg=P.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}]),Hg=P.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}]),Ug=P.makeMessageType(`livekit.SpeakersChanged`,()=>[{no:1,name:`speakers`,kind:`message`,T:zh,repeated:!0}]),Wg=P.makeMessageType(`livekit.RoomUpdate`,()=>[{no:1,name:`room`,kind:`message`,T:xh}]),Gg=P.makeMessageType(`livekit.ConnectionQualityInfo`,()=>[{no:1,name:`participant_sid`,kind:`scalar`,T:9},{no:2,name:`quality`,kind:`enum`,T:P.getEnumType(hh)},{no:3,name:`score`,kind:`scalar`,T:2}]),Kg=P.makeMessageType(`livekit.ConnectionQualityUpdate`,()=>[{no:1,name:`updates`,kind:`message`,T:Gg,repeated:!0}]),qg=P.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:P.getEnumType(fg)}]),Jg=P.makeMessageType(`livekit.StreamStateUpdate`,()=>[{no:1,name:`stream_states`,kind:`message`,T:qg,repeated:!0}]),Yg=P.makeMessageType(`livekit.SubscribedQuality`,()=>[{no:1,name:`quality`,kind:`enum`,T:P.getEnumType(mh)},{no:2,name:`enabled`,kind:`scalar`,T:8}]),Xg=P.makeMessageType(`livekit.SubscribedCodec`,()=>[{no:1,name:`codec`,kind:`scalar`,T:9},{no:2,name:`qualities`,kind:`message`,T:Yg,repeated:!0}]),Zg=P.makeMessageType(`livekit.SubscribedQualityUpdate`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`subscribed_qualities`,kind:`message`,T:Yg,repeated:!0},{no:3,name:`subscribed_codecs`,kind:`message`,T:Xg,repeated:!0}]),Qg=P.makeMessageType(`livekit.SubscribedAudioCodecUpdate`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`subscribed_audio_codecs`,kind:`message`,T:ug,repeated:!0}]),$g=P.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}]),e_=P.makeMessageType(`livekit.SubscriptionPermission`,()=>[{no:1,name:`all_participants`,kind:`scalar`,T:8},{no:2,name:`track_permissions`,kind:`message`,T:$g,repeated:!0}]),t_=P.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}]),n_=P.makeMessageType(`livekit.RoomMovedResponse`,()=>[{no:1,name:`room`,kind:`message`,T:xh},{no:2,name:`token`,kind:`scalar`,T:9},{no:3,name:`participant`,kind:`message`,T:wh},{no:4,name:`other_participants`,kind:`message`,T:wh,repeated:!0}]),r_=P.makeMessageType(`livekit.SyncState`,()=>[{no:1,name:`answer`,kind:`message`,T:Ag},{no:2,name:`subscription`,kind:`message`,T:Mg},{no:3,name:`publish_tracks`,kind:`message`,T:Og,repeated:!0},{no:4,name:`data_channels`,kind:`message`,T:a_,repeated:!0},{no:5,name:`offer`,kind:`message`,T:Ag},{no:6,name:`track_sids_disabled`,kind:`scalar`,T:9,repeated:!0},{no:7,name:`datachannel_receive_states`,kind:`message`,T:i_,repeated:!0},{no:8,name:`publish_data_tracks`,kind:`message`,T:yg,repeated:!0}]),i_=P.makeMessageType(`livekit.DataChannelReceiveState`,()=>[{no:1,name:`publisher_sid`,kind:`scalar`,T:9},{no:2,name:`last_seq`,kind:`scalar`,T:13}]),a_=P.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:P.getEnumType(dg)}]),o_=P.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:P.getEnumType(pg),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`}]),s_=P.makeMessageType(`livekit.Ping`,()=>[{no:1,name:`timestamp`,kind:`scalar`,T:3},{no:2,name:`rtt`,kind:`scalar`,T:3}]),c_=P.makeMessageType(`livekit.Pong`,()=>[{no:1,name:`last_ping_timestamp`,kind:`scalar`,T:3},{no:2,name:`timestamp`,kind:`scalar`,T:3}]),l_=P.makeMessageType(`livekit.RegionSettings`,()=>[{no:1,name:`regions`,kind:`message`,T:u_,repeated:!0}]),u_=P.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}]),d_=P.makeMessageType(`livekit.SubscriptionResponse`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`err`,kind:`enum`,T:P.getEnumType(yh)}]),f_=P.makeMessageType(`livekit.RequestResponse`,()=>[{no:1,name:`request_id`,kind:`scalar`,T:13},{no:2,name:`reason`,kind:`enum`,T:P.getEnumType(p_)},{no:3,name:`message`,kind:`scalar`,T:9},{no:4,name:`trickle`,kind:`message`,T:wg,oneof:`request`},{no:5,name:`add_track`,kind:`message`,T:_g,oneof:`request`},{no:6,name:`mute`,kind:`message`,T:Tg,oneof:`request`},{no:7,name:`update_metadata`,kind:`message`,T:Vg,oneof:`request`},{no:8,name:`update_audio_track`,kind:`message`,T:Ig,oneof:`request`},{no:9,name:`update_video_track`,kind:`message`,T:Lg,oneof:`request`},{no:10,name:`publish_data_track`,kind:`message`,T:vg,oneof:`request`},{no:11,name:`unpublish_data_track`,kind:`message`,T:bg,oneof:`request`}]),p_=P.makeEnum(`livekit.RequestResponse.Reason`,[{no:0,name:`OK`},{no:1,name:`NOT_FOUND`},{no:2,name:`NOT_ALLOWED`},{no:3,name:`LIMIT_EXCEEDED`},{no:4,name:`QUEUED`},{no:5,name:`UNSUPPORTED_TYPE`},{no:6,name:`UNCLASSIFIED_ERROR`},{no:7,name:`INVALID_HANDLE`},{no:8,name:`INVALID_NAME`},{no:9,name:`DUPLICATE_HANDLE`},{no:10,name:`DUPLICATE_NAME`}]),m_=P.makeMessageType(`livekit.TrackSubscribed`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9}]),h_=P.makeMessageType(`livekit.ConnectionSettings`,()=>[{no:1,name:`auto_subscribe`,kind:`scalar`,T:8},{no:2,name:`adaptive_stream`,kind:`scalar`,T:8},{no:3,name:`subscriber_allow_pause`,kind:`scalar`,T:8,opt:!0},{no:4,name:`disable_ice_lite`,kind:`scalar`,T:8},{no:5,name:`auto_subscribe_data_track`,kind:`scalar`,T:8,opt:!0}]),g_=P.makeMessageType(`livekit.JoinRequest`,()=>[{no:1,name:`client_info`,kind:`message`,T:Qh},{no:2,name:`connection_settings`,kind:`message`,T:h_},{no:3,name:`metadata`,kind:`scalar`,T:9},{no:4,name:`participant_attributes`,kind:`map`,K:9,V:{kind:`scalar`,T:9}},{no:5,name:`add_track_requests`,kind:`message`,T:_g,repeated:!0},{no:6,name:`publisher_offer`,kind:`message`,T:Ag},{no:7,name:`reconnect`,kind:`scalar`,T:8},{no:8,name:`reconnect_reason`,kind:`enum`,T:P.getEnumType(vh)},{no:9,name:`participant_sid`,kind:`scalar`,T:9},{no:10,name:`sync_state`,kind:`message`,T:r_}]),__=P.makeMessageType(`livekit.WrappedJoinRequest`,()=>[{no:1,name:`compression`,kind:`enum`,T:P.getEnumType(v_)},{no:2,name:`join_request`,kind:`scalar`,T:12}]),v_=P.makeEnum(`livekit.WrappedJoinRequest.Compression`,[{no:0,name:`NONE`},{no:1,name:`GZIP`}]),y_=P.makeMessageType(`livekit.MediaSectionsRequirement`,()=>[{no:1,name:`num_audios`,kind:`scalar`,T:13},{no:2,name:`num_videos`,kind:`scalar`,T:13}]);function b_(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,`default`)?e.default:e}var x_={exports:{}},S_=x_.exports,C_;function w_(){return C_?x_.exports:(C_=1,(function(e){(function(t,n){e.exports?e.exports=n():t.log=n()})(S_,function(){var e=function(){},t=`undefined`,n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),r=[`trace`,`debug`,`info`,`warn`,`error`],i={},a=null;function o(e,t){var n=e[t];if(typeof n.bind==`function`)return n.bind(e);try{return Function.prototype.bind.call(n,e)}catch{return function(){return Function.prototype.apply.apply(n,[e,arguments])}}}function s(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(r){return r===`debug`&&(r=`log`),typeof console===t?!1:r===`trace`&&n?s:console[r]===void 0?console.log===void 0?e:o(console,`log`):o(console,r)}function l(){for(var n=this.getLevel(),i=0;i<r.length;i++){var a=r[i];this[a]=i<n?e:this.methodFactory(a,n,this.name)}if(this.log=this.debug,typeof console===t&&n<this.levels.SILENT)return`No console available for logging`}function u(e){return function(){typeof console!==t&&(l.call(this),this[e].apply(this,arguments))}}function d(e,t,n){return c(e)||u.apply(this,arguments)}function f(e,n){var o=this,s,c,u,f=`loglevel`;typeof e==`string`?f+=`:`+e:typeof e==`symbol`&&(f=void 0);function p(e){var n=(r[e]||`silent`).toUpperCase();if(!(typeof window===t||!f)){try{window.localStorage[f]=n;return}catch{}try{window.document.cookie=encodeURIComponent(f)+`=`+n+`;`}catch{}}}function m(){var e;if(!(typeof window===t||!f)){try{e=window.localStorage[f]}catch{}if(typeof e===t)try{var n=window.document.cookie,r=encodeURIComponent(f),i=n.indexOf(r+`=`);i!==-1&&(e=/^([^;]+)/.exec(n.slice(i+r.length+1))[1])}catch{}return o.levels[e]===void 0&&(e=void 0),e}}function h(){if(!(typeof window===t||!f)){try{window.localStorage.removeItem(f)}catch{}try{window.document.cookie=encodeURIComponent(f)+`=; expires=Thu, 01 Jan 1970 00:00:00 UTC`}catch{}}}function g(e){var t=e;if(typeof t==`string`&&o.levels[t.toUpperCase()]!==void 0&&(t=o.levels[t.toUpperCase()]),typeof t==`number`&&t>=0&&t<=o.levels.SILENT)return t;throw TypeError(`log.setLevel() called with invalid level: `+e)}o.name=e,o.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},o.methodFactory=n||d,o.getLevel=function(){return u??c??s},o.setLevel=function(e,t){return u=g(e),t!==!1&&p(u),l.call(o)},o.setDefaultLevel=function(e){c=g(e),m()||o.setLevel(e,!1)},o.resetLevel=function(){u=null,h(),l.call(o)},o.enableAll=function(e){o.setLevel(o.levels.TRACE,e)},o.disableAll=function(e){o.setLevel(o.levels.SILENT,e)},o.rebuild=function(){if(a!==o&&(s=g(a.getLevel())),l.call(o),a===o)for(var e in i)i[e].rebuild()},s=g(a?a.getLevel():`WARN`);var _=m();_!=null&&(u=g(_)),l.call(o)}a=new f,a.getLogger=function(e){if(typeof e!=`symbol`&&typeof e!=`string`||e===``)throw TypeError(`You must supply a name when creating a logger.`);var t=i[e];return t||=i[e]=new f(e,a.methodFactory),t};var p=typeof window===t?void 0:window.log;return a.noConflict=function(){return typeof window!==t&&window.log===a&&(window.log=p),a},a.getLoggers=function(){return i},a.default=a,a})})(x_),x_.exports)}var T_=w_(),E_;(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`})(E_||={});var D_;(function(e){e.Default=`livekit`,e.Room=`livekit-room`,e.TokenSource=`livekit-token-source`,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`,e.DataTracks=`livekit-data-tracks`})(D_||={});var I=T_.getLogger(`livekit`);Object.values(D_).map(e=>T_.getLogger(e)),I.setDefaultLevel(E_.info);function O_(e){let t=T_.getLogger(e);return t.setDefaultLevel(I.getLevel()),t}var k_=T_.getLogger(`lk-e2ee`),A_=7e3,j_=[0,300,4*300,9*300,16*300,A_,A_,A_,A_,A_],M_=class{constructor(e){this._retryDelays=e===void 0?j_:[...e]}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;let t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+Math.random()*1e3}};function N_(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols==`function`)for(var i=0,r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]]);return n}function L(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})}function P_(e){var t=typeof Symbol==`function`&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length==`number`)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw TypeError(t?`Object is not iterable.`:`Symbol.iterator is not defined.`)}function F_(e){return this instanceof F_?(this.v=e,this):new F_(e)}function I_(e,t,n){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var r=n.apply(e,t||[]),i,a=[];return i=Object.create((typeof AsyncIterator==`function`?AsyncIterator:Object).prototype),s(`next`),s(`throw`),s(`return`,o),i[Symbol.asyncIterator]=function(){return this},i;function o(e){return function(t){return Promise.resolve(t).then(e,d)}}function s(e,t){r[e]&&(i[e]=function(t){return new Promise(function(n,r){a.push([e,t,n,r])>1||c(e,t)})},t&&(i[e]=t(i[e])))}function c(e,t){try{l(r[e](t))}catch(e){f(a[0][3],e)}}function l(e){e.value instanceof F_?Promise.resolve(e.value.v).then(u,d):f(a[0][2],e)}function u(e){c(`next`,e)}function d(e){c(`throw`,e)}function f(e,t){e(t),a.shift(),a.length&&c(a[0][0],a[0][1])}}function L_(e){var t,n;return t={},r(`next`),r(`throw`,function(e){throw e}),r(`return`),t[Symbol.iterator]=function(){return this},t;function r(r,i){t[r]=e[r]?function(t){return(n=!n)?{value:F_(e[r](t)),done:!1}:i?i(t):t}:i}}function R_(e){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var t=e[Symbol.asyncIterator],n;return t?t.call(e):(e=typeof P_==`function`?P_(e):e[Symbol.iterator](),n={},r(`next`),r(`throw`),r(`return`),n[Symbol.asyncIterator]=function(){return this},n);function r(t){n[t]=e[t]&&function(n){return new Promise(function(r,a){n=e[t](n),i(r,a,n.done,n.value)})}}function i(e,t,n,r){Promise.resolve(r).then(function(t){e({value:t,done:n})},t)}}var z_={exports:{}},B_;function V_(){if(B_)return z_.exports;B_=1;var e=typeof Reflect==`object`?Reflect:null,t=e&&typeof e.apply==`function`?e.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)},n=e&&typeof e.ownKeys==`function`?e.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};function r(e){console&&console.warn&&console.warn(e)}var i=Number.isNaN||function(e){return e!==e};function a(){a.init.call(this)}z_.exports=a,z_.exports.once=_,a.EventEmitter=a,a.prototype._events=void 0,a.prototype._eventsCount=0,a.prototype._maxListeners=void 0;var o=10;function s(e){if(typeof e!=`function`)throw TypeError(`The "listener" argument must be of type Function. Received type `+typeof e)}Object.defineProperty(a,`defaultMaxListeners`,{enumerable:!0,get:function(){return o},set:function(e){if(typeof e!=`number`||e<0||i(e))throw RangeError(`The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received `+e+`.`);o=e}}),a.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},a.prototype.setMaxListeners=function(e){if(typeof e!=`number`||e<0||i(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};function c(e){return e._maxListeners===void 0?a.defaultMaxListeners:e._maxListeners}a.prototype.getMaxListeners=function(){return c(this)},a.prototype.emit=function(e){for(var n=[],r=1;r<arguments.length;r++)n.push(arguments[r]);var i=e===`error`,a=this._events;if(a!==void 0)i&&=a.error===void 0;else if(!i)return!1;if(i){var o;if(n.length>0&&(o=n[0]),o instanceof Error)throw o;var s=Error(`Unhandled error.`+(o?` (`+o.message+`)`:``));throw s.context=o,s}var c=a[e];if(c===void 0)return!1;if(typeof c==`function`)t(c,this,n);else for(var l=c.length,u=m(c,l),r=0;r<l;++r)t(u[r],this,n);return!0};function l(e,t,n,i){var a,o,l;if(s(n),o=e._events,o===void 0?(o=e._events=Object.create(null),e._eventsCount=0):(o.newListener!==void 0&&(e.emit(`newListener`,t,n.listener?n.listener:n),o=e._events),l=o[t]),l===void 0)l=o[t]=n,++e._eventsCount;else if(typeof l==`function`?l=o[t]=i?[n,l]:[l,n]:i?l.unshift(n):l.push(n),a=c(e),a>0&&l.length>a&&!l.warned){l.warned=!0;var u=Error(`Possible EventEmitter memory leak detected. `+l.length+` `+String(t)+` listeners added. Use emitter.setMaxListeners() to increase limit`);u.name=`MaxListenersExceededWarning`,u.emitter=e,u.type=t,u.count=l.length,r(u)}return e}a.prototype.addListener=function(e,t){return l(this,e,t,!1)},a.prototype.on=a.prototype.addListener,a.prototype.prependListener=function(e,t){return l(this,e,t,!0)};function u(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function d(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},i=u.bind(r);return i.listener=n,r.wrapFn=i,i}a.prototype.once=function(e,t){return s(t),this.on(e,d(this,e,t)),this},a.prototype.prependOnceListener=function(e,t){return s(t),this.prependListener(e,d(this,e,t)),this},a.prototype.removeListener=function(e,t){var n,r,i,a,o;if(s(t),r=this._events,r===void 0||(n=r[e],n===void 0))return this;if(n===t||n.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete r[e],r.removeListener&&this.emit(`removeListener`,e,n.listener||t));else if(typeof n!=`function`){for(i=-1,a=n.length-1;a>=0;a--)if(n[a]===t||n[a].listener===t){o=n[a].listener,i=a;break}if(i<0)return this;i===0?n.shift():h(n,i),n.length===1&&(r[e]=n[0]),r.removeListener!==void 0&&this.emit(`removeListener`,e,o||t)}return this},a.prototype.off=a.prototype.removeListener,a.prototype.removeAllListeners=function(e){var t,n=this._events,r;if(n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var i=Object.keys(n),a;for(r=0;r<i.length;++r)a=i[r],a!==`removeListener`&&this.removeAllListeners(a);return this.removeAllListeners(`removeListener`),this._events=Object.create(null),this._eventsCount=0,this}if(t=n[e],typeof t==`function`)this.removeListener(e,t);else if(t!==void 0)for(r=t.length-1;r>=0;r--)this.removeListener(e,t[r]);return this};function f(e,t,n){var r=e._events;if(r===void 0)return[];var i=r[t];return i===void 0?[]:typeof i==`function`?n?[i.listener||i]:[i]:n?g(i):m(i,i.length)}a.prototype.listeners=function(e){return f(this,e,!0)},a.prototype.rawListeners=function(e){return f(this,e,!1)},a.listenerCount=function(e,t){return typeof e.listenerCount==`function`?e.listenerCount(t):p.call(e,t)},a.prototype.listenerCount=p;function p(e){var t=this._events;if(t!==void 0){var n=t[e];if(typeof n==`function`)return 1;if(n!==void 0)return n.length}return 0}a.prototype.eventNames=function(){return this._eventsCount>0?n(this._events):[]};function m(e,t){for(var n=Array(t),r=0;r<t;++r)n[r]=e[r];return n}function h(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}function g(e){for(var t=Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}function _(e,t){return new Promise(function(n,r){function i(n){e.removeListener(t,a),r(n)}function a(){typeof e.removeListener==`function`&&e.removeListener(`error`,i),n([].slice.call(arguments))}y(e,t,a,{once:!0}),t!==`error`&&v(e,i,{once:!0})})}function v(e,t,n){typeof e.on==`function`&&y(e,`error`,t,n)}function y(e,t,n,r){if(typeof e.on==`function`)r.once?e.once(t,n):e.on(t,n);else if(typeof e.addEventListener==`function`)e.addEventListener(t,function i(a){r.once&&e.removeEventListener(t,i),n(a)});else throw TypeError(`The "emitter" argument must be of type EventEmitter. Received type `+typeof e)}return z_.exports}var H_=V_(),U_=!0,W_=!0;function G_(e,t,n){let r=e.match(t);return r&&r.length>=n&&parseFloat(r[n],10)}function K_(e,t,n){if(!e.RTCPeerConnection)return;let r=e.RTCPeerConnection.prototype,i=r.addEventListener;r.addEventListener=function(e,r){if(e!==t)return i.apply(this,arguments);let a=e=>{let t=n(e);t&&(r.handleEvent?r.handleEvent(t):r(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(r,a),i.apply(this,[e,a])};let a=r.removeEventListener;r.removeEventListener=function(e,n){if(e!==t||!this._eventMap||!this._eventMap[t]||!this._eventMap[t].has(n))return a.apply(this,arguments);let r=this._eventMap[t].get(n);return this._eventMap[t].delete(n),this._eventMap[t].size===0&&delete this._eventMap[t],Object.keys(this._eventMap).length===0&&delete this._eventMap,a.apply(this,[e,r])},Object.defineProperty(r,`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 q_(e){return typeof e==`boolean`?(U_=e,e?`adapter.js logging disabled`:`adapter.js logging enabled`):Error(`Argument type: `+typeof e+`. Please use a boolean.`)}function J_(e){return typeof e==`boolean`?(W_=!e,`adapter.js deprecation warnings `+(e?`disabled`:`enabled`)):Error(`Argument type: `+typeof e+`. Please use a boolean.`)}function Y_(){if(typeof window==`object`){if(U_)return;typeof console<`u`&&typeof console.log==`function`&&console.log.apply(console,arguments)}}function X_(e,t){W_&&console.warn(e+` is deprecated, please use `+t+` instead.`)}function Z_(e){let t={browser:null,version:null};if(e===void 0||!e.navigator||!e.navigator.userAgent)return t.browser=`Not a browser.`,t;let{navigator:n}=e;if(n.userAgentData&&n.userAgentData.brands){let e=n.userAgentData.brands.find(e=>e.brand===`Chromium`);if(e)return{browser:`chrome`,version:parseInt(e.version,10)}}if(n.mozGetUserMedia)t.browser=`firefox`,t.version=parseInt(G_(n.userAgent,/Firefox\/(\d+)\./,1));else if(n.webkitGetUserMedia||e.isSecureContext===!1&&e.webkitRTCPeerConnection)t.browser=`chrome`,t.version=parseInt(G_(n.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else if(e.RTCPeerConnection&&n.userAgent.match(/AppleWebKit\/(\d+)\./))t.browser=`safari`,t.version=parseInt(G_(n.userAgent,/AppleWebKit\/(\d+)\./,1)),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&`currentDirection`in e.RTCRtpTransceiver.prototype,t._safariVersion=G_(n.userAgent,/Version\/(\d+(\.?\d+))/,1);else return t.browser=`Not a supported browser.`,t;return t}function Q_(e){return Object.prototype.toString.call(e)===`[object Object]`}function $_(e){return Q_(e)?Object.keys(e).reduce(function(t,n){let r=Q_(e[n]),i=r?$_(e[n]):e[n],a=r&&!Object.keys(i).length;return i===void 0||a?t:Object.assign(t,{[n]:i})},{}):e}function ev(e,t,n){!t||n.has(t.id)||(n.set(t.id,t),Object.keys(t).forEach(r=>{r.endsWith(`Id`)?ev(e,e.get(t[r]),n):r.endsWith(`Ids`)&&t[r].forEach(t=>{ev(e,e.get(t),n)})}))}function tv(e,t,n){let r=n?`outbound-rtp`:`inbound-rtp`,i=new Map;if(t===null)return i;let a=[];return e.forEach(e=>{e.type===`track`&&e.trackIdentifier===t.id&&a.push(e)}),a.forEach(t=>{e.forEach(n=>{n.type===r&&n.trackId===t.id&&ev(e,n,i)})}),i}var nv=Y_;function rv(e,t){let n=e&&e.navigator;if(!n.mediaDevices)return;let r=function(e){if(typeof e!=`object`||e.mandatory||e.optional)return e;let t={};return Object.keys(e).forEach(n=>{if(n===`require`||n===`advanced`||n===`mediaSource`)return;let r=typeof e[n]==`object`?e[n]:{ideal:e[n]};r.exact!==void 0&&typeof r.exact==`number`&&(r.min=r.max=r.exact);let i=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):t===`deviceId`?`sourceId`:t};if(r.ideal!==void 0){t.optional=t.optional||[];let e={};typeof r.ideal==`number`?(e[i(`min`,n)]=r.ideal,t.optional.push(e),e={},e[i(`max`,n)]=r.ideal,t.optional.push(e)):(e[i(``,n)]=r.ideal,t.optional.push(e))}r.exact!==void 0&&typeof r.exact!=`number`?(t.mandatory=t.mandatory||{},t.mandatory[i(``,n)]=r.exact):[`min`,`max`].forEach(e=>{r[e]!==void 0&&(t.mandatory=t.mandatory||{},t.mandatory[i(e,n)]=r[e])})}),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},i=function(e,i){if(t.version>=61)return i(e);if(e=JSON.parse(JSON.stringify(e)),e&&typeof e.audio==`object`){let t=function(e,t,n){t in e&&!(n in e)&&(e[n]=e[t],delete e[t])};e=JSON.parse(JSON.stringify(e)),t(e.audio,`autoGainControl`,`googAutoGainControl`),t(e.audio,`noiseSuppression`,`googNoiseSuppression`),e.audio=r(e.audio)}if(e&&typeof e.video==`object`){let a=e.video.facingMode;a&&=typeof a==`object`?a:{ideal:a};let o=t.version<66;if(a&&(a.exact===`user`||a.exact===`environment`||a.ideal===`user`||a.ideal===`environment`)&&!(n.mediaDevices.getSupportedConstraints&&n.mediaDevices.getSupportedConstraints().facingMode&&!o)){delete e.video.facingMode;let t;if(a.exact===`environment`||a.ideal===`environment`?t=[`back`,`rear`]:(a.exact===`user`||a.ideal===`user`)&&(t=[`front`]),t)return n.mediaDevices.enumerateDevices().then(n=>{n=n.filter(e=>e.kind===`videoinput`);let o=n.find(e=>t.some(t=>e.label.toLowerCase().includes(t)));return!o&&n.length&&t.includes(`back`)&&(o=n[n.length-1]),o&&(e.video.deviceId=a.exact?{exact:o.deviceId}:{ideal:o.deviceId}),e.video=r(e.video),nv(`chrome: `+JSON.stringify(e)),i(e)})}e.video=r(e.video)}return nv(`chrome: `+JSON.stringify(e)),i(e)},a=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(n.getUserMedia=function(e,t,r){i(e,e=>{n.webkitGetUserMedia(e,t,e=>{r&&r(a(e))})})}.bind(n),n.mediaDevices.getUserMedia){let e=n.mediaDevices.getUserMedia.bind(n.mediaDevices);n.mediaDevices.getUserMedia=function(t){return i(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(a(e))))}}}function iv(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function av(e){if(typeof e==`object`&&e.RTCPeerConnection&&!(`ontrack`in e.RTCPeerConnection.prototype)){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`,n=>{let r;r=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===n.track.id):{track:n.track};let i=new Event(`track`);i.track=n.track,i.receiver=r,i.transceiver={receiver:r},i.streams=[t.stream],this.dispatchEvent(i)}),t.stream.getTracks().forEach(n=>{let r;r=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===n.id):{track:n};let i=new Event(`track`);i.track=n,i.receiver=r,i.transceiver={receiver:r},i.streams=[t.stream],this.dispatchEvent(i)})},this.addEventListener(`addstream`,this._ontrackpoly)),t.apply(this,arguments)}}else K_(e,`track`,e=>(e.transceiver||Object.defineProperty(e,`transceiver`,{value:{receiver:e.receiver}}),e))}function ov(e){if(typeof e==`object`&&e.RTCPeerConnection&&!(`getSenders`in e.RTCPeerConnection.prototype)&&`createDTMFSender`in e.RTCPeerConnection.prototype){let t=function(e,t){return{track:t,get dtmf(){return this._dtmf===void 0&&(t.kind===`audio`?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 n=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,r){let i=n.apply(this,arguments);return i||(i=t(this,e),this._senders.push(i)),i};let r=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){r.apply(this,arguments);let t=this._senders.indexOf(e);t!==-1&&this._senders.splice(t,1)}}let n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach(e=>{this._senders.push(t(this,e))})};let r=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],r.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(typeof e==`object`&&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 this._dtmf===void 0&&(this.track.kind===`audio`?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function sv(e){if(!(typeof e==`object`&&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 n=e.RTCPeerConnection.prototype.addTrack;n&&(e.RTCPeerConnection.prototype.addTrack=function(){let e=n.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){let e=this;return this._pc.getStats().then(t=>tv(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}),K_(e,`track`,e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){let e=this;return this._pc.getStats().then(t=>tv(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=arguments[0],t,n,r;return this.getSenders().forEach(n=>{n.track===e&&(t?r=!0:t=n)}),this.getReceivers().forEach(t=>(t.track===e&&(n?r=!0:n=t),t.track===e)),r||t&&n?Promise.reject(new DOMException(`There are more than one sender or receiver for the track.`,`InvalidAccessError`)):t?t.getStats():n?n.getStats():Promise.reject(new DOMException(`There is no sender or receiver for the track.`,`InvalidAccessError`))}return t.apply(this,arguments)}}function cv(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,n){if(!n)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};let r=t.apply(this,arguments);return this._shimmedLocalStreams[n.id]?this._shimmedLocalStreams[n.id].indexOf(r)===-1&&this._shimmedLocalStreams[n.id].push(r):this._shimmedLocalStreams[n.id]=[n,r],r};let n=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();n.apply(this,arguments);let r=this.getSenders().filter(e=>t.indexOf(e)===-1);this._shimmedLocalStreams[e.id]=[e].concat(r)};let r=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],r.apply(this,arguments)};let i=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach(t=>{let n=this._shimmedLocalStreams[t].indexOf(e);n!==-1&&this._shimmedLocalStreams[t].splice(n,1),this._shimmedLocalStreams[t].length===1&&delete this._shimmedLocalStreams[t]}),i.apply(this,arguments)}}function lv(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return cv(e);let n=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){let e=n.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map(e=>this._reverseStreams[e.id])};let r=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 n=new e.MediaStream(t.getTracks());this._streams[t.id]=n,this._reverseStreams[n.id]=t,t=n}r.apply(this,[t])};let i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},i.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,n){if(this.signalingState===`closed`)throw new DOMException(`The RTCPeerConnection's signalingState is 'closed'.`,`InvalidStateError`);let r=[].slice.call(arguments,1);if(r.length!==1||!r[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 i=this._streams[n.id];if(i)i.addTrack(t),Promise.resolve().then(()=>{this.dispatchEvent(new Event(`negotiationneeded`))});else{let r=new e.MediaStream([t]);this._streams[n.id]=r,this._reverseStreams[r.id]=n,this.addStream(r)}return this.getSenders().find(e=>e.track===t)};function a(e,t){let n=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{let r=e._reverseStreams[t],i=e._streams[r.id];n=n.replace(new RegExp(i.id,`g`),r.id)}),new RTCSessionDescription({type:t.type,sdp:n})}function o(e,t){let n=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{let r=e._reverseStreams[t],i=e._streams[r.id];n=n.replace(new RegExp(r.id,`g`),i.id)}),new RTCSessionDescription({type:t.type,sdp:n})}[`createOffer`,`createAnswer`].forEach(function(t){let n=e.RTCPeerConnection.prototype[t],r={[t](){let e=arguments;return arguments.length&&typeof arguments[0]==`function`?n.apply(this,[t=>{let n=a(this,t);e[0].apply(null,[n])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):n.apply(this,arguments).then(e=>a(this,e))}};e.RTCPeerConnection.prototype[t]=r[t]});let s=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type||(arguments[0]=o(this,arguments[0])),s.apply(this,arguments)};let c=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,`localDescription`);Object.defineProperty(e.RTCPeerConnection.prototype,`localDescription`,{get(){let e=c.get.apply(this);return e.type===``?e:a(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if(this.signalingState===`closed`)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||{};let t;Object.keys(this._streams).forEach(n=>{this._streams[n].getTracks().find(t=>e.track===t)&&(t=this._streams[n])}),t&&(t.getTracks().length===1?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event(`negotiationneeded`)))}}function uv(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&[`setLocalDescription`,`setRemoteDescription`,`addIceCandidate`].forEach(function(t){let n=e.RTCPeerConnection.prototype[t],r={[t](){return arguments[0]=new(t===`addIceCandidate`?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=r[t]})}function dv(e,t){K_(e,`negotiationneeded`,e=>{let n=e.target;if(!((t.version<72||n.getConfiguration&&n.getConfiguration().sdpSemantics===`plan-b`)&&n.signalingState!==`stable`))return e})}var fv=Object.freeze({__proto__:null,fixNegotiationNeeded:dv,shimAddTrackRemoveTrack:lv,shimAddTrackRemoveTrackWithNative:cv,shimGetSendersWithDtmf:ov,shimGetUserMedia:rv,shimMediaStream:iv,shimOnTrack:av,shimPeerConnection:uv,shimSenderReceiverGetStats:sv});function pv(e,t){let n=e&&e.navigator,r=e&&e.MediaStreamTrack;if(n.getUserMedia=function(e,t,r){X_(`navigator.getUserMedia`,`navigator.mediaDevices.getUserMedia`),n.mediaDevices.getUserMedia(e).then(t,r)},!(t.version>55&&`autoGainControl`in n.mediaDevices.getSupportedConstraints())){let e=function(e,t,n){t in e&&!(n in e)&&(e[n]=e[t],delete e[t])},t=n.mediaDevices.getUserMedia.bind(n.mediaDevices);if(n.mediaDevices.getUserMedia=function(n){return typeof n==`object`&&typeof n.audio==`object`&&(n=JSON.parse(JSON.stringify(n)),e(n.audio,`autoGainControl`,`mozAutoGainControl`),e(n.audio,`noiseSuppression`,`mozNoiseSuppression`)),t(n)},r&&r.prototype.getSettings){let t=r.prototype.getSettings;r.prototype.getSettings=function(){let n=t.apply(this,arguments);return e(n,`mozAutoGainControl`,`autoGainControl`),e(n,`mozNoiseSuppression`,`noiseSuppression`),n}}if(r&&r.prototype.applyConstraints){let t=r.prototype.applyConstraints;r.prototype.applyConstraints=function(n){return this.kind===`audio`&&typeof n==`object`&&(n=JSON.parse(JSON.stringify(n)),e(n,`autoGainControl`,`mozAutoGainControl`),e(n,`noiseSuppression`,`mozNoiseSuppression`)),t.apply(this,[n])}}}}function mv(e,t){e.navigator.mediaDevices&&`getDisplayMedia`in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(n){if(!(n&&n.video)){let e=new DOMException(`getDisplayMedia without video constraints is undefined`);return e.name=`NotFoundError`,e.code=8,Promise.reject(e)}return n.video===!0?n.video={mediaSource:t}:n.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(n)})}function hv(e){typeof e==`object`&&e.RTCTrackEvent&&`receiver`in e.RTCTrackEvent.prototype&&!(`transceiver`in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,`transceiver`,{get(){return{receiver:this.receiver}}})}function gv(e,t){if(typeof e!=`object`||!(e.RTCPeerConnection||e.mozRTCPeerConnection))return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&[`setLocalDescription`,`setRemoteDescription`,`addIceCandidate`].forEach(function(t){let n=e.RTCPeerConnection.prototype[t],r={[t](){return arguments[0]=new(t===`addIceCandidate`?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=r[t]});let n={inboundrtp:`inbound-rtp`,outboundrtp:`outbound-rtp`,candidatepair:`candidate-pair`,localcandidate:`local-candidate`,remotecandidate:`remote-candidate`},r=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){let[e,i,a]=arguments;return r.apply(this,[e||null]).then(e=>{if(t.version<53&&!i)try{e.forEach(e=>{e.type=n[e.type]||e.type})}catch(t){if(t.name!==`TypeError`)throw t;e.forEach((t,r)=>{e.set(r,Object.assign({},t,{type:n[t.type]||t.type}))})}return e}).then(i,a)}}function _v(e){if(!(typeof e==`object`&&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 n=e.RTCPeerConnection.prototype.addTrack;n&&(e.RTCPeerConnection.prototype.addTrack=function(){let e=n.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 vv(e){if(!(typeof e==`object`&&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}),K_(e,`track`,e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function yv(e){!e.RTCPeerConnection||`removeStream`in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){X_(`removeStream`,`removeTrack`),this.getSenders().forEach(t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)})})}function bv(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function xv(e){if(!(typeof e==`object`&&e.RTCPeerConnection))return;let t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;e===void 0&&(e=[]),e=[...e];let n=e.length>0;n&&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 r=t.apply(this,arguments);if(n){let{sender:t}=r,n=t.getParameters();(!(`encodings`in n)||n.encodings.length===1&&Object.keys(n.encodings[0]).length===0)&&(n.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(n).then(()=>{delete t.sendEncodings}).catch(()=>{delete t.sendEncodings})))}return r})}function Sv(e){if(!(typeof e==`object`&&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 Cv(e){if(!(typeof e==`object`&&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 wv(e){if(!(typeof e==`object`&&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 Tv=Object.freeze({__proto__:null,shimAddTransceiver:xv,shimCreateAnswer:wv,shimCreateOffer:Cv,shimGetDisplayMedia:mv,shimGetParameters:Sv,shimGetUserMedia:pv,shimOnTrack:hv,shimPeerConnection:gv,shimRTCDataChannel:bv,shimReceiverGetStats:vv,shimRemoveStream:yv,shimSenderGetStats:_v});function Ev(e){if(!(typeof e!=`object`||!e.RTCPeerConnection)){if(`getLocalStreams`in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return 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.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach(n=>t.call(this,n,e)),e.getVideoTracks().forEach(n=>t.call(this,n,e))},e.RTCPeerConnection.prototype.addTrack=function(e){for(var n=arguments.length,r=Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return r&&r.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||=[];let t=this._localStreams.indexOf(e);if(t===-1)return;this._localStreams.splice(t,1);let n=e.getTracks();this.getSenders().forEach(e=>{n.includes(e.track)&&this.removeTrack(e)})})}}function Dv(e){if(!(typeof e!=`object`||!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.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.indexOf(t)>=0)return;e._remoteStreams.push(t);let n=new Event(`addstream`);n.stream=t,e.dispatchEvent(n)})}),t.apply(e,arguments)}}}function Ov(e){if(typeof e!=`object`||!e.RTCPeerConnection)return;let t=e.RTCPeerConnection.prototype,n=t.createOffer,r=t.createAnswer,i=t.setLocalDescription,a=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=function(e,t){let r=arguments.length>=2?arguments[2]:arguments[0],i=n.apply(this,[r]);return t?(i.then(e,t),Promise.resolve()):i},t.createAnswer=function(e,t){let n=arguments.length>=2?arguments[2]:arguments[0],i=r.apply(this,[n]);return t?(i.then(e,t),Promise.resolve()):i};let s=function(e,t,n){let r=i.apply(this,[e]);return n?(r.then(t,n),Promise.resolve()):r};t.setLocalDescription=s,s=function(e,t,n){let r=a.apply(this,[e]);return n?(r.then(t,n),Promise.resolve()):r},t.setRemoteDescription=s,s=function(e,t,n){let r=o.apply(this,[e]);return n?(r.then(t,n),Promise.resolve()):r},t.addIceCandidate=s}function kv(e){let t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){let e=t.mediaDevices,n=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>n(Av(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,n,r){t.mediaDevices.getUserMedia(e).then(n,r)}.bind(t))}function Av(e){return e&&e.video!==void 0?Object.assign({},e,{video:$_(e.video)}):e}function jv(e){if(!e.RTCPeerConnection)return;let t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,n){if(e&&e.iceServers){let t=[];for(let n=0;n<e.iceServers.length;n++){let r=e.iceServers[n];r.urls===void 0&&r.url?(X_(`RTCIceServer.url`,`RTCIceServer.urls`),r=JSON.parse(JSON.stringify(r)),r.urls=r.url,delete r.url,t.push(r)):t.push(e.iceServers[n])}e.iceServers=t}return new t(e,n)},e.RTCPeerConnection.prototype=t.prototype,`generateCertificate`in t&&Object.defineProperty(e.RTCPeerConnection,`generateCertificate`,{get(){return t.generateCertificate}})}function Mv(e){typeof e==`object`&&e.RTCTrackEvent&&`receiver`in e.RTCTrackEvent.prototype&&!(`transceiver`in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,`transceiver`,{get(){return{receiver:this.receiver}}})}function Nv(e){let t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){e.offerToReceiveAudio!==void 0&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);let t=this.getTransceivers().find(e=>e.receiver.track.kind===`audio`);e.offerToReceiveAudio===!1&&t?t.direction===`sendrecv`?t.setDirection?t.setDirection(`sendonly`):t.direction=`sendonly`:t.direction===`recvonly`&&(t.setDirection?t.setDirection(`inactive`):t.direction=`inactive`):e.offerToReceiveAudio===!0&&!t&&this.addTransceiver(`audio`,{direction:`recvonly`}),e.offerToReceiveVideo!==void 0&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);let n=this.getTransceivers().find(e=>e.receiver.track.kind===`video`);e.offerToReceiveVideo===!1&&n?n.direction===`sendrecv`?n.setDirection?n.setDirection(`sendonly`):n.direction=`sendonly`:n.direction===`recvonly`&&(n.setDirection?n.setDirection(`inactive`):n.direction=`inactive`):e.offerToReceiveVideo===!0&&!n&&this.addTransceiver(`video`,{direction:`recvonly`})}return t.apply(this,arguments)}}function Pv(e){typeof e!=`object`||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var Fv=Object.freeze({__proto__:null,shimAudioContext:Pv,shimCallbacksAPI:Ov,shimConstraints:Av,shimCreateOfferLegacy:Nv,shimGetUserMedia:kv,shimLocalStreamsAPI:Ev,shimRTCIceServerUrls:jv,shimRemoteStreamsAPI:Dv,shimTrackEventTransceiver:Mv}),Iv={exports:{}},Lv;function Rv(){return Lv?Iv.exports:(Lv=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(`
25
+ `,document.head.appendChild(e)};function sn(e,t){if(typeof document>`u`)return null;if(e){let n=document.getElementById(e)||document.querySelector(`[data-section="${e}"]`);if(n)return n;t||=e.replace(/[-_]+/g,` `).trim()}if(!t)return null;let n=t.toLowerCase().trim(),r=n.split(/\s+/).filter(e=>e.length>2),i=Array.from(document.querySelectorAll(`h1, h2, h3, h4, h5, h6, [data-section]`)).filter(e=>!en(e));for(let e of i)if(e.textContent.replace(/\s+/g,` `).toLowerCase().trim()===n)return e;for(let e of i){let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.startsWith(n)||t.endsWith(n))return e}let a=[];for(let e of i){let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();t.includes(n)&&a.push({el:e,len:t.length})}if(a.length)return a.sort((e,t)=>e.len-t.len),a[0].el;for(let e of i){let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.length>3&&n.includes(t))return e}if(r.length>0){let e=null,t=0;for(let n of i){let i=n.textContent.replace(/\s+/g,` `).toLowerCase(),a=0;for(let e of r)i.includes(e)&&a++;let o=a/r.length;o>t&&o>=.6&&(t=o,e=n)}if(e)return e}let o=Array.from(document.querySelectorAll(`main [role='group']`)).filter(e=>!en(e)),s=[];for(let e of o){let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();t.length<15||t.length>8e3||t.includes(n)&&s.push({el:e,len:t.length})}if(s.length)return s.sort((e,t)=>e.len-t.len),s[0].el;if(r.length>0){let e=Array.from(document.querySelectorAll(`main a[href], article a[href], .views-row a[href], h2 a[href], h3 a[href], .card a[href], [class*='teaser'] a[href]`)).filter(e=>{if(en(e))return!1;try{let t=e.getAttribute(`href`)||``;if(!t||t===`#`||t.startsWith(`javascript:`))return!1}catch{return!1}let t=e.textContent.replace(/\s+/g,` `).trim();return t.length>=3&&t.length<=220}),t=null,n=0;for(let i of e){let e=i.textContent.replace(/\s+/g,` `).toLowerCase(),a=0;for(let t of r)e.includes(t)&&a++;let o=a/r.length;o>n&&o>=.5&&(n=o,t=i)}if(t)return t.closest(`article`)||t.closest(`.views-row`)||t}let c=document.querySelectorAll(`section, article, .card, [class*='feature'], [class*='service']`);for(let e of c){if(en(e))continue;let t=e.querySelector(`h1, h2, h3, h4, h5, h6`);if(t){let r=t.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(r.includes(n)||n.includes(r))return e}}let l=document.querySelectorAll(`li, strong, blockquote, dt`);for(let e of l){if(en(e))continue;let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.includes(n)&&t.length<500)return e.tagName===`STRONG`&&e.parentElement?.tagName===`LI`?e.parentElement:e}let u=Array.from(document.querySelectorAll(`a[href]`)).filter(e=>!en(e));u.sort((e,t)=>(e.textContent||``).trim().length-(t.textContent||``).trim().length);for(let e of u){let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.includes(n)&&t.length<500)return e}let d=document.querySelectorAll(`p`);for(let e of d){if(en(e))continue;let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.includes(n)&&t.length<800)return e}return null}function cn(e,{speaking:t=!1,scroll:n=!0}={}){if(!e||typeof document>`u`)return;on();let r=document.querySelectorAll(`.fe-highlight-section`);for(let t of r)t!==e&&(t.classList.remove(`fe-highlight-section`,`fe-highlight-speaking`),t.classList.add(`fe-highlight-exiting`),setTimeout(()=>t.classList.remove(`fe-highlight-exiting`),300));if(e.classList.remove(`fe-highlight-exiting`),e.classList.add(`fe-highlight-section`),t?e.classList.add(`fe-highlight-speaking`):e.classList.remove(`fe-highlight-speaking`),n)try{e.scrollIntoView({behavior:`smooth`,block:`center`})}catch{try{e.scrollIntoView(!0)}catch{}}}function ln(){typeof document>`u`||document.querySelectorAll(`.fe-highlight-section, .fe-highlight-exiting`).forEach(e=>e.classList.remove(`fe-highlight-section`,`fe-highlight-speaking`,`fe-highlight-exiting`))}function un(e){if(typeof window>`u`)return e;try{let t=new URL(String(e).trim(),window.location.href);return!/^https?:$/i.test(t.protocol)||t.origin===window.location.origin?t.href:new URL(t.pathname+t.search+t.hash,window.location.origin).href}catch{return e}}async function dn(e){if(typeof window>`u`)return!1;try{let t=new URL(String(e).trim(),window.location.href);return t.origin===window.location.origin?(await fetch(t.href,{method:`HEAD`,mode:`same-origin`,cache:`no-store`})).ok:!1}catch{return!1}}async function fn(e,{siteId:t,apiBaseUrl:n}){if(!e)return!1;if(!t||!n)return console.warn(`[FlowEngage] shouldProceedWithNavigation: missing siteId or apiBaseUrl`),!1;let r=String(n).replace(/\/$/,``),i=new URLSearchParams({siteId:String(t),url:String(e).trim()});try{let t=await(await fetch(`${r}/api/widget/navigate-allowed?${i.toString()}`)).json().catch(()=>({}));return t.success?t.allowed?!0:t.hasIndex===!1?dn(e):!1:!1}catch(e){return console.warn(`[FlowEngage] navigate-allowed check failed:`,e?.message),!1}}function pn(e){if(!(!e||typeof sessionStorage>`u`))try{sessionStorage.setItem(nn,JSON.stringify({sectionText:e,ts:Date.now()}))}catch{}}async function mn(e,t={}){if(typeof window>`u`)return!1;let{sectionText:n}=t;try{let t=un(e),r=new URL(t,window.location.origin);if(tn(`input:`,e,`→ normalized:`,t,`href:`,r.href),r.hash&&r.pathname===window.location.pathname){let e=r.hash.slice(1),t=document.getElementById(e);if(t)return tn(`branch: hash scroll (same path)`),t.scrollIntoView({behavior:`smooth`,block:`start`}),!0}if(r.pathname===window.location.pathname&&r.search===window.location.search&&!r.hash)return tn(`branch: already on page (no nav)`),!1;let i=r.pathname+r.search+r.hash,a=window.next?.router;if(a?.push)return tn(`branch: Next.js Pages router.push`,i),new Promise(e=>{let t=()=>{a.events?.off(`routeChangeComplete`,t),e(!0)};a.events?.on(`routeChangeComplete`,t),a.push(i),setTimeout(t,5e3)});let o=window.__NEXT_ROUTER__;return o?.push?(tn(`branch: __NEXT_ROUTER__.push`,i),o.push(i),!0):(n?(pn(n),tn(`branch: location.assign (full navigation, section stored):`,n)):tn(`branch: location.assign (full navigation)`,r.href),window.location.assign(r.href),!0)}catch(t){console.warn(`[FlowEngage] shadowNavigate error:`,t),n&&pn(n);try{window.location.href=un(e)}catch{window.location.href=e}return!0}}var hn=e=>!e||typeof e!=`string`?e:e.replace(/<human_assistance_request>[\s\S]*?<\/human_assistance_request>/gi,``).replace(/<human_assistance_request>/gi,``).replace(/<\/human_assistance_request>/gi,``).replace(/<navigate[^>]*\/>/gi,``).replace(/<navigate[^>]*>[\s\S]*?<\/navigate>/gi,``).replace(/<[a-z]+(?:_[a-z]+)+[^>]*>[\s\S]*?<\/[a-z]+(?:_[a-z]+)+>/gi,``).replace(/<[a-z]+(?:_[a-z]+)+[^>]*\/>/gi,``).trim(),gn=(e=[])=>e.map(e=>({...e,message:hn(e.message),isPending:!1,id:e.messageId||`${e.sender}-${e.timestamp||Date.now()}-${Math.random()}`})),_n=(e,t)=>e?typeof e==`string`?e:e.message||e.error||e.reason||t:t,vn=(e={})=>{if(!e?.candidate)return null;if(typeof e.candidate==`object`)return e.candidate;let t=e.sdpMid!==void 0&&e.sdpMid!==null&&e.sdpMid!==``,n=e.sdpMLineIndex!==void 0&&e.sdpMLineIndex!==null;return!t&&!n?null:{candidate:e.candidate,...t?{sdpMid:e.sdpMid}:{},...n?{sdpMLineIndex:e.sdpMLineIndex}:{}}},yn=e=>{if(!e)return null;let t=typeof e==`object`?e:{candidate:e};return{hasCandidate:!!t.candidate,sdpMid:t.sdpMid??null,sdpMLineIndex:t.sdpMLineIndex??null,candidatePreview:typeof t.candidate==`string`?t.candidate.slice(0,80):null}},bn=(e=[],t=`Agent`)=>{for(let t of e)if(typeof t==`string`&&t.trim())return t.trim();return t},xn=(e=[],t,n=6)=>!t?.message||e.slice(-n).some(e=>e.sender===`system`&&e.message===t.message)?e:[...e,t];function Sn({siteId:e,config:t,children:n,language:r=`en`}){let i=(0,d.useMemo)(()=>e?{...t||{},siteId:e}:t||null,[e,t]),[a,o]=(0,d.useState)(`booting`),[s,c]=(0,d.useState)(null),[l,u]=(0,d.useState)(null),[m,h]=(0,d.useState)(``),[g,_]=(0,d.useState)([]),[x,S]=(0,d.useState)(ne().isOpen),[oe,se]=(0,d.useState)(ne().activeScreen),[de,fe]=(0,d.useState)(ne().isHumanHandled),[pe,me]=(0,d.useState)(ne().agentName),[he,ge]=(0,d.useState)(ne().agentHeadshot),[_e,ve]=(0,d.useState)(()=>ie(i?.siteId)),[ye,be]=(0,d.useState)(!1),[xe,Se]=(0,d.useState)(!1),[Ce,we]=(0,d.useState)(`idle`),[Te,Ee]=(0,d.useState)(!1),[De,Oe]=(0,d.useState)(!1),[ke,Ae]=(0,d.useState)(``),[je,Me]=(0,d.useState)(!1),[Ne,Pe]=(0,d.useState)(!1),[w,Fe]=(0,d.useState)(null),[T,Ie]=(0,d.useState)(null),[Le,E]=(0,d.useState)(`idle`),[Re,ze]=(0,d.useState)(null),[Be,Ve]=(0,d.useState)(!1),[He,Ue]=(0,d.useState)(``),We=(0,d.useRef)(null),D=(0,d.useRef)(null),O=(0,d.useRef)(``),Ge=(0,d.useRef)(null),Ke=(0,d.useRef)(null),qe=(0,d.useRef)(null),Je=(0,d.useRef)(null),Ye=(0,d.useRef)(null),Xe=(0,d.useRef)([]),Ze=(0,d.useRef)(null),Qe=(0,d.useRef)(null),$e=(0,d.useRef)(!1),et=(0,d.useRef)(!1),tt=(0,d.useRef)(``),nt=(0,d.useRef)(pe),rt=(0,d.useRef)([]),it=(0,d.useRef)(!1),at=(0,d.useRef)({notifyRouteChange:()=>{},cleanup:()=>{}}),ot=(0,d.useCallback)((e={})=>{let t=!!e.is_human_handled;return fe(t),t?(se(`agent`),e.agent_info?.name&&me(e.agent_info.name),e.agent_info?.headshot&&ge(e.agent_info.headshot),t):(se(`ai`),t)},[]),st=(0,d.useMemo)(()=>{let e=l?.widgetSettings?.call?.maxDurationSeconds??i?.widgetSettings?.call?.maxDurationSeconds??i?.callMaxDurationSeconds,t=Number(e);return Number.isFinite(t)&&t>0?t:y},[i,l]);(0,d.useEffect)(()=>{Ge.current=w},[w]),(0,d.useEffect)(()=>{nt.current=pe},[pe]);let ct=()=>{Ue(``)},lt=e=>{let t=typeof e==`string`?e.trim().toLowerCase():``;return ve(t),ae(t,i?.siteId),t};(0,d.useEffect)(()=>{let e=i?.siteId;e&&ve(ie(e))},[i?.siteId]);let ut=(e=`unspecified`)=>{console.log(`[FlowEngageCall] cleanup:start`,{reason:e,chatId:O.current,activeCallId:Ze.current,acceptingCallId:Qe.current,hasPeerConnection:!!Ke.current,hasLocalStream:!!qe.current,hasRemoteAudio:!!Je.current,queuedIceCount:Xe.current.length}),Ke.current&&=(Ke.current.close(),null),qe.current&&=(qe.current.getTracks().forEach(e=>e.stop()),null),Je.current&&=(Je.current.srcObject=null,Je.current.remove(),null),Ye.current=null,Xe.current=[],Ze.current=null,Qe.current=null,$e.current=!1,Ve(!1),Fe(null),Ie(null),E(`idle`),ze(null),console.log(`[FlowEngageCall] cleanup:complete`,{reason:e,chatId:O.current})},dt=(e=new Date().toISOString())=>{let t=We.current,n=Ze.current||Ye.current?.callId;if(!t?.connected||!n||$e.current){console.log(`[FlowEngageProvider] skipping call:connected emit`,{callId:n,chatId:O.current,socketConnected:!!t?.connected,alreadyReported:$e.current});return}console.log(`[FlowEngageProvider] emitting call:connected`,{callId:n,chatId:O.current,connectedAt:e}),$e.current=!0,t.emit(`call:connected`,{callId:n,chatId:O.current,connectedAt:e})},ft=(e={})=>{if(!e.callId)return;let t=Qe.current===e.callId,n=Ze.current===e.callId,r=Ge.current?.callId===e.callId;if(!(!t&&!n&&!r)){if(console.log(`[FlowEngageProvider] syncing accepted call state`,{callId:e.callId,chatId:e.chatId||O.current,isAcceptingHere:t,isAlreadyActive:n,isIncomingHere:r}),Fe(null),t||n){Ze.current=e.callId,Ie(e.callId),E(e=>e===`connected`?e:`connecting`),S(!0);return}E(`idle`)}},pt=(e={})=>{if(!e.callId)return;let t=Qe.current===e.callId,n=Ze.current===e.callId,r=Ge.current?.callId===e.callId;if(!(!t&&!n&&!r)){if(console.log(`[FlowEngageProvider] syncing ended incoming call state`,{callId:e.callId,chatId:e.chatId||O.current,isAcceptingHere:t,isAlreadyActive:n,isIncomingHere:r,reason:e.reason||e.status||null}),n){ut();return}Qe.current=null,Ye.current=null,Xe.current=[],Fe(null),E(`idle`)}},mt=async(e={})=>{let t=Ke.current,n=We.current,r=e.sdpOffer||e.offer?.sdp;if(!t||!n?.connected||!r||!e.callId){console.log(`[FlowEngageProvider] deferring remote offer until peer/socket ready`,{callId:e.callId,chatId:O.current,hasPeerConnection:!!t,socketConnected:!!n?.connected,hasOffer:!!r}),Ye.current=e;return}if(console.log(`[FlowEngageProvider] applying remote offer`,{callId:e.callId,chatId:O.current,offerLength:r.length,signalingState:t.signalingState,iceConnectionState:t.iceConnectionState,connectionState:t.connectionState}),await t.setRemoteDescription(new RTCSessionDescription({type:`offer`,sdp:r})),Xe.current.length>0){console.log(`[FlowEngageProvider] flushing queued agent ICE candidates after remote offer`,{callId:e.callId,chatId:O.current,queuedCount:Xe.current.length});for(let e of Xe.current)await t.addIceCandidate(new RTCIceCandidate(e));Xe.current=[]}let i=await t.createAnswer();await t.setLocalDescription(i),console.log(`[FlowEngageCall] local-answer:created`,{callId:e.callId,chatId:O.current,answerLength:i.sdp?.length||0,signalingState:t.signalingState,iceConnectionState:t.iceConnectionState,connectionState:t.connectionState}),console.log(`[FlowEngageCall] local-answer:emitting`,{callId:e.callId,chatId:O.current}),n.emit(`call:answer`,{callId:e.callId,sdpAnswer:i.sdp,chatId:O.current})};(0,d.useEffect)(()=>{re({isOpen:x,activeScreen:oe,isHumanHandled:de,agentName:pe,agentHeadshot:he})},[x,oe,de,pe,he]),(0,d.useEffect)(()=>{let e=!0;return(async()=>{try{console.log(`[FlowEngageProvider] boot start`,{resolvedConfig:i,language:r});let t=p(i);console.log(`[FlowEngageProvider] config validated`,t);let n=await le(t);if(!e)return;let a=``;try{if(a=(await ce({apiBaseUrl:t.apiBaseUrl,userId:n.userId,siteId:t.siteId,priorChatId:ee()}))?.data?.chatId,!a)throw Error(`resolve-session returned no chatId`);te()}catch(e){console.warn(`[FlowEngageProvider] resolve-session failed, using ephemeral chat id`,e?.message||e),a=C()}O.current=a;let s=ue({apiBaseUrl:t.apiBaseUrl,userId:n.userId,siteId:t.siteId});D.current=s,u({...n,apiBaseUrl:t.apiBaseUrl}),h(a);let c=n?.widgetSettings?.branding?.fallbackAgentName||`Agent`;console.log(`[FlowEngageProvider] bootstrap resolved`,{bootstrapData:n,resolvedChatId:a});let l=Yt({apiBaseUrl:t.apiBaseUrl,userId:n.userId,chatId:a,siteId:t.siteId});We.current=l,l.on(`connect`,()=>{console.log(`[FlowEngageProvider] socket connected`),we(`connected`)}),l.on(`disconnect`,()=>{console.log(`[FlowEngageProvider] socket disconnected`),we(`disconnected`)}),l.on(`aiTyping`,()=>{console.log(`[FlowEngageProvider] received aiTyping`,{chatId:O.current}),Se(!0)}),l.on(`ai:typing`,()=>{console.log(`[FlowEngageProvider] received ai:typing`,{chatId:O.current}),Se(!0)}),l.on(`messageReceived`,e=>{let t=e.message||e,n={...t,message:hn(t.message)};Se(!1),be(!1),_(e=>[...e.filter(e=>!e.isPending),{...n,isPending:!1,id:n.messageId||`${n.sender}-${Date.now()}-${Math.random()}`}])}),l.on(`conversationStarted`,e=>{console.log(`[FlowEngageProvider] conversationStarted`,e),e?.message&&_(t=>[...t,{id:`system-start-${Date.now()}`,sender:`system`,message:e.message,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`message:new`,e=>{let t=e.message||e,n={...t,message:hn(t.message)};Se(!1),(n.sender===`agent`||n.agent_name||n.sender===`ai`||n.sender===`bot`)&&be(!1),_(e=>n.sender===`bot`||n.sender===`ai`?[...e,{...n,isPending:!1,id:n.messageId||`${n.sender}-${Date.now()}-${Math.random()}`}]:e.some(e=>e.id===n.messageId||e.sender===n.sender&&e.message===n.message&&e.isPending)?e.map(e=>e.sender===n.sender&&e.message===n.message&&e.isPending?{...n,isPending:!1,id:n.messageId||e.id}:e):[...e,{...n,isPending:!1,id:n.messageId||`${n.sender}-${Date.now()}-${Math.random()}`}]),(n.sender===`agent`||n.agent_name)&&(fe(!0),se(`agent`),me(bn([n.agent_name,n.agentName,n.metadata?.agentName],c)),n.sender_headshot&&ge(n.sender_headshot),S(!0))});let d=(e={})=>{let t=bn([e.agent?.name,e.agentName,e.agent_name,nt.current],c);fe(!0),se(`agent`),me(t),ge(e.agent?.headshot||null),S(!0),_(e=>xn(e,{id:`agent-joined-${Date.now()}`,sender:`system`,message:`${t} has joined the chat.`,timestamp:new Date().toISOString(),isPending:!1}))},f=(e={})=>{let t=bn([e.agent?.name,e.agentName,e.agent_name,nt.current],c);fe(!1),se(`ai`),_(e=>xn(e,{id:`agent-left-${Date.now()}`,sender:`system`,message:`${t} has left the chat.`,timestamp:new Date().toISOString(),isPending:!1}))};l.on(`agent:joined`,d),l.on(`agentJoined`,d),l.on(`agent:left`,f),l.on(`agentLeft`,f),l.on(`conversationEnded`,e=>{Pe(!0);let t=e?.message||`This conversation has ended. Thank you for reaching out!`;_(e=>[...e,{id:`conversation-ended-${Date.now()}`,sender:`system`,message:t,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`chat:history_update`,e=>{_(gn(e.chat_history||[]))}),l.on(`typing:start`,e=>{console.log(`[FlowEngageProvider] received typing:start`,{chatId:e?.chatId||O.current,sender:e?.sender}),e.sender===`agent`&&be(!0)}),l.on(`typing:stop`,e=>{console.log(`[FlowEngageProvider] received typing:stop`,{chatId:e?.chatId||O.current,sender:e?.sender}),e.sender===`agent`&&be(!1)}),l.on(`call:incoming`,(e={})=>{let t=bn([e.agentName,e.ownerName,e.agent?.name,nt.current],`Agent`);console.log(`[FlowEngageProvider] received call:incoming`,{callId:e.callId,chatId:O.current,agentName:t}),ct(),$e.current=!1,Fe({callId:e.callId,from:e.from||`owner`,agentId:e.agentId||null,agentName:t}),me(e=>bn([t,e],`Agent`)),E(`incoming`),ze(null),S(!0)}),l.on(`call:offer`,async(e={})=>{console.log(`[FlowEngageProvider] received call:offer`,{callId:e.callId,chatId:e.chatId||O.current,offerLength:(e.sdpOffer||e.offer?.sdp||``).length}),Ye.current=e;try{await mt(e)}catch(e){console.error(`[FlowEngageProvider] failed to apply remote offer`,e)}}),l.on(`call:ice-candidate-from-agent`,async(e={})=>{if(!e.candidate){console.log(`[FlowEngageProvider] skipping agent ICE candidate`,{callId:e.callId,chatId:e.chatId||O.current,hasPeerConnection:!!Ke.current,hasCandidate:!!e.candidate});return}try{let t=vn(e);if(!t){console.warn(`[FlowEngageProvider] ignoring invalid ICE candidate payload`,e);return}if(console.log(`[FlowEngageProvider] adding agent ICE candidate`,{callId:e.callId,chatId:e.chatId||O.current,candidate:yn(t),hasRemoteDescription:!!Ke.current?.remoteDescription}),!Ke.current||!Ke.current.remoteDescription){console.log(`[FlowEngageProvider] queueing agent ICE candidate until peer/remote description is ready`,{callId:e.callId,chatId:e.chatId||O.current,queueSize:Xe.current.length+1}),Xe.current.push(t);return}await Ke.current.addIceCandidate(new RTCIceCandidate(t))}catch(e){console.error(`[FlowEngageProvider] failed to add ICE candidate`,e)}}),l.on(`call:ended`,()=>{ct(),console.log(`[FlowEngageCall] socket:event call:ended`,{chatId:O.current,activeCallId:Ze.current}),ut(`socket:call_ended`)}),l.on(`call:accepted`,(e={})=>{console.log(`[FlowEngageProvider] received call:accepted`,{callId:e.callId,chatId:e.chatId||O.current}),ft(e)}),l.on(`call:accepted_by_other`,(e={})=>{console.log(`[FlowEngageProvider] received call:accepted_by_other`,{callId:e.callId,chatId:e.chatId||O.current}),ft(e)}),l.on(`call:rejected`,(e={})=>{console.log(`[FlowEngageProvider] received call:rejected`,{callId:e.callId,chatId:e.chatId||O.current,reason:e.reason}),pt(e)}),l.on(`call:missed`,(e={})=>{console.log(`[FlowEngageProvider] received call:missed`,{callId:e.callId,chatId:e.chatId||O.current,reason:e.reason}),pt(e)}),l.on(`call:failed`,(e={})=>{console.log(`[FlowEngageProvider] received call:failed`,{callId:e.callId,chatId:e.chatId||O.current,reason:e.reason}),pt(e)}),l.on(`call:connected`,(e={})=>{if(!e.callId)return;let t=Qe.current===e.callId,n=Ze.current===e.callId,r=Ye.current?.callId===e.callId,i=Ge.current?.callId===e.callId;if(console.log(`[FlowEngageProvider] received call:connected`,{callId:e.callId,chatId:e.chatId||O.current,connectedAt:e.connectedAt,status:e.status,isAcceptingHere:t,isAlreadyActive:n,isPendingOfferHere:r,isIncomingHere:i}),!t&&!n&&!r){i&&(Fe(null),E(`idle`));return}$e.current=!0,Qe.current=null,Ze.current=e.callId,Ie(e.callId),Fe(null),E(`connected`),ze(e.connectedAt||new Date().toISOString()),S(!0)}),l.on(`call:unavailable`,(e={})=>{console.warn(`[FlowEngageCall] socket:event call:unavailable`,{chatId:e.chatId||O.current,callId:e.callId,reason:e.reason||e.message||null,raw:e}),ut(`socket:call_unavailable`),Ue(_n(e,`This visitor is not available for a call right now.`)),S(!0)}),l.on(`call:error`,(e={})=>{console.error(`[FlowEngageCall] socket:event call:error`,{chatId:e.chatId||O.current,callId:e.callId,reason:e.reason||e.message||null,raw:e}),ut(`socket:call_error`),Ue(_n(e,`We couldn't connect the call right now.`)),S(!0)}),l.on(`visitor:navigate`,async({url:e,section:n,highlight:r}={})=>{if(e){if(console.log(`[FlowEngageProvider] visitor:navigate`,{url:e,section:n,highlight:r}),!await fn(e,{siteId:t.siteId,apiBaseUrl:t.apiBaseUrl})){console.warn(`[FlowEngageProvider] visitor:navigate blocked (not indexed)`,e);return}mn(e).then(e=>{let t=n||r;t&&setTimeout(()=>{let e=sn(null,t);e&&cn(e)},e?300:150)})}}),l.on(`visitor:highlight`,({sectionId:e,sectionText:t}={})=>{if(!e&&!t)return;console.log(`[FlowEngageProvider] visitor:highlight`,{sectionId:e,sectionText:t});let n=sn(e||null,t||null);n&&cn(n)}),l.on(`visitor:clear_highlight`,()=>{ln()}),at.current=Xt({socket:l,chatId:a}),console.log(`[FlowEngageProvider] tracking started`,{chatId:a});let m=await s.loadHistory(a,r);if(console.log(`[FlowEngageProvider] history loaded`,m),!e||(_(gn(m.chat_history||[])),fe(!!m.is_human_handled),se(m.is_human_handled?`agent`:oe),await new Promise(e=>setTimeout(e,500)),!e))return;o(`ready`),console.log(`[FlowEngageProvider] status ready`)}catch(t){if(!e)return;console.error(`[FlowEngageProvider] boot failed`,t),c(t),o(`error`)}})(),()=>{e=!1,at.current?.cleanup?.(),ut(),We.current?.disconnect()}},[i,r]),(0,d.useEffect)(()=>()=>{if(je&&!it.current&&rt.current.length>0){let e=O.current,t=rt.current,n=D.current;n&&e&&t.length>0&&(console.log(`[FlowEngageProvider] safety-net: syncing voice transcript on unmount`),n.beaconSyncVoice(e,t)||n.syncVoice(e,t).catch(()=>{}),it.current=!0)}},[je,l]),(0,d.useEffect)(()=>{if(!D.current||!m||a!==`ready`)return;let e=window.setInterval(async()=>{try{let e=await D.current.checkHumanHandled(m);fe(!!e.is_human_handled),e.is_human_handled&&(se(`agent`),e.agent_info?.name&&me(bn([e.agent_info.name],`Agent`)),e.agent_info?.headshot&&ge(e.agent_info.headshot)),ot(e)}catch{}},1e4);return()=>window.clearInterval(e)},[m,a,ot]);let ht=async()=>{if(!(!w?.callId||!D.current||!We.current||!m)){ct(),Qe.current=w.callId,console.log(`[FlowEngageProvider] acceptCall started`,{callId:w?.callId,chatId:m,socketConnected:!!We.current?.connected,hasPendingOffer:!!Ye.current});try{let e=await navigator.mediaDevices.getUserMedia({audio:!0});console.log(`[FlowEngageProvider] microphone stream acquired`,{callId:w.callId,chatId:m,trackCount:e.getTracks().length}),qe.current=e;let t=[{urls:`stun:stun.l.google.com:19302`}];try{let e=await D.current.getIceServersConfig();e?.data?.iceServers?.length&&(t=e.data.iceServers)}catch(e){console.warn(`[FlowEngageProvider] ice-config fetch failed, using STUN default`,e)}let n=new RTCPeerConnection({iceServers:t});Ke.current=n,console.log(`[FlowEngageCall] peer-connection:created`,{callId:w.callId,chatId:m,iceServers:1}),n.onconnectionstatechange=()=>{let e=n.connectionState;if(console.log(`[FlowEngageProvider] peer connection state changed`,{callId:w.callId,chatId:m,connectionState:e,iceConnectionState:n.iceConnectionState,signalingState:n.signalingState}),e===`connected`){let e=new Date().toISOString();E(`connected`),ze(t=>t||e),dt(e);return}if(e===`connecting`){E(e=>e===`connected`?e:`connecting`);return}(e===`failed`||e===`disconnected`||e===`closed`)&&console.warn(`[FlowEngageCall] peer-connection:terminal-state`,{callId:w.callId,chatId:m,connectionState:e,iceConnectionState:n.iceConnectionState,signalingState:n.signalingState})},n.oniceconnectionstatechange=()=>{let e=n.iceConnectionState;if(console.log(`[FlowEngageProvider] ICE connection state changed`,{callId:w.callId,chatId:m,iceConnectionState:e,connectionState:n.connectionState,signalingState:n.signalingState}),e===`connected`||e===`completed`){let e=new Date().toISOString();E(`connected`),ze(t=>t||e),dt(e);return}if(e===`checking`||e===`new`){E(e=>e===`connected`?e:`connecting`);return}(e===`failed`||e===`disconnected`||e===`closed`)&&console.warn(`[FlowEngageCall] ice-connection:terminal-state`,{callId:w.callId,chatId:m,iceConnectionState:e,connectionState:n.connectionState,signalingState:n.signalingState})},n.onsignalingstatechange=()=>{console.log(`[FlowEngageCall] signaling-state:changed`,{callId:w.callId,chatId:m,signalingState:n.signalingState,connectionState:n.connectionState,iceConnectionState:n.iceConnectionState})},n.onicegatheringstatechange=()=>{console.log(`[FlowEngageCall] ice-gathering-state:changed`,{callId:w.callId,chatId:m,iceGatheringState:n.iceGatheringState})},e.getTracks().forEach(t=>{console.log(`[FlowEngageCall] local-track:added`,{callId:w.callId,chatId:m,kind:t.kind,enabled:t.enabled,readyState:t.readyState,muted:t.muted,label:t.label}),n.addTrack(t,e)}),n.onicecandidate=e=>{if(!e.candidate||!We.current?.connected){console.log(`[FlowEngageProvider] local ICE candidate skipped`,{callId:w.callId,chatId:m,hasCandidate:!!e.candidate,socketConnected:!!We.current?.connected});return}let t=e.candidate;console.log(`[FlowEngageProvider] emitting local ICE candidate`,{callId:w.callId,chatId:m,candidate:yn(t)}),We.current.emit(`call:ice-candidate`,{callId:w.callId,candidate:t.candidate,sdpMid:t.sdpMid,sdpMLineIndex:t.sdpMLineIndex,chatId:m,from:`customer`})},n.ontrack=e=>{console.log(`[FlowEngageProvider] remote audio track received`,{callId:w.callId,chatId:m,streamCount:e.streams?.length||0});let[t]=e.streams||[],[n]=t?.getAudioTracks?.()||[];if(console.log(`[FlowEngageCall] remote-track:details`,{callId:w.callId,chatId:m,trackKind:e.track?.kind||null,trackEnabled:e.track?.enabled??null,trackMuted:e.track?.muted??null,trackReadyState:e.track?.readyState??null,streamId:t?.id||null,audioTrackCount:t?.getAudioTracks?.().length||0,firstAudioTrackState:n?{enabled:n.enabled,muted:n.muted,readyState:n.readyState,label:n.label}:null}),!Je.current){let e=document.createElement(`audio`);e.id=`flowengage-remote-audio`,e.autoplay=!0,e.playsInline=!0,e.onplay=()=>{console.log(`[FlowEngageCall] remote-audio:onplay`,{callId:w.callId,chatId:m})},e.onpause=()=>{console.warn(`[FlowEngageCall] remote-audio:onpause`,{callId:w.callId,chatId:m,currentTime:e.currentTime})},e.onended=()=>{console.warn(`[FlowEngageCall] remote-audio:onended`,{callId:w.callId,chatId:m,currentTime:e.currentTime})},e.onerror=t=>{console.error(`[FlowEngageCall] remote-audio:onerror`,{callId:w.callId,chatId:m,error:e.error?{code:e.error.code,message:e.error.message}:null,raw:t})},Je.current=e,document.body.appendChild(e)}Je.current.srcObject=e.streams[0];let r=w?.callId,i=r&&(Qe.current===r||Ze.current===r);if(!$e.current&&i){let e=new Date().toISOString();E(`connected`),ze(t=>t||e),Ze.current=r,Ie(r),dt(e)}Je.current.srcObject=t||null;let a=Je.current.play?.();a?.catch&&a.catch(e=>{console.error(`[FlowEngageCall] remote-audio:play-failed`,{callId:w.callId,chatId:m,message:e?.message,name:e?.name,raw:e})})};let r=Ye.current;r&&(console.log(`[FlowEngageProvider] found pending remote offer during accept`,{callId:r.callId||w.callId,chatId:m}),await mt({...r,callId:r.callId||w.callId})),await D.current.acceptCall(w.callId,m),console.log(`[FlowEngageProvider] acceptCall API succeeded`,{callId:w.callId,chatId:m}),Ze.current=w.callId,Ie(w.callId),E(e=>e===`connected`||$e.current?`connected`:`connecting`),Fe(null),S(!0)}catch(e){if(console.error(`[FlowEngageProvider] acceptCall failed`,e),Qe.current=null,ut(`accept_call_failed`),e?.status===404||e?.status===409||e?.status===422){Ue(_n(e,`This visitor call is no longer available.`));return}if(e?.name===`NotAllowedError`||e?.name===`PermissionDeniedError`){try{await D.current.rejectCall(w.callId,m)}catch(e){console.error(`[FlowEngageProvider] failed to reject call after microphone denial`,e)}Ue(`Microphone access was denied. Please allow microphone access to accept the call.`);return}Ue(`We couldn't connect the call right now. Please try again.`)}}},gt=async()=>{if(!w?.callId||!D.current||!m){ut(`reject_call_without_server_context`);return}ct();try{await D.current.rejectCall(w.callId,m)}catch(e){console.error(`[FlowEngageProvider] rejectCall failed`,e),Ue(_n(e,`We couldn't decline the call cleanly.`))}finally{ut(`reject_call_finally`)}},_t=(0,d.useRef)(gt);_t.current=gt,(0,d.useEffect)(()=>{if(!w?.callId||T)return;let e=w.callId,t=window.setTimeout(()=>{Ge.current?.callId===e&&_t.current()},b);return()=>window.clearTimeout(t)},[w?.callId,T]);let vt=async()=>{if(!T||!D.current||!m){ut(`end_call_without_server_context`);return}ct();try{await D.current.endWebRTCCall(T,m)}catch(e){console.error(`[FlowEngageProvider] endWebRTCCall failed`,e),Ue(_n(e,`The call ended locally, but the server could not be updated.`))}finally{ut(`end_call_finally`)}},yt=()=>{let e=qe.current?.getAudioTracks?.()||[],t=Ke.current?.getSenders?.().map(e=>e.track).filter(e=>e?.kind===`audio`)||[],n=[...e,...t].filter(Boolean);if(n.length===0){console.warn(`[FlowEngageProvider] no local audio tracks available for mute`);return}let r=!Be;n.forEach(e=>{e.enabled=!r}),console.log(`[FlowEngageProvider] toggled local mute`,{nextMuted:r,trackCount:n.length}),Ve(r)},bt=async(e={})=>{let t=e.notifyChatInitiated===!0;if(S(!0),!(!t||!D.current||!m||typeof window>`u`)){try{await D.current.trackVisitor({chatId:m,currentPagePath:window.location.pathname||`/`})}catch{}try{await D.current.updateChatStatus(m,`open`)}catch{}}},xt=async e=>{let t=lt(e);if(!t||!D.current||!O.current)return t;try{await D.current.trackVisitor({chatId:O.current,currentPagePath:typeof window<`u`&&window.location.pathname||`/`,email:t})}catch(e){console.error(`[FlowEngageProvider] failed to persist visitor email`,e)}return t},St=()=>{if(!m||!We.current?.connected||et.current){console.log(`[FlowEngageProvider] skipped typing:start emit`,{chatId:m,socketConnected:!!We.current?.connected,alreadyTyping:et.current});return}et.current=!0,console.log(`[FlowEngageProvider] emitting typing:start`,{chatId:m,sender:`user`}),We.current.emit(`typing:start`,{chatId:m,sender:`user`})},Ct=()=>{if(!m||!We.current?.connected||!et.current){console.log(`[FlowEngageProvider] skipped typing:stop emit`,{chatId:m,socketConnected:!!We.current?.connected,wasTyping:et.current});return}et.current=!1,console.log(`[FlowEngageProvider] emitting typing:stop`,{chatId:m,sender:`user`}),We.current.emit(`typing:stop`,{chatId:m,sender:`user`})},wt=(e=``)=>{let t=typeof e==`string`?e:``;if(!m||!We.current?.connected){console.log(`[FlowEngageProvider] skipped typing:update emit`,{chatId:m,socketConnected:!!We.current?.connected,textLength:t.length});return}tt.current!==t&&(tt.current=t,console.log(`[FlowEngageProvider] emitting typing:update`,{chatId:m,sender:`user`,textLength:t.length}),We.current.emit(`typing:update`,{chatId:m,sender:`user`,text:t}))},Tt=async(e,t=``,n=null,i={})=>{if(!(typeof e==`string`&&e.trim())||!D.current||!m||a!==`ready`||Ne)return;Ct();let o=`pending-user-${Date.now()}`,s={id:o,sender:`user`,message:e,timestamp:new Date().toISOString(),isPending:!0,type:i?.type||`text`,metadata:i?.metadata||void 0,...n||{}};_(e=>[...e,s]);let l=de;if(l)try{l=ot(await D.current.checkHumanHandled(m))}catch{}if(l&&We.current?.connected){We.current.emit(`customer:message`,{chatId:m,content:e,sender:`user`,email:_e||void 0,type:i?.type||`text`,metadata:i?.metadata||{},...n||{}});return}Ee(!0);try{let a=await D.current.sendAiMessage(m,e,r,t,{...n||{},..._e?{email:_e}:{}},i);_(gn(a.chat_history||[])),fe(!!a.is_human_handled),se(a.is_human_handled?`agent`:`ai`),Se(!1),await D.current.updateChatStatus(m,`messageSent`)}catch(e){_(e=>e.filter(e=>e.id!==o)),Se(!1),e.status===429?(Oe(!0),Ae(e.message),window.setTimeout(()=>{Oe(!1),Ae(``)},v)):c(e)}finally{Ee(!1)}},Et=async e=>{if(!D.current||!e)throw Error(`Upload is unavailable right now.`);return D.current.uploadChatFile(e)},Dt=async e=>{if(!(!D.current||!m)){try{let t=e?`voice`:`text`;await D.current.setChatMode(m,t)}catch(e){console.error(`[FlowEngageProvider] setVoiceMode failed`,e)}Me(e),e&&(it.current=!1)}},Ot=async e=>{if(it.current)return;if(it.current=!0,!D.current||!m||!e?.length){Me(!1);return}let t=()=>{let t=gn(e);_(e=>{if(!e.length)return t;let n=e[e.length-1],r=t[0];return n&&r&&n.sender===r.sender&&n.message===r.message?e:[...e,...t]})};try{let n=await D.current.syncVoice(m,e);if(n?.chat_history?.length)_(gn(n.chat_history));else if(n?.success)try{let e=await D.current.loadHistory(m,r);e?.chat_history?.length?_(gn(e.chat_history)):t()}catch{t()}else t()}catch{t()}finally{Me(!1)}},kt=async()=>{if(!(!D.current||!m)){je&&!it.current&&rt.current.length>0&&await Ot(rt.current);try{await D.current.endConversation(m)}catch{try{await D.current.updateChatStatus(m,`ended`)}catch{}}Pe(!0),_(e=>[...e,{id:`conversation-ended-${Date.now()}`,sender:`system`,message:`This conversation has ended. Thank you for reaching out!`,timestamp:new Date().toISOString(),isPending:!1}])}};(0,d.useEffect)(()=>{if(Le!==`connected`||!T||!m||!Re||!st)return;let e=new Date(Re).getTime(),t=Number.isFinite(e)?Date.now()-e:0,n=Math.max(0,st*1e3-t),r=window.setTimeout(()=>{Ue(`The call ended because it reached the time limit.`),vt()},n);return()=>window.clearTimeout(r)},[T,Re,Le,m,vt,st]),(0,d.useEffect)(()=>{let e=()=>{let e=O.current,t=D.current;if(!t||!e)return;if(Ze.current){t.beaconEndWebRTCCall(Ze.current,e);return}let n=Qe.current||Ge.current?.callId;n&&t.beaconCustomerUnavailable(n,e)};return window.addEventListener(`pagehide`,e),window.addEventListener(`beforeunload`,e),()=>{window.removeEventListener(`pagehide`,e),window.removeEventListener(`beforeunload`,e)}},[]);let At=(0,d.useMemo)(()=>({status:a,error:s,runtimeConfig:l,resolvedConfig:i,chatId:m,chatHistory:g,isOpen:x,activeScreen:oe,isHumanHandled:de,agentName:pe,agentHeadshot:he,visitorEmail:_e,isAgentTyping:ye,isAiTyping:xe,connectionStatus:Ce,isLoading:Te,isVoiceMode:je,isRateLimited:De,rateLimitMessage:ke,isConversationEnded:Ne,incomingCall:w,activeCallId:T,callConnectionState:Le,callConnectedAt:Re,isCallMuted:Be,webRTCError:He,language:r,historyRef:rt,hasSyncedRef:it,dismissCallError:ct,captureVisitorEmail:xt,startTyping:St,stopTyping:Ct,updateTypingDraft:wt,notifyRouteChange:()=>at.current?.notifyRouteChange?.(),openWidget:bt,closeWidget:()=>S(!1),toggleWidget:()=>{if(x){S(!1);return}bt({notifyChatInitiated:!0})},sendMessage:Tt,uploadChatFile:Et,setVoiceMode:Dt,onMessageSync:Ot,endConversation:kt,acceptCall:ht,rejectCall:gt,endWebRTCCall:vt,toggleCallMute:yt}),[a,s,l,i,m,g,x,oe,de,pe,he,_e,ye,xe,Ce,Te,je,De,ke,Ne,w,T,Le,Re,Be,He,r,xt,St,Ct,wt,ht,gt,vt,yt,bt,Tt,Et,Dt,Ot,kt,ct]);return(0,f.jsx)(Zt.Provider,{value:At,children:n})}var Cn=(0,d.createContext)({});function wn(e){let t=(0,d.useRef)(null);return t.current===null&&(t.current=e()),t.current}var Tn=typeof window<`u`?d.useLayoutEffect:d.useEffect,En=(0,d.createContext)(null);function Dn(e,t){e.indexOf(t)===-1&&e.push(t)}function On(e,t){let n=e.indexOf(t);n>-1&&e.splice(n,1)}var kn=(e,t,n)=>n>t?t:n<e?e:n;function An(e,t){return t?`${e}. For more information and steps for solving, visit https://motion.dev/troubleshooting/${t}`:e}var jn=()=>{},Mn=()=>{};typeof process<`u`&&process.env.NODE_ENV!==`production`&&(jn=(e,t,n)=>{!e&&typeof console<`u`&&console.warn(An(t,n))},Mn=(e,t,n)=>{if(!e)throw Error(An(t,n))});var Nn={},Pn=e=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(e);function Fn(e){return typeof e==`object`&&!!e}var In=e=>/^0[^.\s]+$/u.test(e);function Ln(e){let t;return()=>(t===void 0&&(t=e()),t)}var Rn=e=>e,zn=(e,t)=>n=>t(e(n)),Bn=(...e)=>e.reduce(zn),Vn=(e,t,n)=>{let r=t-e;return r===0?1:(n-e)/r},Hn=class{constructor(){this.subscriptions=[]}add(e){return Dn(this.subscriptions,e),()=>On(this.subscriptions,e)}notify(e,t,n){let r=this.subscriptions.length;if(r)if(r===1)this.subscriptions[0](e,t,n);else for(let i=0;i<r;i++){let r=this.subscriptions[i];r&&r(e,t,n)}}getSize(){return this.subscriptions.length}clear(){this.subscriptions.length=0}},Un=e=>e*1e3,Wn=e=>e/1e3;function Gn(e,t){return t?1e3/t*e:0}var Kn=new Set;function qn(e,t,n){e||Kn.has(t)||(console.warn(An(t,n)),Kn.add(t))}var Jn=(e,t,n)=>(((1-3*n+3*t)*e+(3*n-6*t))*e+3*t)*e,Yn=1e-7,Xn=12;function Zn(e,t,n,r,i){let a,o,s=0;do o=t+(n-t)/2,a=Jn(o,r,i)-e,a>0?n=o:t=o;while(Math.abs(a)>Yn&&++s<Xn);return o}function Qn(e,t,n,r){if(e===t&&n===r)return Rn;let i=t=>Zn(t,0,1,e,n);return e=>e===0||e===1?e:Jn(i(e),t,r)}var $n=e=>t=>t<=.5?e(2*t)/2:(2-e(2*(1-t)))/2,er=e=>t=>1-e(1-t),tr=Qn(.33,1.53,.69,.99),nr=er(tr),rr=$n(nr),ir=e=>e>=1?1:(e*=2)<1?.5*nr(e):.5*(2-2**(-10*(e-1))),ar=e=>1-Math.sin(Math.acos(e)),or=er(ar),sr=$n(ar),cr=Qn(.42,0,1,1),lr=Qn(0,0,.58,1),ur=Qn(.42,0,.58,1),dr=e=>Array.isArray(e)&&typeof e[0]!=`number`,fr=e=>Array.isArray(e)&&typeof e[0]==`number`,pr={linear:Rn,easeIn:cr,easeInOut:ur,easeOut:lr,circIn:ar,circInOut:sr,circOut:or,backIn:nr,backInOut:rr,backOut:tr,anticipate:ir},mr=e=>typeof e==`string`,hr=e=>{if(fr(e)){Mn(e.length===4,`Cubic bezier arrays must contain four numerical values.`,`cubic-bezier-length`);let[t,n,r,i]=e;return Qn(t,n,r,i)}else if(mr(e))return Mn(pr[e]!==void 0,`Invalid easing type '${e}'`,`invalid-easing-type`),pr[e];return e},gr=[`setup`,`read`,`resolveKeyframes`,`preUpdate`,`update`,`preRender`,`render`,`postRender`],_r={value:null,addProjectionMetrics:null};function vr(e,t){let n=new Set,r=new Set,i=!1,a=!1,o=new WeakSet,s={delta:0,timestamp:0,isProcessing:!1},c=0;function l(t){o.has(t)&&(u.schedule(t),e()),c++,t(s)}let u={schedule:(e,t=!1,a=!1)=>{let s=a&&i?n:r;return t&&o.add(e),s.add(e),e},cancel:e=>{r.delete(e),o.delete(e)},process:e=>{if(s=e,i){a=!0;return}i=!0;let o=n;n=r,r=o,n.forEach(l),t&&_r.value&&_r.value.frameloop[t].push(c),c=0,n.clear(),i=!1,a&&(a=!1,u.process(e))}};return u}var yr=40;function br(e,t){let n=!1,r=!0,i={delta:0,timestamp:0,isProcessing:!1},a=()=>n=!0,o=gr.reduce((e,n)=>(e[n]=vr(a,t?n:void 0),e),{}),{setup:s,read:c,resolveKeyframes:l,preUpdate:u,update:d,preRender:f,render:p,postRender:m}=o,h=()=>{let a=Nn.useManualTiming,o=a?i.timestamp:performance.now();n=!1,a||(i.delta=r?1e3/60:Math.max(Math.min(o-i.timestamp,yr),1)),i.timestamp=o,i.isProcessing=!0,s.process(i),c.process(i),l.process(i),u.process(i),d.process(i),f.process(i),p.process(i),m.process(i),i.isProcessing=!1,n&&t&&(r=!1,e(h))},g=()=>{n=!0,r=!0,i.isProcessing||e(h)};return{schedule:gr.reduce((e,t)=>{let r=o[t];return e[t]=(e,t=!1,i=!1)=>(n||g(),r.schedule(e,t,i)),e},{}),cancel:e=>{for(let t=0;t<gr.length;t++)o[gr[t]].cancel(e)},state:i,steps:o}}var{schedule:A,cancel:xr,state:Sr,steps:Cr}=br(typeof requestAnimationFrame<`u`?requestAnimationFrame:Rn,!0),wr;function Tr(){wr=void 0}var Er={now:()=>(wr===void 0&&Er.set(Sr.isProcessing||Nn.useManualTiming?Sr.timestamp:performance.now()),wr),set:e=>{wr=e,queueMicrotask(Tr)}},Dr={layout:0,mainThread:0,waapi:0},Or=e=>t=>typeof t==`string`&&t.startsWith(e),kr=Or(`--`),Ar=Or(`var(--`),jr=e=>Ar(e)?Mr.test(e.split(`/*`)[0].trim()):!1,Mr=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu;function Nr(e){return typeof e==`string`?e.split(`/*`)[0].includes(`var(--`):!1}var Pr={test:e=>typeof e==`number`,parse:parseFloat,transform:e=>e},Fr={...Pr,transform:e=>kn(0,1,e)},Ir={...Pr,default:1},Lr=e=>Math.round(e*1e5)/1e5,Rr=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function zr(e){return e==null}var Br=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,Vr=(e,t)=>n=>!!(typeof n==`string`&&Br.test(n)&&n.startsWith(e)||t&&!zr(n)&&Object.prototype.hasOwnProperty.call(n,t)),Hr=(e,t,n)=>r=>{if(typeof r!=`string`)return r;let[i,a,o,s]=r.match(Rr);return{[e]:parseFloat(i),[t]:parseFloat(a),[n]:parseFloat(o),alpha:s===void 0?1:parseFloat(s)}},Ur=e=>kn(0,255,e),Wr={...Pr,transform:e=>Math.round(Ur(e))},Gr={test:Vr(`rgb`,`red`),parse:Hr(`red`,`green`,`blue`),transform:({red:e,green:t,blue:n,alpha:r=1})=>`rgba(`+Wr.transform(e)+`, `+Wr.transform(t)+`, `+Wr.transform(n)+`, `+Lr(Fr.transform(r))+`)`};function Kr(e){let t=``,n=``,r=``,i=``;return e.length>5?(t=e.substring(1,3),n=e.substring(3,5),r=e.substring(5,7),i=e.substring(7,9)):(t=e.substring(1,2),n=e.substring(2,3),r=e.substring(3,4),i=e.substring(4,5),t+=t,n+=n,r+=r,i+=i),{red:parseInt(t,16),green:parseInt(n,16),blue:parseInt(r,16),alpha:i?parseInt(i,16)/255:1}}var qr={test:Vr(`#`),parse:Kr,transform:Gr.transform},Jr=e=>({test:t=>typeof t==`string`&&t.endsWith(e)&&t.split(` `).length===1,parse:parseFloat,transform:t=>`${t}${e}`}),Yr=Jr(`deg`),Xr=Jr(`%`),j=Jr(`px`),Zr=Jr(`vh`),Qr=Jr(`vw`),$r={...Xr,parse:e=>Xr.parse(e)/100,transform:e=>Xr.transform(e*100)},ei={test:Vr(`hsl`,`hue`),parse:Hr(`hue`,`saturation`,`lightness`),transform:({hue:e,saturation:t,lightness:n,alpha:r=1})=>`hsla(`+Math.round(e)+`, `+Xr.transform(Lr(t))+`, `+Xr.transform(Lr(n))+`, `+Lr(Fr.transform(r))+`)`},ti={test:e=>Gr.test(e)||qr.test(e)||ei.test(e),parse:e=>Gr.test(e)?Gr.parse(e):ei.test(e)?ei.parse(e):qr.parse(e),transform:e=>typeof e==`string`?e:e.hasOwnProperty(`red`)?Gr.transform(e):ei.transform(e),getAnimatableNone:e=>{let t=ti.parse(e);return t.alpha=0,ti.transform(t)}},ni=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function ri(e){return isNaN(e)&&typeof e==`string`&&(e.match(Rr)?.length||0)+(e.match(ni)?.length||0)>0}var ii=`number`,ai=`color`,oi=`var`,si=`var(`,ci="${}",li=/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 ui(e){let t=e.toString(),n=[],r={color:[],number:[],var:[]},i=[],a=0;return{values:n,split:t.replace(li,e=>(ti.test(e)?(r.color.push(a),i.push(ai),n.push(ti.parse(e))):e.startsWith(si)?(r.var.push(a),i.push(oi),n.push(e)):(r.number.push(a),i.push(ii),n.push(parseFloat(e))),++a,ci)).split(ci),indexes:r,types:i}}function di(e){return ui(e).values}function fi({split:e,types:t}){let n=e.length;return r=>{let i=``;for(let a=0;a<n;a++)if(i+=e[a],r[a]!==void 0){let e=t[a];e===ii?i+=Lr(r[a]):e===ai?i+=ti.transform(r[a]):i+=r[a]}return i}}function pi(e){return fi(ui(e))}var mi=e=>typeof e==`number`?0:ti.test(e)?ti.getAnimatableNone(e):e,hi=(e,t)=>typeof e==`number`?t?.trim().endsWith(`/`)?e:0:mi(e);function gi(e){let t=ui(e);return fi(t)(t.values.map((e,n)=>hi(e,t.split[n])))}var _i={test:ri,parse:di,createTransformer:pi,getAnimatableNone:gi};function vi(e,t,n){return n<0&&(n+=1),n>1&&--n,n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*(2/3-n)*6:e}function yi({hue:e,saturation:t,lightness:n,alpha:r}){e/=360,t/=100,n/=100;let i=0,a=0,o=0;if(!t)i=a=o=n;else{let r=n<.5?n*(1+t):n+t-n*t,s=2*n-r;i=vi(s,r,e+1/3),a=vi(s,r,e),o=vi(s,r,e-1/3)}return{red:Math.round(i*255),green:Math.round(a*255),blue:Math.round(o*255),alpha:r}}function bi(e,t){return n=>n>0?t:e}var M=(e,t,n)=>e+(t-e)*n,xi=(e,t,n)=>{let r=e*e,i=n*(t*t-r)+r;return i<0?0:Math.sqrt(i)},Si=[qr,Gr,ei],Ci=e=>Si.find(t=>t.test(e));function wi(e){let t=Ci(e);if(jn(!!t,`'${e}' is not an animatable color. Use the equivalent color code instead.`,`color-not-animatable`),!t)return!1;let n=t.parse(e);return t===ei&&(n=yi(n)),n}var Ti=(e,t)=>{let n=wi(e),r=wi(t);if(!n||!r)return bi(e,t);let i={...n};return e=>(i.red=xi(n.red,r.red,e),i.green=xi(n.green,r.green,e),i.blue=xi(n.blue,r.blue,e),i.alpha=M(n.alpha,r.alpha,e),Gr.transform(i))},Ei=new Set([`none`,`hidden`]);function Di(e,t){return Ei.has(e)?n=>n<=0?e:t:n=>n>=1?t:e}function Oi(e,t){return n=>M(e,t,n)}function ki(e){return typeof e==`number`?Oi:typeof e==`string`?jr(e)?bi:ti.test(e)?Ti:Ni:Array.isArray(e)?Ai:typeof e==`object`?ti.test(e)?Ti:ji:bi}function Ai(e,t){let n=[...e],r=n.length,i=e.map((e,n)=>ki(e)(e,t[n]));return e=>{for(let t=0;t<r;t++)n[t]=i[t](e);return n}}function ji(e,t){let n={...e,...t},r={};for(let i in n)e[i]!==void 0&&t[i]!==void 0&&(r[i]=ki(e[i])(e[i],t[i]));return e=>{for(let t in r)n[t]=r[t](e);return n}}function Mi(e,t){let n=[],r={color:0,var:0,number:0};for(let i=0;i<t.values.length;i++){let a=t.types[i],o=e.indexes[a][r[a]];n[i]=e.values[o]??0,r[a]++}return n}var Ni=(e,t)=>{let n=_i.createTransformer(t),r=ui(e),i=ui(t);return r.indexes.var.length===i.indexes.var.length&&r.indexes.color.length===i.indexes.color.length&&r.indexes.number.length>=i.indexes.number.length?Ei.has(e)&&!i.values.length||Ei.has(t)&&!r.values.length?Di(e,t):Bn(Ai(Mi(r,i),i.values),n):(jn(!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.`,`complex-values-different`),bi(e,t))};function Pi(e,t,n){return typeof e==`number`&&typeof t==`number`&&typeof n==`number`?M(e,t,n):ki(e)(e,t)}var Fi=e=>{let t=({timestamp:t})=>e(t);return{start:(e=!0)=>A.update(t,e),stop:()=>xr(t),now:()=>Sr.isProcessing?Sr.timestamp:Er.now()}},Ii=(e,t,n=10)=>{let r=``,i=Math.max(Math.round(t/n),2);for(let t=0;t<i;t++)r+=Math.round(e(t/(i-1))*1e4)/1e4+`, `;return`linear(${r.substring(0,r.length-2)})`},Li=2e4;function Ri(e){let t=0,n=e.next(t);for(;!n.done&&t<2e4;)t+=50,n=e.next(t);return t>=2e4?1/0:t}function zi(e,t=100,n){let r=n({...e,keyframes:[0,t]}),i=Math.min(Ri(r),Li);return{type:`keyframes`,ease:e=>r.next(i*e).value/t,duration:Wn(i)}}var Bi={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 Vi(e,t){return e*Math.sqrt(1-t*t)}var Hi=12;function Ui(e,t,n){let r=n;for(let n=1;n<Hi;n++)r-=e(r)/t(r);return r}var Wi=.001;function Gi({duration:e=Bi.duration,bounce:t=Bi.bounce,velocity:n=Bi.velocity,mass:r=Bi.mass}){let i,a;jn(e<=Un(Bi.maxDuration),`Spring duration must be 10 seconds or less`,`spring-duration-limit`);let o=1-t;o=kn(Bi.minDamping,Bi.maxDamping,o),e=kn(Bi.minDuration,Bi.maxDuration,Wn(e)),o<1?(i=t=>{let r=t*o,i=r*e,a=r-n,s=Vi(t,o),c=Math.exp(-i);return Wi-a/s*c},a=t=>{let r=t*o*e,a=r*n+n,s=o**2*t**2*e,c=Math.exp(-r),l=Vi(t**2,o);return(-i(t)+Wi>0?-1:1)*((a-s)*c)/l}):(i=t=>{let r=Math.exp(-t*e),i=(t-n)*e+1;return-Wi+r*i},a=t=>Math.exp(-t*e)*((n-t)*(e*e)));let s=5/e,c=Ui(i,a,s);if(e=Un(e),isNaN(c))return{stiffness:Bi.stiffness,damping:Bi.damping,duration:e};{let t=c**2*r;return{stiffness:t,damping:o*2*Math.sqrt(r*t),duration:e}}}var Ki=[`duration`,`bounce`],qi=[`stiffness`,`damping`,`mass`];function Ji(e,t){return t.some(t=>e[t]!==void 0)}function Yi(e){let t={velocity:Bi.velocity,stiffness:Bi.stiffness,damping:Bi.damping,mass:Bi.mass,isResolvedFromDuration:!1,...e};if(!Ji(e,qi)&&Ji(e,Ki))if(t.velocity=0,e.visualDuration){let n=e.visualDuration,r=2*Math.PI/(n*1.2),i=r*r,a=2*kn(.05,1,1-(e.bounce||0))*Math.sqrt(i);t={...t,mass:Bi.mass,stiffness:i,damping:a}}else{let n=Gi({...e,velocity:0});t={...t,...n,mass:Bi.mass},t.isResolvedFromDuration=!0}return t}function Xi(e=Bi.visualDuration,t=Bi.bounce){let n=typeof e==`object`?e:{visualDuration:e,keyframes:[0,1],bounce:t},{restSpeed:r,restDelta:i}=n,a=n.keyframes[0],o=n.keyframes[n.keyframes.length-1],s={done:!1,value:a},{stiffness:c,damping:l,mass:u,duration:d,velocity:f,isResolvedFromDuration:p}=Yi({...n,velocity:-Wn(n.velocity||0)}),m=f||0,h=l/(2*Math.sqrt(c*u)),g=o-a,_=Wn(Math.sqrt(c/u)),v=Math.abs(g)<5;r||=v?Bi.restSpeed.granular:Bi.restSpeed.default,i||=v?Bi.restDelta.granular:Bi.restDelta.default;let y,b,x,S,ee,te;if(h<1)x=Vi(_,h),S=(m+h*_*g)/x,y=e=>o-Math.exp(-h*_*e)*(S*Math.sin(x*e)+g*Math.cos(x*e)),ee=h*_*S+g*x,te=h*_*g-S*x,b=e=>Math.exp(-h*_*e)*(ee*Math.sin(x*e)+te*Math.cos(x*e));else if(h===1){y=e=>o-Math.exp(-_*e)*(g+(m+_*g)*e);let e=m+_*g;b=t=>Math.exp(-_*t)*(_*e*t-m)}else{let e=_*Math.sqrt(h*h-1);y=t=>{let n=Math.exp(-h*_*t),r=Math.min(e*t,300);return o-n*((m+h*_*g)*Math.sinh(r)+e*g*Math.cosh(r))/e};let t=(m+h*_*g)/e,n=h*_*t-g*e,r=h*_*g-t*e;b=t=>{let i=Math.exp(-h*_*t),a=Math.min(e*t,300);return i*(n*Math.sinh(a)+r*Math.cosh(a))}}let C={calculatedDuration:p&&d||null,velocity:e=>Un(b(e)),next:e=>{if(!p&&h<1){let t=Math.exp(-h*_*e),n=Math.sin(x*e),a=Math.cos(x*e),c=o-t*(S*n+g*a),l=Un(t*(ee*n+te*a));return s.done=Math.abs(l)<=r&&Math.abs(o-c)<=i,s.value=s.done?o:c,s}let t=y(e);if(p)s.done=e>=d;else{let n=Un(b(e));s.done=Math.abs(n)<=r&&Math.abs(o-t)<=i}return s.value=s.done?o:t,s},toString:()=>{let e=Math.min(Ri(C),Li),t=Ii(t=>C.next(e*t).value,e,30);return e+`ms `+t},toTransition:()=>{}};return C}Xi.applyToOptions=e=>{let t=zi(e,100,Xi);return e.ease=t.ease,e.duration=Un(t.duration),e.type=`keyframes`,e};var Zi=5;function Qi(e,t,n){let r=Math.max(t-Zi,0);return Gn(n-e(r),t-r)}function $i({keyframes:e,velocity:t=0,power:n=.8,timeConstant:r=325,bounceDamping:i=10,bounceStiffness:a=500,modifyTarget:o,min:s,max:c,restDelta:l=.5,restSpeed:u}){let d=e[0],f={done:!1,value:d},p=e=>s!==void 0&&e<s||c!==void 0&&e>c,m=e=>s===void 0?c:c===void 0||Math.abs(s-e)<Math.abs(c-e)?s:c,h=n*t,g=d+h,_=o===void 0?g:o(g);_!==g&&(h=_-d);let v=e=>-h*Math.exp(-e/r),y=e=>_+v(e),b=e=>{let t=v(e),n=y(e);f.done=Math.abs(t)<=l,f.value=f.done?_:n},x,S,ee=e=>{p(f.value)&&(x=e,S=Xi({keyframes:[f.value,m(f.value)],velocity:Qi(y,e,f.value),damping:i,stiffness:a,restDelta:l,restSpeed:u}))};return ee(0),{calculatedDuration:null,next:e=>{let t=!1;return!S&&x===void 0&&(t=!0,b(e),ee(e)),x!==void 0&&e>=x?S.next(e-x):(!t&&b(e),f)}}}function ea(e,t,n){let r=[],i=n||Nn.mix||Pi,a=e.length-1;for(let n=0;n<a;n++){let a=i(e[n],e[n+1]);t&&(a=Bn(Array.isArray(t)?t[n]||Rn:t,a)),r.push(a)}return r}function ta(e,t,{clamp:n=!0,ease:r,mixer:i}={}){let a=e.length;if(Mn(a===t.length,`Both input and output ranges must be the same length`,`range-length`),a===1)return()=>t[0];if(a===2&&t[0]===t[1])return()=>t[1];let o=e[0]===e[1];e[0]>e[a-1]&&(e=[...e].reverse(),t=[...t].reverse());let s=ea(t,r,i),c=s.length,l=n=>{if(o&&n<e[0])return t[0];let r=0;if(c>1)for(;r<e.length-2&&!(n<e[r+1]);r++);let i=Vn(e[r],e[r+1],n);return s[r](i)};return n?t=>l(kn(e[0],e[a-1],t)):l}function na(e,t){let n=e[e.length-1];for(let r=1;r<=t;r++){let i=Vn(0,t,r);e.push(M(n,1,i))}}function ra(e){let t=[0];return na(t,e.length-1),t}function ia(e,t){return e.map(e=>e*t)}function aa(e,t){return e.map(()=>t||ur).splice(0,e.length-1)}function oa({duration:e=300,keyframes:t,times:n,ease:r=`easeInOut`}){let i=dr(r)?r.map(hr):hr(r),a={done:!1,value:t[0]},o=ta(ia(n&&n.length===t.length?n:ra(t),e),t,{ease:Array.isArray(i)?i:aa(t,i)});return{calculatedDuration:e,next:t=>(a.value=o(t),a.done=t>=e,a)}}var sa=e=>e!==null;function ca(e,{repeat:t,repeatType:n=`loop`},r,i=1){let a=e.filter(sa),o=i<0||t&&n!==`loop`&&t%2==1?0:a.length-1;return!o||r===void 0?a[o]:r}var la={decay:$i,inertia:$i,tween:oa,keyframes:oa,spring:Xi};function ua(e){typeof e.type==`string`&&(e.type=la[e.type])}var da=class{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(e=>{this.resolve=e})}notifyFinished(){this.resolve()}then(e,t){return this.finished.then(e,t)}},fa=e=>e/100,pa=class extends da{constructor(e){super(),this.state=`idle`,this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.delayState={done:!1,value:void 0},this.stop=()=>{let{motionValue:e}=this.options;e&&e.updatedAt!==Er.now()&&this.tick(Er.now()),this.isStopped=!0,this.state!==`idle`&&(this.teardown(),this.options.onStop?.())},Dr.mainThread++,this.options=e,this.initAnimation(),this.play(),e.autoplay===!1&&this.pause()}initAnimation(){let{options:e}=this;ua(e);let{type:t=oa,repeat:n=0,repeatDelay:r=0,repeatType:i,velocity:a=0}=e,{keyframes:o}=e,s=t||oa;process.env.NODE_ENV!==`production`&&s!==oa&&Mn(o.length<=2,`Only two keyframes currently supported with spring and inertia animations. Trying to animate ${o}`,`spring-two-frames`),s!==oa&&typeof o[0]!=`number`&&(this.mixKeyframes=Bn(fa,Pi(o[0],o[1])),o=[0,100]);let c=s({...e,keyframes:o});i===`mirror`&&(this.mirroredGenerator=s({...e,keyframes:[...o].reverse(),velocity:-a})),c.calculatedDuration===null&&(c.calculatedDuration=Ri(c));let{calculatedDuration:l}=c;this.calculatedDuration=l,this.resolvedDuration=l+r,this.totalDuration=this.resolvedDuration*(n+1)-r,this.generator=c}updateTime(e){let t=Math.round(e-this.startTime)*this.playbackSpeed;this.holdTime===null?this.currentTime=t:this.currentTime=this.holdTime}tick(e,t=!1){let{generator:n,totalDuration:r,mixKeyframes:i,mirroredGenerator:a,resolvedDuration:o,calculatedDuration:s}=this;if(this.startTime===null)return n.next(0);let{delay:c=0,keyframes:l,repeat:u,repeatType:d,repeatDelay:f,type:p,onUpdate:m,finalKeyframe:h}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,e):this.speed<0&&(this.startTime=Math.min(e-r/this.speed,this.startTime)),t?this.currentTime=e:this.updateTime(e);let g=this.currentTime-c*(this.playbackSpeed>=0?1:-1),_=this.playbackSpeed>=0?g<0:g>r;this.currentTime=Math.max(g,0),this.state===`finished`&&this.holdTime===null&&(this.currentTime=r);let v=this.currentTime,y=n;if(u){let e=Math.min(this.currentTime,r)/o,t=Math.floor(e),n=e%1;!n&&e>=1&&(n=1),n===1&&t--,t=Math.min(t,u+1),t%2&&(d===`reverse`?(n=1-n,f&&(n-=f/o)):d===`mirror`&&(y=a)),v=kn(0,1,n)*o}let b;_?(this.delayState.value=l[0],b=this.delayState):b=y.next(v),i&&!_&&(b.value=i(b.value));let{done:x}=b;!_&&s!==null&&(x=this.playbackSpeed>=0?this.currentTime>=r:this.currentTime<=0);let S=this.holdTime===null&&(this.state===`finished`||this.state===`running`&&x);return S&&p!==$i&&(b.value=ca(l,this.options,h,this.speed)),m&&m(b.value),S&&this.finish(),b}then(e,t){return this.finished.then(e,t)}get duration(){return Wn(this.calculatedDuration)}get iterationDuration(){let{delay:e=0}=this.options||{};return this.duration+Wn(e)}get time(){return Wn(this.currentTime)}set time(e){e=Un(e),this.currentTime=e,this.startTime===null||this.holdTime!==null||this.playbackSpeed===0?this.holdTime=e:this.driver&&(this.startTime=this.driver.now()-e/this.playbackSpeed),this.driver?this.driver.start(!1):(this.startTime=0,this.state=`paused`,this.holdTime=e,this.tick(e))}getGeneratorVelocity(){let e=this.currentTime;if(e<=0)return this.options.velocity||0;if(this.generator.velocity)return this.generator.velocity(e);let t=this.generator.next(e).value;return Qi(e=>this.generator.next(e).value,e,t)}get speed(){return this.playbackSpeed}set speed(e){let t=this.playbackSpeed!==e;t&&this.driver&&this.updateTime(Er.now()),this.playbackSpeed=e,t&&this.driver&&(this.time=Wn(this.currentTime))}play(){if(this.isStopped)return;let{driver:e=Fi,startTime:t}=this.options;this.driver||=e(e=>this.tick(e)),this.options.onPlay?.();let n=this.driver.now();this.state===`finished`?(this.updateFinished(),this.startTime=n):this.holdTime===null?this.startTime||=t??n:this.startTime=n-this.holdTime,this.state===`finished`&&this.speed<0&&(this.startTime+=this.calculatedDuration),this.holdTime=null,this.state=`running`,this.driver.start()}pause(){this.state=`paused`,this.updateTime(Er.now()),this.holdTime=this.currentTime}complete(){this.state!==`running`&&this.play(),this.state=`finished`,this.holdTime=null}finish(){this.notifyFinished(),this.teardown(),this.state=`finished`,this.options.onComplete?.()}cancel(){this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),this.options.onCancel?.()}teardown(){this.state=`idle`,this.stopDriver(),this.startTime=this.holdTime=null,Dr.mainThread--}stopDriver(){this.driver&&=(this.driver.stop(),void 0)}sample(e){return this.startTime=0,this.tick(e,!0)}attachTimeline(e){return this.options.allowFlatten&&(this.options.type=`keyframes`,this.options.ease=`linear`,this.initAnimation()),this.driver?.stop(),e.observe(this)}};function ma(e){for(let t=1;t<e.length;t++)e[t]??(e[t]=e[t-1])}var ha=e=>e*180/Math.PI,ga=e=>va(ha(Math.atan2(e[1],e[0]))),_a={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:e=>(Math.abs(e[0])+Math.abs(e[3]))/2,rotate:ga,rotateZ:ga,skewX:e=>ha(Math.atan(e[1])),skewY:e=>ha(Math.atan(e[2])),skew:e=>(Math.abs(e[1])+Math.abs(e[2]))/2},va=e=>(e%=360,e<0&&(e+=360),e),ya=ga,ba=e=>Math.sqrt(e[0]*e[0]+e[1]*e[1]),xa=e=>Math.sqrt(e[4]*e[4]+e[5]*e[5]),Sa={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:ba,scaleY:xa,scale:e=>(ba(e)+xa(e))/2,rotateX:e=>va(ha(Math.atan2(e[6],e[5]))),rotateY:e=>va(ha(Math.atan2(-e[2],e[0]))),rotateZ:ya,rotate:ya,skewX:e=>ha(Math.atan(e[4])),skewY:e=>ha(Math.atan(e[1])),skew:e=>(Math.abs(e[1])+Math.abs(e[4]))/2};function Ca(e){return e.includes(`scale`)?1:0}function wa(e,t){if(!e||e===`none`)return Ca(t);let n=e.match(/^matrix3d\(([-\d.e\s,]+)\)$/u),r,i;if(n)r=Sa,i=n;else{let t=e.match(/^matrix\(([-\d.e\s,]+)\)$/u);r=_a,i=t}if(!i)return Ca(t);let a=r[t],o=i[1].split(`,`).map(Ea);return typeof a==`function`?a(o):o[a]}var Ta=(e,t)=>{let{transform:n=`none`}=getComputedStyle(e);return wa(n,t)};function Ea(e){return parseFloat(e.trim())}var Da=[`transformPerspective`,`x`,`y`,`z`,`translateX`,`translateY`,`translateZ`,`scale`,`scaleX`,`scaleY`,`rotate`,`rotateX`,`rotateY`,`rotateZ`,`skew`,`skewX`,`skewY`],Oa=new Set(Da),ka=e=>e===Pr||e===j,Aa=new Set([`x`,`y`,`z`]),ja=Da.filter(e=>!Aa.has(e));function Ma(e){let t=[];return ja.forEach(n=>{let r=e.getValue(n);r!==void 0&&(t.push([n,r.get()]),r.set(n.startsWith(`scale`)?1:0))}),t}var Na={width:({x:e},{paddingLeft:t=`0`,paddingRight:n=`0`,boxSizing:r})=>{let i=e.max-e.min;return r===`border-box`?i:i-parseFloat(t)-parseFloat(n)},height:({y:e},{paddingTop:t=`0`,paddingBottom:n=`0`,boxSizing:r})=>{let i=e.max-e.min;return r===`border-box`?i:i-parseFloat(t)-parseFloat(n)},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:(e,{transform:t})=>wa(t,`x`),y:(e,{transform:t})=>wa(t,`y`)};Na.translateX=Na.x,Na.translateY=Na.y;var Pa=new Set,Fa=!1,Ia=!1,La=!1;function Ra(){if(Ia){let e=Array.from(Pa).filter(e=>e.needsMeasurement),t=new Set(e.map(e=>e.element)),n=new Map;t.forEach(e=>{let t=Ma(e);t.length&&(n.set(e,t),e.render())}),e.forEach(e=>e.measureInitialState()),t.forEach(e=>{e.render();let t=n.get(e);t&&t.forEach(([t,n])=>{e.getValue(t)?.set(n)})}),e.forEach(e=>e.measureEndState()),e.forEach(e=>{e.suspendedScrollY!==void 0&&window.scrollTo(0,e.suspendedScrollY)})}Ia=!1,Fa=!1,Pa.forEach(e=>e.complete(La)),Pa.clear()}function za(){Pa.forEach(e=>{e.readKeyframes(),e.needsMeasurement&&(Ia=!0)})}function Ba(){La=!0,za(),Ra(),La=!1}var Va=class{constructor(e,t,n,r,i,a=!1){this.state=`pending`,this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...e],this.onComplete=t,this.name=n,this.motionValue=r,this.element=i,this.isAsync=a}scheduleResolve(){this.state=`scheduled`,this.isAsync?(Pa.add(this),Fa||(Fa=!0,A.read(za),A.resolveKeyframes(Ra))):(this.readKeyframes(),this.complete())}readKeyframes(){let{unresolvedKeyframes:e,name:t,element:n,motionValue:r}=this;if(e[0]===null){let i=r?.get(),a=e[e.length-1];if(i!==void 0)e[0]=i;else if(n&&t){let r=n.readValue(t,a);r!=null&&(e[0]=r)}e[0]===void 0&&(e[0]=a),r&&i===void 0&&r.set(e[0])}ma(e)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(e=!1){this.state=`complete`,this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,e),Pa.delete(this)}cancel(){this.state===`scheduled`&&(Pa.delete(this),this.state=`pending`)}resume(){this.state===`pending`&&this.scheduleResolve()}},Ha=e=>e.startsWith(`--`);function Ua(e,t,n){Ha(t)?e.style.setProperty(t,n):e.style[t]=n}var Wa={};function Ga(e,t){let n=Ln(e);return()=>Wa[t]??n()}var Ka=Ga(()=>window.ScrollTimeline!==void 0,`scrollTimeline`),qa=Ga(()=>{try{document.createElement(`div`).animate({opacity:0},{easing:`linear(0, 1)`})}catch{return!1}return!0},`linearEasing`),Ja=([e,t,n,r])=>`cubic-bezier(${e}, ${t}, ${n}, ${r})`,Ya={linear:`linear`,ease:`ease`,easeIn:`ease-in`,easeOut:`ease-out`,easeInOut:`ease-in-out`,circIn:Ja([0,.65,.55,1]),circOut:Ja([.55,0,1,.45]),backIn:Ja([.31,.01,.66,-.59]),backOut:Ja([.33,1.53,.69,.99])};function Xa(e,t){if(e)return typeof e==`function`?qa()?Ii(e,t):`ease-out`:fr(e)?Ja(e):Array.isArray(e)?e.map(e=>Xa(e,t)||Ya.easeOut):Ya[e]}function Za(e,t,n,{delay:r=0,duration:i=300,repeat:a=0,repeatType:o=`loop`,ease:s=`easeOut`,times:c}={},l=void 0){let u={[t]:n};c&&(u.offset=c);let d=Xa(s,i);Array.isArray(d)&&(u.easing=d),_r.value&&Dr.waapi++;let f={delay:r,duration:i,easing:Array.isArray(d)?`linear`:d,fill:`both`,iterations:a+1,direction:o===`reverse`?`alternate`:`normal`};l&&(f.pseudoElement=l);let p=e.animate(u,f);return _r.value&&p.finished.finally(()=>{Dr.waapi--}),p}function Qa(e){return typeof e==`function`&&`applyToOptions`in e}function $a({type:e,...t}){return Qa(e)&&qa()?e.applyToOptions(t):(t.duration??=300,t.ease??=`easeOut`,t)}var eo=class extends da{constructor(e){if(super(),this.finishedTime=null,this.isStopped=!1,this.manualStartTime=null,!e)return;let{element:t,name:n,keyframes:r,pseudoElement:i,allowFlatten:a=!1,finalKeyframe:o,onComplete:s}=e;this.isPseudoElement=!!i,this.allowFlatten=a,this.options=e,Mn(typeof e.type!=`string`,`Mini animate() doesn't support "type" as a string.`,`mini-spring`);let c=$a(e);this.animation=Za(t,n,r,c,i),c.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!i){let e=ca(r,this.options,o,this.speed);this.updateMotionValue&&this.updateMotionValue(e),Ua(t,n,e),this.animation.cancel()}s?.(),this.notifyFinished()}}play(){this.isStopped||(this.manualStartTime=null,this.animation.play(),this.state===`finished`&&this.updateFinished())}pause(){this.animation.pause()}complete(){this.animation.finish?.()}cancel(){try{this.animation.cancel()}catch{}}stop(){if(this.isStopped)return;this.isStopped=!0;let{state:e}=this;e===`idle`||e===`finished`||(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){let e=this.options?.element;!this.isPseudoElement&&e?.isConnected&&this.animation.commitStyles?.()}get duration(){let e=this.animation.effect?.getComputedTiming?.().duration||0;return Wn(Number(e))}get iterationDuration(){let{delay:e=0}=this.options||{};return this.duration+Wn(e)}get time(){return Wn(Number(this.animation.currentTime)||0)}set time(e){let t=this.finishedTime!==null;this.manualStartTime=null,this.finishedTime=null,this.animation.currentTime=Un(e),t&&this.animation.pause()}get speed(){return this.animation.playbackRate}set speed(e){e<0&&(this.finishedTime=null),this.animation.playbackRate=e}get state(){return this.finishedTime===null?this.animation.playState:`finished`}get startTime(){return this.manualStartTime??Number(this.animation.startTime)}set startTime(e){this.manualStartTime=this.animation.startTime=e}attachTimeline({timeline:e,rangeStart:t,rangeEnd:n,observe:r}){return this.allowFlatten&&this.animation.effect?.updateTiming({easing:`linear`}),this.animation.onfinish=null,e&&Ka()?(this.animation.timeline=e,t&&(this.animation.rangeStart=t),n&&(this.animation.rangeEnd=n),Rn):r(this)}},to={anticipate:ir,backInOut:rr,circInOut:sr};function no(e){return e in to}function ro(e){typeof e.ease==`string`&&no(e.ease)&&(e.ease=to[e.ease])}var io=10,ao=class extends eo{constructor(e){ro(e),ua(e),super(e),e.startTime!==void 0&&e.autoplay!==!1&&(this.startTime=e.startTime),this.options=e}updateMotionValue(e){let{motionValue:t,onUpdate:n,onComplete:r,element:i,...a}=this.options;if(!t)return;if(e!==void 0){t.set(e);return}let o=new pa({...a,autoplay:!1}),s=Math.max(io,Er.now()-this.startTime),c=kn(0,io,s-io),l=o.sample(s).value,{name:u}=this.options;i&&u&&Ua(i,u,l),t.setWithVelocity(o.sample(Math.max(0,s-c)).value,l,c),o.stop()}},oo=(e,t)=>t===`zIndex`?!1:!!(typeof e==`number`||Array.isArray(e)||typeof e==`string`&&(_i.test(e)||e===`0`)&&!e.startsWith(`url(`));function so(e){let t=e[0];if(e.length===1)return!0;for(let n=0;n<e.length;n++)if(e[n]!==t)return!0}function co(e,t,n,r){let i=e[0];if(i===null)return!1;if(t===`display`||t===`visibility`)return!0;let a=e[e.length-1],o=oo(i,t),s=oo(a,t);return jn(o===s,`You are trying to animate ${t} from "${i}" to "${a}". "${o?a:i}" is not an animatable value.`,`value-not-animatable`),!o||!s?!1:so(e)||(n===`spring`||Qa(n))&&r}function lo(e){e.duration=0,e.type=`keyframes`}var uo=new Set([`opacity`,`clipPath`,`filter`,`transform`]),fo=/^(?:oklch|oklab|lab|lch|color|color-mix|light-dark)\(/;function po(e){for(let t=0;t<e.length;t++)if(typeof e[t]==`string`&&fo.test(e[t]))return!0;return!1}var mo=new Set([`color`,`backgroundColor`,`outlineColor`,`fill`,`stroke`,`borderColor`,`borderTopColor`,`borderRightColor`,`borderBottomColor`,`borderLeftColor`]),ho=Ln(()=>Object.hasOwnProperty.call(Element.prototype,`animate`));function go(e){let{motionValue:t,name:n,repeatDelay:r,repeatType:i,damping:a,type:o,keyframes:s}=e;if(!(t?.owner?.current instanceof HTMLElement))return!1;let{onUpdate:c,transformTemplate:l}=t.owner.getProps();return ho()&&n&&(uo.has(n)||mo.has(n)&&po(s))&&(n!==`transform`||!l)&&!c&&!r&&i!==`mirror`&&a!==0&&o!==`inertia`}var _o=40,vo=class extends da{constructor({autoplay:e=!0,delay:t=0,type:n=`keyframes`,repeat:r=0,repeatDelay:i=0,repeatType:a=`loop`,keyframes:o,name:s,motionValue:c,element:l,...u}){super(),this.stop=()=>{this._animation&&(this._animation.stop(),this.stopTimeline?.()),this.keyframeResolver?.cancel()},this.createdAt=Er.now();let d={autoplay:e,delay:t,type:n,repeat:r,repeatDelay:i,repeatType:a,name:s,motionValue:c,element:l,...u};this.keyframeResolver=new(l?.KeyframeResolver||Va)(o,(e,t,n)=>this.onKeyframesResolved(e,t,d,!n),s,c,l),this.keyframeResolver?.scheduleResolve()}onKeyframesResolved(e,t,n,r){this.keyframeResolver=void 0;let{name:i,type:a,velocity:o,delay:s,isHandoff:c,onUpdate:l}=n;this.resolvedAt=Er.now();let u=!0;co(e,i,a,o)||(u=!1,(Nn.instantAnimations||!s)&&l?.(ca(e,n,t)),e[0]=e[e.length-1],lo(n),n.repeat=0);let d={startTime:r?this.resolvedAt&&this.resolvedAt-this.createdAt>_o?this.resolvedAt:this.createdAt:void 0,finalKeyframe:t,...n,keyframes:e},f=u&&!c&&go(d),p=d.motionValue?.owner?.current,m;if(f)try{m=new ao({...d,element:p})}catch{m=new pa(d)}else m=new pa(d);m.finished.then(()=>{this.notifyFinished()}).catch(Rn),this.pendingTimeline&&=(this.stopTimeline=m.attachTimeline(this.pendingTimeline),void 0),this._animation=m}get finished(){return this._animation?this.animation.finished:this._finished}then(e,t){return this.finished.finally(e).then(()=>{})}get animation(){return this._animation||(this.keyframeResolver?.resume(),Ba()),this._animation}get duration(){return this.animation.duration}get iterationDuration(){return this.animation.iterationDuration}get time(){return this.animation.time}set time(e){this.animation.time=e}get speed(){return this.animation.speed}get state(){return this.animation.state}set speed(e){this.animation.speed=e}get startTime(){return this.animation.startTime}attachTimeline(e){return this._animation?this.stopTimeline=this.animation.attachTimeline(e):this.pendingTimeline=e,()=>this.stop()}play(){this.animation.play()}pause(){this.animation.pause()}complete(){this.animation.complete()}cancel(){this._animation&&this.animation.cancel(),this.keyframeResolver?.cancel()}};function yo(e,t,n,r=0,i=1){let a=Array.from(e).sort((e,t)=>e.sortNodePosition(t)).indexOf(t),o=e.size,s=(o-1)*r;return typeof n==`function`?n(a,o):i===1?a*r:s-a*r}var bo=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function xo(e){let t=bo.exec(e);if(!t)return[,];let[,n,r,i]=t;return[`--${n??r}`,i]}var So=4;function Co(e,t,n=1){Mn(n<=So,`Max CSS variable fallback depth detected in property "${e}". This may indicate a circular fallback dependency.`,`max-css-var-depth`);let[r,i]=xo(e);if(!r)return;let a=window.getComputedStyle(t).getPropertyValue(r);if(a){let e=a.trim();return Pn(e)?parseFloat(e):e}return jr(i)?Co(i,t,n+1):i}var wo={type:`spring`,stiffness:500,damping:25,restSpeed:10},To=e=>({type:`spring`,stiffness:550,damping:e===0?2*Math.sqrt(550):30,restSpeed:10}),Eo={type:`keyframes`,duration:.8},Do={type:`keyframes`,ease:[.25,.1,.35,1],duration:.3},Oo=(e,{keyframes:t})=>t.length>2?Eo:Oa.has(e)?e.startsWith(`scale`)?To(t[1]):wo:Do;function ko(e,t){if(e?.inherit&&t){let{inherit:n,...r}=e;return{...t,...r}}return e}function Ao(e,t){let n=e?.[t]??e?.default??e;return n===e?n:ko(n,e)}var jo=new Set([`when`,`delay`,`delayChildren`,`staggerChildren`,`staggerDirection`,`repeat`,`repeatType`,`repeatDelay`,`from`,`elapsed`]);function Mo(e){for(let t in e)if(!jo.has(t))return!0;return!1}var No=(e,t,n,r={},i,a)=>o=>{let s=Ao(r,e)||{},c=s.delay||r.delay||0,{elapsed:l=0}=r;l-=Un(c);let u={keyframes:Array.isArray(n)?n:[null,n],ease:`easeOut`,velocity:t.getVelocity(),...s,delay:-l,onUpdate:e=>{t.set(e),s.onUpdate&&s.onUpdate(e)},onComplete:()=>{o(),s.onComplete&&s.onComplete()},name:e,motionValue:t,element:a?void 0:i};Mo(s)||Object.assign(u,Oo(e,u)),u.duration&&=Un(u.duration),u.repeatDelay&&=Un(u.repeatDelay),u.from!==void 0&&(u.keyframes[0]=u.from);let d=!1;if((u.type===!1||u.duration===0&&!u.repeatDelay)&&(lo(u),u.delay===0&&(d=!0)),(Nn.instantAnimations||Nn.skipAnimations||i?.shouldSkipAnimations)&&(d=!0,lo(u),u.delay=0),u.allowFlatten=!s.type&&!s.ease,d&&!a&&t.get()!==void 0){let e=ca(u.keyframes,s);if(e!==void 0){A.update(()=>{u.onUpdate(e),u.onComplete()});return}}return s.isSync?new pa(u):new vo(u)};function Po(e){let t=[{},{}];return e?.values.forEach((e,n)=>{t[0][n]=e.get(),t[1][n]=e.getVelocity()}),t}function Fo(e,t,n,r){if(typeof t==`function`){let[i,a]=Po(r);t=t(n===void 0?e.custom:n,i,a)}if(typeof t==`string`&&(t=e.variants&&e.variants[t]),typeof t==`function`){let[i,a]=Po(r);t=t(n===void 0?e.custom:n,i,a)}return t}function Io(e,t,n){let r=e.getProps();return Fo(r,t,n===void 0?r.custom:n,e)}var Lo=new Set([`width`,`height`,`top`,`left`,`right`,`bottom`,...Da]),Ro=30,zo=e=>!isNaN(parseFloat(e)),Bo={current:void 0},Vo=class{constructor(e,t={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=e=>{let t=Er.now();if(this.updatedAt!==t&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(e),this.current!==this.prev&&(this.events.change?.notify(this.current),this.dependents))for(let e of this.dependents)e.dirty()},this.hasAnimated=!1,this.setCurrent(e),this.owner=t.owner}setCurrent(e){this.current=e,this.updatedAt=Er.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=zo(this.current))}setPrevFrameValue(e=this.current){this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt}onChange(e){return process.env.NODE_ENV!==`production`&&qn(!1,`value.onChange(callback) is deprecated. Switch to value.on("change", callback).`),this.on(`change`,e)}on(e,t){this.events[e]||(this.events[e]=new Hn);let n=this.events[e].add(t);return e===`change`?()=>{n(),A.read(()=>{this.events.change.getSize()||this.stop()})}:n}clearListeners(){for(let e in this.events)this.events[e].clear()}attach(e,t){this.passiveEffect=e,this.stopPassiveEffect=t}set(e){this.passiveEffect?this.passiveEffect(e,this.updateAndNotify):this.updateAndNotify(e)}setWithVelocity(e,t,n){this.set(t),this.prev=void 0,this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt-n}jump(e,t=!0){this.updateAndNotify(e),this.prev=e,this.prevUpdatedAt=this.prevFrameValue=void 0,t&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}dirty(){this.events.change?.notify(this.current)}addDependent(e){this.dependents||=new Set,this.dependents.add(e)}removeDependent(e){this.dependents&&this.dependents.delete(e)}get(){return Bo.current&&Bo.current.push(this),this.current}getPrevious(){return this.prev}getVelocity(){let e=Er.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>Ro)return 0;let t=Math.min(this.updatedAt-this.prevUpdatedAt,Ro);return Gn(parseFloat(this.current)-parseFloat(this.prevFrameValue),t)}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.dependents?.clear(),this.events.destroy?.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}};function Ho(e,t){return new Vo(e,t)}var Uo=e=>Array.isArray(e);function Wo(e,t,n){e.hasValue(t)?e.getValue(t).set(n):e.addValue(t,Ho(n))}function Go(e){return Uo(e)?e[e.length-1]||0:e}function Ko(e,t){let{transitionEnd:n={},transition:r={},...i}=Io(e,t)||{};i={...i,...n};for(let t in i)Wo(e,t,Go(i[t]))}var qo=e=>!!(e&&e.getVelocity);function Jo(e){return!!(qo(e)&&e.add)}function Yo(e,t){let n=e.getValue(`willChange`);if(Jo(n))return n.add(t);if(!n&&Nn.WillChange){let n=new Nn.WillChange(`auto`);e.addValue(`willChange`,n),n.add(t)}}function Xo(e){return e.replace(/([A-Z])/g,e=>`-${e.toLowerCase()}`)}var Zo=`data-`+Xo(`framerAppearId`);function Qo(e){return e.props[Zo]}function $o({protectedKeys:e,needsAnimating:t},n){let r=e.hasOwnProperty(n)&&t[n]!==!0;return t[n]=!1,r}function es(e,t,{delay:n=0,transitionOverride:r,type:i}={}){let{transition:a,transitionEnd:o,...s}=t,c=e.getDefaultTransition();a=a?ko(a,c):c;let l=a?.reduceMotion;r&&(a=r);let u=[],d=i&&e.animationState&&e.animationState.getState()[i];for(let t in s){let r=e.getValue(t,e.latestValues[t]??null),i=s[t];if(i===void 0||d&&$o(d,t))continue;let o={delay:n,...Ao(a||{},t)},c=r.get();if(c!==void 0&&!r.isAnimating()&&!Array.isArray(i)&&i===c&&!o.velocity){A.update(()=>r.set(i));continue}let f=!1;if(window.MotionHandoffAnimation){let n=Qo(e);if(n){let e=window.MotionHandoffAnimation(n,t,A);e!==null&&(o.startTime=e,f=!0)}}Yo(e,t);let p=l??e.shouldReduceMotion;r.start(No(t,r,i,p&&Lo.has(t)?{type:!1}:o,e,f));let m=r.animation;m&&u.push(m)}if(o){let t=()=>A.update(()=>{o&&Ko(e,o)});u.length?Promise.all(u).then(t):t()}return u}function ts(e,t,n={}){let r=Io(e,t,n.type===`exit`?e.presenceContext?.custom:void 0),{transition:i=e.getDefaultTransition()||{}}=r||{};n.transitionOverride&&(i=n.transitionOverride);let a=r?()=>Promise.all(es(e,r,n)):()=>Promise.resolve(),o=e.variantChildren&&e.variantChildren.size?(r=0)=>{let{delayChildren:a=0,staggerChildren:o,staggerDirection:s}=i;return ns(e,t,r,a,o,s,n)}:()=>Promise.resolve(),{when:s}=i;if(s){let[e,t]=s===`beforeChildren`?[a,o]:[o,a];return e().then(()=>t())}else return Promise.all([a(),o(n.delay)])}function ns(e,t,n=0,r=0,i=0,a=1,o){let s=[];for(let c of e.variantChildren)c.notify(`AnimationStart`,t),s.push(ts(c,t,{...o,delay:n+(typeof r==`function`?0:r)+yo(e.variantChildren,c,r,i,a)}).then(()=>c.notify(`AnimationComplete`,t)));return Promise.all(s)}function rs(e,t,n={}){e.notify(`AnimationStart`,t);let r;if(Array.isArray(t)){let i=t.map(t=>ts(e,t,n));r=Promise.all(i)}else if(typeof t==`string`)r=ts(e,t,n);else{let i=typeof t==`function`?Io(e,t,n.custom):t;r=Promise.all(es(e,i,n))}return r.then(()=>{e.notify(`AnimationComplete`,t)})}var is={test:e=>e===`auto`,parse:e=>e},as=e=>t=>t.test(e),os=[Pr,j,Xr,Yr,Qr,Zr,is],ss=e=>os.find(as(e));function cs(e){return typeof e==`number`?e===0:e===null?!0:e===`none`||e===`0`||In(e)}var ls=new Set([`brightness`,`contrast`,`saturate`,`opacity`]);function us(e){let[t,n]=e.slice(0,-1).split(`(`);if(t===`drop-shadow`)return e;let[r]=n.match(Rr)||[];if(!r)return e;let i=n.replace(r,``),a=ls.has(t)?1:0;return r!==n&&(a*=100),t+`(`+a+i+`)`}var ds=/\b([a-z-]*)\(.*?\)/gu,fs={..._i,getAnimatableNone:e=>{let t=e.match(ds);return t?t.map(us).join(` `):e}},ps={..._i,getAnimatableNone:e=>{let t=_i.parse(e);return _i.createTransformer(e)(t.map(e=>typeof e==`number`?0:typeof e==`object`?{...e,alpha:1}:e))}},ms={...Pr,transform:Math.round},hs={borderWidth:j,borderTopWidth:j,borderRightWidth:j,borderBottomWidth:j,borderLeftWidth:j,borderRadius:j,borderTopLeftRadius:j,borderTopRightRadius:j,borderBottomRightRadius:j,borderBottomLeftRadius:j,width:j,maxWidth:j,height:j,maxHeight:j,top:j,right:j,bottom:j,left:j,inset:j,insetBlock:j,insetBlockStart:j,insetBlockEnd:j,insetInline:j,insetInlineStart:j,insetInlineEnd:j,padding:j,paddingTop:j,paddingRight:j,paddingBottom:j,paddingLeft:j,paddingBlock:j,paddingBlockStart:j,paddingBlockEnd:j,paddingInline:j,paddingInlineStart:j,paddingInlineEnd:j,margin:j,marginTop:j,marginRight:j,marginBottom:j,marginLeft:j,marginBlock:j,marginBlockStart:j,marginBlockEnd:j,marginInline:j,marginInlineStart:j,marginInlineEnd:j,fontSize:j,backgroundPositionX:j,backgroundPositionY:j,rotate:Yr,rotateX:Yr,rotateY:Yr,rotateZ:Yr,scale:Ir,scaleX:Ir,scaleY:Ir,scaleZ:Ir,skew:Yr,skewX:Yr,skewY:Yr,distance:j,translateX:j,translateY:j,translateZ:j,x:j,y:j,z:j,perspective:j,transformPerspective:j,opacity:Fr,originX:$r,originY:$r,originZ:j,zIndex:ms,fillOpacity:Fr,strokeOpacity:Fr,numOctaves:ms},gs={...hs,color:ti,backgroundColor:ti,outlineColor:ti,fill:ti,stroke:ti,borderColor:ti,borderTopColor:ti,borderRightColor:ti,borderBottomColor:ti,borderLeftColor:ti,filter:fs,WebkitFilter:fs,mask:ps,WebkitMask:ps},_s=e=>gs[e],vs=new Set([fs,ps]);function ys(e,t){let n=_s(e);return vs.has(n)||(n=_i),n.getAnimatableNone?n.getAnimatableNone(t):void 0}var bs=new Set([`auto`,`none`,`0`]);function xs(e,t,n){let r=0,i;for(;r<e.length&&!i;){let t=e[r];typeof t==`string`&&!bs.has(t)&&ui(t).values.length&&(i=e[r]),r++}if(i&&n)for(let r of t)e[r]=ys(n,i)}var Ss=class extends Va{constructor(e,t,n,r,i){super(e,t,n,r,i,!0)}readKeyframes(){let{unresolvedKeyframes:e,element:t,name:n}=this;if(!t||!t.current)return;super.readKeyframes();for(let n=0;n<e.length;n++){let r=e[n];if(typeof r==`string`&&(r=r.trim(),jr(r))){let i=Co(r,t.current);i!==void 0&&(e[n]=i),n===e.length-1&&(this.finalKeyframe=r)}}if(this.resolveNoneKeyframes(),!Lo.has(n)||e.length!==2)return;let[r,i]=e,a=ss(r),o=ss(i);if(Nr(r)!==Nr(i)&&Na[n]){this.needsMeasurement=!0;return}if(a!==o)if(ka(a)&&ka(o))for(let t=0;t<e.length;t++){let n=e[t];typeof n==`string`&&(e[t]=parseFloat(n))}else Na[n]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){let{unresolvedKeyframes:e,name:t}=this,n=[];for(let t=0;t<e.length;t++)(e[t]===null||cs(e[t]))&&n.push(t);n.length&&xs(e,n,t)}measureInitialState(){let{element:e,unresolvedKeyframes:t,name:n}=this;if(!e||!e.current)return;n===`height`&&(this.suspendedScrollY=window.pageYOffset),this.measuredOrigin=Na[n](e.measureViewportBox(),window.getComputedStyle(e.current)),t[0]=this.measuredOrigin;let r=t[t.length-1];r!==void 0&&e.getValue(n,r).jump(r,!1)}measureEndState(){let{element:e,name:t,unresolvedKeyframes:n}=this;if(!e||!e.current)return;let r=e.getValue(t);r&&r.jump(this.measuredOrigin,!1);let i=n.length-1,a=n[i];n[i]=Na[t](e.measureViewportBox(),window.getComputedStyle(e.current)),a!==null&&this.finalKeyframe===void 0&&(this.finalKeyframe=a),this.removedTransforms?.length&&this.removedTransforms.forEach(([t,n])=>{e.getValue(t).set(n)}),this.resolveNoneKeyframes()}};function Cs(e,t,n){if(e==null)return[];if(e instanceof EventTarget)return[e];if(typeof e==`string`){let r=document;t&&(r=t.current);let i=n?.[e]??r.querySelectorAll(e);return i?Array.from(i):[]}return Array.from(e).filter(e=>e!=null)}var ws=(e,t)=>t&&typeof e==`number`?t.transform(e):e;function Ts(e){return Fn(e)&&`offsetHeight`in e&&!(`ownerSVGElement`in e)}var{schedule:Es,cancel:Ds}=br(queueMicrotask,!1),Os={x:!1,y:!1};function ks(){return Os.x||Os.y}function As(e){return e===`x`||e===`y`?Os[e]?null:(Os[e]=!0,()=>{Os[e]=!1}):Os.x||Os.y?null:(Os.x=Os.y=!0,()=>{Os.x=Os.y=!1})}function js(e,t){let n=Cs(e),r=new AbortController;return[n,{passive:!0,...t,signal:r.signal},()=>r.abort()]}function Ms(e){return!(e.pointerType===`touch`||ks())}function Ns(e,t,n={}){let[r,i,a]=js(e,n);return r.forEach(e=>{let n=!1,r=!1,a,o=()=>{e.removeEventListener(`pointerleave`,u)},s=e=>{a&&=(a(e),void 0),o()},c=e=>{n=!1,window.removeEventListener(`pointerup`,c),window.removeEventListener(`pointercancel`,c),r&&(r=!1,s(e))},l=()=>{n=!0,window.addEventListener(`pointerup`,c,i),window.addEventListener(`pointercancel`,c,i)},u=e=>{if(e.pointerType!==`touch`){if(n){r=!0;return}s(e)}};e.addEventListener(`pointerenter`,n=>{if(!Ms(n))return;r=!1;let o=t(e,n);typeof o==`function`&&(a=o,e.addEventListener(`pointerleave`,u,i))},i),e.addEventListener(`pointerdown`,l,i)}),a}var Ps=(e,t)=>t?e===t?!0:Ps(e,t.parentElement):!1,Fs=e=>e.pointerType===`mouse`?typeof e.button!=`number`||e.button<=0:e.isPrimary!==!1,Is=new Set([`BUTTON`,`INPUT`,`SELECT`,`TEXTAREA`,`A`]);function Ls(e){return Is.has(e.tagName)||e.isContentEditable===!0}var Rs=new Set([`INPUT`,`SELECT`,`TEXTAREA`]);function zs(e){return Rs.has(e.tagName)||e.isContentEditable===!0}var Bs=new WeakSet;function Vs(e){return t=>{t.key===`Enter`&&e(t)}}function Hs(e,t){e.dispatchEvent(new PointerEvent(`pointer`+t,{isPrimary:!0,bubbles:!0}))}var Us=(e,t)=>{let n=e.currentTarget;if(!n)return;let r=Vs(()=>{if(Bs.has(n))return;Hs(n,`down`);let e=Vs(()=>{Hs(n,`up`)});n.addEventListener(`keyup`,e,t),n.addEventListener(`blur`,()=>Hs(n,`cancel`),t)});n.addEventListener(`keydown`,r,t),n.addEventListener(`blur`,()=>n.removeEventListener(`keydown`,r),t)};function Ws(e){return Fs(e)&&!ks()}var Gs=new WeakSet;function Ks(e,t,n={}){let[r,i,a]=js(e,n),o=e=>{let r=e.currentTarget;if(!Ws(e)||Gs.has(e))return;Bs.add(r),n.stopPropagation&&Gs.add(e);let a=t(r,e),o=(e,t)=>{window.removeEventListener(`pointerup`,s),window.removeEventListener(`pointercancel`,c),Bs.has(r)&&Bs.delete(r),Ws(e)&&typeof a==`function`&&a(e,{success:t})},s=e=>{o(e,r===window||r===document||n.useGlobalTarget||Ps(r,e.target))},c=e=>{o(e,!1)};window.addEventListener(`pointerup`,s,i),window.addEventListener(`pointercancel`,c,i)};return r.forEach(e=>{(n.useGlobalTarget?window:e).addEventListener(`pointerdown`,o,i),Ts(e)&&(e.addEventListener(`focus`,e=>Us(e,i)),!Ls(e)&&!e.hasAttribute(`tabindex`)&&(e.tabIndex=0))}),a}function qs(e){return Fn(e)&&`ownerSVGElement`in e}var Js=new WeakMap,Ys,Xs=(e,t,n)=>(r,i)=>i&&i[0]?i[0][e+`Size`]:qs(r)&&`getBBox`in r?r.getBBox()[t]:r[n],Zs=Xs(`inline`,`width`,`offsetWidth`),Qs=Xs(`block`,`height`,`offsetHeight`);function $s({target:e,borderBoxSize:t}){Js.get(e)?.forEach(n=>{n(e,{get width(){return Zs(e,t)},get height(){return Qs(e,t)}})})}function ec(e){e.forEach($s)}function tc(){typeof ResizeObserver>`u`||(Ys=new ResizeObserver(ec))}function nc(e,t){Ys||tc();let n=Cs(e);return n.forEach(e=>{let n=Js.get(e);n||(n=new Set,Js.set(e,n)),n.add(t),Ys?.observe(e)}),()=>{n.forEach(e=>{let n=Js.get(e);n?.delete(t),n?.size||Ys?.unobserve(e)})}}var rc=new Set,ic;function ac(){ic=()=>{let e={get width(){return window.innerWidth},get height(){return window.innerHeight}};rc.forEach(t=>t(e))},window.addEventListener(`resize`,ic)}function oc(e){return rc.add(e),ic||ac(),()=>{rc.delete(e),!rc.size&&typeof ic==`function`&&(window.removeEventListener(`resize`,ic),ic=void 0)}}function sc(e,t){return typeof e==`function`?oc(e):nc(e,t)}function cc(e){return qs(e)&&e.tagName===`svg`}var lc=[...os,ti,_i],uc=e=>lc.find(as(e)),dc=()=>({translate:0,scale:1,origin:0,originPoint:0}),fc=()=>({x:dc(),y:dc()}),pc=()=>({min:0,max:0}),mc=()=>({x:pc(),y:pc()}),hc=new WeakMap;function gc(e){return typeof e==`object`&&!!e&&typeof e.start==`function`}function _c(e){return typeof e==`string`||Array.isArray(e)}var vc=[`animate`,`whileInView`,`whileFocus`,`whileHover`,`whileTap`,`whileDrag`,`exit`],yc=[`initial`,...vc];function bc(e){return gc(e.animate)||yc.some(t=>_c(e[t]))}function xc(e){return!!(bc(e)||e.variants)}function Sc(e,t,n){for(let r in t){let i=t[r],a=n[r];if(qo(i))e.addValue(r,i);else if(qo(a))e.addValue(r,Ho(i,{owner:e}));else if(a!==i)if(e.hasValue(r)){let t=e.getValue(r);t.liveStyle===!0?t.jump(i):t.hasAnimated||t.set(i)}else{let t=e.getStaticValue(r);e.addValue(r,Ho(t===void 0?i:t,{owner:e}))}}for(let r in n)t[r]===void 0&&e.removeValue(r);return t}var Cc={current:null},wc={current:!1},Tc=typeof window<`u`;function Ec(){if(wc.current=!0,Tc)if(window.matchMedia){let e=window.matchMedia(`(prefers-reduced-motion)`),t=()=>Cc.current=e.matches;e.addEventListener(`change`,t),t()}else Cc.current=!1}var Dc=[`AnimationStart`,`AnimationComplete`,`Update`,`BeforeLayoutMeasure`,`LayoutMeasure`,`LayoutAnimationStart`,`LayoutAnimationComplete`],Oc={};function kc(e){Oc=e}function Ac(){return Oc}var jc=class{scrapeMotionValuesFromProps(e,t,n){return{}}constructor({parent:e,props:t,presenceContext:n,reducedMotionConfig:r,skipAnimations:i,blockInitialAnimation:a,visualState:o},s={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.shouldSkipAnimations=!1,this.values=new Map,this.KeyframeResolver=Va,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.hasBeenMounted=!1,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=Er.now();this.renderScheduledAt<e&&(this.renderScheduledAt=e,A.render(this.render,!1,!0))};let{latestValues:c,renderState:l}=o;this.latestValues=c,this.baseTarget={...c},this.initialValues=t.initial?{...c}:{},this.renderState=l,this.parent=e,this.props=t,this.presenceContext=n,this.depth=e?e.depth+1:0,this.reducedMotionConfig=r,this.skipAnimationsConfig=i,this.options=s,this.blockInitialAnimation=!!a,this.isControllingVariants=bc(t),this.isVariantNode=xc(t),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(e&&e.current);let{willChange:u,...d}=this.scrapeMotionValuesFromProps(t,{},this);for(let e in d){let t=d[e];c[e]!==void 0&&qo(t)&&t.set(c[e])}}mount(e){if(this.hasBeenMounted)for(let e in this.initialValues)this.values.get(e)?.jump(this.initialValues[e]),this.latestValues[e]=this.initialValues[e];this.current=e,hc.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)),this.reducedMotionConfig===`never`?this.shouldReduceMotion=!1:this.reducedMotionConfig===`always`?this.shouldReduceMotion=!0:(wc.current||Ec(),this.shouldReduceMotion=Cc.current),process.env.NODE_ENV!==`production`&&qn(this.shouldReduceMotion!==!0,`You have Reduced Motion enabled on your device. Animations may not appear as expected.`,`reduced-motion-disabled`),this.shouldSkipAnimations=this.skipAnimationsConfig??!1,this.parent?.addChild(this),this.update(this.props,this.presenceContext),this.hasBeenMounted=!0}unmount(){this.projection&&this.projection.unmount(),xr(this.notifyUpdate),xr(this.render),this.valueSubscriptions.forEach(e=>e()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),this.parent?.removeChild(this);for(let e in 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}addChild(e){this.children.add(e),this.enteringChildren??=new Set,this.enteringChildren.add(e)}removeChild(e){this.children.delete(e),this.enteringChildren&&this.enteringChildren.delete(e)}bindToMotionValue(e,t){if(this.valueSubscriptions.has(e)&&this.valueSubscriptions.get(e)(),t.accelerate&&uo.has(e)&&this.current instanceof HTMLElement){let{factory:n,keyframes:r,times:i,ease:a,duration:o}=t.accelerate,s=new eo({element:this.current,name:e,keyframes:r,times:i,ease:a,duration:Un(o)}),c=n(s);this.valueSubscriptions.set(e,()=>{c(),s.cancel()});return}let n=Oa.has(e);n&&this.onBindTransform&&this.onBindTransform();let r=t.on(`change`,t=>{this.latestValues[e]=t,this.props.onUpdate&&A.preRender(this.notifyUpdate),n&&this.projection&&(this.projection.isTransformDirty=!0),this.scheduleRender()}),i;typeof window<`u`&&window.MotionCheckAppearSync&&(i=window.MotionCheckAppearSync(this,e,t)),this.valueSubscriptions.set(e,()=>{r(),i&&i(),t.owner&&t.stop()})}sortNodePosition(e){return!this.current||!this.sortInstanceNodePosition||this.type!==e.type?0:this.sortInstanceNodePosition(this.current,e.current)}updateFeatures(){let e=`animation`;for(e in Oc){let t=Oc[e];if(!t)continue;let{isEnabled:n,Feature:r}=t;if(!this.features[e]&&r&&n(this.props)&&(this.features[e]=new r(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):mc()}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<Dc.length;t++){let n=Dc[t];this.propEventSubscriptions[n]&&(this.propEventSubscriptions[n](),delete this.propEventSubscriptions[n]);let r=e[`on`+n];r&&(this.propEventSubscriptions[n]=this.on(n,r))}this.prevMotionValues=Sc(this,this.scrapeMotionValuesFromProps(e,this.prevProps||{},this),this.prevMotionValues),this.handleChildMotionValue&&this.handleChildMotionValue()}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 n=this.values.get(e);t!==n&&(n&&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 n=this.values.get(e);return n===void 0&&t!==void 0&&(n=Ho(t===null?void 0:t,{owner:this}),this.addValue(e,n)),n}readValue(e,t){let n=this.latestValues[e]!==void 0||!this.current?this.latestValues[e]:this.getBaseTargetFromProps(this.props,e)??this.readValueFromInstance(this.current,e,this.options);return n!=null&&(typeof n==`string`&&(Pn(n)||In(n))?n=parseFloat(n):!uc(n)&&_i.test(t)&&(n=ys(e,t)),this.setBaseTarget(e,qo(n)?n.get():n)),qo(n)?n.get():n}setBaseTarget(e,t){this.baseTarget[e]=t}getBaseTarget(e){let{initial:t}=this.props,n;if(typeof t==`string`||typeof t==`object`){let r=Fo(this.props,t,this.presenceContext?.custom);r&&(n=r[e])}if(t&&n!==void 0)return n;let r=this.getBaseTargetFromProps(this.props,e);return r!==void 0&&!qo(r)?r:this.initialValues[e]!==void 0&&n===void 0?void 0:this.baseTarget[e]}on(e,t){return this.events[e]||(this.events[e]=new Hn),this.events[e].add(t)}notify(e,...t){this.events[e]&&this.events[e].notify(...t)}scheduleRenderMicrotask(){Es.render(this.render)}},Mc=class extends jc{constructor(){super(...arguments),this.KeyframeResolver=Ss}sortInstanceNodePosition(e,t){return e.compareDocumentPosition(t)&2?1:-1}getBaseTargetFromProps(e,t){let n=e.style;return n?n[t]:void 0}removeValueFromRenderState(e,{vars:t,style:n}){delete t[e],delete n[e]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);let{children:e}=this.props;qo(e)&&(this.childSubscription=e.on(`change`,e=>{this.current&&(this.current.textContent=`${e}`)}))}},Nc=class{constructor(e){this.isMounted=!1,this.node=e}update(){}};function Pc({top:e,left:t,right:n,bottom:r}){return{x:{min:t,max:n},y:{min:e,max:r}}}function Fc({x:e,y:t}){return{top:t.min,right:e.max,bottom:t.max,left:e.min}}function Ic(e,t){if(!t)return e;let n=t({x:e.left,y:e.top}),r=t({x:e.right,y:e.bottom});return{top:n.y,left:n.x,bottom:r.y,right:r.x}}function Lc(e){return e===void 0||e===1}function Rc({scale:e,scaleX:t,scaleY:n}){return!Lc(e)||!Lc(t)||!Lc(n)}function zc(e){return Rc(e)||Bc(e)||e.z||e.rotate||e.rotateX||e.rotateY||e.skewX||e.skewY}function Bc(e){return Vc(e.x)||Vc(e.y)}function Vc(e){return e&&e!==`0%`}function Hc(e,t,n){return n+t*(e-n)}function Uc(e,t,n,r,i){return i!==void 0&&(e=Hc(e,i,r)),Hc(e,n,r)+t}function Wc(e,t=0,n=1,r,i){e.min=Uc(e.min,t,n,r,i),e.max=Uc(e.max,t,n,r,i)}function Gc(e,{x:t,y:n}){Wc(e.x,t.translate,t.scale,t.originPoint),Wc(e.y,n.translate,n.scale,n.originPoint)}var Kc=.999999999999,qc=1.0000000000001;function Jc(e,t,n,r=!1){let i=n.length;if(!i)return;t.x=t.y=1;let a,o;for(let s=0;s<i;s++){a=n[s],o=a.projectionDelta;let{visualElement:i}=a.options;i&&i.props.style&&i.props.style.display===`contents`||(r&&a.options.layoutScroll&&a.scroll&&a!==a.root&&(Yc(e.x,-a.scroll.offset.x),Yc(e.y,-a.scroll.offset.y)),o&&(t.x*=o.x.scale,t.y*=o.y.scale,Gc(e,o)),r&&zc(a.latestValues)&&Qc(e,a.latestValues,a.layout?.layoutBox))}t.x<qc&&t.x>Kc&&(t.x=1),t.y<qc&&t.y>Kc&&(t.y=1)}function Yc(e,t){e.min+=t,e.max+=t}function Xc(e,t,n,r,i=.5){Wc(e,t,n,M(e.min,e.max,i),r)}function Zc(e,t){return typeof e==`string`?parseFloat(e)/100*(t.max-t.min):e}function Qc(e,t,n){let r=n??e;Xc(e.x,Zc(t.x,r.x),t.scaleX,t.scale,t.originX),Xc(e.y,Zc(t.y,r.y),t.scaleY,t.scale,t.originY)}function $c(e,t){return Pc(Ic(e.getBoundingClientRect(),t))}function el(e,t,n){let r=$c(e,n),{scroll:i}=t;return i&&(Yc(r.x,i.offset.x),Yc(r.y,i.offset.y)),r}var tl={x:`translateX`,y:`translateY`,z:`translateZ`,transformPerspective:`perspective`},nl=Da.length;function rl(e,t,n){let r=``,i=!0;for(let a=0;a<nl;a++){let o=Da[a],s=e[o];if(s===void 0)continue;let c=!0;if(typeof s==`number`)c=s===(o.startsWith(`scale`)?1:0);else{let e=parseFloat(s);c=o.startsWith(`scale`)?e===1:e===0}if(!c||n){let e=ws(s,hs[o]);if(!c){i=!1;let t=tl[o]||o;r+=`${t}(${e}) `}n&&(t[o]=e)}}return r=r.trim(),n?r=n(t,i?``:r):i&&(r=`none`),r}function il(e,t,n){let{style:r,vars:i,transformOrigin:a}=e,o=!1,s=!1;for(let e in t){let n=t[e];if(Oa.has(e)){o=!0;continue}else if(kr(e)){i[e]=n;continue}else{let t=ws(n,hs[e]);e.startsWith(`origin`)?(s=!0,a[e]=t):r[e]=t}}if(t.transform||(o||n?r.transform=rl(t,e.transform,n):r.transform&&=`none`),s){let{originX:e=`50%`,originY:t=`50%`,originZ:n=0}=a;r.transformOrigin=`${e} ${t} ${n}`}}function al(e,{style:t,vars:n},r,i){let a=e.style,o;for(o in t)a[o]=t[o];for(o in i?.applyProjectionStyles(a,r),n)a.setProperty(o,n[o])}function ol(e,t){return t.max===t.min?0:e/(t.max-t.min)*100}var sl={correct:(e,t)=>{if(!t.target)return e;if(typeof e==`string`)if(j.test(e))e=parseFloat(e);else return e;return`${ol(e,t.target.x)}% ${ol(e,t.target.y)}%`}},cl={correct:(e,{treeScale:t,projectionDelta:n})=>{let r=e,i=_i.parse(e);if(i.length>5)return r;let a=_i.createTransformer(e),o=typeof i[0]==`number`?0:1,s=n.x.scale*t.x,c=n.y.scale*t.y;i[0+o]/=s,i[1+o]/=c;let l=M(s,c,.5);return typeof i[2+o]==`number`&&(i[2+o]/=l),typeof i[3+o]==`number`&&(i[3+o]/=l),a(i)}},ll={borderRadius:{...sl,applyTo:[`borderTopLeftRadius`,`borderTopRightRadius`,`borderBottomLeftRadius`,`borderBottomRightRadius`]},borderTopLeftRadius:sl,borderTopRightRadius:sl,borderBottomLeftRadius:sl,borderBottomRightRadius:sl,boxShadow:cl};function ul(e,{layout:t,layoutId:n}){return Oa.has(e)||e.startsWith(`origin`)||(t||n!==void 0)&&(!!ll[e]||e===`opacity`)}function dl(e,t,n){let r=e.style,i=t?.style,a={};if(!r)return a;for(let t in r)(qo(r[t])||i&&qo(i[t])||ul(t,e)||n?.getValue(t)?.liveStyle!==void 0)&&(a[t]=r[t]);return a}function fl(e){return window.getComputedStyle(e)}var pl=class extends Mc{constructor(){super(...arguments),this.type=`html`,this.renderInstance=al}readValueFromInstance(e,t){if(Oa.has(t))return this.projection?.isProjecting?Ca(t):Ta(e,t);{let n=fl(e),r=(kr(t)?n.getPropertyValue(t):n[t])||0;return typeof r==`string`?r.trim():r}}measureInstanceViewportBox(e,{transformPagePoint:t}){return $c(e,t)}build(e,t,n){il(e,t,n.transformTemplate)}scrapeMotionValuesFromProps(e,t,n){return dl(e,t,n)}},ml={offset:`stroke-dashoffset`,array:`stroke-dasharray`},hl={offset:`strokeDashoffset`,array:`strokeDasharray`};function gl(e,t,n=1,r=0,i=!0){e.pathLength=1;let a=i?ml:hl;e[a.offset]=`${-r}`,e[a.array]=`${t} ${n}`}var _l=[`offsetDistance`,`offsetPath`,`offsetRotate`,`offsetAnchor`];function vl(e,{attrX:t,attrY:n,attrScale:r,pathLength:i,pathSpacing:a=1,pathOffset:o=0,...s},c,l,u){if(il(e,s,l),c){e.style.viewBox&&(e.attrs.viewBox=e.style.viewBox);return}e.attrs=e.style,e.style={};let{attrs:d,style:f}=e;d.transform&&(f.transform=d.transform,delete d.transform),(f.transform||d.transformOrigin)&&(f.transformOrigin=d.transformOrigin??`50% 50%`,delete d.transformOrigin),f.transform&&(f.transformBox=u?.transformBox??`fill-box`,delete d.transformBox);for(let e of _l)d[e]!==void 0&&(f[e]=d[e],delete d[e]);t!==void 0&&(d.x=t),n!==void 0&&(d.y=n),r!==void 0&&(d.scale=r),i!==void 0&&gl(d,i,a,o,!1)}var yl=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`]),bl=e=>typeof e==`string`&&e.toLowerCase()===`svg`;function xl(e,t,n,r){al(e,t,void 0,r);for(let n in t.attrs)e.setAttribute(yl.has(n)?n:Xo(n),t.attrs[n])}function Sl(e,t,n){let r=dl(e,t,n);for(let n in e)if(qo(e[n])||qo(t[n])){let t=Da.indexOf(n)===-1?n:`attr`+n.charAt(0).toUpperCase()+n.substring(1);r[t]=e[n]}return r}var Cl=class extends Mc{constructor(){super(...arguments),this.type=`svg`,this.isSVGTag=!1,this.measureInstanceViewportBox=mc}getBaseTargetFromProps(e,t){return e[t]}readValueFromInstance(e,t){if(Oa.has(t)){let e=_s(t);return e&&e.default||0}return t=yl.has(t)?t:Xo(t),e.getAttribute(t)}scrapeMotionValuesFromProps(e,t,n){return Sl(e,t,n)}build(e,t,n){vl(e,t,this.isSVGTag,n.transformTemplate,n.style)}renderInstance(e,t,n,r){xl(e,t,n,r)}mount(e){this.isSVGTag=bl(e.tagName),super.mount(e)}},wl=yc.length;function Tl(e){if(!e)return;if(!e.isControllingVariants){let t=e.parent&&Tl(e.parent)||{};return e.props.initial!==void 0&&(t.initial=e.props.initial),t}let t={};for(let n=0;n<wl;n++){let r=yc[n],i=e.props[r];(_c(i)||i===!1)&&(t[r]=i)}return t}function El(e,t){if(!Array.isArray(t))return!1;let n=t.length;if(n!==e.length)return!1;for(let r=0;r<n;r++)if(t[r]!==e[r])return!1;return!0}var Dl=[...vc].reverse(),Ol=vc.length;function kl(e){return t=>Promise.all(t.map(({animation:t,options:n})=>rs(e,t,n)))}function Al(e){let t=kl(e),n=Nl(),r=!0,i=!1,a=t=>(n,r)=>{let i=Io(e,r,t===`exit`?e.presenceContext?.custom:void 0);if(i){let{transition:e,transitionEnd:t,...r}=i;n={...n,...r,...t}}return n};function o(n){t=n(e)}function s(o){let{props:s}=e,c=Tl(e.parent)||{},l=[],u=new Set,d={},f=1/0;for(let t=0;t<Ol;t++){let p=Dl[t],m=n[p],h=s[p]===void 0?c[p]:s[p],g=_c(h),_=p===o?m.isActive:null;_===!1&&(f=t);let v=h===c[p]&&h!==s[p]&&g;if(v&&(r||i)&&e.manuallyAnimateOnMount&&(v=!1),m.protectedKeys={...d},!m.isActive&&_===null||!h&&!m.prevProp||gc(h)||typeof h==`boolean`)continue;if(p===`exit`&&m.isActive&&_!==!0){m.prevResolvedValues&&(d={...d,...m.prevResolvedValues});continue}let y=jl(m.prevProp,h),b=y||p===o&&m.isActive&&!v&&g||t>f&&g,x=!1,S=Array.isArray(h)?h:[h],ee=S.reduce(a(p),{});_===!1&&(ee={});let{prevResolvedValues:te={}}=m,C={...te,...ee},ne=t=>{b=!0,u.has(t)&&(x=!0,u.delete(t)),m.needsAnimating[t]=!0;let n=e.getValue(t);n&&(n.liveStyle=!1)};for(let e in C){let t=ee[e],n=te[e];if(d.hasOwnProperty(e))continue;let r=!1;r=Uo(t)&&Uo(n)?!El(t,n):t!==n,r?t==null?u.add(e):ne(e):t!==void 0&&u.has(e)?ne(e):m.protectedKeys[e]=!0}m.prevProp=h,m.prevResolvedValues=ee,m.isActive&&(d={...d,...ee}),(r||i)&&e.blockInitialAnimation&&(b=!1);let re=v&&y;b&&(!re||x)&&l.push(...S.map(t=>{let n={type:p};if(typeof t==`string`&&(r||i)&&!re&&e.manuallyAnimateOnMount&&e.parent){let{parent:r}=e,i=Io(r,t);if(r.enteringChildren&&i){let{delayChildren:t}=i.transition||{};n.delay=yo(r.enteringChildren,e,t)}}return{animation:t,options:n}}))}if(u.size){let t={};if(typeof s.initial!=`boolean`){let n=Io(e,Array.isArray(s.initial)?s.initial[0]:s.initial);n&&n.transition&&(t.transition=n.transition)}u.forEach(n=>{let r=e.getBaseTarget(n),i=e.getValue(n);i&&(i.liveStyle=!0),t[n]=r??null}),l.push({animation:t})}let p=!!l.length;return r&&(s.initial===!1||s.initial===s.animate)&&!e.manuallyAnimateOnMount&&(p=!1),r=!1,i=!1,p?t(l):Promise.resolve()}function c(t,r){if(n[t].isActive===r)return Promise.resolve();e.variantChildren?.forEach(e=>e.animationState?.setActive(t,r)),n[t].isActive=r;let i=s(t);for(let e in n)n[e].protectedKeys={};return i}return{animateChanges:s,setActive:c,setAnimateFunction:o,getState:()=>n,reset:()=>{n=Nl(),i=!0}}}function jl(e,t){return typeof t==`string`?t!==e:Array.isArray(t)?!El(t,e):!1}function Ml(e=!1){return{isActive:e,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Nl(){return{animate:Ml(!0),whileInView:Ml(),whileHover:Ml(),whileTap:Ml(),whileDrag:Ml(),whileFocus:Ml(),exit:Ml()}}function Pl(e,t){e.min=t.min,e.max=t.max}function Fl(e,t){Pl(e.x,t.x),Pl(e.y,t.y)}function Il(e,t){e.translate=t.translate,e.scale=t.scale,e.originPoint=t.originPoint,e.origin=t.origin}var Ll=1e-4,Rl=1-Ll,zl=1+Ll,Bl=.01,Vl=0-Bl,Hl=0+Bl;function Ul(e){return e.max-e.min}function Wl(e,t,n){return Math.abs(e-t)<=n}function Gl(e,t,n,r=.5){e.origin=r,e.originPoint=M(t.min,t.max,e.origin),e.scale=Ul(n)/Ul(t),e.translate=M(n.min,n.max,e.origin)-e.originPoint,(e.scale>=Rl&&e.scale<=zl||isNaN(e.scale))&&(e.scale=1),(e.translate>=Vl&&e.translate<=Hl||isNaN(e.translate))&&(e.translate=0)}function Kl(e,t,n,r){Gl(e.x,t.x,n.x,r?r.originX:void 0),Gl(e.y,t.y,n.y,r?r.originY:void 0)}function ql(e,t,n,r=0){e.min=(r?M(n.min,n.max,r):n.min)+t.min,e.max=e.min+Ul(t)}function Jl(e,t,n,r){ql(e.x,t.x,n.x,r?.x),ql(e.y,t.y,n.y,r?.y)}function Yl(e,t,n,r=0){let i=r?M(n.min,n.max,r):n.min;e.min=t.min-i,e.max=e.min+Ul(t)}function Xl(e,t,n,r){Yl(e.x,t.x,n.x,r?.x),Yl(e.y,t.y,n.y,r?.y)}function Zl(e,t,n,r,i){return e-=t,e=Hc(e,1/n,r),i!==void 0&&(e=Hc(e,1/i,r)),e}function Ql(e,t=0,n=1,r=.5,i,a=e,o=e){if(Xr.test(t)&&(t=parseFloat(t),t=M(o.min,o.max,t/100)-o.min),typeof t!=`number`)return;let s=M(a.min,a.max,r);e===a&&(s-=t),e.min=Zl(e.min,t,n,s,i),e.max=Zl(e.max,t,n,s,i)}function $l(e,t,[n,r,i],a,o){Ql(e,t[n],t[r],t[i],t.scale,a,o)}var eu=[`x`,`scaleX`,`originX`],tu=[`y`,`scaleY`,`originY`];function nu(e,t,n,r){$l(e.x,t,eu,n?n.x:void 0,r?r.x:void 0),$l(e.y,t,tu,n?n.y:void 0,r?r.y:void 0)}function ru(e){return e.translate===0&&e.scale===1}function iu(e){return ru(e.x)&&ru(e.y)}function au(e,t){return e.min===t.min&&e.max===t.max}function ou(e,t){return au(e.x,t.x)&&au(e.y,t.y)}function su(e,t){return Math.round(e.min)===Math.round(t.min)&&Math.round(e.max)===Math.round(t.max)}function cu(e,t){return su(e.x,t.x)&&su(e.y,t.y)}function lu(e){return Ul(e.x)/Ul(e.y)}function uu(e,t){return e.translate===t.translate&&e.scale===t.scale&&e.originPoint===t.originPoint}function du(e){return[e(`x`),e(`y`)]}function fu(e,t,n){let r=``,i=e.x.translate/t.x,a=e.y.translate/t.y,o=n?.z||0;if((i||a||o)&&(r=`translate3d(${i}px, ${a}px, ${o}px) `),(t.x!==1||t.y!==1)&&(r+=`scale(${1/t.x}, ${1/t.y}) `),n){let{transformPerspective:e,rotate:t,rotateX:i,rotateY:a,skewX:o,skewY:s}=n;e&&(r=`perspective(${e}px) ${r}`),t&&(r+=`rotate(${t}deg) `),i&&(r+=`rotateX(${i}deg) `),a&&(r+=`rotateY(${a}deg) `),o&&(r+=`skewX(${o}deg) `),s&&(r+=`skewY(${s}deg) `)}let s=e.x.scale*t.x,c=e.y.scale*t.y;return(s!==1||c!==1)&&(r+=`scale(${s}, ${c})`),r||`none`}var pu=[`borderTopLeftRadius`,`borderTopRightRadius`,`borderBottomLeftRadius`,`borderBottomRightRadius`],mu=pu.length,hu=e=>typeof e==`string`?parseFloat(e):e,gu=e=>typeof e==`number`||j.test(e);function _u(e,t,n,r,i,a){i?(e.opacity=M(0,n.opacity??1,yu(r)),e.opacityExit=M(t.opacity??1,0,bu(r))):a&&(e.opacity=M(t.opacity??1,n.opacity??1,r));for(let i=0;i<mu;i++){let a=pu[i],o=vu(t,a),s=vu(n,a);o===void 0&&s===void 0||(o||=0,s||=0,o===0||s===0||gu(o)===gu(s)?(e[a]=Math.max(M(hu(o),hu(s),r),0),(Xr.test(s)||Xr.test(o))&&(e[a]+=`%`)):e[a]=s)}(t.rotate||n.rotate)&&(e.rotate=M(t.rotate||0,n.rotate||0,r))}function vu(e,t){return e[t]===void 0?e.borderRadius:e[t]}var yu=xu(0,.5,or),bu=xu(.5,.95,Rn);function xu(e,t,n){return r=>r<e?0:r>t?1:n(Vn(e,t,r))}function Su(e,t,n){let r=qo(e)?e:Ho(e);return r.start(No(``,r,t,n)),r.animation}function Cu(e,t,n,r={passive:!0}){return e.addEventListener(t,n,r),()=>e.removeEventListener(t,n)}var wu=(e,t)=>e.depth-t.depth,Tu=class{constructor(){this.children=[],this.isDirty=!1}add(e){Dn(this.children,e),this.isDirty=!0}remove(e){On(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort(wu),this.isDirty=!1,this.children.forEach(e)}};function Eu(e,t){let n=Er.now(),r=({timestamp:i})=>{let a=i-n;a>=t&&(xr(r),e(a-t))};return A.setup(r,!0),()=>xr(r)}function Du(e){return qo(e)?e.get():e}var Ou=class{constructor(){this.members=[]}add(e){Dn(this.members,e);for(let t=this.members.length-1;t>=0;t--){let n=this.members[t];if(n===e||n===this.lead||n===this.prevLead)continue;let r=n.instance;(!r||r.isConnected===!1)&&!n.snapshot&&(On(this.members,n),n.unmount())}e.scheduleRender()}remove(e){if(On(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){for(let t=this.members.indexOf(e)-1;t>=0;t--){let e=this.members[t];if(e.isPresent!==!1&&e.instance?.isConnected!==!1)return this.promote(e),!0}return!1}promote(e,t){let n=this.lead;if(e!==n&&(this.prevLead=n,this.lead=e,e.show(),n)){n.updateSnapshot(),e.scheduleRender();let{layoutDependency:r}=n.options,{layoutDependency:i}=e.options;(r===void 0||r!==i)&&(e.resumeFrom=n,t&&(n.preserveOpacity=!0),n.snapshot&&(e.snapshot=n.snapshot,e.snapshot.latestValues=n.animationValues||n.latestValues),e.root?.isUpdating&&(e.isLayoutDirty=!0)),e.options.crossfade===!1&&n.hide()}}exitAnimationComplete(){this.members.forEach(e=>{e.options.onExitComplete?.(),e.resumingFrom?.options.onExitComplete?.()})}scheduleRender(){this.members.forEach(e=>e.instance&&e.scheduleRender(!1))}removeLeadSnapshot(){this.lead?.snapshot&&(this.lead.snapshot=void 0)}},ku={hasAnimatedSinceResize:!0,hasEverUpdated:!1},Au={nodes:0,calculatedTargetDeltas:0,calculatedProjections:0},ju=[``,`X`,`Y`,`Z`],Mu=1e3,Nu=0;function Pu(e,t,n,r){let{latestValues:i}=t;i[e]&&(n[e]=i[e],t.setStaticValue(e,0),r&&(r[e]=0))}function Fu(e){if(e.hasCheckedOptimisedAppear=!0,e.root===e)return;let{visualElement:t}=e.options;if(!t)return;let n=Qo(t);if(window.MotionHasOptimisedAnimation(n,`transform`)){let{layout:t,layoutId:r}=e.options;window.MotionCancelOptimisedAnimation(n,`transform`,A,!(t||r))}let{parent:r}=e;r&&!r.hasCheckedOptimisedAppear&&Fu(r)}function Iu({attachResizeListener:e,defaultParent:t,measureScroll:n,checkIsScrollRoot:r,resetTransform:i}){return class{constructor(e={},n=t?.()){this.id=Nu++,this.animationId=0,this.animationCommitId=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.layoutVersion=0,this.updateScheduled=!1,this.scheduleUpdate=()=>this.update(),this.projectionUpdateScheduled=!1,this.checkUpdateFailed=()=>{this.isUpdating&&(this.isUpdating=!1,this.clearAllSnapshots())},this.updateProjection=()=>{this.projectionUpdateScheduled=!1,_r.value&&(Au.nodes=Au.calculatedTargetDeltas=Au.calculatedProjections=0),this.nodes.forEach(zu),this.nodes.forEach(Ju),this.nodes.forEach(Yu),this.nodes.forEach(Bu),_r.addProjectionMetrics&&_r.addProjectionMetrics(Au)},this.resolvedRelativeTargetAt=0,this.linkedParentVersion=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=e,this.root=n?n.root||n:this,this.path=n?[...n.path,n]:[],this.parent=n,this.depth=n?n.depth+1:0;for(let e=0;e<this.path.length;e++)this.path[e].shouldResetTransform=!0;this.root===this&&(this.nodes=new Tu)}addEventListener(e,t){return this.eventHandlers.has(e)||this.eventHandlers.set(e,new Hn),this.eventHandlers.get(e).add(t)}notifyListeners(e,...t){let n=this.eventHandlers.get(e);n&&n.notify(...t)}hasListeners(e){return this.eventHandlers.has(e)}mount(t){if(this.instance)return;this.isSVG=qs(t)&&!cc(t),this.instance=t;let{layoutId:n,layout:r,visualElement:i}=this.options;if(i&&!i.current&&i.mount(t),this.root.nodes.add(this),this.parent&&this.parent.children.add(this),this.root.hasTreeAnimated&&(r||n)&&(this.isLayoutDirty=!0),e){let n,r=0,i=()=>this.root.updateBlockedByResize=!1;A.read(()=>{r=window.innerWidth}),e(t,()=>{let e=window.innerWidth;e!==r&&(r=e,this.root.updateBlockedByResize=!0,n&&n(),n=Eu(i,250),ku.hasAnimatedSinceResize&&(ku.hasAnimatedSinceResize=!1,this.nodes.forEach(qu)))})}n&&this.root.registerSharedNode(n,this),this.options.animate!==!1&&i&&(n||r)&&this.addEventListener(`didUpdate`,({delta:e,hasLayoutChanged:t,hasRelativeLayoutChanged:n,layout:r})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}let a=this.options.transition||i.getDefaultTransition()||nd,{onLayoutAnimationStart:o,onLayoutAnimationComplete:s}=i.getProps(),c=!this.targetLayout||!cu(this.targetLayout,r),l=!t&&n;if(this.options.layoutRoot||this.resumeFrom||l||t&&(c||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);let t={...Ao(a,`layout`),onPlay:o,onComplete:s};(i.shouldReduceMotion||this.options.layoutRoot)&&(t.delay=0,t.type=!1),this.startAnimation(t),this.setAnimationOrigin(e,l)}else t||qu(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=r})}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,this.eventHandlers.clear(),xr(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(Xu),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&&Fu(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,(typeof t.latestValues.x==`string`||typeof t.latestValues.y==`string`)&&(t.isLayoutDirty=!0),t.updateScroll(`snapshot`),t.options.layoutRoot&&t.willUpdate(!1)}let{layoutId:t,layout:n}=this.options;if(t===void 0&&!n)return;let r=this.getTransformTemplate();this.prevTransformTemplateValue=r?r(this.latestValues,``):void 0,this.updateSnapshot(),e&&this.notifyListeners(`willUpdate`)}update(){if(this.updateScheduled=!1,this.isUpdateBlocked()){let e=this.updateBlockedByResize;this.unblockUpdate(),this.updateBlockedByResize=!1,this.clearAllSnapshots(),e&&this.nodes.forEach(Uu),this.nodes.forEach(Hu);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(Wu);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(Gu),this.nodes.forEach(Ku),this.nodes.forEach(Lu),this.nodes.forEach(Ru)):this.nodes.forEach(Wu),this.clearAllSnapshots();let e=Er.now();Sr.delta=kn(0,1e3/60,e-Sr.timestamp),Sr.timestamp=e,Sr.isProcessing=!0,Cr.update.process(Sr),Cr.preRender.process(Sr),Cr.render.process(Sr),Sr.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,Es.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(Vu),this.sharedNodes.forEach(Zu)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,A.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){A.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!Ul(this.snapshot.measuredBox.x)&&!Ul(this.snapshot.measuredBox.y)&&(this.snapshot=void 0))}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.layoutVersion++,this.layoutCorrected||=mc(),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&&this.instance){let t=r(this.instance);this.scroll={animationId:this.root.animationId,phase:e,isRoot:t,offset:n(this.instance),wasRoot:this.scroll?this.scroll.isRoot:t}}}resetTransform(){if(!i)return;let e=this.isLayoutDirty||this.shouldResetTransform||this.options.alwaysMeasureLayout,t=this.projectionDelta&&!iu(this.projectionDelta),n=this.getTransformTemplate(),r=n?n(this.latestValues,``):void 0,a=r!==this.prevTransformTemplateValue;e&&this.instance&&(t||zc(this.latestValues)||a)&&(i(this.instance,r),this.shouldResetTransform=!1,this.scheduleRender())}measure(e=!0){let t=this.measurePageBox(),n=this.removeElementScroll(t);return e&&(n=this.removeTransform(n)),od(n),{animationId:this.root.animationId,measuredBox:t,layoutBox:n,latestValues:{},source:this.id}}measurePageBox(){let{visualElement:e}=this.options;if(!e)return mc();let t=e.measureViewportBox();if(!(this.scroll?.wasRoot||this.path.some(cd))){let{scroll:e}=this.root;e&&(Yc(t.x,e.offset.x),Yc(t.y,e.offset.y))}return t}removeElementScroll(e){let t=mc();if(Fl(t,e),this.scroll?.wasRoot)return t;for(let n=0;n<this.path.length;n++){let r=this.path[n],{scroll:i,options:a}=r;r!==this.root&&i&&a.layoutScroll&&(i.wasRoot&&Fl(t,e),Yc(t.x,i.offset.x),Yc(t.y,i.offset.y))}return t}applyTransform(e,t=!1,n){let r=n||mc();Fl(r,e);for(let e=0;e<this.path.length;e++){let n=this.path[e];!t&&n.options.layoutScroll&&n.scroll&&n!==n.root&&(Yc(r.x,-n.scroll.offset.x),Yc(r.y,-n.scroll.offset.y)),zc(n.latestValues)&&Qc(r,n.latestValues,n.layout?.layoutBox)}return zc(this.latestValues)&&Qc(r,this.latestValues,this.layout?.layoutBox),r}removeTransform(e){let t=mc();Fl(t,e);for(let e=0;e<this.path.length;e++){let n=this.path[e];if(!zc(n.latestValues))continue;let r;n.instance&&(Rc(n.latestValues)&&n.updateSnapshot(),r=mc(),Fl(r,n.measurePageBox())),nu(t,n.latestValues,n.snapshot?.layoutBox,r)}return zc(this.latestValues)&&nu(t,this.latestValues),t}setTargetDelta(e){this.targetDelta=e,this.root.scheduleUpdateProjection(),this.isProjectionDirty=!0}setOptions(e){this.options={...this.options,...e,crossfade:e.crossfade===void 0?!0: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!==Sr.timestamp&&this.relativeParent.resolveTargetDelta(!0)}resolveTargetDelta(e=!1){let t=this.getLead();this.isProjectionDirty||=t.isProjectionDirty,this.isTransformDirty||=t.isTransformDirty,this.isSharedProjectionDirty||=t.isSharedProjectionDirty;let n=!!this.resumingFrom||this!==t;if(!(e||n&&this.isSharedProjectionDirty||this.isProjectionDirty||this.parent?.isProjectionDirty||this.attemptToResolveRelativeTarget||this.root.updateBlockedByResize))return;let{layout:r,layoutId:i}=this.options;if(!this.layout||!(r||i))return;this.resolvedRelativeTargetAt=Sr.timestamp;let a=this.getClosestProjectingParent();a&&this.linkedParentVersion!==a.layoutVersion&&!a.options.layoutRoot&&this.removeRelativeTarget(),!this.targetDelta&&!this.relativeTarget&&(this.options.layoutAnchor!==!1&&a&&a.layout?this.createRelativeTarget(a,this.layout.layoutBox,a.layout.layoutBox):this.removeRelativeTarget()),!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=mc(),this.targetWithTransforms=mc()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),Jl(this.target,this.relativeTarget,this.relativeParent.target,this.options.layoutAnchor||void 0)):this.targetDelta?(this.resumingFrom?this.applyTransform(this.layout.layoutBox,!1,this.target):Fl(this.target,this.layout.layoutBox),Gc(this.target,this.targetDelta)):Fl(this.target,this.layout.layoutBox),this.attemptToResolveRelativeTarget&&(this.attemptToResolveRelativeTarget=!1,this.options.layoutAnchor!==!1&&a&&!!a.resumingFrom==!!this.resumingFrom&&!a.options.layoutScroll&&a.target&&this.animationProgress!==1?this.createRelativeTarget(a,this.target,a.target):this.relativeParent=this.relativeTarget=void 0),_r.value&&Au.calculatedTargetDeltas++)}getClosestProjectingParent(){if(!(!this.parent||Rc(this.parent.latestValues)||Bc(this.parent.latestValues)))return this.parent.isProjecting()?this.parent:this.parent.getClosestProjectingParent()}isProjecting(){return!!((this.relativeTarget||this.targetDelta||this.options.layoutRoot)&&this.layout)}createRelativeTarget(e,t,n){this.relativeParent=e,this.linkedParentVersion=e.layoutVersion,this.forceRelativeParentToResolveTarget(),this.relativeTarget=mc(),this.relativeTargetOrigin=mc(),Xl(this.relativeTargetOrigin,t,n,this.options.layoutAnchor||void 0),Fl(this.relativeTarget,this.relativeTargetOrigin)}removeRelativeTarget(){this.relativeParent=this.relativeTarget=void 0}calcProjection(){let e=this.getLead(),t=!!this.resumingFrom||this!==e,n=!0;if((this.isProjectionDirty||this.parent?.isProjectionDirty)&&(n=!1),t&&(this.isSharedProjectionDirty||this.isTransformDirty)&&(n=!1),this.resolvedRelativeTargetAt===Sr.timestamp&&(n=!1),n)return;let{layout:r,layoutId:i}=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||i))return;Fl(this.layoutCorrected,this.layout.layoutBox);let a=this.treeScale.x,o=this.treeScale.y;Jc(this.layoutCorrected,this.treeScale,this.path,t),e.layout&&!e.target&&(this.treeScale.x!==1||this.treeScale.y!==1)&&(e.target=e.layout.layoutBox,e.targetWithTransforms=mc());let{target:s}=e;if(!s){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(Il(this.prevProjectionDelta.x,this.projectionDelta.x),Il(this.prevProjectionDelta.y,this.projectionDelta.y)),Kl(this.projectionDelta,this.layoutCorrected,s,this.latestValues),(this.treeScale.x!==a||this.treeScale.y!==o||!uu(this.projectionDelta.x,this.prevProjectionDelta.x)||!uu(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners(`projectionUpdate`,s)),_r.value&&Au.calculatedProjections++}hide(){this.isVisible=!1}show(){this.isVisible=!0}scheduleRender(e=!0){if(this.options.visualElement?.scheduleRender(),e){let e=this.getStack();e&&e.scheduleRender()}this.resumingFrom&&!this.resumingFrom.instance&&(this.resumingFrom=void 0)}createProjectionDeltas(){this.prevProjectionDelta=fc(),this.projectionDelta=fc(),this.projectionDeltaWithTransform=fc()}setAnimationOrigin(e,t=!1){let n=this.snapshot,r=n?n.latestValues:{},i={...this.latestValues},a=fc();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!t;let o=mc(),s=(n?n.source:void 0)!==(this.layout?this.layout.source:void 0),c=this.getStack(),l=!c||c.members.length<=1,u=!!(s&&!l&&this.options.crossfade===!0&&!this.path.some(td));this.animationProgress=0;let d;this.mixTargetDelta=t=>{let n=t/1e3;Qu(a.x,e.x,n),Qu(a.y,e.y,n),this.setTargetDelta(a),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(Xl(o,this.layout.layoutBox,this.relativeParent.layout.layoutBox,this.options.layoutAnchor||void 0),ed(this.relativeTarget,this.relativeTargetOrigin,o,n),d&&ou(this.relativeTarget,d)&&(this.isProjectionDirty=!1),d||=mc(),Fl(d,this.relativeTarget)),s&&(this.animationValues=i,_u(i,r,this.latestValues,n,u,l)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=n},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(e){this.notifyListeners(`animationStart`),this.currentAnimation?.stop(),this.resumingFrom?.currentAnimation?.stop(),this.pendingAnimation&&=(xr(this.pendingAnimation),void 0),this.pendingAnimation=A.update(()=>{ku.hasAnimatedSinceResize=!0,Dr.layout++,this.motionValue||=Ho(0),this.motionValue.jump(0,!1),this.currentAnimation=Su(this.motionValue,[0,1e3],{...e,velocity:0,isSync:!0,onUpdate:t=>{this.mixTargetDelta(t),e.onUpdate&&e.onUpdate(t)},onStop:()=>{Dr.layout--},onComplete:()=>{Dr.layout--,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(Mu),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){let e=this.getLead(),{targetWithTransforms:t,target:n,layout:r,latestValues:i}=e;if(!(!t||!n||!r)){if(this!==e&&this.layout&&r&&sd(this.options.animationType,this.layout.layoutBox,r.layoutBox)){n=this.target||mc();let t=Ul(this.layout.layoutBox.x);n.x.min=e.target.x.min,n.x.max=n.x.min+t;let r=Ul(this.layout.layoutBox.y);n.y.min=e.target.y.min,n.y.max=n.y.min+r}Fl(t,n),Qc(t,i),Kl(this.projectionDeltaWithTransform,this.layoutCorrected,t,i)}}registerSharedNode(e,t){this.sharedNodes.has(e)||this.sharedNodes.set(e,new Ou),this.sharedNodes.get(e).add(t);let n=t.options.initialPromotionConfig;t.promote({transition:n?n.transition:void 0,preserveFollowOpacity:n&&n.shouldPreserveFollowOpacity?n.shouldPreserveFollowOpacity(t):void 0})}isLead(){let e=this.getStack();return e?e.lead===this:!0}getLead(){let{layoutId:e}=this.options;return e&&this.getStack()?.lead||this}getPrevLead(){let{layoutId:e}=this.options;return e?this.getStack()?.prevLead:void 0}getStack(){let{layoutId:e}=this.options;if(e)return this.root.sharedNodes.get(e)}promote({needsReset:e,transition:t,preserveFollowOpacity:n}={}){let r=this.getStack();r&&r.promote(this,n),e&&(this.projectionDelta=void 0,this.needsReset=!0),t&&this.setOptions({transition:t})}relegate(){let e=this.getStack();return e?e.relegate(this):!1}resetSkewAndRotation(){let{visualElement:e}=this.options;if(!e)return;let t=!1,{latestValues:n}=e;if((n.z||n.rotate||n.rotateX||n.rotateY||n.rotateZ||n.skewX||n.skewY)&&(t=!0),!t)return;let r={};n.z&&Pu(`z`,e,r,this.animationValues);for(let t=0;t<ju.length;t++)Pu(`rotate${ju[t]}`,e,r,this.animationValues),Pu(`skew${ju[t]}`,e,r,this.animationValues);e.render();for(let t in r)e.setStaticValue(t,r[t]),this.animationValues&&(this.animationValues[t]=r[t]);e.scheduleRender()}applyProjectionStyles(e,t){if(!this.instance||this.isSVG)return;if(!this.isVisible){e.visibility=`hidden`;return}let n=this.getTransformTemplate();if(this.needsReset){this.needsReset=!1,e.visibility=``,e.opacity=``,e.pointerEvents=Du(t?.pointerEvents)||``,e.transform=n?n(this.latestValues,``):`none`;return}let r=this.getLead();if(!this.projectionDelta||!this.layout||!r.target){this.options.layoutId&&(e.opacity=this.latestValues.opacity===void 0?1:this.latestValues.opacity,e.pointerEvents=Du(t?.pointerEvents)||``),this.hasProjected&&!zc(this.latestValues)&&(e.transform=n?n({},``):`none`,this.hasProjected=!1);return}e.visibility=``;let i=r.animationValues||r.latestValues;this.applyTransformsToTarget();let a=fu(this.projectionDeltaWithTransform,this.treeScale,i);n&&(a=n(i,a)),e.transform=a;let{x:o,y:s}=this.projectionDelta;e.transformOrigin=`${o.origin*100}% ${s.origin*100}% 0`,r.animationValues?e.opacity=r===this?i.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:i.opacityExit:e.opacity=r===this?i.opacity===void 0?``:i.opacity:i.opacityExit===void 0?0:i.opacityExit;for(let t in ll){if(i[t]===void 0)continue;let{correct:n,applyTo:o,isCSSVariable:s}=ll[t],c=a===`none`?i[t]:n(i[t],r);if(o){let t=o.length;for(let n=0;n<t;n++)e[o[n]]=c}else s?this.options.visualElement.renderState.vars[t]=c:e[t]=c}this.options.layoutId&&(e.pointerEvents=r===this?Du(t?.pointerEvents)||``:`none`)}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(e=>e.currentAnimation?.stop()),this.root.nodes.forEach(Hu),this.root.sharedNodes.clear()}}}function Lu(e){e.updateLayout()}function Ru(e){let t=e.resumeFrom?.snapshot||e.snapshot;if(e.isLead()&&e.layout&&t&&e.hasListeners(`didUpdate`)){let{layoutBox:n,measuredBox:r}=e.layout,{animationType:i}=e.options,a=t.source!==e.layout.source;if(i===`size`)du(e=>{let r=a?t.measuredBox[e]:t.layoutBox[e],i=Ul(r);r.min=n[e].min,r.max=r.min+i});else if(i===`x`||i===`y`){let e=i===`x`?`y`:`x`;Pl(a?t.measuredBox[e]:t.layoutBox[e],n[e])}else sd(i,t.layoutBox,n)&&du(r=>{let i=a?t.measuredBox[r]:t.layoutBox[r],o=Ul(n[r]);i.max=i.min+o,e.relativeTarget&&!e.currentAnimation&&(e.isProjectionDirty=!0,e.relativeTarget[r].max=e.relativeTarget[r].min+o)});let o=fc();Kl(o,n,t.layoutBox);let s=fc();a?Kl(s,e.applyTransform(r,!0),t.measuredBox):Kl(s,n,t.layoutBox);let c=!iu(o),l=!1;if(!e.resumeFrom){let r=e.getClosestProjectingParent();if(r&&!r.resumeFrom){let{snapshot:i,layout:a}=r;if(i&&a){let o=e.options.layoutAnchor||void 0,s=mc();Xl(s,t.layoutBox,i.layoutBox,o);let c=mc();Xl(c,n,a.layoutBox,o),cu(s,c)||(l=!0),r.options.layoutRoot&&(e.relativeTarget=c,e.relativeTargetOrigin=s,e.relativeParent=r)}}}e.notifyListeners(`didUpdate`,{layout:n,snapshot:t,delta:s,layoutDelta:o,hasLayoutChanged:c,hasRelativeLayoutChanged:l})}else if(e.isLead()){let{onExitComplete:t}=e.options;t&&t()}e.options.transition=void 0}function zu(e){_r.value&&Au.nodes++,e.parent&&(e.isProjecting()||(e.isProjectionDirty=e.parent.isProjectionDirty),e.isSharedProjectionDirty||=!!(e.isProjectionDirty||e.parent.isProjectionDirty||e.parent.isSharedProjectionDirty),e.isTransformDirty||=e.parent.isTransformDirty)}function Bu(e){e.isProjectionDirty=e.isSharedProjectionDirty=e.isTransformDirty=!1}function Vu(e){e.clearSnapshot()}function Hu(e){e.clearMeasurements()}function Uu(e){e.isLayoutDirty=!0,e.updateLayout()}function Wu(e){e.isLayoutDirty=!1}function Gu(e){e.isAnimationBlocked&&e.layout&&!e.isLayoutDirty&&(e.snapshot=e.layout,e.isLayoutDirty=!0)}function Ku(e){let{visualElement:t}=e.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify(`BeforeLayoutMeasure`),e.resetTransform()}function qu(e){e.finishAnimation(),e.targetDelta=e.relativeTarget=e.target=void 0,e.isProjectionDirty=!0}function Ju(e){e.resolveTargetDelta()}function Yu(e){e.calcProjection()}function Xu(e){e.resetSkewAndRotation()}function Zu(e){e.removeLeadSnapshot()}function Qu(e,t,n){e.translate=M(t.translate,0,n),e.scale=M(t.scale,1,n),e.origin=t.origin,e.originPoint=t.originPoint}function $u(e,t,n,r){e.min=M(t.min,n.min,r),e.max=M(t.max,n.max,r)}function ed(e,t,n,r){$u(e.x,t.x,n.x,r),$u(e.y,t.y,n.y,r)}function td(e){return e.animationValues&&e.animationValues.opacityExit!==void 0}var nd={duration:.45,ease:[.4,0,.1,1]},rd=e=>typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(e),id=rd(`applewebkit/`)&&!rd(`chrome/`)?Math.round:Rn;function ad(e){e.min=id(e.min),e.max=id(e.max)}function od(e){ad(e.x),ad(e.y)}function sd(e,t,n){return e===`position`||e===`preserve-aspect`&&!Wl(lu(t),lu(n),.2)}function cd(e){return e!==e.root&&e.scroll?.wasRoot}var ld=Iu({attachResizeListener:(e,t)=>Cu(e,`resize`,t),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body?.scrollLeft||0,y:document.documentElement.scrollTop||document.body?.scrollTop||0}),checkIsScrollRoot:()=>!0}),ud={current:void 0},dd=Iu({measureScroll:e=>({x:e.scrollLeft,y:e.scrollTop}),defaultParent:()=>{if(!ud.current){let e=new ld({});e.mount(window),e.setOptions({layoutScroll:!0}),ud.current=e}return ud.current},resetTransform:(e,t)=>{e.style.transform=t===void 0?`none`:t},checkIsScrollRoot:e=>window.getComputedStyle(e).position===`fixed`}),fd=(0,d.createContext)({transformPagePoint:e=>e,isStatic:!1,reducedMotion:`never`});function pd(e=!0){let t=(0,d.useContext)(En);if(t===null)return[!0,null];let{isPresent:n,onExitComplete:r,register:i}=t,a=(0,d.useId)();(0,d.useEffect)(()=>{if(e)return i(a)},[e]);let o=(0,d.useCallback)(()=>e&&r&&r(a),[a,r,e]);return!n&&r?[!1,o]:[!0]}var md=(0,d.createContext)({strict:!1}),hd={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`]},gd=!1;function _d(){if(gd)return;let e={};for(let t in hd)e[t]={isEnabled:e=>hd[t].some(t=>!!e[t])};kc(e),gd=!0}function vd(){return _d(),Ac()}function yd(e){let t=vd();for(let n in e)t[n]={...t[n],...e[n]};kc(t)}var bd=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.propagate.ignoreStrict.viewport`.split(`.`));function xd(e){return e.startsWith(`while`)||e.startsWith(`drag`)&&e!==`draggable`||e.startsWith(`layout`)||e.startsWith(`onTap`)||e.startsWith(`onPan`)||e.startsWith(`onLayout`)||bd.has(e)}var Sd=s({default:()=>Cd}),Cd,wd=o((()=>{throw Cd={},Error(`Could not resolve "@emotion/is-prop-valid" imported by "framer-motion". Is it installed?`)})),Td=e=>!xd(e);function Ed(e){typeof e==`function`&&(Td=t=>t.startsWith(`on`)?!xd(t):e(t))}try{Ed((wd(),u(Sd)).default)}catch{}function Dd(e,t,n){let r={};for(let i in e)i===`values`&&typeof e.values==`object`||qo(e[i])||(Td(i)||n===!0&&xd(i)||!t&&!xd(i)||e.draggable&&i.startsWith(`onDrag`))&&(r[i]=e[i]);return r}var Od=(0,d.createContext)({});function kd(e,t){if(bc(e)){let{initial:t,animate:n}=e;return{initial:t===!1||_c(t)?t:void 0,animate:_c(n)?n:void 0}}return e.inherit===!1?{}:t}function Ad(e){let{initial:t,animate:n}=kd(e,(0,d.useContext)(Od));return(0,d.useMemo)(()=>({initial:t,animate:n}),[jd(t),jd(n)])}function jd(e){return Array.isArray(e)?e.join(` `):e}var Md=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Nd(e,t,n){for(let r in t)!qo(t[r])&&!ul(r,n)&&(e[r]=t[r])}function Pd({transformTemplate:e},t){return(0,d.useMemo)(()=>{let n=Md();return il(n,t,e),Object.assign({},n.vars,n.style)},[t])}function Fd(e,t){let n=e.style||{},r={};return Nd(r,n,e),Object.assign(r,Pd(e,t)),r}function Id(e,t){let n={},r=Fd(e,t);return e.drag&&e.dragListener!==!1&&(n.draggable=!1,r.userSelect=r.WebkitUserSelect=r.WebkitTouchCallout=`none`,r.touchAction=e.drag===!0?`none`:`pan-${e.drag===`x`?`y`:`x`}`),e.tabIndex===void 0&&(e.onTap||e.onTapStart||e.whileTap)&&(n.tabIndex=0),n.style=r,n}var Ld=()=>({...Md(),attrs:{}});function Rd(e,t,n,r){let i=(0,d.useMemo)(()=>{let n=Ld();return vl(n,t,bl(r),e.transformTemplate,e.style),{...n.attrs,style:{...n.style}}},[t]);if(e.style){let t={};Nd(t,e.style,e),i.style={...t,...i.style}}return i}var zd=[`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 Bd(e){return typeof e!=`string`||e.includes(`-`)?!1:!!(zd.indexOf(e)>-1||/[A-Z]/u.test(e))}function Vd(e,t,n,{latestValues:r},i,a=!1,o){let s=(o??Bd(e)?Rd:Id)(t,r,i,e),c=Dd(t,typeof e==`string`,a),l=e===d.Fragment?{}:{...c,...s,ref:n},{children:u}=t,f=(0,d.useMemo)(()=>qo(u)?u.get():u,[u]);return(0,d.createElement)(e,{...l,children:f})}function Hd({scrapeMotionValuesFromProps:e,createRenderState:t},n,r,i){return{latestValues:Ud(n,r,i,e),renderState:t()}}function Ud(e,t,n,r){let i={},a=r(e,{});for(let e in a)i[e]=Du(a[e]);let{initial:o,animate:s}=e,c=bc(e),l=xc(e);t&&l&&!c&&e.inherit!==!1&&(o===void 0&&(o=t.initial),s===void 0&&(s=t.animate));let u=n?n.initial===!1:!1;u||=o===!1;let d=u?s:o;if(d&&typeof d!=`boolean`&&!gc(d)){let t=Array.isArray(d)?d:[d];for(let n=0;n<t.length;n++){let r=Fo(e,t[n]);if(r){let{transitionEnd:e,transition:t,...n}=r;for(let e in n){let t=n[e];if(Array.isArray(t)){let e=u?t.length-1:0;t=t[e]}t!==null&&(i[e]=t)}for(let t in e)i[t]=e[t]}}}return i}var Wd=e=>(t,n)=>{let r=(0,d.useContext)(Od),i=(0,d.useContext)(En),a=()=>Hd(e,t,r,i);return n?a():wn(a)},Gd=Wd({scrapeMotionValuesFromProps:dl,createRenderState:Md}),Kd=Wd({scrapeMotionValuesFromProps:Sl,createRenderState:Ld}),qd=Symbol.for(`motionComponentSymbol`);function Jd(e,t,n){let r=(0,d.useRef)(n);(0,d.useInsertionEffect)(()=>{r.current=n});let i=(0,d.useRef)(null);return(0,d.useCallback)(n=>{n&&e.onMount?.(n);let a=r.current;if(typeof a==`function`)if(n){let e=a(n);typeof e==`function`&&(i.current=e)}else i.current?(i.current(),i.current=null):a(n);else a&&(a.current=n);t&&(n?t.mount(n):t.unmount())},[t])}var Yd=(0,d.createContext)({});function Xd(e){return e&&typeof e==`object`&&Object.prototype.hasOwnProperty.call(e,`current`)}function Zd(e,t,n,r,i,a){let{visualElement:o}=(0,d.useContext)(Od),s=(0,d.useContext)(md),c=(0,d.useContext)(En),l=(0,d.useContext)(fd),u=l.reducedMotion,f=l.skipAnimations,p=(0,d.useRef)(null),m=(0,d.useRef)(!1);r||=s.renderer,!p.current&&r&&(p.current=r(e,{visualState:t,parent:o,props:n,presenceContext:c,blockInitialAnimation:c?c.initial===!1:!1,reducedMotionConfig:u,skipAnimations:f,isSVG:a}),m.current&&p.current&&(p.current.manuallyAnimateOnMount=!0));let h=p.current,g=(0,d.useContext)(Yd);h&&!h.projection&&i&&(h.type===`html`||h.type===`svg`)&&Qd(p.current,n,i,g);let _=(0,d.useRef)(!1);(0,d.useInsertionEffect)(()=>{h&&_.current&&h.update(n,c)});let v=n[Zo],y=(0,d.useRef)(!!v&&typeof window<`u`&&!window.MotionHandoffIsComplete?.(v)&&window.MotionHasOptimisedAnimation?.(v));return Tn(()=>{m.current=!0,h&&(_.current=!0,window.MotionIsMounted=!0,h.updateFeatures(),h.scheduleRenderMicrotask(),y.current&&h.animationState&&h.animationState.animateChanges())}),(0,d.useEffect)(()=>{h&&(!y.current&&h.animationState&&h.animationState.animateChanges(),y.current&&=(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(v)}),!1),h.enteringChildren=void 0)}),h}function Qd(e,t,n,r){let{layoutId:i,layout:a,drag:o,dragConstraints:s,layoutScroll:c,layoutRoot:l,layoutAnchor:u,layoutCrossfade:d}=t;e.projection=new n(e.latestValues,t[`data-framer-portal-id`]?void 0:$d(e.parent)),e.projection.setOptions({layoutId:i,layout:a,alwaysMeasureLayout:!!o||s&&Xd(s),visualElement:e,animationType:typeof a==`string`?a:`both`,initialPromotionConfig:r,crossfade:d,layoutScroll:c,layoutRoot:l,layoutAnchor:u})}function $d(e){if(e)return e.options.allowProjection===!1?$d(e.parent):e.projection}function ef(e,{forwardMotionProps:t=!1,type:n}={},r,i){r&&yd(r);let a=n?n===`svg`:Bd(e),o=a?Kd:Gd;function s(n,s){let c,l={...(0,d.useContext)(fd),...n,layoutId:tf(n)},{isStatic:u}=l,p=Ad(n),m=o(n,u);if(!u&&typeof window<`u`){nf(l,r);let t=rf(l);c=t.MeasureLayout,p.visualElement=Zd(e,m,l,i,t.ProjectionNode,a)}return(0,f.jsxs)(Od.Provider,{value:p,children:[c&&p.visualElement?(0,f.jsx)(c,{visualElement:p.visualElement,...l}):null,Vd(e,n,Jd(m,p.visualElement,s),m,u,t,a)]})}s.displayName=`motion.${typeof e==`string`?e:`create(${e.displayName??e.name??``})`}`;let c=(0,d.forwardRef)(s);return c[qd]=e,c}function tf({layoutId:e}){let t=(0,d.useContext)(Cn).id;return t&&e!==void 0?t+`-`+e:e}function nf(e,t){let n=(0,d.useContext)(md).strict;if(process.env.NODE_ENV!==`production`&&t&&n){let t="You have rendered a `motion` component within a `LazyMotion` component. This will break tree shaking. Import and render a `m` component instead.";e.ignoreStrict?jn(!1,t,`lazy-strict-mode`):Mn(!1,t,`lazy-strict-mode`)}}function rf(e){let{drag:t,layout:n}=vd();if(!t&&!n)return{};let r={...t,...n};return{MeasureLayout:t?.isEnabled(e)||n?.isEnabled(e)?r.MeasureLayout:void 0,ProjectionNode:r.ProjectionNode}}function af(e,t){if(typeof Proxy>`u`)return ef;let n=new Map,r=(n,r)=>ef(n,r,e,t);return new Proxy((e,t)=>(process.env.NODE_ENV!==`production`&&qn(!1,`motion() is deprecated. Use motion.create() instead.`),r(e,t)),{get:(i,a)=>a===`create`?r:(n.has(a)||n.set(a,ef(a,void 0,e,t)),n.get(a))})}var of=(e,t)=>t.isSVG??Bd(e)?new Cl(t):new pl(t,{allowProjection:e!==d.Fragment}),sf=class extends Nc{constructor(e){super(e),e.animationState||=Al(e)}updateAnimationControlsSubscription(){let{animate:e}=this.node.getProps();gc(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(){this.node.animationState.reset(),this.unmountControls?.()}},cf=0,lf={animation:{Feature:sf},exit:{Feature:class extends Nc{constructor(){super(...arguments),this.id=cf++,this.isExitComplete=!1}update(){if(!this.node.presenceContext)return;let{isPresent:e,onExitComplete:t}=this.node.presenceContext,{isPresent:n}=this.node.prevPresenceContext||{};if(!this.node.animationState||e===n)return;if(e&&n===!1){if(this.isExitComplete){let{initial:e,custom:t}=this.node.getProps();if(typeof e==`string`){let n=Io(this.node,e,t);if(n){let{transition:e,transitionEnd:t,...r}=n;for(let e in r)this.node.getValue(e)?.jump(r[e])}}this.node.animationState.reset(),this.node.animationState.animateChanges()}else this.node.animationState.setActive(`exit`,!1);this.isExitComplete=!1;return}let r=this.node.animationState.setActive(`exit`,!e);t&&!e&&r.then(()=>{this.isExitComplete=!0,t(this.id)})}mount(){let{register:e,onExitComplete:t}=this.node.presenceContext||{};t&&t(this.id),e&&(this.unmount=e(this.id))}unmount(){}}}};function uf(e){return{point:{x:e.pageX,y:e.pageY}}}var df=e=>t=>Fs(t)&&e(t,uf(t));function ff(e,t,n,r){return Cu(e,t,df(n),r)}var pf=({current:e})=>e?e.ownerDocument.defaultView:null,mf=(e,t)=>Math.abs(e-t);function hf(e,t){let n=mf(e.x,t.x),r=mf(e.y,t.y);return Math.sqrt(n**2+r**2)}var gf=new Set([`auto`,`scroll`]),_f=class{constructor(e,t,{transformPagePoint:n,contextWindow:r=window,dragSnapToOrigin:i=!1,distanceThreshold:a=3,element:o}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.lastRawMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.scrollPositions=new Map,this.removeScrollListeners=null,this.onElementScroll=e=>{this.handleScroll(e.target)},this.onWindowScroll=()=>{this.handleScroll(window)},this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;this.lastRawMoveEventInfo&&(this.lastMoveEventInfo=vf(this.lastRawMoveEventInfo,this.transformPagePoint));let e=bf(this.lastMoveEventInfo,this.history),t=this.startEvent!==null,n=hf(e.offset,{x:0,y:0})>=this.distanceThreshold;if(!t&&!n)return;let{point:r}=e,{timestamp:i}=Sr;this.history.push({...r,timestamp:i});let{onStart:a,onMove:o}=this.handlers;t||(a&&a(this.lastMoveEvent,e),this.startEvent=this.lastMoveEvent),o&&o(this.lastMoveEvent,e)},this.handlePointerMove=(e,t)=>{this.lastMoveEvent=e,this.lastRawMoveEventInfo=t,this.lastMoveEventInfo=vf(t,this.transformPagePoint),A.update(this.updatePoint,!0)},this.handlePointerUp=(e,t)=>{this.end();let{onEnd:n,onSessionEnd:r,resumeAnimation:i}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&i&&i(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;let a=bf(e.type===`pointercancel`?this.lastMoveEventInfo:vf(t,this.transformPagePoint),this.history);this.startEvent&&n&&n(e,a),r&&r(e,a)},!Fs(e))return;this.dragSnapToOrigin=i,this.handlers=t,this.transformPagePoint=n,this.distanceThreshold=a,this.contextWindow=r||window;let s=vf(uf(e),this.transformPagePoint),{point:c}=s,{timestamp:l}=Sr;this.history=[{...c,timestamp:l}];let{onSessionStart:u}=t;u&&u(e,bf(s,this.history)),this.removeListeners=Bn(ff(this.contextWindow,`pointermove`,this.handlePointerMove),ff(this.contextWindow,`pointerup`,this.handlePointerUp),ff(this.contextWindow,`pointercancel`,this.handlePointerUp)),o&&this.startScrollTracking(o)}startScrollTracking(e){let t=e.parentElement;for(;t;){let e=getComputedStyle(t);(gf.has(e.overflowX)||gf.has(e.overflowY))&&this.scrollPositions.set(t,{x:t.scrollLeft,y:t.scrollTop}),t=t.parentElement}this.scrollPositions.set(window,{x:window.scrollX,y:window.scrollY}),window.addEventListener(`scroll`,this.onElementScroll,{capture:!0}),window.addEventListener(`scroll`,this.onWindowScroll),this.removeScrollListeners=()=>{window.removeEventListener(`scroll`,this.onElementScroll,{capture:!0}),window.removeEventListener(`scroll`,this.onWindowScroll)}}handleScroll(e){let t=this.scrollPositions.get(e);if(!t)return;let n=e===window,r=n?{x:window.scrollX,y:window.scrollY}:{x:e.scrollLeft,y:e.scrollTop},i={x:r.x-t.x,y:r.y-t.y};i.x===0&&i.y===0||(n?this.lastMoveEventInfo&&(this.lastMoveEventInfo.point.x+=i.x,this.lastMoveEventInfo.point.y+=i.y):this.history.length>0&&(this.history[0].x-=i.x,this.history[0].y-=i.y),this.scrollPositions.set(e,r),A.update(this.updatePoint,!0))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),xr(this.updatePoint)}};function vf(e,t){return t?{point:t(e.point)}:e}function yf(e,t){return{x:e.x-t.x,y:e.y-t.y}}function bf({point:e},t){return{point:e,delta:yf(e,Sf(t)),offset:yf(e,xf(t)),velocity:Cf(t,.1)}}function xf(e){return e[0]}function Sf(e){return e[e.length-1]}function Cf(e,t){if(e.length<2)return{x:0,y:0};let n=e.length-1,r=null,i=Sf(e);for(;n>=0&&(r=e[n],!(i.timestamp-r.timestamp>Un(t)));)n--;if(!r)return{x:0,y:0};r===e[0]&&e.length>2&&i.timestamp-r.timestamp>Un(t)*2&&(r=e[1]);let a=Wn(i.timestamp-r.timestamp);if(a===0)return{x:0,y:0};let o={x:(i.x-r.x)/a,y:(i.y-r.y)/a};return o.x===1/0&&(o.x=0),o.y===1/0&&(o.y=0),o}function wf(e,{min:t,max:n},r){return t!==void 0&&e<t?e=r?M(t,e,r.min):Math.max(e,t):n!==void 0&&e>n&&(e=r?M(n,e,r.max):Math.min(e,n)),e}function Tf(e,t,n){return{min:t===void 0?void 0:e.min+t,max:n===void 0?void 0:e.max+n-(e.max-e.min)}}function Ef(e,{top:t,left:n,bottom:r,right:i}){return{x:Tf(e.x,n,i),y:Tf(e.y,t,r)}}function Df(e,t){let n=t.min-e.min,r=t.max-e.max;return t.max-t.min<e.max-e.min&&([n,r]=[r,n]),{min:n,max:r}}function Of(e,t){return{x:Df(e.x,t.x),y:Df(e.y,t.y)}}function kf(e,t){let n=.5,r=Ul(e),i=Ul(t);return i>r?n=Vn(t.min,t.max-r,e.min):r>i&&(n=Vn(e.min,e.max-i,t.min)),kn(0,1,n)}function Af(e,t){let n={};return t.min!==void 0&&(n.min=t.min-e.min),t.max!==void 0&&(n.max=t.max-e.min),n}var jf=.35;function Mf(e=jf){return e===!1?e=0:e===!0&&(e=jf),{x:Nf(e,`left`,`right`),y:Nf(e,`top`,`bottom`)}}function Nf(e,t,n){return{min:Pf(e,t),max:Pf(e,n)}}function Pf(e,t){return typeof e==`number`?e:e[t]||0}var Ff=new WeakMap,If=class{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=mc(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=e}start(e,{snapToCursor:t=!1,distanceThreshold:n}={}){let{presenceContext:r}=this.visualElement;if(r&&r.isPresent===!1)return;let i=e=>{t&&this.snapToCursor(uf(e).point),this.stopAnimation()},a=(e,t)=>{let{drag:n,dragPropagation:r,onDragStart:i}=this.getProps();if(n&&!r&&(this.openDragLock&&this.openDragLock(),this.openDragLock=As(n),!this.openDragLock))return;this.latestPointerEvent=e,this.latestPanInfo=t,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),du(e=>{let t=this.getAxisMotionValue(e).get()||0;if(Xr.test(t)){let{projection:n}=this.visualElement;if(n&&n.layout){let r=n.layout.layoutBox[e];r&&(t=Ul(r)*(parseFloat(t)/100))}}this.originPoint[e]=t}),i&&A.update(()=>i(e,t),!1,!0),Yo(this.visualElement,`transform`);let{animationState:a}=this.visualElement;a&&a.setActive(`whileDrag`,!0)},o=(e,t)=>{this.latestPointerEvent=e,this.latestPanInfo=t;let{dragPropagation:n,dragDirectionLock:r,onDirectionLock:i,onDrag:a}=this.getProps();if(!n&&!this.openDragLock)return;let{offset:o}=t;if(r&&this.currentDirection===null){this.currentDirection=Bf(o),this.currentDirection!==null&&i&&i(this.currentDirection);return}this.updateAxis(`x`,t.point,o),this.updateAxis(`y`,t.point,o),this.visualElement.render(),a&&A.update(()=>a(e,t),!1,!0)},s=(e,t)=>{this.latestPointerEvent=e,this.latestPanInfo=t,this.stop(e,t),this.latestPointerEvent=null,this.latestPanInfo=null},c=()=>{let{dragSnapToOrigin:e}=this.getProps();(e||this.constraints)&&this.startAnimation({x:0,y:0})},{dragSnapToOrigin:l}=this.getProps();this.panSession=new _f(e,{onSessionStart:i,onStart:a,onMove:o,onSessionEnd:s,resumeAnimation:c},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:l,distanceThreshold:n,contextWindow:pf(this.visualElement),element:this.visualElement.current})}stop(e,t){let n=e||this.latestPointerEvent,r=t||this.latestPanInfo,i=this.isDragging;if(this.cancel(),!i||!r||!n)return;let{velocity:a}=r;this.startAnimation(a);let{onDragEnd:o}=this.getProps();o&&A.postRender(()=>o(n,r))}cancel(){this.isDragging=!1;let{projection:e,animationState:t}=this.visualElement;e&&(e.isAnimationBlocked=!1),this.endPanSession();let{dragPropagation:n}=this.getProps();!n&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),t&&t.setActive(`whileDrag`,!1)}endPanSession(){this.panSession&&this.panSession.end(),this.panSession=void 0}updateAxis(e,t,n){let{drag:r}=this.getProps();if(!n||!zf(e,r,this.currentDirection))return;let i=this.getAxisMotionValue(e),a=this.originPoint[e]+n[e];this.constraints&&this.constraints[e]&&(a=wf(a,this.constraints[e],this.elastic[e])),i.set(a)}resolveConstraints(){let{dragConstraints:e,dragElastic:t}=this.getProps(),n=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):this.visualElement.projection?.layout,r=this.constraints;e&&Xd(e)?this.constraints||=this.resolveRefConstraints():e&&n?this.constraints=Ef(n.layoutBox,e):this.constraints=!1,this.elastic=Mf(t),r!==this.constraints&&!Xd(e)&&n&&this.constraints&&!this.hasMutatedConstraints&&du(e=>{this.constraints!==!1&&this.getAxisMotionValue(e)&&(this.constraints[e]=Af(n.layoutBox[e],this.constraints[e]))})}resolveRefConstraints(){let{dragConstraints:e,onMeasureDragConstraints:t}=this.getProps();if(!e||!Xd(e))return!1;let n=e.current;Mn(n!==null,"If `dragConstraints` is set as a React ref, that ref must be passed to another component's `ref` prop.",`drag-constraints-ref`);let{projection:r}=this.visualElement;if(!r||!r.layout)return!1;let i=el(n,r.root,this.visualElement.getTransformPagePoint()),a=Of(r.layout.layoutBox,i);if(t){let e=t(Fc(a));this.hasMutatedConstraints=!!e,e&&(a=Pc(e))}return a}startAnimation(e){let{drag:t,dragMomentum:n,dragElastic:r,dragTransition:i,dragSnapToOrigin:a,onDragTransitionEnd:o}=this.getProps(),s=this.constraints||{},c=du(o=>{if(!zf(o,t,this.currentDirection))return;let c=s&&s[o]||{};(a===!0||a===o)&&(c={min:0,max:0});let l=r?200:1e6,u=r?40:1e7,d={type:`inertia`,velocity:n?e[o]:0,bounceStiffness:l,bounceDamping:u,timeConstant:750,restDelta:1,restSpeed:10,...i,...c};return this.startAxisValueAnimation(o,d)});return Promise.all(c).then(o)}startAxisValueAnimation(e,t){let n=this.getAxisMotionValue(e);return Yo(this.visualElement,e),n.start(No(e,n,0,t,this.visualElement,!1))}stopAnimation(){du(e=>this.getAxisMotionValue(e).stop())}getAxisMotionValue(e){let t=`_drag${e.toUpperCase()}`,n=this.visualElement.getProps();return n[t]||this.visualElement.getValue(e,(n.initial?n.initial[e]:void 0)||0)}snapToCursor(e){du(t=>{let{drag:n}=this.getProps();if(!zf(t,n,this.currentDirection))return;let{projection:r}=this.visualElement,i=this.getAxisMotionValue(t);if(r&&r.layout){let{min:n,max:a}=r.layout.layoutBox[t],o=i.get()||0;i.set(e[t]-M(n,a,.5)+o)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;let{drag:e,dragConstraints:t}=this.getProps(),{projection:n}=this.visualElement;if(!Xd(t)||!n||!this.constraints)return;this.stopAnimation();let r={x:0,y:0};du(e=>{let t=this.getAxisMotionValue(e);if(t&&this.constraints!==!1){let n=t.get();r[e]=kf({min:n,max:n},this.constraints[e])}});let{transformTemplate:i}=this.visualElement.getProps();this.visualElement.current.style.transform=i?i({},``):`none`,n.root&&n.root.updateScroll(),n.updateLayout(),this.constraints=!1,this.resolveConstraints(),du(t=>{if(!zf(t,e,null))return;let n=this.getAxisMotionValue(t),{min:i,max:a}=this.constraints[t];n.set(M(i,a,r[t]))}),this.visualElement.render()}addListeners(){if(!this.visualElement.current)return;Ff.set(this.visualElement,this);let e=this.visualElement.current,t=ff(e,`pointerdown`,t=>{let{drag:n,dragListener:r=!0}=this.getProps(),i=t.target,a=i!==e&&zs(i);n&&r&&!a&&this.start(t)}),n,r=()=>{let{dragConstraints:t}=this.getProps();Xd(t)&&t.current&&(this.constraints=this.resolveRefConstraints(),n||=Rf(e,t.current,()=>this.scalePositionWithinConstraints()))},{projection:i}=this.visualElement,a=i.addEventListener(`measure`,r);i&&!i.layout&&(i.root&&i.root.updateScroll(),i.updateLayout()),A.read(r);let o=Cu(window,`resize`,()=>this.scalePositionWithinConstraints()),s=i.addEventListener(`didUpdate`,(({delta:e,hasLayoutChanged:t})=>{this.isDragging&&t&&(du(t=>{let n=this.getAxisMotionValue(t);n&&(this.originPoint[t]+=e[t].translate,n.set(n.get()+e[t].translate))}),this.visualElement.render())}));return()=>{o(),t(),a(),s&&s(),n&&n()}}getProps(){let e=this.visualElement.getProps(),{drag:t=!1,dragDirectionLock:n=!1,dragPropagation:r=!1,dragConstraints:i=!1,dragElastic:a=jf,dragMomentum:o=!0}=e;return{...e,drag:t,dragDirectionLock:n,dragPropagation:r,dragConstraints:i,dragElastic:a,dragMomentum:o}}};function Lf(e){let t=!0;return()=>{if(t){t=!1;return}e()}}function Rf(e,t,n){let r=sc(e,Lf(n)),i=sc(t,Lf(n));return()=>{r(),i()}}function zf(e,t,n){return(t===!0||t===e)&&(n===null||n===e)}function Bf(e,t=10){let n=null;return Math.abs(e.y)>t?n=`y`:Math.abs(e.x)>t&&(n=`x`),n}var Vf=class extends Nc{constructor(e){super(e),this.removeGroupControls=Rn,this.removeListeners=Rn,this.controls=new If(e)}mount(){let{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Rn}update(){let{dragControls:e}=this.node.getProps(),{dragControls:t}=this.node.prevProps||{};e!==t&&(this.removeGroupControls(),e&&(this.removeGroupControls=e.subscribe(this.controls)))}unmount(){this.removeGroupControls(),this.removeListeners(),this.controls.isDragging||this.controls.endPanSession()}},Hf=e=>(t,n)=>{e&&A.update(()=>e(t,n),!1,!0)},Uf=class extends Nc{constructor(){super(...arguments),this.removePointerDownListener=Rn}onPointerDown(e){this.session=new _f(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:pf(this.node)})}createPanHandlers(){let{onPanSessionStart:e,onPanStart:t,onPan:n,onPanEnd:r}=this.node.getProps();return{onSessionStart:Hf(e),onStart:Hf(t),onMove:Hf(n),onEnd:(e,t)=>{delete this.session,r&&A.postRender(()=>r(e,t))}}}mount(){this.removePointerDownListener=ff(this.node.current,`pointerdown`,e=>this.onPointerDown(e))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}},Wf=!1,Gf=class extends d.Component{componentDidMount(){let{visualElement:e,layoutGroup:t,switchLayoutGroup:n,layoutId:r}=this.props,{projection:i}=e;i&&(t.group&&t.group.add(i),n&&n.register&&r&&n.register(i),Wf&&i.root.didUpdate(),i.addEventListener(`animationComplete`,()=>{this.safeToRemove()}),i.setOptions({...i.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),ku.hasEverUpdated=!0}getSnapshotBeforeUpdate(e){let{layoutDependency:t,visualElement:n,drag:r,isPresent:i}=this.props,{projection:a}=n;return a?(a.isPresent=i,e.layoutDependency!==t&&a.setOptions({...a.options,layoutDependency:t}),Wf=!0,r||e.layoutDependency!==t||t===void 0||e.isPresent!==i?a.willUpdate():this.safeToRemove(),e.isPresent!==i&&(i?a.promote():a.relegate()||A.postRender(()=>{let e=a.getStack();(!e||!e.members.length)&&this.safeToRemove()})),null):null}componentDidUpdate(){let{visualElement:e,layoutAnchor:t}=this.props,{projection:n}=e;n&&(n.options.layoutAnchor=t,n.root.didUpdate(),Es.postRender(()=>{!n.currentAnimation&&n.isLead()&&this.safeToRemove()}))}componentWillUnmount(){let{visualElement:e,layoutGroup:t,switchLayoutGroup:n}=this.props,{projection:r}=e;Wf=!0,r&&(r.scheduleCheckAfterUnmount(),t&&t.group&&t.group.remove(r),n&&n.deregister&&n.deregister(r))}safeToRemove(){let{safeToRemove:e}=this.props;e&&e()}render(){return null}};function Kf(e){let[t,n]=pd(),r=(0,d.useContext)(Cn);return(0,f.jsx)(Gf,{...e,layoutGroup:r,switchLayoutGroup:(0,d.useContext)(Yd),isPresent:t,safeToRemove:n})}var qf={pan:{Feature:Uf},drag:{Feature:Vf,ProjectionNode:dd,MeasureLayout:Kf}};function Jf(e,t,n){let{props:r}=e;e.animationState&&r.whileHover&&e.animationState.setActive(`whileHover`,n===`Start`);let i=r[`onHover`+n];i&&A.postRender(()=>i(t,uf(t)))}var Yf=class extends Nc{mount(){let{current:e}=this.node;e&&(this.unmount=Ns(e,(e,t)=>(Jf(this.node,t,`Start`),e=>Jf(this.node,e,`End`))))}unmount(){}},Xf=class extends Nc{constructor(){super(...arguments),this.isActive=!1}onFocus(){let e=!1;try{e=this.node.current.matches(`:focus-visible`)}catch{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=Bn(Cu(this.node.current,`focus`,()=>this.onFocus()),Cu(this.node.current,`blur`,()=>this.onBlur()))}unmount(){}};function Zf(e,t,n){let{props:r}=e;if(e.current instanceof HTMLButtonElement&&e.current.disabled)return;e.animationState&&r.whileTap&&e.animationState.setActive(`whileTap`,n===`Start`);let i=r[`onTap`+(n===`End`?``:n)];i&&A.postRender(()=>i(t,uf(t)))}var Qf=class extends Nc{mount(){let{current:e}=this.node;if(!e)return;let{globalTapTarget:t,propagate:n}=this.node.props;this.unmount=Ks(e,(e,t)=>(Zf(this.node,t,`Start`),(e,{success:t})=>Zf(this.node,e,t?`End`:`Cancel`)),{useGlobalTarget:t,stopPropagation:n?.tap===!1})}unmount(){}},$f=new WeakMap,ep=new WeakMap,tp=e=>{let t=$f.get(e.target);t&&t(e)},np=e=>{e.forEach(tp)};function rp({root:e,...t}){let n=e||document;ep.has(n)||ep.set(n,{});let r=ep.get(n),i=JSON.stringify(t);return r[i]||(r[i]=new IntersectionObserver(np,{root:e,...t})),r[i]}function ip(e,t,n){let r=rp(t);return $f.set(e,n),r.observe(e),()=>{$f.delete(e),r.unobserve(e)}}var ap={some:0,all:1},op=class extends Nc{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.stopObserver?.();let{viewport:e={}}=this.node.getProps(),{root:t,margin:n,amount:r=`some`,once:i}=e,a={root:t?t.current:void 0,rootMargin:n,threshold:typeof r==`number`?r:ap[r]};this.stopObserver=ip(this.node.current,a,e=>{let{isIntersecting:t}=e;if(this.isInView===t||(this.isInView=t,i&&!t&&this.hasEnteredView))return;t&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive(`whileInView`,t);let{onViewportEnter:n,onViewportLeave:r}=this.node.getProps(),a=t?n:r;a&&a(e)})}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>`u`)return;let{props:e,prevProps:t}=this.node;[`amount`,`margin`,`root`].some(sp(e,t))&&this.startObserver()}unmount(){this.stopObserver?.(),this.hasEnteredView=!1,this.isInView=!1}};function sp({viewport:e={}},{viewport:t={}}={}){return n=>e[n]!==t[n]}var cp={inView:{Feature:op},tap:{Feature:Qf},focus:{Feature:Xf},hover:{Feature:Yf}},lp={layout:{ProjectionNode:dd,MeasureLayout:Kf}},up=af({...lf,...cp,...qf,...lp},of);function dp(e,t){return t.forEach(function(t){t&&typeof t!=`string`&&!Array.isArray(t)&&Object.keys(t).forEach(function(n){if(n!==`default`&&!(n in e)){var r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,r.get?r:{enumerable:!0,get:function(){return t[n]}})}})}),Object.freeze(e)}var fp=Object.defineProperty,pp=(e,t,n)=>t in e?fp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,mp=(e,t,n)=>pp(e,typeof t==`symbol`?t:t+``,n),hp=class{constructor(){mp(this,`_locking`),mp(this,`_locks`),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){this._locks+=1;let e,t=new Promise(t=>e=()=>{--this._locks,t()}),n=this._locking.then(()=>e);return this._locking=this._locking.then(()=>t),n}};function gp(e,t){if(!e)throw Error(t)}var _p=34028234663852886e22,vp=-34028234663852886e22,yp=4294967295,bp=2147483647,xp=-2147483648;function Sp(e){if(typeof e!=`number`)throw Error(`invalid int 32: `+typeof e);if(!Number.isInteger(e)||e>bp||e<xp)throw Error(`invalid int 32: `+e)}function Cp(e){if(typeof e!=`number`)throw Error(`invalid uint 32: `+typeof e);if(!Number.isInteger(e)||e>yp||e<0)throw Error(`invalid uint 32: `+e)}function wp(e){if(typeof e!=`number`)throw Error(`invalid float 32: `+typeof e);if(Number.isFinite(e)&&(e>_p||e<vp))throw Error(`invalid float 32: `+e)}var Tp=Symbol(`@bufbuild/protobuf/enum-type`);function Ep(e){let t=e[Tp];return gp(t,`missing enum type on enum object`),t}function Dp(e,t,n,r){e[Tp]=Op(t,n.map(t=>({no:t.no,name:t.name,localName:e[t.no]})))}function Op(e,t,n){let r=Object.create(null),i=Object.create(null),a=[];for(let e of t){let t=Ap(e);a.push(t),r[e.name]=t,i[e.no]=t}return{typeName:e,values:a,findName(e){return r[e]},findNumber(e){return i[e]}}}function kp(e,t,n){let r={};for(let e of t){let t=Ap(e);r[t.localName]=t.no,r[t.no]=t.localName}return Dp(r,e,t),r}function Ap(e){return`localName`in e?e:Object.assign(Object.assign({},e),{localName:e.name})}var jp=class{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){let n=this.getType().runtime.bin,r=n.makeReadOptions(t);return n.readMessage(this,r.readerFactory(e),e.byteLength,r),this}fromJson(e,t){let n=this.getType(),r=n.runtime.json,i=r.makeReadOptions(t);return r.readMessage(n,e,i,this),this}fromJsonString(e,t){let n;try{n=JSON.parse(e)}catch(e){throw Error(`cannot decode ${this.getType().typeName} from JSON: ${e instanceof Error?e.message:String(e)}`)}return this.fromJson(n,t)}toBinary(e){let t=this.getType().runtime.bin,n=t.makeWriteOptions(e),r=n.writerFactory();return t.writeMessage(this,r,n),r.finish()}toJson(e){let t=this.getType().runtime.json,n=t.makeWriteOptions(e);return t.writeMessage(this,n)}toJsonString(e){let t=this.toJson(e);return JSON.stringify(t,null,e?.prettySpaces??0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}};function Mp(e,t,n,r){let i=r?.localName??t.substring(t.lastIndexOf(`.`)+1),a={[i]:function(t){e.util.initFields(this),e.util.initPartial(t,this)}}[i];return Object.setPrototypeOf(a.prototype,new jp),Object.assign(a,{runtime:e,typeName:t,fields:e.util.newFieldList(n),fromBinary(e,t){return new a().fromBinary(e,t)},fromJson(e,t){return new a().fromJson(e,t)},fromJsonString(e,t){return new a().fromJsonString(e,t)},equals(t,n){return e.util.equals(a,t,n)}}),a}function Np(){let e=0,t=0;for(let n=0;n<28;n+=7){let r=this.buf[this.pos++];if(e|=(r&127)<<n,!(r&128))return this.assertBounds(),[e,t]}let n=this.buf[this.pos++];if(e|=(n&15)<<28,t=(n&112)>>4,!(n&128))return this.assertBounds(),[e,t];for(let n=3;n<=31;n+=7){let r=this.buf[this.pos++];if(t|=(r&127)<<n,!(r&128))return this.assertBounds(),[e,t]}throw Error(`invalid varint`)}function Pp(e,t,n){for(let r=0;r<28;r+=7){let i=e>>>r,a=!(!(i>>>7)&&t==0),o=(a?i|128:i)&255;if(n.push(o),!a)return}let r=e>>>28&15|(t&7)<<4,i=!!(t>>3);if(n.push((i?r|128:r)&255),i){for(let e=3;e<31;e+=7){let r=t>>>e,i=!!(r>>>7),a=(i?r|128:r)&255;if(n.push(a),!i)return}n.push(t>>>31&1)}}var Fp=4294967296;function Ip(e){let t=e[0]===`-`;t&&(e=e.slice(1));let n=1e6,r=0,i=0;function a(t,a){let o=Number(e.slice(t,a));i*=n,r=r*n+o,r>=Fp&&(i+=r/Fp|0,r%=Fp)}return a(-24,-18),a(-18,-12),a(-12,-6),a(-6),t?Vp(r,i):Bp(r,i)}function Lp(e,t){let n=Bp(e,t),r=n.hi&2147483648;r&&(n=Vp(n.lo,n.hi));let i=Rp(n.lo,n.hi);return r?`-`+i:i}function Rp(e,t){if({lo:e,hi:t}=zp(e,t),t<=2097151)return String(Fp*t+e);let n=e&16777215,r=(e>>>24|t<<8)&16777215,i=t>>16&65535,a=n+r*6777216+i*6710656,o=r+i*8147497,s=i*2,c=1e7;return a>=c&&(o+=Math.floor(a/c),a%=c),o>=c&&(s+=Math.floor(o/c),o%=c),s.toString()+Hp(o)+Hp(a)}function zp(e,t){return{lo:e>>>0,hi:t>>>0}}function Bp(e,t){return{lo:e|0,hi:t|0}}function Vp(e,t){return t=~t,e?e=~e+1:t+=1,Bp(e,t)}var Hp=e=>{let t=String(e);return`0000000`.slice(t.length)+t};function Up(e,t){if(e>=0){for(;e>127;)t.push(e&127|128),e>>>=7;t.push(e)}else{for(let n=0;n<9;n++)t.push(e&127|128),e>>=7;t.push(1)}}function Wp(){let e=this.buf[this.pos++],t=e&127;if(!(e&128)||(e=this.buf[this.pos++],t|=(e&127)<<7,!(e&128))||(e=this.buf[this.pos++],t|=(e&127)<<14,!(e&128))||(e=this.buf[this.pos++],t|=(e&127)<<21,!(e&128)))return this.assertBounds(),t;e=this.buf[this.pos++],t|=(e&15)<<28;for(let t=5;e&128&&t<10;t++)e=this.buf[this.pos++];if(e&128)throw Error(`invalid varint`);return this.assertBounds(),t>>>0}function Gp(){let e=new DataView(new ArrayBuffer(8));if(typeof BigInt==`function`&&typeof e.getBigInt64==`function`&&typeof e.getBigUint64==`function`&&typeof e.setBigInt64==`function`&&typeof e.setBigUint64==`function`&&(typeof process!=`object`||typeof process.env!=`object`||process.env.BUF_BIGINT_DISABLE!==`1`)){let t=BigInt(`-9223372036854775808`),n=BigInt(`9223372036854775807`),r=BigInt(`0`),i=BigInt(`18446744073709551615`);return{zero:BigInt(0),supported:!0,parse(e){let r=typeof e==`bigint`?e:BigInt(e);if(r>n||r<t)throw Error(`int64 invalid: ${e}`);return r},uParse(e){let t=typeof e==`bigint`?e:BigInt(e);if(t>i||t<r)throw Error(`uint64 invalid: ${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,n){return e.setInt32(0,t,!0),e.setInt32(4,n,!0),e.getBigInt64(0,!0)},uDec(t,n){return e.setInt32(0,t,!0),e.setInt32(4,n,!0),e.getBigUint64(0,!0)}}}let t=e=>gp(/^-?[0-9]+$/.test(e),`int64 invalid: ${e}`),n=e=>gp(/^[0-9]+$/.test(e),`uint64 invalid: ${e}`);return{zero:`0`,supported:!1,parse(e){return typeof e!=`string`&&(e=e.toString()),t(e),e},uParse(e){return typeof e!=`string`&&(e=e.toString()),n(e),e},enc(e){return typeof e!=`string`&&(e=e.toString()),t(e),Ip(e)},uEnc(e){return typeof e!=`string`&&(e=e.toString()),n(e),Ip(e)},dec(e,t){return Lp(e,t)},uDec(e,t){return Rp(e,t)}}}var Kp=Gp(),N;(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`})(N||={});var qp;(function(e){e[e.BIGINT=0]=`BIGINT`,e[e.STRING=1]=`STRING`})(qp||={});function Jp(e,t,n){if(t===n)return!0;if(e==N.BYTES){if(!(t instanceof Uint8Array)||!(n instanceof Uint8Array)||t.length!==n.length)return!1;for(let e=0;e<t.length;e++)if(t[e]!==n[e])return!1;return!0}switch(e){case N.UINT64:case N.FIXED64:case N.INT64:case N.SFIXED64:case N.SINT64:return t==n}return!1}function Yp(e,t){switch(e){case N.BOOL:return!1;case N.UINT64:case N.FIXED64:case N.INT64:case N.SFIXED64:case N.SINT64:return t==0?Kp.zero:`0`;case N.DOUBLE:case N.FLOAT:return 0;case N.BYTES:return new Uint8Array;case N.STRING:return``;default:return 0}}function Xp(e,t){switch(e){case N.BOOL:return t===!1;case N.STRING:return t===``;case N.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return t==0}}var Zp;(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`})(Zp||={});var Qp=class{constructor(e){this.stack=[],this.textEncoder=e??new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let t=0;t<this.chunks.length;t++)e+=this.chunks[t].length;let t=new Uint8Array(e),n=0;for(let e=0;e<this.chunks.length;e++)t.set(this.chunks[e],n),n+=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(Cp(e);e>127;)this.buf.push(e&127|128),e>>>=7;return this.buf.push(e),this}int32(e){return Sp(e),Up(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){wp(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){Cp(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){Sp(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return Sp(e),e=(e<<1^e>>31)>>>0,Up(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),r=Kp.enc(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),r=Kp.uEnc(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(t)}int64(e){let t=Kp.enc(e);return Pp(t.lo,t.hi,this.buf),this}sint64(e){let t=Kp.enc(e),n=t.hi>>31;return Pp(t.lo<<1^n,(t.hi<<1|t.lo>>>31)^n,this.buf),this}uint64(e){let t=Kp.uEnc(e);return Pp(t.lo,t.hi,this.buf),this}},$p=class{constructor(e,t){this.varint64=Np,this.uint32=Wp,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=t??new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,n=e&7;if(t<=0||n<0||n>5)throw Error(`illegal tag: field no `+t+` wire type `+n);return[t,n]}skip(e,t){let n=this.pos;switch(e){case Zp.Varint:for(;this.buf[this.pos++]&128;);break;case Zp.Bit64:this.pos+=4;case Zp.Bit32:this.pos+=4;break;case Zp.LengthDelimited:let n=this.uint32();this.pos+=n;break;case Zp.StartGroup:for(;;){let[e,n]=this.tag();if(n===Zp.EndGroup){if(t!==void 0&&e!==t)throw Error(`invalid end group tag`);break}this.skip(n,e)}break;default:throw Error(`cant skip wire type `+e)}return this.assertBounds(),this.buf.subarray(n,this.pos)}assertBounds(){if(this.pos>this.len)throw RangeError(`premature EOF`)}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return Kp.dec(...this.varint64())}uint64(){return Kp.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),n=-(e&1);return e=(e>>>1|(t&1)<<31)^n,t=t>>>1^n,Kp.dec(e,t)}bool(){let[e,t]=this.varint64();return e!==0||t!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return Kp.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return Kp.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 em(e,t,n,r){let i;return{typeName:t,extendee:n,get field(){if(!i){let n=typeof r==`function`?r():r;n.name=t.split(`.`).pop(),n.jsonName=`[${t}]`,i=e.util.newFieldList([n]).list()[0]}return i},runtime:e}}function tm(e){let t=e.field.localName,n=Object.create(null);return n[t]=nm(e),[n,()=>n[t]]}function nm(e){let t=e.field;if(t.repeated)return[];if(t.default!==void 0)return t.default;switch(t.kind){case`enum`:return t.T.values[0].no;case`scalar`:return Yp(t.T,t.L);case`message`:let e=t.T,n=new e;return e.fieldWrapper?e.fieldWrapper.unwrapField(n):n;case`map`:throw`map fields are not allowed to be extensions`}}function rm(e,t){if(!t.repeated&&(t.kind==`enum`||t.kind==`scalar`)){for(let n=e.length-1;n>=0;--n)if(e[n].no==t.no)return[e[n]];return[]}return e.filter(e=>e.no===t.no)}var im=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`.split(``),am=[];for(let e=0;e<im.length;e++)am[im[e].charCodeAt(0)]=e;am[45]=im.indexOf(`+`),am[95]=im.indexOf(`/`);var om={dec(e){let t=e.length*3/4;e[e.length-2]==`=`?t-=2:e[e.length-1]==`=`&&--t;let n=new Uint8Array(t),r=0,i=0,a,o=0;for(let t=0;t<e.length;t++){if(a=am[e.charCodeAt(t)],a===void 0)switch(e[t]){case`=`:i=0;case`
26
+ `:case`\r`:case` `:case` `:continue;default:throw Error(`invalid base64 string.`)}switch(i){case 0:o=a,i=1;break;case 1:n[r++]=o<<2|(a&48)>>4,o=a,i=2;break;case 2:n[r++]=(o&15)<<4|(a&60)>>2,o=a,i=3;break;case 3:n[r++]=(o&3)<<6|a,i=0;break}}if(i==1)throw Error(`invalid base64 string.`);return n.subarray(0,r)},enc(e){let t=``,n=0,r,i=0;for(let a=0;a<e.length;a++)switch(r=e[a],n){case 0:t+=im[r>>2],i=(r&3)<<4,n=1;break;case 1:t+=im[i|r>>4],i=(r&15)<<2,n=2;break;case 2:t+=im[i|r>>6],t+=im[r&63],n=0;break}return n&&(t+=im[i],t+=`=`,n==1&&(t+=`=`)),t}};function sm(e,t,n){um(t,e);let r=t.runtime.bin.makeReadOptions(n),i=rm(e.getType().runtime.bin.listUnknownFields(e),t.field),[a,o]=tm(t);for(let e of i)t.runtime.bin.readField(a,r.readerFactory(e.data),t.field,e.wireType,r);return o()}function cm(e,t,n,r){um(t,e);let i=t.runtime.bin.makeReadOptions(r),a=t.runtime.bin.makeWriteOptions(r);if(lm(e,t)){let n=e.getType().runtime.bin.listUnknownFields(e).filter(e=>e.no!=t.field.no);e.getType().runtime.bin.discardUnknownFields(e);for(let t of n)e.getType().runtime.bin.onUnknownField(e,t.no,t.wireType,t.data)}let o=a.writerFactory(),s=t.field;!s.opt&&!s.repeated&&(s.kind==`enum`||s.kind==`scalar`)&&(s=Object.assign(Object.assign({},t.field),{opt:!0})),t.runtime.bin.writeField(s,n,o,a);let c=i.readerFactory(o.finish());for(;c.pos<c.len;){let[t,n]=c.tag(),r=c.skip(n,t);e.getType().runtime.bin.onUnknownField(e,t,n,r)}}function lm(e,t){let n=e.getType();return t.extendee.typeName===n.typeName&&!!n.runtime.bin.listUnknownFields(e).find(e=>e.no==t.field.no)}function um(e,t){gp(e.extendee.typeName==t.getType().typeName,`extension ${e.typeName} can only be applied to message ${e.extendee.typeName}`)}function dm(e,t){let n=e.localName;if(e.repeated)return t[n].length>0;if(e.oneof)return t[e.oneof.localName].case===n;switch(e.kind){case`enum`:case`scalar`:return e.opt||e.req?t[n]!==void 0:e.kind==`enum`?t[n]!==e.T.values[0].no:!Xp(e.T,t[n]);case`message`:return t[n]!==void 0;case`map`:return Object.keys(t[n]).length>0}}function fm(e,t){let n=e.localName,r=!e.opt&&!e.req;if(e.repeated)t[n]=[];else if(e.oneof)t[e.oneof.localName]={case:void 0};else switch(e.kind){case`map`:t[n]={};break;case`enum`:t[n]=r?e.T.values[0].no:void 0;break;case`scalar`:t[n]=r?Yp(e.T,e.L):void 0;break;case`message`:t[n]=void 0;break}}function pm(e,t){if(typeof e!=`object`||!e||!Object.getOwnPropertyNames(jp.prototype).every(t=>t in e&&typeof e[t]==`function`))return!1;let n=e.getType();return n===null||typeof n!=`function`||!(`typeName`in n)||typeof n.typeName!=`string`?!1:t===void 0?!0:n.typeName==t.typeName}function mm(e,t){return pm(t)||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}N.DOUBLE,N.FLOAT,N.INT64,N.UINT64,N.INT32,N.UINT32,N.BOOL,N.STRING,N.BYTES;var hm={ignoreUnknownFields:!1},gm={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function _m(e){return e?Object.assign(Object.assign({},hm),e):hm}function vm(e){return e?Object.assign(Object.assign({},gm),e):gm}var ym=Symbol(),bm=Symbol();function xm(){return{makeReadOptions:_m,makeWriteOptions:vm,readMessage(e,t,n,r){if(t==null||Array.isArray(t)||typeof t!=`object`)throw Error(`cannot decode message ${e.typeName} from JSON: ${Sm(t)}`);r??=new e;let i=new Map,a=n.typeRegistry;for(let[o,s]of Object.entries(t)){let t=e.fields.findJsonName(o);if(t){if(t.oneof){if(s===null&&t.kind==`scalar`)continue;let n=i.get(t.oneof);if(n!==void 0)throw Error(`cannot decode message ${e.typeName} from JSON: multiple keys for oneof "${t.oneof.name}" present: "${n}", "${o}"`);i.set(t.oneof,o)}Cm(r,s,t,n,e)}else{let t=!1;if(a?.findExtension&&o.startsWith(`[`)&&o.endsWith(`]`)){let i=a.findExtension(o.substring(1,o.length-1));if(i&&i.extendee.typeName==e.typeName){t=!0;let[e,a]=tm(i);Cm(e,s,i.field,n,i),cm(r,i,a(),n)}}if(!t&&!n.ignoreUnknownFields)throw Error(`cannot decode message ${e.typeName} from JSON: key "${o}" is unknown`)}}return r},writeMessage(e,t){let n=e.getType(),r={},i;try{for(i of n.fields.byNumber()){if(!dm(i,e)){if(i.req)throw`required field not set`;if(!t.emitDefaultValues||!Dm(i))continue}let n=i.oneof?e[i.oneof.localName].value:e[i.localName],a=Om(i,n,t);a!==void 0&&(r[t.useProtoFieldName?i.name:i.jsonName]=a)}let a=t.typeRegistry;if(a?.findExtensionFor)for(let i of n.runtime.bin.listUnknownFields(e)){let o=a.findExtensionFor(n.typeName,i.no);if(o&&lm(e,o)){let n=sm(e,o,t),i=Om(o.field,n,t);i!==void 0&&(r[o.field.jsonName]=i)}}}catch(e){let t=i?`cannot encode field ${n.typeName}.${i.name} to JSON`:`cannot encode message ${n.typeName} to JSON`,r=e instanceof Error?e.message:String(e);throw Error(t+(r.length>0?`: ${r}`:``))}return r},readScalar(e,t,n){return Tm(e,t,n??qp.BIGINT,!0)},writeScalar(e,t,n){if(t!==void 0&&(n||Xp(e,t)))return Am(e,t)},debug:Sm}}function Sm(e){if(e===null)return`null`;switch(typeof e){case`object`:return Array.isArray(e)?`array`:`object`;case`string`:return e.length>100?`string`:`"${e.split(`"`).join(`\\"`)}"`;default:return String(e)}}function Cm(e,t,n,r,i){let a=n.localName;if(n.repeated){if(gp(n.kind!=`map`),t===null)return;if(!Array.isArray(t))throw Error(`cannot decode field ${i.typeName}.${n.name} from JSON: ${Sm(t)}`);let o=e[a];for(let e of t){if(e===null)throw Error(`cannot decode field ${i.typeName}.${n.name} from JSON: ${Sm(e)}`);switch(n.kind){case`message`:o.push(n.T.fromJson(e,r));break;case`enum`:let t=Em(n.T,e,r.ignoreUnknownFields,!0);t!==bm&&o.push(t);break;case`scalar`:try{o.push(Tm(n.T,e,n.L,!0))}catch(t){let r=`cannot decode field ${i.typeName}.${n.name} from JSON: ${Sm(e)}`;throw t instanceof Error&&t.message.length>0&&(r+=`: ${t.message}`),Error(r)}break}}}else if(n.kind==`map`){if(t===null)return;if(typeof t!=`object`||Array.isArray(t))throw Error(`cannot decode field ${i.typeName}.${n.name} from JSON: ${Sm(t)}`);let o=e[a];for(let[e,a]of Object.entries(t)){if(a===null)throw Error(`cannot decode field ${i.typeName}.${n.name} from JSON: map value null`);let s;try{s=wm(n.K,e)}catch(e){let r=`cannot decode map key for field ${i.typeName}.${n.name} from JSON: ${Sm(t)}`;throw e instanceof Error&&e.message.length>0&&(r+=`: ${e.message}`),Error(r)}switch(n.V.kind){case`message`:o[s]=n.V.T.fromJson(a,r);break;case`enum`:let e=Em(n.V.T,a,r.ignoreUnknownFields,!0);e!==bm&&(o[s]=e);break;case`scalar`:try{o[s]=Tm(n.V.T,a,qp.BIGINT,!0)}catch(e){let r=`cannot decode map value for field ${i.typeName}.${n.name} from JSON: ${Sm(t)}`;throw e instanceof Error&&e.message.length>0&&(r+=`: ${e.message}`),Error(r)}break}}}else switch(n.oneof&&(e=e[n.oneof.localName]={case:a},a=`value`),n.kind){case`message`:let o=n.T;if(t===null&&o.typeName!=`google.protobuf.Value`)return;let s=e[a];pm(s)?s.fromJson(t,r):(e[a]=s=o.fromJson(t,r),o.fieldWrapper&&!n.oneof&&(e[a]=o.fieldWrapper.unwrapField(s)));break;case`enum`:let c=Em(n.T,t,r.ignoreUnknownFields,!1);switch(c){case ym:fm(n,e);break;case bm:break;default:e[a]=c;break}break;case`scalar`:try{let r=Tm(n.T,t,n.L,!1);switch(r){case ym:fm(n,e);break;default:e[a]=r;break}}catch(e){let r=`cannot decode field ${i.typeName}.${n.name} from JSON: ${Sm(t)}`;throw e instanceof Error&&e.message.length>0&&(r+=`: ${e.message}`),Error(r)}break}}function wm(e,t){if(e===N.BOOL)switch(t){case`true`:t=!0;break;case`false`:t=!1;break}return Tm(e,t,qp.BIGINT,!0).toString()}function Tm(e,t,n,r){if(t===null)return r?Yp(e,n):ym;switch(e){case N.DOUBLE:case N.FLOAT:if(t===`NaN`)return NaN;if(t===`Infinity`)return 1/0;if(t===`-Infinity`)return-1/0;if(t===``||typeof t==`string`&&t.trim().length!==t.length||typeof t!=`string`&&typeof t!=`number`)break;let r=Number(t);if(Number.isNaN(r)||!Number.isFinite(r))break;return e==N.FLOAT&&wp(r),r;case N.INT32:case N.FIXED32:case N.SFIXED32:case N.SINT32:case N.UINT32:let i;if(typeof t==`number`?i=t:typeof t==`string`&&t.length>0&&t.trim().length===t.length&&(i=Number(t)),i===void 0)break;return e==N.UINT32||e==N.FIXED32?Cp(i):Sp(i),i;case N.INT64:case N.SFIXED64:case N.SINT64:if(typeof t!=`number`&&typeof t!=`string`)break;let a=Kp.parse(t);return n?a.toString():a;case N.FIXED64:case N.UINT64:if(typeof t!=`number`&&typeof t!=`string`)break;let o=Kp.uParse(t);return n?o.toString():o;case N.BOOL:if(typeof t!=`boolean`)break;return t;case N.STRING:if(typeof t!=`string`)break;return t;case N.BYTES:if(t===``)return new Uint8Array;if(typeof t!=`string`)break;return om.dec(t)}throw Error()}function Em(e,t,n,r){if(t===null)return e.typeName==`google.protobuf.NullValue`?0:r?e.values[0].no:ym;switch(typeof t){case`number`:if(Number.isInteger(t))return t;break;case`string`:let r=e.findName(t);if(r!==void 0)return r.no;if(n)return bm;break}throw Error(`cannot decode enum ${e.typeName} from JSON: ${Sm(t)}`)}function Dm(e){return e.repeated||e.kind==`map`?!0:!(e.oneof||e.kind==`message`||e.opt||e.req)}function Om(e,t,n){if(e.kind==`map`){gp(typeof t==`object`&&!!t);let r={},i=Object.entries(t);switch(e.V.kind){case`scalar`:for(let[t,n]of i)r[t.toString()]=Am(e.V.T,n);break;case`message`:for(let[e,t]of i)r[e.toString()]=t.toJson(n);break;case`enum`:let t=e.V.T;for(let[e,a]of i)r[e.toString()]=km(t,a,n.enumAsInteger);break}return n.emitDefaultValues||i.length>0?r:void 0}if(e.repeated){gp(Array.isArray(t));let r=[];switch(e.kind){case`scalar`:for(let n=0;n<t.length;n++)r.push(Am(e.T,t[n]));break;case`enum`:for(let i=0;i<t.length;i++)r.push(km(e.T,t[i],n.enumAsInteger));break;case`message`:for(let e=0;e<t.length;e++)r.push(t[e].toJson(n));break}return n.emitDefaultValues||r.length>0?r:void 0}switch(e.kind){case`scalar`:return Am(e.T,t);case`enum`:return km(e.T,t,n.enumAsInteger);case`message`:return mm(e.T,t).toJson(n)}}function km(e,t,n){return gp(typeof t==`number`),e.typeName==`google.protobuf.NullValue`?null:n?t:e.findNumber(t)?.name??t}function Am(e,t){switch(e){case N.INT32:case N.SFIXED32:case N.SINT32:case N.FIXED32:case N.UINT32:return gp(typeof t==`number`),t;case N.FLOAT:case N.DOUBLE:return gp(typeof t==`number`),Number.isNaN(t)?`NaN`:t===1/0?`Infinity`:t===-1/0?`-Infinity`:t;case N.STRING:return gp(typeof t==`string`),t;case N.BOOL:return gp(typeof t==`boolean`),t;case N.UINT64:case N.FIXED64:case N.INT64:case N.SFIXED64:case N.SINT64:return gp(typeof t==`bigint`||typeof t==`string`||typeof t==`number`),t.toString();case N.BYTES:return gp(t instanceof Uint8Array),om.enc(t)}}var jm=Symbol(`@bufbuild/protobuf/unknown-fields`),Mm={readUnknownFields:!0,readerFactory:e=>new $p(e)},Nm={writeUnknownFields:!0,writerFactory:()=>new Qp};function Pm(e){return e?Object.assign(Object.assign({},Mm),e):Mm}function Fm(e){return e?Object.assign(Object.assign({},Nm),e):Nm}function Im(){return{makeReadOptions:Pm,makeWriteOptions:Fm,listUnknownFields(e){return e[jm]??[]},discardUnknownFields(e){delete e[jm]},writeUnknownFields(e,t){let n=e[jm];if(n)for(let e of n)t.tag(e.no,e.wireType).raw(e.data)},onUnknownField(e,t,n,r){let i=e;Array.isArray(i[jm])||(i[jm]=[]),i[jm].push({no:t,wireType:n,data:r})},readMessage(e,t,n,r,i){let a=e.getType(),o=i?t.len:t.pos+n,s,c;for(;t.pos<o&&([s,c]=t.tag(),!(i===!0&&c==Zp.EndGroup));){let n=a.fields.find(s);if(!n){let n=t.skip(c,s);r.readUnknownFields&&this.onUnknownField(e,s,c,n);continue}Lm(e,t,n,c,r)}if(i&&(c!=Zp.EndGroup||s!==n))throw Error(`invalid end group tag`)},readField:Lm,writeMessage(e,t,n){let r=e.getType();for(let i of r.fields.byNumber()){if(!dm(i,e)){if(i.req)throw Error(`cannot encode field ${r.typeName}.${i.name} to binary: required field not set`);continue}Hm(i,i.oneof?e[i.oneof.localName].value:e[i.localName],t,n)}return n.writeUnknownFields&&this.writeUnknownFields(e,t),t},writeField(e,t,n,r){t!==void 0&&Hm(e,t,n,r)}}}function Lm(e,t,n,r,i){let{repeated:a,localName:o}=n;switch(n.oneof&&(e=e[n.oneof.localName],e.case!=o&&delete e.value,e.case=o,o=`value`),n.kind){case`scalar`:case`enum`:let s=n.kind==`enum`?N.INT32:n.T,c=Vm;if(n.kind==`scalar`&&n.L>0&&(c=Bm),a){let n=e[o];if(r==Zp.LengthDelimited&&s!=N.STRING&&s!=N.BYTES){let e=t.uint32()+t.pos;for(;t.pos<e;)n.push(c(t,s))}else n.push(c(t,s))}else e[o]=c(t,s);break;case`message`:let l=n.T;a?e[o].push(Rm(t,new l,i,n)):pm(e[o])?Rm(t,e[o],i,n):(e[o]=Rm(t,new l,i,n),l.fieldWrapper&&!n.oneof&&!n.repeated&&(e[o]=l.fieldWrapper.unwrapField(e[o])));break;case`map`:let[u,d]=zm(n,t,i);e[o][u]=d;break}}function Rm(e,t,n,r){let i=t.getType().runtime.bin,a=r?.delimited;return i.readMessage(t,e,a?r.no:e.uint32(),n,a),t}function zm(e,t,n){let r=t.uint32(),i=t.pos+r,a,o;for(;t.pos<i;){let[r]=t.tag();switch(r){case 1:a=Vm(t,e.K);break;case 2:switch(e.V.kind){case`scalar`:o=Vm(t,e.V.T);break;case`enum`:o=t.int32();break;case`message`:o=Rm(t,new e.V.T,n,void 0);break}break}}if(a===void 0&&(a=Yp(e.K,qp.BIGINT)),typeof a!=`string`&&typeof a!=`number`&&(a=a.toString()),o===void 0)switch(e.V.kind){case`scalar`:o=Yp(e.V.T,qp.BIGINT);break;case`enum`:o=e.V.T.values[0].no;break;case`message`:o=new e.V.T;break}return[a,o]}function Bm(e,t){let n=Vm(e,t);return typeof n==`bigint`?n.toString():n}function Vm(e,t){switch(t){case N.STRING:return e.string();case N.BOOL:return e.bool();case N.DOUBLE:return e.double();case N.FLOAT:return e.float();case N.INT32:return e.int32();case N.INT64:return e.int64();case N.UINT64:return e.uint64();case N.FIXED64:return e.fixed64();case N.BYTES:return e.bytes();case N.FIXED32:return e.fixed32();case N.SFIXED32:return e.sfixed32();case N.SFIXED64:return e.sfixed64();case N.SINT64:return e.sint64();case N.UINT32:return e.uint32();case N.SINT32:return e.sint32()}}function Hm(e,t,n,r){gp(t!==void 0);let i=e.repeated;switch(e.kind){case`scalar`:case`enum`:let a=e.kind==`enum`?N.INT32:e.T;if(i)if(gp(Array.isArray(t)),e.packed)Km(n,a,e.no,t);else for(let r of t)Gm(n,a,e.no,r);else Gm(n,a,e.no,t);break;case`message`:if(i){gp(Array.isArray(t));for(let i of t)Wm(n,r,e,i)}else Wm(n,r,e,t);break;case`map`:gp(typeof t==`object`&&!!t);for(let[i,a]of Object.entries(t))Um(n,r,e,i,a);break}}function Um(e,t,n,r,i){e.tag(n.no,Zp.LengthDelimited),e.fork();let a=r;switch(n.K){case N.INT32:case N.FIXED32:case N.UINT32:case N.SFIXED32:case N.SINT32:a=Number.parseInt(r);break;case N.BOOL:gp(r==`true`||r==`false`),a=r==`true`;break}switch(Gm(e,n.K,1,a),n.V.kind){case`scalar`:Gm(e,n.V.T,2,i);break;case`enum`:Gm(e,N.INT32,2,i);break;case`message`:gp(i!==void 0),e.tag(2,Zp.LengthDelimited).bytes(i.toBinary(t));break}e.join()}function Wm(e,t,n,r){let i=mm(n.T,r);n.delimited?e.tag(n.no,Zp.StartGroup).raw(i.toBinary(t)).tag(n.no,Zp.EndGroup):e.tag(n.no,Zp.LengthDelimited).bytes(i.toBinary(t))}function Gm(e,t,n,r){gp(r!==void 0);let[i,a]=qm(t);e.tag(n,i)[a](r)}function Km(e,t,n,r){if(!r.length)return;e.tag(n,Zp.LengthDelimited).fork();let[,i]=qm(t);for(let t=0;t<r.length;t++)e[i](r[t]);e.join()}function qm(e){let t=Zp.Varint;switch(e){case N.BYTES:case N.STRING:t=Zp.LengthDelimited;break;case N.DOUBLE:case N.FIXED64:case N.SFIXED64:t=Zp.Bit64;break;case N.FIXED32:case N.SFIXED32:case N.FLOAT:t=Zp.Bit32;break}let n=N[e].toLowerCase();return[t,n]}function Jm(){return{setEnumType:Dp,initPartial(e,t){if(e===void 0)return;let n=t.getType();for(let r of n.fields.byMember()){let n=r.localName,i=t,a=e;if(a[n]!=null)switch(r.kind){case`oneof`:let e=a[n].case;if(e===void 0)continue;let t=r.findField(e),o=a[n].value;t&&t.kind==`message`&&!pm(o,t.T)?o=new t.T(o):t&&t.kind===`scalar`&&t.T===N.BYTES&&(o=Xm(o)),i[n]={case:e,value:o};break;case`scalar`:case`enum`:let s=a[n];r.T===N.BYTES&&(s=r.repeated?s.map(Xm):Xm(s)),i[n]=s;break;case`map`:switch(r.V.kind){case`scalar`:case`enum`:if(r.V.T===N.BYTES)for(let[e,t]of Object.entries(a[n]))i[n][e]=Xm(t);else Object.assign(i[n],a[n]);break;case`message`:let e=r.V.T;for(let t of Object.keys(a[n])){let r=a[n][t];e.fieldWrapper||(r=new e(r)),i[n][t]=r}break}break;case`message`:let c=r.T;if(r.repeated)i[n]=a[n].map(e=>pm(e,c)?e:new c(e));else{let e=a[n];c.fieldWrapper?c.typeName===`google.protobuf.BytesValue`?i[n]=Xm(e):i[n]=e:i[n]=pm(e,c)?e:new c(e)}break}}},equals(e,t,n){return t===n?!0:!t||!n?!1:e.fields.byMember().every(e=>{let r=t[e.localName],i=n[e.localName];if(e.repeated){if(r.length!==i.length)return!1;switch(e.kind){case`message`:return r.every((t,n)=>e.T.equals(t,i[n]));case`scalar`:return r.every((t,n)=>Jp(e.T,t,i[n]));case`enum`:return r.every((e,t)=>Jp(N.INT32,e,i[t]))}throw Error(`repeated cannot contain ${e.kind}`)}switch(e.kind){case`message`:let t=r,n=i;return e.T.fieldWrapper&&(t!==void 0&&!pm(t)&&(t=e.T.fieldWrapper.wrapField(t)),n!==void 0&&!pm(n)&&(n=e.T.fieldWrapper.wrapField(n))),e.T.equals(t,n);case`enum`:return Jp(N.INT32,r,i);case`scalar`:return Jp(e.T,r,i);case`oneof`:if(r.case!==i.case)return!1;let a=e.findField(r.case);if(a===void 0)return!0;switch(a.kind){case`message`:return a.T.equals(r.value,i.value);case`enum`:return Jp(N.INT32,r.value,i.value);case`scalar`:return Jp(a.T,r.value,i.value)}throw Error(`oneof cannot contain ${a.kind}`);case`map`:let o=Object.keys(r).concat(Object.keys(i));switch(e.V.kind){case`message`:let t=e.V.T;return o.every(e=>t.equals(r[e],i[e]));case`enum`:return o.every(e=>Jp(N.INT32,r[e],i[e]));case`scalar`:let n=e.V.T;return o.every(e=>Jp(n,r[e],i[e]))}break}})},clone(e){let t=e.getType(),n=new t,r=n;for(let n of t.fields.byMember()){let t=e[n.localName],i;if(n.repeated)i=t.map(Ym);else if(n.kind==`map`){i=r[n.localName];for(let[e,n]of Object.entries(t))i[e]=Ym(n)}else i=n.kind==`oneof`?n.findField(t.case)?{case:t.case,value:Ym(t.value)}:{case:void 0}:Ym(t);r[n.localName]=i}for(let n of t.runtime.bin.listUnknownFields(e))t.runtime.bin.onUnknownField(r,n.no,n.wireType,n.data);return n}}}function Ym(e){if(e===void 0)return e;if(pm(e))return e.clone();if(e instanceof Uint8Array){let t=new Uint8Array(e.byteLength);return t.set(e),t}return e}function Xm(e){return e instanceof Uint8Array?e:new Uint8Array(e)}function Zm(e,t,n){return{syntax:e,json:xm(),bin:Im(),util:Object.assign(Object.assign({},Jm()),{newFieldList:t,initFields:n}),makeMessageType(e,t,n){return Mp(this,e,t,n)},makeEnum:kp,makeEnumType:Op,getEnumType:Ep,makeExtension(e,t,n){return em(this,e,t,n)}}}var Qm=class{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._normalizer(this._fields),this.all}byNumber(){return this.numbersAsc||=this.list().concat().sort((e,t)=>e.no-t.no),this.numbersAsc}byMember(){if(!this.members){this.members=[];let e=this.members,t;for(let n of this.list())n.oneof?n.oneof!==t&&(t=n.oneof,e.push(t)):e.push(n)}return this.members}};function $m(e,t){let n=nh(e);return t?n:sh(oh(n))}function eh(e){return $m(e,!1)}var th=nh;function nh(e){let t=!1,n=[];for(let r=0;r<e.length;r++){let i=e.charAt(r);switch(i){case`_`:t=!0;break;case`0`:case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:n.push(i),t=!1;break;default:t&&(t=!1,i=i.toUpperCase()),n.push(i);break}}return n.join(``)}var rh=new Set([`constructor`,`toString`,`toJSON`,`valueOf`]),ih=new Set([`getType`,`clone`,`equals`,`fromBinary`,`fromJson`,`fromJsonString`,`toBinary`,`toJson`,`toJsonString`,`toObject`]),ah=e=>`${e}\$`,oh=e=>ih.has(e)?ah(e):e,sh=e=>rh.has(e)?ah(e):e,ch=class{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=eh(e)}addField(e){gp(e.oneof===this,`field ${e.name} not one of ${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]}};function lh(e,t){let n=[],r;for(let t of typeof e==`function`?e():e){let e=t;if(e.localName=$m(t.name,t.oneof!==void 0),e.jsonName=t.jsonName??th(t.name),e.repeated=t.repeated??!1,t.kind==`scalar`&&(e.L=t.L??qp.BIGINT),e.delimited=t.delimited??!1,e.req=t.req??!1,e.opt=t.opt??!1,t.packed===void 0&&(e.packed=t.kind==`enum`||t.kind==`scalar`&&t.T!=N.BYTES&&t.T!=N.STRING),t.oneof!==void 0){let n=typeof t.oneof==`string`?t.oneof:t.oneof.name;(!r||r.name!=n)&&(r=new ch(n)),e.oneof=r,r.addField(e)}n.push(e)}return n}var P=Zm(`proto3`,e=>new Qm(e,e=>lh(e)),e=>{for(let t of e.getType().fields.byMember()){if(t.opt)continue;let n=t.localName,r=e;if(t.repeated){r[n]=[];continue}switch(t.kind){case`oneof`:r[n]={case:void 0};break;case`enum`:r[n]=0;break;case`map`:r[n]={};break;case`scalar`:r[n]=Yp(t.T,t.L);break}}}),uh=class e extends jp{constructor(e){super(),this.seconds=Kp.zero,this.nanos=0,P.util.initPartial(e,this)}fromJson(e,t){if(typeof e!=`string`)throw Error(`cannot decode google.protobuf.Timestamp from JSON: ${P.json.debug(e)}`);let n=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!n)throw Error(`cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string`);let r=Date.parse(n[1]+`-`+n[2]+`-`+n[3]+`T`+n[4]+`:`+n[5]+`:`+n[6]+(n[8]?n[8]:`Z`));if(Number.isNaN(r))throw Error(`cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string`);if(r<Date.parse(`0001-01-01T00:00:00Z`)||r>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=Kp.parse(r/1e3),this.nanos=0,n[7]&&(this.nanos=parseInt(`1`+n[7]+`0`.repeat(9-n[7].length))-1e9),this}toJson(e){let t=Number(this.seconds)*1e3;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 n=`Z`;if(this.nanos>0){let e=(this.nanos+1e9).toString().substring(1);n=e.substring(3)===`000000`?`.`+e.substring(0,3)+`Z`:e.substring(6)===`000`?`.`+e.substring(0,6)+`Z`:`.`+e+`Z`}return new Date(t).toISOString().replace(`.000Z`,n)}toDate(){return new Date(Number(this.seconds)*1e3+Math.ceil(this.nanos/1e6))}static now(){return e.fromDate(new Date)}static fromDate(t){let n=t.getTime();return new e({seconds:Kp.parse(Math.floor(n/1e3)),nanos:n%1e3*1e6})}static fromBinary(t,n){return new e().fromBinary(t,n)}static fromJson(t,n){return new e().fromJson(t,n)}static fromJsonString(t,n){return new e().fromJsonString(t,n)}static equals(t,n){return P.util.equals(e,t,n)}};uh.runtime=P,uh.typeName=`google.protobuf.Timestamp`,uh.fields=P.util.newFieldList(()=>[{no:1,name:`seconds`,kind:`scalar`,T:3},{no:2,name:`nanos`,kind:`scalar`,T:5}]);var dh=P.makeMessageType(`livekit.MetricsBatch`,()=>[{no:1,name:`timestamp_ms`,kind:`scalar`,T:3},{no:2,name:`normalized_timestamp`,kind:`message`,T:uh},{no:3,name:`str_data`,kind:`scalar`,T:9,repeated:!0},{no:4,name:`time_series`,kind:`message`,T:fh,repeated:!0},{no:5,name:`events`,kind:`message`,T:mh,repeated:!0}]),fh=P.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:ph,repeated:!0},{no:5,name:`rid`,kind:`scalar`,T:13}]),ph=P.makeMessageType(`livekit.MetricSample`,()=>[{no:1,name:`timestamp_ms`,kind:`scalar`,T:3},{no:2,name:`normalized_timestamp`,kind:`message`,T:uh},{no:3,name:`value`,kind:`scalar`,T:2}]),mh=P.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:uh},{no:7,name:`normalized_end_timestamp`,kind:`message`,T:uh,opt:!0},{no:8,name:`metadata`,kind:`scalar`,T:9},{no:9,name:`rid`,kind:`scalar`,T:13}]),hh=P.makeEnum(`livekit.BackupCodecPolicy`,[{no:0,name:`PREFER_REGRESSION`},{no:1,name:`SIMULCAST`},{no:2,name:`REGRESSION`}]),gh=P.makeEnum(`livekit.TrackType`,[{no:0,name:`AUDIO`},{no:1,name:`VIDEO`},{no:2,name:`DATA`}]),_h=P.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`}]),vh=P.makeEnum(`livekit.VideoQuality`,[{no:0,name:`LOW`},{no:1,name:`MEDIUM`},{no:2,name:`HIGH`},{no:3,name:`OFF`}]),yh=P.makeEnum(`livekit.ConnectionQuality`,[{no:0,name:`POOR`},{no:1,name:`GOOD`},{no:2,name:`EXCELLENT`},{no:3,name:`LOST`}]),bh=P.makeEnum(`livekit.ClientConfigSetting`,[{no:0,name:`UNSET`},{no:1,name:`DISABLED`},{no:2,name:`ENABLED`}]),xh=P.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`}]),Sh=P.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`}]),Ch=P.makeEnum(`livekit.SubscriptionError`,[{no:0,name:`SE_UNKNOWN`},{no:1,name:`SE_CODEC_UNSUPPORTED`},{no:2,name:`SE_TRACK_NOTFOUND`}]),wh=P.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`}]),Th=P.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:Eh,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:sg}]),Eh=P.makeMessageType(`livekit.Codec`,()=>[{no:1,name:`mime`,kind:`scalar`,T:9},{no:2,name:`fmtp_line`,kind:`scalar`,T:9}]),Dh=P.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:P.getEnumType(_h),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}]),Oh=P.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:P.getEnumType(kh)},{no:4,name:`tracks`,kind:`message`,T:Nh,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:Dh},{no:12,name:`region`,kind:`scalar`,T:9},{no:13,name:`is_publisher`,kind:`scalar`,T:8},{no:14,name:`kind`,kind:`enum`,T:P.getEnumType(Ah)},{no:15,name:`attributes`,kind:`map`,K:9,V:{kind:`scalar`,T:9}},{no:16,name:`disconnect_reason`,kind:`enum`,T:P.getEnumType(xh)},{no:18,name:`kind_details`,kind:`enum`,T:P.getEnumType(jh),repeated:!0},{no:19,name:`data_tracks`,kind:`message`,T:Ph,repeated:!0}]),kh=P.makeEnum(`livekit.ParticipantInfo.State`,[{no:0,name:`JOINING`},{no:1,name:`JOINED`},{no:2,name:`ACTIVE`},{no:3,name:`DISCONNECTED`}]),Ah=P.makeEnum(`livekit.ParticipantInfo.Kind`,[{no:0,name:`STANDARD`},{no:1,name:`INGRESS`},{no:2,name:`EGRESS`},{no:3,name:`SIP`},{no:4,name:`AGENT`},{no:7,name:`CONNECTOR`},{no:8,name:`BRIDGE`}]),jh=P.makeEnum(`livekit.ParticipantInfo.KindDetail`,[{no:0,name:`CLOUD_AGENT`},{no:1,name:`FORWARDED`},{no:2,name:`CONNECTOR_WHATSAPP`},{no:3,name:`CONNECTOR_TWILIO`},{no:4,name:`BRIDGE_RTSP`}]),F=P.makeEnum(`livekit.Encryption.Type`,[{no:0,name:`NONE`},{no:1,name:`GCM`},{no:2,name:`CUSTOM`}]),Mh=P.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:Ih,repeated:!0},{no:5,name:`video_layer_mode`,kind:`enum`,T:P.getEnumType(Lh)},{no:6,name:`sdp_cid`,kind:`scalar`,T:9}]),Nh=P.makeMessageType(`livekit.TrackInfo`,()=>[{no:1,name:`sid`,kind:`scalar`,T:9},{no:2,name:`type`,kind:`enum`,T:P.getEnumType(gh)},{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:P.getEnumType(_h)},{no:10,name:`layers`,kind:`message`,T:Ih,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:Mh,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:P.getEnumType(F)},{no:17,name:`stream`,kind:`scalar`,T:9},{no:18,name:`version`,kind:`message`,T:sg},{no:19,name:`audio_features`,kind:`enum`,T:P.getEnumType(wh),repeated:!0},{no:20,name:`backup_codec_policy`,kind:`enum`,T:P.getEnumType(hh)}]),Ph=P.makeMessageType(`livekit.DataTrackInfo`,()=>[{no:1,name:`pub_handle`,kind:`scalar`,T:13},{no:2,name:`sid`,kind:`scalar`,T:9},{no:3,name:`name`,kind:`scalar`,T:9},{no:4,name:`encryption`,kind:`enum`,T:P.getEnumType(F)}]),Fh=P.makeMessageType(`livekit.DataTrackSubscriptionOptions`,()=>[{no:1,name:`target_fps`,kind:`scalar`,T:13,opt:!0}]),Ih=P.makeMessageType(`livekit.VideoLayer`,()=>[{no:1,name:`quality`,kind:`enum`,T:P.getEnumType(vh)},{no:2,name:`width`,kind:`scalar`,T:13},{no:3,name:`height`,kind:`scalar`,T:13},{no:4,name:`bitrate`,kind:`scalar`,T:13},{no:5,name:`ssrc`,kind:`scalar`,T:13},{no:6,name:`spatial_layer`,kind:`scalar`,T:5},{no:7,name:`rid`,kind:`scalar`,T:9},{no:8,name:`repair_ssrc`,kind:`scalar`,T:13}]),Lh=P.makeEnum(`livekit.VideoLayer.Mode`,[{no:0,name:`MODE_UNUSED`},{no:1,name:`ONE_SPATIAL_LAYER_PER_STREAM`},{no:2,name:`MULTIPLE_SPATIAL_LAYERS_PER_STREAM`},{no:3,name:`ONE_SPATIAL_LAYER_PER_STREAM_INCOMPLETE_RTCP_SR`}]),Rh=P.makeMessageType(`livekit.DataPacket`,()=>[{no:1,name:`kind`,kind:`enum`,T:P.getEnumType(zh)},{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:Wh,oneof:`value`},{no:3,name:`speaker`,kind:`message`,T:Hh,oneof:`value`},{no:6,name:`sip_dtmf`,kind:`message`,T:Gh,oneof:`value`},{no:7,name:`transcription`,kind:`message`,T:Kh,oneof:`value`},{no:8,name:`metrics`,kind:`message`,T:dh,oneof:`value`},{no:9,name:`chat_message`,kind:`message`,T:Jh,oneof:`value`},{no:10,name:`rpc_request`,kind:`message`,T:Yh,oneof:`value`},{no:11,name:`rpc_ack`,kind:`message`,T:Xh,oneof:`value`},{no:12,name:`rpc_response`,kind:`message`,T:Zh,oneof:`value`},{no:13,name:`stream_header`,kind:`message`,T:dg,oneof:`value`},{no:14,name:`stream_chunk`,kind:`message`,T:fg,oneof:`value`},{no:15,name:`stream_trailer`,kind:`message`,T:pg,oneof:`value`},{no:18,name:`encrypted_packet`,kind:`message`,T:Bh,oneof:`value`},{no:16,name:`sequence`,kind:`scalar`,T:13},{no:17,name:`participant_sid`,kind:`scalar`,T:9}]),zh=P.makeEnum(`livekit.DataPacket.Kind`,[{no:0,name:`RELIABLE`},{no:1,name:`LOSSY`}]),Bh=P.makeMessageType(`livekit.EncryptedPacket`,()=>[{no:1,name:`encryption_type`,kind:`enum`,T:P.getEnumType(F)},{no:2,name:`iv`,kind:`scalar`,T:12},{no:3,name:`key_index`,kind:`scalar`,T:13},{no:4,name:`encrypted_value`,kind:`scalar`,T:12}]),Vh=P.makeMessageType(`livekit.EncryptedPacketPayload`,()=>[{no:1,name:`user`,kind:`message`,T:Wh,oneof:`value`},{no:3,name:`chat_message`,kind:`message`,T:Jh,oneof:`value`},{no:4,name:`rpc_request`,kind:`message`,T:Yh,oneof:`value`},{no:5,name:`rpc_ack`,kind:`message`,T:Xh,oneof:`value`},{no:6,name:`rpc_response`,kind:`message`,T:Zh,oneof:`value`},{no:7,name:`stream_header`,kind:`message`,T:dg,oneof:`value`},{no:8,name:`stream_chunk`,kind:`message`,T:fg,oneof:`value`},{no:9,name:`stream_trailer`,kind:`message`,T:pg,oneof:`value`}]),Hh=P.makeMessageType(`livekit.ActiveSpeakerUpdate`,()=>[{no:1,name:`speakers`,kind:`message`,T:Uh,repeated:!0}]),Uh=P.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}]),Wh=P.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}]),Gh=P.makeMessageType(`livekit.SipDTMF`,()=>[{no:3,name:`code`,kind:`scalar`,T:13},{no:4,name:`digit`,kind:`scalar`,T:9}]),Kh=P.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:qh,repeated:!0}]),qh=P.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}]),Jh=P.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}]),Yh=P.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}]),Xh=P.makeMessageType(`livekit.RpcAck`,()=>[{no:1,name:`request_id`,kind:`scalar`,T:9}]),Zh=P.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:Qh,oneof:`value`}]),Qh=P.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}]),$h=P.makeMessageType(`livekit.ParticipantTracks`,()=>[{no:1,name:`participant_sid`,kind:`scalar`,T:9},{no:2,name:`track_sids`,kind:`scalar`,T:9,repeated:!0}]),eg=P.makeMessageType(`livekit.ServerInfo`,()=>[{no:1,name:`edition`,kind:`enum`,T:P.getEnumType(tg)},{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}]),tg=P.makeEnum(`livekit.ServerInfo.Edition`,[{no:0,name:`Standard`},{no:1,name:`Cloud`}]),ng=P.makeMessageType(`livekit.ClientInfo`,()=>[{no:1,name:`sdk`,kind:`enum`,T:P.getEnumType(rg)},{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}]),rg=P.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`}]),ig=P.makeMessageType(`livekit.ClientConfiguration`,()=>[{no:1,name:`video`,kind:`message`,T:ag},{no:2,name:`screen`,kind:`message`,T:ag},{no:3,name:`resume_connection`,kind:`enum`,T:P.getEnumType(bh)},{no:4,name:`disabled_codecs`,kind:`message`,T:og},{no:5,name:`force_relay`,kind:`enum`,T:P.getEnumType(bh)}]),ag=P.makeMessageType(`livekit.VideoConfiguration`,()=>[{no:1,name:`hardware_encoder`,kind:`enum`,T:P.getEnumType(bh)}]),og=P.makeMessageType(`livekit.DisabledCodecs`,()=>[{no:1,name:`codecs`,kind:`message`,T:Eh,repeated:!0},{no:2,name:`publish`,kind:`message`,T:Eh,repeated:!0}]),sg=P.makeMessageType(`livekit.TimedVersion`,()=>[{no:1,name:`unix_micro`,kind:`scalar`,T:3},{no:2,name:`ticks`,kind:`scalar`,T:5}]),cg=P.makeEnum(`livekit.DataStream.OperationType`,[{no:0,name:`CREATE`},{no:1,name:`UPDATE`},{no:2,name:`DELETE`},{no:3,name:`REACTION`}]),lg=P.makeMessageType(`livekit.DataStream.TextHeader`,()=>[{no:1,name:`operation_type`,kind:`enum`,T:P.getEnumType(cg)},{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`}),ug=P.makeMessageType(`livekit.DataStream.ByteHeader`,()=>[{no:1,name:`name`,kind:`scalar`,T:9}],{localName:`DataStream_ByteHeader`}),dg=P.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:P.getEnumType(F)},{no:8,name:`attributes`,kind:`map`,K:9,V:{kind:`scalar`,T:9}},{no:9,name:`text_header`,kind:`message`,T:lg,oneof:`content_header`},{no:10,name:`byte_header`,kind:`message`,T:ug,oneof:`content_header`}],{localName:`DataStream_Header`}),fg=P.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`}),pg=P.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`}),mg=P.makeMessageType(`livekit.SubscribedAudioCodec`,()=>[{no:1,name:`codec`,kind:`scalar`,T:9},{no:2,name:`enabled`,kind:`scalar`,T:8}]),hg=P.makeEnum(`livekit.SignalTarget`,[{no:0,name:`PUBLISHER`},{no:1,name:`SUBSCRIBER`}]),gg=P.makeEnum(`livekit.StreamState`,[{no:0,name:`ACTIVE`},{no:1,name:`PAUSED`}]),_g=P.makeEnum(`livekit.CandidateProtocol`,[{no:0,name:`UDP`},{no:1,name:`TCP`},{no:2,name:`TLS`}]),vg=P.makeMessageType(`livekit.SignalRequest`,()=>[{no:1,name:`offer`,kind:`message`,T:Pg,oneof:`message`},{no:2,name:`answer`,kind:`message`,T:Pg,oneof:`message`},{no:3,name:`trickle`,kind:`message`,T:Og,oneof:`message`},{no:4,name:`add_track`,kind:`message`,T:xg,oneof:`message`},{no:5,name:`mute`,kind:`message`,T:kg,oneof:`message`},{no:6,name:`subscription`,kind:`message`,T:Ig,oneof:`message`},{no:7,name:`track_setting`,kind:`message`,T:zg,oneof:`message`},{no:8,name:`leave`,kind:`message`,T:Hg,oneof:`message`},{no:10,name:`update_layers`,kind:`message`,T:Wg,oneof:`message`},{no:11,name:`subscription_permission`,kind:`message`,T:i_,oneof:`message`},{no:12,name:`sync_state`,kind:`message`,T:s_,oneof:`message`},{no:13,name:`simulate`,kind:`message`,T:u_,oneof:`message`},{no:14,name:`ping`,kind:`scalar`,T:3,oneof:`message`},{no:15,name:`update_metadata`,kind:`message`,T:Gg,oneof:`message`},{no:16,name:`ping_req`,kind:`message`,T:d_,oneof:`message`},{no:17,name:`update_audio_track`,kind:`message`,T:Bg,oneof:`message`},{no:18,name:`update_video_track`,kind:`message`,T:Vg,oneof:`message`},{no:19,name:`publish_data_track_request`,kind:`message`,T:Sg,oneof:`message`},{no:20,name:`unpublish_data_track_request`,kind:`message`,T:wg,oneof:`message`},{no:21,name:`update_data_subscription`,kind:`message`,T:Lg,oneof:`message`}]),yg=P.makeMessageType(`livekit.SignalResponse`,()=>[{no:1,name:`join`,kind:`message`,T:Ag,oneof:`message`},{no:2,name:`answer`,kind:`message`,T:Pg,oneof:`message`},{no:3,name:`offer`,kind:`message`,T:Pg,oneof:`message`},{no:4,name:`trickle`,kind:`message`,T:Og,oneof:`message`},{no:5,name:`update`,kind:`message`,T:Fg,oneof:`message`},{no:6,name:`track_published`,kind:`message`,T:Mg,oneof:`message`},{no:8,name:`leave`,kind:`message`,T:Hg,oneof:`message`},{no:9,name:`mute`,kind:`message`,T:kg,oneof:`message`},{no:10,name:`speakers_changed`,kind:`message`,T:qg,oneof:`message`},{no:11,name:`room_update`,kind:`message`,T:Jg,oneof:`message`},{no:12,name:`connection_quality`,kind:`message`,T:Xg,oneof:`message`},{no:13,name:`stream_state_update`,kind:`message`,T:Qg,oneof:`message`},{no:14,name:`subscribed_quality_update`,kind:`message`,T:t_,oneof:`message`},{no:15,name:`subscription_permission_update`,kind:`message`,T:a_,oneof:`message`},{no:16,name:`refresh_token`,kind:`scalar`,T:9,oneof:`message`},{no:17,name:`track_unpublished`,kind:`message`,T:Ng,oneof:`message`},{no:18,name:`pong`,kind:`scalar`,T:3,oneof:`message`},{no:19,name:`reconnect`,kind:`message`,T:jg,oneof:`message`},{no:20,name:`pong_resp`,kind:`message`,T:f_,oneof:`message`},{no:21,name:`subscription_response`,kind:`message`,T:h_,oneof:`message`},{no:22,name:`request_response`,kind:`message`,T:g_,oneof:`message`},{no:23,name:`track_subscribed`,kind:`message`,T:v_,oneof:`message`},{no:24,name:`room_moved`,kind:`message`,T:o_,oneof:`message`},{no:25,name:`media_sections_requirement`,kind:`message`,T:C_,oneof:`message`},{no:26,name:`subscribed_audio_codec_update`,kind:`message`,T:n_,oneof:`message`},{no:27,name:`publish_data_track_response`,kind:`message`,T:Cg,oneof:`message`},{no:28,name:`unpublish_data_track_response`,kind:`message`,T:Tg,oneof:`message`},{no:29,name:`data_track_subscriber_handles`,kind:`message`,T:Eg,oneof:`message`}]),bg=P.makeMessageType(`livekit.SimulcastCodec`,()=>[{no:1,name:`codec`,kind:`scalar`,T:9},{no:2,name:`cid`,kind:`scalar`,T:9},{no:4,name:`layers`,kind:`message`,T:Ih,repeated:!0},{no:5,name:`video_layer_mode`,kind:`enum`,T:P.getEnumType(Lh)}]),xg=P.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:P.getEnumType(gh)},{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:P.getEnumType(_h)},{no:9,name:`layers`,kind:`message`,T:Ih,repeated:!0},{no:10,name:`simulcast_codecs`,kind:`message`,T:bg,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:P.getEnumType(F)},{no:15,name:`stream`,kind:`scalar`,T:9},{no:16,name:`backup_codec_policy`,kind:`enum`,T:P.getEnumType(hh)},{no:17,name:`audio_features`,kind:`enum`,T:P.getEnumType(wh),repeated:!0}]),Sg=P.makeMessageType(`livekit.PublishDataTrackRequest`,()=>[{no:1,name:`pub_handle`,kind:`scalar`,T:13},{no:2,name:`name`,kind:`scalar`,T:9},{no:3,name:`encryption`,kind:`enum`,T:P.getEnumType(F)}]),Cg=P.makeMessageType(`livekit.PublishDataTrackResponse`,()=>[{no:1,name:`info`,kind:`message`,T:Ph}]),wg=P.makeMessageType(`livekit.UnpublishDataTrackRequest`,()=>[{no:1,name:`pub_handle`,kind:`scalar`,T:13}]),Tg=P.makeMessageType(`livekit.UnpublishDataTrackResponse`,()=>[{no:1,name:`info`,kind:`message`,T:Ph}]),Eg=P.makeMessageType(`livekit.DataTrackSubscriberHandles`,()=>[{no:1,name:`sub_handles`,kind:`map`,K:13,V:{kind:`message`,T:Dg}}]),Dg=P.makeMessageType(`livekit.DataTrackSubscriberHandles.PublishedDataTrack`,()=>[{no:1,name:`publisher_identity`,kind:`scalar`,T:9},{no:2,name:`publisher_sid`,kind:`scalar`,T:9},{no:3,name:`track_sid`,kind:`scalar`,T:9}],{localName:`DataTrackSubscriberHandles_PublishedDataTrack`}),Og=P.makeMessageType(`livekit.TrickleRequest`,()=>[{no:1,name:`candidateInit`,kind:`scalar`,T:9},{no:2,name:`target`,kind:`enum`,T:P.getEnumType(hg)},{no:3,name:`final`,kind:`scalar`,T:8}]),kg=P.makeMessageType(`livekit.MuteTrackRequest`,()=>[{no:1,name:`sid`,kind:`scalar`,T:9},{no:2,name:`muted`,kind:`scalar`,T:8}]),Ag=P.makeMessageType(`livekit.JoinResponse`,()=>[{no:1,name:`room`,kind:`message`,T:Th},{no:2,name:`participant`,kind:`message`,T:Oh},{no:3,name:`other_participants`,kind:`message`,T:Oh,repeated:!0},{no:4,name:`server_version`,kind:`scalar`,T:9},{no:5,name:`ice_servers`,kind:`message`,T:Kg,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:ig},{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:eg},{no:13,name:`sif_trailer`,kind:`scalar`,T:12},{no:14,name:`enabled_publish_codecs`,kind:`message`,T:Eh,repeated:!0},{no:15,name:`fast_publish`,kind:`scalar`,T:8}]),jg=P.makeMessageType(`livekit.ReconnectResponse`,()=>[{no:1,name:`ice_servers`,kind:`message`,T:Kg,repeated:!0},{no:2,name:`client_configuration`,kind:`message`,T:ig},{no:3,name:`server_info`,kind:`message`,T:eg},{no:4,name:`last_message_seq`,kind:`scalar`,T:13}]),Mg=P.makeMessageType(`livekit.TrackPublishedResponse`,()=>[{no:1,name:`cid`,kind:`scalar`,T:9},{no:2,name:`track`,kind:`message`,T:Nh}]),Ng=P.makeMessageType(`livekit.TrackUnpublishedResponse`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9}]),Pg=P.makeMessageType(`livekit.SessionDescription`,()=>[{no:1,name:`type`,kind:`scalar`,T:9},{no:2,name:`sdp`,kind:`scalar`,T:9},{no:3,name:`id`,kind:`scalar`,T:13},{no:4,name:`mid_to_track_id`,kind:`map`,K:9,V:{kind:`scalar`,T:9}}]),Fg=P.makeMessageType(`livekit.ParticipantUpdate`,()=>[{no:1,name:`participants`,kind:`message`,T:Oh,repeated:!0}]),Ig=P.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:$h,repeated:!0}]),Lg=P.makeMessageType(`livekit.UpdateDataSubscription`,()=>[{no:1,name:`updates`,kind:`message`,T:Rg,repeated:!0}]),Rg=P.makeMessageType(`livekit.UpdateDataSubscription.Update`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`subscribe`,kind:`scalar`,T:8},{no:3,name:`options`,kind:`message`,T:Fh}],{localName:`UpdateDataSubscription_Update`}),zg=P.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:P.getEnumType(vh)},{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}]),Bg=P.makeMessageType(`livekit.UpdateLocalAudioTrack`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`features`,kind:`enum`,T:P.getEnumType(wh),repeated:!0}]),Vg=P.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}]),Hg=P.makeMessageType(`livekit.LeaveRequest`,()=>[{no:1,name:`can_reconnect`,kind:`scalar`,T:8},{no:2,name:`reason`,kind:`enum`,T:P.getEnumType(xh)},{no:3,name:`action`,kind:`enum`,T:P.getEnumType(Ug)},{no:4,name:`regions`,kind:`message`,T:p_}]),Ug=P.makeEnum(`livekit.LeaveRequest.Action`,[{no:0,name:`DISCONNECT`},{no:1,name:`RESUME`},{no:2,name:`RECONNECT`}]),Wg=P.makeMessageType(`livekit.UpdateVideoLayers`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`layers`,kind:`message`,T:Ih,repeated:!0}]),Gg=P.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}]),Kg=P.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}]),qg=P.makeMessageType(`livekit.SpeakersChanged`,()=>[{no:1,name:`speakers`,kind:`message`,T:Uh,repeated:!0}]),Jg=P.makeMessageType(`livekit.RoomUpdate`,()=>[{no:1,name:`room`,kind:`message`,T:Th}]),Yg=P.makeMessageType(`livekit.ConnectionQualityInfo`,()=>[{no:1,name:`participant_sid`,kind:`scalar`,T:9},{no:2,name:`quality`,kind:`enum`,T:P.getEnumType(yh)},{no:3,name:`score`,kind:`scalar`,T:2}]),Xg=P.makeMessageType(`livekit.ConnectionQualityUpdate`,()=>[{no:1,name:`updates`,kind:`message`,T:Yg,repeated:!0}]),Zg=P.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:P.getEnumType(gg)}]),Qg=P.makeMessageType(`livekit.StreamStateUpdate`,()=>[{no:1,name:`stream_states`,kind:`message`,T:Zg,repeated:!0}]),$g=P.makeMessageType(`livekit.SubscribedQuality`,()=>[{no:1,name:`quality`,kind:`enum`,T:P.getEnumType(vh)},{no:2,name:`enabled`,kind:`scalar`,T:8}]),e_=P.makeMessageType(`livekit.SubscribedCodec`,()=>[{no:1,name:`codec`,kind:`scalar`,T:9},{no:2,name:`qualities`,kind:`message`,T:$g,repeated:!0}]),t_=P.makeMessageType(`livekit.SubscribedQualityUpdate`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`subscribed_qualities`,kind:`message`,T:$g,repeated:!0},{no:3,name:`subscribed_codecs`,kind:`message`,T:e_,repeated:!0}]),n_=P.makeMessageType(`livekit.SubscribedAudioCodecUpdate`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`subscribed_audio_codecs`,kind:`message`,T:mg,repeated:!0}]),r_=P.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}]),i_=P.makeMessageType(`livekit.SubscriptionPermission`,()=>[{no:1,name:`all_participants`,kind:`scalar`,T:8},{no:2,name:`track_permissions`,kind:`message`,T:r_,repeated:!0}]),a_=P.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}]),o_=P.makeMessageType(`livekit.RoomMovedResponse`,()=>[{no:1,name:`room`,kind:`message`,T:Th},{no:2,name:`token`,kind:`scalar`,T:9},{no:3,name:`participant`,kind:`message`,T:Oh},{no:4,name:`other_participants`,kind:`message`,T:Oh,repeated:!0}]),s_=P.makeMessageType(`livekit.SyncState`,()=>[{no:1,name:`answer`,kind:`message`,T:Pg},{no:2,name:`subscription`,kind:`message`,T:Ig},{no:3,name:`publish_tracks`,kind:`message`,T:Mg,repeated:!0},{no:4,name:`data_channels`,kind:`message`,T:l_,repeated:!0},{no:5,name:`offer`,kind:`message`,T:Pg},{no:6,name:`track_sids_disabled`,kind:`scalar`,T:9,repeated:!0},{no:7,name:`datachannel_receive_states`,kind:`message`,T:c_,repeated:!0},{no:8,name:`publish_data_tracks`,kind:`message`,T:Cg,repeated:!0}]),c_=P.makeMessageType(`livekit.DataChannelReceiveState`,()=>[{no:1,name:`publisher_sid`,kind:`scalar`,T:9},{no:2,name:`last_seq`,kind:`scalar`,T:13}]),l_=P.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:P.getEnumType(hg)}]),u_=P.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:P.getEnumType(_g),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`}]),d_=P.makeMessageType(`livekit.Ping`,()=>[{no:1,name:`timestamp`,kind:`scalar`,T:3},{no:2,name:`rtt`,kind:`scalar`,T:3}]),f_=P.makeMessageType(`livekit.Pong`,()=>[{no:1,name:`last_ping_timestamp`,kind:`scalar`,T:3},{no:2,name:`timestamp`,kind:`scalar`,T:3}]),p_=P.makeMessageType(`livekit.RegionSettings`,()=>[{no:1,name:`regions`,kind:`message`,T:m_,repeated:!0}]),m_=P.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}]),h_=P.makeMessageType(`livekit.SubscriptionResponse`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`err`,kind:`enum`,T:P.getEnumType(Ch)}]),g_=P.makeMessageType(`livekit.RequestResponse`,()=>[{no:1,name:`request_id`,kind:`scalar`,T:13},{no:2,name:`reason`,kind:`enum`,T:P.getEnumType(__)},{no:3,name:`message`,kind:`scalar`,T:9},{no:4,name:`trickle`,kind:`message`,T:Og,oneof:`request`},{no:5,name:`add_track`,kind:`message`,T:xg,oneof:`request`},{no:6,name:`mute`,kind:`message`,T:kg,oneof:`request`},{no:7,name:`update_metadata`,kind:`message`,T:Gg,oneof:`request`},{no:8,name:`update_audio_track`,kind:`message`,T:Bg,oneof:`request`},{no:9,name:`update_video_track`,kind:`message`,T:Vg,oneof:`request`},{no:10,name:`publish_data_track`,kind:`message`,T:Sg,oneof:`request`},{no:11,name:`unpublish_data_track`,kind:`message`,T:wg,oneof:`request`}]),__=P.makeEnum(`livekit.RequestResponse.Reason`,[{no:0,name:`OK`},{no:1,name:`NOT_FOUND`},{no:2,name:`NOT_ALLOWED`},{no:3,name:`LIMIT_EXCEEDED`},{no:4,name:`QUEUED`},{no:5,name:`UNSUPPORTED_TYPE`},{no:6,name:`UNCLASSIFIED_ERROR`},{no:7,name:`INVALID_HANDLE`},{no:8,name:`INVALID_NAME`},{no:9,name:`DUPLICATE_HANDLE`},{no:10,name:`DUPLICATE_NAME`}]),v_=P.makeMessageType(`livekit.TrackSubscribed`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9}]),y_=P.makeMessageType(`livekit.ConnectionSettings`,()=>[{no:1,name:`auto_subscribe`,kind:`scalar`,T:8},{no:2,name:`adaptive_stream`,kind:`scalar`,T:8},{no:3,name:`subscriber_allow_pause`,kind:`scalar`,T:8,opt:!0},{no:4,name:`disable_ice_lite`,kind:`scalar`,T:8},{no:5,name:`auto_subscribe_data_track`,kind:`scalar`,T:8,opt:!0}]),b_=P.makeMessageType(`livekit.JoinRequest`,()=>[{no:1,name:`client_info`,kind:`message`,T:ng},{no:2,name:`connection_settings`,kind:`message`,T:y_},{no:3,name:`metadata`,kind:`scalar`,T:9},{no:4,name:`participant_attributes`,kind:`map`,K:9,V:{kind:`scalar`,T:9}},{no:5,name:`add_track_requests`,kind:`message`,T:xg,repeated:!0},{no:6,name:`publisher_offer`,kind:`message`,T:Pg},{no:7,name:`reconnect`,kind:`scalar`,T:8},{no:8,name:`reconnect_reason`,kind:`enum`,T:P.getEnumType(Sh)},{no:9,name:`participant_sid`,kind:`scalar`,T:9},{no:10,name:`sync_state`,kind:`message`,T:s_}]),x_=P.makeMessageType(`livekit.WrappedJoinRequest`,()=>[{no:1,name:`compression`,kind:`enum`,T:P.getEnumType(S_)},{no:2,name:`join_request`,kind:`scalar`,T:12}]),S_=P.makeEnum(`livekit.WrappedJoinRequest.Compression`,[{no:0,name:`NONE`},{no:1,name:`GZIP`}]),C_=P.makeMessageType(`livekit.MediaSectionsRequirement`,()=>[{no:1,name:`num_audios`,kind:`scalar`,T:13},{no:2,name:`num_videos`,kind:`scalar`,T:13}]);function w_(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,`default`)?e.default:e}var T_={exports:{}},E_=T_.exports,D_;function O_(){return D_?T_.exports:(D_=1,(function(e){(function(t,n){e.exports?e.exports=n():t.log=n()})(E_,function(){var e=function(){},t=`undefined`,n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),r=[`trace`,`debug`,`info`,`warn`,`error`],i={},a=null;function o(e,t){var n=e[t];if(typeof n.bind==`function`)return n.bind(e);try{return Function.prototype.bind.call(n,e)}catch{return function(){return Function.prototype.apply.apply(n,[e,arguments])}}}function s(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(r){return r===`debug`&&(r=`log`),typeof console===t?!1:r===`trace`&&n?s:console[r]===void 0?console.log===void 0?e:o(console,`log`):o(console,r)}function l(){for(var n=this.getLevel(),i=0;i<r.length;i++){var a=r[i];this[a]=i<n?e:this.methodFactory(a,n,this.name)}if(this.log=this.debug,typeof console===t&&n<this.levels.SILENT)return`No console available for logging`}function u(e){return function(){typeof console!==t&&(l.call(this),this[e].apply(this,arguments))}}function d(e,t,n){return c(e)||u.apply(this,arguments)}function f(e,n){var o=this,s,c,u,f=`loglevel`;typeof e==`string`?f+=`:`+e:typeof e==`symbol`&&(f=void 0);function p(e){var n=(r[e]||`silent`).toUpperCase();if(!(typeof window===t||!f)){try{window.localStorage[f]=n;return}catch{}try{window.document.cookie=encodeURIComponent(f)+`=`+n+`;`}catch{}}}function m(){var e;if(!(typeof window===t||!f)){try{e=window.localStorage[f]}catch{}if(typeof e===t)try{var n=window.document.cookie,r=encodeURIComponent(f),i=n.indexOf(r+`=`);i!==-1&&(e=/^([^;]+)/.exec(n.slice(i+r.length+1))[1])}catch{}return o.levels[e]===void 0&&(e=void 0),e}}function h(){if(!(typeof window===t||!f)){try{window.localStorage.removeItem(f)}catch{}try{window.document.cookie=encodeURIComponent(f)+`=; expires=Thu, 01 Jan 1970 00:00:00 UTC`}catch{}}}function g(e){var t=e;if(typeof t==`string`&&o.levels[t.toUpperCase()]!==void 0&&(t=o.levels[t.toUpperCase()]),typeof t==`number`&&t>=0&&t<=o.levels.SILENT)return t;throw TypeError(`log.setLevel() called with invalid level: `+e)}o.name=e,o.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},o.methodFactory=n||d,o.getLevel=function(){return u??c??s},o.setLevel=function(e,t){return u=g(e),t!==!1&&p(u),l.call(o)},o.setDefaultLevel=function(e){c=g(e),m()||o.setLevel(e,!1)},o.resetLevel=function(){u=null,h(),l.call(o)},o.enableAll=function(e){o.setLevel(o.levels.TRACE,e)},o.disableAll=function(e){o.setLevel(o.levels.SILENT,e)},o.rebuild=function(){if(a!==o&&(s=g(a.getLevel())),l.call(o),a===o)for(var e in i)i[e].rebuild()},s=g(a?a.getLevel():`WARN`);var _=m();_!=null&&(u=g(_)),l.call(o)}a=new f,a.getLogger=function(e){if(typeof e!=`symbol`&&typeof e!=`string`||e===``)throw TypeError(`You must supply a name when creating a logger.`);var t=i[e];return t||=i[e]=new f(e,a.methodFactory),t};var p=typeof window===t?void 0:window.log;return a.noConflict=function(){return typeof window!==t&&window.log===a&&(window.log=p),a},a.getLoggers=function(){return i},a.default=a,a})})(T_),T_.exports)}var k_=O_(),A_;(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`})(A_||={});var j_;(function(e){e.Default=`livekit`,e.Room=`livekit-room`,e.TokenSource=`livekit-token-source`,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`,e.DataTracks=`livekit-data-tracks`})(j_||={});var I=k_.getLogger(`livekit`);Object.values(j_).map(e=>k_.getLogger(e)),I.setDefaultLevel(A_.info);function M_(e){let t=k_.getLogger(e);return t.setDefaultLevel(I.getLevel()),t}var N_=k_.getLogger(`lk-e2ee`),P_=7e3,F_=[0,300,4*300,9*300,16*300,P_,P_,P_,P_,P_],I_=class{constructor(e){this._retryDelays=e===void 0?F_:[...e]}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;let t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+Math.random()*1e3}};function L_(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols==`function`)for(var i=0,r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]]);return n}function L(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})}function R_(e){var t=typeof Symbol==`function`&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length==`number`)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw TypeError(t?`Object is not iterable.`:`Symbol.iterator is not defined.`)}function z_(e){return this instanceof z_?(this.v=e,this):new z_(e)}function B_(e,t,n){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var r=n.apply(e,t||[]),i,a=[];return i=Object.create((typeof AsyncIterator==`function`?AsyncIterator:Object).prototype),s(`next`),s(`throw`),s(`return`,o),i[Symbol.asyncIterator]=function(){return this},i;function o(e){return function(t){return Promise.resolve(t).then(e,d)}}function s(e,t){r[e]&&(i[e]=function(t){return new Promise(function(n,r){a.push([e,t,n,r])>1||c(e,t)})},t&&(i[e]=t(i[e])))}function c(e,t){try{l(r[e](t))}catch(e){f(a[0][3],e)}}function l(e){e.value instanceof z_?Promise.resolve(e.value.v).then(u,d):f(a[0][2],e)}function u(e){c(`next`,e)}function d(e){c(`throw`,e)}function f(e,t){e(t),a.shift(),a.length&&c(a[0][0],a[0][1])}}function V_(e){var t,n;return t={},r(`next`),r(`throw`,function(e){throw e}),r(`return`),t[Symbol.iterator]=function(){return this},t;function r(r,i){t[r]=e[r]?function(t){return(n=!n)?{value:z_(e[r](t)),done:!1}:i?i(t):t}:i}}function H_(e){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var t=e[Symbol.asyncIterator],n;return t?t.call(e):(e=typeof R_==`function`?R_(e):e[Symbol.iterator](),n={},r(`next`),r(`throw`),r(`return`),n[Symbol.asyncIterator]=function(){return this},n);function r(t){n[t]=e[t]&&function(n){return new Promise(function(r,a){n=e[t](n),i(r,a,n.done,n.value)})}}function i(e,t,n,r){Promise.resolve(r).then(function(t){e({value:t,done:n})},t)}}var U_={exports:{}},W_;function G_(){if(W_)return U_.exports;W_=1;var e=typeof Reflect==`object`?Reflect:null,t=e&&typeof e.apply==`function`?e.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)},n=e&&typeof e.ownKeys==`function`?e.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};function r(e){console&&console.warn&&console.warn(e)}var i=Number.isNaN||function(e){return e!==e};function a(){a.init.call(this)}U_.exports=a,U_.exports.once=_,a.EventEmitter=a,a.prototype._events=void 0,a.prototype._eventsCount=0,a.prototype._maxListeners=void 0;var o=10;function s(e){if(typeof e!=`function`)throw TypeError(`The "listener" argument must be of type Function. Received type `+typeof e)}Object.defineProperty(a,`defaultMaxListeners`,{enumerable:!0,get:function(){return o},set:function(e){if(typeof e!=`number`||e<0||i(e))throw RangeError(`The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received `+e+`.`);o=e}}),a.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},a.prototype.setMaxListeners=function(e){if(typeof e!=`number`||e<0||i(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};function c(e){return e._maxListeners===void 0?a.defaultMaxListeners:e._maxListeners}a.prototype.getMaxListeners=function(){return c(this)},a.prototype.emit=function(e){for(var n=[],r=1;r<arguments.length;r++)n.push(arguments[r]);var i=e===`error`,a=this._events;if(a!==void 0)i&&=a.error===void 0;else if(!i)return!1;if(i){var o;if(n.length>0&&(o=n[0]),o instanceof Error)throw o;var s=Error(`Unhandled error.`+(o?` (`+o.message+`)`:``));throw s.context=o,s}var c=a[e];if(c===void 0)return!1;if(typeof c==`function`)t(c,this,n);else for(var l=c.length,u=m(c,l),r=0;r<l;++r)t(u[r],this,n);return!0};function l(e,t,n,i){var a,o,l;if(s(n),o=e._events,o===void 0?(o=e._events=Object.create(null),e._eventsCount=0):(o.newListener!==void 0&&(e.emit(`newListener`,t,n.listener?n.listener:n),o=e._events),l=o[t]),l===void 0)l=o[t]=n,++e._eventsCount;else if(typeof l==`function`?l=o[t]=i?[n,l]:[l,n]:i?l.unshift(n):l.push(n),a=c(e),a>0&&l.length>a&&!l.warned){l.warned=!0;var u=Error(`Possible EventEmitter memory leak detected. `+l.length+` `+String(t)+` listeners added. Use emitter.setMaxListeners() to increase limit`);u.name=`MaxListenersExceededWarning`,u.emitter=e,u.type=t,u.count=l.length,r(u)}return e}a.prototype.addListener=function(e,t){return l(this,e,t,!1)},a.prototype.on=a.prototype.addListener,a.prototype.prependListener=function(e,t){return l(this,e,t,!0)};function u(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function d(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},i=u.bind(r);return i.listener=n,r.wrapFn=i,i}a.prototype.once=function(e,t){return s(t),this.on(e,d(this,e,t)),this},a.prototype.prependOnceListener=function(e,t){return s(t),this.prependListener(e,d(this,e,t)),this},a.prototype.removeListener=function(e,t){var n,r,i,a,o;if(s(t),r=this._events,r===void 0||(n=r[e],n===void 0))return this;if(n===t||n.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete r[e],r.removeListener&&this.emit(`removeListener`,e,n.listener||t));else if(typeof n!=`function`){for(i=-1,a=n.length-1;a>=0;a--)if(n[a]===t||n[a].listener===t){o=n[a].listener,i=a;break}if(i<0)return this;i===0?n.shift():h(n,i),n.length===1&&(r[e]=n[0]),r.removeListener!==void 0&&this.emit(`removeListener`,e,o||t)}return this},a.prototype.off=a.prototype.removeListener,a.prototype.removeAllListeners=function(e){var t,n=this._events,r;if(n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var i=Object.keys(n),a;for(r=0;r<i.length;++r)a=i[r],a!==`removeListener`&&this.removeAllListeners(a);return this.removeAllListeners(`removeListener`),this._events=Object.create(null),this._eventsCount=0,this}if(t=n[e],typeof t==`function`)this.removeListener(e,t);else if(t!==void 0)for(r=t.length-1;r>=0;r--)this.removeListener(e,t[r]);return this};function f(e,t,n){var r=e._events;if(r===void 0)return[];var i=r[t];return i===void 0?[]:typeof i==`function`?n?[i.listener||i]:[i]:n?g(i):m(i,i.length)}a.prototype.listeners=function(e){return f(this,e,!0)},a.prototype.rawListeners=function(e){return f(this,e,!1)},a.listenerCount=function(e,t){return typeof e.listenerCount==`function`?e.listenerCount(t):p.call(e,t)},a.prototype.listenerCount=p;function p(e){var t=this._events;if(t!==void 0){var n=t[e];if(typeof n==`function`)return 1;if(n!==void 0)return n.length}return 0}a.prototype.eventNames=function(){return this._eventsCount>0?n(this._events):[]};function m(e,t){for(var n=Array(t),r=0;r<t;++r)n[r]=e[r];return n}function h(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}function g(e){for(var t=Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}function _(e,t){return new Promise(function(n,r){function i(n){e.removeListener(t,a),r(n)}function a(){typeof e.removeListener==`function`&&e.removeListener(`error`,i),n([].slice.call(arguments))}y(e,t,a,{once:!0}),t!==`error`&&v(e,i,{once:!0})})}function v(e,t,n){typeof e.on==`function`&&y(e,`error`,t,n)}function y(e,t,n,r){if(typeof e.on==`function`)r.once?e.once(t,n):e.on(t,n);else if(typeof e.addEventListener==`function`)e.addEventListener(t,function i(a){r.once&&e.removeEventListener(t,i),n(a)});else throw TypeError(`The "emitter" argument must be of type EventEmitter. Received type `+typeof e)}return U_.exports}var K_=G_(),q_=!0,J_=!0;function Y_(e,t,n){let r=e.match(t);return r&&r.length>=n&&parseFloat(r[n],10)}function X_(e,t,n){if(!e.RTCPeerConnection)return;let r=e.RTCPeerConnection.prototype,i=r.addEventListener;r.addEventListener=function(e,r){if(e!==t)return i.apply(this,arguments);let a=e=>{let t=n(e);t&&(r.handleEvent?r.handleEvent(t):r(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(r,a),i.apply(this,[e,a])};let a=r.removeEventListener;r.removeEventListener=function(e,n){if(e!==t||!this._eventMap||!this._eventMap[t]||!this._eventMap[t].has(n))return a.apply(this,arguments);let r=this._eventMap[t].get(n);return this._eventMap[t].delete(n),this._eventMap[t].size===0&&delete this._eventMap[t],Object.keys(this._eventMap).length===0&&delete this._eventMap,a.apply(this,[e,r])},Object.defineProperty(r,`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 Z_(e){return typeof e==`boolean`?(q_=e,e?`adapter.js logging disabled`:`adapter.js logging enabled`):Error(`Argument type: `+typeof e+`. Please use a boolean.`)}function Q_(e){return typeof e==`boolean`?(J_=!e,`adapter.js deprecation warnings `+(e?`disabled`:`enabled`)):Error(`Argument type: `+typeof e+`. Please use a boolean.`)}function $_(){if(typeof window==`object`){if(q_)return;typeof console<`u`&&typeof console.log==`function`&&console.log.apply(console,arguments)}}function ev(e,t){J_&&console.warn(e+` is deprecated, please use `+t+` instead.`)}function tv(e){let t={browser:null,version:null};if(e===void 0||!e.navigator||!e.navigator.userAgent)return t.browser=`Not a browser.`,t;let{navigator:n}=e;if(n.userAgentData&&n.userAgentData.brands){let e=n.userAgentData.brands.find(e=>e.brand===`Chromium`);if(e)return{browser:`chrome`,version:parseInt(e.version,10)}}if(n.mozGetUserMedia)t.browser=`firefox`,t.version=parseInt(Y_(n.userAgent,/Firefox\/(\d+)\./,1));else if(n.webkitGetUserMedia||e.isSecureContext===!1&&e.webkitRTCPeerConnection)t.browser=`chrome`,t.version=parseInt(Y_(n.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else if(e.RTCPeerConnection&&n.userAgent.match(/AppleWebKit\/(\d+)\./))t.browser=`safari`,t.version=parseInt(Y_(n.userAgent,/AppleWebKit\/(\d+)\./,1)),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&`currentDirection`in e.RTCRtpTransceiver.prototype,t._safariVersion=Y_(n.userAgent,/Version\/(\d+(\.?\d+))/,1);else return t.browser=`Not a supported browser.`,t;return t}function nv(e){return Object.prototype.toString.call(e)===`[object Object]`}function rv(e){return nv(e)?Object.keys(e).reduce(function(t,n){let r=nv(e[n]),i=r?rv(e[n]):e[n],a=r&&!Object.keys(i).length;return i===void 0||a?t:Object.assign(t,{[n]:i})},{}):e}function iv(e,t,n){!t||n.has(t.id)||(n.set(t.id,t),Object.keys(t).forEach(r=>{r.endsWith(`Id`)?iv(e,e.get(t[r]),n):r.endsWith(`Ids`)&&t[r].forEach(t=>{iv(e,e.get(t),n)})}))}function av(e,t,n){let r=n?`outbound-rtp`:`inbound-rtp`,i=new Map;if(t===null)return i;let a=[];return e.forEach(e=>{e.type===`track`&&e.trackIdentifier===t.id&&a.push(e)}),a.forEach(t=>{e.forEach(n=>{n.type===r&&n.trackId===t.id&&iv(e,n,i)})}),i}var ov=$_;function sv(e,t){let n=e&&e.navigator;if(!n.mediaDevices)return;let r=function(e){if(typeof e!=`object`||e.mandatory||e.optional)return e;let t={};return Object.keys(e).forEach(n=>{if(n===`require`||n===`advanced`||n===`mediaSource`)return;let r=typeof e[n]==`object`?e[n]:{ideal:e[n]};r.exact!==void 0&&typeof r.exact==`number`&&(r.min=r.max=r.exact);let i=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):t===`deviceId`?`sourceId`:t};if(r.ideal!==void 0){t.optional=t.optional||[];let e={};typeof r.ideal==`number`?(e[i(`min`,n)]=r.ideal,t.optional.push(e),e={},e[i(`max`,n)]=r.ideal,t.optional.push(e)):(e[i(``,n)]=r.ideal,t.optional.push(e))}r.exact!==void 0&&typeof r.exact!=`number`?(t.mandatory=t.mandatory||{},t.mandatory[i(``,n)]=r.exact):[`min`,`max`].forEach(e=>{r[e]!==void 0&&(t.mandatory=t.mandatory||{},t.mandatory[i(e,n)]=r[e])})}),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},i=function(e,i){if(t.version>=61)return i(e);if(e=JSON.parse(JSON.stringify(e)),e&&typeof e.audio==`object`){let t=function(e,t,n){t in e&&!(n in e)&&(e[n]=e[t],delete e[t])};e=JSON.parse(JSON.stringify(e)),t(e.audio,`autoGainControl`,`googAutoGainControl`),t(e.audio,`noiseSuppression`,`googNoiseSuppression`),e.audio=r(e.audio)}if(e&&typeof e.video==`object`){let a=e.video.facingMode;a&&=typeof a==`object`?a:{ideal:a};let o=t.version<66;if(a&&(a.exact===`user`||a.exact===`environment`||a.ideal===`user`||a.ideal===`environment`)&&!(n.mediaDevices.getSupportedConstraints&&n.mediaDevices.getSupportedConstraints().facingMode&&!o)){delete e.video.facingMode;let t;if(a.exact===`environment`||a.ideal===`environment`?t=[`back`,`rear`]:(a.exact===`user`||a.ideal===`user`)&&(t=[`front`]),t)return n.mediaDevices.enumerateDevices().then(n=>{n=n.filter(e=>e.kind===`videoinput`);let o=n.find(e=>t.some(t=>e.label.toLowerCase().includes(t)));return!o&&n.length&&t.includes(`back`)&&(o=n[n.length-1]),o&&(e.video.deviceId=a.exact?{exact:o.deviceId}:{ideal:o.deviceId}),e.video=r(e.video),ov(`chrome: `+JSON.stringify(e)),i(e)})}e.video=r(e.video)}return ov(`chrome: `+JSON.stringify(e)),i(e)},a=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(n.getUserMedia=function(e,t,r){i(e,e=>{n.webkitGetUserMedia(e,t,e=>{r&&r(a(e))})})}.bind(n),n.mediaDevices.getUserMedia){let e=n.mediaDevices.getUserMedia.bind(n.mediaDevices);n.mediaDevices.getUserMedia=function(t){return i(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(a(e))))}}}function cv(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function lv(e){if(typeof e==`object`&&e.RTCPeerConnection&&!(`ontrack`in e.RTCPeerConnection.prototype)){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`,n=>{let r;r=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===n.track.id):{track:n.track};let i=new Event(`track`);i.track=n.track,i.receiver=r,i.transceiver={receiver:r},i.streams=[t.stream],this.dispatchEvent(i)}),t.stream.getTracks().forEach(n=>{let r;r=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===n.id):{track:n};let i=new Event(`track`);i.track=n,i.receiver=r,i.transceiver={receiver:r},i.streams=[t.stream],this.dispatchEvent(i)})},this.addEventListener(`addstream`,this._ontrackpoly)),t.apply(this,arguments)}}else X_(e,`track`,e=>(e.transceiver||Object.defineProperty(e,`transceiver`,{value:{receiver:e.receiver}}),e))}function uv(e){if(typeof e==`object`&&e.RTCPeerConnection&&!(`getSenders`in e.RTCPeerConnection.prototype)&&`createDTMFSender`in e.RTCPeerConnection.prototype){let t=function(e,t){return{track:t,get dtmf(){return this._dtmf===void 0&&(t.kind===`audio`?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 n=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,r){let i=n.apply(this,arguments);return i||(i=t(this,e),this._senders.push(i)),i};let r=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){r.apply(this,arguments);let t=this._senders.indexOf(e);t!==-1&&this._senders.splice(t,1)}}let n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach(e=>{this._senders.push(t(this,e))})};let r=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],r.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(typeof e==`object`&&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 this._dtmf===void 0&&(this.track.kind===`audio`?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function dv(e){if(!(typeof e==`object`&&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 n=e.RTCPeerConnection.prototype.addTrack;n&&(e.RTCPeerConnection.prototype.addTrack=function(){let e=n.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){let e=this;return this._pc.getStats().then(t=>av(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}),X_(e,`track`,e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){let e=this;return this._pc.getStats().then(t=>av(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=arguments[0],t,n,r;return this.getSenders().forEach(n=>{n.track===e&&(t?r=!0:t=n)}),this.getReceivers().forEach(t=>(t.track===e&&(n?r=!0:n=t),t.track===e)),r||t&&n?Promise.reject(new DOMException(`There are more than one sender or receiver for the track.`,`InvalidAccessError`)):t?t.getStats():n?n.getStats():Promise.reject(new DOMException(`There is no sender or receiver for the track.`,`InvalidAccessError`))}return t.apply(this,arguments)}}function fv(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,n){if(!n)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};let r=t.apply(this,arguments);return this._shimmedLocalStreams[n.id]?this._shimmedLocalStreams[n.id].indexOf(r)===-1&&this._shimmedLocalStreams[n.id].push(r):this._shimmedLocalStreams[n.id]=[n,r],r};let n=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();n.apply(this,arguments);let r=this.getSenders().filter(e=>t.indexOf(e)===-1);this._shimmedLocalStreams[e.id]=[e].concat(r)};let r=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],r.apply(this,arguments)};let i=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach(t=>{let n=this._shimmedLocalStreams[t].indexOf(e);n!==-1&&this._shimmedLocalStreams[t].splice(n,1),this._shimmedLocalStreams[t].length===1&&delete this._shimmedLocalStreams[t]}),i.apply(this,arguments)}}function pv(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return fv(e);let n=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){let e=n.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map(e=>this._reverseStreams[e.id])};let r=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 n=new e.MediaStream(t.getTracks());this._streams[t.id]=n,this._reverseStreams[n.id]=t,t=n}r.apply(this,[t])};let i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},i.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,n){if(this.signalingState===`closed`)throw new DOMException(`The RTCPeerConnection's signalingState is 'closed'.`,`InvalidStateError`);let r=[].slice.call(arguments,1);if(r.length!==1||!r[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 i=this._streams[n.id];if(i)i.addTrack(t),Promise.resolve().then(()=>{this.dispatchEvent(new Event(`negotiationneeded`))});else{let r=new e.MediaStream([t]);this._streams[n.id]=r,this._reverseStreams[r.id]=n,this.addStream(r)}return this.getSenders().find(e=>e.track===t)};function a(e,t){let n=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{let r=e._reverseStreams[t],i=e._streams[r.id];n=n.replace(new RegExp(i.id,`g`),r.id)}),new RTCSessionDescription({type:t.type,sdp:n})}function o(e,t){let n=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{let r=e._reverseStreams[t],i=e._streams[r.id];n=n.replace(new RegExp(r.id,`g`),i.id)}),new RTCSessionDescription({type:t.type,sdp:n})}[`createOffer`,`createAnswer`].forEach(function(t){let n=e.RTCPeerConnection.prototype[t],r={[t](){let e=arguments;return arguments.length&&typeof arguments[0]==`function`?n.apply(this,[t=>{let n=a(this,t);e[0].apply(null,[n])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):n.apply(this,arguments).then(e=>a(this,e))}};e.RTCPeerConnection.prototype[t]=r[t]});let s=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type||(arguments[0]=o(this,arguments[0])),s.apply(this,arguments)};let c=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,`localDescription`);Object.defineProperty(e.RTCPeerConnection.prototype,`localDescription`,{get(){let e=c.get.apply(this);return e.type===``?e:a(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if(this.signalingState===`closed`)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||{};let t;Object.keys(this._streams).forEach(n=>{this._streams[n].getTracks().find(t=>e.track===t)&&(t=this._streams[n])}),t&&(t.getTracks().length===1?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event(`negotiationneeded`)))}}function mv(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&[`setLocalDescription`,`setRemoteDescription`,`addIceCandidate`].forEach(function(t){let n=e.RTCPeerConnection.prototype[t],r={[t](){return arguments[0]=new(t===`addIceCandidate`?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=r[t]})}function hv(e,t){X_(e,`negotiationneeded`,e=>{let n=e.target;if(!((t.version<72||n.getConfiguration&&n.getConfiguration().sdpSemantics===`plan-b`)&&n.signalingState!==`stable`))return e})}var gv=Object.freeze({__proto__:null,fixNegotiationNeeded:hv,shimAddTrackRemoveTrack:pv,shimAddTrackRemoveTrackWithNative:fv,shimGetSendersWithDtmf:uv,shimGetUserMedia:sv,shimMediaStream:cv,shimOnTrack:lv,shimPeerConnection:mv,shimSenderReceiverGetStats:dv});function _v(e,t){let n=e&&e.navigator,r=e&&e.MediaStreamTrack;if(n.getUserMedia=function(e,t,r){ev(`navigator.getUserMedia`,`navigator.mediaDevices.getUserMedia`),n.mediaDevices.getUserMedia(e).then(t,r)},!(t.version>55&&`autoGainControl`in n.mediaDevices.getSupportedConstraints())){let e=function(e,t,n){t in e&&!(n in e)&&(e[n]=e[t],delete e[t])},t=n.mediaDevices.getUserMedia.bind(n.mediaDevices);if(n.mediaDevices.getUserMedia=function(n){return typeof n==`object`&&typeof n.audio==`object`&&(n=JSON.parse(JSON.stringify(n)),e(n.audio,`autoGainControl`,`mozAutoGainControl`),e(n.audio,`noiseSuppression`,`mozNoiseSuppression`)),t(n)},r&&r.prototype.getSettings){let t=r.prototype.getSettings;r.prototype.getSettings=function(){let n=t.apply(this,arguments);return e(n,`mozAutoGainControl`,`autoGainControl`),e(n,`mozNoiseSuppression`,`noiseSuppression`),n}}if(r&&r.prototype.applyConstraints){let t=r.prototype.applyConstraints;r.prototype.applyConstraints=function(n){return this.kind===`audio`&&typeof n==`object`&&(n=JSON.parse(JSON.stringify(n)),e(n,`autoGainControl`,`mozAutoGainControl`),e(n,`noiseSuppression`,`mozNoiseSuppression`)),t.apply(this,[n])}}}}function vv(e,t){e.navigator.mediaDevices&&`getDisplayMedia`in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(n){if(!(n&&n.video)){let e=new DOMException(`getDisplayMedia without video constraints is undefined`);return e.name=`NotFoundError`,e.code=8,Promise.reject(e)}return n.video===!0?n.video={mediaSource:t}:n.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(n)})}function yv(e){typeof e==`object`&&e.RTCTrackEvent&&`receiver`in e.RTCTrackEvent.prototype&&!(`transceiver`in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,`transceiver`,{get(){return{receiver:this.receiver}}})}function bv(e,t){if(typeof e!=`object`||!(e.RTCPeerConnection||e.mozRTCPeerConnection))return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&[`setLocalDescription`,`setRemoteDescription`,`addIceCandidate`].forEach(function(t){let n=e.RTCPeerConnection.prototype[t],r={[t](){return arguments[0]=new(t===`addIceCandidate`?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=r[t]});let n={inboundrtp:`inbound-rtp`,outboundrtp:`outbound-rtp`,candidatepair:`candidate-pair`,localcandidate:`local-candidate`,remotecandidate:`remote-candidate`},r=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){let[e,i,a]=arguments;return r.apply(this,[e||null]).then(e=>{if(t.version<53&&!i)try{e.forEach(e=>{e.type=n[e.type]||e.type})}catch(t){if(t.name!==`TypeError`)throw t;e.forEach((t,r)=>{e.set(r,Object.assign({},t,{type:n[t.type]||t.type}))})}return e}).then(i,a)}}function xv(e){if(!(typeof e==`object`&&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 n=e.RTCPeerConnection.prototype.addTrack;n&&(e.RTCPeerConnection.prototype.addTrack=function(){let e=n.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 Sv(e){if(!(typeof e==`object`&&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}),X_(e,`track`,e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Cv(e){!e.RTCPeerConnection||`removeStream`in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){ev(`removeStream`,`removeTrack`),this.getSenders().forEach(t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)})})}function wv(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function Tv(e){if(!(typeof e==`object`&&e.RTCPeerConnection))return;let t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;e===void 0&&(e=[]),e=[...e];let n=e.length>0;n&&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 r=t.apply(this,arguments);if(n){let{sender:t}=r,n=t.getParameters();(!(`encodings`in n)||n.encodings.length===1&&Object.keys(n.encodings[0]).length===0)&&(n.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(n).then(()=>{delete t.sendEncodings}).catch(()=>{delete t.sendEncodings})))}return r})}function Ev(e){if(!(typeof e==`object`&&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 Dv(e){if(!(typeof e==`object`&&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 Ov(e){if(!(typeof e==`object`&&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 kv=Object.freeze({__proto__:null,shimAddTransceiver:Tv,shimCreateAnswer:Ov,shimCreateOffer:Dv,shimGetDisplayMedia:vv,shimGetParameters:Ev,shimGetUserMedia:_v,shimOnTrack:yv,shimPeerConnection:bv,shimRTCDataChannel:wv,shimReceiverGetStats:Sv,shimRemoveStream:Cv,shimSenderGetStats:xv});function Av(e){if(!(typeof e!=`object`||!e.RTCPeerConnection)){if(`getLocalStreams`in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return 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.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach(n=>t.call(this,n,e)),e.getVideoTracks().forEach(n=>t.call(this,n,e))},e.RTCPeerConnection.prototype.addTrack=function(e){for(var n=arguments.length,r=Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return r&&r.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||=[];let t=this._localStreams.indexOf(e);if(t===-1)return;this._localStreams.splice(t,1);let n=e.getTracks();this.getSenders().forEach(e=>{n.includes(e.track)&&this.removeTrack(e)})})}}function jv(e){if(!(typeof e!=`object`||!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.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.indexOf(t)>=0)return;e._remoteStreams.push(t);let n=new Event(`addstream`);n.stream=t,e.dispatchEvent(n)})}),t.apply(e,arguments)}}}function Mv(e){if(typeof e!=`object`||!e.RTCPeerConnection)return;let t=e.RTCPeerConnection.prototype,n=t.createOffer,r=t.createAnswer,i=t.setLocalDescription,a=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=function(e,t){let r=arguments.length>=2?arguments[2]:arguments[0],i=n.apply(this,[r]);return t?(i.then(e,t),Promise.resolve()):i},t.createAnswer=function(e,t){let n=arguments.length>=2?arguments[2]:arguments[0],i=r.apply(this,[n]);return t?(i.then(e,t),Promise.resolve()):i};let s=function(e,t,n){let r=i.apply(this,[e]);return n?(r.then(t,n),Promise.resolve()):r};t.setLocalDescription=s,s=function(e,t,n){let r=a.apply(this,[e]);return n?(r.then(t,n),Promise.resolve()):r},t.setRemoteDescription=s,s=function(e,t,n){let r=o.apply(this,[e]);return n?(r.then(t,n),Promise.resolve()):r},t.addIceCandidate=s}function Nv(e){let t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){let e=t.mediaDevices,n=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>n(Pv(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,n,r){t.mediaDevices.getUserMedia(e).then(n,r)}.bind(t))}function Pv(e){return e&&e.video!==void 0?Object.assign({},e,{video:rv(e.video)}):e}function Fv(e){if(!e.RTCPeerConnection)return;let t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,n){if(e&&e.iceServers){let t=[];for(let n=0;n<e.iceServers.length;n++){let r=e.iceServers[n];r.urls===void 0&&r.url?(ev(`RTCIceServer.url`,`RTCIceServer.urls`),r=JSON.parse(JSON.stringify(r)),r.urls=r.url,delete r.url,t.push(r)):t.push(e.iceServers[n])}e.iceServers=t}return new t(e,n)},e.RTCPeerConnection.prototype=t.prototype,`generateCertificate`in t&&Object.defineProperty(e.RTCPeerConnection,`generateCertificate`,{get(){return t.generateCertificate}})}function Iv(e){typeof e==`object`&&e.RTCTrackEvent&&`receiver`in e.RTCTrackEvent.prototype&&!(`transceiver`in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,`transceiver`,{get(){return{receiver:this.receiver}}})}function Lv(e){let t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){e.offerToReceiveAudio!==void 0&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);let t=this.getTransceivers().find(e=>e.receiver.track.kind===`audio`);e.offerToReceiveAudio===!1&&t?t.direction===`sendrecv`?t.setDirection?t.setDirection(`sendonly`):t.direction=`sendonly`:t.direction===`recvonly`&&(t.setDirection?t.setDirection(`inactive`):t.direction=`inactive`):e.offerToReceiveAudio===!0&&!t&&this.addTransceiver(`audio`,{direction:`recvonly`}),e.offerToReceiveVideo!==void 0&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);let n=this.getTransceivers().find(e=>e.receiver.track.kind===`video`);e.offerToReceiveVideo===!1&&n?n.direction===`sendrecv`?n.setDirection?n.setDirection(`sendonly`):n.direction=`sendonly`:n.direction===`recvonly`&&(n.setDirection?n.setDirection(`inactive`):n.direction=`inactive`):e.offerToReceiveVideo===!0&&!n&&this.addTransceiver(`video`,{direction:`recvonly`})}return t.apply(this,arguments)}}function Rv(e){typeof e!=`object`||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var zv=Object.freeze({__proto__:null,shimAudioContext:Rv,shimCallbacksAPI:Mv,shimConstraints:Pv,shimCreateOfferLegacy:Lv,shimGetUserMedia:Nv,shimLocalStreamsAPI:Av,shimRTCIceServerUrls:Fv,shimRemoteStreamsAPI:jv,shimTrackEventTransceiver:Iv}),Bv={exports:{}},Vv;function Hv(){return Vv?Bv.exports:(Vv=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(`
27
27
  `).map(e=>e.trim())},t.splitSections=function(e){return e.split(`
28
28
  m=`).map((e,t)=>(t>0?`m=`+e:e).trim()+`\r
29
29
  `)},t.getDescription=function(e){let n=t.splitSections(e);return n&&n[0]},t.getMediaSections=function(e){let n=t.splitSections(e);return n.shift(),n},t.matchPrefix=function(e,n){return t.splitLines(e).filter(e=>e.indexOf(n)===0)},t.parseCandidate=function(e){let t;t=e.indexOf(`a=candidate:`)===0?e.substring(12).split(` `):e.substring(10).split(` `);let n={foundation:t[0],component:{1:`rtp`,2:`rtcp`}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let e=8;e<t.length;e+=2)switch(t[e]){case`raddr`:n.relatedAddress=t[e+1];break;case`rport`:n.relatedPort=parseInt(t[e+1],10);break;case`tcptype`:n.tcpType=t[e+1];break;case`ufrag`:n.ufrag=t[e+1],n.usernameFragment=t[e+1];break;default:n[t[e]]===void 0&&(n[t[e]]=t[e+1]);break}return n},t.writeCandidate=function(e){let t=[];t.push(e.foundation);let n=e.component;n===`rtp`?t.push(1):n===`rtcp`?t.push(2):t.push(n),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);let r=e.type;return t.push(`typ`),t.push(r),r!==`host`&&e.relatedAddress&&e.relatedPort&&(t.push(`raddr`),t.push(e.relatedAddress),t.push(`rport`),t.push(e.relatedPort)),e.tcpType&&e.protocol.toLowerCase()===`tcp`&&(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(` `),n={payloadType:parseInt(t.shift(),10)};return t=t[0].split(`/`),n.name=t[0],n.clockRate=parseInt(t[1],10),n.channels=t.length===3?parseInt(t[2],10):1,n.numChannels=n.channels,n},t.writeRtpMap=function(e){let t=e.payloadType;e.preferredPayloadType!==void 0&&(t=e.preferredPayloadType);let n=e.channels||e.numChannels||1;return`a=rtpmap:`+t+` `+e.name+`/`+e.clockRate+(n===1?``:`/`+n)+`\r
@@ -54,12 +54,12 @@ a=ice-pwd:`+e.password+`\r
54
54
  o=`+(r||`thisisadapterortc`)+` `+i+` `+a+` IN IP4 127.0.0.1\r
55
55
  s=-\r
56
56
  t=0 0\r
57
- `},t.getDirection=function(e,n){let r=t.splitLines(e);for(let e=0;e<r.length;e++)switch(r[e]){case`a=sendrecv`:case`a=sendonly`:case`a=recvonly`:case`a=inactive`:return r[e].substring(2)}return n?t.getDirection(n):`sendrecv`},t.getKind=function(e){return t.splitLines(e)[0].split(` `)[0].substring(2)},t.isRejected=function(e){return e.split(` `,2)[1]===`0`},t.parseMLine=function(e){let n=t.splitLines(e)[0].substring(2).split(` `);return{kind:n[0],port:parseInt(n[1],10),protocol:n[2],fmt:n.slice(3).join(` `)}},t.parseOLine=function(e){let n=t.matchPrefix(e,`o=`)[0].substring(2).split(` `);return{username:n[0],sessionId:n[1],sessionVersion:parseInt(n[2],10),netType:n[3],addressType:n[4],address:n[5]}},t.isValidSDP=function(e){if(typeof e!=`string`||e.length===0)return!1;let n=t.splitLines(e);for(let e=0;e<n.length;e++)if(n[e].length<2||n[e].charAt(1)!==`=`)return!1;return!0},e.exports=t})(Iv),Iv.exports)}var zv=Rv(),Bv=b_(zv),Vv=sp({__proto__:null,default:Bv},[zv]);function Hv(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&`foundation`in e.RTCIceCandidate.prototype)return;let t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if(typeof e==`object`&&e.candidate&&e.candidate.indexOf(`a=`)===0&&(e=JSON.parse(JSON.stringify(e)),e.candidate=e.candidate.substring(2)),e.candidate&&e.candidate.length){let n=new t(e),r=Bv.parseCandidate(e.candidate);for(let e in r)e in n||Object.defineProperty(n,e,{value:r[e]});return n.toJSON=function(){return{candidate:n.candidate,sdpMid:n.sdpMid,sdpMLineIndex:n.sdpMLineIndex,usernameFragment:n.usernameFragment}},n}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,K_(e,`icecandidate`,t=>(t.candidate&&Object.defineProperty(t,`candidate`,{value:new e.RTCIceCandidate(t.candidate),writable:`false`}),t))}function Uv(e){!e.RTCIceCandidate||e.RTCIceCandidate&&`relayProtocol`in e.RTCIceCandidate.prototype||K_(e,`icecandidate`,e=>{if(e.candidate){let t=Bv.parseCandidate(e.candidate.candidate);t.type===`relay`&&(e.candidate.relayProtocol={0:`tls`,1:`tcp`,2:`udp`}[t.priority>>24])}return e})}function Wv(e,t){if(!e.RTCPeerConnection)return;`sctp`in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,`sctp`,{get(){return this._sctp===void 0?null:this._sctp}});let n=function(e){if(!e||!e.sdp)return!1;let t=Bv.splitSections(e.sdp);return t.shift(),t.some(e=>{let t=Bv.parseMLine(e);return t&&t.kind===`application`&&t.protocol.indexOf(`SCTP`)!==-1})},r=function(e){let t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(t===null||t.length<2)return-1;let n=parseInt(t[1],10);return n===n?n:-1},i=function(e){let n=65536;return t.browser===`firefox`&&(n=t.version<57?e===-1?16384:2147483637:t.version<60?t.version===57?65535:65536:2147483637),n},a=function(e,n){let r=65536;t.browser===`firefox`&&t.version===57&&(r=65535);let i=Bv.matchPrefix(e.sdp,`a=max-message-size:`);return i.length>0?r=parseInt(i[0].substring(19),10):t.browser===`firefox`&&n!==-1&&(r=2147483637),r},o=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,t.browser===`chrome`&&t.version>=76){let{sdpSemantics:e}=this.getConfiguration();e===`plan-b`&&Object.defineProperty(this,`sctp`,{get(){return this._sctp===void 0?null:this._sctp},enumerable:!0,configurable:!0})}if(n(arguments[0])){let e=r(arguments[0]),t=i(e),n=a(arguments[0],e),o;o=t===0&&n===0?1/0:t===0||n===0?Math.max(t,n):Math.min(t,n);let s={};Object.defineProperty(s,`maxMessageSize`,{get(){return o}}),this._sctp=s}return o.apply(this,arguments)}}function Gv(e){if(!(e.RTCPeerConnection&&`createDataChannel`in e.RTCPeerConnection.prototype))return;function t(e,t){let n=e.send;e.send=function(){let r=arguments[0],i=r.length||r.size||r.byteLength;if(e.readyState===`open`&&t.sctp&&i>t.sctp.maxMessageSize)throw TypeError(`Message too large (can send a maximum of `+t.sctp.maxMessageSize+` bytes)`);return n.apply(e,arguments)}}let n=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){let e=n.apply(this,arguments);return t(e,this),e},K_(e,`datachannel`,e=>(t(e.channel,e.target),e))}function Kv(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 n=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 n=new Event(`connectionstatechange`,e);t.dispatchEvent(n)}return e},this.addEventListener(`iceconnectionstatechange`,this._connectionstatechangepoly)),n.apply(this,arguments)}})}function qv(e,t){if(!e.RTCPeerConnection||t.browser===`chrome`&&t.version>=71||t.browser===`safari`&&t._safariVersion>=13.1)return;let n=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&t.sdp.indexOf(`
57
+ `},t.getDirection=function(e,n){let r=t.splitLines(e);for(let e=0;e<r.length;e++)switch(r[e]){case`a=sendrecv`:case`a=sendonly`:case`a=recvonly`:case`a=inactive`:return r[e].substring(2)}return n?t.getDirection(n):`sendrecv`},t.getKind=function(e){return t.splitLines(e)[0].split(` `)[0].substring(2)},t.isRejected=function(e){return e.split(` `,2)[1]===`0`},t.parseMLine=function(e){let n=t.splitLines(e)[0].substring(2).split(` `);return{kind:n[0],port:parseInt(n[1],10),protocol:n[2],fmt:n.slice(3).join(` `)}},t.parseOLine=function(e){let n=t.matchPrefix(e,`o=`)[0].substring(2).split(` `);return{username:n[0],sessionId:n[1],sessionVersion:parseInt(n[2],10),netType:n[3],addressType:n[4],address:n[5]}},t.isValidSDP=function(e){if(typeof e!=`string`||e.length===0)return!1;let n=t.splitLines(e);for(let e=0;e<n.length;e++)if(n[e].length<2||n[e].charAt(1)!==`=`)return!1;return!0},e.exports=t})(Bv),Bv.exports)}var Uv=Hv(),Wv=w_(Uv),Gv=dp({__proto__:null,default:Wv},[Uv]);function Kv(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&`foundation`in e.RTCIceCandidate.prototype)return;let t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if(typeof e==`object`&&e.candidate&&e.candidate.indexOf(`a=`)===0&&(e=JSON.parse(JSON.stringify(e)),e.candidate=e.candidate.substring(2)),e.candidate&&e.candidate.length){let n=new t(e),r=Wv.parseCandidate(e.candidate);for(let e in r)e in n||Object.defineProperty(n,e,{value:r[e]});return n.toJSON=function(){return{candidate:n.candidate,sdpMid:n.sdpMid,sdpMLineIndex:n.sdpMLineIndex,usernameFragment:n.usernameFragment}},n}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,X_(e,`icecandidate`,t=>(t.candidate&&Object.defineProperty(t,`candidate`,{value:new e.RTCIceCandidate(t.candidate),writable:`false`}),t))}function qv(e){!e.RTCIceCandidate||e.RTCIceCandidate&&`relayProtocol`in e.RTCIceCandidate.prototype||X_(e,`icecandidate`,e=>{if(e.candidate){let t=Wv.parseCandidate(e.candidate.candidate);t.type===`relay`&&(e.candidate.relayProtocol={0:`tls`,1:`tcp`,2:`udp`}[t.priority>>24])}return e})}function Jv(e,t){if(!e.RTCPeerConnection)return;`sctp`in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,`sctp`,{get(){return this._sctp===void 0?null:this._sctp}});let n=function(e){if(!e||!e.sdp)return!1;let t=Wv.splitSections(e.sdp);return t.shift(),t.some(e=>{let t=Wv.parseMLine(e);return t&&t.kind===`application`&&t.protocol.indexOf(`SCTP`)!==-1})},r=function(e){let t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(t===null||t.length<2)return-1;let n=parseInt(t[1],10);return n===n?n:-1},i=function(e){let n=65536;return t.browser===`firefox`&&(n=t.version<57?e===-1?16384:2147483637:t.version<60?t.version===57?65535:65536:2147483637),n},a=function(e,n){let r=65536;t.browser===`firefox`&&t.version===57&&(r=65535);let i=Wv.matchPrefix(e.sdp,`a=max-message-size:`);return i.length>0?r=parseInt(i[0].substring(19),10):t.browser===`firefox`&&n!==-1&&(r=2147483637),r},o=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,t.browser===`chrome`&&t.version>=76){let{sdpSemantics:e}=this.getConfiguration();e===`plan-b`&&Object.defineProperty(this,`sctp`,{get(){return this._sctp===void 0?null:this._sctp},enumerable:!0,configurable:!0})}if(n(arguments[0])){let e=r(arguments[0]),t=i(e),n=a(arguments[0],e),o;o=t===0&&n===0?1/0:t===0||n===0?Math.max(t,n):Math.min(t,n);let s={};Object.defineProperty(s,`maxMessageSize`,{get(){return o}}),this._sctp=s}return o.apply(this,arguments)}}function Yv(e){if(!(e.RTCPeerConnection&&`createDataChannel`in e.RTCPeerConnection.prototype))return;function t(e,t){let n=e.send;e.send=function(){let r=arguments[0],i=r.length||r.size||r.byteLength;if(e.readyState===`open`&&t.sctp&&i>t.sctp.maxMessageSize)throw TypeError(`Message too large (can send a maximum of `+t.sctp.maxMessageSize+` bytes)`);return n.apply(e,arguments)}}let n=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){let e=n.apply(this,arguments);return t(e,this),e},X_(e,`datachannel`,e=>(t(e.channel,e.target),e))}function Xv(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 n=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 n=new Event(`connectionstatechange`,e);t.dispatchEvent(n)}return e},this.addEventListener(`iceconnectionstatechange`,this._connectionstatechangepoly)),n.apply(this,arguments)}})}function Zv(e,t){if(!e.RTCPeerConnection||t.browser===`chrome`&&t.version>=71||t.browser===`safari`&&t._safariVersion>=13.1)return;let n=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&t.sdp.indexOf(`
58
58
  a=extmap-allow-mixed`)!==-1){let n=t.sdp.split(`
59
59
  `).filter(e=>e.trim()!==`a=extmap-allow-mixed`).join(`
60
- `);e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:n}):t.sdp=n}return n.apply(this,arguments)}}function Jv(e,t){if(!(e.RTCPeerConnection&&e.RTCPeerConnection.prototype))return;let n=e.RTCPeerConnection.prototype.addIceCandidate;!n||n.length===0||(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(t.browser===`chrome`&&t.version<78||t.browser===`firefox`&&t.version<68||t.browser===`safari`)&&arguments[0]&&arguments[0].candidate===``?Promise.resolve():n.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function Yv(e,t){if(!(e.RTCPeerConnection&&e.RTCPeerConnection.prototype))return;let n=e.RTCPeerConnection.prototype.setLocalDescription;!n||n.length===0||(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if(typeof e!=`object`||e.type&&e.sdp)return n.apply(this,arguments);if(e={type:e.type,sdp:e.sdp},!e.type)switch(this.signalingState){case`stable`:case`have-local-offer`:case`have-remote-pranswer`:e.type=`offer`;break;default:e.type=`answer`;break}return e.sdp||e.type!==`offer`&&e.type!==`answer`?n.apply(this,[e]):(e.type===`offer`?this.createOffer:this.createAnswer).apply(this).then(e=>n.apply(this,[e]))})}var Xv=Object.freeze({__proto__:null,removeExtmapAllowMixed:qv,shimAddIceCandidateNullOrEmpty:Jv,shimConnectionState:Kv,shimMaxMessageSize:Wv,shimParameterlessSetLocalDescription:Yv,shimRTCIceCandidate:Hv,shimRTCIceCandidateRelayProtocol:Uv,shimSendThrowTypeError:Gv});function Zv(){let{window:e}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0},n=Y_,r=Z_(e),i={browserDetails:r,commonShim:Xv,extractVersion:G_,disableLog:q_,disableWarnings:J_,sdp:Vv};switch(r.browser){case`chrome`:if(!fv||!uv||!t.shimChrome)return n(`Chrome shim is not included in this adapter release.`),i;if(r.version===null)return n(`Chrome shim can not determine version, not shimming.`),i;n(`adapter.js shimming chrome.`),i.browserShim=fv,Jv(e,r),Yv(e),rv(e,r),iv(e),uv(e,r),av(e),lv(e,r),ov(e),sv(e),dv(e,r),Hv(e),Uv(e),Kv(e),Wv(e,r),Gv(e),qv(e,r);break;case`firefox`:if(!Tv||!gv||!t.shimFirefox)return n(`Firefox shim is not included in this adapter release.`),i;n(`adapter.js shimming firefox.`),i.browserShim=Tv,Jv(e,r),Yv(e),pv(e,r),gv(e,r),hv(e),yv(e),_v(e),vv(e),bv(e),xv(e),Sv(e),Cv(e),wv(e),Hv(e),Kv(e),Wv(e,r),Gv(e);break;case`safari`:if(!Fv||!t.shimSafari)return n(`Safari shim is not included in this adapter release.`),i;n(`adapter.js shimming safari.`),i.browserShim=Fv,Jv(e,r),Yv(e),jv(e),Nv(e),Ov(e),Ev(e),Dv(e),Mv(e),kv(e),Pv(e),Hv(e),Uv(e),Wv(e,r),Gv(e),qv(e,r);break;default:n(`Unsupported browser!`);break}return i}Zv({window:typeof window>`u`?void 0:window});var Qv,$v,ey=class extends ($v=Promise){constructor(e){super(e)}catch(e){return super.catch(e)}static reject(e){return super.reject(e)}static all(e){return super.all(e)}static race(e){return super.race(e)}};Qv=ey,ey.resolve=e=>Reflect.get($v,`resolve`,Qv).call(Qv,e);var ty=/version\/(\d+(\.?_?\d+)+)/i,ny;function ry(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(e===void 0&&typeof navigator>`u`)return;let n=(e??navigator.userAgent).toLowerCase();return(ny===void 0||t)&&(ny=iy.find(e=>{let{test:t}=e;return t.test(n)})?.describe(n)),ny}var iy=[{test:/firefox|iceweasel|fxios/i,describe(e){return{name:`Firefox`,version:ay(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes(`fxios`)?`iOS`:void 0,osVersion:oy(e)}}},{test:/chrom|crios|crmo/i,describe(e){return{name:`Chrome`,version:ay(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes(`crios`)?`iOS`:void 0,osVersion:oy(e)}}},{test:/safari|applewebkit/i,describe(e){return{name:`Safari`,version:ay(ty,e),os:e.includes(`mobile/`)?`iOS`:`macOS`,osVersion:oy(e)}}}];function ay(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,r=t.match(e);return r&&r.length>=n&&r[n]||``}function oy(e){return e.includes(`mac os`)?ay(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,`.`):void 0}var sy=`2.18.1`,cy=class extends Error{constructor(e,t,n){super(t||`an error has occurred`),this.name=`LiveKitError`,this.code=e,n?.cause!==void 0&&(this.cause=n?.cause)}},ly=class extends cy{},R;(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`,e[e.WebSocket=6]=`WebSocket`,e[e.ServiceNotFound=7]=`ServiceNotFound`})(R||={});var z=class e extends ly{constructor(e,t,n,r){super(1,e),this.name=`ConnectionError`,this.status=n,this.reason=t,this.context=r,this.reasonName=R[t]}static notAllowed(t,n,r){return new e(t,R.NotAllowed,n,r)}static timeout(t){return new e(t,R.Timeout)}static leaveRequest(t,n){return new e(t,R.LeaveRequest,void 0,n)}static internal(t,n){return new e(t,R.InternalError,void 0,n)}static cancelled(t){return new e(t,R.Cancelled)}static serverUnreachable(t,n){return new e(t,R.ServerUnreachable,n)}static websocket(t,n,r){return new e(t,R.WebSocket,n,r)}static serviceNotFound(t,n){return new e(t,R.ServiceNotFound,void 0,n)}},uy=class extends cy{constructor(e){super(21,e??`device is unsupported`),this.name=`DeviceUnsupportedError`}},dy=class extends cy{constructor(e){super(20,e??`track is invalid`),this.name=`TrackInvalidError`}},fy=class extends cy{constructor(e){super(10,e??`unsupported server`),this.name=`UnsupportedServer`}},py=class extends cy{constructor(e){super(12,e??`unexpected connection state`),this.name=`UnexpectedConnectionState`}},my=class extends cy{constructor(e){super(13,e??`unable to negotiate`),this.name=`NegotiationError`}},hy=class extends cy{constructor(e,t){super(15,e),this.name=`PublishTrackError`,this.status=t}},gy=class extends ly{constructor(e,t){super(15,e),this.name=`SignalRequestError`,this.reason=t,this.reasonName=typeof t==`string`?t:p_[t]}},_y;(function(e){e[e.AlreadyOpened=0]=`AlreadyOpened`,e[e.AbnormalEnd=1]=`AbnormalEnd`,e[e.DecodeFailed=2]=`DecodeFailed`,e[e.LengthExceeded=3]=`LengthExceeded`,e[e.Incomplete=4]=`Incomplete`,e[e.HandlerAlreadyRegistered=7]=`HandlerAlreadyRegistered`,e[e.EncryptionTypeMismatch=8]=`EncryptionTypeMismatch`})(_y||={});var vy=class extends ly{constructor(e,t){super(16,e),this.name=`DataStreamError`,this.reason=t,this.reasonName=_y[t]}},yy=class extends cy{constructor(e){super(18,e),this.name=`SignalReconnectError`}},by;(function(e){e.PermissionDenied=`PermissionDenied`,e.NotFound=`NotFound`,e.DeviceInUse=`DeviceInUse`,e.Other=`Other`})(by||={}),(function(e){function t(t){if(t&&`name`in t)return t.name===`NotFoundError`||t.name===`DevicesNotFoundError`?e.NotFound:t.name===`NotAllowedError`||t.name===`PermissionDeniedError`?e.PermissionDenied:t.name===`NotReadableError`||t.name===`TrackStartError`?e.DeviceInUse:e.Other}e.getFailure=t})(by||={});var xy=class{};xy.setTimeout=function(){return setTimeout(...arguments)},xy.setInterval=function(){return setInterval(...arguments)},xy.clearTimeout=function(){return clearTimeout(...arguments)},xy.clearInterval=function(){return clearInterval(...arguments)};var B;(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`,e.DataTrackPublished=`dataTrackPublished`,e.DataTrackUnpublished=`dataTrackUnpublished`,e.LocalDataTrackPublished=`localDataTrackPublished`,e.LocalDataTrackUnpublished=`localDataTrackUnpublished`})(B||={});var V;(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`})(V||={});var H;(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`,e.PublishDataTrackResponse=`publishDataTrackResponse`,e.UnPublishDataTrackResponse=`unPublishDataTrackResponse`,e.DataTrackSubscriberHandles=`dataTrackSubscriberHandles`,e.DataTrackPacketReceived=`dataTrackPacketReceived`,e.Joined=`joined`})(H||={});var U;(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`})(U||={});function Sy(e){return e===void 0?e:typeof structuredClone==`function`?typeof e==`object`&&e?structuredClone(Object.assign({},e)):structuredClone(e):JSON.parse(JSON.stringify(e))}var W=class{constructor(e,t,n,r,i){if(typeof e==`object`)this.width=e.width,this.height=e.height,this.aspectRatio=e.aspectRatio,this.encoding={maxBitrate:e.maxBitrate,maxFramerate:e.maxFramerate,priority:e.priority};else if(t!==void 0&&n!==void 0)this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:n,maxFramerate:r,priority:i};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}}},Cy=[`vp8`,`h264`],wy=[`vp8`,`h264`,`vp9`,`av1`,`h265`];function Ty(e){return!!Cy.find(t=>t===e)}var Ey=Ty,Dy;(function(e){e[e.PREFER_REGRESSION=0]=`PREFER_REGRESSION`,e[e.SIMULCAST=1]=`SIMULCAST`,e[e.REGRESSION=2]=`REGRESSION`})(Dy||={});var Oy;(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}})(Oy||={});var ky={h90:new W(160,90,9e4,20),h180:new W(320,180,16e4,20),h216:new W(384,216,18e4,20),h360:new W(640,360,45e4,20),h540:new W(960,540,8e5,25),h720:new W(1280,720,17e5,30),h1080:new W(1920,1080,3e6,30),h1440:new W(2560,1440,5e6,30),h2160:new W(3840,2160,8e6,30)},Ay={h120:new W(160,120,7e4,20),h180:new W(240,180,125e3,20),h240:new W(320,240,14e4,20),h360:new W(480,360,33e4,20),h480:new W(640,480,5e5,20),h540:new W(720,540,6e5,25),h720:new W(960,720,13e5,30),h1080:new W(1440,1080,23e5,30),h1440:new W(1920,1440,38e5,30)},jy={h360fps3:new W(640,360,2e5,3,`medium`),h360fps15:new W(640,360,4e5,15,`medium`),h720fps5:new W(1280,720,8e5,5,`medium`),h720fps15:new W(1280,720,15e5,15,`medium`),h720fps30:new W(1280,720,2e6,30,`medium`),h1080fps15:new W(1920,1080,25e5,15,`medium`),h1080fps30:new W(1920,1080,5e6,30,`medium`),original:new W(0,0,7e6,30,`medium`)};function My(e,t,n){var r,i;let{optionsWithoutProcessor:a,audioProcessor:o,videoProcessor:s}=Wy(e??{}),c=t?.processor,l=n?.processor,u=a??{};return u.audio===!0&&(u.audio={}),u.video===!0&&(u.video={}),u.audio&&(Ny(u.audio,t),(r=u.audio).deviceId??(r.deviceId={ideal:`default`}),(o||c)&&(u.audio.processor=o??c)),u.video&&(Ny(u.video,n),(i=u.video).deviceId??(i.deviceId={ideal:`default`}),(s||l)&&(u.video.processor=s??l)),u}function Ny(e,t){return Object.keys(t).forEach(n=>{e[n]===void 0&&(e[n]=t[n])}),e}function Py(e){var t,n;let r={};if(e.video)if(typeof e.video==`object`){let n={},i=n,a=e.video;Object.keys(a).forEach(e=>{switch(e){case`resolution`:Ny(i,a.resolution);break;default:i[e]=a[e]}}),r.video=n,(t=r.video).deviceId??(t.deviceId={ideal:`default`})}else r.video=e.video?{deviceId:{ideal:`default`}}:!1;else r.video=!1;return e.audio?typeof e.audio==`object`?(r.audio=e.audio,(n=r.audio).deviceId??(n.deviceId={ideal:`default`})):r.audio={deviceId:{ideal:`default`}}:r.audio=!1,r}function Fy(e){return L(this,arguments,void 0,function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return function*(){let n=Iy();if(n){let r=n.createAnalyser();r.fftSize=2048;let i=r.frequencyBinCount,a=new Uint8Array(i);n.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(r),yield nb(t),r.getByteTimeDomainData(a);let o=a.some(e=>e!==128&&e!==0);return n.close(),!o}return!1}()})}function Iy(){let e=typeof window<`u`&&(window.AudioContext||window.webkitAudioContext);if(e){let t=new e({latencyHint:`interactive`});if(t.state===`suspended`&&typeof window<`u`&&window.document?.body){let e=()=>L(this,void 0,void 0,function*(){var n;try{t.state===`suspended`&&(yield t.resume())}catch(e){console.warn(`Error trying to auto-resume audio context`,e)}finally{(n=window.document.body)==null||n.removeEventListener(`click`,e)}});t.addEventListener(`statechange`,()=>{var n;t.state===`closed`&&((n=window.document.body)==null||n.removeEventListener(`click`,e))}),window.document.body.addEventListener(`click`,e)}return t}}function Ly(e){return e===`audioinput`?K.Source.Microphone:e===`videoinput`?K.Source.Camera:K.Source.Unknown}function Ry(e){if(e===K.Source.Microphone)return`audioinput`;if(e===K.Source.Camera)return`videoinput`}function zy(e){let t=e.video??!0;return e.resolution&&e.resolution.width>0&&e.resolution.height>0&&(t=typeof t==`boolean`?{}:t,t=fb()?Object.assign(Object.assign({},t),{width:{max:e.resolution.width},height:{max:e.resolution.height},frameRate:e.resolution.frameRate}):Object.assign(Object.assign({},t),{width:{ideal:e.resolution.width},height:{ideal:e.resolution.height},frameRate:e.resolution.frameRate})),{audio:e.audio??!1,video:t,controller:e.controller,selfBrowserSurface:e.selfBrowserSurface,surfaceSwitching:e.surfaceSwitching,systemAudio:e.systemAudio,preferCurrentTab:e.preferCurrentTab}}function By(e){return e.split(`/`)[1].toLowerCase()}function Vy(e){let t=[];return e.forEach(e=>{e.track!==void 0&&t.push(new Og({cid:e.track.mediaStreamID,track:e.trackInfo}))}),t}function G(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?G(e.track):{})}}function Hy(){return typeof RTCRtpReceiver<`u`&&`getSynchronizationSources`in RTCRtpReceiver}function Uy(e,t){e===void 0&&(e={}),t===void 0&&(t={});let n=[...Object.keys(t),...Object.keys(e)],r={};for(let i of n)e[i]!==t[i]&&(r[i]=t[i]??``);return r}function Wy(e){let t=Object.assign({},e),n,r;return typeof t.audio==`object`&&t.audio.processor&&(n=t.audio.processor,t.audio=Object.assign(Object.assign({},t.audio),{processor:void 0})),typeof t.video==`object`&&t.video.processor&&(r=t.video.processor,t.video=Object.assign(Object.assign({},t.video),{processor:void 0})),{audioProcessor:n,videoProcessor:r,optionsWithoutProcessor:Sy(t)}}function Gy(e){switch(e){case ph.CAMERA:return K.Source.Camera;case ph.MICROPHONE:return K.Source.Microphone;case ph.SCREEN_SHARE:return K.Source.ScreenShare;case ph.SCREEN_SHARE_AUDIO:return K.Source.ScreenShareAudio;default:return K.Source.Unknown}}function Ky(e,t){return e.width*e.height<t.width*t.height}function qy(e,t){return e.layers?.find(e=>e.quality===t)}var Jy=5e3,Yy=[],Xy;(function(e){e[e.LOW=0]=`LOW`,e[e.MEDIUM=1]=`MEDIUM`,e[e.HIGH=2]=`HIGH`})(Xy||={});var K=class e extends H_.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState=e}constructor(t,n){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.attachedElements=[],this.isMuted=!1,this._streamState=e.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=I,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState===`hidden`?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),Jy):this.handleAppVisibilityChanged()},this.log=O_(r.loggerName??D_.Track),this.loggerContextCb=r.loggerContextCb,this.setMaxListeners(100),this.kind=n,this._mediaStreamTrack=t,this._mediaStreamID=t.id,this.source=e.Source.Unknown}get logContext(){return Object.assign(Object.assign({},this.loggerContextCb?.call(this)),G(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(t){let n=`audio`;this.kind===e.Kind.Video&&(n=`video`),this.attachedElements.length===0&&this.kind===e.Kind.Video&&this.addAppVisibilityListener(),t||(n===`audio`&&(Yy.forEach(e=>{e.parentElement===null&&!t&&(t=e)}),t&&Yy.splice(Yy.indexOf(t),1)),t||=document.createElement(n)),this.attachedElements.includes(t)||this.attachedElements.push(t),Zy(this.mediaStreamTrack,t);let r=t.srcObject.getTracks(),i=r.some(e=>e.kind===`audio`);return t.play().then(()=>{this.emit(i?U.AudioPlaybackStarted:U.VideoPlaybackStarted)}).catch(e=>{e.name===`NotAllowedError`?this.emit(i?U.AudioPlaybackFailed:U.VideoPlaybackFailed,e):e.name===`AbortError`?I.debug(`${i?`audio`:`video`} playback aborted, likely due to new play request`):I.warn(`could not playback ${i?`audio`:`video`}`,e),i&&t&&r.some(e=>e.kind===`video`)&&e.name===`NotAllowedError`&&(t.muted=!0,t.play().catch(()=>{}))}),this.emit(U.ElementAttached,t),t}detach(e){try{if(e){Qy(this.mediaStreamTrack,e);let t=this.attachedElements.indexOf(e);return t>=0&&(this.attachedElements.splice(t,1),this.recycleElement(e),this.emit(U.ElementDetached,e)),e}let t=[];return this.attachedElements.forEach(e=>{Qy(this.mediaStreamTrack,e),t.push(e),this.recycleElement(e),this.emit(U.ElementDetached,e)}),this.attachedElements=[],t}finally{this.attachedElements.length===0&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(e){e.loggerName&&(this.log=O_(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),Yy.forEach(e=>{e.parentElement||(t=!1)}),t&&Yy.push(e)}}handleAppVisibilityChanged(){return L(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState===`hidden`,!this.isInBackground&&this.kind===e.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){vb()?(this.isInBackground=document.visibilityState===`hidden`,document.addEventListener(`visibilitychange`,this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){vb()&&document.removeEventListener(`visibilitychange`,this.appVisibilityChangedListener)}};function Zy(e,t){let n;n=t.srcObject instanceof MediaStream?t.srcObject:new MediaStream;let r;r=e.kind===`audio`?n.getAudioTracks():n.getVideoTracks(),r.includes(e)||(r.forEach(e=>{n.removeTrack(e)}),n.addTrack(e)),(!fb()||!(t instanceof HTMLVideoElement))&&(t.autoplay=!0),t.muted=n.getAudioTracks().length===0,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==n&&(t.srcObject=n,(fb()||ub())&&t instanceof HTMLVideoElement&&setTimeout(()=>{t.srcObject=n,t.play().catch(()=>{})},0))}function Qy(e,t){if(t.srcObject instanceof MediaStream){let n=t.srcObject;n.removeTrack(e),n.getTracks().length>0?t.srcObject=n:t.srcObject=null}}(function(e){let t;(function(e){e.Audio=`audio`,e.Video=`video`,e.Unknown=`unknown`})(t=e.Kind||={});let n;(function(e){e.Camera=`camera`,e.Microphone=`microphone`,e.ScreenShare=`screen_share`,e.ScreenShareAudio=`screen_share_audio`,e.Unknown=`unknown`})(n=e.Source||={});let r;(function(e){e.Active=`active`,e.Paused=`paused`,e.Unknown=`unknown`})(r=e.StreamState||={});function i(e){switch(e){case t.Audio:return fh.AUDIO;case t.Video:return fh.VIDEO;default:return fh.DATA}}e.kindToProto=i;function a(e){switch(e){case fh.AUDIO:return t.Audio;case fh.VIDEO:return t.Video;default:return t.Unknown}}e.kindFromProto=a;function o(e){switch(e){case n.Camera:return ph.CAMERA;case n.Microphone:return ph.MICROPHONE;case n.ScreenShare:return ph.SCREEN_SHARE;case n.ScreenShareAudio:return ph.SCREEN_SHARE_AUDIO;default:return ph.UNKNOWN}}e.sourceToProto=o;function s(e){switch(e){case ph.CAMERA:return n.Camera;case ph.MICROPHONE:return n.Microphone;case ph.SCREEN_SHARE:return n.ScreenShare;case ph.SCREEN_SHARE_AUDIO:return n.ScreenShareAudio;default:return n.Unknown}}e.sourceFromProto=s;function c(e){switch(e){case fg.ACTIVE:return r.Active;case fg.PAUSED:return r.Paused;default:return r.Unknown}}e.streamStateFromProto=c})(K||={});var $y=`|`,eb=`https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension`;function tb(e){let t=e.split($y);return t.length>1?[t[0],e.substr(t[0].length+1)]:[e,``]}function nb(e){return new ey(t=>xy.setTimeout(t,e))}function rb(){return`addTransceiver`in RTCPeerConnection.prototype}function ib(){return`addTrack`in RTCPeerConnection.prototype}function ab(){if(!(`getCapabilities`in RTCRtpSender)||fb()||ub())return!1;let e=RTCRtpSender.getCapabilities(`video`),t=!1;if(e){for(let n of e.codecs)if(n.mimeType.toLowerCase()===`video/av1`){t=!0;break}}return t}function ob(){if(!(`getCapabilities`in RTCRtpSender)||ub())return!1;if(fb()){let e=ry();if(e?.version&&Tb(e.version,`16`)<0||e?.os===`iOS`&&e?.osVersion&&Tb(e.osVersion,`16`)<0)return!1}let e=RTCRtpSender.getCapabilities(`video`),t=!1;if(e){for(let n of e.codecs)if(n.mimeType.toLowerCase()===`video/vp9`){t=!0;break}}return t}function sb(e){return e===`av1`||e===`vp9`}function cb(e){return!document||pb()?!1:(e||=document.createElement(`audio`),`setSinkId`in e)}function lb(){return typeof RTCPeerConnection>`u`?!1:rb()||ib()}function ub(){return ry()?.name===`Firefox`}function db(){let e=ry();return!!e&&e.name===`Chrome`&&e.os!==`iOS`}function fb(){return ry()?.name===`Safari`}function pb(){let e=ry();return e?.name===`Safari`||e?.os===`iOS`}function mb(){let e=ry();return e?.name===`Safari`&&e.version.startsWith(`17.`)||e?.os===`iOS`&&!!e?.osVersion&&Tb(e.osVersion,`17`)>=0}function hb(e){return e||=ry(),e?.name===`Safari`&&Tb(e.version,`18.3`)>0||e?.os===`iOS`&&!!e?.osVersion&&Tb(e.osVersion,`18.3`)>0}function gb(){return vb()?navigator.userAgentData?.mobile??/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function _b(){let e=ry(),t=`17.2`;if(e)return e.name!==`Safari`&&e.os!==`iOS`||e.os===`iOS`&&e.osVersion&&Tb(e.osVersion,t)>=0?!0:e.name===`Safari`&&Tb(e.version,t)>=0}function vb(){return typeof document<`u`}function yb(){return navigator.product==`ReactNative`}function bb(e){return e.hostname.endsWith(`.livekit.cloud`)||e.hostname.endsWith(`.livekit.run`)}function xb(e){return bb(e)?e.hostname.split(`.`)[0]:null}function Sb(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function Cb(){if(!yb())return;let e=Sb();if(e)return e.platform}function wb(){if(vb())return window.devicePixelRatio;if(yb()){let e=Sb();if(e)return e.devicePixelRatio}return 1}function Tb(e,t){let n=e.split(`.`),r=t.split(`.`),i=Math.min(n.length,r.length);for(let e=0;e<i;++e){let t=parseInt(n[e],10),a=parseInt(r[e],10);if(t>a)return 1;if(t<a)return-1;if(e===i-1&&t===a)return 0}return e===``&&t!==``?-1:t===``?1:n.length==r.length?0:n.length<r.length?-1:1}function Eb(e){for(let t of e)t.target.handleResize(t)}function Db(e){for(let t of e)t.target.handleVisibilityChanged(t)}var Ob=null,kb=()=>(Ob||=new ResizeObserver(Eb),Ob),Ab=null,jb=()=>(Ab||=new IntersectionObserver(Db,{root:null,rootMargin:`0px`}),Ab);function Mb(){let e=new Qh({sdk:$h.JS,protocol:16,version:sy});return yb()&&(e.os=Cb()??``),e}function Nb(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:16,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:16,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,i=document.createElement(`canvas`);i.width=e,i.height=t;let a=i.getContext(`2d`);a?.fillRect(0,0,i.width,i.height),r&&a&&(a.beginPath(),a.arc(e/2,t/2,50,0,Math.PI*2,!0),a.closePath(),a.fillStyle=`grey`,a.fill());let[o]=i.captureStream().getTracks();if(!o)throw Error(`Could not get empty media stream video track`);return o.enabled=n,o}var Pb;function Fb(){if(!Pb){let e=new AudioContext,t=e.createOscillator(),n=e.createGain();n.gain.setValueAtTime(0,0);let r=e.createMediaStreamDestination();if(t.connect(n),n.connect(r),t.start(),[Pb]=r.stream.getAudioTracks(),!Pb)throw Error(`Could not get empty media stream audio track`);Pb.enabled=!1}return Pb.clone()}var Ib=class{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise((t,n)=>L(this,void 0,void 0,function*(){this.resolve=t,this.reject=n,e&&(yield e(t,n))})).finally(()=>{var e;this._isResolved=!0,(e=this.onFinally)==null||e.call(this)})}};function Lb(e){return wy.includes(e)}function Rb(e){if(typeof e==`string`||typeof e==`number`)return e;if(Array.isArray(e))return e[0];if(e.exact!==void 0)return Array.isArray(e.exact)?e.exact[0]:e.exact;if(e.ideal!==void 0)return Array.isArray(e.ideal)?e.ideal[0]:e.ideal;throw Error(`could not unwrap constraint`)}function zb(e){return e.startsWith(`http`)?e.replace(/^(http)/,`ws`):e}function Bb(e){return e.startsWith(`ws`)?e.replace(/^(ws)/,`http`):e}function Vb(e,t){return e.segments.map(e=>{let{id:n,text:r,language:i,startTime:a,endTime:o,final:s}=e,c=t.get(n)??Date.now(),l=Date.now();return s?t.delete(n):t.set(n,c),{id:n,text:r,startTime:Number.parseInt(a.toString()),endTime:Number.parseInt(o.toString()),final:s,language:i,firstReceivedTime:c,lastReceivedTime:l}})}function Hb(e){let{id:t,timestamp:n,message:r,editTimestamp:i}=e;return{id:t,timestamp:Number.parseInt(n.toString()),editTimestamp:i?Number.parseInt(i.toString()):void 0,message:r}}function Ub(e){switch(e.reason){case R.LeaveRequest:return e.context;case R.Cancelled:return _h.CLIENT_INITIATED;case R.NotAllowed:return _h.USER_REJECTED;case R.ServerUnreachable:return _h.JOIN_FAILURE;default:return _h.UNKNOWN_REASON}}function Wb(e){return e===void 0?void 0:Number(e)}function Gb(e){return e===void 0?void 0:BigInt(e)}function Kb(e){return!!e&&!(e instanceof MediaStreamTrack)&&e.isLocal}function qb(e){return!!e&&e.kind==K.Kind.Audio}function Jb(e){return!!e&&e.kind==K.Kind.Video}function Yb(e){return Kb(e)&&Jb(e)}function Xb(e){return Kb(e)&&qb(e)}function Zb(e){return!!e&&!e.isLocal}function Qb(e){return!!e&&!e.isLocal}function $b(e){return Zb(e)&&Jb(e)}function ex(e){return e.isLocal}function tx(e,t){let n=[],r=new TextEncoder().encode(e);for(;r.length>t;){let e=t;for(;e>0;){let t=r[e];if(t!==void 0&&(t&192)!=128)break;e--}n.push(r.slice(0,e)),r=r.slice(e)}return r.length>0&&n.push(r),n}function nx(e){let t=e.get(`Cache-Control`);if(t){let e=t.match(/(?:^|[,\s])max-age=(\d+)/)?.[1];if(e)return parseInt(e,10)}}function rx(){return typeof CompressionStream<`u`}function ix(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,r=ax(e,t);return n?r:cx(r,`v1`)}function ax(e,t){let n=new URL(zb(e));return t.forEach((e,t)=>{n.searchParams.set(t,e)}),cx(n,`rtc`)}function ox(e){return cx(new URL(Bb(e)),`validate`)}function sx(e){return e.endsWith(`/`)?e:`${e}/`}function cx(e,t){return e.pathname=`${sx(e.pathname)}${t}`,e}function lx(e){if(typeof e==`string`)return hg.fromJson(JSON.parse(e),{ignoreUnknownFields:!0});if(e instanceof ArrayBuffer)return hg.fromBinary(new Uint8Array(e));throw Error(`could not decode websocket message: ${typeof e}`)}function ux(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:`Unknown reason`;if(!(e instanceof AbortSignal))return t;let n=e.reason;switch(typeof n){case`string`:return n;case`object`:return n instanceof Error?n.message:t;default:return`toString`in n?n.toString():t}}var dx=`lk_e2ee`,fx;(function(e){e.SetKey=`setKey`,e.RatchetRequest=`ratchetRequest`,e.KeyRatcheted=`keyRatcheted`})(fx||={});var px;(function(e){e.KeyRatcheted=`keyRatcheted`})(px||={});var mx;(function(e){e.ParticipantEncryptionStatusChanged=`participantEncryptionStatusChanged`,e.EncryptionError=`encryptionError`})(mx||={});var hx;(function(e){e.Error=`cryptorError`})(hx||={});function gx(){return vx()||_x()}function _x(){return window.RTCRtpScriptTransform!==void 0}function vx(){return window.RTCRtpSender!==void 0&&window.RTCRtpSender.prototype.createEncodedStreams!==void 0}function yx(e){if(e.value?.case!==`sipDtmf`&&e.value?.case!==`metrics`&&e.value?.case!==`speaker`&&e.value?.case!==`transcription`&&e.value?.case!==`encryptedPacket`)return new Lh({value:e.value})}H_.EventEmitter;var bx;(function(e){e[e.InvalidKey=0]=`InvalidKey`,e[e.MissingKey=1]=`MissingKey`,e[e.InternalError=2]=`InternalError`})(bx||={});var xx=class extends H_.EventEmitter{constructor(e,t){super(),this.decryptDataRequests=new Map,this.encryptDataRequests=new Map,this.onWorkerMessage=e=>{let{kind:t,data:n}=e.data;switch(t){case`error`:if(I.error(n.error.message),n.uuid){let e=this.decryptDataRequests.get(n.uuid);if(e?.reject){e.reject(n.error);break}let t=this.encryptDataRequests.get(n.uuid);if(t?.reject){t.reject(n.error);break}}this.emit(mx.EncryptionError,n.error,n.participantIdentity);break;case`initAck`:n.enabled&&this.keyProvider.getKeys().forEach(e=>{this.postKey(e,!1)});break;case`enable`:if(n.enabled&&this.keyProvider.getKeys().forEach(e=>{this.postKey(e,!1)}),this.encryptionEnabled!==n.enabled&&n.participantIdentity===this.room?.localParticipant.identity)this.emit(mx.ParticipantEncryptionStatusChanged,n.enabled,this.room.localParticipant),this.encryptionEnabled=n.enabled;else if(n.participantIdentity){let e=this.room?.getParticipantByIdentity(n.participantIdentity);if(!e)throw TypeError(`couldn't set encryption status, participant not found${n.participantIdentity}`);this.emit(mx.ParticipantEncryptionStatusChanged,n.enabled,e)}break;case`ratchetKey`:this.keyProvider.emit(fx.KeyRatcheted,n.ratchetResult,n.participantIdentity,n.keyIndex);break;case`decryptDataResponse`:let e=this.decryptDataRequests.get(n.uuid);e?.resolve&&e.resolve(n);break;case`encryptDataResponse`:let t=this.encryptDataRequests.get(n.uuid);t?.resolve&&t.resolve(n);break}},this.onWorkerError=e=>{I.error(`e2ee worker encountered an error:`,{error:e.error}),this.emit(mx.EncryptionError,e.error,void 0)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1,this.dataChannelEncryptionEnabled=t}get isEnabled(){return this.encryptionEnabled}get isDataChannelEncryptionEnabled(){return this.isEnabled&&this.dataChannelEncryptionEnabled}setup(e){if(!gx())throw new uy(`tried to setup end-to-end encryption on an unsupported browser`);if(I.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:k_.getLevel()}};this.worker&&(I.info(`initializing worker`,{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){I.debug(`set e2ee to ${e} for participant ${t}`),this.postEnable(e,t)}setSifTrailer(e){!e||e.length===0?I.warn(`ignoring server sent trailer as it's empty`):this.postSifTrailer(e)}setupEngine(e){e.on(H.RTPVideoMapUpdate,e=>{this.postRTPMap(e)})}setupEventListeners(e,t){e.on(B.TrackPublished,(e,t)=>this.setParticipantCryptorEnabled(e.trackInfo.encryption!==F.NONE,t.identity)),e.on(B.ConnectionStateChanged,t=>{t===Y.Connected&&e.remoteParticipants.forEach(e=>{e.trackPublications.forEach(t=>{this.setParticipantCryptorEnabled(t.trackInfo.encryption!==F.NONE,e.identity)})})}).on(B.TrackUnsubscribed,(e,t,n)=>{var r;let i={kind:`removeTransform`,data:{participantIdentity:n.identity,trackId:e.mediaStreamID}};(r=this.worker)==null||r.postMessage(i)}).on(B.TrackSubscribed,(e,t,n)=>{this.setupE2EEReceiver(e,n.identity,t.trackInfo)}).on(B.SignalConnected,()=>{if(!this.room)throw TypeError(`expected room to be present on signal connect`);let e=t.getLatestManuallySetKeyIndex();t.getKeys().forEach(t=>{this.postKey(t,e===(t.keyIndex??0))}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(V.LocalSenderCreated,(e,t)=>L(this,void 0,void 0,function*(){this.setupE2EESender(t,e)})),e.localParticipant.on(V.LocalTrackPublished,e=>{if(!Jb(e.track)||!pb())return;let t={kind:`updateCodec`,data:{trackId:e.track.mediaStreamID,codec:By(e.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(t)}),t.on(fx.SetKey,(e,t)=>this.postKey(e,t??!0)).on(fx.RatchetRequest,(e,t)=>this.postRatchetRequest(e,t))}encryptData(e){return L(this,void 0,void 0,function*(){if(!this.worker)throw Error(`could not encrypt data, worker is missing`);let t=crypto.randomUUID(),n={kind:`encryptDataRequest`,data:{uuid:t,payload:e,participantIdentity:this.room.localParticipant.identity}},r=new Ib;return r.onFinally=()=>{this.encryptDataRequests.delete(t)},this.encryptDataRequests.set(t,r),this.worker.postMessage(n),r.promise})}handleEncryptedData(e,t,n,r){if(!this.worker)throw Error(`could not handle encrypted data, worker is missing`);let i=crypto.randomUUID(),a={kind:`decryptDataRequest`,data:{uuid:i,payload:e,iv:t,participantIdentity:n,keyIndex:r}},o=new Ib;return o.onFinally=()=>{this.decryptDataRequests.delete(i)},this.decryptDataRequests.set(i,o),this.worker.postMessage(a),o.promise}postRatchetRequest(e,t){if(!this.worker)throw Error(`could not ratchet key, worker is missing`);let n={kind:`ratchetRequest`,data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(n)}postKey(e,t){let{key:n,participantIdentity:r,keyIndex:i}=e;if(!this.worker)throw Error(`could not set key, worker is missing`);let a={kind:`setKey`,data:{participantIdentity:r,isPublisher:r===this.room?.localParticipant.identity,key:n,keyIndex:i,updateCurrentKeyIndex:t}};this.worker.postMessage(a)}postEnable(e,t){if(this.worker){let n={kind:`enable`,data:{enabled:e,participantIdentity:t}};this.worker.postMessage(n)}else throw ReferenceError(`failed to enable e2ee, worker is not ready`)}postRTPMap(e){if(!this.worker)throw TypeError(`could not post rtp map, worker is missing`);if(!this.room?.localParticipant.identity)throw TypeError(`could not post rtp map, local participant identity is missing`);let t={kind:`setRTPMap`,data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(t)}postSifTrailer(e){if(!this.worker)throw Error(`could not post SIF trailer, worker is missing`);let t={kind:`setSifTrailer`,data:{trailer:e}};this.worker.postMessage(t)}setupE2EEReceiver(e,t,n){if(e.receiver){if(!n?.mimeType||n.mimeType===``)throw TypeError(`MimeType missing from trackInfo, cannot set up E2EE cryptor`);this.handleReceiver(e.receiver,e.mediaStreamID,t,e.kind===`video`?By(n.mimeType):void 0)}}setupE2EESender(e,t){if(!Kb(e)||!t){t||I.warn(`early return because sender is not ready`);return}this.handleSender(t,e.mediaStreamID,void 0)}handleReceiver(e,t,n,r){return L(this,void 0,void 0,function*(){if(this.worker){if(_x()&&!db()){let i={kind:`decode`,participantIdentity:n,trackId:t,codec:r};e.transform=new RTCRtpScriptTransform(this.worker,i)}else{if(dx in e&&r){let e={kind:`updateCodec`,data:{trackId:t,codec:r,participantIdentity:n}};this.worker.postMessage(e);return}let i=e.writableStream,a=e.readableStream;if(!i||!a){let t=e.createEncodedStreams();e.writableStream=t.writable,i=t.writable,e.readableStream=t.readable,a=t.readable}let o={kind:`decode`,data:{readableStream:a,writableStream:i,trackId:t,codec:r,participantIdentity:n,isReuse:dx in e}};this.worker.postMessage(o,[a,i])}e[dx]=!0}})}handleSender(e,t,n){if(!(dx in e||!this.worker)){if(!this.room?.localParticipant.identity||this.room.localParticipant.identity===``)throw TypeError(`local identity needs to be known in order to set up encrypted sender`);if(_x()&&!db()){I.info(`initialize script transform`);let r={kind:`encode`,participantIdentity:this.room.localParticipant.identity,trackId:t,codec:n};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{I.info(`initialize encoded streams`);let r=e.createEncodedStreams(),i={kind:`encode`,data:{readableStream:r.readable,writableStream:r.writable,codec:n,trackId:t,participantIdentity:this.room.localParticipant.identity,isReuse:!1}};this.worker.postMessage(i,[r.readable,r.writable])}e[dx]=!0}}},Sx=500,Cx=15e3,wx=class e{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||=new e,this._instance}addFailedConnectionAttempt(e){let t=xb(new URL(e));if(!t)return;let n=this.failedConnectionAttempts.get(t)??0;this.failedConnectionAttempts.set(t,n+1),this.backOffPromises.set(t,nb(Math.min(Sx*2**n,Cx)))}getBackOffPromise(e){let t=new URL(e),n=t&&xb(t);return n&&this.backOffPromises.get(n)||Promise.resolve()}resetFailedConnectionAttempts(e){let t=new URL(e),n=t&&xb(t);n&&(this.failedConnectionAttempts.set(n,0),this.backOffPromises.set(n,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}};wx._instance=null;var Tx=`default`,Ex=class e{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new e),this.instance}get previousDevices(){return this._previousDevices}getDevices(t){return L(this,arguments,void 0,function(t){var n=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){if(e.userMediaPromiseMap?.size>0){I.debug(`awaiting getUserMedia promise`);try{t?yield e.userMediaPromiseMap.get(t):yield Promise.all(e.userMediaPromiseMap.values())}catch{I.warn(`error waiting for media permissons`)}}let i=yield navigator.mediaDevices.enumerateDevices();if(r&&!(fb()&&n.hasDeviceInUse(t))&&(i.filter(e=>e.kind===t).length===0||i.some(e=>{let n=e.label===``,r=t?e.kind===t:!0;return n&&r}))){let e={video:t!==`audioinput`&&t!==`audiooutput`,audio:t!==`videoinput`&&{deviceId:{ideal:`default`}}},n=yield navigator.mediaDevices.getUserMedia(e);i=yield navigator.mediaDevices.enumerateDevices(),n.getTracks().forEach(e=>{e.stop()})}return n._previousDevices=i,t&&(i=i.filter(e=>e.kind===t)),i}()})}normalizeDeviceId(e,t,n){return L(this,void 0,void 0,function*(){if(t!==Tx)return t;let r=yield this.getDevices(e),i=r.find(e=>e.deviceId===Tx);if(!i){I.warn(`could not reliably determine default device`);return}let a=r.find(e=>e.deviceId!==Tx&&e.groupId===(n??i.groupId));if(!a){I.warn(`could not reliably determine default device`);return}return a?.deviceId})}hasDeviceInUse(t){return t?e.userMediaPromiseMap.has(t):e.userMediaPromiseMap.size>0}};Ex.mediaDeviceKinds=[`audioinput`,`audiooutput`,`videoinput`],Ex.userMediaPromiseMap=new Map;var Dx=65535,Ox=4294967295,kx=class e{static u16(t){return new e(t,Dx)}static u32(t){return new e(t,Ox)}constructor(e,t){if(this.value=e,e<0)throw Error(`WrapAroundUnsignedInt: cannot faithfully represent an integer smaller than 0`);if(t>2**53-1)throw Error(`WrapAroundUnsignedInt: cannot faithfully represent an integer bigger than MAX_SAFE_INTEGER.`);this.maxSize=t,this.clamp()}clamp(){for(;this.value>this.maxSize;)this.value-=this.maxSize+1;for(;this.value<0;)this.value+=this.maxSize+1}clone(){return new e(this.value,this.maxSize)}update(e){this.value=e(this.value),this.clamp()}increment(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1;this.update(t=>t+e)}decrement(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1;this.update(t=>t-e)}getThenIncrement(){let t=this.value;return this.increment(),new e(t,this.maxSize)}isBefore(e){let t=this.value>>>0,n=(e.value>>>0)-t>>>0;return n!==0&&n<this.maxSize+1}},Ax=class e{static fromRtpTicks(t){return new e(t,9e4)}static rtpRandom(){let t=Math.round(Math.random()*Ox);return e.fromRtpTicks(t)}constructor(e,t){this.timestamp=kx.u32(e),this.rateInHz=t}asTicks(){return this.timestamp.value}clone(){return new e(this.timestamp.value,this.rateInHz)}wrappingAdd(e){this.timestamp.increment(e)}isBefore(e){return this.timestamp.isBefore(e.timestamp)}},jx=class e{constructor(e,t,n){this.epoch=t,this.base=n,this.previous=n.clone(),this.rateInHz=e}static startingNow(t,n){return new e(n,new Date,t)}static startingAtTime(t,n,r){return new e(r,t,n)}static rtpStartingNow(t){return e.startingNow(t,9e4)}static rtpStartingAtTime(t,n){return e.startingAtTime(t,n,9e4)}now(){return this.at(new Date)}at(t){let n=t.getTime()-this.epoch.getTime(),r=e.durationInMsToTicks(n,this.rateInHz),i=this.base.clone();return i.wrappingAdd(r),i.isBefore(this.previous)&&(i=this.previous),this.previous=i.clone(),i.clone()}static durationInMsToTicks(e,t){let n=(e*1e6*t+5e8)/1e9;return Math.round(n)}};function Mx(e){if(e instanceof DataView)return e;if(e instanceof ArrayBuffer)return new DataView(e);if(e instanceof Uint8Array)return new DataView(e.buffer,e.byteOffset,e.byteLength);throw Error(`Error coercing ${e} to DataView - input was not DataView, ArrayBuffer, or Uint8Array.`)}var Nx;(function(e){e[e.Reserved=0]=`Reserved`,e[e.TooLarge=1]=`TooLarge`})(Nx||={});var Px=class e extends ly{constructor(e,t){super(19,e),this.name=`DataTrackHandleError`,this.reason=t,this.reasonName=Nx[t]}isReason(e){return this.reason===e}static tooLarge(){return new e(`Value too large to be a valid track handle`,Nx.TooLarge)}static reserved(t){return new e(`0x${t.toString(16)} is a reserved value.`,Nx.Reserved)}},Fx={fromNumber(e){if(e===0)throw Px.reserved(e);if(e>Dx)throw Px.tooLarge();return e}},Ix=class{constructor(){this.value=0}get(){return this.value+=1,this.value>Dx?null:this.value}},Lx={from(e){return{sid:e.sid,pubHandle:e.pubHandle,name:e.name,usesE2ee:e.encryption!==F.NONE}},toProtobuf(e){return new Ah({sid:e.sid,pubHandle:e.pubHandle,name:e.name,encryption:e.usesE2ee?F.GCM:F.NONE})}},Rx;(function(e){e[e.WAITING=0]=`WAITING`,e[e.RUNNING=1]=`RUNNING`,e[e.COMPLETED=2]=`COMPLETED`})(Rx||={});var zx=class{constructor(){this.pendingTasks=new Map,this.taskMutex=new dp,this.nextTaskIndex=0}run(e){return L(this,void 0,void 0,function*(){let t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:Rx.WAITING};this.pendingTasks.set(t.id,t);let n=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=Rx.RUNNING,yield e()}finally{t.status=Rx.COMPLETED,this.pendingTasks.delete(t.id),n()}})}flush(){return L(this,void 0,void 0,function*(){return this.run(()=>L(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}},Bx=class{get readyState(){return this.ws.readyState}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(t.signal?.aborted)throw new DOMException(`This operation was aborted`,`AbortError`);this.url=e;let n=new WebSocket(e,t.protocols??[]);n.binaryType=`arraybuffer`,this.ws=n;let r=function(){let{closeCode:e,reason:t}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return n.close(e,t)};this.opened=new ey((e,t)=>{let i=()=>{t(z.websocket(`Encountered websocket error during connection establishment`))};n.onopen=()=>{e({readable:new ReadableStream({start(e){n.onmessage=t=>{let{data:n}=t;return e.enqueue(n)},n.onerror=t=>e.error(t)},cancel:r}),writable:new WritableStream({write(e){n.send(e)},abort(){n.close()},close:r}),protocol:n.protocol,extensions:n.extensions}),n.removeEventListener(`error`,i)},n.addEventListener(`error`,i)}),this.closed=new ey((e,t)=>{let r=()=>L(this,void 0,void 0,function*(){let r=new ey(e=>{n.readyState!==WebSocket.CLOSED&&n.addEventListener(`close`,t=>{e(t)},{once:!0})}),i=yield ey.race([nb(250),r]);i?e(i):t(z.websocket(`Encountered unspecified websocket error without a timely close event`))});n.onclose=t=>{let{code:i,reason:a}=t;e({closeCode:i,reason:a}),n.removeEventListener(`error`,r)},n.addEventListener(`error`,r)}),t.signal&&(t.signal.onabort=()=>n.close()),this.close=r}},Vx=[`syncState`,`trickle`,`offer`,`answer`,`simulate`,`leave`];function Hx(e){let t=Vx.indexOf(e.case)>=0;return I.trace(`request allowed to bypass queue:`,{canPass:t,req:e}),t}var q;(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`})(q||={});var Ux=250,Wx=class{get currentState(){return this.state}get isDisconnected(){return this.state===q.DISCONNECTING||this.state===q.DISCONNECTED}get isEstablishingConnection(){return this.state===q.CONNECTING||this.state===q.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.rtt=0,this.state=q.DISCONNECTED,this.log=I,this._requestId=0,this.useV0SignalPath=!1,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0,this.onMediaSectionsRequirement=void 0},this.log=O_(t.loggerName??D_.Signal),this.loggerContextCb=t.loggerContextCb,this.useJSON=e,this.requestQueue=new zx,this.queuedRequests=[],this.closingLock=new dp,this.connectionLock=new dp,this.state=q.DISCONNECTED}get logContext(){return this.loggerContextCb?.call(this)??{}}join(e,t,n,r){return L(this,arguments,void 0,function(e,t,n,r){var i=this;let a=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1,o=arguments.length>5?arguments[5]:void 0;return function*(){return i.state=q.CONNECTING,i.options=n,yield i.connect(e,t,n,r,a,o)}()})}reconnect(e,t,n,r){return L(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=q.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:n,reconnectReason:r}),void 0,this.useV0SignalPath)})}connect(e,t,n,r){return L(this,arguments,void 0,function(e,t,n,r){var i=this;let a=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1,o=arguments.length>5?arguments[5]:void 0;return function*(){let s=yield i.connectionLock.lock();i.connectOptions=n,i.useV0SignalPath=a;let c=Mb(),l=ix(e,a?qx(t,c,n):yield Jx(t,c,n,o),a).toString(),u=ox(l).toString();return new Promise((e,t)=>L(i,void 0,void 0,function*(){try{let i=!1,a=e=>L(this,void 0,void 0,function*(){if(i)return;i=!0;let n=ux(e instanceof Event?e.currentTarget:e,`Abort handler called`);this.streamWriter&&!this.isDisconnected?this.sendLeave().then(()=>this.close(n)).catch(e=>{this.log.error(e),this.close()}):this.close(),o(),t(z.cancelled(n))});r?.addEventListener(`abort`,a);let o=()=>{clearTimeout(s),r?.removeEventListener(`abort`,a)},s=setTimeout(()=>{a(z.timeout(`room connection has timed out (signal)`))},n.websocketTimeout),c=(e,t)=>{this.handleSignalConnected(e,s,t)},d=new URL(l);d.searchParams.has(`access_token`)&&d.searchParams.set(`access_token`,`<redacted>`),this.log.debug(`connecting to ${d}`,Object.assign({reconnect:n.reconnect,reconnectReason:n.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new Bx(l);try{this.ws.closed.then(e=>{this.isEstablishingConnection&&t(z.internal(`Websocket got closed during a (re)connection attempt: ${e.reason}`)),e.closeCode!==1e3&&(this.log.warn(`websocket closed`,Object.assign(Object.assign({},this.logContext),{reason:e.reason,code:e.closeCode,wasClean:e.closeCode===1e3,state:this.state})),this.state===q.CONNECTED&&this.handleOnClose(e.reason??`Unexpected WS error`))}).catch(e=>{this.isEstablishingConnection&&t(z.internal(`Websocket error during a (re)connection attempt: ${e}`))});let r=yield this.ws.opened.catch(e=>L(this,void 0,void 0,function*(){if(this.state!==q.CONNECTED){this.state=q.DISCONNECTED,clearTimeout(s),t(yield this.handleConnectionError(e,u));return}this.handleWSError(e),t(e)}));if(clearTimeout(s),!r)return;let i=r.readable.getReader();this.streamWriter=r.writable.getWriter();let a=yield i.read();if(i.releaseLock(),!a.value)throw z.internal(`no message received as first message`);let o=lx(a.value),l=this.validateFirstMessage(o,n.reconnect??!1);if(!l.isValid){t(l.error);return}o.message?.case===`join`&&(this.pingTimeoutDuration=o.message.value.pingTimeout,this.pingIntervalDuration=o.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.onJoined&&this.onJoined(o.message.value)),c(r,l.shouldProcessFirstMessage?o:void 0),e(l.response)}catch(e){t(e)}finally{o()}}finally{s()}}))}()})}startReadingLoop(e,t){return L(this,void 0,void 0,function*(){for(t&&this.handleSignalResponse(t);;){this.signalLatency&&(yield nb(this.signalLatency));let{done:t,value:n}=yield e.read();if(t)break;let r=lx(n);this.handleSignalResponse(r)}})}close(){return L(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:`Close method called on signal client`;return function*(){if([q.DISCONNECTING||q.DISCONNECTED].includes(e.state)){e.log.debug(`ignoring signal close as it's already in disconnecting state`);return}let r=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=q.DISCONNECTING),e.ws){e.ws.close({closeCode:1e3,reason:n});let t=e.ws.closed;e.ws=void 0,e.streamWriter=void 0,yield Promise.race([t,nb(Ux)])}}catch(t){e.log.debug(`websocket error while closing`,Object.assign(Object.assign({},e.logContext),{error:t}))}finally{t&&(e.state=q.DISCONNECTED),r()}}()})}sendOffer(e,t){this.log.debug(`sending offer`,Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:`offer`,value:Kx(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:Kx(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 wg({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:`mute`,value:new Tg({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:`addTrack`,value:e})}sendUpdateLocalMetadata(e,t){return L(this,arguments,void 0,function(e,t){var n=this;let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return function*(){let i=n.getNextRequestId();return yield n.sendRequest({case:`updateMetadata`,value:new Vg({requestId:i,metadata:e,name:t,attributes:r})}),i}()})}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 Bg({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:`subscriptionPermission`,value:new e_({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:`simulate`,value:e})}sendPing(){return Promise.all([this.sendRequest({case:`ping`,value:Hp.parse(Date.now())}),this.sendRequest({case:`pingReq`,value:new s_({timestamp:Hp.parse(Date.now()),rtt:Hp.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:`updateAudioTrack`,value:new Ig({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:`leave`,value:new Rg({reason:_h.CLIENT_INITIATED,action:zg.DISCONNECT})})}sendPublishDataTrackRequest(e,t,n){return this.sendRequest({case:`publishDataTrackRequest`,value:new vg({pubHandle:e,name:t,encryption:n?F.GCM:F.NONE})})}sendUnPublishDataTrackRequest(e){return this.sendRequest({case:`unpublishDataTrackRequest`,value:new bg({pubHandle:e})})}sendUpdateDataSubscription(e,t){return this.sendRequest({case:`updateDataSubscription`,value:new Ng({updates:[new Pg({trackSid:e,subscribe:t})]})})}sendRequest(e){return L(this,arguments,void 0,function(e){var t=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return function*(){if(!n&&!Hx(e)&&t.state===q.RECONNECTING){t.queuedRequests.push(()=>L(t,void 0,void 0,function*(){yield this.sendRequest(e,!0)}));return}if(n||(yield t.requestQueue.flush()),t.signalLatency&&(yield nb(t.signalLatency)),t.isDisconnected){t.log.debug(`skipping signal request (type: ${e.case}) - SignalClient disconnected`);return}if(!t.streamWriter){t.log.error(`cannot send signal request before connected, type: ${e?.case}`,t.logContext);return}let r=new mg({message:e});try{t.useJSON?yield t.streamWriter.write(r.toJsonString()):yield t.streamWriter.write(r.toBinary())}catch(e){t.log.error(`error sending signal message`,Object.assign(Object.assign({},t.logContext),{error:e}))}}()})}handleSignalResponse(e){let t=e.message;if(t==null){this.log.debug(`received unsupported message`,this.logContext);return}let n=!1;if(t.case===`answer`){let e=Gx(t.value);this.onAnswer&&this.onAnswer(e,t.value.id,t.value.midToTrackId)}else if(t.case===`offer`){let e=Gx(t.value);this.onOffer&&this.onOffer(e,t.value.id,t.value.midToTrackId)}else if(t.case===`trickle`){let e=JSON.parse(t.value.candidateInit);this.onTrickle&&this.onTrickle(e,t.value.target)}else t.case===`update`?this.onParticipantUpdate&&this.onParticipantUpdate(t.value.participants??[]):t.case===`trackPublished`?this.onLocalTrackPublished&&this.onLocalTrackPublished(t.value):t.case===`speakersChanged`?this.onSpeakersChanged&&this.onSpeakersChanged(t.value.speakers??[]):t.case===`leave`?this.onLeave&&this.onLeave(t.value):t.case===`mute`?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(t.value.sid,t.value.muted):t.case===`roomUpdate`?this.onRoomUpdate&&t.value.room&&this.onRoomUpdate(t.value.room):t.case===`connectionQuality`?this.onConnectionQuality&&this.onConnectionQuality(t.value):t.case===`streamStateUpdate`?this.onStreamStateUpdate&&this.onStreamStateUpdate(t.value):t.case===`subscribedQualityUpdate`?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(t.value):t.case===`subscriptionPermissionUpdate`?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(t.value):t.case===`refreshToken`?this.onTokenRefresh&&this.onTokenRefresh(t.value):t.case===`trackUnpublished`?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(t.value):t.case===`subscriptionResponse`?this.onSubscriptionError&&this.onSubscriptionError(t.value):t.case===`pong`||(t.case===`pongResp`?(this.rtt=Date.now()-Number.parseInt(t.value.lastPingTimestamp.toString()),this.resetPingTimeout(),n=!0):t.case===`requestResponse`?this.onRequestResponse&&this.onRequestResponse(t.value):t.case===`trackSubscribed`?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(t.value.trackSid):t.case===`roomMoved`?(this.onTokenRefresh&&this.onTokenRefresh(t.value.token),this.onRoomMoved&&this.onRoomMoved(t.value)):t.case===`mediaSectionsRequirement`?this.onMediaSectionsRequirement&&this.onMediaSectionsRequirement(t.value):t.case===`publishDataTrackResponse`?this.onPublishDataTrackResponse&&this.onPublishDataTrackResponse(t.value):t.case===`unpublishDataTrackResponse`?this.onUnPublishDataTrackResponse&&this.onUnPublishDataTrackResponse(t.value):t.case===`dataTrackSubscriberHandles`?this.onDataTrackSubscriberHandles&&this.onDataTrackSubscriberHandles(t.value):this.log.debug(`unsupported message`,Object.assign(Object.assign({},this.logContext),{msgCase:t.case})));n||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){let e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return L(this,void 0,void 0,function*(){if(this.state===q.DISCONNECTED)return;let t=this.onClose;yield this.close(void 0,e),this.log.debug(`websocket connection closed: ${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=xy.setTimeout(()=>{this.log.warn(`ping timeout triggered. last pong received at: ${new Date(Date.now()-this.pingTimeoutDuration*1e3).toUTCString()}`,this.logContext),this.handleOnClose(`ping timeout`)},this.pingTimeoutDuration*1e3)}clearPingTimeout(){this.pingTimeout&&xy.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=xy.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug(`clearing ping interval`,this.logContext),this.clearPingTimeout(),this.pingInterval&&xy.clearInterval(this.pingInterval)}handleSignalConnected(e,t,n){this.state=q.CONNECTED,clearTimeout(t),this.startPingInterval(),this.startReadingLoop(e.readable.getReader(),n)}validateFirstMessage(e,t){return e.message?.case===`join`?{isValid:!0,response:e.message.value}:this.state===q.RECONNECTING&&e.message?.case!==`leave`?e.message?.case===`reconnect`?{isValid:!0,response:e.message.value}:(this.log.debug(`declaring signal reconnected without reconnect response received`,this.logContext),{isValid:!0,response:void 0,shouldProcessFirstMessage:!0}):this.isEstablishingConnection&&e.message?.case===`leave`?{isValid:!1,error:z.leaveRequest(`Received leave request while trying to (re)connect`,e.message.value.reason)}:t?{isValid:!1,error:z.internal(`Unexpected first message`)}:{isValid:!1,error:z.internal(`did not receive join response, got ${e.message?.case} instead`)}}handleConnectionError(e,t){return L(this,void 0,void 0,function*(){try{let n=yield fetch(t);switch(n.status){case 404:return z.serviceNotFound(`v1 RTC path not found. Consider upgrading your LiveKit server version`,`v0-rtc`);case 401:case 403:let e=yield n.text();return z.notAllowed(e,n.status);default:break}return e instanceof z?e:z.internal(`Encountered unknown websocket error during connection: ${e}`,{status:n.status,statusText:n.statusText})}catch(e){return e instanceof z?e:z.serverUnreachable(e instanceof Error?e.message:`server was not reachable`)}})}};function Gx(e){let t={type:`offer`,sdp:e.sdp};switch(e.type){case`answer`:case`offer`:case`pranswer`:case`rollback`:t.type=e.type;break}return t}function Kx(e,t){return new Ag({sdp:e.sdp,type:e.type,id:t})}function qx(e,t,n){let r=new URLSearchParams;return r.set(`access_token`,e),n.reconnect&&(r.set(`reconnect`,`1`),n.sid&&r.set(`sid`,n.sid)),r.set(`auto_subscribe`,n.autoSubscribe?`1`:`0`),r.set(`sdk`,yb()?`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),n.adaptiveStream&&r.set(`adaptive_stream`,`1`),n.reconnectReason&&r.set(`reconnect_reason`,n.reconnectReason.toString()),navigator.connection?.type&&r.set(`network`,navigator.connection.type),r}function Jx(e,t,n,r){return L(this,void 0,void 0,function*(){let i=new URLSearchParams;i.set(`access_token`,e);let a=new g_({clientInfo:t,connectionSettings:new h_({autoSubscribe:!!n.autoSubscribe,adaptiveStream:!!n.adaptiveStream}),reconnect:!!n.reconnect,participantSid:n.sid?n.sid:void 0,publisherOffer:r});n.reconnectReason&&(a.reconnectReason=n.reconnectReason);let o=a.toBinary(),s,c;if(rx()){let e=new CompressionStream(`gzip`),t=e.writable.getWriter();t.write(new Uint8Array(o)),t.close();let n=[],r=e.readable.getReader();for(;;){let{done:e,value:t}=yield r.read();if(e)break;n.push(t)}let i=n.reduce((e,t)=>e+t.length,0),a=new Uint8Array(i),l=0;for(let e of n)a.set(e,l),l+=e.length;s=a,c=v_.GZIP}else s=o,c=v_.NONE;let l=new __({joinRequest:s,compression:c}).toBinary();return i.set(`join_request`,(e=>{let t=Array.from(e,e=>String.fromCodePoint(e)).join(``);return btoa(t)})(l).replace(/\+/g,`-`).replace(/\//g,`_`)),i})}var Yx=class{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&&this.buffer[0].sequence<=e;)this.pop()}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}},Xx=class{constructor(e){this._map=new Map,this._lastCleanup=0,this.ttl=e}set(e,t){let n=Date.now();n-this._lastCleanup>this.ttl/2&&this.cleanup();let r=n+this.ttl;return this._map.set(e,{value:t,expiresAt:r}),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):!0:!1}delete(e){return this._map.delete(e)}clear(){this._map.clear()}cleanup(){let e=Date.now();for(let[t,n]of this._map.entries())n.expiresAt<e&&this._map.delete(t);this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){this.cleanup();for(let[t,n]of this._map.entries())n.expiresAt>=Date.now()&&e(n.value,t,this.asValueMap())}map(e){this.cleanup();let t=[],n=this.asValueMap();for(let[r,i]of n.entries())t.push(e(i,r,n));return t}asValueMap(){let e=new Map;for(let[t,n]of this._map.entries())n.expiresAt>=Date.now()&&e.set(t,n.value);return e}},Zx={},Qx={},$x={exports:{}},eS;function tS(){if(eS)return $x.exports;eS=1;var e=$x.exports={v:[{name:`version`,reg:/^(\d*)$/}],o:[{name:`origin`,reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:[`username`,`sessionId`,`sessionVersion`,`netType`,`ipVer`,`address`],format:`%s %s %d %s IP%d %s`}],s:[{name:`name`}],i:[{name:`description`}],u:[{name:`uri`}],e:[{name:`email`}],p:[{name:`phone`}],z:[{name:`timezones`}],r:[{name:`repeats`}],t:[{name:`timing`,reg:/^(\d*) (\d*)/,names:[`start`,`stop`],format:`%d %d`}],c:[{name:`connection`,reg:/^IN IP(\d) (\S*)/,names:[`version`,`ip`],format:`IN IP%d %s`}],b:[{push:`bandwidth`,reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:[`type`,`limit`],format:`%s:%s`}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:[`type`,`port`,`protocol`,`payloads`],format:`%s %d %s %s`}],a:[{push:`rtp`,reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:[`payload`,`codec`,`rate`,`encoding`],format:function(e){return e.encoding?`rtpmap:%d %s/%s/%s`:e.rate?`rtpmap:%d %s/%s`:`rtpmap:%d %s`}},{push:`fmtp`,reg:/^fmtp:(\d*) ([\S| ]*)/,names:[`payload`,`config`],format:`fmtp:%d %s`},{name:`control`,reg:/^control:(.*)/,format:`control:%s`},{name:`rtcp`,reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:[`port`,`netType`,`ipVer`,`address`],format:function(e){return e.address==null?`rtcp:%d`:`rtcp:%d %s IP%d %s`}},{push:`rtcpFbTrrInt`,reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:[`payload`,`value`],format:`rtcp-fb:%s trr-int %d`},{push:`rtcpFb`,reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:[`payload`,`type`,`subtype`],format:function(e){return e.subtype==null?`rtcp-fb:%s %s`:`rtcp-fb:%s %s %s`}},{push:`ext`,reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:[`value`,`direction`,`encrypt-uri`,`uri`,`config`],format:function(e){return`extmap:%d`+(e.direction?`/%s`:`%v`)+(e[`encrypt-uri`]?` %s`:`%v`)+` %s`+(e.config?` %s`:``)}},{name:`extmapAllowMixed`,reg:/^(extmap-allow-mixed)/},{push:`crypto`,reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:[`id`,`suite`,`config`,`sessionConfig`],format:function(e){return e.sessionConfig==null?`crypto:%d %s %s`:`crypto:%d %s %s %s`}},{name:`setup`,reg:/^setup:(\w*)/,format:`setup:%s`},{name:`connectionType`,reg:/^connection:(new|existing)/,format:`connection:%s`},{name:`mid`,reg:/^mid:([^\s]*)/,format:`mid:%s`},{name:`msid`,reg:/^msid:(.*)/,format:`msid:%s`},{name:`ptime`,reg:/^ptime:(\d*(?:\.\d*)*)/,format:`ptime:%d`},{name:`maxptime`,reg:/^maxptime:(\d*(?:\.\d*)*)/,format:`maxptime:%d`},{name:`direction`,reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:`icelite`,reg:/^(ice-lite)/},{name:`iceUfrag`,reg:/^ice-ufrag:(\S*)/,format:`ice-ufrag:%s`},{name:`icePwd`,reg:/^ice-pwd:(\S*)/,format:`ice-pwd:%s`},{name:`fingerprint`,reg:/^fingerprint:(\S*) (\S*)/,names:[`type`,`hash`],format:`fingerprint:%s %s`},{push:`candidates`,reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:[`foundation`,`component`,`transport`,`priority`,`ip`,`port`,`type`,`raddr`,`rport`,`tcptype`,`generation`,`network-id`,`network-cost`],format:function(e){var t=`candidate:%s %d %s %d %s %d typ %s`;return t+=e.raddr==null?`%v%v`:` raddr %s rport %d`,t+=e.tcptype==null?`%v`:` tcptype %s`,e.generation!=null&&(t+=` generation %d`),t+=e[`network-id`]==null?`%v`:` network-id %d`,t+=e[`network-cost`]==null?`%v`:` network-cost %d`,t}},{name:`endOfCandidates`,reg:/^(end-of-candidates)/},{name:`remoteCandidates`,reg:/^remote-candidates:(.*)/,format:`remote-candidates:%s`},{name:`iceOptions`,reg:/^ice-options:(\S*)/,format:`ice-options:%s`},{push:`ssrcs`,reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:[`id`,`attribute`,`value`],format:function(e){var t=`ssrc:%d`;return e.attribute!=null&&(t+=` %s`,e.value!=null&&(t+=`:%s`)),t}},{push:`ssrcGroups`,reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:[`semantics`,`ssrcs`],format:`ssrc-group:%s %s`},{name:`msidSemantic`,reg:/^msid-semantic:\s?(\w*) (\S*)/,names:[`semantic`,`token`],format:`msid-semantic: %s %s`},{push:`groups`,reg:/^group:(\w*) (.*)/,names:[`type`,`mids`],format:`group:%s %s`},{name:`rtcpMux`,reg:/^(rtcp-mux)/},{name:`rtcpRsize`,reg:/^(rtcp-rsize)/},{name:`sctpmap`,reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:[`sctpmapNumber`,`app`,`maxMessageSize`],format:function(e){return e.maxMessageSize==null?`sctpmap:%s %s`:`sctpmap:%s %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`+(e.clksrcExt==null?``:`=%s`)}},{name:`mediaClk`,reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:[`id`,`mediaClockName`,`mediaClockValue`,`rateNumerator`,`rateDenominator`],format:function(e){var t=`mediaclk:`;return t+=e.id==null?`%v%s`:`id=%s %s`,t+=e.mediaClockValue==null?``:`=%s`,t+=e.rateNumerator==null?``:` rate=%s`,t+=e.rateDenominator==null?``:`/%s`,t}},{name:`keywords`,reg:/^keywds:(.+)$/,format:`keywds:%s`},{name:`content`,reg:/^content:(.+)/,format:`content:%s`},{name:`bfcpFloorCtrl`,reg:/^floorctrl:(c-only|s-only|c-s)/,format:`floorctrl:%s`},{name:`bfcpConfId`,reg:/^confid:(\d+)/,format:`confid:%s`},{name:`bfcpUserId`,reg:/^userid:(\d+)/,format:`userid:%s`},{name:`bfcpFloorId`,reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:[`id`,`mStream`],format:`floorid:%s mstrm:%s`},{push:`invalid`,names:[`value`]}]};return Object.keys(e).forEach(function(t){e[t].forEach(function(e){e.reg||=/(.*)/,e.format||=`%s`})}),$x.exports}var nS;function rS(){return nS?Qx:(nS=1,(function(e){var t=function(e){return String(Number(e))===e?Number(e):e},n=function(e,n,r,i){if(i&&!r)n[i]=t(e[1]);else for(var a=0;a<r.length;a+=1)e[a+1]!=null&&(n[r[a]]=t(e[a+1]))},r=function(e,t,r){var i=e.name&&e.names;e.push&&!t[e.push]?t[e.push]=[]:i&&!t[e.name]&&(t[e.name]={});var a=e.push?{}:i?t[e.name]:t;n(r.match(e.reg),a,e.names,e.name),e.push&&t[e.push].push(a)},i=tS(),a=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},n=[],o=t;return e.split(/(\r\n|\r|\n)/).filter(a).forEach(function(e){var t=e[0],a=e.slice(2);t===`m`&&(n.push({rtp:[],fmtp:[]}),o=n[n.length-1]);for(var s=0;s<(i[t]||[]).length;s+=1){var c=i[t][s];if(c.reg.test(a))return r(c,o,a)}}),t.media=n,t};var o=function(e,n){var r=n.split(/=(.+)/,2);return r.length===2?e[r[0]]=t(r[1]):r.length===1&&n.length>1&&(e[r[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(o,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(` `).map(Number)},e.parseRemoteCandidates=function(e){for(var n=[],r=e.split(` `).map(t),i=0;i<r.length;i+=3)n.push({component:r[i],ip:r[i+1],port:r[i+2]});return n},e.parseImageAttributes=function(e){return e.split(` `).map(function(e){return e.substring(1,e.length-1).split(`,`).reduce(o,{})})},e.parseSimulcastStreamList=function(e){return e.split(`;`).map(function(e){return e.split(`,`).map(function(e){var n,r=!1;return e[0]===`~`?(n=t(e.substring(1,e.length)),r=!0):n=t(e),{scid:n,paused:r}})})}})(Qx),Qx)}var iS,aS;function oS(){if(aS)return iS;aS=1;var e=tS(),t=/%[sdv%]/g,n=function(e){var n=1,r=arguments,i=r.length;return e.replace(t,function(e){if(n>=i)return e;var t=r[n];switch(n+=1,e){case`%%`:return`%`;case`%s`:return String(t);case`%d`:return Number(t);case`%v`:return``}})},r=function(e,t,r){var i=t.format instanceof Function?t.format(t.push?r:r[t.name]):t.format,a=[e+`=`+i];if(t.names)for(var o=0;o<t.names.length;o+=1){var s=t.names[o];t.name?a.push(r[t.name][s]):a.push(r[t.names[o]])}else a.push(r[t.name]);return n.apply(null,a)},i=[`v`,`o`,`s`,`i`,`u`,`e`,`p`,`c`,`b`,`t`,`r`,`z`,`a`],a=[`i`,`c`,`b`,`a`];return iS=function(t,n){n||={},t.version??=0,t.name??=` `,t.media.forEach(function(e){e.payloads??=``});var o=n.outerOrder||i,s=n.innerOrder||a,c=[];return o.forEach(function(n){e[n].forEach(function(e){e.name in t&&t[e.name]!=null?c.push(r(n,e,t)):e.push in t&&t[e.push]!=null&&t[e.push].forEach(function(t){c.push(r(n,e,t))})})}),t.media.forEach(function(t){c.push(r(`m`,e.m[0],t)),s.forEach(function(n){e[n].forEach(function(e){e.name in t&&t[e.name]!=null?c.push(r(n,e,t)):e.push in t&&t[e.push]!=null&&t[e.push].forEach(function(t){c.push(r(n,e,t))})})})}),c.join(`\r
60
+ `);e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:n}):t.sdp=n}return n.apply(this,arguments)}}function Qv(e,t){if(!(e.RTCPeerConnection&&e.RTCPeerConnection.prototype))return;let n=e.RTCPeerConnection.prototype.addIceCandidate;!n||n.length===0||(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(t.browser===`chrome`&&t.version<78||t.browser===`firefox`&&t.version<68||t.browser===`safari`)&&arguments[0]&&arguments[0].candidate===``?Promise.resolve():n.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function $v(e,t){if(!(e.RTCPeerConnection&&e.RTCPeerConnection.prototype))return;let n=e.RTCPeerConnection.prototype.setLocalDescription;!n||n.length===0||(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if(typeof e!=`object`||e.type&&e.sdp)return n.apply(this,arguments);if(e={type:e.type,sdp:e.sdp},!e.type)switch(this.signalingState){case`stable`:case`have-local-offer`:case`have-remote-pranswer`:e.type=`offer`;break;default:e.type=`answer`;break}return e.sdp||e.type!==`offer`&&e.type!==`answer`?n.apply(this,[e]):(e.type===`offer`?this.createOffer:this.createAnswer).apply(this).then(e=>n.apply(this,[e]))})}var ey=Object.freeze({__proto__:null,removeExtmapAllowMixed:Zv,shimAddIceCandidateNullOrEmpty:Qv,shimConnectionState:Xv,shimMaxMessageSize:Jv,shimParameterlessSetLocalDescription:$v,shimRTCIceCandidate:Kv,shimRTCIceCandidateRelayProtocol:qv,shimSendThrowTypeError:Yv});function ty(){let{window:e}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0},n=$_,r=tv(e),i={browserDetails:r,commonShim:ey,extractVersion:Y_,disableLog:Z_,disableWarnings:Q_,sdp:Gv};switch(r.browser){case`chrome`:if(!gv||!mv||!t.shimChrome)return n(`Chrome shim is not included in this adapter release.`),i;if(r.version===null)return n(`Chrome shim can not determine version, not shimming.`),i;n(`adapter.js shimming chrome.`),i.browserShim=gv,Qv(e,r),$v(e),sv(e,r),cv(e),mv(e,r),lv(e),pv(e,r),uv(e),dv(e),hv(e,r),Kv(e),qv(e),Xv(e),Jv(e,r),Yv(e),Zv(e,r);break;case`firefox`:if(!kv||!bv||!t.shimFirefox)return n(`Firefox shim is not included in this adapter release.`),i;n(`adapter.js shimming firefox.`),i.browserShim=kv,Qv(e,r),$v(e),_v(e,r),bv(e,r),yv(e),Cv(e),xv(e),Sv(e),wv(e),Tv(e),Ev(e),Dv(e),Ov(e),Kv(e),Xv(e),Jv(e,r),Yv(e);break;case`safari`:if(!zv||!t.shimSafari)return n(`Safari shim is not included in this adapter release.`),i;n(`adapter.js shimming safari.`),i.browserShim=zv,Qv(e,r),$v(e),Fv(e),Lv(e),Mv(e),Av(e),jv(e),Iv(e),Nv(e),Rv(e),Kv(e),qv(e),Jv(e,r),Yv(e),Zv(e,r);break;default:n(`Unsupported browser!`);break}return i}ty({window:typeof window>`u`?void 0:window});var ny,ry,iy=class extends (ry=Promise){constructor(e){super(e)}catch(e){return super.catch(e)}static reject(e){return super.reject(e)}static all(e){return super.all(e)}static race(e){return super.race(e)}};ny=iy,iy.resolve=e=>Reflect.get(ry,`resolve`,ny).call(ny,e);var ay=/version\/(\d+(\.?_?\d+)+)/i,oy;function sy(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(e===void 0&&typeof navigator>`u`)return;let n=(e??navigator.userAgent).toLowerCase();return(oy===void 0||t)&&(oy=cy.find(e=>{let{test:t}=e;return t.test(n)})?.describe(n)),oy}var cy=[{test:/firefox|iceweasel|fxios/i,describe(e){return{name:`Firefox`,version:ly(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes(`fxios`)?`iOS`:void 0,osVersion:uy(e)}}},{test:/chrom|crios|crmo/i,describe(e){return{name:`Chrome`,version:ly(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes(`crios`)?`iOS`:void 0,osVersion:uy(e)}}},{test:/safari|applewebkit/i,describe(e){return{name:`Safari`,version:ly(ay,e),os:e.includes(`mobile/`)?`iOS`:`macOS`,osVersion:uy(e)}}}];function ly(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,r=t.match(e);return r&&r.length>=n&&r[n]||``}function uy(e){return e.includes(`mac os`)?ly(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,`.`):void 0}var dy=`2.18.1`,fy=class extends Error{constructor(e,t,n){super(t||`an error has occurred`),this.name=`LiveKitError`,this.code=e,n?.cause!==void 0&&(this.cause=n?.cause)}},py=class extends fy{},R;(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`,e[e.WebSocket=6]=`WebSocket`,e[e.ServiceNotFound=7]=`ServiceNotFound`})(R||={});var z=class e extends py{constructor(e,t,n,r){super(1,e),this.name=`ConnectionError`,this.status=n,this.reason=t,this.context=r,this.reasonName=R[t]}static notAllowed(t,n,r){return new e(t,R.NotAllowed,n,r)}static timeout(t){return new e(t,R.Timeout)}static leaveRequest(t,n){return new e(t,R.LeaveRequest,void 0,n)}static internal(t,n){return new e(t,R.InternalError,void 0,n)}static cancelled(t){return new e(t,R.Cancelled)}static serverUnreachable(t,n){return new e(t,R.ServerUnreachable,n)}static websocket(t,n,r){return new e(t,R.WebSocket,n,r)}static serviceNotFound(t,n){return new e(t,R.ServiceNotFound,void 0,n)}},my=class extends fy{constructor(e){super(21,e??`device is unsupported`),this.name=`DeviceUnsupportedError`}},hy=class extends fy{constructor(e){super(20,e??`track is invalid`),this.name=`TrackInvalidError`}},gy=class extends fy{constructor(e){super(10,e??`unsupported server`),this.name=`UnsupportedServer`}},_y=class extends fy{constructor(e){super(12,e??`unexpected connection state`),this.name=`UnexpectedConnectionState`}},vy=class extends fy{constructor(e){super(13,e??`unable to negotiate`),this.name=`NegotiationError`}},yy=class extends fy{constructor(e,t){super(15,e),this.name=`PublishTrackError`,this.status=t}},by=class extends py{constructor(e,t){super(15,e),this.name=`SignalRequestError`,this.reason=t,this.reasonName=typeof t==`string`?t:__[t]}},xy;(function(e){e[e.AlreadyOpened=0]=`AlreadyOpened`,e[e.AbnormalEnd=1]=`AbnormalEnd`,e[e.DecodeFailed=2]=`DecodeFailed`,e[e.LengthExceeded=3]=`LengthExceeded`,e[e.Incomplete=4]=`Incomplete`,e[e.HandlerAlreadyRegistered=7]=`HandlerAlreadyRegistered`,e[e.EncryptionTypeMismatch=8]=`EncryptionTypeMismatch`})(xy||={});var Sy=class extends py{constructor(e,t){super(16,e),this.name=`DataStreamError`,this.reason=t,this.reasonName=xy[t]}},Cy=class extends fy{constructor(e){super(18,e),this.name=`SignalReconnectError`}},wy;(function(e){e.PermissionDenied=`PermissionDenied`,e.NotFound=`NotFound`,e.DeviceInUse=`DeviceInUse`,e.Other=`Other`})(wy||={}),(function(e){function t(t){if(t&&`name`in t)return t.name===`NotFoundError`||t.name===`DevicesNotFoundError`?e.NotFound:t.name===`NotAllowedError`||t.name===`PermissionDeniedError`?e.PermissionDenied:t.name===`NotReadableError`||t.name===`TrackStartError`?e.DeviceInUse:e.Other}e.getFailure=t})(wy||={});var Ty=class{};Ty.setTimeout=function(){return setTimeout(...arguments)},Ty.setInterval=function(){return setInterval(...arguments)},Ty.clearTimeout=function(){return clearTimeout(...arguments)},Ty.clearInterval=function(){return clearInterval(...arguments)};var B;(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`,e.DataTrackPublished=`dataTrackPublished`,e.DataTrackUnpublished=`dataTrackUnpublished`,e.LocalDataTrackPublished=`localDataTrackPublished`,e.LocalDataTrackUnpublished=`localDataTrackUnpublished`})(B||={});var V;(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`})(V||={});var H;(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`,e.PublishDataTrackResponse=`publishDataTrackResponse`,e.UnPublishDataTrackResponse=`unPublishDataTrackResponse`,e.DataTrackSubscriberHandles=`dataTrackSubscriberHandles`,e.DataTrackPacketReceived=`dataTrackPacketReceived`,e.Joined=`joined`})(H||={});var U;(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`})(U||={});function Ey(e){return e===void 0?e:typeof structuredClone==`function`?typeof e==`object`&&e?structuredClone(Object.assign({},e)):structuredClone(e):JSON.parse(JSON.stringify(e))}var W=class{constructor(e,t,n,r,i){if(typeof e==`object`)this.width=e.width,this.height=e.height,this.aspectRatio=e.aspectRatio,this.encoding={maxBitrate:e.maxBitrate,maxFramerate:e.maxFramerate,priority:e.priority};else if(t!==void 0&&n!==void 0)this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:n,maxFramerate:r,priority:i};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}}},Dy=[`vp8`,`h264`],Oy=[`vp8`,`h264`,`vp9`,`av1`,`h265`];function ky(e){return!!Dy.find(t=>t===e)}var Ay=ky,jy;(function(e){e[e.PREFER_REGRESSION=0]=`PREFER_REGRESSION`,e[e.SIMULCAST=1]=`SIMULCAST`,e[e.REGRESSION=2]=`REGRESSION`})(jy||={});var My;(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}})(My||={});var Ny={h90:new W(160,90,9e4,20),h180:new W(320,180,16e4,20),h216:new W(384,216,18e4,20),h360:new W(640,360,45e4,20),h540:new W(960,540,8e5,25),h720:new W(1280,720,17e5,30),h1080:new W(1920,1080,3e6,30),h1440:new W(2560,1440,5e6,30),h2160:new W(3840,2160,8e6,30)},Py={h120:new W(160,120,7e4,20),h180:new W(240,180,125e3,20),h240:new W(320,240,14e4,20),h360:new W(480,360,33e4,20),h480:new W(640,480,5e5,20),h540:new W(720,540,6e5,25),h720:new W(960,720,13e5,30),h1080:new W(1440,1080,23e5,30),h1440:new W(1920,1440,38e5,30)},Fy={h360fps3:new W(640,360,2e5,3,`medium`),h360fps15:new W(640,360,4e5,15,`medium`),h720fps5:new W(1280,720,8e5,5,`medium`),h720fps15:new W(1280,720,15e5,15,`medium`),h720fps30:new W(1280,720,2e6,30,`medium`),h1080fps15:new W(1920,1080,25e5,15,`medium`),h1080fps30:new W(1920,1080,5e6,30,`medium`),original:new W(0,0,7e6,30,`medium`)};function Iy(e,t,n){var r,i;let{optionsWithoutProcessor:a,audioProcessor:o,videoProcessor:s}=Jy(e??{}),c=t?.processor,l=n?.processor,u=a??{};return u.audio===!0&&(u.audio={}),u.video===!0&&(u.video={}),u.audio&&(Ly(u.audio,t),(r=u.audio).deviceId??(r.deviceId={ideal:`default`}),(o||c)&&(u.audio.processor=o??c)),u.video&&(Ly(u.video,n),(i=u.video).deviceId??(i.deviceId={ideal:`default`}),(s||l)&&(u.video.processor=s??l)),u}function Ly(e,t){return Object.keys(t).forEach(n=>{e[n]===void 0&&(e[n]=t[n])}),e}function Ry(e){var t,n;let r={};if(e.video)if(typeof e.video==`object`){let n={},i=n,a=e.video;Object.keys(a).forEach(e=>{switch(e){case`resolution`:Ly(i,a.resolution);break;default:i[e]=a[e]}}),r.video=n,(t=r.video).deviceId??(t.deviceId={ideal:`default`})}else r.video=e.video?{deviceId:{ideal:`default`}}:!1;else r.video=!1;return e.audio?typeof e.audio==`object`?(r.audio=e.audio,(n=r.audio).deviceId??(n.deviceId={ideal:`default`})):r.audio={deviceId:{ideal:`default`}}:r.audio=!1,r}function zy(e){return L(this,arguments,void 0,function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return function*(){let n=By();if(n){let r=n.createAnalyser();r.fftSize=2048;let i=r.frequencyBinCount,a=new Uint8Array(i);n.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(r),yield ob(t),r.getByteTimeDomainData(a);let o=a.some(e=>e!==128&&e!==0);return n.close(),!o}return!1}()})}function By(){let e=typeof window<`u`&&(window.AudioContext||window.webkitAudioContext);if(e){let t=new e({latencyHint:`interactive`});if(t.state===`suspended`&&typeof window<`u`&&window.document?.body){let e=()=>L(this,void 0,void 0,function*(){var n;try{t.state===`suspended`&&(yield t.resume())}catch(e){console.warn(`Error trying to auto-resume audio context`,e)}finally{(n=window.document.body)==null||n.removeEventListener(`click`,e)}});t.addEventListener(`statechange`,()=>{var n;t.state===`closed`&&((n=window.document.body)==null||n.removeEventListener(`click`,e))}),window.document.body.addEventListener(`click`,e)}return t}}function Vy(e){return e===`audioinput`?K.Source.Microphone:e===`videoinput`?K.Source.Camera:K.Source.Unknown}function Hy(e){if(e===K.Source.Microphone)return`audioinput`;if(e===K.Source.Camera)return`videoinput`}function Uy(e){let t=e.video??!0;return e.resolution&&e.resolution.width>0&&e.resolution.height>0&&(t=typeof t==`boolean`?{}:t,t=gb()?Object.assign(Object.assign({},t),{width:{max:e.resolution.width},height:{max:e.resolution.height},frameRate:e.resolution.frameRate}):Object.assign(Object.assign({},t),{width:{ideal:e.resolution.width},height:{ideal:e.resolution.height},frameRate:e.resolution.frameRate})),{audio:e.audio??!1,video:t,controller:e.controller,selfBrowserSurface:e.selfBrowserSurface,surfaceSwitching:e.surfaceSwitching,systemAudio:e.systemAudio,preferCurrentTab:e.preferCurrentTab}}function Wy(e){return e.split(`/`)[1].toLowerCase()}function Gy(e){let t=[];return e.forEach(e=>{e.track!==void 0&&t.push(new Mg({cid:e.track.mediaStreamID,track:e.trackInfo}))}),t}function G(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?G(e.track):{})}}function Ky(){return typeof RTCRtpReceiver<`u`&&`getSynchronizationSources`in RTCRtpReceiver}function qy(e,t){e===void 0&&(e={}),t===void 0&&(t={});let n=[...Object.keys(t),...Object.keys(e)],r={};for(let i of n)e[i]!==t[i]&&(r[i]=t[i]??``);return r}function Jy(e){let t=Object.assign({},e),n,r;return typeof t.audio==`object`&&t.audio.processor&&(n=t.audio.processor,t.audio=Object.assign(Object.assign({},t.audio),{processor:void 0})),typeof t.video==`object`&&t.video.processor&&(r=t.video.processor,t.video=Object.assign(Object.assign({},t.video),{processor:void 0})),{audioProcessor:n,videoProcessor:r,optionsWithoutProcessor:Ey(t)}}function Yy(e){switch(e){case _h.CAMERA:return K.Source.Camera;case _h.MICROPHONE:return K.Source.Microphone;case _h.SCREEN_SHARE:return K.Source.ScreenShare;case _h.SCREEN_SHARE_AUDIO:return K.Source.ScreenShareAudio;default:return K.Source.Unknown}}function Xy(e,t){return e.width*e.height<t.width*t.height}function Zy(e,t){return e.layers?.find(e=>e.quality===t)}var Qy=5e3,$y=[],eb;(function(e){e[e.LOW=0]=`LOW`,e[e.MEDIUM=1]=`MEDIUM`,e[e.HIGH=2]=`HIGH`})(eb||={});var K=class e extends K_.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState=e}constructor(t,n){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.attachedElements=[],this.isMuted=!1,this._streamState=e.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=I,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState===`hidden`?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),Qy):this.handleAppVisibilityChanged()},this.log=M_(r.loggerName??j_.Track),this.loggerContextCb=r.loggerContextCb,this.setMaxListeners(100),this.kind=n,this._mediaStreamTrack=t,this._mediaStreamID=t.id,this.source=e.Source.Unknown}get logContext(){return Object.assign(Object.assign({},this.loggerContextCb?.call(this)),G(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(t){let n=`audio`;this.kind===e.Kind.Video&&(n=`video`),this.attachedElements.length===0&&this.kind===e.Kind.Video&&this.addAppVisibilityListener(),t||(n===`audio`&&($y.forEach(e=>{e.parentElement===null&&!t&&(t=e)}),t&&$y.splice($y.indexOf(t),1)),t||=document.createElement(n)),this.attachedElements.includes(t)||this.attachedElements.push(t),tb(this.mediaStreamTrack,t);let r=t.srcObject.getTracks(),i=r.some(e=>e.kind===`audio`);return t.play().then(()=>{this.emit(i?U.AudioPlaybackStarted:U.VideoPlaybackStarted)}).catch(e=>{e.name===`NotAllowedError`?this.emit(i?U.AudioPlaybackFailed:U.VideoPlaybackFailed,e):e.name===`AbortError`?I.debug(`${i?`audio`:`video`} playback aborted, likely due to new play request`):I.warn(`could not playback ${i?`audio`:`video`}`,e),i&&t&&r.some(e=>e.kind===`video`)&&e.name===`NotAllowedError`&&(t.muted=!0,t.play().catch(()=>{}))}),this.emit(U.ElementAttached,t),t}detach(e){try{if(e){nb(this.mediaStreamTrack,e);let t=this.attachedElements.indexOf(e);return t>=0&&(this.attachedElements.splice(t,1),this.recycleElement(e),this.emit(U.ElementDetached,e)),e}let t=[];return this.attachedElements.forEach(e=>{nb(this.mediaStreamTrack,e),t.push(e),this.recycleElement(e),this.emit(U.ElementDetached,e)}),this.attachedElements=[],t}finally{this.attachedElements.length===0&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(e){e.loggerName&&(this.log=M_(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),$y.forEach(e=>{e.parentElement||(t=!1)}),t&&$y.push(e)}}handleAppVisibilityChanged(){return L(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState===`hidden`,!this.isInBackground&&this.kind===e.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){Sb()?(this.isInBackground=document.visibilityState===`hidden`,document.addEventListener(`visibilitychange`,this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){Sb()&&document.removeEventListener(`visibilitychange`,this.appVisibilityChangedListener)}};function tb(e,t){let n;n=t.srcObject instanceof MediaStream?t.srcObject:new MediaStream;let r;r=e.kind===`audio`?n.getAudioTracks():n.getVideoTracks(),r.includes(e)||(r.forEach(e=>{n.removeTrack(e)}),n.addTrack(e)),(!gb()||!(t instanceof HTMLVideoElement))&&(t.autoplay=!0),t.muted=n.getAudioTracks().length===0,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==n&&(t.srcObject=n,(gb()||mb())&&t instanceof HTMLVideoElement&&setTimeout(()=>{t.srcObject=n,t.play().catch(()=>{})},0))}function nb(e,t){if(t.srcObject instanceof MediaStream){let n=t.srcObject;n.removeTrack(e),n.getTracks().length>0?t.srcObject=n:t.srcObject=null}}(function(e){let t;(function(e){e.Audio=`audio`,e.Video=`video`,e.Unknown=`unknown`})(t=e.Kind||={});let n;(function(e){e.Camera=`camera`,e.Microphone=`microphone`,e.ScreenShare=`screen_share`,e.ScreenShareAudio=`screen_share_audio`,e.Unknown=`unknown`})(n=e.Source||={});let r;(function(e){e.Active=`active`,e.Paused=`paused`,e.Unknown=`unknown`})(r=e.StreamState||={});function i(e){switch(e){case t.Audio:return gh.AUDIO;case t.Video:return gh.VIDEO;default:return gh.DATA}}e.kindToProto=i;function a(e){switch(e){case gh.AUDIO:return t.Audio;case gh.VIDEO:return t.Video;default:return t.Unknown}}e.kindFromProto=a;function o(e){switch(e){case n.Camera:return _h.CAMERA;case n.Microphone:return _h.MICROPHONE;case n.ScreenShare:return _h.SCREEN_SHARE;case n.ScreenShareAudio:return _h.SCREEN_SHARE_AUDIO;default:return _h.UNKNOWN}}e.sourceToProto=o;function s(e){switch(e){case _h.CAMERA:return n.Camera;case _h.MICROPHONE:return n.Microphone;case _h.SCREEN_SHARE:return n.ScreenShare;case _h.SCREEN_SHARE_AUDIO:return n.ScreenShareAudio;default:return n.Unknown}}e.sourceFromProto=s;function c(e){switch(e){case gg.ACTIVE:return r.Active;case gg.PAUSED:return r.Paused;default:return r.Unknown}}e.streamStateFromProto=c})(K||={});var rb=`|`,ib=`https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension`;function ab(e){let t=e.split(rb);return t.length>1?[t[0],e.substr(t[0].length+1)]:[e,``]}function ob(e){return new iy(t=>Ty.setTimeout(t,e))}function sb(){return`addTransceiver`in RTCPeerConnection.prototype}function cb(){return`addTrack`in RTCPeerConnection.prototype}function lb(){if(!(`getCapabilities`in RTCRtpSender)||gb()||mb())return!1;let e=RTCRtpSender.getCapabilities(`video`),t=!1;if(e){for(let n of e.codecs)if(n.mimeType.toLowerCase()===`video/av1`){t=!0;break}}return t}function ub(){if(!(`getCapabilities`in RTCRtpSender)||mb())return!1;if(gb()){let e=sy();if(e?.version&&kb(e.version,`16`)<0||e?.os===`iOS`&&e?.osVersion&&kb(e.osVersion,`16`)<0)return!1}let e=RTCRtpSender.getCapabilities(`video`),t=!1;if(e){for(let n of e.codecs)if(n.mimeType.toLowerCase()===`video/vp9`){t=!0;break}}return t}function db(e){return e===`av1`||e===`vp9`}function fb(e){return!document||_b()?!1:(e||=document.createElement(`audio`),`setSinkId`in e)}function pb(){return typeof RTCPeerConnection>`u`?!1:sb()||cb()}function mb(){return sy()?.name===`Firefox`}function hb(){let e=sy();return!!e&&e.name===`Chrome`&&e.os!==`iOS`}function gb(){return sy()?.name===`Safari`}function _b(){let e=sy();return e?.name===`Safari`||e?.os===`iOS`}function vb(){let e=sy();return e?.name===`Safari`&&e.version.startsWith(`17.`)||e?.os===`iOS`&&!!e?.osVersion&&kb(e.osVersion,`17`)>=0}function yb(e){return e||=sy(),e?.name===`Safari`&&kb(e.version,`18.3`)>0||e?.os===`iOS`&&!!e?.osVersion&&kb(e.osVersion,`18.3`)>0}function bb(){return Sb()?navigator.userAgentData?.mobile??/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function xb(){let e=sy(),t=`17.2`;if(e)return e.name!==`Safari`&&e.os!==`iOS`||e.os===`iOS`&&e.osVersion&&kb(e.osVersion,t)>=0?!0:e.name===`Safari`&&kb(e.version,t)>=0}function Sb(){return typeof document<`u`}function Cb(){return navigator.product==`ReactNative`}function wb(e){return e.hostname.endsWith(`.livekit.cloud`)||e.hostname.endsWith(`.livekit.run`)}function Tb(e){return wb(e)?e.hostname.split(`.`)[0]:null}function Eb(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function Db(){if(!Cb())return;let e=Eb();if(e)return e.platform}function Ob(){if(Sb())return window.devicePixelRatio;if(Cb()){let e=Eb();if(e)return e.devicePixelRatio}return 1}function kb(e,t){let n=e.split(`.`),r=t.split(`.`),i=Math.min(n.length,r.length);for(let e=0;e<i;++e){let t=parseInt(n[e],10),a=parseInt(r[e],10);if(t>a)return 1;if(t<a)return-1;if(e===i-1&&t===a)return 0}return e===``&&t!==``?-1:t===``?1:n.length==r.length?0:n.length<r.length?-1:1}function Ab(e){for(let t of e)t.target.handleResize(t)}function jb(e){for(let t of e)t.target.handleVisibilityChanged(t)}var Mb=null,Nb=()=>(Mb||=new ResizeObserver(Ab),Mb),Pb=null,Fb=()=>(Pb||=new IntersectionObserver(jb,{root:null,rootMargin:`0px`}),Pb);function Ib(){let e=new ng({sdk:rg.JS,protocol:16,version:dy});return Cb()&&(e.os=Db()??``),e}function Lb(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:16,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:16,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,i=document.createElement(`canvas`);i.width=e,i.height=t;let a=i.getContext(`2d`);a?.fillRect(0,0,i.width,i.height),r&&a&&(a.beginPath(),a.arc(e/2,t/2,50,0,Math.PI*2,!0),a.closePath(),a.fillStyle=`grey`,a.fill());let[o]=i.captureStream().getTracks();if(!o)throw Error(`Could not get empty media stream video track`);return o.enabled=n,o}var Rb;function zb(){if(!Rb){let e=new AudioContext,t=e.createOscillator(),n=e.createGain();n.gain.setValueAtTime(0,0);let r=e.createMediaStreamDestination();if(t.connect(n),n.connect(r),t.start(),[Rb]=r.stream.getAudioTracks(),!Rb)throw Error(`Could not get empty media stream audio track`);Rb.enabled=!1}return Rb.clone()}var Bb=class{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise((t,n)=>L(this,void 0,void 0,function*(){this.resolve=t,this.reject=n,e&&(yield e(t,n))})).finally(()=>{var e;this._isResolved=!0,(e=this.onFinally)==null||e.call(this)})}};function Vb(e){return Oy.includes(e)}function Hb(e){if(typeof e==`string`||typeof e==`number`)return e;if(Array.isArray(e))return e[0];if(e.exact!==void 0)return Array.isArray(e.exact)?e.exact[0]:e.exact;if(e.ideal!==void 0)return Array.isArray(e.ideal)?e.ideal[0]:e.ideal;throw Error(`could not unwrap constraint`)}function Ub(e){return e.startsWith(`http`)?e.replace(/^(http)/,`ws`):e}function Wb(e){return e.startsWith(`ws`)?e.replace(/^(ws)/,`http`):e}function Gb(e,t){return e.segments.map(e=>{let{id:n,text:r,language:i,startTime:a,endTime:o,final:s}=e,c=t.get(n)??Date.now(),l=Date.now();return s?t.delete(n):t.set(n,c),{id:n,text:r,startTime:Number.parseInt(a.toString()),endTime:Number.parseInt(o.toString()),final:s,language:i,firstReceivedTime:c,lastReceivedTime:l}})}function Kb(e){let{id:t,timestamp:n,message:r,editTimestamp:i}=e;return{id:t,timestamp:Number.parseInt(n.toString()),editTimestamp:i?Number.parseInt(i.toString()):void 0,message:r}}function qb(e){switch(e.reason){case R.LeaveRequest:return e.context;case R.Cancelled:return xh.CLIENT_INITIATED;case R.NotAllowed:return xh.USER_REJECTED;case R.ServerUnreachable:return xh.JOIN_FAILURE;default:return xh.UNKNOWN_REASON}}function Jb(e){return e===void 0?void 0:Number(e)}function Yb(e){return e===void 0?void 0:BigInt(e)}function Xb(e){return!!e&&!(e instanceof MediaStreamTrack)&&e.isLocal}function Zb(e){return!!e&&e.kind==K.Kind.Audio}function Qb(e){return!!e&&e.kind==K.Kind.Video}function $b(e){return Xb(e)&&Qb(e)}function ex(e){return Xb(e)&&Zb(e)}function tx(e){return!!e&&!e.isLocal}function nx(e){return!!e&&!e.isLocal}function rx(e){return tx(e)&&Qb(e)}function ix(e){return e.isLocal}function ax(e,t){let n=[],r=new TextEncoder().encode(e);for(;r.length>t;){let e=t;for(;e>0;){let t=r[e];if(t!==void 0&&(t&192)!=128)break;e--}n.push(r.slice(0,e)),r=r.slice(e)}return r.length>0&&n.push(r),n}function ox(e){let t=e.get(`Cache-Control`);if(t){let e=t.match(/(?:^|[,\s])max-age=(\d+)/)?.[1];if(e)return parseInt(e,10)}}function sx(){return typeof CompressionStream<`u`}function cx(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,r=lx(e,t);return n?r:fx(r,`v1`)}function lx(e,t){let n=new URL(Ub(e));return t.forEach((e,t)=>{n.searchParams.set(t,e)}),fx(n,`rtc`)}function ux(e){return fx(new URL(Wb(e)),`validate`)}function dx(e){return e.endsWith(`/`)?e:`${e}/`}function fx(e,t){return e.pathname=`${dx(e.pathname)}${t}`,e}function px(e){if(typeof e==`string`)return yg.fromJson(JSON.parse(e),{ignoreUnknownFields:!0});if(e instanceof ArrayBuffer)return yg.fromBinary(new Uint8Array(e));throw Error(`could not decode websocket message: ${typeof e}`)}function mx(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:`Unknown reason`;if(!(e instanceof AbortSignal))return t;let n=e.reason;switch(typeof n){case`string`:return n;case`object`:return n instanceof Error?n.message:t;default:return`toString`in n?n.toString():t}}var hx=`lk_e2ee`,gx;(function(e){e.SetKey=`setKey`,e.RatchetRequest=`ratchetRequest`,e.KeyRatcheted=`keyRatcheted`})(gx||={});var _x;(function(e){e.KeyRatcheted=`keyRatcheted`})(_x||={});var vx;(function(e){e.ParticipantEncryptionStatusChanged=`participantEncryptionStatusChanged`,e.EncryptionError=`encryptionError`})(vx||={});var yx;(function(e){e.Error=`cryptorError`})(yx||={});function bx(){return Sx()||xx()}function xx(){return window.RTCRtpScriptTransform!==void 0}function Sx(){return window.RTCRtpSender!==void 0&&window.RTCRtpSender.prototype.createEncodedStreams!==void 0}function Cx(e){if(e.value?.case!==`sipDtmf`&&e.value?.case!==`metrics`&&e.value?.case!==`speaker`&&e.value?.case!==`transcription`&&e.value?.case!==`encryptedPacket`)return new Vh({value:e.value})}K_.EventEmitter;var wx;(function(e){e[e.InvalidKey=0]=`InvalidKey`,e[e.MissingKey=1]=`MissingKey`,e[e.InternalError=2]=`InternalError`})(wx||={});var Tx=class extends K_.EventEmitter{constructor(e,t){super(),this.decryptDataRequests=new Map,this.encryptDataRequests=new Map,this.onWorkerMessage=e=>{let{kind:t,data:n}=e.data;switch(t){case`error`:if(I.error(n.error.message),n.uuid){let e=this.decryptDataRequests.get(n.uuid);if(e?.reject){e.reject(n.error);break}let t=this.encryptDataRequests.get(n.uuid);if(t?.reject){t.reject(n.error);break}}this.emit(vx.EncryptionError,n.error,n.participantIdentity);break;case`initAck`:n.enabled&&this.keyProvider.getKeys().forEach(e=>{this.postKey(e,!1)});break;case`enable`:if(n.enabled&&this.keyProvider.getKeys().forEach(e=>{this.postKey(e,!1)}),this.encryptionEnabled!==n.enabled&&n.participantIdentity===this.room?.localParticipant.identity)this.emit(vx.ParticipantEncryptionStatusChanged,n.enabled,this.room.localParticipant),this.encryptionEnabled=n.enabled;else if(n.participantIdentity){let e=this.room?.getParticipantByIdentity(n.participantIdentity);if(!e)throw TypeError(`couldn't set encryption status, participant not found${n.participantIdentity}`);this.emit(vx.ParticipantEncryptionStatusChanged,n.enabled,e)}break;case`ratchetKey`:this.keyProvider.emit(gx.KeyRatcheted,n.ratchetResult,n.participantIdentity,n.keyIndex);break;case`decryptDataResponse`:let e=this.decryptDataRequests.get(n.uuid);e?.resolve&&e.resolve(n);break;case`encryptDataResponse`:let t=this.encryptDataRequests.get(n.uuid);t?.resolve&&t.resolve(n);break}},this.onWorkerError=e=>{I.error(`e2ee worker encountered an error:`,{error:e.error}),this.emit(vx.EncryptionError,e.error,void 0)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1,this.dataChannelEncryptionEnabled=t}get isEnabled(){return this.encryptionEnabled}get isDataChannelEncryptionEnabled(){return this.isEnabled&&this.dataChannelEncryptionEnabled}setup(e){if(!bx())throw new my(`tried to setup end-to-end encryption on an unsupported browser`);if(I.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:N_.getLevel()}};this.worker&&(I.info(`initializing worker`,{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){I.debug(`set e2ee to ${e} for participant ${t}`),this.postEnable(e,t)}setSifTrailer(e){!e||e.length===0?I.warn(`ignoring server sent trailer as it's empty`):this.postSifTrailer(e)}setupEngine(e){e.on(H.RTPVideoMapUpdate,e=>{this.postRTPMap(e)})}setupEventListeners(e,t){e.on(B.TrackPublished,(e,t)=>this.setParticipantCryptorEnabled(e.trackInfo.encryption!==F.NONE,t.identity)),e.on(B.ConnectionStateChanged,t=>{t===Y.Connected&&e.remoteParticipants.forEach(e=>{e.trackPublications.forEach(t=>{this.setParticipantCryptorEnabled(t.trackInfo.encryption!==F.NONE,e.identity)})})}).on(B.TrackUnsubscribed,(e,t,n)=>{var r;let i={kind:`removeTransform`,data:{participantIdentity:n.identity,trackId:e.mediaStreamID}};(r=this.worker)==null||r.postMessage(i)}).on(B.TrackSubscribed,(e,t,n)=>{this.setupE2EEReceiver(e,n.identity,t.trackInfo)}).on(B.SignalConnected,()=>{if(!this.room)throw TypeError(`expected room to be present on signal connect`);let e=t.getLatestManuallySetKeyIndex();t.getKeys().forEach(t=>{this.postKey(t,e===(t.keyIndex??0))}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(V.LocalSenderCreated,(e,t)=>L(this,void 0,void 0,function*(){this.setupE2EESender(t,e)})),e.localParticipant.on(V.LocalTrackPublished,e=>{if(!Qb(e.track)||!_b())return;let t={kind:`updateCodec`,data:{trackId:e.track.mediaStreamID,codec:Wy(e.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(t)}),t.on(gx.SetKey,(e,t)=>this.postKey(e,t??!0)).on(gx.RatchetRequest,(e,t)=>this.postRatchetRequest(e,t))}encryptData(e){return L(this,void 0,void 0,function*(){if(!this.worker)throw Error(`could not encrypt data, worker is missing`);let t=crypto.randomUUID(),n={kind:`encryptDataRequest`,data:{uuid:t,payload:e,participantIdentity:this.room.localParticipant.identity}},r=new Bb;return r.onFinally=()=>{this.encryptDataRequests.delete(t)},this.encryptDataRequests.set(t,r),this.worker.postMessage(n),r.promise})}handleEncryptedData(e,t,n,r){if(!this.worker)throw Error(`could not handle encrypted data, worker is missing`);let i=crypto.randomUUID(),a={kind:`decryptDataRequest`,data:{uuid:i,payload:e,iv:t,participantIdentity:n,keyIndex:r}},o=new Bb;return o.onFinally=()=>{this.decryptDataRequests.delete(i)},this.decryptDataRequests.set(i,o),this.worker.postMessage(a),o.promise}postRatchetRequest(e,t){if(!this.worker)throw Error(`could not ratchet key, worker is missing`);let n={kind:`ratchetRequest`,data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(n)}postKey(e,t){let{key:n,participantIdentity:r,keyIndex:i}=e;if(!this.worker)throw Error(`could not set key, worker is missing`);let a={kind:`setKey`,data:{participantIdentity:r,isPublisher:r===this.room?.localParticipant.identity,key:n,keyIndex:i,updateCurrentKeyIndex:t}};this.worker.postMessage(a)}postEnable(e,t){if(this.worker){let n={kind:`enable`,data:{enabled:e,participantIdentity:t}};this.worker.postMessage(n)}else throw ReferenceError(`failed to enable e2ee, worker is not ready`)}postRTPMap(e){if(!this.worker)throw TypeError(`could not post rtp map, worker is missing`);if(!this.room?.localParticipant.identity)throw TypeError(`could not post rtp map, local participant identity is missing`);let t={kind:`setRTPMap`,data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(t)}postSifTrailer(e){if(!this.worker)throw Error(`could not post SIF trailer, worker is missing`);let t={kind:`setSifTrailer`,data:{trailer:e}};this.worker.postMessage(t)}setupE2EEReceiver(e,t,n){if(e.receiver){if(!n?.mimeType||n.mimeType===``)throw TypeError(`MimeType missing from trackInfo, cannot set up E2EE cryptor`);this.handleReceiver(e.receiver,e.mediaStreamID,t,e.kind===`video`?Wy(n.mimeType):void 0)}}setupE2EESender(e,t){if(!Xb(e)||!t){t||I.warn(`early return because sender is not ready`);return}this.handleSender(t,e.mediaStreamID,void 0)}handleReceiver(e,t,n,r){return L(this,void 0,void 0,function*(){if(this.worker){if(xx()&&!hb()){let i={kind:`decode`,participantIdentity:n,trackId:t,codec:r};e.transform=new RTCRtpScriptTransform(this.worker,i)}else{if(hx in e&&r){let e={kind:`updateCodec`,data:{trackId:t,codec:r,participantIdentity:n}};this.worker.postMessage(e);return}let i=e.writableStream,a=e.readableStream;if(!i||!a){let t=e.createEncodedStreams();e.writableStream=t.writable,i=t.writable,e.readableStream=t.readable,a=t.readable}let o={kind:`decode`,data:{readableStream:a,writableStream:i,trackId:t,codec:r,participantIdentity:n,isReuse:hx in e}};this.worker.postMessage(o,[a,i])}e[hx]=!0}})}handleSender(e,t,n){if(!(hx in e||!this.worker)){if(!this.room?.localParticipant.identity||this.room.localParticipant.identity===``)throw TypeError(`local identity needs to be known in order to set up encrypted sender`);if(xx()&&!hb()){I.info(`initialize script transform`);let r={kind:`encode`,participantIdentity:this.room.localParticipant.identity,trackId:t,codec:n};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{I.info(`initialize encoded streams`);let r=e.createEncodedStreams(),i={kind:`encode`,data:{readableStream:r.readable,writableStream:r.writable,codec:n,trackId:t,participantIdentity:this.room.localParticipant.identity,isReuse:!1}};this.worker.postMessage(i,[r.readable,r.writable])}e[hx]=!0}}},Ex=500,Dx=15e3,Ox=class e{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||=new e,this._instance}addFailedConnectionAttempt(e){let t=Tb(new URL(e));if(!t)return;let n=this.failedConnectionAttempts.get(t)??0;this.failedConnectionAttempts.set(t,n+1),this.backOffPromises.set(t,ob(Math.min(Ex*2**n,Dx)))}getBackOffPromise(e){let t=new URL(e),n=t&&Tb(t);return n&&this.backOffPromises.get(n)||Promise.resolve()}resetFailedConnectionAttempts(e){let t=new URL(e),n=t&&Tb(t);n&&(this.failedConnectionAttempts.set(n,0),this.backOffPromises.set(n,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}};Ox._instance=null;var kx=`default`,Ax=class e{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new e),this.instance}get previousDevices(){return this._previousDevices}getDevices(t){return L(this,arguments,void 0,function(t){var n=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){if(e.userMediaPromiseMap?.size>0){I.debug(`awaiting getUserMedia promise`);try{t?yield e.userMediaPromiseMap.get(t):yield Promise.all(e.userMediaPromiseMap.values())}catch{I.warn(`error waiting for media permissons`)}}let i=yield navigator.mediaDevices.enumerateDevices();if(r&&!(gb()&&n.hasDeviceInUse(t))&&(i.filter(e=>e.kind===t).length===0||i.some(e=>{let n=e.label===``,r=t?e.kind===t:!0;return n&&r}))){let e={video:t!==`audioinput`&&t!==`audiooutput`,audio:t!==`videoinput`&&{deviceId:{ideal:`default`}}},n=yield navigator.mediaDevices.getUserMedia(e);i=yield navigator.mediaDevices.enumerateDevices(),n.getTracks().forEach(e=>{e.stop()})}return n._previousDevices=i,t&&(i=i.filter(e=>e.kind===t)),i}()})}normalizeDeviceId(e,t,n){return L(this,void 0,void 0,function*(){if(t!==kx)return t;let r=yield this.getDevices(e),i=r.find(e=>e.deviceId===kx);if(!i){I.warn(`could not reliably determine default device`);return}let a=r.find(e=>e.deviceId!==kx&&e.groupId===(n??i.groupId));if(!a){I.warn(`could not reliably determine default device`);return}return a?.deviceId})}hasDeviceInUse(t){return t?e.userMediaPromiseMap.has(t):e.userMediaPromiseMap.size>0}};Ax.mediaDeviceKinds=[`audioinput`,`audiooutput`,`videoinput`],Ax.userMediaPromiseMap=new Map;var jx=65535,Mx=4294967295,Nx=class e{static u16(t){return new e(t,jx)}static u32(t){return new e(t,Mx)}constructor(e,t){if(this.value=e,e<0)throw Error(`WrapAroundUnsignedInt: cannot faithfully represent an integer smaller than 0`);if(t>2**53-1)throw Error(`WrapAroundUnsignedInt: cannot faithfully represent an integer bigger than MAX_SAFE_INTEGER.`);this.maxSize=t,this.clamp()}clamp(){for(;this.value>this.maxSize;)this.value-=this.maxSize+1;for(;this.value<0;)this.value+=this.maxSize+1}clone(){return new e(this.value,this.maxSize)}update(e){this.value=e(this.value),this.clamp()}increment(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1;this.update(t=>t+e)}decrement(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1;this.update(t=>t-e)}getThenIncrement(){let t=this.value;return this.increment(),new e(t,this.maxSize)}isBefore(e){let t=this.value>>>0,n=(e.value>>>0)-t>>>0;return n!==0&&n<this.maxSize+1}},Px=class e{static fromRtpTicks(t){return new e(t,9e4)}static rtpRandom(){let t=Math.round(Math.random()*Mx);return e.fromRtpTicks(t)}constructor(e,t){this.timestamp=Nx.u32(e),this.rateInHz=t}asTicks(){return this.timestamp.value}clone(){return new e(this.timestamp.value,this.rateInHz)}wrappingAdd(e){this.timestamp.increment(e)}isBefore(e){return this.timestamp.isBefore(e.timestamp)}},Fx=class e{constructor(e,t,n){this.epoch=t,this.base=n,this.previous=n.clone(),this.rateInHz=e}static startingNow(t,n){return new e(n,new Date,t)}static startingAtTime(t,n,r){return new e(r,t,n)}static rtpStartingNow(t){return e.startingNow(t,9e4)}static rtpStartingAtTime(t,n){return e.startingAtTime(t,n,9e4)}now(){return this.at(new Date)}at(t){let n=t.getTime()-this.epoch.getTime(),r=e.durationInMsToTicks(n,this.rateInHz),i=this.base.clone();return i.wrappingAdd(r),i.isBefore(this.previous)&&(i=this.previous),this.previous=i.clone(),i.clone()}static durationInMsToTicks(e,t){let n=(e*1e6*t+5e8)/1e9;return Math.round(n)}};function Ix(e){if(e instanceof DataView)return e;if(e instanceof ArrayBuffer)return new DataView(e);if(e instanceof Uint8Array)return new DataView(e.buffer,e.byteOffset,e.byteLength);throw Error(`Error coercing ${e} to DataView - input was not DataView, ArrayBuffer, or Uint8Array.`)}var Lx;(function(e){e[e.Reserved=0]=`Reserved`,e[e.TooLarge=1]=`TooLarge`})(Lx||={});var Rx=class e extends py{constructor(e,t){super(19,e),this.name=`DataTrackHandleError`,this.reason=t,this.reasonName=Lx[t]}isReason(e){return this.reason===e}static tooLarge(){return new e(`Value too large to be a valid track handle`,Lx.TooLarge)}static reserved(t){return new e(`0x${t.toString(16)} is a reserved value.`,Lx.Reserved)}},zx={fromNumber(e){if(e===0)throw Rx.reserved(e);if(e>jx)throw Rx.tooLarge();return e}},Bx=class{constructor(){this.value=0}get(){return this.value+=1,this.value>jx?null:this.value}},Vx={from(e){return{sid:e.sid,pubHandle:e.pubHandle,name:e.name,usesE2ee:e.encryption!==F.NONE}},toProtobuf(e){return new Ph({sid:e.sid,pubHandle:e.pubHandle,name:e.name,encryption:e.usesE2ee?F.GCM:F.NONE})}},Hx;(function(e){e[e.WAITING=0]=`WAITING`,e[e.RUNNING=1]=`RUNNING`,e[e.COMPLETED=2]=`COMPLETED`})(Hx||={});var Ux=class{constructor(){this.pendingTasks=new Map,this.taskMutex=new hp,this.nextTaskIndex=0}run(e){return L(this,void 0,void 0,function*(){let t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:Hx.WAITING};this.pendingTasks.set(t.id,t);let n=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=Hx.RUNNING,yield e()}finally{t.status=Hx.COMPLETED,this.pendingTasks.delete(t.id),n()}})}flush(){return L(this,void 0,void 0,function*(){return this.run(()=>L(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}},Wx=class{get readyState(){return this.ws.readyState}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(t.signal?.aborted)throw new DOMException(`This operation was aborted`,`AbortError`);this.url=e;let n=new WebSocket(e,t.protocols??[]);n.binaryType=`arraybuffer`,this.ws=n;let r=function(){let{closeCode:e,reason:t}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return n.close(e,t)};this.opened=new iy((e,t)=>{let i=()=>{t(z.websocket(`Encountered websocket error during connection establishment`))};n.onopen=()=>{e({readable:new ReadableStream({start(e){n.onmessage=t=>{let{data:n}=t;return e.enqueue(n)},n.onerror=t=>e.error(t)},cancel:r}),writable:new WritableStream({write(e){n.send(e)},abort(){n.close()},close:r}),protocol:n.protocol,extensions:n.extensions}),n.removeEventListener(`error`,i)},n.addEventListener(`error`,i)}),this.closed=new iy((e,t)=>{let r=()=>L(this,void 0,void 0,function*(){let r=new iy(e=>{n.readyState!==WebSocket.CLOSED&&n.addEventListener(`close`,t=>{e(t)},{once:!0})}),i=yield iy.race([ob(250),r]);i?e(i):t(z.websocket(`Encountered unspecified websocket error without a timely close event`))});n.onclose=t=>{let{code:i,reason:a}=t;e({closeCode:i,reason:a}),n.removeEventListener(`error`,r)},n.addEventListener(`error`,r)}),t.signal&&(t.signal.onabort=()=>n.close()),this.close=r}},Gx=[`syncState`,`trickle`,`offer`,`answer`,`simulate`,`leave`];function Kx(e){let t=Gx.indexOf(e.case)>=0;return I.trace(`request allowed to bypass queue:`,{canPass:t,req:e}),t}var q;(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`})(q||={});var qx=250,Jx=class{get currentState(){return this.state}get isDisconnected(){return this.state===q.DISCONNECTING||this.state===q.DISCONNECTED}get isEstablishingConnection(){return this.state===q.CONNECTING||this.state===q.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.rtt=0,this.state=q.DISCONNECTED,this.log=I,this._requestId=0,this.useV0SignalPath=!1,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0,this.onMediaSectionsRequirement=void 0},this.log=M_(t.loggerName??j_.Signal),this.loggerContextCb=t.loggerContextCb,this.useJSON=e,this.requestQueue=new Ux,this.queuedRequests=[],this.closingLock=new hp,this.connectionLock=new hp,this.state=q.DISCONNECTED}get logContext(){return this.loggerContextCb?.call(this)??{}}join(e,t,n,r){return L(this,arguments,void 0,function(e,t,n,r){var i=this;let a=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1,o=arguments.length>5?arguments[5]:void 0;return function*(){return i.state=q.CONNECTING,i.options=n,yield i.connect(e,t,n,r,a,o)}()})}reconnect(e,t,n,r){return L(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=q.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:n,reconnectReason:r}),void 0,this.useV0SignalPath)})}connect(e,t,n,r){return L(this,arguments,void 0,function(e,t,n,r){var i=this;let a=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1,o=arguments.length>5?arguments[5]:void 0;return function*(){let s=yield i.connectionLock.lock();i.connectOptions=n,i.useV0SignalPath=a;let c=Ib(),l=cx(e,a?Zx(t,c,n):yield Qx(t,c,n,o),a).toString(),u=ux(l).toString();return new Promise((e,t)=>L(i,void 0,void 0,function*(){try{let i=!1,a=e=>L(this,void 0,void 0,function*(){if(i)return;i=!0;let n=mx(e instanceof Event?e.currentTarget:e,`Abort handler called`);this.streamWriter&&!this.isDisconnected?this.sendLeave().then(()=>this.close(n)).catch(e=>{this.log.error(e),this.close()}):this.close(),o(),t(z.cancelled(n))});r?.addEventListener(`abort`,a);let o=()=>{clearTimeout(s),r?.removeEventListener(`abort`,a)},s=setTimeout(()=>{a(z.timeout(`room connection has timed out (signal)`))},n.websocketTimeout),c=(e,t)=>{this.handleSignalConnected(e,s,t)},d=new URL(l);d.searchParams.has(`access_token`)&&d.searchParams.set(`access_token`,`<redacted>`),this.log.debug(`connecting to ${d}`,Object.assign({reconnect:n.reconnect,reconnectReason:n.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new Wx(l);try{this.ws.closed.then(e=>{this.isEstablishingConnection&&t(z.internal(`Websocket got closed during a (re)connection attempt: ${e.reason}`)),e.closeCode!==1e3&&(this.log.warn(`websocket closed`,Object.assign(Object.assign({},this.logContext),{reason:e.reason,code:e.closeCode,wasClean:e.closeCode===1e3,state:this.state})),this.state===q.CONNECTED&&this.handleOnClose(e.reason??`Unexpected WS error`))}).catch(e=>{this.isEstablishingConnection&&t(z.internal(`Websocket error during a (re)connection attempt: ${e}`))});let r=yield this.ws.opened.catch(e=>L(this,void 0,void 0,function*(){if(this.state!==q.CONNECTED){this.state=q.DISCONNECTED,clearTimeout(s),t(yield this.handleConnectionError(e,u));return}this.handleWSError(e),t(e)}));if(clearTimeout(s),!r)return;let i=r.readable.getReader();this.streamWriter=r.writable.getWriter();let a=yield i.read();if(i.releaseLock(),!a.value)throw z.internal(`no message received as first message`);let o=px(a.value),l=this.validateFirstMessage(o,n.reconnect??!1);if(!l.isValid){t(l.error);return}o.message?.case===`join`&&(this.pingTimeoutDuration=o.message.value.pingTimeout,this.pingIntervalDuration=o.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.onJoined&&this.onJoined(o.message.value)),c(r,l.shouldProcessFirstMessage?o:void 0),e(l.response)}catch(e){t(e)}finally{o()}}finally{s()}}))}()})}startReadingLoop(e,t){return L(this,void 0,void 0,function*(){for(t&&this.handleSignalResponse(t);;){this.signalLatency&&(yield ob(this.signalLatency));let{done:t,value:n}=yield e.read();if(t)break;let r=px(n);this.handleSignalResponse(r)}})}close(){return L(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:`Close method called on signal client`;return function*(){if([q.DISCONNECTING||q.DISCONNECTED].includes(e.state)){e.log.debug(`ignoring signal close as it's already in disconnecting state`);return}let r=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=q.DISCONNECTING),e.ws){e.ws.close({closeCode:1e3,reason:n});let t=e.ws.closed;e.ws=void 0,e.streamWriter=void 0,yield Promise.race([t,ob(qx)])}}catch(t){e.log.debug(`websocket error while closing`,Object.assign(Object.assign({},e.logContext),{error:t}))}finally{t&&(e.state=q.DISCONNECTED),r()}}()})}sendOffer(e,t){this.log.debug(`sending offer`,Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:`offer`,value:Xx(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:Xx(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 Og({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:`mute`,value:new kg({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:`addTrack`,value:e})}sendUpdateLocalMetadata(e,t){return L(this,arguments,void 0,function(e,t){var n=this;let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return function*(){let i=n.getNextRequestId();return yield n.sendRequest({case:`updateMetadata`,value:new Gg({requestId:i,metadata:e,name:t,attributes:r})}),i}()})}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 Wg({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:`subscriptionPermission`,value:new i_({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:`simulate`,value:e})}sendPing(){return Promise.all([this.sendRequest({case:`ping`,value:Kp.parse(Date.now())}),this.sendRequest({case:`pingReq`,value:new d_({timestamp:Kp.parse(Date.now()),rtt:Kp.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:`updateAudioTrack`,value:new Bg({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:`leave`,value:new Hg({reason:xh.CLIENT_INITIATED,action:Ug.DISCONNECT})})}sendPublishDataTrackRequest(e,t,n){return this.sendRequest({case:`publishDataTrackRequest`,value:new Sg({pubHandle:e,name:t,encryption:n?F.GCM:F.NONE})})}sendUnPublishDataTrackRequest(e){return this.sendRequest({case:`unpublishDataTrackRequest`,value:new wg({pubHandle:e})})}sendUpdateDataSubscription(e,t){return this.sendRequest({case:`updateDataSubscription`,value:new Lg({updates:[new Rg({trackSid:e,subscribe:t})]})})}sendRequest(e){return L(this,arguments,void 0,function(e){var t=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return function*(){if(!n&&!Kx(e)&&t.state===q.RECONNECTING){t.queuedRequests.push(()=>L(t,void 0,void 0,function*(){yield this.sendRequest(e,!0)}));return}if(n||(yield t.requestQueue.flush()),t.signalLatency&&(yield ob(t.signalLatency)),t.isDisconnected){t.log.debug(`skipping signal request (type: ${e.case}) - SignalClient disconnected`);return}if(!t.streamWriter){t.log.error(`cannot send signal request before connected, type: ${e?.case}`,t.logContext);return}let r=new vg({message:e});try{t.useJSON?yield t.streamWriter.write(r.toJsonString()):yield t.streamWriter.write(r.toBinary())}catch(e){t.log.error(`error sending signal message`,Object.assign(Object.assign({},t.logContext),{error:e}))}}()})}handleSignalResponse(e){let t=e.message;if(t==null){this.log.debug(`received unsupported message`,this.logContext);return}let n=!1;if(t.case===`answer`){let e=Yx(t.value);this.onAnswer&&this.onAnswer(e,t.value.id,t.value.midToTrackId)}else if(t.case===`offer`){let e=Yx(t.value);this.onOffer&&this.onOffer(e,t.value.id,t.value.midToTrackId)}else if(t.case===`trickle`){let e=JSON.parse(t.value.candidateInit);this.onTrickle&&this.onTrickle(e,t.value.target)}else t.case===`update`?this.onParticipantUpdate&&this.onParticipantUpdate(t.value.participants??[]):t.case===`trackPublished`?this.onLocalTrackPublished&&this.onLocalTrackPublished(t.value):t.case===`speakersChanged`?this.onSpeakersChanged&&this.onSpeakersChanged(t.value.speakers??[]):t.case===`leave`?this.onLeave&&this.onLeave(t.value):t.case===`mute`?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(t.value.sid,t.value.muted):t.case===`roomUpdate`?this.onRoomUpdate&&t.value.room&&this.onRoomUpdate(t.value.room):t.case===`connectionQuality`?this.onConnectionQuality&&this.onConnectionQuality(t.value):t.case===`streamStateUpdate`?this.onStreamStateUpdate&&this.onStreamStateUpdate(t.value):t.case===`subscribedQualityUpdate`?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(t.value):t.case===`subscriptionPermissionUpdate`?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(t.value):t.case===`refreshToken`?this.onTokenRefresh&&this.onTokenRefresh(t.value):t.case===`trackUnpublished`?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(t.value):t.case===`subscriptionResponse`?this.onSubscriptionError&&this.onSubscriptionError(t.value):t.case===`pong`||(t.case===`pongResp`?(this.rtt=Date.now()-Number.parseInt(t.value.lastPingTimestamp.toString()),this.resetPingTimeout(),n=!0):t.case===`requestResponse`?this.onRequestResponse&&this.onRequestResponse(t.value):t.case===`trackSubscribed`?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(t.value.trackSid):t.case===`roomMoved`?(this.onTokenRefresh&&this.onTokenRefresh(t.value.token),this.onRoomMoved&&this.onRoomMoved(t.value)):t.case===`mediaSectionsRequirement`?this.onMediaSectionsRequirement&&this.onMediaSectionsRequirement(t.value):t.case===`publishDataTrackResponse`?this.onPublishDataTrackResponse&&this.onPublishDataTrackResponse(t.value):t.case===`unpublishDataTrackResponse`?this.onUnPublishDataTrackResponse&&this.onUnPublishDataTrackResponse(t.value):t.case===`dataTrackSubscriberHandles`?this.onDataTrackSubscriberHandles&&this.onDataTrackSubscriberHandles(t.value):this.log.debug(`unsupported message`,Object.assign(Object.assign({},this.logContext),{msgCase:t.case})));n||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){let e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return L(this,void 0,void 0,function*(){if(this.state===q.DISCONNECTED)return;let t=this.onClose;yield this.close(void 0,e),this.log.debug(`websocket connection closed: ${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=Ty.setTimeout(()=>{this.log.warn(`ping timeout triggered. last pong received at: ${new Date(Date.now()-this.pingTimeoutDuration*1e3).toUTCString()}`,this.logContext),this.handleOnClose(`ping timeout`)},this.pingTimeoutDuration*1e3)}clearPingTimeout(){this.pingTimeout&&Ty.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=Ty.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug(`clearing ping interval`,this.logContext),this.clearPingTimeout(),this.pingInterval&&Ty.clearInterval(this.pingInterval)}handleSignalConnected(e,t,n){this.state=q.CONNECTED,clearTimeout(t),this.startPingInterval(),this.startReadingLoop(e.readable.getReader(),n)}validateFirstMessage(e,t){return e.message?.case===`join`?{isValid:!0,response:e.message.value}:this.state===q.RECONNECTING&&e.message?.case!==`leave`?e.message?.case===`reconnect`?{isValid:!0,response:e.message.value}:(this.log.debug(`declaring signal reconnected without reconnect response received`,this.logContext),{isValid:!0,response:void 0,shouldProcessFirstMessage:!0}):this.isEstablishingConnection&&e.message?.case===`leave`?{isValid:!1,error:z.leaveRequest(`Received leave request while trying to (re)connect`,e.message.value.reason)}:t?{isValid:!1,error:z.internal(`Unexpected first message`)}:{isValid:!1,error:z.internal(`did not receive join response, got ${e.message?.case} instead`)}}handleConnectionError(e,t){return L(this,void 0,void 0,function*(){try{let n=yield fetch(t);switch(n.status){case 404:return z.serviceNotFound(`v1 RTC path not found. Consider upgrading your LiveKit server version`,`v0-rtc`);case 401:case 403:let e=yield n.text();return z.notAllowed(e,n.status);default:break}return e instanceof z?e:z.internal(`Encountered unknown websocket error during connection: ${e}`,{status:n.status,statusText:n.statusText})}catch(e){return e instanceof z?e:z.serverUnreachable(e instanceof Error?e.message:`server was not reachable`)}})}};function Yx(e){let t={type:`offer`,sdp:e.sdp};switch(e.type){case`answer`:case`offer`:case`pranswer`:case`rollback`:t.type=e.type;break}return t}function Xx(e,t){return new Pg({sdp:e.sdp,type:e.type,id:t})}function Zx(e,t,n){let r=new URLSearchParams;return r.set(`access_token`,e),n.reconnect&&(r.set(`reconnect`,`1`),n.sid&&r.set(`sid`,n.sid)),r.set(`auto_subscribe`,n.autoSubscribe?`1`:`0`),r.set(`sdk`,Cb()?`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),n.adaptiveStream&&r.set(`adaptive_stream`,`1`),n.reconnectReason&&r.set(`reconnect_reason`,n.reconnectReason.toString()),navigator.connection?.type&&r.set(`network`,navigator.connection.type),r}function Qx(e,t,n,r){return L(this,void 0,void 0,function*(){let i=new URLSearchParams;i.set(`access_token`,e);let a=new b_({clientInfo:t,connectionSettings:new y_({autoSubscribe:!!n.autoSubscribe,adaptiveStream:!!n.adaptiveStream}),reconnect:!!n.reconnect,participantSid:n.sid?n.sid:void 0,publisherOffer:r});n.reconnectReason&&(a.reconnectReason=n.reconnectReason);let o=a.toBinary(),s,c;if(sx()){let e=new CompressionStream(`gzip`),t=e.writable.getWriter();t.write(new Uint8Array(o)),t.close();let n=[],r=e.readable.getReader();for(;;){let{done:e,value:t}=yield r.read();if(e)break;n.push(t)}let i=n.reduce((e,t)=>e+t.length,0),a=new Uint8Array(i),l=0;for(let e of n)a.set(e,l),l+=e.length;s=a,c=S_.GZIP}else s=o,c=S_.NONE;let l=new x_({joinRequest:s,compression:c}).toBinary();return i.set(`join_request`,(e=>{let t=Array.from(e,e=>String.fromCodePoint(e)).join(``);return btoa(t)})(l).replace(/\+/g,`-`).replace(/\//g,`_`)),i})}var $x=class{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&&this.buffer[0].sequence<=e;)this.pop()}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}},eS=class{constructor(e){this._map=new Map,this._lastCleanup=0,this.ttl=e}set(e,t){let n=Date.now();n-this._lastCleanup>this.ttl/2&&this.cleanup();let r=n+this.ttl;return this._map.set(e,{value:t,expiresAt:r}),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):!0:!1}delete(e){return this._map.delete(e)}clear(){this._map.clear()}cleanup(){let e=Date.now();for(let[t,n]of this._map.entries())n.expiresAt<e&&this._map.delete(t);this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){this.cleanup();for(let[t,n]of this._map.entries())n.expiresAt>=Date.now()&&e(n.value,t,this.asValueMap())}map(e){this.cleanup();let t=[],n=this.asValueMap();for(let[r,i]of n.entries())t.push(e(i,r,n));return t}asValueMap(){let e=new Map;for(let[t,n]of this._map.entries())n.expiresAt>=Date.now()&&e.set(t,n.value);return e}},tS={},nS={},rS={exports:{}},iS;function aS(){if(iS)return rS.exports;iS=1;var e=rS.exports={v:[{name:`version`,reg:/^(\d*)$/}],o:[{name:`origin`,reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:[`username`,`sessionId`,`sessionVersion`,`netType`,`ipVer`,`address`],format:`%s %s %d %s IP%d %s`}],s:[{name:`name`}],i:[{name:`description`}],u:[{name:`uri`}],e:[{name:`email`}],p:[{name:`phone`}],z:[{name:`timezones`}],r:[{name:`repeats`}],t:[{name:`timing`,reg:/^(\d*) (\d*)/,names:[`start`,`stop`],format:`%d %d`}],c:[{name:`connection`,reg:/^IN IP(\d) (\S*)/,names:[`version`,`ip`],format:`IN IP%d %s`}],b:[{push:`bandwidth`,reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:[`type`,`limit`],format:`%s:%s`}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:[`type`,`port`,`protocol`,`payloads`],format:`%s %d %s %s`}],a:[{push:`rtp`,reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:[`payload`,`codec`,`rate`,`encoding`],format:function(e){return e.encoding?`rtpmap:%d %s/%s/%s`:e.rate?`rtpmap:%d %s/%s`:`rtpmap:%d %s`}},{push:`fmtp`,reg:/^fmtp:(\d*) ([\S| ]*)/,names:[`payload`,`config`],format:`fmtp:%d %s`},{name:`control`,reg:/^control:(.*)/,format:`control:%s`},{name:`rtcp`,reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:[`port`,`netType`,`ipVer`,`address`],format:function(e){return e.address==null?`rtcp:%d`:`rtcp:%d %s IP%d %s`}},{push:`rtcpFbTrrInt`,reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:[`payload`,`value`],format:`rtcp-fb:%s trr-int %d`},{push:`rtcpFb`,reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:[`payload`,`type`,`subtype`],format:function(e){return e.subtype==null?`rtcp-fb:%s %s`:`rtcp-fb:%s %s %s`}},{push:`ext`,reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:[`value`,`direction`,`encrypt-uri`,`uri`,`config`],format:function(e){return`extmap:%d`+(e.direction?`/%s`:`%v`)+(e[`encrypt-uri`]?` %s`:`%v`)+` %s`+(e.config?` %s`:``)}},{name:`extmapAllowMixed`,reg:/^(extmap-allow-mixed)/},{push:`crypto`,reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:[`id`,`suite`,`config`,`sessionConfig`],format:function(e){return e.sessionConfig==null?`crypto:%d %s %s`:`crypto:%d %s %s %s`}},{name:`setup`,reg:/^setup:(\w*)/,format:`setup:%s`},{name:`connectionType`,reg:/^connection:(new|existing)/,format:`connection:%s`},{name:`mid`,reg:/^mid:([^\s]*)/,format:`mid:%s`},{name:`msid`,reg:/^msid:(.*)/,format:`msid:%s`},{name:`ptime`,reg:/^ptime:(\d*(?:\.\d*)*)/,format:`ptime:%d`},{name:`maxptime`,reg:/^maxptime:(\d*(?:\.\d*)*)/,format:`maxptime:%d`},{name:`direction`,reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:`icelite`,reg:/^(ice-lite)/},{name:`iceUfrag`,reg:/^ice-ufrag:(\S*)/,format:`ice-ufrag:%s`},{name:`icePwd`,reg:/^ice-pwd:(\S*)/,format:`ice-pwd:%s`},{name:`fingerprint`,reg:/^fingerprint:(\S*) (\S*)/,names:[`type`,`hash`],format:`fingerprint:%s %s`},{push:`candidates`,reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:[`foundation`,`component`,`transport`,`priority`,`ip`,`port`,`type`,`raddr`,`rport`,`tcptype`,`generation`,`network-id`,`network-cost`],format:function(e){var t=`candidate:%s %d %s %d %s %d typ %s`;return t+=e.raddr==null?`%v%v`:` raddr %s rport %d`,t+=e.tcptype==null?`%v`:` tcptype %s`,e.generation!=null&&(t+=` generation %d`),t+=e[`network-id`]==null?`%v`:` network-id %d`,t+=e[`network-cost`]==null?`%v`:` network-cost %d`,t}},{name:`endOfCandidates`,reg:/^(end-of-candidates)/},{name:`remoteCandidates`,reg:/^remote-candidates:(.*)/,format:`remote-candidates:%s`},{name:`iceOptions`,reg:/^ice-options:(\S*)/,format:`ice-options:%s`},{push:`ssrcs`,reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:[`id`,`attribute`,`value`],format:function(e){var t=`ssrc:%d`;return e.attribute!=null&&(t+=` %s`,e.value!=null&&(t+=`:%s`)),t}},{push:`ssrcGroups`,reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:[`semantics`,`ssrcs`],format:`ssrc-group:%s %s`},{name:`msidSemantic`,reg:/^msid-semantic:\s?(\w*) (\S*)/,names:[`semantic`,`token`],format:`msid-semantic: %s %s`},{push:`groups`,reg:/^group:(\w*) (.*)/,names:[`type`,`mids`],format:`group:%s %s`},{name:`rtcpMux`,reg:/^(rtcp-mux)/},{name:`rtcpRsize`,reg:/^(rtcp-rsize)/},{name:`sctpmap`,reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:[`sctpmapNumber`,`app`,`maxMessageSize`],format:function(e){return e.maxMessageSize==null?`sctpmap:%s %s`:`sctpmap:%s %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`+(e.clksrcExt==null?``:`=%s`)}},{name:`mediaClk`,reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:[`id`,`mediaClockName`,`mediaClockValue`,`rateNumerator`,`rateDenominator`],format:function(e){var t=`mediaclk:`;return t+=e.id==null?`%v%s`:`id=%s %s`,t+=e.mediaClockValue==null?``:`=%s`,t+=e.rateNumerator==null?``:` rate=%s`,t+=e.rateDenominator==null?``:`/%s`,t}},{name:`keywords`,reg:/^keywds:(.+)$/,format:`keywds:%s`},{name:`content`,reg:/^content:(.+)/,format:`content:%s`},{name:`bfcpFloorCtrl`,reg:/^floorctrl:(c-only|s-only|c-s)/,format:`floorctrl:%s`},{name:`bfcpConfId`,reg:/^confid:(\d+)/,format:`confid:%s`},{name:`bfcpUserId`,reg:/^userid:(\d+)/,format:`userid:%s`},{name:`bfcpFloorId`,reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:[`id`,`mStream`],format:`floorid:%s mstrm:%s`},{push:`invalid`,names:[`value`]}]};return Object.keys(e).forEach(function(t){e[t].forEach(function(e){e.reg||=/(.*)/,e.format||=`%s`})}),rS.exports}var oS;function sS(){return oS?nS:(oS=1,(function(e){var t=function(e){return String(Number(e))===e?Number(e):e},n=function(e,n,r,i){if(i&&!r)n[i]=t(e[1]);else for(var a=0;a<r.length;a+=1)e[a+1]!=null&&(n[r[a]]=t(e[a+1]))},r=function(e,t,r){var i=e.name&&e.names;e.push&&!t[e.push]?t[e.push]=[]:i&&!t[e.name]&&(t[e.name]={});var a=e.push?{}:i?t[e.name]:t;n(r.match(e.reg),a,e.names,e.name),e.push&&t[e.push].push(a)},i=aS(),a=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},n=[],o=t;return e.split(/(\r\n|\r|\n)/).filter(a).forEach(function(e){var t=e[0],a=e.slice(2);t===`m`&&(n.push({rtp:[],fmtp:[]}),o=n[n.length-1]);for(var s=0;s<(i[t]||[]).length;s+=1){var c=i[t][s];if(c.reg.test(a))return r(c,o,a)}}),t.media=n,t};var o=function(e,n){var r=n.split(/=(.+)/,2);return r.length===2?e[r[0]]=t(r[1]):r.length===1&&n.length>1&&(e[r[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(o,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(` `).map(Number)},e.parseRemoteCandidates=function(e){for(var n=[],r=e.split(` `).map(t),i=0;i<r.length;i+=3)n.push({component:r[i],ip:r[i+1],port:r[i+2]});return n},e.parseImageAttributes=function(e){return e.split(` `).map(function(e){return e.substring(1,e.length-1).split(`,`).reduce(o,{})})},e.parseSimulcastStreamList=function(e){return e.split(`;`).map(function(e){return e.split(`,`).map(function(e){var n,r=!1;return e[0]===`~`?(n=t(e.substring(1,e.length)),r=!0):n=t(e),{scid:n,paused:r}})})}})(nS),nS)}var cS,lS;function uS(){if(lS)return cS;lS=1;var e=aS(),t=/%[sdv%]/g,n=function(e){var n=1,r=arguments,i=r.length;return e.replace(t,function(e){if(n>=i)return e;var t=r[n];switch(n+=1,e){case`%%`:return`%`;case`%s`:return String(t);case`%d`:return Number(t);case`%v`:return``}})},r=function(e,t,r){var i=t.format instanceof Function?t.format(t.push?r:r[t.name]):t.format,a=[e+`=`+i];if(t.names)for(var o=0;o<t.names.length;o+=1){var s=t.names[o];t.name?a.push(r[t.name][s]):a.push(r[t.names[o]])}else a.push(r[t.name]);return n.apply(null,a)},i=[`v`,`o`,`s`,`i`,`u`,`e`,`p`,`c`,`b`,`t`,`r`,`z`,`a`],a=[`i`,`c`,`b`,`a`];return cS=function(t,n){n||={},t.version??=0,t.name??=` `,t.media.forEach(function(e){e.payloads??=``});var o=n.outerOrder||i,s=n.innerOrder||a,c=[];return o.forEach(function(n){e[n].forEach(function(e){e.name in t&&t[e.name]!=null?c.push(r(n,e,t)):e.push in t&&t[e.push]!=null&&t[e.push].forEach(function(t){c.push(r(n,e,t))})})}),t.media.forEach(function(t){c.push(r(`m`,e.m[0],t)),s.forEach(function(n){e[n].forEach(function(e){e.name in t&&t[e.name]!=null?c.push(r(n,e,t)):e.push in t&&t[e.push]!=null&&t[e.push].forEach(function(t){c.push(r(n,e,t))})})})}),c.join(`\r
61
61
  `)+`\r
62
- `},iS}var sS;function cS(){if(sS)return Zx;sS=1;var e=rS(),t=oS();return Zx.grammar=tS(),Zx.write=t,Zx.parse=e.parse,Zx.parseParams=e.parseParams,Zx.parseFmtpConfig=e.parseFmtpConfig,Zx.parsePayloads=e.parsePayloads,Zx.parseRemoteCandidates=e.parseRemoteCandidates,Zx.parseImageAttributes=e.parseImageAttributes,Zx.parseSimulcastStreamList=e.parseSimulcastStreamList,Zx}var lS=cS();function uS(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:50,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},r,i=n.isImmediate??!1,a=n.callback??!1,o=n.maxWait,s=Date.now(),c=[];function l(){if(o!==void 0){let e=Date.now()-s;if(e+t>=o)return o-e}return t}let u=function(){for(var t=arguments.length,n=Array(t),o=0;o<t;o++)n[o]=arguments[o];let u=this;return new Promise((t,o)=>{let d=function(){if(r=void 0,s=Date.now(),!i){let t=e.apply(u,n);a&&a(t),c.forEach(e=>{let{resolve:n}=e;return n(t)}),c=[]}},f=i&&r===void 0;if(r!==void 0&&xy.clearTimeout(r),r=xy.setTimeout(d,l()),f){let r=e.apply(u,n);return a&&a(r),t(r)}c.push({resolve:t,reject:o})})};return u.cancel=function(e){r!==void 0&&xy.clearTimeout(r),c.forEach(t=>{let{reject:n}=t;return n(e)}),c=[]},u}var dS=.7,fS=20,pS={NegotiationStarted:`negotiationStarted`,NegotiationComplete:`negotiationComplete`,RTPVideoPayloadTypes:`rtpVideoPayloadTypes`},mS=class extends H_.EventEmitter{get pc(){return this._pc||=this.createPC(),this._pc}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),this.log=I,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=uS(e=>L(this,void 0,void 0,function*(){this.emit(pS.NegotiationStarted);try{yield this.createAndSendOffer()}catch(t){if(e)e(t);else throw t}}),fS),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,null)},this.log=O_(t.loggerName??D_.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC(),this.offerLock=new dp}createPC(){let e=new RTCPeerConnection(this.config);return e.onicecandidate=e=>{var t;e.candidate&&((t=this.onIceCandidate)==null||t.call(this,e.candidate))},e.onicecandidateerror=e=>{var t;(t=this.onIceCandidateError)==null||t.call(this,e)},e.oniceconnectionstatechange=()=>{var t;(t=this.onIceConnectionStateChange)==null||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;(t=this.onSignalingStatechange)==null||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;(t=this.onConnectionStateChange)==null||t.call(this,e.connectionState)},e.ondatachannel=e=>{var t;(t=this.onDataChannel)==null||t.call(this,e)},e.ontrack=e=>{var t;(t=this.onTrack)==null||t.call(this,e)},e}get logContext(){var e;return Object.assign({},(e=this.loggerOptions).loggerContextCb?.call(e))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState===`connected`||this.pc.iceConnectionState===`completed`)}addIceCandidate(e){return L(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 L(this,void 0,void 0,function*(){if(e.type===`answer`&&this.latestOfferId>0&&t>0&&t!==this.latestOfferId)return this.log.warn(`ignoring answer for old offer`,Object.assign(Object.assign({},this.logContext),{offerId:t,latestOfferId:this.latestOfferId})),!1;let n;if(e.type===`offer`){let{stereoMids:t,nackMids:n}=gS(e);this.remoteStereoMids=t,this.remoteNackMids=n}else if(e.type===`answer`){if(this.pendingInitialOffer){let e=this.pendingInitialOffer;this.pendingInitialOffer=void 0;let t=lS.parse(e.sdp??``);t.media.forEach(e=>{_S(e)}),this.log.debug(`setting pending initial offer before processing answer`,this.logContext),yield this.setMungedSDP(e,lS.write(t))}let t=lS.parse(e.sdp??``);t.media.forEach(e=>{let t=vS(e.mid);e.type===`audio`&&this.trackBitrates.some(n=>{if(!n.transceiver||t!=n.transceiver.mid)return!1;let r=0;if(e.rtp.some(e=>e.codec.toUpperCase()===n.codec.toUpperCase()?(r=e.payload,!0):!1),r===0)return!0;let i=!1;for(let t of e.fmtp)if(t.payload===r){t.config=t.config.split(`;`).filter(e=>!e.includes(`maxaveragebitrate`)).join(`;`),n.maxbr>0&&(t.config+=`;maxaveragebitrate=${n.maxbr*1e3}`),i=!0;break}return i||n.maxbr>0&&e.fmtp.push({payload:r,config:`maxaveragebitrate=${n.maxbr*1e3}`}),!0})}),n=lS.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()):e.type===`answer`&&(this.emit(pS.NegotiationComplete),e.sdp&&lS.parse(e.sdp).media.forEach(e=>{e.type===`video`&&this.emit(pS.RTPVideoPayloadTypes,e.rtp)})),!0})}createInitialOffer(){return L(this,void 0,void 0,function*(){let e=yield this.offerLock.lock();try{if(this.pc.signalingState!==`stable`){this.log.warn(`signaling state is not stable, cannot create initial offer`,this.logContext);return}let e=this.latestOfferId+1;this.latestOfferId=e;let t=yield this.pc.createOffer();this.pendingInitialOffer={sdp:t.sdp,type:t.type};let n=lS.parse(t.sdp??``);return n.media.forEach(e=>{_S(e)}),t.sdp=lS.write(n),{offer:t,offerId:e}}finally{e()}})}createAndSendOffer(e){return L(this,void 0,void 0,function*(){let t=yield this.offerLock.lock();try{if(this.onOffer===void 0)return;if(e?.iceRestart&&(this.log.debug(`restarting ICE`,this.logContext),this.restartingIce=!0),this._pc&&(this._pc.signalingState===`have-local-offer`||this.pendingInitialOffer)){let t=this._pc.remoteDescription;if(e?.iceRestart&&t)yield this._pc.setRemoteDescription(t);else{this.renegotiate=!0,this.log.debug(`requesting renegotiation`,Object.assign({},this.logContext));return}}else if(!this._pc||this._pc.signalingState===`closed`){this.log.warn(`could not createOffer with closed peer connection`,this.logContext);return}this.log.debug(`starting to negotiate`,this.logContext);let t=this.latestOfferId+1;this.latestOfferId=t;let n=yield this.pc.createOffer(e);this.log.debug(`original offer`,Object.assign({sdp:n.sdp},this.logContext));let r=lS.parse(n.sdp??``);if(r.media.forEach(e=>{_S(e),e.type===`audio`?hS(e,[`all`],[]):e.type===`video`&&this.trackBitrates.some(t=>{if(!e.msid||!t.cid||!e.msid.includes(t.cid))return!1;let n=0;if(e.rtp.some(e=>e.codec.toUpperCase()===t.codec.toUpperCase()?(n=e.payload,!0):!1),n===0||(sb(t.codec)&&!fb()&&this.ensureVideoDDExtensionForSVC(e,r),!sb(t.codec)))return!0;let i=Math.round(t.maxbr*dS);for(let t of e.fmtp)if(t.payload===n){t.config.includes(`x-google-start-bitrate`)||(t.config+=`;x-google-start-bitrate=${i}`);break}return!0})}),this.latestOfferId>t){this.log.warn(`latestOfferId mismatch`,Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:t}));return}yield this.setMungedSDP(n,lS.write(r)),this.onOffer(n,this.latestOfferId)}finally{t()}})}createAndSetAnswer(){return L(this,void 0,void 0,function*(){let e=yield this.pc.createAnswer(),t=lS.parse(e.sdp??``);return t.media.forEach(e=>{_S(e),e.type===`audio`&&hS(e,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(e,lS.write(t)),e})}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTransceiverOfKind(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new py(`PC closed, cannot add track`);return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){if(!this._pc)throw new py(`PC closed, cannot configure`);return this._pc?.setConfiguration(e)}canRemoveTrack(){return!!this._pc?.removeTrack}removeTrack(e){return this._pc?.removeTrack(e)}getConnectionState(){return this._pc?.connectionState??`closed`}getICEConnectionState(){return this._pc?.iceConnectionState??`closed`}getSignallingState(){return this._pc?.signalingState??`closed`}getTransceivers(){return this._pc?.getTransceivers()??[]}getSenders(){return this._pc?.getSenders()??[]}getLocalDescription(){return this._pc?.localDescription}getRemoteDescription(){return this.pc?.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return L(this,void 0,void 0,function*(){if(!this._pc)return;let e=``,t=new Map,n=new Map;if((yield this._pc.getStats()).forEach(r=>{switch(r.type){case`transport`:e=r.selectedCandidatePairId;break;case`candidate-pair`:e===``&&r.selected&&(e=r.id),t.set(r.id,r);break;case`remote-candidate`:n.set(r.id,`${r.address}:${r.port}`);break}}),e===``)return;let r=t.get(e)?.remoteCandidateId;if(r!==void 0)return n.get(r)})}setMungedSDP(e,t,n){return L(this,void 0,void 0,function*(){if(t){let r=e.sdp;e.sdp=t;try{this.log.debug(`setting munged ${n?`remote`:`local`} description`,this.logContext),n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(n){this.log.warn(`not able to set ${e.type}, falling back to unmodified sdp`,Object.assign(Object.assign({},this.logContext),{error:n,sdp:t})),e.sdp=r}}try{n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(t){let r=`unknown error`;t instanceof Error?r=t.message:typeof t==`string`&&(r=t);let i={error:r,sdp:e.sdp};throw!n&&this.pc.remoteDescription&&(i.remoteSdp=this.pc.remoteDescription),this.log.error(`unable to set ${e.type}`,Object.assign(Object.assign({},this.logContext),{fields:i})),new my(r)}})}ensureVideoDDExtensionForSVC(e,t){var n;if(!e.ext?.some(e=>e.uri===eb)){if(this.ddExtID===0){let e=0;t.media.forEach(t=>{var n;t.type===`video`&&((n=t.ext)==null||n.forEach(t=>{t.value>e&&(e=t.value)}))}),this.ddExtID=e+1}(n=e.ext)==null||n.push({value:this.ddExtID,uri:eb})}}};function hS(e,t,n){let r=vS(e.mid),i=0;e.rtp.some(e=>e.codec===`opus`?(i=e.payload,!0):!1),i>0&&(e.rtcpFb||=[],n.includes(r)&&!e.rtcpFb.some(e=>e.payload===i&&e.type===`nack`)&&e.rtcpFb.push({payload:i,type:`nack`}),(t.includes(r)||t.length===1&&t[0]===`all`)&&e.fmtp.some(e=>e.payload===i?(e.config.includes(`stereo=1`)||(e.config+=`;stereo=1`),!0):!1))}function gS(e){let t=[],n=[],r=lS.parse(e.sdp??``),i=0;return r.media.forEach(e=>{let r=vS(e.mid);e.type===`audio`&&(e.rtp.some(e=>e.codec===`opus`?(i=e.payload,!0):!1),e.rtcpFb?.some(e=>e.payload===i&&e.type===`nack`)&&n.push(r),e.fmtp.some(e=>e.payload===i?(e.config.includes(`sprop-stereo=1`)&&t.push(r),!0):!1))}),{stereoMids:t,nackMids:n}}function _S(e){if(e.connection){let t=e.connection.ip.indexOf(`:`)>=0;(e.connection.version===4&&t||e.connection.version===6&&!t)&&(e.connection.ip=`0.0.0.0`,e.connection.version=4)}}function vS(e){return typeof e==`number`?e.toFixed(0):e}var yS=`vp8`,bS={audioPreset:Oy.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:jy.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:yS,backupCodec:!0,preConnectBuffer:!1},xS={deviceId:{ideal:`default`},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},SS={deviceId:{ideal:`default`},resolution:ky.h720.resolution},CS={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new M_,disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!0},wS={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3},TS;(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`})(TS||={});var ES=class{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}get mode(){return this._mode}constructor(e,t,n){this.peerConnectionTimeout=wS.peerConnectionTimeout,this.log=I,this.updateState=()=>{var e;let t=this.state,n=this.requiredTransports.map(e=>e.getConnectionState());n.every(e=>e===`connected`)?this.state=TS.CONNECTED:n.some(e=>e===`failed`)?this.state=TS.FAILED:n.some(e=>e===`connecting`)?this.state=TS.CONNECTING:n.every(e=>e===`closed`)?this.state=TS.CLOSED:n.some(e=>e===`closed`)?this.state=TS.CLOSING:n.every(e=>e===`new`)&&(this.state=TS.NEW),t!==this.state&&(this.log.debug(`pc state change: from ${TS[t]} to ${TS[this.state]}`,this.logContext),(e=this.onStateChange)==null||e.call(this,this.state,this.publisher.getConnectionState(),this.subscriber?.getConnectionState()))},this.log=O_(t.loggerName??D_.PCManager),this.loggerOptions=t,this.isPublisherConnectionRequired=e!==`subscriber-primary`,this.isSubscriberConnectionRequired=e===`subscriber-primary`,this.publisher=new mS(n,t),this._mode=e,e!==`publisher-only`&&(this.subscriber=new mS(n,t),this.subscriber.onConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.subscriber.onIceCandidate=e=>{var t;(t=this.onIceCandidate)==null||t.call(this,e,dg.SUBSCRIBER)},this.subscriber.onDataChannel=e=>{var t;(t=this.onDataChannel)==null||t.call(this,e)},this.subscriber.onTrack=e=>{var t;(t=this.onTrack)==null||t.call(this,e)}),this.publisher.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=e=>{var t;(t=this.onIceCandidate)==null||t.call(this,e,dg.PUBLISHER)},this.publisher.onTrack=e=>{var t;(t=this.onTrack)==null||t.call(this,e)},this.publisher.onOffer=(e,t)=>{var n;(n=this.onPublisherOffer)==null||n.call(this,e,t)},this.state=TS.NEW,this.connectionLock=new dp,this.remoteOfferLock=new dp}get logContext(){var e;return Object.assign({},(e=this.loggerOptions).loggerContextCb?.call(e))}requirePublisher(){this.isPublisherConnectionRequired=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,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 L(this,void 0,void 0,function*(){if(this.publisher&&this.publisher.getSignallingState()!==`closed`){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 L(this,void 0,void 0,function*(){this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return L(this,void 0,void 0,function*(){t===dg.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber?.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,t){return L(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 n=yield this.remoteOfferLock.lock();try{return(yield this.subscriber?.setRemoteDescription(e,t))?yield this.subscriber?.createAndSetAnswer():void 0}finally{n()}})}updateConfiguration(e,t){var n;this.publisher.setConfiguration(e),(n=this.subscriber)==null||n.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return L(this,void 0,void 0,function*(){let n=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&this.publisher.getConnectionState()!==`connected`&&this.publisher.getConnectionState()!==`connecting`&&(this.log.debug(`negotiation required, start negotiating`,this.logContext),this.publisher.negotiate()),yield Promise.all(this.requiredTransports?.map(n=>this.ensureTransportConnected(n,e,t)))}finally{n()}})}negotiate(e){return L(this,void 0,void 0,function*(){return new ey((t,n)=>L(this,void 0,void 0,function*(){let r=setTimeout(()=>{n(new my(`negotiation timed out`))},this.peerConnectionTimeout),i=()=>{clearTimeout(r),this.publisher.off(pS.NegotiationStarted,o),e.signal.removeEventListener(`abort`,a)},a=()=>{i(),n(new my(`negotiation aborted`))},o=()=>{e.signal.aborted||(clearTimeout(r),r=setTimeout(()=>{i(),n(new my(`negotiation timed out`))},this.peerConnectionTimeout))};e.signal.addEventListener(`abort`,a),this.publisher.on(pS.NegotiationStarted,o),this.publisher.once(pS.NegotiationComplete,()=>{i(),t()}),yield this.publisher.negotiate(e=>{i(),e instanceof Error?n(e):n(Error(String(e)))})}))})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTransceiverOfKind(e,t){return this.publisher.addTransceiverOfKind(e,t)}getMidForReceiver(e){return(this.subscriber?this.subscriber.getTransceivers():this.publisher.getTransceivers()).find(t=>t.receiver===e)?.mid}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===dg.PUBLISHER||e===dg.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){let e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&this.subscriber&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return L(this,arguments,void 0,function(e,t){var n=this;let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return function*(){if(e.getConnectionState()!==`connected`)return new Promise((e,i)=>L(n,void 0,void 0,function*(){let n=()=>{this.log.warn(`abort transport connection`,this.logContext),xy.clearTimeout(a),i(z.cancelled(`room connection has been cancelled`))};t?.signal.aborted&&n(),t?.signal.addEventListener(`abort`,n);let a=xy.setTimeout(()=>{t?.signal.removeEventListener(`abort`,n),i(z.internal(`could not establish pc connection`))},r);for(;this.state!==TS.CONNECTED;)if(yield nb(50),t?.signal.aborted){i(z.cancelled(`room connection has been cancelled`));return}xy.clearTimeout(a),t?.signal.removeEventListener(`abort`,n),e()}))}()})}},DS=5e3,OS=3e4,kS=class e{static fetchRegionSettings(t,n,r){return L(this,void 0,void 0,function*(){let i=yield e.fetchLock.lock();try{let e=yield fetch(`${AS(t)}/regions`,{headers:{authorization:`Bearer ${n}`},signal:r});if(e.ok){let t=nx(e.headers),n=t?t*1e3:DS;return{regionSettings:yield e.json(),updatedAtInMs:Date.now(),maxAgeInMs:n}}else if(e.status===401)throw z.notAllowed(`Could not fetch region settings: ${e.statusText}`,e.status);else throw z.internal(`Could not fetch region settings: ${e.statusText}`)}catch(e){throw e instanceof z?e:r?.aborted?z.cancelled(`Region fetching was aborted`):z.serverUnreachable(`Could not fetch region settings, ${e instanceof Error?`${e.name}: ${e.message}`:e}`)}finally{i()}})}static scheduleRefetch(t,n,r){return L(this,void 0,void 0,function*(){let i=e.settingsTimeouts.get(t.hostname);clearTimeout(i),e.settingsTimeouts.set(t.hostname,setTimeout(()=>L(this,void 0,void 0,function*(){try{let r=yield e.fetchRegionSettings(t,n);e.updateCachedRegionSettings(t,n,r)}catch(i){if(i instanceof z&&i.reason===R.NotAllowed){I.debug(`token is not valid, cancelling auto region refresh`);return}I.debug(`auto refetching of region settings failed`,{error:i}),e.scheduleRefetch(t,n,r)}}),r))})}static updateCachedRegionSettings(t,n,r){e.cache.set(t.hostname,r),e.scheduleRefetch(t,n,r.maxAgeInMs)}static stopRefetch(t){let n=e.settingsTimeouts.get(t);n&&(clearTimeout(n),e.settingsTimeouts.delete(t))}static scheduleCleanup(t){let n=e.connectionTrackers.get(t);n&&(n.cleanupTimeout&&clearTimeout(n.cleanupTimeout),n.cleanupTimeout=setTimeout(()=>{let n=e.connectionTrackers.get(t);n&&n.connectionCount===0&&(I.debug(`stopping region refetch after disconnect delay`,{hostname:t}),e.stopRefetch(t)),n&&(n.cleanupTimeout=void 0)},OS))}static cancelCleanup(t){let n=e.connectionTrackers.get(t);n?.cleanupTimeout&&(clearTimeout(n.cleanupTimeout),n.cleanupTimeout=void 0)}notifyConnected(){let t=this.serverUrl.hostname,n=e.connectionTrackers.get(t);n||(n={connectionCount:0},e.connectionTrackers.set(t,n)),n.connectionCount++,e.cancelCleanup(t)}notifyDisconnected(){let t=this.serverUrl.hostname,n=e.connectionTrackers.get(t);n&&(n.connectionCount=Math.max(0,n.connectionCount-1),n.connectionCount===0&&e.scheduleCleanup(t))}constructor(e,t){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return bb(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(t){return L(this,void 0,void 0,function*(){return e.fetchRegionSettings(this.serverUrl,this.token,t)})}getNextBestRegionUrl(t){return L(this,void 0,void 0,function*(){if(!this.isCloud())throw Error(`region availability is only supported for LiveKit Cloud domains`);let n=e.cache.get(this.serverUrl.hostname);(!n||Date.now()-n.updatedAtInMs>n.maxAgeInMs)&&(n=yield this.fetchRegionSettings(t),e.updateCachedRegionSettings(this.serverUrl,this.token,n));let r=n.regionSettings.regions.filter(e=>!this.attemptedRegions.find(t=>t.url===e.url));if(r.length>0){let e=r[0];return this.attemptedRegions.push(e),I.debug(`next region: ${e.region}`),e.url}else return null})}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(t){e.updateCachedRegionSettings(this.serverUrl,this.token,t)}};kS.cache=new Map,kS.settingsTimeouts=new Map,kS.connectionTrackers=new Map,kS.fetchLock=new dp;function AS(e){return`${e.protocol.replace(`ws`,`http`)}//${e.host}/settings`}var jS=class e extends Error{constructor(t,n,r){super(n),this.code=t,this.message=PS(n,e.MAX_MESSAGE_BYTES),this.data=r?PS(r,e.MAX_DATA_BYTES):void 0}static fromProto(t){return new e(t.code,t.message,t.data)}toProto(){return new Jh({code:this.code,message:this.message,data:this.data})}static builtIn(t,n){return new e(e.ErrorCode[t],e.ErrorMessage[t],n)}};jS.MAX_MESSAGE_BYTES=256,jS.MAX_DATA_BYTES=15360,jS.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},jS.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`};var MS=15360;function NS(e){return new TextEncoder().encode(e).length}function PS(e,t){if(NS(e)<=t)return e;let n=0,r=e.length,i=new TextEncoder;for(;n<r;){let a=Math.floor((n+r+1)/2);i.encode(e.slice(0,a)).length<=t?n=a:r=a-1}return e.slice(0,n)}var FS=2e3;function IS(e,t){if(!t)return 0;let n,r;return`bytesReceived`in e?(n=e.bytesReceived,r=t.bytesReceived):`bytesSent`in e&&(n=e.bytesSent,r=t.bytesSent),n===void 0||r===void 0||e.timestamp===void 0||t.timestamp===void 0?0:(n-r)*8*1e3/(e.timestamp-t.timestamp)}var LS=typeof MediaRecorder<`u`,RS=LS?MediaRecorder:class{constructor(){throw Error(`MediaRecorder is not available in this environment`)}},zS=class extends RS{constructor(e,t){if(!LS)throw Error(`MediaRecorder is not available in this environment`);super(new MediaStream([e.mediaStreamTrack]),t);let n,r,i=()=>r===void 0,a=()=>{this.removeEventListener(`dataavailable`,n),this.removeEventListener(`stop`,a),this.removeEventListener(`error`,o),r?.close(),r=void 0},o=e=>{r?.error(e),this.removeEventListener(`dataavailable`,n),this.removeEventListener(`stop`,a),this.removeEventListener(`error`,o),r=void 0};this.byteStream=new ReadableStream({start:e=>{r=e,n=t=>L(this,void 0,void 0,function*(){let n;if(t.data.arrayBuffer){let e=yield t.data.arrayBuffer();n=new Uint8Array(e)}else if(t.data.byteArray)n=t.data.byteArray;else throw Error(`no data available!`);i()||e.enqueue(n)}),this.addEventListener(`dataavailable`,n)},cancel:()=>{a()}}),this.addEventListener(`stop`,a),this.addEventListener(`error`,o)}};function BS(){return LS}var VS=1e3,HS=1e4,US=class extends K{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(e,t,n){let r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,i=arguments.length>4?arguments[4]:void 0;super(e,t,i),this.manuallyStopped=!1,this.pendingDeviceChange=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch(()=>this.log.debug(`track mute bounce got cancelled by an unmute event`,this.logContext)),this.debouncedTrackMuteHandler=uS(()=>L(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>L(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(U.Ended,this)},this.reacquireTrack=!1,this.providedByUser=r,this.muteLock=new dp,this.pauseUpstreamLock=new dp,this.trackChangeLock=new dp,this.trackChangeLock.lock().then(t=>L(this,void 0,void 0,function*(){try{yield this.setMediaStreamTrack(e,!0)}finally{t()}})),this._constraints=e.getConstraints(),n&&(this._constraints=n)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==K.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(){return this.processor?.processedTrack??this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t,n){return L(this,void 0,void 0,function*(){if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(e=>{Qy(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());let r;if(this.processor&&e){if(this.log.debug(`restarting processor`,this.logContext),this.kind===`unknown`)throw TypeError(`cannot set processor on track of unknown kind`);this.processorElement&&(Zy(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),r=this.processor.processedTrack}this.sender&&this.sender.transport?.state!==`closed`&&(yield this.sender.replaceTrack(r??e)),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=n?!0:!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(t=>{Zy(r??e,t)}))})}waitForDimensions(){return L(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:VS;return function*(){if(e.kind===K.Kind.Audio)throw Error(`cannot get dimensions for audio tracks`);ry()?.os===`iOS`&&(yield nb(10));let n=Date.now();for(;Date.now()-n<t;){let t=e.dimensions;if(t)return t;yield nb(50)}throw new dy(`unable to get track dimensions after timeout`)}()})}setDeviceId(e){return L(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Rb(e)?!0:(this._constraints.deviceId=e,this.isMuted?(this.pendingDeviceChange=!0,!0):(yield this.restartTrack(),Rb(e)===this._mediaStreamTrack.getSettings().deviceId))})}getDeviceId(){return L(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){if(e.source===K.Source.ScreenShare)return;let{deviceId:n,groupId:r}=e._mediaStreamTrack.getSettings(),i=e.kind===K.Kind.Audio?`audioinput`:`videoinput`;return t?Ex.getInstance().normalizeDeviceId(i,n,r):n}()})}mute(){return L(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return L(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return L(this,void 0,void 0,function*(){let n=yield this.trackChangeLock.lock();try{if(!this.sender)throw new dy(`unable to replace an unpublished track`);let n,r;return typeof t==`boolean`?n=t:t!==void 0&&(n=t.userProvidedTrack,r=t.stopProcessor),this.providedByUser=n??!0,this.log.debug(`replace MediaStreamTrack`,this.logContext),yield this.setMediaStreamTrack(e),r&&this.processor&&(yield this.internalStopProcessor()),this}finally{n()}})}restart(e,t){return L(this,void 0,void 0,function*(){this.manuallyStopped=!1;let n=yield this.trackChangeLock.lock();try{e||=this._constraints;let{deviceId:n,facingMode:r}=e,i=N_(e,[`deviceId`,`facingMode`]);this.log.debug(`restarting track with constraints`,Object.assign(Object.assign({},this.logContext),{constraints:e}));let a={audio:!1,video:!1};this.kind===K.Kind.Video?a.video=n||r?{deviceId:n,facingMode:r}:!0:a.audio=n?Object.assign({deviceId:n},i):!0,this.attachedElements.forEach(e=>{Qy(this.mediaStreamTrack,e)}),this._mediaStreamTrack.removeEventListener(`ended`,this.handleEnded),this._mediaStreamTrack.stop();let o=(yield navigator.mediaDevices.getUserMedia(a)).getTracks()[0];return this.kind===K.Kind.Video&&(yield o.applyConstraints(i)),o.addEventListener(`ended`,this.handleEnded),this.log.debug(`re-acquired MediaStreamTrack`,this.logContext),yield this.setMediaStreamTrack(o,!1,t),this._constraints=e,this.pendingDeviceChange=!1,this.emit(U.Restarted,this),this.manuallyStopped&&(this.log.warn(`track was stopped during a restart, stopping restarted track`,this.logContext),this.stop()),this}finally{n()}})}setTrackMuted(e){this.log.debug(`setting ${this.kind} track ${e?`muted`:`unmuted`}`,this.logContext),!(this.isMuted===e&&this._mediaStreamTrack.enabled!==e)&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?U.Muted:U.Unmuted,this))}get needsReAcquisition(){return this._mediaStreamTrack.readyState!==`live`||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return L(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),gb()&&(this.log.debug(`visibility changed, is in Background: ${this.isInBackground}`,this.logContext),!this.isInBackground&&this.needsReAcquisition&&!this.isUserProvided&&!this.isMuted&&(this.log.debug(`track needs to be reacquired, restarting ${this.source}`,this.logContext),yield this.restart(),this.reacquireTrack=!1))})}stop(){var e;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener(`ended`,this.handleEnded),this._mediaStreamTrack.removeEventListener(`mute`,this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener(`unmute`,this.handleTrackUnmuteEvent),(e=this.processor)==null||e.destroy(),this.processor=void 0}pauseUpstream(){return L(this,void 0,void 0,function*(){let e=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!0)return;if(!this.sender){this.log.warn(`unable to pause upstream for an unpublished track`,this.logContext);return}this._isUpstreamPaused=!0,this.emit(U.UpstreamPaused,this);let e=ry();if(e?.name===`Safari`&&Tb(e.version,`12.0`)<0)throw new uy(`pauseUpstream is not supported on Safari < 12.`);this.sender.transport?.state!==`closed`&&(yield this.sender.replaceTrack(null))}finally{e()}})}resumeUpstream(){return L(this,void 0,void 0,function*(){let e=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!1)return;if(!this.sender){this.log.warn(`unable to resume upstream for an unpublished track`,this.logContext);return}this._isUpstreamPaused=!1,this.emit(U.UpstreamResumed,this),this.sender.transport?.state!==`closed`&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{e()}})}getRTCStatsReport(){return L(this,void 0,void 0,function*(){if(this.sender?.getStats)return yield this.sender.getStats()})}setProcessor(e){return L(this,arguments,void 0,function(e){var t=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){let r=yield t.trackChangeLock.lock();try{t.log.debug(`setting up processor`,t.logContext);let r=document.createElement(t.kind),i={kind:t.kind,track:t._mediaStreamTrack,element:r,audioContext:t.audioContext};if(yield e.init(i),t.log.debug(`processor initialized`,t.logContext),t.processor&&(yield t.internalStopProcessor()),t.kind===`unknown`)throw TypeError(`cannot set processor on track of unknown kind`);if(Zy(t._mediaStreamTrack,r),r.muted=!0,r.play().catch(e=>{e instanceof DOMException&&e.name===`AbortError`?(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&&n&&(Qy(t._mediaStreamTrack,e),Zy(t.processor.processedTrack,e));yield t.sender?.replaceTrack(t.processor.processedTrack)}t.emit(U.TrackProcessorUpdate,t.processor)}finally{r()}}()})}getProcessor(){return this.processor}stopProcessor(){return L(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){let n=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(t)}finally{n()}}()})}internalStopProcessor(){return L(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var n,r;e.processor&&(e.log.debug(`stopping processor`,e.logContext),(n=e.processor.processedTrack)==null||n.stop(),yield e.processor.destroy(),e.processor=void 0,t||((r=e.processorElement)==null||r.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(U.TrackProcessorUpdate))}()})}startPreConnectBuffer(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:100;if(!BS()){this.log.warn(`MediaRecorder is not available, cannot start preconnect buffer`,this.logContext);return}if(this.localTrackRecorder){this.log.warn(`preconnect buffer already started`);return}else{let e=`audio/webm;codecs=opus`;MediaRecorder.isTypeSupported(e)||(e=`video/mp4`),this.localTrackRecorder=new zS(this,{mimeType:e})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn(`preconnect buffer timed out, stopping recording automatically`,this.logContext),this.stopPreConnectBuffer()},HS)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&=(this.localTrackRecorder.stop(),void 0)}getPreConnectBuffer(){return this.localTrackRecorder?.byteStream}getPreConnectBufferMimeType(){return this.localTrackRecorder?.mimeType}},WS=class extends US{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0,i=arguments.length>4?arguments[4]:void 0;super(e,K.Kind.Audio,t,n,i),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>L(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let e;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=IS(e,this.prevStats)),this.prevStats=e}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug(`Krisp noise filter enabled`,this.logContext),this.emit(U.AudioTrackFeatureUpdate,this,bh.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug(`Krisp noise filter disabled`,this.logContext),this.emit(U.AudioTrackFeatureUpdate,this,bh.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=r,this.checkForSilence()}mute(){let e=Object.create(null,{mute:{get:()=>super.mute}});return L(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug(`Track already muted`,this.logContext),this):(this.source===K.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 L(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{return this.isMuted?(this.source===K.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState===`ended`||this.pendingDeviceChange)&&!this.isUserProvided&&(this.log.debug(`reacquiring mic track`,this.logContext),yield this.restart(void 0,!0)),yield e.unmute.call(this),this):(this.log.debug(`Track already unmuted`,this.logContext),this)}finally{t()}})}restartTrack(e){return L(this,void 0,void 0,function*(){let t;if(e){let n=Py({audio:e});typeof n.audio!=`boolean`&&(t=n.audio)}yield this.restart(t)})}restart(e,t){let n=Object.create(null,{restart:{get:()=>super.restart}});return L(this,void 0,void 0,function*(){let r=yield n.restart.call(this,e,t);return this.checkForSilence(),r})}startMonitor(){vb()&&(this.monitorInterval||=setInterval(()=>{this.monitorSender()},FS))}setProcessor(e){return L(this,void 0,void 0,function*(){let t=yield this.trackChangeLock.lock();try{if(!yb()&&!this.audioContext)throw Error(`Audio context needs to be set on LocalAudioTrack in order to enable processors`);this.processor&&(yield this.internalStopProcessor());let t={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug(`setting up audio processor ${e.name}`,this.logContext),yield e.init(t),this.processor=e,this.processor.processedTrack&&(yield this.sender?.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(U.TrackProcessorUpdate,this.processor)}finally{t()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return L(this,void 0,void 0,function*(){if(!this.sender?.getStats)return;let e=yield this.sender.getStats(),t;return e.forEach(e=>{e.type===`outbound-rtp`&&(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 L(this,void 0,void 0,function*(){let e=yield Fy(this);return e&&(this.isMuted||this.log.debug(`silence detected on local audio track`,this.logContext),this.emit(U.AudioSilenceDetected)),e})}};function GS(e,t,n){switch(e.kind){case`audio`:return new WS(e,t,!1,void 0,n);case`video`:return new lC(e,t,!1,n);default:throw new dy(`unsupported track type: ${e.kind}`)}}var KS=Object.values(ky),qS=Object.values(Ay),JS=Object.values(jy),YS=[ky.h180,ky.h360],XS=[Ay.h180,Ay.h360],ZS=e=>[{scaleResolutionDownBy:2,fps:e.encoding.maxFramerate}].map(t=>new W(Math.floor(e.width/t.scaleResolutionDownBy),Math.floor(e.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(e.encoding.maxBitrate/(t.scaleResolutionDownBy**2*((e.encoding.maxFramerate??30)/(t.fps??30))))),t.fps,e.encoding.priority)),QS=[`q`,`h`,`f`];function $S(e,t,n,r){let i=r?.videoEncoding;e&&(i=r?.screenShareEncoding);let a=r?.simulcast,o=r?.scalabilityMode,s=r?.videoCodec;if(!i&&!a&&!o||!t||!n)return[{}];i||(i=tC(e,t,n,s),I.debug(`using video encoding`,i));let c=i.maxFramerate,l=new W(t,n,i.maxBitrate,i.maxFramerate,i.priority);if(o&&sb(s)){let e=new oC(o),t=[];if(e.spatial>3)throw Error(`unsupported scalabilityMode: ${o}`);let n=ry();if(pb()||yb()||n?.name===`Chrome`&&Tb(n?.version,`113`)<0){let r=e.suffix==`h`?2:3,a=hb(n);for(let n=0;n<e.spatial;n+=1)t.push({rid:QS[2-n],maxBitrate:i.maxBitrate/r**+n,maxFramerate:l.encoding.maxFramerate,scaleResolutionDownBy:a?2**n:void 0});t[0].scalabilityMode=o}else t.push({maxBitrate:i.maxBitrate,maxFramerate:l.encoding.maxFramerate,scalabilityMode:o});return l.encoding.priority&&(t[0].priority=l.encoding.priority,t[0].networkPriority=l.encoding.priority),I.debug(`using svc encoding`,{encodings:t}),t}if(!a)return[i];let u=[];u=e?aC(r?.screenShareSimulcastLayers)??rC(e,l):aC(r?.videoSimulcastLayers)??rC(e,l);let d;if(u.length>0){let e=u[0];u.length>1&&([,d]=u);let r=Math.max(t,n);if(r>=960&&d)return iC(t,n,[e,d,l],c);if(r>=480)return iC(t,n,[e,l],c)}return iC(t,n,[l])}function eC(e,t,n){if(!n.backupCodec||n.backupCodec===!0||n.backupCodec.codec===n.videoCodec)return;t!==n.backupCodec.codec&&I.warn(`requested a different codec than specified as backup`,{serverRequested:t,backup:n.backupCodec.codec}),n.videoCodec=t,n.videoEncoding=n.backupCodec.encoding;let r=e.mediaStreamTrack.getSettings(),i=r.width??e.dimensions?.width,a=r.height??e.dimensions?.height;return e.source===K.Source.ScreenShare&&n.simulcast&&(n.simulcast=!1),$S(e.source===K.Source.ScreenShare,i,a,n)}function tC(e,t,n,r){let i=nC(e,t,n),{encoding:a}=i[0],o=Math.max(t,n);for(let e=0;e<i.length;e+=1){let t=i[e];if(a=t.encoding,t.width>=o)break}if(r)switch(r){case`av1`:case`h265`:a=Object.assign({},a),a.maxBitrate*=.7;break;case`vp9`:a=Object.assign({},a),a.maxBitrate*=.85;break}return a}function nC(e,t,n){if(e)return JS;let r=t>n?t/n:n/t;return Math.abs(r-16/9)<Math.abs(r-4/3)?KS:qS}function rC(e,t){if(e)return ZS(t);let{width:n,height:r}=t,i=n>r?n/r:r/n;return Math.abs(i-16/9)<Math.abs(i-4/3)?YS:XS}function iC(e,t,n,r){let i=[];if(n.forEach((n,a)=>{if(a>=QS.length)return;let o=Math.min(e,t),s={rid:QS[a],scaleResolutionDownBy:Math.max(1,o/Math.min(n.width,n.height)),maxBitrate:n.encoding.maxBitrate},c=r&&n.encoding.maxFramerate?Math.min(r,n.encoding.maxFramerate):n.encoding.maxFramerate;c&&(s.maxFramerate=c);let l=ub()||a===0;n.encoding.priority&&l&&(s.priority=n.encoding.priority,s.networkPriority=n.encoding.priority),i.push(s)}),yb()&&Cb()===`ios`){let e;i.forEach(t=>{e?t.maxFramerate&&t.maxFramerate>e&&(e=t.maxFramerate):e=t.maxFramerate});let t=!0;i.forEach(n=>{n.maxFramerate!=e&&(t&&(t=!1,I.info(`Simulcast on iOS React-Native requires all encodings to share the same framerate.`)),I.info(`Setting framerate of encoding "${n.rid??``}" to ${e}`),n.maxFramerate=e)})}return i}function aC(e){if(e)return e.sort((e,t)=>{let{encoding:n}=e,{encoding:r}=t;return n.maxBitrate>r.maxBitrate?1:n.maxBitrate<r.maxBitrate?-1:n.maxBitrate===r.maxBitrate&&n.maxFramerate&&r.maxFramerate?n.maxFramerate>r.maxFramerate?1:-1:0})}var oC=class{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(){return`L${this.spatial}T${this.temporal}${this.suffix??``}`}};function sC(e){return e.source===K.Source.ScreenShare||e.constraints.height&&Rb(e.constraints.height)>=1080?`maintain-resolution`:`balanced`}var cC=5e3,lC=class extends US{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0;super(e,K.Kind.Video,t,n,r),this.simulcastCodecs=new Map,this.degradationPreference=`balanced`,this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>L(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let e;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])),n=e.some(e=>e.qualityLimitationReason===`cpu`);if(n!==this.isCpuConstrained&&(this.isCpuConstrained=n,this.isCpuConstrained&&this.emit(U.CpuConstrained)),this.prevStats){let e=0;t.forEach((t,n)=>{let r=this.prevStats?.get(n);e+=IS(t,r)}),this._currentBitrate=e}this.prevStats=t}),this.senderLock=new dp}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){if(this.signalClient=e,!vb())return;let t=this.sender?.getParameters();t&&(this.encodings=t.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},FS))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){let e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return L(this,void 0,void 0,function*(){var t,n,r,i;yield e.pauseUpstream.call(this);try{for(var a=!0,o=R_(this.simulcastCodecs.values()),s;s=yield o.next(),t=s.done,!t;a=!0)i=s.value,a=!1,yield i.sender?.replaceTrack(null)}catch(e){n={error:e}}finally{try{!a&&!t&&(r=o.return)&&(yield r.call(o))}finally{if(n)throw n.error}}})}resumeUpstream(){let e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return L(this,void 0,void 0,function*(){var t,n,r,i;yield e.resumeUpstream.call(this);try{for(var a=!0,o=R_(this.simulcastCodecs.values()),s;s=yield o.next(),t=s.done,!t;a=!0){i=s.value,a=!1;let e=i;yield e.sender?.replaceTrack(e.mediaStreamTrack)}}catch(e){n={error:e}}finally{try{!a&&!t&&(r=o.return)&&(yield r.call(o))}finally{if(n)throw n.error}}})}mute(){let e=Object.create(null,{mute:{get:()=>super.mute}});return L(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug(`Track already muted`,this.logContext),this):(this.source===K.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 L(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{return this.isMuted?(this.source===K.Source.Camera&&!this.isUserProvided&&(this.log.debug(`reacquiring camera track`,this.logContext),yield this.restart(void 0,!0)),yield e.unmute.call(this),this):(this.log.debug(`Track already unmuted`,this.logContext),this)}finally{t()}})}setTrackMuted(e){super.setTrackMuted(e);for(let t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return L(this,void 0,void 0,function*(){if(!this.sender?.getStats)return[];let e=[],t=yield this.sender.getStats();return t.forEach(n=>{if(n.type===`outbound-rtp`){let r={type:`video`,streamId:n.id,frameHeight:n.frameHeight,frameWidth:n.frameWidth,framesPerSecond:n.framesPerSecond,framesSent:n.framesSent,firCount:n.firCount,pliCount:n.pliCount,nackCount:n.nackCount,packetsSent:n.packetsSent,bytesSent:n.bytesSent,qualityLimitationReason:n.qualityLimitationReason,qualityLimitationDurations:n.qualityLimitationDurations,qualityLimitationResolutionChanges:n.qualityLimitationResolutionChanges,rid:n.rid??n.id,retransmittedPacketsSent:n.retransmittedPacketsSent,targetBitrate:n.targetBitrate,timestamp:n.timestamp},i=t.get(n.remoteId);i&&(r.jitter=i.jitter,r.packetsLost=i.packetsLost,r.roundTripTime=i.roundTripTime),e.push(r)}}),e.sort((e,t)=>(t.frameWidth??0)-(e.frameWidth??0)),e})}setPublishingQuality(e){let t=[];for(let n=Xy.LOW;n<=Xy.HIGH;n+=1)t.push(new Yg({quality:n,enabled:n<=e}));this.log.debug(`setting publishing quality. max quality ${e}`,this.logContext),this.setPublishingLayers(sb(this.codec),t)}restartTrack(e){return L(this,void 0,void 0,function*(){var t,n,r,i;let a;if(e){let t=Py({video:e});typeof t.video!=`boolean`&&(a=t.video)}yield this.restart(a),this.isCpuConstrained=!1;try{for(var o=!0,s=R_(this.simulcastCodecs.values()),c;c=yield s.next(),t=c.done,!t;o=!0){i=c.value,o=!1;let e=i;e.sender&&e.sender.transport?.state!==`closed`&&(e.mediaStreamTrack=this.mediaStreamTrack.clone(),yield e.sender.replaceTrack(e.mediaStreamTrack))}}catch(e){n={error:e}}finally{try{!o&&!t&&(r=s.return)&&(yield r.call(s))}finally{if(n)throw n.error}}})}setProcessor(e){let t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return L(this,arguments,void 0,function(e){var n=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var i,a,o,s;if(yield t.setProcessor.call(n,e,r),n.processor?.processedTrack)try{for(var c=!0,l=R_(n.simulcastCodecs.values()),u;u=yield l.next(),i=u.done,!i;c=!0)s=u.value,c=!1,yield s.sender?.replaceTrack(n.processor.processedTrack)}catch(e){a={error:e}}finally{try{!c&&!i&&(o=l.return)&&(yield o.call(l))}finally{if(a)throw a.error}}}()})}setDegradationPreference(e){return L(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug(`setting degradationPreference to ${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(`${e} already added, skipping adding simulcast codec`,this.logContext);return}let n={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,n),n}setSimulcastTrackSender(e,t){let n=this.simulcastCodecs.get(e);n&&(n.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},cC))}setPublishingCodecs(e){return L(this,void 0,void 0,function*(){var t,n,r,i,a,o,s;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(sb(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;let c=[];try{for(t=!0,n=R_(e);r=yield n.next(),i=r.done,!i;t=!0){s=r.value,t=!1;let e=s;if(!this.codec||this.codec===e.codec)yield this.setPublishingLayers(sb(e.codec),e.qualities);else{let t=this.simulcastCodecs.get(e.codec);if(this.log.debug(`try setPublishingCodec for ${e.codec}`,Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:t})),!t||!t.sender){for(let t of e.qualities)if(t.enabled){c.push(e.codec);break}}else t.encodings&&(this.log.debug(`try setPublishingLayersForSender ${e.codec}`,this.logContext),yield uC(t.sender,t.encodings,e.qualities,this.senderLock,sb(e.codec),this.log,this.logContext))}}}catch(e){a={error:e}}finally{try{!t&&!i&&(o=n.return)&&(yield o.call(n))}finally{if(a)throw a.error}}return c})}setPublishingLayers(e,t){return L(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 uC(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext))})}prioritizePerformance(){return L(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)=>Object.assign(Object.assign({},e),{active:t===0,scaleResolutionDownBy:Math.max(1,Math.ceil((this.mediaStreamTrack.getSettings().height??360)/360)),scalabilityMode:t===0&&sb(this.codec)?`L1T3`:void 0,maxFramerate:t===0?15:0,maxBitrate:t===0?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 L(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),gb()&&this.isInBackground&&this.source===K.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}};function uC(e,t,n,r,i,a,o){return L(this,void 0,void 0,function*(){let s=yield r.lock();a.debug(`setPublishingLayersForSender`,Object.assign(Object.assign({},o),{sender:e,qualities:n,senderEncodings:t}));try{let r=e.getParameters(),{encodings:s}=r;if(!s)return;if(s.length!==t.length){a.warn(`cannot set publishing layers, encodings mismatch`,Object.assign(Object.assign({},o),{encodings:s,senderEncodings:t}));return}let c=!1;i&&n.some(e=>e.enabled)&&n.forEach(e=>e.enabled=!0),s.forEach((e,r)=>{let i=e.rid??``;i===``&&(i=`q`);let s=dC(i),l=n.find(e=>e.quality===s);l&&e.active!==l.enabled&&(c=!0,e.active=l.enabled,a.debug(`setting layer ${l.quality} to ${e.active?`enabled`:`disabled`}`,o),ub()&&(l.enabled?(e.scaleResolutionDownBy=t[r].scaleResolutionDownBy,e.maxBitrate=t[r].maxBitrate,e.maxFrameRate=t[r].maxFrameRate):(e.scaleResolutionDownBy=4,e.maxBitrate=10,e.maxFrameRate=2)))}),c&&(r.encodings=s,a.debug(`setting encodings`,Object.assign(Object.assign({},o),{encodings:r.encodings})),yield e.setParameters(r))}finally{s()}})}function dC(e){switch(e){case`f`:return Xy.HIGH;case`h`:return Xy.MEDIUM;case`q`:return Xy.LOW;default:return Xy.HIGH}}function fC(e,t,n,r){if(!n)return[new Mh({quality:Xy.HIGH,width:e,height:t,bitrate:0,ssrc:0})];if(r){let r=n[0].scalabilityMode,i=new oC(r),a=[],o=i.suffix==`h`?1.5:2,s=i.suffix==`h`?2:3;for(let r=0;r<i.spatial;r+=1)a.push(new Mh({quality:Math.min(Xy.HIGH,i.spatial-1)-r,width:Math.ceil(e/o**+r),height:Math.ceil(t/o**+r),bitrate:n[0].maxBitrate?Math.ceil(n[0].maxBitrate/s**+r):0,ssrc:0}));return a}return n.map(n=>{let r=n.scaleResolutionDownBy??1;return new Mh({quality:dC(n.rid??``),width:Math.ceil(e/r),height:Math.ceil(t/r),bitrate:n.maxBitrate??0,ssrc:0})})}var pC=`_lossy`,mC=`_reliable`,hC=`_data_track`,gC=2*1e3,_C=`leave-reconnect`,vC=3e4,yC=8*1024,bC=256*1024,xC=3,SC=3,CC;(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`})(CC||={});var J;(function(e){e[e.RELIABLE=0]=`RELIABLE`,e[e.LOSSY=1]=`LOSSY`,e[e.DATA_TRACK_LOSSY=2]=`DATA_TRACK_LOSSY`})(J||={});var wC=class extends H_.EventEmitter{get isClosed(){return this._isClosed}get isNewlyCreated(){return this._isNewlyCreated}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=wS.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=CC.New,this._isClosed=!0,this._isNewlyCreated=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.log=I,this.reliableDataSequence=1,this.reliableMessageBuffer=new Yx,this.reliableReceivedState=new Xx(vC),this.lossyDataStatCurrentBytes=0,this.lossyDataStatByterate=0,this.lossyDataDropCount=0,this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.handleDataChannel=e=>L(this,[e],void 0,function(e){var t=this;let{channel:n}=e;return function*(){if(!n)return;let e;if(n.label===mC)t.reliableDCSub=n,e=t.handleDataMessage;else if(n.label===pC)t.lossyDCSub=n,e=t.handleDataMessage;else if(n.label===hC)t.dataTrackDCSub=n,e=t.handleDataTrackMessage;else return;t.log.debug(`on data channel ${n.id}, ${n.label}`,t.logContext),n.onmessage=e}()}),this.handleDataMessage=e=>L(this,void 0,void 0,function*(){let t=yield this.dataProcessLock.lock();try{let t;if(e.data instanceof ArrayBuffer)t=e.data;else if(e.data instanceof Blob)t=yield e.data.arrayBuffer();else{this.log.error(`unsupported data type`,Object.assign(Object.assign({},this.logContext),{data:e.data}));return}let n=Ph.fromBinary(new Uint8Array(t));if(n.sequence>0&&n.participantSid!==``){let e=this.reliableReceivedState.get(n.participantSid);if(e&&n.sequence<=e)return;this.reliableReceivedState.set(n.participantSid,n.sequence)}if(n.value?.case===`speaker`)this.emit(H.ActiveSpeakersUpdate,n.value.value.speakers);else if(n.value?.case===`encryptedPacket`){if(!this.e2eeManager){this.log.error(`Received encrypted packet but E2EE not set up`,this.logContext);return}let e=yield this.e2eeManager?.handleEncryptedData(n.value.value.encryptedValue,n.value.value.iv,n.participantIdentity,n.value.value.keyIndex),t=new Ph({value:Lh.fromBinary(e.payload).value,participantIdentity:n.participantIdentity,participantSid:n.participantSid});t.value?.case===`user`&&TC(t,t.value.value),this.emit(H.DataPacketReceived,t,n.value.value.encryptionType)}else n.value?.case===`user`&&TC(n,n.value.value),this.emit(H.DataPacketReceived,n,F.NONE)}finally{t()}}),this.handleDataTrackMessage=e=>L(this,void 0,void 0,function*(){let t;if(e.data instanceof ArrayBuffer)t=e.data;else if(e.data instanceof Blob)t=yield e.data.arrayBuffer();else{this.log.error(`unsupported data type`,Object.assign(Object.assign({},this.logContext),{data:e.data}));return}this.emit(`dataTrackPacketReceived`,new Uint8Array(t))}),this.handleDataError=e=>{let t=e.currentTarget.maxRetransmits===0?`lossy`:`reliable`;if(e instanceof ErrorEvent&&e.error){let{error:n}=e.error;this.log.error(`DataChannel error on ${t}: ${e.message}`,Object.assign(Object.assign({},this.logContext),{error:n}))}else this.log.error(`Unknown DataChannel error on ${t}`,Object.assign(Object.assign({},this.logContext),{event:e}))},this.handleBufferedAmountLow=e=>{this.updateAndEmitDCBufferStatus(e)},this.handleDisconnect=(e,t)=>{if(this._isClosed)return;this.log.warn(`${e} disconnected`,this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());let n=e=>{this.log.warn(`could not recover connection after ${this.reconnectAttempts} attempts, ${e}ms. giving up`,this.logContext),this.emit(H.Disconnected),this.close()},r=Date.now()-this.reconnectStart,i=this.getNextRetryDelay({elapsedMs:r,retryCount:this.reconnectAttempts});if(i===null){n(r);return}e===_C&&(i=0),this.log.debug(`reconnecting in ${i}ms`,this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=xy.setTimeout(()=>this.attemptReconnect(t).finally(()=>this.reconnectTimeout=void 0),i)},this.waitForRestarted=()=>new Promise((e,t)=>{this.pcState===CC.Connected&&e();let n=()=>{this.off(H.Disconnected,r),e()},r=()=>{this.off(H.Restarted,n),t()};this.once(H.Restarted,n),this.once(H.Disconnected,r)}),this.updateAndEmitDCBufferStatus=e=>{if(e===J.RELIABLE){let t=this.dataChannelForKind(e);t&&this.reliableMessageBuffer.alignBufferedAmount(t.bufferedAmount)}let t=this.isBufferStatusLow(e);t!==void 0&&t!==this.dcBufferStatus.get(e)&&(this.dcBufferStatus.set(e,t),this.emit(H.DCBufferStatusChanged,t,e))},this.isBufferStatusLow=e=>{let t=this.dataChannelForKind(e);if(t)return t.bufferedAmount<=t.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>L(this,void 0,void 0,function*(){this.url&&(yield fetch(Bb(this.url),{method:`HEAD`}).then(e=>e.ok).catch(()=>!1))&&(this.log.info(`detected network reconnected`),(this.client.currentState===q.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===q.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(vh.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))}),this.handleBrowserOffline=()=>L(this,void 0,void 0,function*(){if(this.url)try{yield Promise.race([fetch(Bb(this.url),{method:`HEAD`}),nb(4e3).then(()=>Promise.reject())])}catch{window.navigator.onLine===!1&&(this.log.info(`detected network interruption`),this.isWaitingForNetworkReconnect=!0)}}),this.log=O_(e.loggerName??D_.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new Wx(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new dp,this.dataProcessLock=new dp,this.dcBufferStatus=new Map([[J.RELIABLE,!0],[J.LOSSY,!0],[J.DATA_TRACK_LOSSY,!0]]),this.client.onParticipantUpdate=e=>this.emit(H.ParticipantUpdate,e),this.client.onConnectionQuality=e=>this.emit(H.ConnectionQualityUpdate,e),this.client.onRoomUpdate=e=>this.emit(H.RoomUpdate,e),this.client.onSubscriptionError=e=>this.emit(H.SubscriptionError,e),this.client.onSubscriptionPermissionUpdate=e=>this.emit(H.SubscriptionPermissionUpdate,e),this.client.onSpeakersChanged=e=>this.emit(H.SpeakersChanged,e),this.client.onStreamStateUpdate=e=>this.emit(H.StreamStateChanged,e),this.client.onRequestResponse=e=>this.emit(H.SignalRequestResponse,e),this.client.onParticipantUpdate=e=>this.emit(H.ParticipantUpdate,e),this.client.onJoined=e=>this.emit(H.Joined,e)}get logContext(){return{room:this.latestJoinResponse?.room?.name,roomID:this.latestJoinResponse?.room?.sid,participant:this.latestJoinResponse?.participant?.identity,participantID:this.participantSid}}join(e,t,n,r){return L(this,arguments,void 0,function(e,t,n,r){var i=this;let a=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return function*(){var o;i._isNewlyCreated=!1,i.url=e,i.token=t,i.signalOpts=n,i.maxJoinAttempts=n.maxRetries;try{i.joinAttempts+=1,i.setupSignalClientCallbacks();let s;if(!a&&rx()){i.pcManager||(yield i.configure(),i.createDataChannels(),i.addMediaSections(xC,SC));let e=yield i.pcManager?.publisher.createInitialOffer();e&&(s=Kx(e.offer,e.offerId))}if(r?.aborted)throw z.cancelled(`Connection aborted`);let c=yield i.client.join(e,t,n,r,a,s);return i._isClosed=!1,i.latestJoinResponse=c,i.participantSid=c.participant?.sid,i.subscriberPrimary=c.subscriberPrimary,!a&&rx()?(o=i.pcManager)==null||o.updateConfiguration(i.makeRTCConfiguration(c)):(i.pcManager||(yield i.configure(c,!a)),(!i.subscriberPrimary||c.fastPublish)&&i.negotiate().catch(e=>{I.error(e,i.logContext)})),i.registerOnLineListener(),i.clientConfiguration=c.clientConfiguration,i.emit(H.SignalConnected,c),c}catch(o){if(o instanceof z){if(o.reason===R.ServerUnreachable){if(i.log.warn(`Couldn't connect to server, attempt ${i.joinAttempts} of ${i.maxJoinAttempts}`,i.logContext),i.joinAttempts<i.maxJoinAttempts)return i.join(e,t,n,r,a)}else if(o.reason===R.ServiceNotFound)return i.log.warn(`Initial connection failed: ${o.message} – Retrying`),i.join(e,t,n,r,!0)}throw o}}()})}close(){return L(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(H.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return L(this,void 0,void 0,function*(){yield this.pcManager?.close(),this.pcManager=void 0;let e=e=>{e&&(e.close(),e.onbufferedamountlow=null,e.onclose=null,e.onclosing=null,e.onerror=null,e.onmessage=null,e.onopen=null)};e(this.lossyDC),e(this.lossyDCSub),e(this.reliableDC),e(this.reliableDCSub),e(this.dataTrackDC),e(this.dataTrackDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.dataTrackDC=void 0,this.dataTrackDCSub=void 0,this.reliableMessageBuffer=new Yx,this.reliableDataSequence=1,this.reliableReceivedState.clear()})}cleanupLossyDataStats(){this.lossyDataStatByterate=0,this.lossyDataStatCurrentBytes=0,this.lossyDataStatInterval&&=(clearInterval(this.lossyDataStatInterval),void 0),this.lossyDataDropCount=0}cleanupClient(){return L(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new dy(`a track with the same ID has already been published`);return new Promise((t,n)=>{let r=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],n(z.timeout(`publication of local track timed out, no response from server`))},1e4);this.pendingTrackResolvers[e.cid]={resolve:e=>{clearTimeout(r),t(e)},reject:()=>{clearTimeout(r),n(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(){return this.reliableDCSub?.readyState}getConnectedServerAddress(){return L(this,void 0,void 0,function*(){return this.pcManager?.getConnectedAddress()})}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e,t){return L(this,void 0,void 0,function*(){if(!(this.pcManager&&this.pcManager.currentState!==TS.NEW)){if(e){this.participantSid=e.participant?.sid;let n=this.makeRTCConfiguration(e);this.pcManager=new ES(t?`publisher-only`:e.subscriberPrimary?`subscriber-primary`:`publisher-primary`,this.loggerOptions,n)}else{let e=this.makeRTCConfiguration();this.pcManager=new ES(`publisher-only`,this.loggerOptions,e)}this.emit(H.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=(e,t,n)=>L(this,void 0,void 0,function*(){if(this.log.debug(`primary PC state changed ${e}`,this.logContext),[`closed`,`disconnected`,`failed`].includes(t)&&(this.publisherConnectionPromise=void 0),e===TS.CONNECTED){let e=this.pcState===CC.New;this.pcState=CC.Connected,e&&this.emit(H.Connected,this.latestJoinResponse)}else e===TS.FAILED&&(this.pcState===CC.Connected||this.pcState===CC.Reconnecting)&&(this.pcState=CC.Disconnected,this.handleDisconnect(`peerconnection failed`,n===`failed`?vh.RR_SUBSCRIBER_FAILED:vh.RR_PUBLISHER_FAILED));let r=this.client.isDisconnected||this.client.currentState===q.RECONNECTING,i=[TS.FAILED,TS.CLOSING,TS.CLOSED].includes(e);r&&i&&!this._isClosed&&this.emit(H.Offline)}),this.pcManager.onTrack=e=>{e.streams.length!==0&&this.emit(H.MediaTrackAdded,e.track,e.streams[0],e.receiver)}}})}setupSignalClientCallbacks(){this.client.onAnswer=(e,t,n)=>L(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug(`received server answer`,Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,midToTrackId:n})),this.midToTrackId=n,yield this.pcManager.setPublisherAnswer(e,t))}),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.debug(`got ICE candidate from peer`,Object.assign(Object.assign({},this.logContext),{candidate:e,target:t})),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=(e,t,n)=>L(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;this.midToTrackId=n;let r=yield this.pcManager.createSubscriberAnswerFromOffer(e,t);r&&this.client.sendAnswer(r,t)}),this.client.onLocalTrackPublished=e=>{if(this.log.debug(`received trackPublishedResponse`,Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:e.track?.sid})),!this.pendingTrackResolvers[e.cid]){this.log.error(`missing track resolver for ${e.cid}`,Object.assign(Object.assign({},this.logContext),{cid:e.cid}));return}let{resolve:t}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],t(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(H.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(H.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{var t;this.token=e,(t=this.regionUrlProvider)==null||t.updateToken(e)},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(H.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(H.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{this.participantSid=e.participant?.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=e.room),this.emit(H.RoomMoved,e)},this.client.onMediaSectionsRequirement=e=>{this.addMediaSections(e.numAudios,e.numVideos),this.negotiate()},this.client.onPublishDataTrackResponse=e=>{this.emit(H.PublishDataTrackResponse,e)},this.client.onUnPublishDataTrackResponse=e=>{this.emit(H.UnPublishDataTrackResponse,e)},this.client.onDataTrackSubscriberHandles=e=>{this.emit(H.DataTrackSubscriberHandles,e)},this.client.onClose=()=>{this.handleDisconnect(`signal`,vh.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.debug(`client leave request`,Object.assign(Object.assign({},this.logContext),{reason:e?.reason})),e.regions&&this.regionUrlProvider&&(this.log.debug(`updating regions`,this.logContext),this.regionUrlProvider.setServerReportedRegions({updatedAtInMs:Date.now(),maxAgeInMs:DS,regionSettings:e.regions})),e.action){case zg.DISCONNECT:this.emit(H.Disconnected,e?.reason),this.close();break;case zg.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(_C);break;case zg.RESUME:this.handleDisconnect(_C)}}}makeRTCConfiguration(e){let t=Object.assign({},this.rtcConfig);if(this.signalOpts?.e2eeEnabled&&(this.log.debug(`E2EE - setting up transports with insertable streams`,this.logContext),t.encodedInsertableStreams=!0),t.sdpSemantics=`unified-plan`,t.continualGatheringPolicy=`gather_continually`,!e)return t;if(e.iceServers&&!t.iceServers){let n=[];e.iceServers.forEach(e=>{let t={urls:e.urls};e.username&&(t.username=e.username),e.credential&&(t.credential=e.credential),n.push(t)}),t.iceServers=n}return e.clientConfiguration&&e.clientConfiguration.forceRelay===gh.ENABLED&&(t.iceTransportPolicy=`relay`),t}addMediaSections(e,t){var n,r;let i={direction:`recvonly`};for(let t=0;t<e;t++)(n=this.pcManager)==null||n.addPublisherTransceiverOfKind(`audio`,i);for(let e=0;e<t;e++)(r=this.pcManager)==null||r.addPublisherTransceiverOfKind(`video`,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.dataTrackDC&&(this.dataTrackDC.onmessage=null,this.dataTrackDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(pC,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(mC,{ordered:!0}),this.dataTrackDC=this.pcManager.createPublisherDataChannel(hC,{ordered:!1,maxRetransmits:0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.dataTrackDC.onmessage=this.handleDataTrackMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.dataTrackDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.dataTrackDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=()=>this.handleBufferedAmountLow(J.LOSSY),this.reliableDC.onbufferedamountlow=()=>this.handleBufferedAmountLow(J.RELIABLE),this.dataTrackDC.onbufferedamountlow=()=>this.handleBufferedAmountLow(J.DATA_TRACK_LOSSY),this.cleanupLossyDataStats(),this.lossyDataStatInterval=setInterval(()=>{this.lossyDataStatByterate=this.lossyDataStatCurrentBytes,this.lossyDataStatCurrentBytes=0;let e=this.dataChannelForKind(J.LOSSY);if(e){let t=this.lossyDataStatByterate/10;e.bufferedAmountLowThreshold=Math.min(Math.max(t,yC),bC)}},1e3))}createSender(e,t,n){return L(this,void 0,void 0,function*(){if(rb())return yield this.createTransceiverRTCRtpSender(e,t,n);if(ib())return this.log.warn(`using add-track fallback`,this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new py(`Required webRTC APIs not supported on this device`)})}createSimulcastSender(e,t,n,r){return L(this,void 0,void 0,function*(){if(rb())return this.createSimulcastTransceiverSender(e,t,n,r);if(ib())return this.log.debug(`using add-track fallback`,this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new py(`Cannot stream on this device`)})}createTransceiverRTCRtpSender(e,t,n){return L(this,void 0,void 0,function*(){if(!this.pcManager)throw new py(`publisher is closed`);let r=[];e.mediaStream&&r.push(e.mediaStream),Jb(e)&&(e.codec=t.videoCodec);let i={direction:`sendonly`,streams:r};return n&&(i.sendEncodings=n),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,i)).sender})}createSimulcastTransceiverSender(e,t,n,r){return L(this,void 0,void 0,function*(){if(!this.pcManager)throw new py(`publisher is closed`);let i={direction:`sendonly`};r&&(i.sendEncodings=r);let a=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,i);if(n.videoCodec)return e.setSimulcastTrackSender(n.videoCodec,a.sender),a.sender})}createRTCRtpSender(e){return L(this,void 0,void 0,function*(){if(!this.pcManager)throw new py(`publisher is closed`);return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return L(this,void 0,void 0,function*(){if(!this._isClosed){if(this.attemptingReconnect){I.warn(`already attempting reconnect, returning early`,this.logContext);return}(this.clientConfiguration?.resumeConnection===gh.DISABLED||(this.pcManager?.currentState??TS.NEW)===TS.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(e){this.reconnectAttempts+=1;let t=!0;e instanceof py?(this.log.debug(`received unrecoverable error`,Object.assign(Object.assign({},this.logContext),{error:e})),t=!1):e instanceof yy||(this.fullReconnectOnNext=!0),t?this.handleDisconnect(`reconnect`,vh.RR_UNKNOWN):(this.log.info(`could not recover connection after ${this.reconnectAttempts} attempts, ${Date.now()-this.reconnectStart}ms. giving up`,this.logContext),this.emit(H.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 L(this,void 0,void 0,function*(){var t,n;try{if(!this.url||!this.token)throw new py(`could not reconnect, url or token not saved`);this.log.info(`reconnecting, attempt: ${this.reconnectAttempts}`,this.logContext),this.emit(H.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let n;try{if(!this.signalOpts)throw this.log.warn(`attempted connection restart, without signal options present`,this.logContext),new yy;n=yield this.join(e??this.url,this.token,this.signalOpts,void 0,!this.options.singlePeerConnection)}catch(e){throw e instanceof z&&e.reason===R.NotAllowed?new py(`could not reconnect, token might be expired`):new yy}if(this.shouldFailNext)throw this.shouldFailNext=!1,Error(`simulated failure`);if(this.client.setReconnected(),this.emit(H.SignalRestarted,n),yield this.waitForPCReconnected(),this.client.currentState!==q.CONNECTED)throw new yy(`Signal connection got severed during reconnect`);(t=this.regionUrlProvider)==null||t.resetAttempts(),this.emit(H.Restarted)}catch(e){let t=yield this.regionUrlProvider?.getNextBestRegionUrl();if(t){yield this.restartConnection(t);return}else throw(n=this.regionUrlProvider)==null||n.resetAttempts(),e}})}resumeConnection(e){return L(this,void 0,void 0,function*(){if(!this.url||!this.token)throw new py(`could not reconnect, url or token not saved`);if(!this.pcManager)throw new py(`publisher and subscriber connections unset`);this.log.info(`resuming signal connection, attempt ${this.reconnectAttempts}`,this.logContext),this.emit(H.Resuming);let t;try{this.setupSignalClientCallbacks(),t=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(e){let t=``;throw e instanceof Error&&(t=e.message,this.log.error(e.message,Object.assign(Object.assign({},this.logContext),{error:e}))),e instanceof z&&e.reason===R.NotAllowed?new py(`could not reconnect, token might be expired`):e instanceof z&&e.reason===R.LeaveRequest?e:new yy(t)}if(this.emit(H.SignalResumed),t){let e=this.makeRTCConfiguration(t);this.pcManager.updateConfiguration(e),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=t.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!==q.CONNECTED)throw new yy(`Signal connection got severed during reconnect`);this.client.setReconnected(),this.reliableDC?.readyState===`open`&&this.reliableDC.id===null&&this.createDataChannels(),t?.lastMessageSeq&&this.resendReliableMessagesForResume(t.lastMessageSeq),this.emit(H.Resumed)})}waitForPCInitialConnection(e,t){return L(this,void 0,void 0,function*(){if(!this.pcManager)throw new py(`PC manager is closed`);yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return L(this,void 0,void 0,function*(){this.pcState=CC.Reconnecting,this.log.debug(`waiting for peer connection to reconnect`,this.logContext);try{if(yield nb(gC),!this.pcManager)throw new py(`PC manager is closed`);yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=CC.Connected}catch(e){throw this.pcState=CC.Disconnected,z.internal(`could not establish PC connection, ${e.message}`)}})}publishRpcResponse(e,t,n,r){return L(this,void 0,void 0,function*(){let i=new Ph({destinationIdentities:[e],kind:Fh.RELIABLE,value:{case:`rpcResponse`,value:new qh({requestId:t,value:r?{case:`error`,value:r.toProto()}:{case:`payload`,value:n??``}})}});yield this.sendDataPacket(i,J.RELIABLE)})}publishRpcAck(e,t){return L(this,void 0,void 0,function*(){let n=new Ph({destinationIdentities:[e],kind:Fh.RELIABLE,value:{case:`rpcAck`,value:new Kh({requestId:t})}});yield this.sendDataPacket(n,J.RELIABLE)})}sendDataPacket(e,t){return L(this,void 0,void 0,function*(){if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){let t=yx(e);if(t){let n=yield this.e2eeManager.encryptData(t.toBinary());e.value={case:`encryptedPacket`,value:new Ih({encryptedValue:n.payload,iv:n.iv,keyIndex:n.keyIndex})}}}t===J.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);let n=e.toBinary();switch(t){case J.LOSSY:case J.DATA_TRACK_LOSSY:return this.sendLossyBytes(n,t);case J.RELIABLE:let r=this.dataChannelForKind(t);if(r){if(yield this.waitForBufferStatusLow(t),this.reliableMessageBuffer.push({data:n,sequence:e.sequence}),this.attemptingReconnect)return;r.send(n)}this.updateAndEmitDCBufferStatus(t);break}})}sendLossyBytes(e,t){return L(this,arguments,void 0,function(e,t){var n=this;let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:`drop`;return function*(){yield n.ensurePublisherConnected(t);let i=n.dataChannelForKind(t);if(i){if(!n.isBufferStatusLow(t))switch(r){case`wait`:yield n.waitForBufferStatusLow(t);break;case`drop`:n.lossyDataDropCount+=1,n.lossyDataDropCount%100==0&&n.log.warn(`dropping lossy data channel messages, total dropped: ${n.lossyDataDropCount}`,n.logContext);return}if(n.lossyDataStatCurrentBytes+=e.byteLength,n.attemptingReconnect)return;i.send(e)}n.updateAndEmitDCBufferStatus(t)}()})}resendReliableMessagesForResume(e){return L(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(J.RELIABLE);let t=this.dataChannelForKind(J.RELIABLE);t&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach(e=>{t.send(e.data)})),this.updateAndEmitDCBufferStatus(J.RELIABLE)})}waitForBufferStatusLow(e){return new ey((t,n)=>L(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))t();else{let r=()=>n(new py(`engine closed`));for(this.once(H.Closing,r);!this.dcBufferStatus.get(e);)yield nb(10);this.off(H.Closing,r),t()}}))}ensureDataTransportConnected(e){return L(this,arguments,void 0,function(e){var t=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return function*(){if(!t.pcManager)throw new py(`PC manager is closed`);let r=n?t.pcManager.subscriber:t.pcManager.publisher,i=n?`Subscriber`:`Publisher`;if(!r)throw z.internal(`${i} connection not set`);let a=!1;if(!n&&!t.dataChannelForKind(e,n)&&(t.createDataChannels(),a=!0),!a&&!n&&!t.pcManager.publisher.isICEConnected&&t.pcManager.publisher.getICEConnectionState()!==`checking`&&(a=!0),a&&t.negotiate().catch(e=>{I.error(e,t.logContext)}),t.dataChannelForKind(e,n)?.readyState===`open`)return;let o=new Date().getTime()+t.peerConnectionTimeout;for(;new Date().getTime()<o;){if(r.isICEConnected&&t.dataChannelForKind(e,n)?.readyState===`open`)return;yield nb(50)}throw z.internal(`could not establish ${i} connection, state: ${r.getICEConnectionState()}`)}()})}ensurePublisherConnected(e){return L(this,void 0,void 0,function*(){this.publisherConnectionPromise||=this.ensureDataTransportConnected(e,!1),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||![TS.CONNECTING,TS.CONNECTED].includes(this.pcManager.currentState)||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return L(this,void 0,void 0,function*(){return new ey((e,t)=>L(this,void 0,void 0,function*(){if(!this.pcManager){t(new my(`PC manager is closed`));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&!this.dataTrackDC&&this.createDataChannels();let n=new AbortController,r=()=>{n.abort(),this.log.debug(`engine disconnected while negotiation was ongoing`,this.logContext),e()};this.isClosed&&t(new my(`cannot negotiate on closed engine`)),this.on(H.Closing,r),this.on(H.Restarting,r),this.pcManager.publisher.once(pS.RTPVideoPayloadTypes,e=>{let t=new Map;e.forEach(e=>{let n=e.codec.toLowerCase();Lb(n)&&t.set(e.payload,n)}),this.emit(H.RTPVideoMapUpdate,t)});try{yield this.pcManager.negotiate(n),e()}catch(r){if(n.signal.aborted){e();return}r instanceof my&&(this.fullReconnectOnNext=!0),this.handleDisconnect(`negotiation`,vh.RR_UNKNOWN),r instanceof Error?t(r):t(Error(String(r)))}finally{this.off(H.Closing,r),this.off(H.Restarting,r)}}))})}dataChannelForKind(e,t){switch(e){case J.RELIABLE:return t?this.reliableDCSub:this.reliableDC;case J.LOSSY:return t?this.lossyDCSub:this.lossyDC;case J.DATA_TRACK_LOSSY:return t?this.dataTrackDCSub:this.dataTrackDC}}sendSyncState(e,t,n){if(!this.pcManager){this.log.warn(`sync state cannot be sent without peer connection setup`,this.logContext);return}let r=this.pcManager.publisher.getLocalDescription(),i=this.pcManager.publisher.getRemoteDescription(),a=this.pcManager.subscriber?.getRemoteDescription(),o=this.pcManager.subscriber?.getLocalDescription(),s=this.signalOpts?.autoSubscribe??!0,c=[],l=[];e.forEach(e=>{e.isDesired!==s&&c.push(e.trackSid),e.isEnabled||l.push(e.trackSid)}),this.client.sendSyncState(new r_({answer:this.pcManager.mode===`publisher-only`?i?Kx({sdp:i.sdp,type:i.type}):void 0:o?Kx({sdp:o.sdp,type:o.type}):void 0,offer:this.pcManager.mode===`publisher-only`?r?Kx({sdp:r.sdp,type:r.type}):void 0:a?Kx({sdp:a.sdp,type:a.type}):void 0,subscription:new Mg({trackSids:c,subscribe:!s,participantTracks:[]}),publishTracks:Vy(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:l,datachannelReceiveStates:this.reliableReceivedState.map((e,t)=>new i_({publisherSid:t,lastSeq:e})),publishDataTracks:n.map(e=>new yg({info:Lx.toProtobuf(e)}))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){let e=[],t=(t,n)=>{t?.id!==void 0&&t.id!==null&&e.push(new a_({label:t.label,id:t.id,target:n}))};return t(this.dataChannelForKind(J.LOSSY),dg.PUBLISHER),t(this.dataChannelForKind(J.RELIABLE),dg.PUBLISHER),t(this.dataChannelForKind(J.LOSSY,!0),dg.SUBSCRIBER),t(this.dataChannelForKind(J.RELIABLE,!0),dg.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&xy.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){vb()&&(window.addEventListener(`online`,this.handleBrowserOnLine),window.addEventListener(`offline`,this.handleBrowserOffline))}deregisterOnLineListener(){vb()&&(window.removeEventListener(`online`,this.handleBrowserOnLine),window.removeEventListener(`offline`,this.handleBrowserOffline))}getTrackIdForReceiver(e){let t=this.pcManager?.getMidForReceiver(e);if(t){let e=Object.entries(this.midToTrackId).find(e=>{let[n]=e;return n===t});if(e)return e[1]}}};function TC(e,t){let n=e.participantIdentity?e.participantIdentity:t.participantIdentity;e.participantIdentity=n,t.participantIdentity=n;let r=e.destinationIdentities.length===0?t.destinationIdentities:e.destinationIdentities;e.destinationIdentities=r,t.destinationIdentities=r}var EC=class{get info(){return this._info}validateBytesReceived(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;if(!(typeof this.totalByteSize!=`number`||this.totalByteSize===0)){if(e&&this.bytesReceived<this.totalByteSize)throw new vy(`Not enough chunk(s) received - expected ${this.totalByteSize} bytes of data total, only received ${this.bytesReceived} bytes`,_y.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new vy(`Extra chunk(s) received - expected ${this.totalByteSize} bytes of data total, received ${this.bytesReceived} bytes`,_y.LengthExceeded)}}constructor(e,t,n){this.reader=t,this.totalByteSize=n,this._info=e,this.bytesReceived=0}},DC=class extends EC{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();let n=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)==null||t.call(this,n)}[Symbol.asyncIterator](){let e=this.reader.getReader();e.closed.catch(()=>{});let t=()=>{e.releaseLock(),this.signal=void 0};return{next:()=>L(this,void 0,void 0,function*(){try{let t=this.signal;if(t?.aborted)throw t.reason;let n=yield new Promise((n,r)=>{if(t){let i=()=>r(t.reason);t.addEventListener(`abort`,i,{once:!0}),e.read().then(n,r).finally(()=>{t.removeEventListener(`abort`,i)})}else e.read().then(n,r)});return n.done?(this.validateBytesReceived(!0),{done:!0,value:void 0}):(this.handleChunkReceived(n.value),{done:!1,value:n.value.content})}catch(e){throw t(),e}}),return(){return L(this,void 0,void 0,function*(){return t(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return L(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return function*(){var n,r,i,a;let o=new Set,s=t.signal?e.withAbortSignal(t.signal):e;try{for(var c=!0,l=R_(s),u;u=yield l.next(),n=u.done,!n;c=!0){a=u.value,c=!1;let e=a;o.add(e)}}catch(e){r={error:e}}finally{try{!c&&!n&&(i=l.return)&&(yield i.call(l))}finally{if(r)throw r.error}}return Array.from(o)}()})}},OC=class extends EC{constructor(e,t,n){super(e,t,n),this.receivedChunks=new Map}handleChunkReceived(e){var t;let n=Wb(e.chunkIndex),r=this.receivedChunks.get(n);if(r&&r.version>e.version)return;this.receivedChunks.set(n,e),this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();let i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)==null||t.call(this,i)}[Symbol.asyncIterator](){let e=this.reader.getReader();e.closed.catch(()=>{});let t=new TextDecoder(`utf-8`,{fatal:!0}),n=this.signal,r=()=>{e.releaseLock(),this.signal=void 0};return{next:()=>L(this,void 0,void 0,function*(){try{if(n?.aborted)throw n.reason;let r=yield new Promise((t,r)=>{if(n){let i=()=>r(n.reason);n.addEventListener(`abort`,i,{once:!0}),e.read().then(t,r).finally(()=>{n.removeEventListener(`abort`,i)})}else e.read().then(t,r)});if(r.done)return this.validateBytesReceived(!0),{done:!0,value:void 0};{this.handleChunkReceived(r.value);let e;try{e=t.decode(r.value.content)}catch(e){throw new vy(`Cannot decode datastream chunk ${r.value.chunkIndex} as text: ${e}`,_y.DecodeFailed)}return{done:!1,value:e}}}catch(e){throw r(),e}}),return(){return L(this,void 0,void 0,function*(){return r(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return L(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return function*(){var n,r,i,a;let o=``,s=t.signal?e.withAbortSignal(t.signal):e;try{for(var c=!0,l=R_(s),u;u=yield l.next(),n=u.done,!n;c=!0)a=u.value,c=!1,o+=a}catch(e){r={error:e}}finally{try{!c&&!n&&(i=l.return)&&(yield i.call(l))}finally{if(r)throw r.error}}return o}()})}},kC=class{constructor(){this.log=I,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new vy(`A text stream handler for topic "${e}" has already been set.`,_y.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new vy(`A byte stream handler for topic "${e}" has already been set.`,_y.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear()}validateParticipantHasNoActiveDataStreams(e){let t=Array.from(this.textStreamControllers.entries()).filter(t=>t[1].sendingParticipantIdentity===e),n=Array.from(this.byteStreamControllers.entries()).filter(t=>t[1].sendingParticipantIdentity===e);if(t.length>0||n.length>0){let r=new vy(`Participant ${e} unexpectedly disconnected in the middle of sending data`,_y.AbnormalEnd);for(let[e,t]of n)t.controller.error(r),this.byteStreamControllers.delete(e);for(let[e,n]of t)n.controller.error(r),this.textStreamControllers.delete(e)}}handleDataStreamPacket(e,t){return L(this,void 0,void 0,function*(){switch(e.value.case){case`streamHeader`:return this.handleStreamHeader(e.value.value,e.participantIdentity,t);case`streamChunk`:return this.handleStreamChunk(e.value.value,t);case`streamTrailer`:return this.handleStreamTrailer(e.value.value,t);default:throw Error(`DataPacket of value "${e.value.case}" is not data stream related!`)}})}handleStreamHeader(e,t,n){return L(this,void 0,void 0,function*(){if(e.contentHeader.case===`byteHeader`){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 i,a={id:e.streamId,name:e.contentHeader.value.name??`unknown`,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Wb(e.timestamp),attributes:e.attributes,encryptionType:n};r(new DC(a,new ReadableStream({start:n=>{if(i=n,this.textStreamControllers.has(e.streamId))throw new vy(`A data stream read is already in progress for a stream with id ${e.streamId}.`,_y.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:a,controller:i,startTime:Date.now(),sendingParticipantIdentity:t})}}),Wb(e.totalLength)),{identity:t})}else if(e.contentHeader.case===`textHeader`){let r=this.textStreamHandlers.get(e.topic);if(!r){this.log.debug(`ignoring incoming text stream due to no handler for topic`,e.topic);return}let i,a={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes,encryptionType:n,attachedStreamIds:e.contentHeader.value.attachedStreamIds};r(new OC(a,new ReadableStream({start:n=>{if(i=n,this.textStreamControllers.has(e.streamId))throw new vy(`A data stream read is already in progress for a stream with id ${e.streamId}.`,_y.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:a,controller:i,startTime:Date.now(),sendingParticipantIdentity:t})}}),Wb(e.totalLength)),{identity:t})}})}handleStreamChunk(e,t){let n=this.byteStreamControllers.get(e.streamId);n&&(n.info.encryptionType===t?e.content.length>0&&n.controller.enqueue(e):(n.controller.error(new vy(`Encryption type mismatch for stream ${e.streamId}. Expected ${t}, got ${n.info.encryptionType}`,_y.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId)));let r=this.textStreamControllers.get(e.streamId);r&&(r.info.encryptionType===t?e.content.length>0&&r.controller.enqueue(e):(r.controller.error(new vy(`Encryption type mismatch for stream ${e.streamId}. Expected ${t}, got ${r.info.encryptionType}`,_y.EncryptionTypeMismatch)),this.textStreamControllers.delete(e.streamId)))}handleStreamTrailer(e,t){let n=this.textStreamControllers.get(e.streamId);n&&(n.info.encryptionType===t?(n.info.attributes=Object.assign(Object.assign({},n.info.attributes),e.attributes),n.controller.close(),this.textStreamControllers.delete(e.streamId)):n.controller.error(new vy(`Encryption type mismatch for stream ${e.streamId}. Expected ${t}, got ${n.info.encryptionType}`,_y.EncryptionTypeMismatch)));let r=this.byteStreamControllers.get(e.streamId);r&&(r.info.encryptionType===t?(r.info.attributes=Object.assign(Object.assign({},r.info.attributes),e.attributes),r.controller.close()):r.controller.error(new vy(`Encryption type mismatch for stream ${e.streamId}. Expected ${t}, got ${r.info.encryptionType}`,_y.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId))}},AC=class{constructor(e,t,n){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=n,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return L(this,void 0,void 0,function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),(e=this.onClose)==null||e.call(this)})}},jC=class extends AC{},MC=class extends AC{},NC=15e3,PC=class{constructor(e,t){this.engine=e,this.log=t}setupEngine(e){this.engine=e}sendText(e,t){return L(this,void 0,void 0,function*(){let n=crypto.randomUUID(),r=new TextEncoder().encode(e).byteLength,i=(t?.attachments)?.map(()=>crypto.randomUUID()),a=Array(i?i.length+1:1).fill(0),o=(e,n)=>{var r;a[n]=e;let i=a.reduce((e,t)=>e+t,0);(r=t?.onProgress)==null||r.call(t,i)},s=yield this.streamText({streamId:n,totalSize:r,destinationIdentities:t?.destinationIdentities,topic:t?.topic,attachedStreamIds:i,attributes:t?.attributes});return yield s.write(e),o(1,0),yield s.close(),t?.attachments&&i&&(yield Promise.all(t.attachments.map((e,n)=>L(this,void 0,void 0,function*(){return this._sendFile(i[n],e,{topic:t.topic,mimeType:e.type,onProgress:e=>{o(e,n+1)}})})))),s.info})}streamText(e){return L(this,void 0,void 0,function*(){let t=e?.streamId??crypto.randomUUID(),n={id:t,mimeType:`text/plain`,timestamp:Date.now(),topic:e?.topic??``,size:e?.totalSize,attributes:e?.attributes,encryptionType:this.engine.e2eeManager?.isDataChannelEncryptionEnabled?F.GCM:F.NONE,attachedStreamIds:e?.attachedStreamIds},r=new sg({streamId:t,mimeType:n.mimeType,topic:n.topic,timestamp:Gb(n.timestamp),totalLength:Gb(n.size),attributes:n.attributes,contentHeader:{case:`textHeader`,value:new ag({version:e?.version,attachedStreamIds:n.attachedStreamIds,replyToStreamId:e?.replyToStreamId,operationType:e?.type===`update`?ig.UPDATE:ig.CREATE})}}),i=e?.destinationIdentities,a=new Ph({destinationIdentities:i,value:{case:`streamHeader`,value:r}});yield this.engine.sendDataPacket(a,J.RELIABLE);let o=0,s=this.engine,c=new WritableStream({write(e){return L(this,void 0,void 0,function*(){for(let n of tx(e,NC)){let e=new Ph({destinationIdentities:i,value:{case:`streamChunk`,value:new cg({content:n,streamId:t,chunkIndex:Gb(o)})}});yield s.sendDataPacket(e,J.RELIABLE),o+=1}})},close(){return L(this,void 0,void 0,function*(){let e=new Ph({destinationIdentities:i,value:{case:`streamTrailer`,value:new lg({streamId:t})}});yield s.sendDataPacket(e,J.RELIABLE)})},abort(e){console.log(`Sink error:`,e)}}),l=()=>L(this,void 0,void 0,function*(){yield u.close()});s.once(H.Closing,l);let u=new jC(c,n,()=>this.engine.off(H.Closing,l));return u})}sendFile(e,t){return L(this,void 0,void 0,function*(){let n=crypto.randomUUID();return yield this._sendFile(n,e,t),{id:n}})}_sendFile(e,t,n){return L(this,void 0,void 0,function*(){let r=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:n?.mimeType??t.type,topic:n?.topic,destinationIdentities:n?.destinationIdentities}),i=t.stream().getReader();for(;;){let{done:e,value:t}=yield i.read();if(e)break;yield r.write(t)}return yield r.close(),r.info})}streamBytes(e){return L(this,void 0,void 0,function*(){let t=e?.streamId??crypto.randomUUID(),n=e?.destinationIdentities,r={id:t,mimeType:e?.mimeType??`application/octet-stream`,topic:e?.topic??``,timestamp:Date.now(),attributes:e?.attributes,size:e?.totalSize,name:e?.name??`unknown`,encryptionType:this.engine.e2eeManager?.isDataChannelEncryptionEnabled?F.GCM:F.NONE},i=new Ph({destinationIdentities:n,value:{case:`streamHeader`,value:new sg({totalLength:Gb(r.size),mimeType:r.mimeType,streamId:t,topic:r.topic,timestamp:Gb(Date.now()),attributes:r.attributes,contentHeader:{case:`byteHeader`,value:new og({name:r.name})}})}});yield this.engine.sendDataPacket(i,J.RELIABLE);let a=0,o=new dp,s=this.engine,c=this.log;return new MC(new WritableStream({write(e){return L(this,void 0,void 0,function*(){let r=yield o.lock(),i=0;try{for(;i<e.byteLength;){let r=e.slice(i,i+NC),o=new Ph({destinationIdentities:n,value:{case:`streamChunk`,value:new cg({content:r,streamId:t,chunkIndex:Gb(a)})}});yield s.sendDataPacket(o,J.RELIABLE),a+=1,i+=r.byteLength}}finally{r()}})},close(){return L(this,void 0,void 0,function*(){let e=new Ph({destinationIdentities:n,value:{case:`streamTrailer`,value:new lg({streamId:t})}});yield s.sendDataPacket(e,J.RELIABLE)})},abort(e){c.error(`Sink error:`,e)}}),r)})}};function FC(e){if(e.length===0)return new AbortController().signal;if(e.length===1)return e[0];for(let t of e)if(t.aborted)return t;let t=new AbortController,n=Array(e.length),r=()=>{for(let e of n)e()};return e.forEach((e,i)=>{let a=()=>{t.abort(e.reason),r()};e.addEventListener(`abort`,a),n[i]=()=>e.removeEventListener(`abort`,a)}),t.signal}function IC(e){let t=new AbortController;return setTimeout(()=>{t.abort(new DOMException(`signal timed out after ${e} ms`,`TimeoutError`))},e),t.signal}var LC=1,RC=2,zC=4,BC=8,VC=0,HC=12,UC=5,WC=7,GC=3,KC=3,qC=2,JC=1,YC=0,XC=3,ZC=2,QC=2,$C=1,ew=0,tw;(function(e){e[e.TooShort=0]=`TooShort`,e[e.HeaderOverrun=1]=`HeaderOverrun`,e[e.MissingExtWords=2]=`MissingExtWords`,e[e.UnsupportedVersion=3]=`UnsupportedVersion`,e[e.InvalidHandle=4]=`InvalidHandle`,e[e.MalformedExt=5]=`MalformedExt`})(tw||={});var nw=class e extends ly{constructor(e,t,n){super(19,e,n),this.name=`DataTrackDeserializeError`,this.reason=t,this.reasonName=tw[t]}static tooShort(){return new e(`Too short to contain a valid header`,tw.TooShort)}static headerOverrun(){return new e(`Header exceeds total packet length`,tw.HeaderOverrun)}static missingExtWords(){return new e(`Extension word indicator is missing`,tw.MissingExtWords)}static unsupportedVersion(t){return new e(`Unsupported version ${t}`,tw.UnsupportedVersion)}static invalidHandle(t){return new e(`invalid track handle: ${t.message}`,tw.InvalidHandle,{cause:t})}static malformedExt(t){return new e(`Extension with tag ${t} is malformed`,tw.MalformedExt)}},rw;(function(e){e[e.TooSmallForHeader=0]=`TooSmallForHeader`,e[e.TooSmallForPayload=1]=`TooSmallForPayload`})(rw||={});var iw=class e extends ly{constructor(e,t,n){super(19,e,n),this.name=`DataTrackSerializeError`,this.reason=t,this.reasonName=rw[t]}static tooSmallForHeader(){return new e(`Buffer cannot fit header`,rw.TooSmallForHeader)}static tooSmallForPayload(){return new e(`Buffer cannot fit payload`,rw.TooSmallForPayload)}},aw=class{toBinary(){let e=this.toBinaryLengthBytes(),t=new ArrayBuffer(e),n=new DataView(t),r=this.toBinaryInto(n);if(e!==r)throw Error(`${this.constructor.name}.toBinary: written bytes (${r} bytes) not equal to allocated array buffer length (${e} bytes).`);return new Uint8Array(t)}},ow;(function(e){e[e.UserTimestamp=2]=`UserTimestamp`,e[e.E2ee=1]=`E2ee`})(ow||={});var sw=class extends aw{},cw=class e extends sw{constructor(e){super(),this.timestamp=e}toBinaryLengthBytes(){return LC+LC+e.lengthBytes}toBinaryInto(t){let n=0;t.setUint8(n,e.tag),n+=LC,t.setUint8(n,e.lengthBytes),n+=LC,t.setBigUint64(n,this.timestamp),n+=BC;let r=this.toBinaryLengthBytes();if(n!==r)throw Error(`DataTrackUserTimestampExtension.toBinaryInto: Wrote ${n} bytes but expected length was ${r} bytes`);return n}toJSON(){return{tag:e.tag,lengthBytes:e.lengthBytes,timestamp:this.timestamp}}};cw.tag=ow.UserTimestamp,cw.lengthBytes=8;var lw=class e extends sw{constructor(e,t){super(),this.keyIndex=e,this.iv=t}toBinaryLengthBytes(){return LC+LC+e.lengthBytes}toBinaryInto(t){let n=0;t.setUint8(n,e.tag),n+=LC,t.setUint8(n,e.lengthBytes),n+=LC,t.setUint8(n,this.keyIndex),n+=LC;for(let e=0;e<this.iv.length;e+=1)t.setUint8(n,this.iv[e]),n+=LC;let r=this.toBinaryLengthBytes();if(n!==r)throw Error(`DataTrackE2eeExtension.toBinaryInto: Wrote ${n} bytes but expected length was ${r} bytes`);return n}toJSON(){return{tag:e.tag,lengthBytes:e.lengthBytes,keyIndex:this.keyIndex,iv:this.iv}}};lw.tag=ow.E2ee,lw.lengthBytes=13;var uw=class e extends aw{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.userTimestamp=e.userTimestamp,this.e2ee=e.e2ee}toBinaryLengthBytes(){let e=0;return this.userTimestamp&&(e+=this.userTimestamp.toBinaryLengthBytes()),this.e2ee&&(e+=this.e2ee.toBinaryLengthBytes()),e}toBinaryInto(e){let t=0;if(this.e2ee){let n=this.e2ee.toBinaryInto(e);t+=n}if(this.userTimestamp){let n=this.userTimestamp.toBinaryInto(new DataView(e.buffer,e.byteOffset+t));t+=n}let n=this.toBinaryLengthBytes();if(t!==n)throw Error(`DataTrackExtensions.toBinaryInto: Wrote ${t} bytes but expected length was ${n} bytes`);return t}static fromBinary(t){let n=Mx(t),r,i,a=0;for(;n.byteLength-a>=LC+LC;){let e=n.getUint8(a);a+=LC;let t=n.getUint8(a);if(a+=LC,e!==ew)switch(e){case ow.UserTimestamp:if(n.byteLength-a<cw.lengthBytes)throw nw.malformedExt(e);r=new cw(n.getBigUint64(a)),a+=t;break;case ow.E2ee:if(n.byteLength-a<lw.lengthBytes)throw nw.malformedExt(e);let o=n.getUint8(a),s=new Uint8Array(12);for(let e=0;e<s.length;e+=1){let t=a;t+=LC,t+=e*LC,s[e]=n.getUint8(t)}i=new lw(o,s),a+=t;break;default:if(n.byteLength-a<t)throw nw.malformedExt(e);a+=t;break}}return[new e({userTimestamp:r,e2ee:i}),n.byteLength]}toJSON(){return{userTimestamp:this.userTimestamp?.toJSON()??null,e2ee:this.e2ee?.toJSON()??null}}},dw={from(e){return{payload:e.payload,extensions:new uw({userTimestamp:e.userTimestamp?new cw(e.userTimestamp):void 0})}},lossyIntoFrame(e){return{payload:e.payload,userTimestamp:e.extensions.userTimestamp?.timestamp}}},fw=Symbol.for(`lk.track`),pw=Symbol.for(`lk.data-track`),mw=class{constructor(e,t,n){this.trackSymbol=fw,this.isLocal=!1,this.typeSymbol=pw,this.info=e,this.manager=t,this.publisherIdentity=n.publisherIdentity}subscribe(e){try{let[t]=this.manager.openSubscriptionStream(this.info.sid,e?.signal,e?.bufferSize);return t}catch(e){throw e}}},hw=class e extends aw{constructor(e){super(),this.marker=e.marker,this.trackHandle=e.trackHandle,this.sequence=e.sequence,this.frameNumber=e.frameNumber,this.timestamp=e.timestamp,this.extensions=e.extensions??new uw}extensionsMetrics(){let e=this.extensions.toBinaryLengthBytes(),t=Math.ceil(e/4);return{lengthBytes:e,lengthWords:t,paddingLengthBytes:t*4-e}}toBinaryLengthBytes(){let{lengthBytes:e,paddingLengthBytes:t}=this.extensionsMetrics(),n=HC;return e>0&&(n+=ZC+e+t),n}toBinaryInto(e){if(e.byteLength<this.toBinaryLengthBytes())throw iw.tooSmallForHeader();let t=VC<<UC,n;switch(this.marker){case gw.Inter:n=YC;break;case gw.Final:n=JC;break;case gw.Start:n=qC;break;case gw.Single:n=XC;break}t|=n<<GC;let{lengthBytes:r,lengthWords:i,paddingLengthBytes:a}=this.extensionsMetrics();r>0&&(t|=1<<QC);let o=0;if(e.setUint8(o,t),o+=LC,e.setUint8(o,0),o+=LC,e.setUint16(o,this.trackHandle),o+=RC,e.setUint16(o,this.sequence.value),o+=RC,e.setUint16(o,this.frameNumber.value),o+=RC,e.setUint32(o,this.timestamp.asTicks()),o+=zC,r>0){let t=i-1;e.setUint16(o,t),o+=RC;let n=this.extensions.toBinaryInto(new DataView(e.buffer,e.byteOffset+o));o+=n;for(let t=0;t<a;t+=1)e.setUint8(o,0),o+=LC}let s=this.toBinaryLengthBytes();if(o!==s)throw Error(`DataTrackPacketHeader.toBinaryInto: Wrote ${o} bytes but expected length was ${s} bytes`);return s}static fromBinary(t){let n=Mx(t);if(n.byteLength<HC)throw nw.tooShort();let r=0,i=n.getUint8(r);r+=LC;let a=i>>UC&WC;if(a>VC)throw nw.unsupportedVersion(a);let o;switch(i>>GC&KC){case qC:o=gw.Start;break;case JC:o=gw.Final;break;case XC:o=gw.Single;break;case YC:default:o=gw.Inter;break}let s=(i>>QC&$C)>0;r+=LC;let c;try{c=Fx.fromNumber(n.getUint16(r))}catch(e){throw e instanceof Px&&(e.isReason(Nx.Reserved)||e.isReason(Nx.TooLarge))?nw.invalidHandle(e):e}r+=RC;let l=kx.u16(n.getUint16(r));r+=RC;let u=kx.u16(n.getUint16(r));r+=RC;let d=Ax.fromRtpTicks(n.getUint32(r));r+=zC;let f=new uw;if(s){if(n.byteLength-r<RC)throw nw.missingExtWords();let e=n.getUint16(r);r+=RC;let t=4*(e+1);if(r+t>n.byteLength)throw nw.headerOverrun();let i=new DataView(n.buffer,n.byteOffset+r,t),[a,o]=uw.fromBinary(i);f=a,r+=o}return[new e({marker:o,trackHandle:c,sequence:l,frameNumber:u,timestamp:d,extensions:f}),r]}toJSON(){return{marker:this.marker,trackHandle:this.trackHandle,sequence:this.sequence.value,frameNumber:this.frameNumber.value,timestamp:this.timestamp.asTicks(),extensions:this.extensions.toJSON()}}},gw;(function(e){e[e.Start=0]=`Start`,e[e.Inter=1]=`Inter`,e[e.Final=2]=`Final`,e[e.Single=3]=`Single`})(gw||={});var _w=class e extends aw{constructor(e,t){super(),this.header=e,this.payload=t}toBinaryLengthBytes(){return this.header.toBinaryLengthBytes()+this.payload.byteLength}toBinaryInto(e){let t=0,n=this.header.toBinaryInto(e);if(t+=n,e.byteLength-t<this.payload.byteLength)throw iw.tooSmallForPayload();for(let n=0;n<this.payload.length;n+=1)e.setUint8(t,this.payload[n]),t+=LC;let r=this.toBinaryLengthBytes();if(t!==r)throw Error(`DataTrackPacket.toBinaryInto: Wrote ${t} bytes but expected length was ${r} bytes`);return r}static fromBinary(t){let n=Mx(t),[r,i]=hw.fromBinary(n),a=n.buffer.slice(n.byteOffset+i,n.byteOffset+n.byteLength);return[new e(r,new Uint8Array(a)),n.byteLength]}toJSON(){return{header:this.header.toJSON(),payload:this.payload}}},vw=O_(D_.DataTracks),yw=class e extends ly{constructor(e,t,n,r){super(19,`Frame ${n} dropped: ${e}`,r),this.name=`DataTrackDepacketizerDropError`,this.reason=t,this.reasonName=bw[t],this.frameNumber=n}static interrupted(t,n){return new e(`Interrupted by the start of a new frame ${n}`,bw.Interrupted,t)}static unknownFrame(t){return new e(`Initial packet was never received.`,bw.UnknownFrame,t)}static bufferFull(t){return new e(`Reorder buffer is full.`,bw.BufferFull,t)}static incomplete(t,n,r){return new e(`Not all packets received before final packet. Received ${n} packets, expected ${r} packets.`,bw.Incomplete,t)}},bw;(function(e){e[e.Interrupted=0]=`Interrupted`,e[e.UnknownFrame=1]=`UnknownFrame`,e[e.BufferFull=2]=`BufferFull`,e[e.Incomplete=3]=`Incomplete`})(bw||={});var xw=class e{constructor(){this.partial=null}push(e,t){switch(e.header.marker){case gw.Single:return this.frameFromSingle(e,t);case gw.Start:return this.beginPartial(e,t);case gw.Inter:case gw.Final:return this.pushToPartial(e)}}reset(){this.partial=null}frameFromSingle(e,t){if(e.header.marker!==gw.Single)throw Error(`Depacketizer.frameFromSingle: packet.header.marker was not FrameMarker.Single, found ${e.header.marker}.`);if(this.partial)if(t?.errorOnPartialFrames){let t=this.partial.frameNumber;throw this.reset(),yw.interrupted(t,e.header.frameNumber.value)}else vw.warn(`Data track frame ${this.partial.frameNumber} was interrupted by the start of a new frame, dropping.`);return this.reset(),{payload:e.payload,extensions:e.header.extensions}}beginPartial(e,t){if(e.header.marker!==gw.Start)throw Error(`Depacketizer.beginPartial: packet.header.marker was not FrameMarker.Start, found ${e.header.marker}.`);if(this.partial)if(t?.errorOnPartialFrames){let t=this.partial.frameNumber;throw this.reset(),yw.interrupted(t,e.header.frameNumber.value)}else vw.warn(`Data track frame ${this.partial.frameNumber} was interrupted by the start of a new frame ${e.header.frameNumber.value}, dropping.`);this.reset();let n=e.header.sequence;return this.partial={frameNumber:e.header.frameNumber.value,startSequence:n,extensions:e.header.extensions,payloads:new Map([[n.value,e.payload]])},null}pushToPartial(t){if(t.header.marker!==gw.Inter&&t.header.marker!==gw.Final)throw Error(`Depacketizer.pushToPartial: packet.header.marker was not FrameMarker.Inter or FrameMarker.Final, found ${t.header.marker}.`);if(!this.partial)throw this.reset(),yw.unknownFrame(t.header.frameNumber.value);if(t.header.frameNumber.value!==this.partial.frameNumber){let e=this.partial.frameNumber;throw this.reset(),yw.interrupted(e,t.header.frameNumber.value)}if(this.partial.payloads.size>=e.MAX_BUFFER_PACKETS){let e=this.partial.frameNumber;throw this.reset(),yw.bufferFull(e)}return this.partial.payloads.has(t.header.sequence.value)&&vw.warn(`Data track frame ${this.partial.frameNumber} received duplicate packet for sequence ${t.header.sequence.value}, so replacing with newly received packet.`),this.partial.payloads.set(t.header.sequence.value,t.payload),t.header.marker===gw.Final?this.finalize(this.partial,t.header.sequence.value):null}finalize(e,t){let n=e.payloads.size,r=0;for(let t of e.payloads.values())r+=t.length;let i=new Uint8Array(r),a=e.startSequence.clone(),o=0;for(;;){let n=e.payloads.get(a.value);if(!n)break;e.payloads.delete(a.value);let r=i.length-o;if(n.length>r)throw Error(`Depacketizer.finalize: Expected at least ${n.length} more bytes left in the payload buffer, only got ${r} bytes.`);if(i.set(n,o),o+=n.length,a.value!=t){a.increment();continue}return this.reset(),{payload:i,extensions:e.extensions}}throw this.reset(),yw.incomplete(e.frameNumber,n,t-e.startSequence.value+1)}};xw.MAX_BUFFER_PACKETS=128;var Sw;(function(e){e[e.Unpublished=0]=`Unpublished`,e[e.Timeout=1]=`Timeout`,e[e.Disconnected=2]=`Disconnected`,e[e.Cancelled=4]=`Cancelled`})(Sw||={});var Cw=class e extends ly{constructor(e,t,n){super(22,e,n),this.name=`DataTrackSubscribeError`,this.reason=t,this.reasonName=Sw[t]}static unpublished(){return new e(`The track has been unpublished and is no longer available`,Sw.Unpublished)}static timeout(){return new e(`Request to subscribe to data track timed-out`,Sw.Timeout)}static disconnected(){return new e(`Cannot subscribe to data track when disconnected`,Sw.Disconnected)}static cancelled(){return new e(`Subscription to data track cancelled by caller`,Sw.Cancelled)}},ww=O_(D_.DataTracks),Tw=class{constructor(e){let t=e.e2eeManager!==null;if(e.info.usesE2ee!==t)throw Error(`IncomingDataTrackPipeline: DataTrackInfo.usesE2ee must match presence of decryptionProvider`);let n=new xw;this.publisherIdentity=e.publisherIdentity,this.e2eeManager=e.e2eeManager??null,this.depacketizer=n}updateE2eeManager(e){this.e2eeManager=e}processPacket(e){return L(this,void 0,void 0,function*(){let t=this.depacketize(e);return t&&(yield this.decryptIfNeeded(t))||null})}depacketize(e){let t;try{t=this.depacketizer.push(e)}catch(e){return ww.warn(`Data frame depacketize error: ${e}`),null}return t}decryptIfNeeded(e){return L(this,void 0,void 0,function*(){let t=this.e2eeManager;if(!t)return e;let n=e.extensions?.e2ee??null;if(!n)return ww.error(`Missing E2EE meta`),null;let r;try{r=yield t.handleEncryptedData(e.payload,n.iv,this.publisherIdentity,n.keyIndex)}catch(e){return ww.error(`Error decrypting packet: ${e}`),null}return e.payload=r.payload,e})}},Ew=O_(D_.DataTracks),Dw=1e4,Ow=16,kw=class extends H_.EventEmitter{constructor(e){super(),this.descriptors=new Map,this.subscriptionHandles=new Map,this.e2eeManager=e?.e2eeManager??null}updateE2eeManager(e){this.e2eeManager=e;for(let t of this.descriptors.values())t.subscription.type===`active`&&t.subscription.pipeline.updateE2eeManager(e)}openSubscriptionStream(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Ow,r=null,i=new Ib;return[new ReadableStream({start:n=>{r=n;let a=()=>{var e;n.error(Cw.cancelled()),(e=i.reject)==null||e.call(i,Cw.cancelled())};this.subscribeRequest(e,t).then(()=>L(this,void 0,void 0,function*(){var r;t?.addEventListener(`abort`,a);let o=this.descriptors.get(e);if(!o){Ew.error(`Unknown track ${e}`);return}if(o.subscription.type!==`active`){Ew.error(`Subscription for track ${e} is not active`);return}o.subscription.streamControllers.add(n),(r=i.resolve)==null||r.call(i)})).catch(e=>{var t;n.error(e),(t=i.reject)==null||t.call(i,e)}).finally(()=>{t?.removeEventListener(`abort`,a)})},cancel:()=>{if(!r){Ew.warn(`ReadableStream subscribed to ${e} was not started.`);return}let t=this.descriptors.get(e);if(!t){Ew.warn(`Unknown track ${e}, skipping cancel...`);return}if(t.subscription.type!==`active`){Ew.warn(`Subscription for track ${e} is not active, skipping cancel...`);return}t.subscription.streamControllers.delete(r),t.subscription.streamControllers.size===0&&this.unSubscribeRequest(t.info.sid)}},new CountQueuingStrategy({highWaterMark:n})),i.promise]}subscribeRequest(e,t){return L(this,void 0,void 0,function*(){let n=this.descriptors.get(e);if(!n)throw Error(`Cannot subscribe to unknown track`);let r=(t,n,r)=>L(this,void 0,void 0,function*(){if(t.subscription.type===`active`)return;if(t.subscription.type!==`pending`)throw Error(`Descriptor for track ${e} is not pending, found ${t.subscription.type}`);let i=FC([n,r].filter(e=>e!==void 0)),a=new Ib;t.subscription.completionFuture.promise.then(()=>a.resolve?.call(a)).catch(e=>a.reject?.call(a,e));let o=()=>{var e;if(t.subscription.type===`pending`){if(--t.subscription.pendingRequestCount,r?.aborted){t.subscription.cancel();return}if(t.subscription.pendingRequestCount<=0){t.subscription.cancel();return}(e=a.reject)==null||e.call(a,Cw.cancelled())}};i.aborted&&o(),i.addEventListener(`abort`,o),yield a.promise,i.removeEventListener(`abort`,o)});switch(n.subscription.type){case`none`:{n.subscription={type:`pending`,completionFuture:new Ib,pendingRequestCount:1,cancel:()=>{var t,r;let a=n.subscription;n.subscription={type:`none`},this.emit(`sfuUpdateSubscription`,{sid:e,subscribe:!1}),a.type===`pending`&&((r=(t=a.completionFuture).reject)==null||r.call(t,i.aborted?Cw.timeout():Cw.cancelled()))}},this.emit(`sfuUpdateSubscription`,{sid:e,subscribe:!0});let i=IC(Dw);yield r(n,t,i);return}case`pending`:n.subscription.pendingRequestCount+=1,yield r(n,t);return;case`active`:return}})}querySubscribed(){return L(this,void 0,void 0,function*(){return Array.from(this.descriptors.values()).filter(e=>e.subscription.type===`active`).map(e=>[e.info,e.publisherIdentity])})}unSubscribeRequest(e){let t=this.descriptors.get(e);if(!t)throw Error(`Cannot subscribe to unknown track`);if(t.subscription.type!==`active`){Ew.warn(`Unexpected descriptor state in unSubscribeRequest, expected active, found ${t.subscription?.type}`);return}for(let e of t.subscription.streamControllers)e.close();let n=t.subscription;t.subscription={type:`none`},this.subscriptionHandles.delete(n.subcriptionHandle),this.emit(`sfuUpdateSubscription`,{sid:e,subscribe:!1})}receiveSfuPublicationUpdates(e){return L(this,void 0,void 0,function*(){if(e.size===0)return;let t=new Map;for(let[n,r]of e.entries()){let e=new Set;for(let t of r)e.add(t.sid),!this.descriptors.has(t.sid)&&(yield this.handleTrackPublished(n,t));t.set(n,e)}for(let[e,n]of t.entries()){let t=Array.from(this.descriptors.entries()).filter(t=>{let[n,r]=t;return r.publisherIdentity===e}).map(e=>{let[t]=e;return t}).filter(e=>!n.has(e));for(let e of t)this.handleTrackUnpublished(e)}})}queryPublications(){return L(this,void 0,void 0,function*(){return Array.from(this.descriptors.values()).map(e=>e.info)})}handleTrackPublished(e,t){return L(this,void 0,void 0,function*(){if(this.descriptors.has(t.sid)){Ew.error(`Existing descriptor for track ${t.sid}`);return}let n={info:t,publisherIdentity:e,subscription:{type:`none`}};this.descriptors.set(n.info.sid,n);let r=new mw(n.info,this,{publisherIdentity:e});this.emit(`trackPublished`,{track:r})})}handleTrackUnpublished(e){let t=this.descriptors.get(e);if(!t){Ew.error(`Unknown track ${e}`);return}this.descriptors.delete(e),t.subscription.type===`active`&&this.subscriptionHandles.delete(t.subscription.subcriptionHandle),this.emit(`trackUnpublished`,{sid:e,publisherIdentity:t.publisherIdentity})}receivedSfuSubscriberHandles(e){for(let[t,n]of e.entries())this.registerSubscriberHandle(t,n)}registerSubscriberHandle(e,t){var n,r;let i=this.descriptors.get(t);if(!i){Ew.error(`Unknown track ${t}`);return}switch(i.subscription.type){case`none`:Ew.warn(`No subscription for ${t}`);return;case`active`:i.subscription.subcriptionHandle=e,this.subscriptionHandles.set(e,t);return;case`pending`:{let a=new Tw({info:i.info,publisherIdentity:i.publisherIdentity,e2eeManager:this.e2eeManager}),o=i.subscription;i.subscription={type:`active`,subcriptionHandle:e,pipeline:a,streamControllers:new Set},this.subscriptionHandles.set(e,t),(r=(n=o.completionFuture).resolve)==null||r.call(n)}}}packetReceived(e){return L(this,void 0,void 0,function*(){let t;try{[t]=_w.fromBinary(e)}catch(e){Ew.error(`Failed to deserialize packet: ${e}`);return}let n=this.subscriptionHandles.get(t.header.trackHandle);if(!n){Ew.warn(`Unknown subscriber handle ${t.header.trackHandle}`);return}let r=this.descriptors.get(n);if(!r){Ew.error(`Missing descriptor for track ${n}`);return}if(r.subscription.type!==`active`){Ew.warn(`Received packet for track ${n} without active subscription`);return}let i=yield r.subscription.pipeline.processPacket(t);if(i)for(let e of r.subscription.streamControllers){if(e.desiredSize!==null&&e.desiredSize<=0){Ew.warn(`Cannot send frame to subscribers: readable stream is full (desiredSize is ${e.desiredSize}). To increase this threshold, set a higher 'options.highWaterMark' when calling .subscribe().`);continue}let t=dw.lossyIntoFrame(i);e.enqueue(t)}})}resendSubscriptionUpdates(){for(let[e,t]of this.descriptors)t.subscription.type!==`none`&&this.emit(`sfuUpdateSubscription`,{sid:e,subscribe:!0})}handleRemoteParticipantDisconnected(e){var t,n;for(let r of this.descriptors.values())if(r.publisherIdentity===e)switch(r.subscription.type){case`none`:break;case`pending`:(n=(t=r.subscription.completionFuture).reject)==null||n.call(t,Cw.disconnected());break;case`active`:this.unSubscribeRequest(r.info.sid);break}}shutdown(){var e,t;for(let n of this.descriptors.values())this.emit(`trackUnpublished`,{sid:n.info.sid,publisherIdentity:n.publisherIdentity}),n.subscription.type===`pending`&&((t=(e=n.subscription.completionFuture).reject)==null||t.call(e,Cw.disconnected()));this.descriptors.clear()}},Aw=class e extends ly{constructor(e,t,n){super(19,e,n),this.name=`DataTrackPacketizerError`,this.reason=t,this.reasonName=jw[t]}static mtuTooShort(){return new e(`MTU is too short to send frame`,jw.MtuTooShort)}},jw;(function(e){e[e.MtuTooShort=0]=`MtuTooShort`})(jw||={});var Mw=class e{constructor(e,t){this.sequence=kx.u16(0),this.frameNumber=kx.u16(0),this.clock=jx.rtpStartingNow(Ax.rtpRandom()),this.handle=e,this.mtuSizeBytes=t}static computeFrameMarker(e,t){return t<=1?gw.Single:e===0?gw.Start:e===t-1?gw.Final:gw.Inter}*packetize(t,n){let r=this.frameNumber.getThenIncrement(),i={marker:gw.Inter,trackHandle:this.handle,sequence:kx.u16(0),frameNumber:r,timestamp:n?.now??this.clock.now(),extensions:t.extensions},a=new hw(i).toBinaryLengthBytes();if(a>=this.mtuSizeBytes)throw Aw.mtuTooShort();let o=this.mtuSizeBytes-a,s=Math.ceil(t.payload.byteLength/o);for(let n=0,r=0;r<t.payload.byteLength;[n,r]=[n+1,r+o]){let a=this.sequence.getThenIncrement(),c=new hw(Object.assign(Object.assign({},i),{marker:e.computeFrameMarker(n,s),sequence:a})),l=Math.min(o,t.payload.byteLength-r);yield new _w(c,new Uint8Array(t.payload.buffer,t.payload.byteOffset+r,l))}}},Nw;(function(e){e[e.NotAllowed=0]=`NotAllowed`,e[e.DuplicateName=1]=`DuplicateName`,e[e.Timeout=2]=`Timeout`,e[e.LimitReached=3]=`LimitReached`,e[e.Disconnected=4]=`Disconnected`,e[e.Cancelled=5]=`Cancelled`,e[e.InvalidName=6]=`InvalidName`,e[e.Unknown=7]=`Unknown`})(Nw||={});var Pw=class e extends ly{constructor(e,t,n){super(21,e,n),this.name=`DataTrackPublishError`,this.reason=t,this.reasonName=Nw[t],this.rawMessage=n?.rawMessage}static notAllowed(t){return new e(`Data track publishing unauthorized`,Nw.NotAllowed,{rawMessage:t})}static duplicateName(t){return new e(`Track name already taken`,Nw.DuplicateName,{rawMessage:t})}static invalidName(t){return new e(`Track name is invalid`,Nw.InvalidName,{rawMessage:t})}static timeout(){return new e(`Publish data track timed-out. Does the LiveKit server support data tracks?`,Nw.Timeout)}static limitReached(t){return new e(`Data track publication limit reached`,Nw.LimitReached,{rawMessage:t})}static unknown(t,n){return new e(`Received RequestResponse for publishDataTrack, but reason was unrecognised (${t}, ${n})`,Nw.Unknown)}static disconnected(){return new e(`Room disconnected`,Nw.Disconnected)}static cancelled(){return new e(`Publish data track cancelled by caller`,Nw.Cancelled)}},Fw;(function(e){e[e.TrackUnpublished=0]=`TrackUnpublished`,e[e.Dropped=1]=`Dropped`})(Fw||={});var Iw=class e extends ly{constructor(e,t,n){super(22,e,n),this.name=`DataTrackPushFrameError`,this.reason=t,this.reasonName=Fw[t]}static trackUnpublished(){return new e(`Track is no longer published`,Fw.TrackUnpublished)}static dropped(t){return new e(`Frame was dropped`,Fw.Dropped,{cause:t})}},Lw;(function(e){e[e.Packetizer=0]=`Packetizer`,e[e.Encryption=1]=`Encryption`})(Lw||={});var Rw=class e extends ly{constructor(e,t,n){super(21,e,n),this.name=`DataTrackOutgoingPipelineError`,this.reason=t,this.reasonName=Lw[t]}static packetizer(t){return new e(`Error packetizing frame`,Lw.Packetizer,{cause:t})}static encryption(t){return new e(`Error encrypting frame`,Lw.Encryption,{cause:t})}},zw=class e{constructor(e,t){this.trackSymbol=fw,this.isLocal=!0,this.typeSymbol=pw,this.handle=null,this.log=I,this.options=e,this.manager=t,this.log=O_(D_.DataTracks)}static withExplicitHandle(t,n,r){let i=new e(t,n);return i.handle=r,i}get info(){let e=this.descriptor;if(e?.type===`active`)return e.info}get descriptor(){return this.handle?this.manager.getDescriptor(this.handle):null}publish(e){return L(this,void 0,void 0,function*(){try{this.handle=yield this.manager.publishRequest(this.options,e)}catch(e){throw e}})}isPublished(){return this.descriptor?.type===`active`&&this.descriptor.publishState!==`unpublished`}tryPush(e){if(!this.handle)throw Iw.trackUnpublished();let t=dw.from(e);try{return this.manager.tryProcessAndSend(this.handle,t)}catch(e){throw e}}unpublish(){return L(this,void 0,void 0,function*(){if(!this.handle){I.warn(`Data track "${this.options.name}" is not published, so unpublishing has no effect.`);return}try{yield this.manager.unpublishRequest(this.handle)}catch(e){throw e}})}},Bw=class e{constructor(t){this.e2eeManager=t.e2eeManager,this.packetizer=new Mw(t.info.pubHandle,e.TRANSPORT_MTU_BYTES)}updateE2eeManager(e){this.e2eeManager=e}processFrame(e){return I_(this,arguments,function*(){let t=yield F_(this.encryptIfNeeded(e));try{yield F_(yield*L_(R_(this.packetizer.packetize(t))))}catch(e){throw e instanceof Aw?Rw.packetizer(e):e}})}encryptIfNeeded(e){return L(this,void 0,void 0,function*(){if(!this.e2eeManager)return e;let t;try{t=yield this.e2eeManager.encryptData(e.payload)}catch(e){throw Rw.encryption(e)}return e.payload=t.payload,e.extensions.e2ee=new lw(t.keyIndex,t.iv),e})}};Bw.TRANSPORT_MTU_BYTES=16e3;var Vw=O_(D_.DataTracks),Hw={pending(){return{type:`pending`,completionFuture:new Ib}},active(e,t){return{type:`active`,info:e,publishState:`published`,pipeline:new Bw({info:e,e2eeManager:t}),unpublishingFuture:new Ib}}},Uw=1e4,Ww=class e extends H_.EventEmitter{constructor(e){super(),this.handleAllocator=new Ix,this.descriptors=new Map,this.e2eeManager=e?.e2eeManager??null}static withDescriptors(t){let n=new e;return n.descriptors=t,n}updateE2eeManager(e){this.e2eeManager=e;for(let t of this.descriptors.values())t.type===`active`&&t.pipeline.updateE2eeManager(e)}getDescriptor(e){return this.descriptors.get(e)??null}tryProcessAndSend(e,t){return L(this,void 0,void 0,function*(){var n,r,i,a;let o=this.getDescriptor(e);if(o?.type!==`active`||o.publishState===`unpublished`)throw Iw.trackUnpublished();if(o.publishState===`republishing`)throw Iw.dropped(`Data track republishing`);try{try{for(var s=!0,c=R_(o.pipeline.processFrame(t)),l;l=yield c.next(),n=l.done,!n;s=!0){a=l.value,s=!1;let e=a;this.emit(`packetAvailable`,{bytes:e.toBinary()})}}catch(e){r={error:e}}finally{try{!s&&!n&&(i=c.return)&&(yield i.call(c))}finally{if(r)throw r.error}}}catch(e){throw Iw.dropped(e)}})}publishRequest(e,t){return L(this,void 0,void 0,function*(){let n=this.handleAllocator.get();if(!n)throw Pw.limitReached();let r=IC(Uw),i=t?FC([t,r]):r;if(this.descriptors.has(n))throw Error(`Descriptor for handle already exists`);let a=Hw.pending();this.descriptors.set(n,a);let o=()=>{var e,t;let i=this.descriptors.get(n);if(!i){Vw.warn(`No descriptor for ${n}`);return}this.descriptors.delete(n),this.emit(`sfuUnpublishRequest`,{handle:n}),i.type===`pending`&&((t=(e=i.completionFuture).reject)==null||t.call(e,r.aborted?Pw.timeout():Pw.cancelled()))};return i.aborted?(o(),a.completionFuture.promise.then(()=>n)):(i.addEventListener(`abort`,o),this.emit(`sfuPublishRequest`,{handle:n,name:e.name,usesE2ee:this.e2eeManager!==null}),yield a.completionFuture.promise,i.removeEventListener(`abort`,o),this.emit(`trackPublished`,{track:zw.withExplicitHandle(e,this,n)}),n)})}queryPublished(){return Array.from(this.descriptors.values()).filter(e=>e.type===`active`).map(e=>e.info)}unpublishRequest(e){return L(this,void 0,void 0,function*(){let t=this.descriptors.get(e);if(!t){Vw.warn(`No descriptor for ${e}`);return}if(t.type!==`active`){Vw.warn(`Track ${e} not active`);return}this.emit(`sfuUnpublishRequest`,{handle:e}),yield t.unpublishingFuture.promise,this.emit(`trackUnpublished`,{sid:t.info.sid})})}receivedSfuPublishResponse(e,t){var n,r,i,a;let o=this.descriptors.get(e);if(!o){Vw.warn(`No descriptor for ${e}`);return}switch(this.descriptors.delete(e),o.type){case`pending`:if(t.type===`ok`){let e=t.data,i=e.usesE2ee?this.e2eeManager:null;this.descriptors.set(e.pubHandle,Hw.active(e,i)),(r=(n=o.completionFuture).resolve)==null||r.call(n)}else (a=(i=o.completionFuture).reject)==null||a.call(i,t.error);return;case`active`:if(o.publishState!==`republishing`){Vw.warn(`Track ${e} already active`);return}if(t.type===`error`){Vw.warn(`Republish failed for track ${e}`);return}Vw.debug(`Track ${e} republished`),o.info.sid=t.data.sid,o.publishState=`published`,this.descriptors.set(o.info.pubHandle,o)}}receivedSfuUnpublishResponse(e){var t,n;let r=this.descriptors.get(e);if(!r){Vw.warn(`No descriptor for ${e}`);return}if(this.descriptors.delete(e),r.type!==`active`){Vw.warn(`Track ${e} not active`);return}r.publishState=`unpublished`,(n=(t=r.unpublishingFuture).resolve)==null||n.call(t)}sfuWillRepublishTracks(){var e,t;for(let[n,r]of this.descriptors.entries())switch(r.type){case`pending`:this.descriptors.delete(n),(t=(e=r.completionFuture).reject)==null||t.call(e,Pw.disconnected());break;case`active`:r.publishState=`republishing`,this.emit(`sfuPublishRequest`,{handle:r.info.pubHandle,name:r.info.name,usesE2ee:r.info.usesE2ee})}}shutdown(){return L(this,void 0,void 0,function*(){var e,t,n,r;for(let i of this.descriptors.values())switch(i.type){case`pending`:(t=(e=i.completionFuture).reject)==null||t.call(e,Pw.disconnected());break;case`active`:(r=(n=i.unpublishingFuture).resolve)==null||r.call(n),yield this.unpublishRequest(i.info.pubHandle);break}this.descriptors.clear()})}},Gw=class extends K{constructor(e,t,n,r,i){super(e,n,i),this.sid=t,this.receiver=r}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?U.Muted:U.Unmuted,this))}setMediaStream(e){this.mediaStream=e;let t=n=>{n.track===this._mediaStreamTrack&&(e.removeEventListener(`removetrack`,t),this.receiver&&`playoutDelayHint`in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(U.Ended,this))};e.addEventListener(`removetrack`,t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return L(this,void 0,void 0,function*(){if(this.receiver?.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||=setInterval(()=>this.monitorReceiver(),FS),Hy()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){let e=()=>{this.timeSyncHandle=requestAnimationFrame(()=>e());let t=this.receiver?.getSynchronizationSources()[0];if(t){let{timestamp:e,rtpTimestamp:n}=t;n&&this.rtpTimestamp!==n&&(this.emit(U.TimeSyncUpdate,{timestamp:e,rtpTimestamp:n}),this.rtpTimestamp=n)}};e()}},Kw=class extends Gw{constructor(e,t,n,r,i,a){super(e,t,K.Kind.Audio,n,a),this.monitorReceiver=()=>L(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=IS(e,this.prevStats)),this.prevStats=e}),this.audioContext=r,this.webAudioPluginNodes=[],i&&(this.sinkId=i.deviceId)}setVolume(e){var t;for(let n of this.attachedElements)this.audioContext?(t=this.gainNode)==null||t.gain.setTargetAtTime(e,0,.1):n.volume=e;yb()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(yb())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return L(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(cb(t))return t.setSinkId(e)}))})}attach(e){let t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&cb(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 n=this.sourceNode;this.webAudioPluginNodes.forEach(e=>{n.connect(e),n=e}),this.gainNode=e.createGain(),n.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),e.state!==`running`&&e.resume().then(()=>{e.state!==`running`&&this.emit(U.AudioPlaybackFailed,Error(`Audio Context couldn't be started automatically`))}).catch(e=>{this.emit(U.AudioPlaybackFailed,e)})}disconnectWebAudio(){var e,t;(e=this.gainNode)==null||e.disconnect(),(t=this.sourceNode)==null||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return L(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;let e=yield this.receiver.getStats(),t;return e.forEach(e=>{e.type===`inbound-rtp`&&(t={type:`audio`,streamId:e.id,timestamp:e.timestamp,jitter:e.jitter,bytesReceived:e.bytesReceived,concealedSamples:e.concealedSamples,concealmentEvents:e.concealmentEvents,silentConcealedSamples:e.silentConcealedSamples,silentConcealmentEvents:e.silentConcealmentEvents,totalAudioEnergy:e.totalAudioEnergy,totalSamplesDuration:e.totalSamplesDuration})}),t})}},qw=100,Jw=class extends Gw{constructor(e,t,n,r,i){super(e,t,K.Kind.Video,n,i),this.elementInfos=[],this.monitorReceiver=()=>L(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=IS(e,this.prevStats)),this.prevStats=e}),this.debouncedHandleResize=uS(()=>{this.updateDimensions()},qw),this.adaptiveStreamSettings=r}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}setStreamState(e){super.setStreamState(e),this.log.debug(`setStreamState`,e),this.isAdaptiveStream&&e===K.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?Qy(this._mediaStreamTrack,t):Zy(this._mediaStreamTrack,t)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(t=>t.element===e)===void 0){let t=new Yw(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&this.elementInfos.find(t=>t===e)===void 0?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn(`visibility resize observer not triggered`,this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream){this.log.warn(`stopObservingElementInfo ignored`,this.logContext);return}let t=this.elementInfos.filter(t=>t===e);for(let e of t)e.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);t=super.detach();for(let e of t)this.stopObservingElement(e);return t}getDecoderImplementation(){return this.prevStats?.decoderImplementation}getReceiverStats(){return L(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;let e=yield this.receiver.getStats(),t,n=``,r=new Map;return e.forEach(e=>{e.type===`inbound-rtp`?(n=e.codecId,t={type:`video`,streamId:e.id,framesDecoded:e.framesDecoded,framesDropped:e.framesDropped,framesReceived:e.framesReceived,packetsReceived:e.packetsReceived,packetsLost:e.packetsLost,frameWidth:e.frameWidth,frameHeight:e.frameHeight,pliCount:e.pliCount,firCount:e.firCount,nackCount:e.nackCount,jitter:e.jitter,timestamp:e.timestamp,bytesReceived:e.bytesReceived,decoderImplementation:e.decoderImplementation}):e.type===`codec`&&r.set(e.id,e)}),t&&n!==``&&r.get(n)&&(t.mimeType=r.get(n).mimeType),t})}stopObservingElement(e){let t=this.elementInfos.filter(t=>t.element===e);for(let e of t)this.stopObservingElementInfo(e)}handleAppVisibilityChanged(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return L(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(e){let t=this.elementInfos.reduce((e,t)=>Math.max(e,t.visibilityChangedAt||0),0),n=this.adaptiveStreamSettings?.pauseVideoInBackground??!0?this.isInBackground:!1,r=this.elementInfos.some(e=>e.pictureInPicture),i=this.elementInfos.some(e=>e.visible)&&!n||r;if(!(this.lastVisible===i&&!e)){if(!i&&Date.now()-t<qw){xy.setTimeout(()=>{this.updateVisibility()},qw);return}this.lastVisible=i,this.emit(U.VisibilityChanged,i,this)}}updateDimensions(){let e=0,t=0,n=this.getPixelDensity();for(let r of this.elementInfos){let i=r.width()*n,a=r.height()*n;i+a>e+t&&(e=i,t=a)}this.lastDimensions?.width===e&&this.lastDimensions?.height===t||(this.lastDimensions={width:e,height:t},this.emit(U.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){let e=this.adaptiveStreamSettings?.pixelDensity;return e===`screen`?wb():e||(wb()>2?2:1)}},Yw=class{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=e=>{var t;let{target:n,isIntersecting:r}=e;n===this.element&&(this.isIntersecting=r,this.isPiP=Xw(this.element),this.visibilityChangedAt=Date.now(),(t=this.handleVisibilityChanged)==null||t.call(this))},this.onEnterPiP=()=>{var e,t;(e=window.documentPictureInPicture?.window)==null||e.addEventListener(`pagehide`,this.onLeavePiP),this.isPiP=Xw(this.element),(t=this.handleVisibilityChanged)==null||t.call(this)},this.onLeavePiP=()=>{var e;this.isPiP=Xw(this.element),(e=this.handleVisibilityChanged)==null||e.call(this)},this.element=e,this.isIntersecting=t??Zw(e),this.isPiP=vb()&&Xw(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t;this.isIntersecting=Zw(this.element),this.isPiP=Xw(this.element),this.element.handleResize=()=>{var e;(e=this.handleResize)==null||e.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,jb().observe(this.element),kb().observe(this.element),this.element.addEventListener(`enterpictureinpicture`,this.onEnterPiP),this.element.addEventListener(`leavepictureinpicture`,this.onLeavePiP),(e=window.documentPictureInPicture)==null||e.addEventListener(`enter`,this.onEnterPiP),(t=window.documentPictureInPicture?.window)==null||t.addEventListener(`pagehide`,this.onLeavePiP)}stopObserving(){var e,t,n,r;(e=jb())==null||e.unobserve(this.element),(t=kb())==null||t.unobserve(this.element),this.element.removeEventListener(`enterpictureinpicture`,this.onEnterPiP),this.element.removeEventListener(`leavepictureinpicture`,this.onLeavePiP),(n=window.documentPictureInPicture)==null||n.removeEventListener(`enter`,this.onEnterPiP),(r=window.documentPictureInPicture?.window)==null||r.removeEventListener(`pagehide`,this.onLeavePiP)}};function Xw(e){return document.pictureInPictureElement===e?!0:window.documentPictureInPicture?.window?Zw(e,window.documentPictureInPicture?.window):!1}function Zw(e,t){let n=t||window,r=e.offsetTop,i=e.offsetLeft,a=e.offsetWidth,o=e.offsetHeight,{hidden:s}=e,{display:c}=getComputedStyle(e);for(;e.offsetParent;)e=e.offsetParent,r+=e.offsetTop,i+=e.offsetLeft;return r<n.pageYOffset+n.innerHeight&&i<n.pageXOffset+n.innerWidth&&r+o>n.pageYOffset&&i+a>n.pageXOffset&&!s&&c!==`none`}var Qw=class extends H_.EventEmitter{constructor(e,t,n,r){super(),this.metadataMuted=!1,this.encryption=F.NONE,this.log=I,this.handleMuted=()=>{this.emit(U.Muted)},this.handleUnmuted=()=>{this.emit(U.Unmuted)},this.log=O_(r?.loggerName??D_.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=n,this.source=K.Source.Unknown}setTrack(e){this.track&&(this.track.off(U.Muted,this.handleMuted),this.track.off(U.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(U.Muted,this.handleMuted),e.on(U.Unmuted,this.handleUnmuted))}get logContext(){return Object.assign(Object.assign({},this.loggerContextCb?.call(this)),G(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==F.NONE}get audioTrack(){if(qb(this.track))return this.track}get videoTrack(){if(Jb(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=K.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===K.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){(function(e){e.Desired=`desired`,e.Subscribed=`subscribed`,e.Unsubscribed=`unsubscribed`})(e.SubscriptionStatus||={}),(function(e){e.Allowed=`allowed`,e.NotAllowed=`not_allowed`})(e.PermissionStatus||={})})(Qw||={});var $w=class extends Qw{get isUpstreamPaused(){return this.track?.isUpstreamPaused}constructor(e,t,n,r){super(e,t.sid,t.name,r),this.track=void 0,this.handleTrackEnded=()=>{this.emit(U.Ended)},this.handleCpuConstrained=()=>{this.track&&Jb(this.track)&&this.emit(U.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(n)}setTrack(e){this.track&&(this.track.off(U.Ended,this.handleTrackEnded),this.track.off(U.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(U.Ended,this.handleTrackEnded),e.on(U.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 L(this,void 0,void 0,function*(){return this.track?.mute()})}unmute(){return L(this,void 0,void 0,function*(){return this.track?.unmute()})}pauseUpstream(){return L(this,void 0,void 0,function*(){yield this.track?.pauseUpstream()})}resumeUpstream(){return L(this,void 0,void 0,function*(){yield this.track?.resumeUpstream()})}getTrackFeatures(){if(qb(this.track)){let e=this.track.getSourceTrackSettings(),t=new Set;return e.autoGainControl&&t.add(bh.TF_AUTO_GAIN_CONTROL),e.echoCancellation&&t.add(bh.TF_ECHO_CANCELLATION),e.noiseSuppression&&t.add(bh.TF_NOISE_SUPPRESSION),e.channelCount&&e.channelCount>1&&t.add(bh.TF_STEREO),this.options?.dtx||t.add(bh.TF_NO_DTX),this.track.enhancedNoiseCancellation&&t.add(bh.TF_ENHANCED_NOISE_CANCELLATION),Array.from(t.values())}else return[]}};function eT(e,t){return L(this,void 0,void 0,function*(){e??={};let n=!1,{audioProcessor:r,videoProcessor:i,optionsWithoutProcessor:a}=Wy(e),o=a.audio,s=a.video;if(r&&typeof a.audio==`object`&&(a.audio.processor=r),i&&typeof a.video==`object`&&(a.video.processor=i),e.audio&&typeof a.audio==`object`&&typeof a.audio.deviceId==`string`){let e=a.audio.deviceId;a.audio.deviceId={exact:e},n=!0,o=Object.assign(Object.assign({},a.audio),{deviceId:{ideal:e}})}if(a.video&&typeof a.video==`object`&&typeof a.video.deviceId==`string`){let e=a.video.deviceId;a.video.deviceId={exact:e},n=!0,s=Object.assign(Object.assign({},a.video),{deviceId:{ideal:e}})}a.audio===!0?a.audio={deviceId:`default`}:typeof a.audio==`object`&&a.audio!==null&&(a.audio=Object.assign(Object.assign({},a.audio),{deviceId:a.audio.deviceId||`default`})),a.video===!0?a.video={deviceId:`default`}:typeof a.video==`object`&&!a.video.deviceId&&(a.video.deviceId=`default`);let c=My(a,xS,SS),l=Py(c),u=navigator.mediaDevices.getUserMedia(l);a.audio&&(Ex.userMediaPromiseMap.set(`audioinput`,u),u.catch(()=>Ex.userMediaPromiseMap.delete(`audioinput`))),a.video&&(Ex.userMediaPromiseMap.set(`videoinput`,u),u.catch(()=>Ex.userMediaPromiseMap.delete(`videoinput`)));try{let e=yield u;return yield Promise.all(e.getTracks().map(n=>L(this,void 0,void 0,function*(){let a=n.kind===`audio`,o=a?c.audio:c.video;(typeof o==`boolean`||!o)&&(o={});let s,u=a?l.audio:l.video;typeof u!=`boolean`&&(s=u);let d=n.getSettings().deviceId;s?.deviceId&&Rb(s.deviceId)!==d?s.deviceId=d:s||={deviceId:d};let f=GS(n,s,t);return f.kind===K.Kind.Video?f.source=K.Source.Camera:f.kind===K.Kind.Audio&&(f.source=K.Source.Microphone),f.mediaStream=e,qb(f)&&r?yield f.setProcessor(r):Jb(f)&&i&&(yield f.setProcessor(i)),f})))}catch(r){if(!n)throw r;return eT(Object.assign(Object.assign({},e),{audio:o,video:s}),t)}})}function tT(e){return L(this,void 0,void 0,function*(){return(yield eT({audio:e??!0,video:!1}))[0]})}var nT;(function(e){e.Excellent=`excellent`,e.Good=`good`,e.Poor=`poor`,e.Lost=`lost`,e.Unknown=`unknown`})(nT||={});function rT(e){switch(e){case hh.EXCELLENT:return nT.Excellent;case hh.GOOD:return nT.Good;case hh.POOR:return nT.Poor;case hh.LOST:return nT.Lost;default:return nT.Unknown}}var iT=class extends H_.EventEmitter{get logContext(){var e;return Object.assign({},((e=this.loggerOptions)?.loggerContextCb)?.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every(e=>e.isEncrypted)}get isAgent(){return this.permissions?.agent||this.kind===Eh.AGENT}get isActive(){return this.participantInfo?.state===Th.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,n,r,i,a){let o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:Eh.STANDARD;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=nT.Unknown,this.log=I,this.log=O_(a?.loggerName??D_.Participant),this.loggerOptions=a,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=n,this.metadata=r,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=o,this._attributes=i??{}}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.promise:(this.activeFuture=new Ib,this.once(V.Active,()=>{var e,t;(t=(e=this.activeFuture)?.resolve)==null||t.call(e),this.activeFuture=void 0}),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){return!(this.getTrackPublication(K.Source.Camera)?.isMuted??!0)}get isMicrophoneEnabled(){return!(this.getTrackPublication(K.Source.Microphone)?.isMuted??!0)}get isScreenShareEnabled(){return!!this.getTrackPublication(K.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(Number.parseInt(this.participantInfo.joinedAt.toString())*1e3):new Date}updateInfo(e){return this.participantInfo&&this.participantInfo.sid===e.sid&&this.participantInfo.version>e.version?!1:(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),this._setAttributes(e.attributes),e.state===Th.ACTIVE&&this.participantInfo?.state!==Th.ACTIVE&&this.emit(V.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){let t=this.metadata!==e,n=this.metadata;this.metadata=e,t&&this.emit(V.ParticipantMetadataChanged,n)}_setName(e){let t=this.name!==e;this.name=e,t&&this.emit(V.ParticipantNameChanged,e)}_setAttributes(e){let t=Uy(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(V.AttributesChanged,t)}setPermissions(e){let t=this.permissions,n=e.canPublish!==this.permissions?.canPublish||e.canSubscribe!==this.permissions?.canSubscribe||e.canPublishData!==this.permissions?.canPublishData||e.hidden!==this.permissions?.hidden||e.recorder!==this.permissions?.recorder||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((e,t)=>e!==this.permissions?.canPublishSources[t])||e.canSubscribeMetrics!==this.permissions?.canSubscribeMetrics;return this.permissions=e,n&&this.emit(V.ParticipantPermissionsChanged,t),n}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(V.IsSpeakingChanged,e))}setConnectionQuality(e){let t=this._connectionQuality;this._connectionQuality=rT(e),t!==this._connectionQuality&&this.emit(V.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,t;this.activeFuture&&=((t=(e=this.activeFuture).reject)==null||t.call(e,Error(`Participant disconnected`)),void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(t=>qb(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(U.Muted,()=>{this.emit(V.TrackMuted,e)}),e.on(U.Unmuted,()=>{this.emit(V.TrackUnmuted,e)});let t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case K.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case K.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}};function aT(e){if(!e.participantSid&&!e.participantIdentity)throw Error(`Invalid track permission, must provide at least one of participantIdentity and participantSid`);return new $g({participantIdentity:e.participantIdentity??``,participantSid:e.participantSid??``,allTracks:e.allowAll??!1,trackSids:e.allowedTrackSids||[]})}var oT=class extends iT{constructor(e,t,n,r,i,a,o){super(e,t,void 0,void 0,void 0,{loggerName:r.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=F.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||=new Ib},this.handleReconnected=()=>{var e,t;(t=(e=this.reconnectFuture)?.resolve)==null||t.call(e),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var e,t,n,r,i,a;this.reconnectFuture&&=(this.reconnectFuture.promise.catch(e=>this.log.warn(e.message,this.logContext)),(t=(e=this.reconnectFuture)?.reject)==null||t.call(e,Error(`Got disconnected during reconnection attempt`)),void 0),this.signalConnectedFuture&&=((r=(n=this.signalConnectedFuture).reject)==null||r.call(n,Error(`Got disconnected without signal connected`)),void 0),(a=(i=this.activeAgentFuture)?.reject)==null||a.call(i,Error(`Got disconnected without active agent present`)),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=e=>{var t,n;e.participant&&this.updateInfo(e.participant),this.signalConnectedFuture||=new Ib,(n=(t=this.signalConnectedFuture).resolve)==null||n.call(t)},this.handleSignalRequestResponse=e=>{let{requestId:t,reason:n,message:r}=e,i=this.pendingSignalRequests.get(t);switch(i&&(n!==p_.OK&&i.reject(new gy(r,n)),this.pendingSignalRequests.delete(t)),e.request.case){case`publishDataTrack`:{let t;switch(e.reason){case p_.NOT_ALLOWED:t=Pw.notAllowed(e.message);break;case p_.DUPLICATE_NAME:t=Pw.duplicateName(e.message);break;case p_.INVALID_NAME:t=Pw.invalidName(e.message);break;case p_.LIMIT_EXCEEDED:t=Pw.limitReached(e.message);break;default:t=Pw.unknown(e.reason,e.message);return}this.roomOutgoingDataTrackManager.receivedSfuPublishResponse(e.request.value.pubHandle,{type:`error`,error:t});break}}},this.handleDataPacket=e=>{switch(e.value.case){case`rpcResponse`:let t=e.value.value,n=null,r=null;t.value.case===`payload`?n=t.value.value:t.value.case===`error`&&(r=jS.fromProto(t.value.value)),this.handleIncomingRpcResponse(t.requestId,n,r);break;case`rpcAck`:let i=e.value.value;this.handleIncomingRpcAck(i.requestId);break}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug(`updating track subscription permissions`,Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(e=>aT(e)))},this.onTrackUnmuted=e=>{this.onTrackMuted(e,e.isUpstreamPaused)},this.onTrackMuted=(e,t)=>{if(t===void 0&&(t=!0),!e.sid){this.log.error(`could not update mute status for unpublished track`,Object.assign(Object.assign({},this.logContext),G(e)));return}this.engine.updateMuteStatus(e.sid,t)},this.onTrackUpstreamPaused=e=>{this.log.debug(`upstream paused`,Object.assign(Object.assign({},this.logContext),G(e))),this.onTrackMuted(e,!0)},this.onTrackUpstreamResumed=e=>{this.log.debug(`upstream resumed`,Object.assign(Object.assign({},this.logContext),G(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 ${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),G(t))),this.emit(V.LocalTrackCpuConstrained,e,t)},this.handleSubscribedQualityUpdate=e=>L(this,void 0,void 0,function*(){var t,n,r,i;if(!this.roomOptions?.dynacast)return;let a=this.videoTrackPublications.get(e.trackSid);if(!a){this.log.warn(`received subscribed quality update for unknown track`,Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}));return}if(!a.videoTrack)return;let o=yield a.videoTrack.setPublishingCodecs(e.subscribedCodecs);try{for(var s=!0,c=R_(o),l;l=yield c.next(),t=l.done,!t;s=!0){i=l.value,s=!1;let e=i;Ey(e)&&(this.log.debug(`publish ${e} for ${a.videoTrack.sid}`,Object.assign(Object.assign({},this.logContext),G(a))),yield this.publishAdditionalCodecForTrack(a.videoTrack,e,a.options))}}catch(e){n={error:e}}finally{try{!s&&!t&&(r=c.return)&&(yield r.call(c))}finally{if(n)throw n.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=>L(this,void 0,void 0,function*(){if(e.source===K.Source.ScreenShare||e.source===K.Source.ScreenShareAudio)this.log.debug(`unpublishing local track due to TrackEnded`,Object.assign(Object.assign({},this.logContext),G(e))),this.unpublishTrack(e);else if(e.isUserProvided)yield e.mute();else if(Xb(e)||Yb(e))try{if(vb())try{let t=yield navigator==null?void 0:navigator.permissions.query({name:e.source===K.Source.Camera?`camera`:`microphone`});if(t&&t.state===`denied`)throw this.log.warn(`user has revoked access to ${e.source}`,Object.assign(Object.assign({},this.logContext),G(e))),t.onchange=()=>{t.state!==`denied`&&(e.isMuted||e.restartTrack(),t.onchange=null)},Error(`GetUserMedia Permission denied`)}catch{}e.isMuted||(this.log.debug(`track ended, attempting to use a different device`,Object.assign(Object.assign({},this.logContext),G(e))),Xb(e)?yield e.restartTrack({deviceId:`default`}):yield e.restartTrack())}catch{this.log.warn(`could not restart track, muting instead`,Object.assign(Object.assign({},this.logContext),G(e))),yield e.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=n,this.roomOptions=r,this.setupEngine(n),this.activeDeviceMap=new Map([[`audioinput`,`default`],[`videoinput`,`default`],[`audiooutput`,`default`]]),this.pendingSignalRequests=new Map,this.rpcHandlers=i,this.roomOutgoingDataStreamManager=a,this.roomOutgoingDataTrackManager=o}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==F.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){this.engine=e,this.engine.on(H.RemoteMute,(e,t)=>{let n=this.trackPublications.get(e);!n||!n.track||(t?n.mute():n.unmute())}),this.signalConnectedFuture?.isResolved&&(this.signalConnectedFuture=void 0),this.engine.on(H.Connected,this.handleReconnected).on(H.SignalConnected,this.handleSignalConnected).on(H.SignalRestarted,this.handleReconnected).on(H.SignalResumed,this.handleReconnected).on(H.Restarting,this.handleReconnecting).on(H.Resuming,this.handleReconnecting).on(H.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(H.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(H.Closing,this.handleClosing).on(H.SignalRequestResponse,this.handleSignalRequestResponse).on(H.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return L(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return L(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return L(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return L(this,arguments,void 0,function(e){var t=this;let{metadata:n,name:r,attributes:i}=e;return function*(){return new ey((e,a)=>L(t,void 0,void 0,function*(){try{let t=!1,o=yield this.engine.client.sendUpdateLocalMetadata(n??this.metadata??``,r??this.name??``,i),s=performance.now();for(this.pendingSignalRequests.set(o,{resolve:e,reject:e=>{a(e),t=!0},values:{name:r,metadata:n,attributes:i}});performance.now()-s<5e3&&!t;){if((!r||this.name===r)&&(!n||this.metadata===n)&&(!i||Object.entries(i).every(e=>{let[t,n]=e;return this.attributes[t]===n||n===``&&!this.attributes[t]}))){this.pendingSignalRequests.delete(o),e();return}yield nb(50)}a(new gy(`Request to update local metadata timed out`,`TimeoutError`))}catch(e){e instanceof Error?a(e):a(Error(String(e)))}}))}()})}setCameraEnabled(e,t,n){return this.setTrackEnabled(K.Source.Camera,e,t,n)}setMicrophoneEnabled(e,t,n){return this.setTrackEnabled(K.Source.Microphone,e,t,n)}setScreenShareEnabled(e,t,n){return this.setTrackEnabled(K.Source.ScreenShare,e,t,n)}setE2EEEnabled(e){return L(this,void 0,void 0,function*(){this.encryptionType=e?F.GCM:F.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,n,r){return L(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 i=this.getTrackPublication(e);if(t)if(i)yield i.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 t?.unmute(),t}this.pendingPublishing.add(e);try{switch(e){case K.Source.Camera:t=yield this.createTracks({video:n??!0});break;case K.Source.Microphone:t=yield this.createTracks({audio:n??!0});break;case K.Source.ScreenShare:t=yield this.createScreenTracks(Object.assign({},n));break;default:throw new dy(e)}}catch(n){throw t?.forEach(e=>{e.stop()}),n instanceof Error&&this.emit(V.MediaDevicesError,n,Ry(e)),this.pendingPublishing.delete(e),n}for(let r of t){let t=Object.assign(Object.assign({},this.roomOptions.publishDefaults),n);e===K.Source.Microphone&&qb(r)&&t.preConnectBuffer&&(this.log.info(`starting preconnect buffer for microphone`,Object.assign({},this.logContext)),r.startPreConnectBuffer())}try{let e=[];for(let n of t)this.log.info(`publishing track`,Object.assign(Object.assign({},this.logContext),G(n))),e.push(this.publishTrack(n,r));let n=yield Promise.all(e);[i]=n}catch(e){throw t?.forEach(e=>{e.stop()}),e}finally{this.pendingPublishing.delete(e)}}else if(!i?.track&&this.pendingPublishing.has(e)&&(i=yield this.waitForPendingPublicationOfSource(e),i||this.log.info(`waiting for pending publication promise timed out`,Object.assign(Object.assign({},this.logContext),{source:e}))),i&&i.track)if(e===K.Source.ScreenShare){i=yield this.unpublishTrack(i.track);let e=this.getTrackPublication(K.Source.ScreenShareAudio);e&&e.track&&this.unpublishTrack(e.track)}else yield i.mute();return i})}enableCameraAndMicrophone(){return L(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(K.Source.Camera)||this.pendingPublishing.has(K.Source.Microphone))){this.pendingPublishing.add(K.Source.Camera),this.pendingPublishing.add(K.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(K.Source.Camera),this.pendingPublishing.delete(K.Source.Microphone)}}})}createTracks(e){return L(this,void 0,void 0,function*(){e??={};let t=My(e,this.roomOptions?.audioCaptureDefaults,this.roomOptions?.videoCaptureDefaults);try{return(yield eT(t,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(e=>(qb(e)&&(this.microphoneError=void 0,e.setAudioContext(this.audioContext),e.source=K.Source.Microphone,this.emit(V.AudioStreamAcquired)),Jb(e)&&(this.cameraError=void 0,e.source=K.Source.Camera),e))}catch(t){throw t instanceof Error&&(e.audio&&(this.microphoneError=t),e.video&&(this.cameraError=t)),t}})}createScreenTracks(e){return L(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new uy(`getDisplayMedia not supported`);e.resolution===void 0&&!mb()&&(e.resolution=jy.h1080fps30.resolution);let t=zy(e),n=yield navigator.mediaDevices.getDisplayMedia(t),r=n.getVideoTracks();if(r.length===0)throw new dy(`no video track found`);let i=new lC(r[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});i.source=K.Source.ScreenShare,e.contentHint&&(i.mediaStreamTrack.contentHint=e.contentHint);let a=[i];if(n.getAudioTracks().length>0){this.emit(V.AudioStreamAcquired);let e=new WS(n.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});e.source=K.Source.ScreenShareAudio,a.push(e)}return a})}publishTrack(e,t){return L(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}publishOrRepublishTrack(e,t){return L(this,arguments,void 0,function(e,t){var n=this;let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return function*(){Xb(e)&&e.setAudioContext(n.audioContext),yield n.reconnectFuture?.promise,n.republishPromise&&!r&&(yield n.republishPromise),Kb(e)&&n.pendingPublishPromises.has(e)&&(yield n.pendingPublishPromises.get(e));let i;if(e instanceof MediaStreamTrack)i=e.getConstraints();else{i=e.constraints;let t;switch(e.source){case K.Source.Microphone:t=`audioinput`;break;case K.Source.Camera:t=`videoinput`}t&&n.activeDeviceMap.has(t)&&(i=Object.assign(Object.assign({},i),{deviceId:n.activeDeviceMap.get(t)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case`audio`:e=new WS(e,i,!0,n.audioContext,{loggerName:n.roomOptions.loggerName,loggerContextCb:()=>n.logContext});break;case`video`:e=new lC(e,i,!0,{loggerName:n.roomOptions.loggerName,loggerContextCb:()=>n.logContext});break;default:throw new dy(`unsupported MediaStreamTrack kind ${e.kind}`)}else e.updateLoggerOptions({loggerName:n.roomOptions.loggerName,loggerContextCb:()=>n.logContext});let a;if(n.trackPublications.forEach(t=>{t.track&&t.track===e&&(a=t)}),a)return n.log.warn(`track has already been published, skipping`,Object.assign(Object.assign({},n.logContext),G(a))),a;let o=Object.assign(Object.assign({},n.roomOptions.publishDefaults),t),s=`channelCount`in e.mediaStreamTrack.getSettings()&&e.mediaStreamTrack.getSettings().channelCount===2||e.mediaStreamTrack.getConstraints().channelCount===2,c=o.forceStereo??s;c&&(o.dtx===void 0&&n.log.info(`Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.`,Object.assign(Object.assign({},n.logContext),G(e))),o.red===void 0&&n.log.info(`Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work.`),o.dtx??=!1,o.red??=!1),!_b()&&n.roomOptions.e2ee&&(n.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({},n.logContext)),o.simulcast=!1),o.source&&(e.source=o.source);let l=new Promise((t,r)=>L(n,void 0,void 0,function*(){try{if(this.engine.client.currentState!==q.CONNECTED){this.log.debug(`deferring track publication until signal is connected`,Object.assign(Object.assign({},this.logContext),{track:G(e)}));let n=!1,i=setTimeout(()=>{n=!0,e.stop(),r(new hy(`publishing rejected as engine not connected within timeout`,408))},15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(i),n)return;t(yield this.publish(e,o,c))}else try{t(yield this.publish(e,o,c))}catch(e){r(e)}}catch(e){r(e)}}));n.pendingPublishPromises.set(e,l);try{return yield l}catch(e){throw e}finally{n.pendingPublishPromises.delete(e)}}()})}waitUntilEngineConnected(){return this.signalConnectedFuture||=new Ib,this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn(`no permissions present for publishing track`,Object.assign(Object.assign({},this.logContext),G(e))),!1;let{canPublish:t,canPublishSources:n}=this.permissions;return t&&(n.length===0||n.map(e=>Gy(e)).includes(e.source))?!0:(this.log.warn(`insufficient permissions to publish`,Object.assign(Object.assign({},this.logContext),G(e))),!1)}publish(e,t,n){return L(this,void 0,void 0,function*(){if(!this.hasPermissionsToPublish(e))throw new hy(`failed to publish track, insufficient permissions`,403);Array.from(this.trackPublications.values()).find(t=>Kb(e)&&t.source===e.source)&&e.source!==K.Source.Unknown&&this.log.info(`publishing a second track with the same source: ${e.source}`,Object.assign(Object.assign({},this.logContext),G(e))),t.stopMicTrackOnMute&&qb(e)&&(e.stopOnMute=!0),e.source===K.Source.ScreenShare&&ub()&&(t.simulcast=!1),t.videoCodec===`av1`&&!ab()&&(t.videoCodec=void 0),t.videoCodec===`vp9`&&!ob()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=yS),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(e=>t.videoCodec===By(e.mime))||(t.videoCodec=By(this.enabledPublishVideoCodecs[0].mime)));let r=t.videoCodec;e.on(U.Muted,this.onTrackMuted),e.on(U.Unmuted,this.onTrackUnmuted),e.on(U.Ended,this.handleTrackEnded),e.on(U.UpstreamPaused,this.onTrackUpstreamPaused),e.on(U.UpstreamResumed,this.onTrackUpstreamResumed),e.on(U.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);let i=[],a=!(t.dtx??!0),o=e.getSourceTrackSettings();o.autoGainControl&&i.push(bh.TF_AUTO_GAIN_CONTROL),o.echoCancellation&&i.push(bh.TF_ECHO_CANCELLATION),o.noiseSuppression&&i.push(bh.TF_NOISE_SUPPRESSION),o.channelCount&&o.channelCount>1&&i.push(bh.TF_STEREO),a&&i.push(bh.TF_NO_DTX),Xb(e)&&e.hasPreConnectBuffer&&i.push(bh.TF_PRECONNECT_BUFFER);let s=new _g({cid:e.mediaStreamTrack.id,name:t.name,type:K.kindToProto(e.kind),muted:e.isMuted,source:K.sourceToProto(e.source),disableDtx:a,encryption:this.encryptionType,stereo:n,disableRed:this.isE2EEEnabled||!(t.red??!0),stream:t?.stream,backupCodecPolicy:t?.backupCodecPolicy,audioFeatures:i}),c;if(e.kind===K.Kind.Video){let n={width:0,height:0};try{n=yield e.waitForDimensions()}catch{let t=this.roomOptions.videoCaptureDefaults?.resolution??ky.h720.resolution;n={width:t.width,height:t.height},this.log.error(`could not determine track dimensions, using defaults`,Object.assign(Object.assign(Object.assign({},this.logContext),G(e)),{dims:n}))}s.width=n.width,s.height=n.height,Yb(e)&&(sb(r)&&(e.source===K.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),G(e))))),t.scalabilityMode=t.scalabilityMode??`L3T3_KEY`),s.simulcastCodecs=[new gg({codec:r,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:yS}),t.backupCodec&&r!==t.backupCodec.codec&&s.encryption===F.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),s.simulcastCodecs.push(new gg({codec:t.backupCodec.codec,cid:``})))),c=$S(e.source===K.Source.ScreenShare,s.width,s.height,t),s.layers=fC(s.width,s.height,c,sb(t.videoCodec))}else e.kind===K.Kind.Audio&&(c=[{maxBitrate:t.audioPreset?.maxBitrate,priority:t.audioPreset?.priority??`high`,networkPriority:t.audioPreset?.priority??`high`}]);if(!this.engine||this.engine.isClosed)throw new py(`cannot publish track when not connected`);let l=()=>L(this,void 0,void 0,function*(){if(!this.engine.pcManager)throw new py(`pcManager is not ready`);if(e.sender=yield this.engine.createSender(e,t,c),this.emit(V.LocalSenderCreated,e.sender,e),Yb(e)&&(t.degradationPreference??=sC(e),e.setDegradationPreference(t.degradationPreference)),c)if(ub()&&e.kind===K.Kind.Audio){let t;for(let n of this.engine.pcManager.publisher.getTransceivers())if(n.sender===e.sender){t=n;break}t&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:t,codec:`opus`,maxbr:c[0]?.maxBitrate?c[0].maxBitrate/1e3:0})}else e.codec&&sb(e.codec)&&c[0]?.maxBitrate&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:s.cid,codec:e.codec,maxbr:c[0].maxBitrate/1e3});yield this.engine.negotiate()}),u,d=new Promise((t,n)=>L(this,void 0,void 0,function*(){try{u=yield this.engine.addTrack(s),t(u)}catch(t){e.sender&&this.engine.pcManager?.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),G(e)),{error:t}))})),n(t)}}));if(this.enabledPublishVideoCodecs.length>0)u=(yield Promise.all([d,l()]))[0];else{u=yield d;let n;if(u.codecs.forEach(e=>{n===void 0&&(n=e.mimeType)}),n&&e.kind===K.Kind.Video){let i=By(n);i!==r&&(this.log.debug(`falling back to server selected codec`,Object.assign(Object.assign(Object.assign({},this.logContext),G(e)),{codec:i})),t.videoCodec=i,c=$S(e.source===K.Source.ScreenShare,s.width,s.height,t))}yield l()}let f=new $w(e.kind,u,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(f.on(U.CpuConstrained,e=>this.onTrackCpuConstrained(e,f)),f.options=t,e.sid=u.sid,this.log.debug(`publishing ${e.kind} with encodings`,Object.assign(Object.assign({},this.logContext),{encodings:c,trackInfo:u})),Yb(e)?e.startMonitor(this.engine.client):Xb(e)&&e.startMonitor(),this.addTrackPublication(f),this.emit(V.LocalTrackPublished,f),Xb(e)&&u.audioFeatures.includes(bh.TF_PRECONNECT_BUFFER)){let t=e.getPreConnectBuffer(),n=e.getPreConnectBufferMimeType();this.on(V.LocalTrackSubscribed,t=>{if(t.trackSid===u.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),G(e))),e.stopPreConnectBuffer()}}),t&&new Promise((r,i)=>L(this,void 0,void 0,function*(){var a,s,c,l;try{this.log.debug(`waiting for agent`,Object.assign(Object.assign({},this.logContext),G(e)));let m=setTimeout(()=>{i(Error(`agent not active within 10 seconds`))},1e4),h=yield this.waitUntilActiveAgentPresent();clearTimeout(m),this.log.debug(`sending preconnect buffer`,Object.assign(Object.assign({},this.logContext),G(e)));let g=yield this.streamBytes({name:`preconnect-buffer`,mimeType:n,topic:`lk.agent.pre-connect-audio-buffer`,destinationIdentities:[h.identity],attributes:{trackId:f.trackSid,sampleRate:String(o.sampleRate??`48000`),channels:String(o.channelCount??`1`)}});try{for(var u=!0,d=R_(t),p;p=yield d.next(),a=p.done,!a;u=!0){l=p.value,u=!1;let e=l;yield g.write(e)}}catch(e){s={error:e}}finally{try{!u&&!a&&(c=d.return)&&(yield c.call(d))}finally{if(s)throw s.error}}yield g.close(),r()}catch(e){i(e)}})).then(()=>{this.log.debug(`preconnect buffer sent successfully`,Object.assign(Object.assign({},this.logContext),G(e)))}).catch(t=>{this.log.error(`error sending preconnect buffer`,Object.assign(Object.assign(Object.assign({},this.logContext),G(e)),{error:t}))})}return f})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,n){return L(this,void 0,void 0,function*(){if(this.encryptionType!==F.NONE)return;let r;if(this.trackPublications.forEach(t=>{t.track&&t.track===e&&(r=t)}),!r)throw new dy(`track is not published`);if(!Yb(e))throw new dy(`track is not a video track`);let i=Object.assign(Object.assign({},this.roomOptions?.publishDefaults),n),a=eC(e,t,i);if(!a){this.log.info(`backup codec has been disabled, ignoring request to add additional codec for track`,Object.assign(Object.assign({},this.logContext),G(e)));return}let o=e.addSimulcastTrack(t,a);if(!o)return;let s=new _g({cid:o.mediaStreamTrack.id,type:K.kindToProto(e.kind),muted:e.isMuted,source:K.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:i.videoCodec,cid:o.mediaStreamTrack.id}]});if(s.layers=fC(s.width,s.height,a),!this.engine||this.engine.isClosed)throw new py(`cannot publish track when not connected`);let c=(yield Promise.all([this.engine.addTrack(s),L(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,o,i,a),yield this.engine.negotiate()})]))[0];this.log.debug(`published ${t} for track ${e.sid}`,Object.assign(Object.assign({},this.logContext),{encodings:a,trackInfo:c}))})}unpublishTrack(e,t){return L(this,void 0,void 0,function*(){if(Kb(e)){let t=this.pendingPublishPromises.get(e);t&&(this.log.info(`awaiting publish promise before attempting to unpublish`,Object.assign(Object.assign({},this.logContext),G(e))),yield t)}let n=this.getPublicationForTrack(e),r=n?G(n):void 0;if(this.log.debug(`unpublishing track`,Object.assign(Object.assign({},this.logContext),r)),!n||!n.track){this.log.warn(`track was not unpublished because no publication was found`,Object.assign(Object.assign({},this.logContext),r));return}e=n.track,e.off(U.Muted,this.onTrackMuted),e.off(U.Unmuted,this.onTrackUnmuted),e.off(U.Ended,this.handleTrackEnded),e.off(U.UpstreamPaused,this.onTrackUpstreamPaused),e.off(U.UpstreamResumed,this.onTrackUpstreamResumed),e.off(U.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),t===void 0&&(t=this.roomOptions?.stopLocalTrackOnUnpublish??!0),t?e.stop():e.stopMonitor();let i=!1,a=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<TS.FAILED&&a)try{for(let e of this.engine.pcManager.publisher.getTransceivers())e.sender===a&&(e.direction=`inactive`,i=!0);if(this.engine.removeTrack(a)&&(i=!0),Yb(e)){for(let[,t]of e.simulcastCodecs)t.sender&&=(this.engine.removeTrack(t.sender)&&(i=!0),void 0);e.simulcastCodecs.clear()}}catch(e){this.log.warn(`failed to unpublish track`,Object.assign(Object.assign(Object.assign({},this.logContext),r),{error:e}))}switch(this.trackPublications.delete(n.trackSid),n.kind){case K.Kind.Audio:this.audioTrackPublications.delete(n.trackSid);break;case K.Kind.Video:this.videoTrackPublications.delete(n.trackSid);break}return this.emit(V.LocalTrackUnpublished,n),n.setTrack(void 0),i&&(yield this.engine.negotiate()),n})}unpublishTracks(e){return L(this,void 0,void 0,function*(){return(yield Promise.all(e.map(e=>this.unpublishTrack(e)))).filter(e=>!!e)})}republishAllTracks(e){return L(this,arguments,void 0,function(e){var t=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){t.republishPromise&&(yield t.republishPromise),t.republishPromise=new ey((r,i)=>L(t,void 0,void 0,function*(){try{let t=[];this.trackPublications.forEach(n=>{n.track&&(e&&(n.options=Object.assign(Object.assign({},n.options),e)),t.push(n))}),yield Promise.all(t.map(e=>L(this,void 0,void 0,function*(){let t=e.track;yield this.unpublishTrack(t,!1),n&&!t.isMuted&&t.source!==K.Source.ScreenShare&&t.source!==K.Source.ScreenShareAudio&&(Xb(t)||Yb(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)}))),r()}catch(e){e instanceof Error?i(e):i(Error(String(e)))}finally{this.republishPromise=void 0}})),yield t.republishPromise}()})}publishData(e){return L(this,arguments,void 0,function(e){var t=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return function*(){let r=n.reliable?J.RELIABLE:J.LOSSY,i=n.reliable?Fh.RELIABLE:Fh.LOSSY,a=n.destinationIdentities,o=n.topic,s=new Ph({kind:i,value:{case:`user`,value:new Bh({participantIdentity:t.identity,payload:e,destinationIdentities:a,topic:o})}});yield t.engine.sendDataPacket(s,r)}()})}publishDtmf(e,t){return L(this,void 0,void 0,function*(){let n=new Ph({kind:Fh.RELIABLE,value:{case:`sipDtmf`,value:new Vh({code:e,digit:t})}});yield this.engine.sendDataPacket(n,J.RELIABLE)})}sendChatMessage(e,t){return L(this,void 0,void 0,function*(){let n={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:t?.attachments},r=new Ph({value:{case:`chatMessage`,value:new Wh(Object.assign(Object.assign({},n),{timestamp:Hp.parse(n.timestamp)}))}});return yield this.engine.sendDataPacket(r,J.RELIABLE),this.emit(V.ChatMessage,n),n})}editChatMessage(e,t){return L(this,void 0,void 0,function*(){let n=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),r=new Ph({value:{case:`chatMessage`,value:new Wh(Object.assign(Object.assign({},n),{timestamp:Hp.parse(n.timestamp),editTimestamp:Hp.parse(n.editTimestamp)}))}});return yield this.engine.sendDataPacket(r,J.RELIABLE),this.emit(V.ChatMessage,n),n})}sendText(e,t){return L(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)})}streamText(e){return L(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,t){return L(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)})}streamBytes(e){return L(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)})}performRpc(e){let{destinationIdentity:t,method:n,payload:r,responseTimeout:i=15e3}=e,a=7e3;return a+1e3,new ey((e,o)=>L(this,void 0,void 0,function*(){if(NS(r)>MS){o(jS.builtIn(`REQUEST_PAYLOAD_TOO_LARGE`));return}if(this.engine.latestJoinResponse?.serverInfo?.version&&Tb(this.engine.latestJoinResponse?.serverInfo?.version,`1.8.0`)<0){o(jS.builtIn(`UNSUPPORTED_SERVER`));return}let s=Math.max(i,8e3),c=crypto.randomUUID();yield this.publishRpcRequest(t,c,n,r,s);let l=setTimeout(()=>{this.pendingAcks.delete(c),o(jS.builtIn(`CONNECTION_TIMEOUT`)),this.pendingResponses.delete(c),clearTimeout(u)},a);this.pendingAcks.set(c,{resolve:()=>{clearTimeout(l)},participantIdentity:t});let u=setTimeout(()=>{this.pendingResponses.delete(c),o(jS.builtIn(`RESPONSE_TIMEOUT`))},i);this.pendingResponses.set(c,{resolve:(t,n)=>{clearTimeout(u),this.pendingAcks.has(c)&&(this.log.warn(`RPC response received before ack`,c),this.pendingAcks.delete(c),clearTimeout(l)),n?o(n):e(t??``)},participantIdentity:t})}))}registerRpcMethod(e,t){this.rpcHandlers.has(e)&&this.log.warn(`you're overriding the RPC handler for method ${e}, in the future this will throw an error`),this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){this.participantTrackPermissions=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[],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,n){let r=this.pendingResponses.get(e);r?(r.resolve(t,n),this.pendingResponses.delete(e)):console.error(`Response received for unexpected RPC request`,e)}publishRpcRequest(e,t,n,r,i){return L(this,void 0,void 0,function*(){let a=new Ph({destinationIdentities:[e],kind:Fh.RELIABLE,value:{case:`rpcRequest`,value:new Gh({id:t,method:n,payload:r,responseTimeoutMs:i,version:1})}});yield this.engine.sendDataPacket(a,J.RELIABLE)})}handleParticipantDisconnected(e){for(let[t,{participantIdentity:n}]of this.pendingAcks)n===e&&this.pendingAcks.delete(t);for(let[t,{participantIdentity:n,resolve:r}]of this.pendingResponses)n===e&&(r(null,jS.builtIn(`RECIPIENT_DISCONNECTED`)),this.pendingResponses.delete(t))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(e=>e.mime.split(`/`)[0].toLowerCase()===`video`)}updateInfo(e){return super.updateInfo(e)?(e.tracks.forEach(e=>{let t=this.trackPublications.get(e.sid);if(t){let n=t.isMuted||(t.track?.isUpstreamPaused??!1);n!==e.muted&&(this.log.debug(`updating server mute state after reconcile`,Object.assign(Object.assign(Object.assign({},this.logContext),G(t)),{mutedOnServer:n})),this.engine.client.sendMuteTrack(e.sid,n))}}),!0):!1}setActiveAgent(e){var t,n,r,i;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?(n=(t=this.activeAgentFuture)?.resolve)==null||n.call(t,e):(i=(r=this.activeAgentFuture)?.reject)==null||i.call(r,Error(`Agent disconnected`)),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||=new Ib,this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(n=>{let r=n.track;r&&(e instanceof MediaStreamTrack?(Xb(r)||Yb(r))&&r.mediaStreamTrack===e&&(t=n):e===r&&(t=n))}),t}waitForPendingPublicationOfSource(e){return L(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[n]=t;return n.source===e});if(t)return t[1];yield nb(20)}})}publishDataTrack(e){return L(this,void 0,void 0,function*(){let t=new zw(e,this.roomOutgoingDataTrackManager);return yield t.publish(),t})}},sT=class extends DOMException{constructor(e,t){super(e,`AbortError`),this.reason=t}},cT=class extends Map{constructor(){super(...arguments),this.pending=new Map}set(e,t){var n;super.set(e,t);let r=this.pending.get(e);if(r){for(let e of r)e.isResolved||(n=e.resolve)==null||n.call(e,t);this.pending.delete(e)}return this}get[Symbol.toStringTag](){return`WaitableMap`}getDeferred(e,t){return L(this,void 0,void 0,function*(){let n=this.get(e);if(n!==void 0)return n;if(t?.aborted)throw new sT(`The operation was aborted.`,t.reason);let r=new Ib(void 0,()=>{let t=this.pending.get(e);if(!t)return;let n=t.indexOf(r);n!==-1&&t.splice(n,1),t.length===0&&this.pending.delete(e)}),i=this.pending.get(e);if(i?i.push(r):this.pending.set(e,[r]),t){let e=()=>{var e;r.isResolved||(e=r.reject)==null||e.call(r,new sT(`The operation was aborted.`,t.reason))};t.addEventListener(`abort`,e,{once:!0}),r.promise.finally(()=>{t.removeEventListener(`abort`,e)})}return r.promise})}},lT=class extends Qw{constructor(e,t,n,r){super(e,t.sid,t.name,r),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=e=>{this.setTrack(void 0),this.emit(U.Ended,e)},this.handleVisibilityChange=e=>{this.log.debug(`adaptivestream video visibility ${this.trackSid}, visible=${e}`,this.logContext),this.visible=e,this.emitTrackUpdate()},this.handleVideoDimensionsChange=e=>{this.log.debug(`adaptivestream video dimensions ${e.width}x${e.height}`,this.logContext),this.videoDimensionsAdaptiveStream=e,this.emitTrackUpdate()},this.subscribed=n,this.updateInfo(t)}setSubscribed(e){let t=this.subscriptionStatus,n=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);let r=new Mg({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new Yh({participantSid:``,trackSids:[this.trackSid]})]});this.emit(U.UpdateSubscription,r),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(n)}get subscriptionStatus(){return this.subscribed===!1?Qw.SubscriptionStatus.Unsubscribed:super.isSubscribed?Qw.SubscriptionStatus.Subscribed:Qw.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?Qw.PermissionStatus.Allowed:Qw.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed===!1?!1:super.isSubscribed}get isDesired(){return this.subscribed!==!1}get isEnabled(){return this.requestedDisabled===void 0?this.isAdaptiveStream?this.visible:!0:!this.requestedDisabled}get isLocal(){return!1}setEnabled(e){!this.isManualOperationAllowed()||this.requestedDisabled===!e||(this.requestedDisabled=!e,this.emitTrackUpdate())}setVideoQuality(e){!this.isManualOperationAllowed()||this.requestedMaxQuality===e||(this.requestedMaxQuality=e,this.requestedVideoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){this.isManualOperationAllowed()&&(this.requestedVideoDimensions?.width===e.width&&this.requestedVideoDimensions?.height===e.height||($b(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&$b(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){return this.requestedMaxQuality??Xy.HIGH}setTrack(e){let t=this.subscriptionStatus,n=this.permissionStatus,r=this.track;r!==e&&(r&&(r.off(U.VideoDimensionsChanged,this.handleVideoDimensionsChange),r.off(U.VisibilityChanged,this.handleVisibilityChange),r.off(U.Ended,this.handleEnded),r.detach(),r.stopMonitor(),this.emit(U.Unsubscribed,r)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(U.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(U.VisibilityChanged,this.handleVisibilityChange),e.on(U.Ended,this.handleEnded),this.emit(U.Subscribed,e)),this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){let t=this.subscriptionStatus,n=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(U.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?U.Muted:U.Unmuted)}emitSubscriptionUpdateIfChanged(e){let t=this.subscriptionStatus;e!==t&&this.emit(U.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(U.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.isDesired?!0:(this.log.warn(`cannot update track settings when not subscribed`,this.logContext),!1)}get isAdaptiveStream(){return $b(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){let e=new Fg({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===K.Kind.Video){let t=this.requestedVideoDimensions;if(this.videoDimensionsAdaptiveStream!==void 0)if(t)Ky(this.videoDimensionsAdaptiveStream,t)&&(this.log.debug(`using adaptive stream dimensions instead of requested`,Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream);else if(this.requestedMaxQuality!==void 0&&this.trackInfo){let e=qy(this.trackInfo,this.requestedMaxQuality);e&&Ky(this.videoDimensionsAdaptiveStream,e)&&(this.log.debug(`using adaptive stream dimensions instead of max quality layer`,Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream)}else this.log.debug(`using adaptive stream dimensions`,Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream;t?(e.width=Math.ceil(t.width),e.height=Math.ceil(t.height)):this.requestedMaxQuality===void 0?(this.log.debug(`using default quality`,Object.assign(Object.assign({},this.logContext),{quality:Xy.HIGH})),e.quality=Xy.HIGH):(this.log.debug(`using requested max quality`,Object.assign(Object.assign({},this.logContext),{quality:this.requestedMaxQuality})),e.quality=this.requestedMaxQuality)}this.emit(U.UpdateSettings,e)}},uT=class e extends iT{static fromParticipantInfo(t,n,r){return new e(t,n.sid,n.identity,n.name,n.metadata,n.attributes,r,n.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{remoteParticipantID:this.sid,remoteParticipant:this.identity})}constructor(e,t,n,r,i,a,o){let s=arguments.length>7&&arguments[7]!==void 0?arguments[7]:Eh.STANDARD;super(t,n||``,r,i,a,o,s),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.dataTracks=new cT,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(U.UpdateSettings,t=>{this.log.debug(`send update settings`,Object.assign(Object.assign(Object.assign({},this.logContext),G(e)),{settings:t})),this.signalClient.sendUpdateTrackSettings(t)}),e.on(U.UpdateSubscription,e=>{e.participantTracks.forEach(e=>{e.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(e)}),e.on(U.SubscriptionPermissionChanged,t=>{this.emit(V.TrackSubscriptionPermissionChanged,e,t)}),e.on(U.SubscriptionStatusChanged,t=>{this.emit(V.TrackSubscriptionStatusChanged,e,t)}),e.on(U.Subscribed,t=>{this.emit(V.TrackSubscribed,t,e)}),e.on(U.Unsubscribed,t=>{this.emit(V.TrackUnsubscribed,t,e)}),e.on(U.SubscriptionFailed,t=>{this.emit(V.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&&arguments[1]!==void 0?arguments[1]:K.Source.Microphone;this.volumeMap.set(t,e);let n=this.getTrackPublication(t);n&&n.track&&n.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:K.Source.Microphone,t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,n,r,i,a){let o=this.getTrackPublicationBySid(t);if(o||t.startsWith(`TR`)||this.trackPublications.forEach(t=>{!o&&e.kind===t.kind.toString()&&(o=t)}),!o){if(a===0){this.log.error(`could not find published track`,Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(V.TrackSubscriptionFailed,t);return}a===void 0&&(a=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,n,r,i,a-1)},150);return}if(e.readyState===`ended`){this.log.error(`unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()`,Object.assign(Object.assign({},this.logContext),G(o))),this.emit(V.TrackSubscriptionFailed,t);return}let s=e.kind===`video`,c;return c=s?new Jw(e,t,r,i):new Kw(e,t,r,this.audioContext,this.audioOutput),c.source=o.source,c.isMuted=o.isMuted,c.setMediaStream(n),c.start(),o.setTrack(c),this.volumeMap.has(o.source)&&Zb(c)&&qb(c)&&c.setVolume(this.volumeMap.get(o.source)),o}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;let t=new Map,n=new Map;return e.tracks.forEach(e=>{let r=this.getTrackPublicationBySid(e.sid);if(r)r.updateInfo(e);else{let t=K.kindFromProto(e.type);if(!t)return;r=new lT(t,e,this.signalClient.connectOptions?.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:this.loggerOptions?.loggerName}),r.updateInfo(e),n.set(e.sid,r);let i=Array.from(this.trackPublications.values()).find(e=>e.source===r?.source);i&&r.source!==K.Source.Unknown&&this.log.debug(`received a second track publication for ${this.identity} with the same source: ${r.source}`,Object.assign(Object.assign({},this.logContext),{oldTrack:G(i),newTrack:G(r)})),this.addTrackPublication(r)}t.set(e.sid,r)}),this.trackPublications.forEach(e=>{t.has(e.trackSid)||(this.log.trace(`detected removed track on remote participant, unpublishing`,Object.assign(Object.assign({},this.logContext),G(e))),this.unpublishTrack(e.trackSid,!0))}),n.forEach(e=>{this.emit(V.TrackPublished,e)}),!0}unpublishTrack(e,t){let n=this.trackPublications.get(e);if(!n)return;let{track:r}=n;switch(r&&(r.stop(),n.setTrack(void 0)),this.trackPublications.delete(e),n.kind){case K.Kind.Audio:this.audioTrackPublications.delete(e);break;case K.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(V.TrackUnpublished,n)}setAudioOutput(e){return L(this,void 0,void 0,function*(){this.audioOutput=e;let t=[];this.audioTrackPublications.forEach(n=>{qb(n.track)&&Zb(n.track)&&t.push(n.track.setSinkId(e.deviceId??`default`))}),yield Promise.all(t)})}addRemoteDataTrack(e){this.dataTracks.set(e.info.name,e)}removeRemoteDataTrack(e){for(let[t,n]of this.dataTracks.entries())e===n.info.sid&&this.dataTracks.delete(t)}emit(e){var t=[...arguments].slice(1);return this.log.trace(`participant event`,Object.assign(Object.assign({},this.logContext),{event:e,args:t})),super.emit(e,...t)}},Y;(function(e){e.Disconnected=`disconnected`,e.Connecting=`connecting`,e.Connected=`connected`,e.Reconnecting=`reconnecting`,e.SignalReconnecting=`signalReconnecting`})(Y||={});var dT=4*1e3,fT=class e extends H_.EventEmitter{get hasE2EESetup(){return this.e2eeManager!==void 0}constructor(t){var n,r,i;if(super(),n=this,this.state=Y.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=I,this.bufferedEvents=[],this.isResuming=!1,this.rpcHandlers=new Map,this.connect=(e,t,n)=>L(this,void 0,void 0,function*(){if(!lb())throw yb()?Error(`WebRTC isn't detected, have you called registerGlobals?`):Error(`LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.`);let r=yield this.disconnectLock.lock();if(this.state===Y.Connected)return this.log.info(`already connected to room ${this.name}`,this.logContext),r(),Promise.resolve();if(this.connectFuture)return r(),this.connectFuture.promise;this.setAndEmitConnectionState(Y.Connecting),this.regionUrlProvider?.getServerUrl().toString()!==sx(e)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),bb(new URL(e))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new kS(e,t):this.regionUrlProvider.updateToken(t),this.regionUrlProvider.fetchRegionSettings().then(e=>{var t;(t=this.regionUrlProvider)==null||t.setServerReportedRegions(e)}).catch(e=>{this.log.warn(`could not fetch region settings`,Object.assign(Object.assign({},this.logContext),{error:e}))}));let i=(a,o,s)=>L(this,void 0,void 0,function*(){this.abortController&&this.abortController.abort();let c=new AbortController;this.abortController=c,r?.();try{if(yield wx.getInstance().getBackOffPromise(e),c.signal.aborted)throw z.cancelled(`Connection attempt aborted`);yield this.attemptConnection(s??e,t,n,c),this.abortController=void 0,a()}catch(t){if(this.regionUrlProvider&&t instanceof z&&t.reason!==R.Cancelled&&t.reason!==R.NotAllowed){let n=null;try{this.log.debug(`Fetching next region`),n=yield this.regionUrlProvider.getNextBestRegionUrl(this.abortController?.signal)}catch(e){if(e instanceof z&&(e.status===401||e.reason===R.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),o(e);return}}[R.InternalError,R.ServerUnreachable,R.Timeout].includes(t.reason)&&(this.log.debug(`Adding failed connection attempt to back off`),wx.getInstance().addFailedConnectionAttempt(e)),n&&!this.abortController?.signal.aborted?(this.log.info(`Initial connection failed with ConnectionError: ${t.message}. Retrying with another region: ${n}`,this.logContext),this.recreateEngine(!0),yield i(a,o,n)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Ub(t)),o(t))}else{let e=_h.UNKNOWN_REASON;t instanceof z&&(e=Ub(t)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e),o(t)}}}),a=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Ib((e,t)=>{i(e,t,a)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(e,t,n,r,i,a)=>L(this,void 0,void 0,function*(){let o=yield n.join(e,t,{autoSubscribe:r.autoSubscribe,adaptiveStream:typeof i.adaptiveStream==`object`?!0:i.adaptiveStream,maxRetries:r.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:r.websocketTimeout},a.signal,!i.singlePeerConnection),s=o.serverInfo;if(s||={version:o.serverVersion,region:o.serverRegion},this.serverInfo=s,this.log.debug(`connected to Livekit Server ${Object.entries(s).map(e=>{let[t,n]=e;return`${t}: ${n}`}).join(`, `)}`,{room:o.room?.name,roomSid:o.room?.sid,identity:o.participant?.identity}),!s.version)throw new fy(`unknown server version`);return s.version===`0.15.1`&&this.options.dynacast&&(this.log.debug(`disabling dynacast due to server version`,this.logContext),i.dynacast=!1),o}),this.applyJoinResponse=e=>{let t=e.participant;if(this.localParticipant.sid=t.sid,this.localParticipant.identity=t.identity,this.localParticipant.setEnabledPublishCodecs(e.enabledPublishCodecs),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,n,r)=>L(this,void 0,void 0,function*(){this.state===Y.Reconnecting||this.isResuming||this.engine?.pendingReconnect?(this.log.info(`Reconnection attempt replaced by new connection attempt`,this.logContext),this.recreateEngine(!0)):this.maybeCreateEngine(),this.regionUrlProvider?.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},wS),n),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{let n=yield this.connectSignal(e,t,this.engine,this.connOptions,this.options,r);this.applyJoinResponse(n),this.setupLocalParticipantEvents(),this.emit(B.SignalConnected)}catch(e){yield this.engine.close(),this.recreateEngine();let t=r.signal.aborted?z.cancelled(`Signal connection aborted`):z.serverUnreachable(`could not establish signal connection`);throw e instanceof Error&&(t.message=`${t.message}: ${e.message}`),e instanceof z&&(t.reason=e.reason,t.status=e.status),this.log.debug(`error trying to establish signal connection`,Object.assign(Object.assign({},this.logContext),{error:e})),t}if(r.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),z.cancelled(`Connection attempt aborted`);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,r)}catch(e){throw yield this.engine.close(),this.recreateEngine(),e}vb()&&this.options.disconnectOnPageLeave&&(window.addEventListener(`pagehide`,this.onPageLeave),window.addEventListener(`beforeunload`,this.onPageLeave)),vb()&&window.addEventListener(`freeze`,this.onPageLeave),this.setAndEmitConnectionState(Y.Connected),this.emit(B.Connected),wx.getInstance().resetFailedConnectionAttempts(e),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()}),this.disconnect=function(){return L(n,[...[...arguments]],void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var n,r,i;let a=yield e.disconnectLock.lock();try{if(e.state===Y.Disconnected){e.log.debug(`already disconnected`,e.logContext);return}if(e.log.info(`disconnect from room`,Object.assign({},e.logContext)),e.state===Y.Connecting||e.state===Y.Reconnecting||e.isResuming){let t=`Abort connection attempt due to user initiated disconnect`;e.log.warn(t,e.logContext),(n=e.abortController)==null||n.abort(t),(i=(r=e.connectFuture)?.reject)==null||i.call(r,z.cancelled(`Client initiated disconnect`)),e.connectFuture=void 0}e.engine&&(e.engine.client.isDisconnected||(yield e.engine.client.sendLeave()),yield e.engine.close()),e.handleDisconnect(t,_h.CLIENT_INITIATED),e.engine=void 0}finally{a()}}()})},this.onPageLeave=()=>L(this,void 0,void 0,function*(){this.log.info(`Page leave detected, disconnecting`,this.logContext),yield this.disconnect()}),this.startAudio=()=>L(this,void 0,void 0,function*(){let e=[],t=ry();if(t&&t.os===`iOS`){let t=`livekit-dummy-audio-el`,n=document.getElementById(t);if(!n){n=document.createElement(`audio`),n.id=t,n.autoplay=!0,n.hidden=!0;let e=Fb();e.enabled=!0;let r=new MediaStream([e]);n.srcObject=r,document.addEventListener(`visibilitychange`,()=>{n&&(n.srcObject=document.hidden?null:r,document.hidden||(this.log.debug(`page visible again, triggering startAudio to resume playback and update playback status`,this.logContext),this.startAudio()))}),document.body.append(n),this.once(B.Disconnected,()=>{n?.remove(),n=null})}e.push(n)}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=()=>L(this,void 0,void 0,function*(){let e=[];for(let t of this.remoteParticipants.values())t.videoTrackPublications.forEach(t=>{var n;(n=t.track)==null||n.attachedElements.forEach(t=>{e.includes(t)||e.push(t)})});yield Promise.all(e.map(e=>e.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(e=>{e.name===`NotAllowedError`?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)})}),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(let e of this.remoteParticipants.values())this.handleParticipantDisconnected(e.identity,e);this.setAndEmitConnectionState(Y.Reconnecting)&&this.emit(B.Reconnecting)},this.handleRestarted=()=>{this.outgoingDataTrackManager.sfuWillRepublishTracks(),this.incomingDataTrackManager.resendSubscriptionUpdates()},this.handleSignalRestarted=e=>L(this,void 0,void 0,function*(){this.log.debug(`signal reconnected to server, region ${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{return}this.setAndEmitConnectionState(Y.Connected),this.emit(B.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=e=>{for(let t of e){if(t.identity===this.localParticipant.identity){this.localParticipant.updateInfo(t);continue}t.identity===``&&(t.identity=this.sidToIdentity.get(t.sid)??``);let e=this.remoteParticipants.get(t.identity);t.state===Th.DISCONNECTED?this.handleParticipantDisconnected(t.identity,e):e=this.getOrCreateParticipant(t.identity,t)}let t=new Map(e.filter(e=>e.identity!==this.localParticipant.identity).map(e=>[e.identity,e.dataTracks.map(e=>Lx.from(e))]));this.incomingDataTrackManager.receiveSfuPublicationUpdates(t)},this.handleActiveSpeakersUpdate=e=>{let t=[],n={};e.forEach(e=>{if(n[e.sid]=!0,e.sid===this.localParticipant.sid)this.localParticipant.audioLevel=e.level,this.localParticipant.setIsSpeaking(!0),t.push(this.localParticipant);else{let n=this.getRemoteParticipantBySid(e.sid);n&&(n.audioLevel=e.level,n.setIsSpeaking(!0),t.push(n))}}),n[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(e=>{n[e.sid]||(e.audioLevel=0,e.setIsSpeaking(!1))}),this.activeSpeakers=t,this.emitWhenConnected(B.ActiveSpeakersChanged,t)},this.handleSpeakersChanged=e=>{let t=new Map;this.activeSpeakers.forEach(e=>{let n=this.remoteParticipants.get(e.identity);n&&n.sid!==e.sid||t.set(e.sid,e)}),e.forEach(e=>{let n=this.getRemoteParticipantBySid(e.sid);e.sid===this.localParticipant.sid&&(n=this.localParticipant),n&&(n.audioLevel=e.level,n.setIsSpeaking(e.active),e.active?t.set(e.sid,n):t.delete(e.sid))});let n=Array.from(t.values());n.sort((e,t)=>t.audioLevel-e.audioLevel),this.activeSpeakers=n,this.emitWhenConnected(B.ActiveSpeakersChanged,n)},this.handleStreamStateUpdate=e=>{e.streamStates.forEach(e=>{let t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;let n=t.getTrackPublicationBySid(e.trackSid);if(!n||!n.track)return;let r=K.streamStateFromProto(e.state);n.track.setStreamState(r),r!==n.track.streamState&&(t.emit(V.TrackStreamStateChanged,n,n.track.streamState),this.emitWhenConnected(B.TrackStreamStateChanged,n,n.track.streamState,t))})},this.handleSubscriptionPermissionUpdate=e=>{let t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;let n=t.getTrackPublicationBySid(e.trackSid);n&&n.setAllowed(e.allowed)},this.handleSubscriptionError=e=>{let t=Array.from(this.remoteParticipants.values()).find(t=>t.trackPublications.has(e.trackSid));if(!t)return;let n=t.getTrackPublicationBySid(e.trackSid);n&&n.setSubscriptionError(e.err)},this.handleDataPacket=(e,t)=>{let n=this.remoteParticipants.get(e.participantIdentity);if(e.value.case===`user`)this.handleUserPacket(n,e.value.value,e.kind,t);else if(e.value.case===`transcription`)this.handleTranscription(n,e.value.value);else if(e.value.case===`sipDtmf`)this.handleSipDtmf(n,e.value.value);else if(e.value.case===`chatMessage`)this.handleChatMessage(n,e.value.value);else if(e.value.case===`metrics`)this.handleMetrics(e.value.value,n);else if(e.value.case===`streamHeader`||e.value.case===`streamChunk`||e.value.case===`streamTrailer`)this.handleDataStream(e,t);else if(e.value.case===`rpcRequest`){let t=e.value.value;this.handleIncomingRpcRequest(e.participantIdentity,t.id,t.method,t.payload,t.responseTimeoutMs,t.version)}},this.handleUserPacket=(e,t,n,r)=>{this.emit(B.DataReceived,t.payload,e,n,t.topic,r),e?.emit(V.DataReceived,t.payload,n,r)},this.handleSipDtmf=(e,t)=>{this.emit(B.SipDTMFReceived,t,e),e?.emit(V.SipDTMFReceived,t)},this.handleTranscription=(e,t)=>{let n=t.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(t.transcribedParticipantIdentity),r=n?.trackPublications.get(t.trackId),i=Vb(t,this.transcriptionReceivedTimes);r?.emit(U.TranscriptionReceived,i),n?.emit(V.TranscriptionReceived,i,r),this.emit(B.TranscriptionReceived,i,n,r)},this.handleChatMessage=(e,t)=>{let n=Hb(t);this.emit(B.ChatMessage,n,e)},this.handleMetrics=(e,t)=>{this.emit(B.MetricsReceived,e,t)},this.handleDataStream=(e,t)=>{this.incomingDataStreamManager.handleDataStreamPacket(e,t)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(B.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(B.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(B.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(B.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>L(this,void 0,void 0,function*(){ry()?.os!==`iOS`&&(yield this.selectDefaultDevices()),this.emit(B.MediaDevicesChanged)}),this.handleRoomUpdate=e=>{let t=this.roomInfo;this.roomInfo=e,t&&t.metadata!==e.metadata&&this.emitWhenConnected(B.RoomMetadataChanged,e.metadata),t?.activeRecording!==e.activeRecording&&this.emitWhenConnected(B.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(B.ParticipantMetadataChanged,e,this.localParticipant)},this.onLocalParticipantNameChanged=e=>{this.emit(B.ParticipantNameChanged,e,this.localParticipant)},this.onLocalAttributesChanged=e=>{this.emit(B.ParticipantAttributesChanged,e,this.localParticipant)},this.onLocalTrackMuted=e=>{this.emit(B.TrackMuted,e,this.localParticipant)},this.onLocalTrackUnmuted=e=>{this.emit(B.TrackUnmuted,e,this.localParticipant)},this.onTrackProcessorUpdate=e=>{var t;(t=e?.onPublish)==null||t.call(e,this)},this.onLocalTrackPublished=e=>L(this,void 0,void 0,function*(){var t,n,r,i;(t=e.track)==null||t.on(U.TrackProcessorUpdate,this.onTrackProcessorUpdate),(n=e.track)==null||n.on(U.Restarted,this.onLocalTrackRestarted),(i=(r=e.track?.getProcessor())?.onPublish)==null||i.call(r,this),this.emit(B.LocalTrackPublished,e,this.localParticipant),Xb(e.track)&&(yield e.track.checkForSilence())&&this.emit(B.LocalAudioSilenceDetected,e);let a=yield e.track?.getDeviceId(!1),o=Ry(e.source);o&&a&&a!==this.localParticipant.activeDeviceMap.get(o)&&(this.localParticipant.activeDeviceMap.set(o,a),this.emit(B.ActiveDeviceChanged,o,a))}),this.onLocalTrackUnpublished=e=>{var t,n;(t=e.track)==null||t.off(U.TrackProcessorUpdate,this.onTrackProcessorUpdate),(n=e.track)==null||n.off(U.Restarted,this.onLocalTrackRestarted),this.emit(B.LocalTrackUnpublished,e,this.localParticipant)},this.onLocalTrackRestarted=e=>L(this,void 0,void 0,function*(){let t=yield e.getDeviceId(!1),n=Ry(e.source);n&&t&&t!==this.localParticipant.activeDeviceMap.get(n)&&(this.log.debug(`local track restarted, setting ${n} ${t} active`,this.logContext),this.localParticipant.activeDeviceMap.set(n,t),this.emit(B.ActiveDeviceChanged,n,t))}),this.onLocalConnectionQualityChanged=e=>{this.emit(B.ConnectionQualityChanged,e,this.localParticipant)},this.onMediaDevicesError=(e,t)=>{this.emit(B.MediaDevicesError,e,t)},this.onLocalParticipantPermissionsChanged=e=>{this.emit(B.ParticipantPermissionsChanged,e,this.localParticipant)},this.onLocalChatMessageSent=e=>{this.emit(B.ChatMessage,e,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},CS),t),this.log=O_(this.options.loggerName??D_.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},xS),t?.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},SS),t?.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},bS),t?.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new kC,this.outgoingDataStreamManager=new PC(this.engine,this.log),this.incomingDataTrackManager=new kw({e2eeManager:this.e2eeManager}),this.incomingDataTrackManager.on(`sfuUpdateSubscription`,e=>{this.engine.client.sendUpdateDataSubscription(e.sid,e.subscribe)}).on(`trackPublished`,e=>{var t;e.track.publisherIdentity!==this.localParticipant.identity&&(this.emit(B.DataTrackPublished,e.track),(t=this.remoteParticipants.get(e.track.publisherIdentity))==null||t.addRemoteDataTrack(e.track))}).on(`trackUnpublished`,e=>{var t;e.publisherIdentity!==this.localParticipant.identity&&(this.emit(B.DataTrackUnpublished,e.sid),(t=this.remoteParticipants.get(e.publisherIdentity))==null||t.removeRemoteDataTrack(e.sid))}),this.outgoingDataTrackManager=new Ww({e2eeManager:this.e2eeManager}),this.outgoingDataTrackManager.on(`sfuPublishRequest`,e=>{this.engine.client.sendPublishDataTrackRequest(e.handle,e.name,e.usesE2ee)}).on(`sfuUnpublishRequest`,e=>{this.engine.client.sendUnPublishDataTrackRequest(e.handle)}).on(`trackPublished`,e=>{this.emit(B.LocalDataTrackPublished,e.track)}).on(`trackUnpublished`,e=>{this.emit(B.LocalDataTrackUnpublished,e.sid)}).on(`packetAvailable`,e=>{let{bytes:t}=e;this.engine.sendLossyBytes(t,J.DATA_TRACK_LOSSY,`wait`)}),this.disconnectLock=new dp,this.localParticipant=new oT(``,``,this.engine,this.options,this.rpcHandlers,this.outgoingDataStreamManager,this.outgoingDataTrackManager),(this.options.e2ee||this.options.encryption)&&this.setupE2EE(),this.engine.e2eeManager=this.e2eeManager,this.incomingDataTrackManager.updateE2eeManager(this.e2eeManager??null),this.outgoingDataTrackManager.updateE2eeManager(this.e2eeManager??null),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set(`videoinput`,Rb(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set(`audioinput`,Rb(this.options.audioCaptureDefaults.deviceId)),this.options.audioOutput?.deviceId&&this.switchActiveDevice(`audiooutput`,Rb(this.options.audioOutput.deviceId)).catch(e=>this.log.warn(`Could not set audio output: ${e.message}`,this.logContext)),vb()){let t=new AbortController;(i=(r=navigator.mediaDevices)?.addEventListener)==null||i.call(r,`devicechange`,this.handleDeviceChange,{signal:t.signal}),e.cleanupRegistry&&e.cleanupRegistry.register(this,()=>{t.abort()})}}registerTextStreamHandler(e,t){return this.incomingDataStreamManager.registerTextStreamHandler(e,t)}unregisterTextStreamHandler(e){return this.incomingDataStreamManager.unregisterTextStreamHandler(e)}registerByteStreamHandler(e,t){return this.incomingDataStreamManager.registerByteStreamHandler(e,t)}unregisterByteStreamHandler(e){return this.incomingDataStreamManager.unregisterByteStreamHandler(e)}registerRpcMethod(e,t){if(this.rpcHandlers.has(e))throw Error(`RPC handler already registered for method ${e}, unregisterRpcMethod before trying to register again`);this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setE2EEEnabled(e){return L(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;let t=!!this.options.encryption,n=this.options.encryption||this.options.e2ee;n&&(`e2eeManager`in n?(this.e2eeManager=n.e2eeManager,this.e2eeManager.isDataChannelEncryptionEnabled=t):this.e2eeManager=new xx(n,t),this.e2eeManager.on(mx.ParticipantEncryptionStatusChanged,(e,t)=>{ex(t)&&(this.isE2EEEnabled=e),this.emit(B.ParticipantEncryptionStatusChanged,e,t)}),this.e2eeManager.on(mx.EncryptionError,(e,t)=>{let n=t?this.getParticipantByIdentity(t):void 0;this.emit(B.EncryptionError,e,n)}),(e=this.e2eeManager)==null||e.setup(this))}get logContext(){return{room:this.name,roomID:this.roomInfo?.sid,participant:this.localParticipant.identity,participantID:this.localParticipant.sid}}get isRecording(){return this.roomInfo?.activeRecording??!1}getSid(){return this.state===Y.Disconnected?ey.resolve(``):this.roomInfo&&this.roomInfo.sid!==``?ey.resolve(this.roomInfo.sid):new ey((e,t)=>{let n=t=>{t.sid!==``&&(this.engine.off(H.RoomUpdate,n),e(t.sid))};this.engine.on(H.RoomUpdate,n),this.once(B.Disconnected,()=>{this.engine.off(H.RoomUpdate,n),t(new py(`Room disconnected before room server id was available`))})})}get name(){return this.roomInfo?.name??``}get metadata(){return this.roomInfo?.metadata}get numParticipants(){return this.roomInfo?.numParticipants??0}get numPublishers(){return this.roomInfo?.numPublishers??0}maybeCreateEngine(){this.engine&&(this.engine.isNewlyCreated||!this.engine.isClosed)||(this.engine=new wC(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(H.ParticipantUpdate,this.handleParticipantUpdates).on(H.RoomUpdate,this.handleRoomUpdate).on(H.SpeakersChanged,this.handleSpeakersChanged).on(H.StreamStateChanged,this.handleStreamStateUpdate).on(H.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(H.SubscriptionError,this.handleSubscriptionError).on(H.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(H.MediaTrackAdded,(e,t,n)=>{this.onTrackAdded(e,t,n)}).on(H.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(H.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(H.DataPacketReceived,this.handleDataPacket).on(H.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info(`Resuming signal connection`,this.logContext),this.setAndEmitConnectionState(Y.SignalReconnecting)&&this.emit(B.SignalReconnecting)}).on(H.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info(`Resumed signal connection`,this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(Y.Connected)&&this.emit(B.Reconnected)}).on(H.SignalResumed,()=>{this.bufferedEvents=[],(this.state===Y.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(H.Restarting,this.handleRestarting).on(H.Restarted,this.handleRestarted).on(H.SignalRestarted,this.handleSignalRestarted).on(H.Offline,()=>{this.setAndEmitConnectionState(Y.Reconnecting)&&this.emit(B.Reconnecting)}).on(H.DCBufferStatusChanged,(e,t)=>{this.emit(B.DCBufferStatusChanged,e,t)}).on(H.LocalTrackSubscribed,e=>{let t=this.localParticipant.getTrackPublications().find(t=>{let{trackSid:n}=t;return n===e});if(!t){this.log.warn(`could not find local track subscription for subscribed event`,this.logContext);return}this.localParticipant.emit(V.LocalTrackSubscribed,t),this.emitWhenConnected(B.LocalTrackSubscribed,t,this.localParticipant)}).on(H.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(B.Moved,e.room.name),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)}).on(H.PublishDataTrackResponse,e=>{if(!e.info){this.log.warn(`received PublishDataTrackResponse, but event.info was ${e.info}, so skipping.`,this.logContext);return}this.outgoingDataTrackManager.receivedSfuPublishResponse(e.info.pubHandle,{type:`ok`,data:{sid:e.info.sid,pubHandle:e.info.pubHandle,name:e.info.name,usesE2ee:e.info.encryption!==F.NONE}})}).on(H.UnPublishDataTrackResponse,e=>{if(!e.info){this.log.warn(`received UnPublishDataTrackResponse, but event.info was ${e.info}, so skipping.`,this.logContext);return}this.outgoingDataTrackManager.receivedSfuUnpublishResponse(e.info.pubHandle)}).on(H.DataTrackSubscriberHandles,e=>{let t=new Map(Object.entries(e.subHandles).map(e=>{let[t,n]=e;return[parseInt(t,10),n.trackSid]}));this.incomingDataTrackManager.receivedSfuSubscriberHandles(t)}).on(H.DataTrackPacketReceived,e=>{try{this.incomingDataTrackManager.packetReceived(e)}catch(e){throw e}}).on(H.Joined,e=>{let t=new Map(e.otherParticipants.map(e=>[e.identity,e.dataTracks.map(e=>Lx.from(e))]));this.incomingDataTrackManager.receiveSfuPublicationUpdates(t)}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine),this.outgoingDataStreamManager&&this.outgoingDataStreamManager.setupEngine(this.engine))}static getLocalDevices(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return Ex.getInstance().getDevices(e,t)}prepareConnection(e,t){return L(this,void 0,void 0,function*(){if(this.state===Y.Disconnected){this.log.debug(`prepareConnection to ${e}`,this.logContext);try{if(bb(new URL(e))&&t){this.regionUrlProvider=new kS(e,t);let n=yield this.regionUrlProvider.getNextBestRegionUrl();n&&this.state===Y.Disconnected&&(this.regionUrl=n,yield fetch(Bb(n),{method:`HEAD`}),this.log.debug(`prepared connection to ${n}`,this.logContext))}else yield fetch(Bb(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 L(this,void 0,void 0,function*(){let n=()=>L(this,void 0,void 0,function*(){}),r;switch(e){case`signal-reconnect`:yield this.engine.client.handleOnClose(`simulate disconnect`);break;case`speaker`:r=new o_({scenario:{case:`speakerUpdate`,value:3}});break;case`node-failure`:r=new o_({scenario:{case:`nodeFailure`,value:!0}});break;case`server-leave`:r=new o_({scenario:{case:`serverLeave`,value:!0}});break;case`migration`:r=new o_({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=()=>L(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose(`simulate resume-disconnect`)}),r=new o_({scenario:{case:`disconnectSignalOnResume`,value:!0}});break;case`disconnect-signal-on-resume-no-messages`:n=()=>L(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose(`simulate resume-disconnect`)}),r=new o_({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`:r=new o_({scenario:{case:`switchCandidateProtocol`,value:e===`force-tls`?2:1}}),n=()=>L(this,void 0,void 0,function*(){let e=this.engine.client.onLeave;e&&e(new Rg({reason:_h.CLIENT_INITIATED,action:zg.RECONNECT}))});break;case`subscriber-bandwidth`:if(t===void 0||typeof t!=`number`)throw Error(`subscriber-bandwidth requires a number as argument`);r=new o_({scenario:{case:`subscriberBandwidth`,value:Gb(t)}});break;case`leave-full-reconnect`:r=new o_({scenario:{case:`leaveRequestFullReconnect`,value:!0}})}r&&(yield this.engine.client.sendSimulateScenario(r),yield n())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return L(this,arguments,void 0,function(e,t){var n=this;let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return function*(){var i,a;let o=!0,s=!1,c=r?{exact:t}:t;if(e===`audioinput`){s=n.localParticipant.audioTrackPublications.size===0;let t=n.getActiveDevice(e)??n.options.audioCaptureDefaults.deviceId;n.options.audioCaptureDefaults.deviceId=c;let r=Array.from(n.localParticipant.audioTrackPublications.values()).filter(e=>e.source===K.Source.Microphone);try{o=(yield Promise.all(r.map(e=>e.audioTrack?.setDeviceId(c)))).every(e=>e===!0)}catch(e){throw n.options.audioCaptureDefaults.deviceId=t,e}let i=r.some(e=>e.track?.isMuted??!1);o&&i&&(s=!0)}else if(e===`videoinput`){s=n.localParticipant.videoTrackPublications.size===0;let t=n.getActiveDevice(e)??n.options.videoCaptureDefaults.deviceId;n.options.videoCaptureDefaults.deviceId=c;let r=Array.from(n.localParticipant.videoTrackPublications.values()).filter(e=>e.source===K.Source.Camera);try{o=(yield Promise.all(r.map(e=>e.videoTrack?.setDeviceId(c)))).every(e=>e===!0)}catch(e){throw n.options.videoCaptureDefaults.deviceId=t,e}let i=r.some(e=>e.track?.isMuted??!1);o&&i&&(s=!0)}else if(e===`audiooutput`){if(s=!0,!cb()&&!n.options.webAudioMix||n.options.webAudioMix&&n.audioContext&&!(`setSinkId`in n.audioContext))throw Error(`cannot switch audio output, the current browser does not support it`);n.options.webAudioMix&&(t=(yield Ex.getInstance().normalizeDeviceId(`audiooutput`,t))??``),(a=n.options).audioOutput??(a.audioOutput={});let r=n.getActiveDevice(e)??n.options.audioOutput.deviceId;n.options.audioOutput.deviceId=t;try{n.options.webAudioMix&&((i=n.audioContext)==null||i.setSinkId(t)),yield Promise.all(Array.from(n.remoteParticipants.values()).map(e=>e.setAudioOutput({deviceId:t})))}catch(e){throw n.options.audioOutput.deviceId=r,e}}return s&&(n.localParticipant.activeDeviceMap.set(e,t),n.emit(B.ActiveDeviceChanged,e,t)),o}()})}setupLocalParticipantEvents(){this.localParticipant.on(V.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(V.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(V.AttributesChanged,this.onLocalAttributesChanged).on(V.TrackMuted,this.onLocalTrackMuted).on(V.TrackUnmuted,this.onLocalTrackUnmuted).on(V.LocalTrackPublished,this.onLocalTrackPublished).on(V.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(V.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(V.MediaDevicesError,this.onMediaDevicesError).on(V.AudioStreamAcquired,this.startAudio).on(V.ChatMessage,this.onLocalChatMessageSent).on(V.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(e){let t=this.engine;e&&t&&!t.client.isDisconnected?t.client.sendLeave().finally(()=>t.close()):t?.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,n){if(this.state===Y.Connecting||this.state===Y.Reconnecting){let r=()=>{this.log.debug(`deferring on track for later`,{mediaTrackId:e.id,mediaStreamId:t.id,tracksInStream:t.getTracks().map(e=>e.id)}),this.onTrackAdded(e,t,n),i()},i=()=>{this.off(B.Reconnected,r),this.off(B.Connected,r),this.off(B.Disconnected,i)};this.once(B.Reconnected,r),this.once(B.Connected,r),this.once(B.Disconnected,i);return}if(this.state===Y.Disconnected){this.log.warn(`skipping incoming track after Room disconnected`,this.logContext);return}if(e.readyState===`ended`){this.log.info(`skipping incoming track as it already ended`,this.logContext);return}let r=tb(t.id),i=r[0],a=r[1],o=e.id;if(a&&a.startsWith(`TR`)&&(o=a),i===this.localParticipant.sid){this.log.warn(`tried to create RemoteParticipant for local participant`,this.logContext);return}let s=Array.from(this.remoteParticipants.values()).find(e=>e.sid===i);if(!s){i.startsWith(`PA`)&&this.log.error(`Tried to add a track for a participant, that's not present. Sid: ${i}`,this.logContext);return}if(!o.startsWith(`TR`)){let e=this.engine.getTrackIdForReceiver(n);if(!e){this.log.error(`Tried to add a track whose 'sid' could not be found for a participant, that's not present. Sid: ${i}`,this.logContext);return}o=e}o.startsWith(`TR`)||this.log.warn(`Tried to add a track whose 'sid' could not be determined for a participant, that's not present. Sid: ${i}, streamId: ${a}, trackId: ${o}`,Object.assign(Object.assign({},this.logContext),{remoteParticipantID:i,streamId:a,trackId:o}));let c;this.options.adaptiveStream&&(c=typeof this.options.adaptiveStream==`object`?this.options.adaptiveStream:{});let l=s.addSubscribedMediaTrack(e,o,t,n,c);l?.isEncrypted&&!this.e2eeManager&&this.emit(B.EncryptionError,Error(`Encrypted ${l.source} track received from participant ${s.sid}, but room does not have encryption enabled!`))}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1?arguments[1]:void 0;var n,r;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearControllers(),this.state!==Y.Disconnected){this.regionUrl=void 0,this.regionUrlProvider&&this.regionUrlProvider.notifyDisconnected();try{this.remoteParticipants.forEach(e=>{e.trackPublications.forEach(t=>{e.unpublishTrack(t.trackSid)})}),this.localParticipant.trackPublications.forEach(t=>{var n,r,i;t.track&&this.localParticipant.unpublishTrack(t.track,e),e?((n=t.track)==null||n.detach(),(r=t.track)==null||r.stop()):(i=t.track)==null||i.stopMonitor()}),this.localParticipant.off(V.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(V.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(V.AttributesChanged,this.onLocalAttributesChanged).off(V.TrackMuted,this.onLocalTrackMuted).off(V.TrackUnmuted,this.onLocalTrackUnmuted).off(V.LocalTrackPublished,this.onLocalTrackPublished).off(V.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(V.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(V.MediaDevicesError,this.onMediaDevicesError).off(V.AudioStreamAcquired,this.startAudio).off(V.ChatMessage,this.onLocalChatMessageSent).off(V.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.trackPublications.clear(),this.localParticipant.videoTrackPublications.clear(),this.localParticipant.audioTrackPublications.clear(),this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.activeSpeakers=[],this.audioContext&&typeof this.options.webAudioMix==`boolean`&&(this.audioContext.close(),this.audioContext=void 0),vb()&&(window.removeEventListener(`beforeunload`,this.onPageLeave),window.removeEventListener(`pagehide`,this.onPageLeave),window.removeEventListener(`freeze`,this.onPageLeave),(r=(n=navigator.mediaDevices)?.removeEventListener)==null||r.call(n,`devicechange`,this.handleDeviceChange))}finally{this.setAndEmitConnectionState(Y.Disconnected),this.emit(B.Disconnected,t)}}}handleParticipantDisconnected(e,t){var n;this.remoteParticipants.delete(e),t&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(e),this.incomingDataTrackManager.handleRemoteParticipantDisconnected(e),t.trackPublications.forEach(e=>{t.unpublishTrack(e.trackSid,!0)}),this.emit(B.ParticipantDisconnected,t),t.setDisconnected(),(n=this.localParticipant)==null||n.handleParticipantDisconnected(t.identity))}handleIncomingRpcRequest(e,t,n,r,i,a){return L(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,t),a!==1){yield this.engine.publishRpcResponse(e,t,null,jS.builtIn(`UNSUPPORTED_VERSION`));return}let o=this.rpcHandlers.get(n);if(!o){yield this.engine.publishRpcResponse(e,t,null,jS.builtIn(`UNSUPPORTED_METHOD`));return}let s=null,c=null;try{let a=yield o({requestId:t,callerIdentity:e,payload:r,responseTimeout:i});NS(a)>MS?(s=jS.builtIn(`RESPONSE_PAYLOAD_TOO_LARGE`),this.log.warn(`RPC Response payload too large for ${n}`)):c=a}catch(e){e instanceof jS?s=e:(this.log.warn(`Uncaught error returned by RPC handler for ${n}. Returning APPLICATION_ERROR instead.`,e),s=jS.builtIn(`APPLICATION_ERROR`))}yield this.engine.publishRpcResponse(e,t,c,s)})}selectDefaultDevices(){return L(this,void 0,void 0,function*(){let e=Ex.getInstance().previousDevices,t=yield Ex.getInstance().getDevices(void 0,!1),n=ry();if(n?.name===`Chrome`&&n.os!==`iOS`)for(let n of t){let t=e.find(e=>e.deviceId===n.deviceId);t&&t.label!==``&&t.kind===n.kind&&t.label!==n.label&&this.getActiveDevice(n.kind)===`default`&&this.emit(B.ActiveDeviceChanged,n.kind,n.deviceId)}for(let n of[`audiooutput`,`audioinput`,`videoinput`]){let r=Ly(n),i=this.localParticipant.getTrackPublication(r);if(i&&i.track?.isUserProvided)continue;let a=t.filter(e=>e.kind===n),o=this.getActiveDevice(n);if(o===e.filter(e=>e.kind===n)[0]?.deviceId&&a.length>0&&a[0]?.deviceId!==o){yield this.switchActiveDevice(n,a[0].deviceId);continue}n===`audioinput`&&!pb()||n===`videoinput`||a.length>0&&!a.find(e=>e.deviceId===this.getActiveDevice(n))&&(n!==`audiooutput`||!pb())&&(yield this.switchActiveDevice(n,a[0].deviceId))}})}acquireAudioContext(){return L(this,void 0,void 0,function*(){if(typeof this.options.webAudioMix!=`boolean`&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:(!this.audioContext||this.audioContext.state===`closed`)&&(this.audioContext=Iy()??void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(e=>e.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state===`suspended`)try{yield Promise.race([this.audioContext.resume(),nb(200)])}catch(e){this.log.warn(`Could not resume audio context`,Object.assign(Object.assign({},this.logContext),{error:e}))}let e=this.audioContext?.state===`running`;e!==this.canPlaybackAudio&&(this.audioEnabled=e,this.emit(B.AudioPlaybackStatusChanged,e))})}createParticipant(e,t){let n;return n=t?uT.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):new uT(this.engine.client,``,e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&n.setAudioContext(this.audioContext),this.options.audioOutput?.deviceId&&n.setAudioOutput(this.options.audioOutput).catch(e=>this.log.warn(`Could not set audio output: ${e.message}`,this.logContext)),n}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){let n=this.remoteParticipants.get(e);return t&&n.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),n}let n=this.createParticipant(e,t);return this.remoteParticipants.set(e,n),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(B.ParticipantConnected,n),n.on(V.TrackPublished,e=>{this.emitWhenConnected(B.TrackPublished,e,n)}).on(V.TrackSubscribed,(e,t)=>{e.kind===K.Kind.Audio?(e.on(U.AudioPlaybackStarted,this.handleAudioPlaybackStarted),e.on(U.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):e.kind===K.Kind.Video&&(e.on(U.VideoPlaybackFailed,this.handleVideoPlaybackFailed),e.on(U.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emitWhenConnected(B.TrackSubscribed,e,t,n)}).on(V.TrackUnpublished,e=>{this.emit(B.TrackUnpublished,e,n)}).on(V.TrackUnsubscribed,(e,t)=>{this.emit(B.TrackUnsubscribed,e,t,n)}).on(V.TrackMuted,e=>{this.emitWhenConnected(B.TrackMuted,e,n)}).on(V.TrackUnmuted,e=>{this.emitWhenConnected(B.TrackUnmuted,e,n)}).on(V.ParticipantMetadataChanged,e=>{this.emitWhenConnected(B.ParticipantMetadataChanged,e,n)}).on(V.ParticipantNameChanged,e=>{this.emitWhenConnected(B.ParticipantNameChanged,e,n)}).on(V.AttributesChanged,e=>{this.emitWhenConnected(B.ParticipantAttributesChanged,e,n)}).on(V.ConnectionQualityChanged,e=>{this.emitWhenConnected(B.ConnectionQualityChanged,e,n)}).on(V.ParticipantPermissionsChanged,e=>{this.emitWhenConnected(B.ParticipantPermissionsChanged,e,n)}).on(V.TrackSubscriptionStatusChanged,(e,t)=>{this.emitWhenConnected(B.TrackSubscriptionStatusChanged,e,t,n)}).on(V.TrackSubscriptionFailed,(e,t)=>{this.emit(B.TrackSubscriptionFailed,e,n,t)}).on(V.TrackSubscriptionPermissionChanged,(e,t)=>{this.emitWhenConnected(B.TrackSubscriptionPermissionChanged,e,t,n)}).on(V.Active,()=>{this.emitWhenConnected(B.ParticipantActive,n),n.kind===Eh.AGENT&&this.localParticipant.setActiveAgent(n)}),t&&n.updateInfo(t),n}sendSyncState(){let e=Array.from(this.remoteParticipants.values()).reduce((e,t)=>(e.push(...t.getTrackPublications()),e),[]),t=this.localParticipant.getTrackPublications(),n=this.outgoingDataTrackManager.queryPublished();this.engine.sendSyncState(e,t,n)}updateSubscriptions(){for(let e of this.remoteParticipants.values())for(let t of e.videoTrackPublications.values())t.isSubscribed&&Qb(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){let t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=xy.setInterval(()=>{!this.engine||this.engine.isClosed||!this.engine.verifyTransport()?(e++,this.log.warn(`detected connection state mismatch`,Object.assign(Object.assign({},this.logContext),{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnectedOrConnecting:this.engine.verifyTransport()}:void 0})),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,_h.STATE_MISMATCH))):e=0},dT)}clearConnectionReconcile(){this.connectionReconcileInterval&&xy.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(B.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[t,n]=e;this.emit(t,...n)}),this.bufferedEvents=[]}emitWhenConnected(e){var t=[...arguments].slice(1);if(this.state===Y.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,t]);else if(this.state===Y.Connected)return this.emit(e,...t);return!1}simulateParticipants(e){return L(this,void 0,void 0,function*(){let t=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),n=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new xh({sid:`RM_SIMULATED`,name:`simulated-room`,emptyTimeout:0,maxParticipants:0,creationTime:Hp.parse(new Date().getTime()),metadata:``,numParticipants:1,numPublishers:1,turnPassword:``,enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new wh({identity:`simulated-local`,name:`local-name`})),this.setupLocalParticipantEvents(),this.emit(B.SignalConnected),this.emit(B.Connected),this.setAndEmitConnectionState(Y.Connected),t.video){let e=new $w(K.Kind.Video,new kh({source:ph.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:fh.AUDIO,name:`video-dummy`}),new lC(t.useRealTracks&&window.navigator.mediaDevices?.getUserMedia?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Nb(160*(n.aspectRatios[0]??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(V.LocalTrackPublished,e)}if(t.audio){let e=new $w(K.Kind.Audio,new kh({source:ph.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:fh.AUDIO}),new WS(t.useRealTracks&&navigator.mediaDevices?.getUserMedia?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Fb(),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(V.LocalTrackPublished,e)}for(let e=0;e<n.count-1;e+=1){let t=new wh({sid:Math.floor(Math.random()*1e4).toString(),identity:`simulated-${e}`,state:Th.ACTIVE,tracks:[],joinedAt:Hp.parse(Date.now())}),r=this.getOrCreateParticipant(t.identity,t);if(n.video){let i=Nb(160*(n.aspectRatios[e%n.aspectRatios.length]??1),160,!1,!0),a=new kh({source:ph.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:fh.AUDIO});r.addSubscribedMediaTrack(i,a.sid,new MediaStream([i]),new RTCRtpReceiver),t.tracks=[...t.tracks,a]}if(n.audio){let e=Fb(),n=new kh({source:ph.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:fh.AUDIO});r.addSubscribedMediaTrack(e,n.sid,new MediaStream([e]),new RTCRtpReceiver),t.tracks=[...t.tracks,n]}r.updateInfo(t)}})}emit(e){var t=[...arguments].slice(1);if(e!==B.ActiveSpeakersChanged&&e!==B.TranscriptionReceived){let n=pT(t).filter(e=>e!==void 0);(e===B.TrackSubscribed||e===B.TrackUnsubscribed)&&this.log.trace(`subscribe trace: ${e}`,Object.assign(Object.assign({},this.logContext),{event:e,args:n})),this.log.debug(`room event ${e}`,Object.assign(Object.assign({},this.logContext),{event:e,args:n}))}return super.emit(e,...t)}};fT.cleanupRegistry=typeof FinalizationRegistry<`u`&&new FinalizationRegistry(e=>{e()});function pT(e){return e.map(e=>{if(e)return Array.isArray(e)?pT(e):typeof e==`object`?`logContext`in e?e.logContext:void 0:e})}var mT;(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`})(mT||={}),H_.EventEmitter,H_.EventEmitter;function X(e,t,n){return(t=gT(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function hT(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function gT(e){var t=hT(e,`string`);return typeof t==`symbol`?t:t+``}new TextEncoder,new TextDecoder;var _T=class extends Error{constructor(e,t){var n;super(e,t),X(this,`code`,`ERR_JOSE_GENERIC`),this.name=this.constructor.name,(n=Error.captureStackTrace)==null||n.call(Error,this,this.constructor)}};X(_T,`code`,`ERR_JOSE_GENERIC`),X(class extends _T{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:`unspecified`,r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:`unspecified`;super(e,{cause:{claim:n,reason:r,payload:t}}),X(this,`code`,`ERR_JWT_CLAIM_VALIDATION_FAILED`),X(this,`claim`,void 0),X(this,`reason`,void 0),X(this,`payload`,void 0),this.claim=n,this.reason=r,this.payload=t}},`code`,`ERR_JWT_CLAIM_VALIDATION_FAILED`),X(class extends _T{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:`unspecified`,r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:`unspecified`;super(e,{cause:{claim:n,reason:r,payload:t}}),X(this,`code`,`ERR_JWT_EXPIRED`),X(this,`claim`,void 0),X(this,`reason`,void 0),X(this,`payload`,void 0),this.claim=n,this.reason=r,this.payload=t}},`code`,`ERR_JWT_EXPIRED`),X(class extends _T{constructor(){super(...arguments),X(this,`code`,`ERR_JOSE_ALG_NOT_ALLOWED`)}},`code`,`ERR_JOSE_ALG_NOT_ALLOWED`),X(class extends _T{constructor(){super(...arguments),X(this,`code`,`ERR_JOSE_NOT_SUPPORTED`)}},`code`,`ERR_JOSE_NOT_SUPPORTED`),X(class extends _T{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:`decryption operation failed`,t=arguments.length>1?arguments[1]:void 0;super(e,t),X(this,`code`,`ERR_JWE_DECRYPTION_FAILED`)}},`code`,`ERR_JWE_DECRYPTION_FAILED`),X(class extends _T{constructor(){super(...arguments),X(this,`code`,`ERR_JWE_INVALID`)}},`code`,`ERR_JWE_INVALID`),X(class extends _T{constructor(){super(...arguments),X(this,`code`,`ERR_JWS_INVALID`)}},`code`,`ERR_JWS_INVALID`),X(class extends _T{constructor(){super(...arguments),X(this,`code`,`ERR_JWT_INVALID`)}},`code`,`ERR_JWT_INVALID`),X(class extends _T{constructor(){super(...arguments),X(this,`code`,`ERR_JWK_INVALID`)}},`code`,`ERR_JWK_INVALID`),X(class extends _T{constructor(){super(...arguments),X(this,`code`,`ERR_JWKS_INVALID`)}},`code`,`ERR_JWKS_INVALID`),X(class extends _T{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:`no applicable key found in the JSON Web Key Set`,t=arguments.length>1?arguments[1]:void 0;super(e,t),X(this,`code`,`ERR_JWKS_NO_MATCHING_KEY`)}},`code`,`ERR_JWKS_NO_MATCHING_KEY`),X(class extends _T{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:`multiple matching keys found in the JSON Web Key Set`,t=arguments.length>1?arguments[1]:void 0;super(e,t),X(this,Symbol.asyncIterator,void 0),X(this,`code`,`ERR_JWKS_MULTIPLE_MATCHING_KEYS`)}},`code`,`ERR_JWKS_MULTIPLE_MATCHING_KEYS`),X(class extends _T{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:`request timed out`,t=arguments.length>1?arguments[1]:void 0;super(e,t),X(this,`code`,`ERR_JWKS_TIMEOUT`)}},`code`,`ERR_JWKS_TIMEOUT`),X(class extends _T{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:`signature verification failed`,t=arguments.length>1?arguments[1]:void 0;super(e,t),X(this,`code`,`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`)}},`code`,`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`);function vT(){return vT=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},vT.apply(null,arguments)}var yT=new Uint8Array,bT=class{static getFullOptions(e){return vT({clientTools:{},onConnect:()=>{},onDebug:()=>{},onDisconnect:()=>{},onError:()=>{},onMessage:()=>{},onAudio:()=>{},onModeChange:()=>{},onStatusChange:()=>{},onCanSendFeedbackChange:()=>{},onInterruption:()=>{}},e)}constructor(e,t){var n=this;this.options=void 0,this.connection=void 0,this.lastInterruptTimestamp=0,this.mode=`listening`,this.status=`connecting`,this.volume=1,this.currentEventId=1,this.lastFeedbackEventId=0,this.canSendFeedback=!1,this.endSessionWithDetails=async function(e){n.status!==`connected`&&n.status!==`connecting`||(n.updateStatus(`disconnecting`),await n.handleEndSession(),n.updateStatus(`disconnected`),n.options.onDisconnect&&n.options.onDisconnect(e))},this.onMessage=async function(e){switch(e.type){case`interruption`:n.handleInterruption(e);return;case`agent_response`:n.handleAgentResponse(e);return;case`user_transcript`:n.handleUserTranscript(e);return;case`internal_tentative_agent_response`:n.handleTentativeAgentResponse(e);return;case`client_tool_call`:try{await n.handleClientToolCall(e)}catch(t){n.onError(`Unexpected error in client tool call handling: ${t instanceof Error?t.message:String(t)}`,{clientToolName:e.client_tool_call.tool_name,toolCallId:e.client_tool_call.tool_call_id})}return;case`audio`:n.handleAudio(e);return;case`vad_score`:n.handleVadScore(e);return;case`ping`:n.connection.sendMessage({type:`pong`,event_id:e.ping_event.event_id});return;case`mcp_tool_call`:n.handleMCPToolCall(e);return;case`mcp_connection_status`:n.handleMCPConnectionStatus(e);return;case`agent_tool_request`:n.handleAgentToolRequest(e);return;case`agent_tool_response`:n.handleAgentToolResponse(e);return;case`conversation_initiation_metadata`:n.handleConversationMetadata(e);return;case`asr_initiation_metadata`:n.handleAsrInitiationMetadata(e);return;case`agent_chat_response_part`:n.handleAgentChatResponsePart(e);return;case`error`:n.handleErrorEvent(e);return;default:n.options.onDebug&&n.options.onDebug(e);return}},this.setVolume=({volume:e})=>{this.volume=e},this.options=e,this.connection=t,this.options.onConnect&&this.options.onConnect({conversationId:t.conversationId}),this.connection.onMessage(this.onMessage),this.connection.onDisconnect(this.endSessionWithDetails),this.connection.onModeChange(e=>this.updateMode(e)),this.updateStatus(`connected`)}endSession(){return this.endSessionWithDetails({reason:`user`})}async handleEndSession(){this.connection.close()}updateMode(e){e!==this.mode&&(this.mode=e,this.options.onModeChange&&this.options.onModeChange({mode:e}))}updateStatus(e){e!==this.status&&(this.status=e,this.options.onStatusChange&&this.options.onStatusChange({status:e}))}updateCanSendFeedback(){let e=this.currentEventId!==this.lastFeedbackEventId;this.canSendFeedback!==e&&(this.canSendFeedback=e,this.options.onCanSendFeedbackChange&&this.options.onCanSendFeedbackChange({canSendFeedback:e}))}handleInterruption(e){e.interruption_event&&(this.lastInterruptTimestamp=e.interruption_event.event_id,this.options.onInterruption&&this.options.onInterruption({event_id:e.interruption_event.event_id}))}handleAgentResponse(e){this.options.onMessage&&this.options.onMessage({source:`ai`,role:`agent`,message:e.agent_response_event.agent_response})}handleUserTranscript(e){this.options.onMessage&&this.options.onMessage({source:`user`,role:`user`,message:e.user_transcription_event.user_transcript})}handleTentativeAgentResponse(e){this.options.onDebug&&this.options.onDebug({type:`tentative_agent_response`,response:e.tentative_agent_response_internal_event.tentative_agent_response})}handleVadScore(e){this.options.onVadScore&&this.options.onVadScore({vadScore:e.vad_score_event.vad_score})}async handleClientToolCall(e){if(Object.prototype.hasOwnProperty.call(this.options.clientTools,e.client_tool_call.tool_name))try{let t=await this.options.clientTools[e.client_tool_call.tool_name](e.client_tool_call.parameters)??`Client tool execution successful.`,n=typeof t==`object`?JSON.stringify(t):String(t);this.connection.sendMessage({type:`client_tool_result`,tool_call_id:e.client_tool_call.tool_call_id,result:n,is_error:!1})}catch(t){this.onError(`Client tool execution failed with following error: ${t?.message}`,{clientToolName:e.client_tool_call.tool_name}),this.connection.sendMessage({type:`client_tool_result`,tool_call_id:e.client_tool_call.tool_call_id,result:`Client tool execution failed: ${t?.message}`,is_error:!0})}else{if(this.options.onUnhandledClientToolCall)return void this.options.onUnhandledClientToolCall(e.client_tool_call);this.onError(`Client tool with name ${e.client_tool_call.tool_name} is not defined on client`,{clientToolName:e.client_tool_call.tool_name}),this.connection.sendMessage({type:`client_tool_result`,tool_call_id:e.client_tool_call.tool_call_id,result:`Client tool with name ${e.client_tool_call.tool_name} is not defined on client`,is_error:!0})}}handleAudio(e){}handleMCPToolCall(e){this.options.onMCPToolCall&&this.options.onMCPToolCall(e.mcp_tool_call)}handleMCPConnectionStatus(e){this.options.onMCPConnectionStatus&&this.options.onMCPConnectionStatus(e.mcp_connection_status)}handleAgentToolRequest(e){this.options.onAgentToolRequest&&this.options.onAgentToolRequest(e.agent_tool_request)}handleAgentToolResponse(e){e.agent_tool_response.tool_name===`end_call`&&this.endSessionWithDetails({reason:`agent`,context:new CloseEvent(`end_call`,{reason:`Agent ended the call`})}),this.options.onAgentToolResponse&&this.options.onAgentToolResponse(e.agent_tool_response)}handleConversationMetadata(e){this.options.onConversationMetadata&&this.options.onConversationMetadata(e.conversation_initiation_metadata_event)}handleAsrInitiationMetadata(e){this.options.onAsrInitiationMetadata&&this.options.onAsrInitiationMetadata(e.asr_initiation_metadata_event)}handleAgentChatResponsePart(e){this.options.onAgentChatResponsePart&&this.options.onAgentChatResponsePart(e.text_response_part)}handleErrorEvent(e){let t=e.error_event.error_type,n=e.error_event.message||e.error_event.reason||`Unknown error`;t===`max_duration_exceeded`?this.endSessionWithDetails({reason:`error`,message:n,context:new Event(`max_duration_exceeded`)}):this.onError(`Server error: ${n}`,{errorType:t,code:e.error_event.code,debugMessage:e.error_event.debug_message,details:e.error_event.details})}onError(e,t){console.error(e,t),this.options.onError&&this.options.onError(e,t)}getId(){return this.connection.conversationId}isOpen(){return this.status===`connected`}setMicMuted(e){this.connection.setMicMuted(e)}getInputByteFrequencyData(){return yT}getOutputByteFrequencyData(){return yT}getInputVolume(){return 0}getOutputVolume(){return 0}sendFeedback(e){this.canSendFeedback?(this.connection.sendMessage({type:`feedback`,score:e?`like`:`dislike`,event_id:this.currentEventId}),this.lastFeedbackEventId=this.currentEventId,this.updateCanSendFeedback()):console.warn(this.lastFeedbackEventId===0?`Cannot send feedback: the conversation has not started yet.`:`Cannot send feedback: feedback has already been sent for the current response.`)}sendContextualUpdate(e){this.connection.sendMessage({type:`contextual_update`,text:e})}sendUserMessage(e){this.connection.sendMessage({type:`user_message`,text:e})}sendUserActivity(){this.connection.sendMessage({type:`user_activity`})}sendMCPToolApprovalResult(e,t){this.connection.sendMessage({type:`mcp_tool_approval_result`,tool_call_id:e,is_approved:t})}},xT=class{constructor(e={}){this.queue=[],this.disconnectionDetails=null,this.onDisconnectCallback=null,this.onMessageCallback=null,this.onModeChangeCallback=null,this.onDebug=void 0,this.onDebug=e.onDebug}debug(e){this.onDebug&&this.onDebug(e)}onMessage(e){this.onMessageCallback=e;let t=this.queue;this.queue=[],t.length>0&&queueMicrotask(()=>{t.forEach(e)})}onDisconnect(e){this.onDisconnectCallback=e;let t=this.disconnectionDetails;t&&queueMicrotask(()=>{e(t)})}onModeChange(e){this.onModeChangeCallback=e}updateMode(e){var t;(t=this.onModeChangeCallback)==null||t.call(this,e)}disconnect(e){var t;this.disconnectionDetails||(this.disconnectionDetails=e,(t=this.onDisconnectCallback)==null||t.call(this,e))}handleMessage(e){this.onMessageCallback?this.onMessageCallback(e):this.queue.push(e)}};function ST(e){let[t,n]=e.split(`_`);if(![`pcm`,`ulaw`].includes(t))throw Error(`Invalid format: ${e}`);let r=Number.parseInt(n);if(Number.isNaN(r))throw Error(`Invalid sample rate: ${n}`);return{format:t,sampleRate:r}}var CT=`0.12.2`;function wT(e){return!!e.type}var TT=`conversation_initiation_client_data`;function ET(e){var t;let n={type:TT};return e.overrides&&(n.conversation_config_override={agent:{prompt:e.overrides.agent?.prompt,first_message:e.overrides.agent?.firstMessage,language:e.overrides.agent?.language},tts:{voice_id:e.overrides.tts?.voiceId,speed:e.overrides.tts?.speed},conversation:{text_only:e.overrides.conversation?.textOnly}}),e.customLlmExtraBody&&(n.custom_llm_extra_body=e.customLlmExtraBody),e.dynamicVariables&&(n.dynamic_variables=e.dynamicVariables),e.userId&&(n.user_id=e.userId),(t=e.overrides)!=null&&t.client&&(n.source_info={source:e.overrides.client.source,version:e.overrides.client.version}),n}var DT=class e extends xT{constructor(e,t,n,r){super(),this.socket=void 0,this.conversationId=void 0,this.inputFormat=void 0,this.outputFormat=void 0,this.socket=e,this.conversationId=t,this.inputFormat=n,this.outputFormat=r,this.socket.addEventListener(`error`,e=>{setTimeout(()=>this.disconnect({reason:`error`,message:`The connection was closed due to a socket error.`,context:e}),0)}),this.socket.addEventListener(`close`,e=>{this.disconnect(e.code===1e3?{reason:`agent`,context:e}:{reason:`error`,message:e.reason||`The connection was closed by the server.`,context:e})}),this.socket.addEventListener(`message`,e=>{try{let t=JSON.parse(e.data);if(!wT(t))return void this.debug({type:`invalid_event`,message:`Received invalid socket event`,data:e.data});this.handleMessage(t)}catch(t){this.debug({type:`parsing_error`,message:`Failed to parse socket message`,error:t instanceof Error?t.message:String(t),data:e.data})}})}static async create(t){let n=null;try{var r,i;let a=t.origin??`wss://api.elevenlabs.io`,o,s=((r=t.overrides)==null||(r=r.client)==null?void 0:r.version)||CT,c=((i=t.overrides)==null||(i=i.client)==null?void 0:i.source)||`js_sdk`;if(t.signedUrl){let e=t.signedUrl.includes(`?`)?`&`:`?`;o=`${t.signedUrl}${e}source=${c}&version=${s}`}else o=`${a}/v1/convai/conversation?agent_id=${t.agentId}&source=${c}&version=${s}`;let l=[`convai`];t.authorization&&l.push(`bearer.${t.authorization}`),n=new WebSocket(o,l);let{conversation_id:u,agent_output_audio_format:d,user_input_audio_format:f}=await new Promise((e,r)=>{n.addEventListener(`open`,()=>{var e;let r=ET(t);(e=n)==null||e.send(JSON.stringify(r))},{once:!0}),n.addEventListener(`error`,e=>{setTimeout(()=>r(e),0)}),n.addEventListener(`close`,r),n.addEventListener(`message`,t=>{let n=JSON.parse(t.data);wT(n)&&(n.type===`conversation_initiation_metadata`?e(n.conversation_initiation_metadata_event):console.warn(`First received message is not conversation metadata.`))},{once:!0})}),p=ST(f??`pcm_16000`),m=ST(d);return new e(n,u,p,m)}catch(e){var a;throw(a=n)==null||a.close(),e}}close(){this.socket.close(1e3,`User ended conversation`)}sendMessage(e){this.socket.send(JSON.stringify(e))}async setMicMuted(e){console.warn(`WebSocket connection setMicMuted called with ${e}, but this is handled by VoiceConversation`)}};function OT(e){let t=new Uint8Array(e);return window.btoa(String.fromCharCode(...t))}function kT(e){let t=window.atob(e),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.charCodeAt(e);return r.buffer}var AT=new Map;function jT(e,t){return async(n,r)=>{let i=AT.get(e);if(i)return n.addModule(i);if(r)try{await n.addModule(r),AT.set(e,r);return}catch(t){throw Error(`Failed to load the ${e} worklet module from path: ${r}. Error: ${t}`)}let a=new Blob([t],{type:`application/javascript`}),o=URL.createObjectURL(a);try{await n.addModule(o),AT.set(e,o);return}catch{URL.revokeObjectURL(o)}try{let r=`data:application/javascript;base64,${btoa(t)}`;await n.addModule(r),AT.set(e,r)}catch{throw Error(`Failed to load the ${e} worklet module. Make sure the browser supports AudioWorklets. If you are using a strict CSP, you may need to self-host the worklet files.`)}}}var MT=jT(`rawAudioProcessor`,`/*
62
+ `},cS}var dS;function fS(){if(dS)return tS;dS=1;var e=sS(),t=uS();return tS.grammar=aS(),tS.write=t,tS.parse=e.parse,tS.parseParams=e.parseParams,tS.parseFmtpConfig=e.parseFmtpConfig,tS.parsePayloads=e.parsePayloads,tS.parseRemoteCandidates=e.parseRemoteCandidates,tS.parseImageAttributes=e.parseImageAttributes,tS.parseSimulcastStreamList=e.parseSimulcastStreamList,tS}var pS=fS();function mS(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:50,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},r,i=n.isImmediate??!1,a=n.callback??!1,o=n.maxWait,s=Date.now(),c=[];function l(){if(o!==void 0){let e=Date.now()-s;if(e+t>=o)return o-e}return t}let u=function(){for(var t=arguments.length,n=Array(t),o=0;o<t;o++)n[o]=arguments[o];let u=this;return new Promise((t,o)=>{let d=function(){if(r=void 0,s=Date.now(),!i){let t=e.apply(u,n);a&&a(t),c.forEach(e=>{let{resolve:n}=e;return n(t)}),c=[]}},f=i&&r===void 0;if(r!==void 0&&Ty.clearTimeout(r),r=Ty.setTimeout(d,l()),f){let r=e.apply(u,n);return a&&a(r),t(r)}c.push({resolve:t,reject:o})})};return u.cancel=function(e){r!==void 0&&Ty.clearTimeout(r),c.forEach(t=>{let{reject:n}=t;return n(e)}),c=[]},u}var hS=.7,gS=20,_S={NegotiationStarted:`negotiationStarted`,NegotiationComplete:`negotiationComplete`,RTPVideoPayloadTypes:`rtpVideoPayloadTypes`},vS=class extends K_.EventEmitter{get pc(){return this._pc||=this.createPC(),this._pc}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),this.log=I,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=mS(e=>L(this,void 0,void 0,function*(){this.emit(_S.NegotiationStarted);try{yield this.createAndSendOffer()}catch(t){if(e)e(t);else throw t}}),gS),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,null)},this.log=M_(t.loggerName??j_.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC(),this.offerLock=new hp}createPC(){let e=new RTCPeerConnection(this.config);return e.onicecandidate=e=>{var t;e.candidate&&((t=this.onIceCandidate)==null||t.call(this,e.candidate))},e.onicecandidateerror=e=>{var t;(t=this.onIceCandidateError)==null||t.call(this,e)},e.oniceconnectionstatechange=()=>{var t;(t=this.onIceConnectionStateChange)==null||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;(t=this.onSignalingStatechange)==null||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;(t=this.onConnectionStateChange)==null||t.call(this,e.connectionState)},e.ondatachannel=e=>{var t;(t=this.onDataChannel)==null||t.call(this,e)},e.ontrack=e=>{var t;(t=this.onTrack)==null||t.call(this,e)},e}get logContext(){var e;return Object.assign({},(e=this.loggerOptions).loggerContextCb?.call(e))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState===`connected`||this.pc.iceConnectionState===`completed`)}addIceCandidate(e){return L(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 L(this,void 0,void 0,function*(){if(e.type===`answer`&&this.latestOfferId>0&&t>0&&t!==this.latestOfferId)return this.log.warn(`ignoring answer for old offer`,Object.assign(Object.assign({},this.logContext),{offerId:t,latestOfferId:this.latestOfferId})),!1;let n;if(e.type===`offer`){let{stereoMids:t,nackMids:n}=bS(e);this.remoteStereoMids=t,this.remoteNackMids=n}else if(e.type===`answer`){if(this.pendingInitialOffer){let e=this.pendingInitialOffer;this.pendingInitialOffer=void 0;let t=pS.parse(e.sdp??``);t.media.forEach(e=>{xS(e)}),this.log.debug(`setting pending initial offer before processing answer`,this.logContext),yield this.setMungedSDP(e,pS.write(t))}let t=pS.parse(e.sdp??``);t.media.forEach(e=>{let t=SS(e.mid);e.type===`audio`&&this.trackBitrates.some(n=>{if(!n.transceiver||t!=n.transceiver.mid)return!1;let r=0;if(e.rtp.some(e=>e.codec.toUpperCase()===n.codec.toUpperCase()?(r=e.payload,!0):!1),r===0)return!0;let i=!1;for(let t of e.fmtp)if(t.payload===r){t.config=t.config.split(`;`).filter(e=>!e.includes(`maxaveragebitrate`)).join(`;`),n.maxbr>0&&(t.config+=`;maxaveragebitrate=${n.maxbr*1e3}`),i=!0;break}return i||n.maxbr>0&&e.fmtp.push({payload:r,config:`maxaveragebitrate=${n.maxbr*1e3}`}),!0})}),n=pS.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()):e.type===`answer`&&(this.emit(_S.NegotiationComplete),e.sdp&&pS.parse(e.sdp).media.forEach(e=>{e.type===`video`&&this.emit(_S.RTPVideoPayloadTypes,e.rtp)})),!0})}createInitialOffer(){return L(this,void 0,void 0,function*(){let e=yield this.offerLock.lock();try{if(this.pc.signalingState!==`stable`){this.log.warn(`signaling state is not stable, cannot create initial offer`,this.logContext);return}let e=this.latestOfferId+1;this.latestOfferId=e;let t=yield this.pc.createOffer();this.pendingInitialOffer={sdp:t.sdp,type:t.type};let n=pS.parse(t.sdp??``);return n.media.forEach(e=>{xS(e)}),t.sdp=pS.write(n),{offer:t,offerId:e}}finally{e()}})}createAndSendOffer(e){return L(this,void 0,void 0,function*(){let t=yield this.offerLock.lock();try{if(this.onOffer===void 0)return;if(e?.iceRestart&&(this.log.debug(`restarting ICE`,this.logContext),this.restartingIce=!0),this._pc&&(this._pc.signalingState===`have-local-offer`||this.pendingInitialOffer)){let t=this._pc.remoteDescription;if(e?.iceRestart&&t)yield this._pc.setRemoteDescription(t);else{this.renegotiate=!0,this.log.debug(`requesting renegotiation`,Object.assign({},this.logContext));return}}else if(!this._pc||this._pc.signalingState===`closed`){this.log.warn(`could not createOffer with closed peer connection`,this.logContext);return}this.log.debug(`starting to negotiate`,this.logContext);let t=this.latestOfferId+1;this.latestOfferId=t;let n=yield this.pc.createOffer(e);this.log.debug(`original offer`,Object.assign({sdp:n.sdp},this.logContext));let r=pS.parse(n.sdp??``);if(r.media.forEach(e=>{xS(e),e.type===`audio`?yS(e,[`all`],[]):e.type===`video`&&this.trackBitrates.some(t=>{if(!e.msid||!t.cid||!e.msid.includes(t.cid))return!1;let n=0;if(e.rtp.some(e=>e.codec.toUpperCase()===t.codec.toUpperCase()?(n=e.payload,!0):!1),n===0||(db(t.codec)&&!gb()&&this.ensureVideoDDExtensionForSVC(e,r),!db(t.codec)))return!0;let i=Math.round(t.maxbr*hS);for(let t of e.fmtp)if(t.payload===n){t.config.includes(`x-google-start-bitrate`)||(t.config+=`;x-google-start-bitrate=${i}`);break}return!0})}),this.latestOfferId>t){this.log.warn(`latestOfferId mismatch`,Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:t}));return}yield this.setMungedSDP(n,pS.write(r)),this.onOffer(n,this.latestOfferId)}finally{t()}})}createAndSetAnswer(){return L(this,void 0,void 0,function*(){let e=yield this.pc.createAnswer(),t=pS.parse(e.sdp??``);return t.media.forEach(e=>{xS(e),e.type===`audio`&&yS(e,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(e,pS.write(t)),e})}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTransceiverOfKind(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new _y(`PC closed, cannot add track`);return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){if(!this._pc)throw new _y(`PC closed, cannot configure`);return this._pc?.setConfiguration(e)}canRemoveTrack(){return!!this._pc?.removeTrack}removeTrack(e){return this._pc?.removeTrack(e)}getConnectionState(){return this._pc?.connectionState??`closed`}getICEConnectionState(){return this._pc?.iceConnectionState??`closed`}getSignallingState(){return this._pc?.signalingState??`closed`}getTransceivers(){return this._pc?.getTransceivers()??[]}getSenders(){return this._pc?.getSenders()??[]}getLocalDescription(){return this._pc?.localDescription}getRemoteDescription(){return this.pc?.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return L(this,void 0,void 0,function*(){if(!this._pc)return;let e=``,t=new Map,n=new Map;if((yield this._pc.getStats()).forEach(r=>{switch(r.type){case`transport`:e=r.selectedCandidatePairId;break;case`candidate-pair`:e===``&&r.selected&&(e=r.id),t.set(r.id,r);break;case`remote-candidate`:n.set(r.id,`${r.address}:${r.port}`);break}}),e===``)return;let r=t.get(e)?.remoteCandidateId;if(r!==void 0)return n.get(r)})}setMungedSDP(e,t,n){return L(this,void 0,void 0,function*(){if(t){let r=e.sdp;e.sdp=t;try{this.log.debug(`setting munged ${n?`remote`:`local`} description`,this.logContext),n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(n){this.log.warn(`not able to set ${e.type}, falling back to unmodified sdp`,Object.assign(Object.assign({},this.logContext),{error:n,sdp:t})),e.sdp=r}}try{n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(t){let r=`unknown error`;t instanceof Error?r=t.message:typeof t==`string`&&(r=t);let i={error:r,sdp:e.sdp};throw!n&&this.pc.remoteDescription&&(i.remoteSdp=this.pc.remoteDescription),this.log.error(`unable to set ${e.type}`,Object.assign(Object.assign({},this.logContext),{fields:i})),new vy(r)}})}ensureVideoDDExtensionForSVC(e,t){var n;if(!e.ext?.some(e=>e.uri===ib)){if(this.ddExtID===0){let e=0;t.media.forEach(t=>{var n;t.type===`video`&&((n=t.ext)==null||n.forEach(t=>{t.value>e&&(e=t.value)}))}),this.ddExtID=e+1}(n=e.ext)==null||n.push({value:this.ddExtID,uri:ib})}}};function yS(e,t,n){let r=SS(e.mid),i=0;e.rtp.some(e=>e.codec===`opus`?(i=e.payload,!0):!1),i>0&&(e.rtcpFb||=[],n.includes(r)&&!e.rtcpFb.some(e=>e.payload===i&&e.type===`nack`)&&e.rtcpFb.push({payload:i,type:`nack`}),(t.includes(r)||t.length===1&&t[0]===`all`)&&e.fmtp.some(e=>e.payload===i?(e.config.includes(`stereo=1`)||(e.config+=`;stereo=1`),!0):!1))}function bS(e){let t=[],n=[],r=pS.parse(e.sdp??``),i=0;return r.media.forEach(e=>{let r=SS(e.mid);e.type===`audio`&&(e.rtp.some(e=>e.codec===`opus`?(i=e.payload,!0):!1),e.rtcpFb?.some(e=>e.payload===i&&e.type===`nack`)&&n.push(r),e.fmtp.some(e=>e.payload===i?(e.config.includes(`sprop-stereo=1`)&&t.push(r),!0):!1))}),{stereoMids:t,nackMids:n}}function xS(e){if(e.connection){let t=e.connection.ip.indexOf(`:`)>=0;(e.connection.version===4&&t||e.connection.version===6&&!t)&&(e.connection.ip=`0.0.0.0`,e.connection.version=4)}}function SS(e){return typeof e==`number`?e.toFixed(0):e}var CS=`vp8`,wS={audioPreset:My.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Fy.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:CS,backupCodec:!0,preConnectBuffer:!1},TS={deviceId:{ideal:`default`},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},ES={deviceId:{ideal:`default`},resolution:Ny.h720.resolution},DS={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new I_,disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!0},OS={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3},kS;(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`})(kS||={});var AS=class{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}get mode(){return this._mode}constructor(e,t,n){this.peerConnectionTimeout=OS.peerConnectionTimeout,this.log=I,this.updateState=()=>{var e;let t=this.state,n=this.requiredTransports.map(e=>e.getConnectionState());n.every(e=>e===`connected`)?this.state=kS.CONNECTED:n.some(e=>e===`failed`)?this.state=kS.FAILED:n.some(e=>e===`connecting`)?this.state=kS.CONNECTING:n.every(e=>e===`closed`)?this.state=kS.CLOSED:n.some(e=>e===`closed`)?this.state=kS.CLOSING:n.every(e=>e===`new`)&&(this.state=kS.NEW),t!==this.state&&(this.log.debug(`pc state change: from ${kS[t]} to ${kS[this.state]}`,this.logContext),(e=this.onStateChange)==null||e.call(this,this.state,this.publisher.getConnectionState(),this.subscriber?.getConnectionState()))},this.log=M_(t.loggerName??j_.PCManager),this.loggerOptions=t,this.isPublisherConnectionRequired=e!==`subscriber-primary`,this.isSubscriberConnectionRequired=e===`subscriber-primary`,this.publisher=new vS(n,t),this._mode=e,e!==`publisher-only`&&(this.subscriber=new vS(n,t),this.subscriber.onConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.subscriber.onIceCandidate=e=>{var t;(t=this.onIceCandidate)==null||t.call(this,e,hg.SUBSCRIBER)},this.subscriber.onDataChannel=e=>{var t;(t=this.onDataChannel)==null||t.call(this,e)},this.subscriber.onTrack=e=>{var t;(t=this.onTrack)==null||t.call(this,e)}),this.publisher.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=e=>{var t;(t=this.onIceCandidate)==null||t.call(this,e,hg.PUBLISHER)},this.publisher.onTrack=e=>{var t;(t=this.onTrack)==null||t.call(this,e)},this.publisher.onOffer=(e,t)=>{var n;(n=this.onPublisherOffer)==null||n.call(this,e,t)},this.state=kS.NEW,this.connectionLock=new hp,this.remoteOfferLock=new hp}get logContext(){var e;return Object.assign({},(e=this.loggerOptions).loggerContextCb?.call(e))}requirePublisher(){this.isPublisherConnectionRequired=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,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 L(this,void 0,void 0,function*(){if(this.publisher&&this.publisher.getSignallingState()!==`closed`){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 L(this,void 0,void 0,function*(){this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return L(this,void 0,void 0,function*(){t===hg.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber?.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,t){return L(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 n=yield this.remoteOfferLock.lock();try{return(yield this.subscriber?.setRemoteDescription(e,t))?yield this.subscriber?.createAndSetAnswer():void 0}finally{n()}})}updateConfiguration(e,t){var n;this.publisher.setConfiguration(e),(n=this.subscriber)==null||n.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return L(this,void 0,void 0,function*(){let n=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&this.publisher.getConnectionState()!==`connected`&&this.publisher.getConnectionState()!==`connecting`&&(this.log.debug(`negotiation required, start negotiating`,this.logContext),this.publisher.negotiate()),yield Promise.all(this.requiredTransports?.map(n=>this.ensureTransportConnected(n,e,t)))}finally{n()}})}negotiate(e){return L(this,void 0,void 0,function*(){return new iy((t,n)=>L(this,void 0,void 0,function*(){let r=setTimeout(()=>{n(new vy(`negotiation timed out`))},this.peerConnectionTimeout),i=()=>{clearTimeout(r),this.publisher.off(_S.NegotiationStarted,o),e.signal.removeEventListener(`abort`,a)},a=()=>{i(),n(new vy(`negotiation aborted`))},o=()=>{e.signal.aborted||(clearTimeout(r),r=setTimeout(()=>{i(),n(new vy(`negotiation timed out`))},this.peerConnectionTimeout))};e.signal.addEventListener(`abort`,a),this.publisher.on(_S.NegotiationStarted,o),this.publisher.once(_S.NegotiationComplete,()=>{i(),t()}),yield this.publisher.negotiate(e=>{i(),e instanceof Error?n(e):n(Error(String(e)))})}))})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTransceiverOfKind(e,t){return this.publisher.addTransceiverOfKind(e,t)}getMidForReceiver(e){return(this.subscriber?this.subscriber.getTransceivers():this.publisher.getTransceivers()).find(t=>t.receiver===e)?.mid}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===hg.PUBLISHER||e===hg.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){let e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&this.subscriber&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return L(this,arguments,void 0,function(e,t){var n=this;let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return function*(){if(e.getConnectionState()!==`connected`)return new Promise((e,i)=>L(n,void 0,void 0,function*(){let n=()=>{this.log.warn(`abort transport connection`,this.logContext),Ty.clearTimeout(a),i(z.cancelled(`room connection has been cancelled`))};t?.signal.aborted&&n(),t?.signal.addEventListener(`abort`,n);let a=Ty.setTimeout(()=>{t?.signal.removeEventListener(`abort`,n),i(z.internal(`could not establish pc connection`))},r);for(;this.state!==kS.CONNECTED;)if(yield ob(50),t?.signal.aborted){i(z.cancelled(`room connection has been cancelled`));return}Ty.clearTimeout(a),t?.signal.removeEventListener(`abort`,n),e()}))}()})}},jS=5e3,MS=3e4,NS=class e{static fetchRegionSettings(t,n,r){return L(this,void 0,void 0,function*(){let i=yield e.fetchLock.lock();try{let e=yield fetch(`${PS(t)}/regions`,{headers:{authorization:`Bearer ${n}`},signal:r});if(e.ok){let t=ox(e.headers),n=t?t*1e3:jS;return{regionSettings:yield e.json(),updatedAtInMs:Date.now(),maxAgeInMs:n}}else if(e.status===401)throw z.notAllowed(`Could not fetch region settings: ${e.statusText}`,e.status);else throw z.internal(`Could not fetch region settings: ${e.statusText}`)}catch(e){throw e instanceof z?e:r?.aborted?z.cancelled(`Region fetching was aborted`):z.serverUnreachable(`Could not fetch region settings, ${e instanceof Error?`${e.name}: ${e.message}`:e}`)}finally{i()}})}static scheduleRefetch(t,n,r){return L(this,void 0,void 0,function*(){let i=e.settingsTimeouts.get(t.hostname);clearTimeout(i),e.settingsTimeouts.set(t.hostname,setTimeout(()=>L(this,void 0,void 0,function*(){try{let r=yield e.fetchRegionSettings(t,n);e.updateCachedRegionSettings(t,n,r)}catch(i){if(i instanceof z&&i.reason===R.NotAllowed){I.debug(`token is not valid, cancelling auto region refresh`);return}I.debug(`auto refetching of region settings failed`,{error:i}),e.scheduleRefetch(t,n,r)}}),r))})}static updateCachedRegionSettings(t,n,r){e.cache.set(t.hostname,r),e.scheduleRefetch(t,n,r.maxAgeInMs)}static stopRefetch(t){let n=e.settingsTimeouts.get(t);n&&(clearTimeout(n),e.settingsTimeouts.delete(t))}static scheduleCleanup(t){let n=e.connectionTrackers.get(t);n&&(n.cleanupTimeout&&clearTimeout(n.cleanupTimeout),n.cleanupTimeout=setTimeout(()=>{let n=e.connectionTrackers.get(t);n&&n.connectionCount===0&&(I.debug(`stopping region refetch after disconnect delay`,{hostname:t}),e.stopRefetch(t)),n&&(n.cleanupTimeout=void 0)},MS))}static cancelCleanup(t){let n=e.connectionTrackers.get(t);n?.cleanupTimeout&&(clearTimeout(n.cleanupTimeout),n.cleanupTimeout=void 0)}notifyConnected(){let t=this.serverUrl.hostname,n=e.connectionTrackers.get(t);n||(n={connectionCount:0},e.connectionTrackers.set(t,n)),n.connectionCount++,e.cancelCleanup(t)}notifyDisconnected(){let t=this.serverUrl.hostname,n=e.connectionTrackers.get(t);n&&(n.connectionCount=Math.max(0,n.connectionCount-1),n.connectionCount===0&&e.scheduleCleanup(t))}constructor(e,t){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return wb(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(t){return L(this,void 0,void 0,function*(){return e.fetchRegionSettings(this.serverUrl,this.token,t)})}getNextBestRegionUrl(t){return L(this,void 0,void 0,function*(){if(!this.isCloud())throw Error(`region availability is only supported for LiveKit Cloud domains`);let n=e.cache.get(this.serverUrl.hostname);(!n||Date.now()-n.updatedAtInMs>n.maxAgeInMs)&&(n=yield this.fetchRegionSettings(t),e.updateCachedRegionSettings(this.serverUrl,this.token,n));let r=n.regionSettings.regions.filter(e=>!this.attemptedRegions.find(t=>t.url===e.url));if(r.length>0){let e=r[0];return this.attemptedRegions.push(e),I.debug(`next region: ${e.region}`),e.url}else return null})}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(t){e.updateCachedRegionSettings(this.serverUrl,this.token,t)}};NS.cache=new Map,NS.settingsTimeouts=new Map,NS.connectionTrackers=new Map,NS.fetchLock=new hp;function PS(e){return`${e.protocol.replace(`ws`,`http`)}//${e.host}/settings`}var FS=class e extends Error{constructor(t,n,r){super(n),this.code=t,this.message=RS(n,e.MAX_MESSAGE_BYTES),this.data=r?RS(r,e.MAX_DATA_BYTES):void 0}static fromProto(t){return new e(t.code,t.message,t.data)}toProto(){return new Qh({code:this.code,message:this.message,data:this.data})}static builtIn(t,n){return new e(e.ErrorCode[t],e.ErrorMessage[t],n)}};FS.MAX_MESSAGE_BYTES=256,FS.MAX_DATA_BYTES=15360,FS.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},FS.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`};var IS=15360;function LS(e){return new TextEncoder().encode(e).length}function RS(e,t){if(LS(e)<=t)return e;let n=0,r=e.length,i=new TextEncoder;for(;n<r;){let a=Math.floor((n+r+1)/2);i.encode(e.slice(0,a)).length<=t?n=a:r=a-1}return e.slice(0,n)}var zS=2e3;function BS(e,t){if(!t)return 0;let n,r;return`bytesReceived`in e?(n=e.bytesReceived,r=t.bytesReceived):`bytesSent`in e&&(n=e.bytesSent,r=t.bytesSent),n===void 0||r===void 0||e.timestamp===void 0||t.timestamp===void 0?0:(n-r)*8*1e3/(e.timestamp-t.timestamp)}var VS=typeof MediaRecorder<`u`,HS=VS?MediaRecorder:class{constructor(){throw Error(`MediaRecorder is not available in this environment`)}},US=class extends HS{constructor(e,t){if(!VS)throw Error(`MediaRecorder is not available in this environment`);super(new MediaStream([e.mediaStreamTrack]),t);let n,r,i=()=>r===void 0,a=()=>{this.removeEventListener(`dataavailable`,n),this.removeEventListener(`stop`,a),this.removeEventListener(`error`,o),r?.close(),r=void 0},o=e=>{r?.error(e),this.removeEventListener(`dataavailable`,n),this.removeEventListener(`stop`,a),this.removeEventListener(`error`,o),r=void 0};this.byteStream=new ReadableStream({start:e=>{r=e,n=t=>L(this,void 0,void 0,function*(){let n;if(t.data.arrayBuffer){let e=yield t.data.arrayBuffer();n=new Uint8Array(e)}else if(t.data.byteArray)n=t.data.byteArray;else throw Error(`no data available!`);i()||e.enqueue(n)}),this.addEventListener(`dataavailable`,n)},cancel:()=>{a()}}),this.addEventListener(`stop`,a),this.addEventListener(`error`,o)}};function WS(){return VS}var GS=1e3,KS=1e4,qS=class extends K{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(e,t,n){let r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,i=arguments.length>4?arguments[4]:void 0;super(e,t,i),this.manuallyStopped=!1,this.pendingDeviceChange=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch(()=>this.log.debug(`track mute bounce got cancelled by an unmute event`,this.logContext)),this.debouncedTrackMuteHandler=mS(()=>L(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>L(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(U.Ended,this)},this.reacquireTrack=!1,this.providedByUser=r,this.muteLock=new hp,this.pauseUpstreamLock=new hp,this.trackChangeLock=new hp,this.trackChangeLock.lock().then(t=>L(this,void 0,void 0,function*(){try{yield this.setMediaStreamTrack(e,!0)}finally{t()}})),this._constraints=e.getConstraints(),n&&(this._constraints=n)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==K.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(){return this.processor?.processedTrack??this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t,n){return L(this,void 0,void 0,function*(){if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(e=>{nb(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());let r;if(this.processor&&e){if(this.log.debug(`restarting processor`,this.logContext),this.kind===`unknown`)throw TypeError(`cannot set processor on track of unknown kind`);this.processorElement&&(tb(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),r=this.processor.processedTrack}this.sender&&this.sender.transport?.state!==`closed`&&(yield this.sender.replaceTrack(r??e)),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=n?!0:!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(t=>{tb(r??e,t)}))})}waitForDimensions(){return L(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:GS;return function*(){if(e.kind===K.Kind.Audio)throw Error(`cannot get dimensions for audio tracks`);sy()?.os===`iOS`&&(yield ob(10));let n=Date.now();for(;Date.now()-n<t;){let t=e.dimensions;if(t)return t;yield ob(50)}throw new hy(`unable to get track dimensions after timeout`)}()})}setDeviceId(e){return L(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Hb(e)?!0:(this._constraints.deviceId=e,this.isMuted?(this.pendingDeviceChange=!0,!0):(yield this.restartTrack(),Hb(e)===this._mediaStreamTrack.getSettings().deviceId))})}getDeviceId(){return L(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){if(e.source===K.Source.ScreenShare)return;let{deviceId:n,groupId:r}=e._mediaStreamTrack.getSettings(),i=e.kind===K.Kind.Audio?`audioinput`:`videoinput`;return t?Ax.getInstance().normalizeDeviceId(i,n,r):n}()})}mute(){return L(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return L(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return L(this,void 0,void 0,function*(){let n=yield this.trackChangeLock.lock();try{if(!this.sender)throw new hy(`unable to replace an unpublished track`);let n,r;return typeof t==`boolean`?n=t:t!==void 0&&(n=t.userProvidedTrack,r=t.stopProcessor),this.providedByUser=n??!0,this.log.debug(`replace MediaStreamTrack`,this.logContext),yield this.setMediaStreamTrack(e),r&&this.processor&&(yield this.internalStopProcessor()),this}finally{n()}})}restart(e,t){return L(this,void 0,void 0,function*(){this.manuallyStopped=!1;let n=yield this.trackChangeLock.lock();try{e||=this._constraints;let{deviceId:n,facingMode:r}=e,i=L_(e,[`deviceId`,`facingMode`]);this.log.debug(`restarting track with constraints`,Object.assign(Object.assign({},this.logContext),{constraints:e}));let a={audio:!1,video:!1};this.kind===K.Kind.Video?a.video=n||r?{deviceId:n,facingMode:r}:!0:a.audio=n?Object.assign({deviceId:n},i):!0,this.attachedElements.forEach(e=>{nb(this.mediaStreamTrack,e)}),this._mediaStreamTrack.removeEventListener(`ended`,this.handleEnded),this._mediaStreamTrack.stop();let o=(yield navigator.mediaDevices.getUserMedia(a)).getTracks()[0];return this.kind===K.Kind.Video&&(yield o.applyConstraints(i)),o.addEventListener(`ended`,this.handleEnded),this.log.debug(`re-acquired MediaStreamTrack`,this.logContext),yield this.setMediaStreamTrack(o,!1,t),this._constraints=e,this.pendingDeviceChange=!1,this.emit(U.Restarted,this),this.manuallyStopped&&(this.log.warn(`track was stopped during a restart, stopping restarted track`,this.logContext),this.stop()),this}finally{n()}})}setTrackMuted(e){this.log.debug(`setting ${this.kind} track ${e?`muted`:`unmuted`}`,this.logContext),!(this.isMuted===e&&this._mediaStreamTrack.enabled!==e)&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?U.Muted:U.Unmuted,this))}get needsReAcquisition(){return this._mediaStreamTrack.readyState!==`live`||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return L(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),bb()&&(this.log.debug(`visibility changed, is in Background: ${this.isInBackground}`,this.logContext),!this.isInBackground&&this.needsReAcquisition&&!this.isUserProvided&&!this.isMuted&&(this.log.debug(`track needs to be reacquired, restarting ${this.source}`,this.logContext),yield this.restart(),this.reacquireTrack=!1))})}stop(){var e;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener(`ended`,this.handleEnded),this._mediaStreamTrack.removeEventListener(`mute`,this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener(`unmute`,this.handleTrackUnmuteEvent),(e=this.processor)==null||e.destroy(),this.processor=void 0}pauseUpstream(){return L(this,void 0,void 0,function*(){let e=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!0)return;if(!this.sender){this.log.warn(`unable to pause upstream for an unpublished track`,this.logContext);return}this._isUpstreamPaused=!0,this.emit(U.UpstreamPaused,this);let e=sy();if(e?.name===`Safari`&&kb(e.version,`12.0`)<0)throw new my(`pauseUpstream is not supported on Safari < 12.`);this.sender.transport?.state!==`closed`&&(yield this.sender.replaceTrack(null))}finally{e()}})}resumeUpstream(){return L(this,void 0,void 0,function*(){let e=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!1)return;if(!this.sender){this.log.warn(`unable to resume upstream for an unpublished track`,this.logContext);return}this._isUpstreamPaused=!1,this.emit(U.UpstreamResumed,this),this.sender.transport?.state!==`closed`&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{e()}})}getRTCStatsReport(){return L(this,void 0,void 0,function*(){if(this.sender?.getStats)return yield this.sender.getStats()})}setProcessor(e){return L(this,arguments,void 0,function(e){var t=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){let r=yield t.trackChangeLock.lock();try{t.log.debug(`setting up processor`,t.logContext);let r=document.createElement(t.kind),i={kind:t.kind,track:t._mediaStreamTrack,element:r,audioContext:t.audioContext};if(yield e.init(i),t.log.debug(`processor initialized`,t.logContext),t.processor&&(yield t.internalStopProcessor()),t.kind===`unknown`)throw TypeError(`cannot set processor on track of unknown kind`);if(tb(t._mediaStreamTrack,r),r.muted=!0,r.play().catch(e=>{e instanceof DOMException&&e.name===`AbortError`?(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&&n&&(nb(t._mediaStreamTrack,e),tb(t.processor.processedTrack,e));yield t.sender?.replaceTrack(t.processor.processedTrack)}t.emit(U.TrackProcessorUpdate,t.processor)}finally{r()}}()})}getProcessor(){return this.processor}stopProcessor(){return L(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){let n=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(t)}finally{n()}}()})}internalStopProcessor(){return L(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var n,r;e.processor&&(e.log.debug(`stopping processor`,e.logContext),(n=e.processor.processedTrack)==null||n.stop(),yield e.processor.destroy(),e.processor=void 0,t||((r=e.processorElement)==null||r.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(U.TrackProcessorUpdate))}()})}startPreConnectBuffer(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:100;if(!WS()){this.log.warn(`MediaRecorder is not available, cannot start preconnect buffer`,this.logContext);return}if(this.localTrackRecorder){this.log.warn(`preconnect buffer already started`);return}else{let e=`audio/webm;codecs=opus`;MediaRecorder.isTypeSupported(e)||(e=`video/mp4`),this.localTrackRecorder=new US(this,{mimeType:e})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn(`preconnect buffer timed out, stopping recording automatically`,this.logContext),this.stopPreConnectBuffer()},KS)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&=(this.localTrackRecorder.stop(),void 0)}getPreConnectBuffer(){return this.localTrackRecorder?.byteStream}getPreConnectBufferMimeType(){return this.localTrackRecorder?.mimeType}},JS=class extends qS{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0,i=arguments.length>4?arguments[4]:void 0;super(e,K.Kind.Audio,t,n,i),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>L(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let e;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=BS(e,this.prevStats)),this.prevStats=e}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug(`Krisp noise filter enabled`,this.logContext),this.emit(U.AudioTrackFeatureUpdate,this,wh.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug(`Krisp noise filter disabled`,this.logContext),this.emit(U.AudioTrackFeatureUpdate,this,wh.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=r,this.checkForSilence()}mute(){let e=Object.create(null,{mute:{get:()=>super.mute}});return L(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug(`Track already muted`,this.logContext),this):(this.source===K.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 L(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{return this.isMuted?(this.source===K.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState===`ended`||this.pendingDeviceChange)&&!this.isUserProvided&&(this.log.debug(`reacquiring mic track`,this.logContext),yield this.restart(void 0,!0)),yield e.unmute.call(this),this):(this.log.debug(`Track already unmuted`,this.logContext),this)}finally{t()}})}restartTrack(e){return L(this,void 0,void 0,function*(){let t;if(e){let n=Ry({audio:e});typeof n.audio!=`boolean`&&(t=n.audio)}yield this.restart(t)})}restart(e,t){let n=Object.create(null,{restart:{get:()=>super.restart}});return L(this,void 0,void 0,function*(){let r=yield n.restart.call(this,e,t);return this.checkForSilence(),r})}startMonitor(){Sb()&&(this.monitorInterval||=setInterval(()=>{this.monitorSender()},zS))}setProcessor(e){return L(this,void 0,void 0,function*(){let t=yield this.trackChangeLock.lock();try{if(!Cb()&&!this.audioContext)throw Error(`Audio context needs to be set on LocalAudioTrack in order to enable processors`);this.processor&&(yield this.internalStopProcessor());let t={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug(`setting up audio processor ${e.name}`,this.logContext),yield e.init(t),this.processor=e,this.processor.processedTrack&&(yield this.sender?.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(U.TrackProcessorUpdate,this.processor)}finally{t()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return L(this,void 0,void 0,function*(){if(!this.sender?.getStats)return;let e=yield this.sender.getStats(),t;return e.forEach(e=>{e.type===`outbound-rtp`&&(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 L(this,void 0,void 0,function*(){let e=yield zy(this);return e&&(this.isMuted||this.log.debug(`silence detected on local audio track`,this.logContext),this.emit(U.AudioSilenceDetected)),e})}};function YS(e,t,n){switch(e.kind){case`audio`:return new JS(e,t,!1,void 0,n);case`video`:return new pC(e,t,!1,n);default:throw new hy(`unsupported track type: ${e.kind}`)}}var XS=Object.values(Ny),ZS=Object.values(Py),QS=Object.values(Fy),$S=[Ny.h180,Ny.h360],eC=[Py.h180,Py.h360],tC=e=>[{scaleResolutionDownBy:2,fps:e.encoding.maxFramerate}].map(t=>new W(Math.floor(e.width/t.scaleResolutionDownBy),Math.floor(e.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(e.encoding.maxBitrate/(t.scaleResolutionDownBy**2*((e.encoding.maxFramerate??30)/(t.fps??30))))),t.fps,e.encoding.priority)),nC=[`q`,`h`,`f`];function rC(e,t,n,r){let i=r?.videoEncoding;e&&(i=r?.screenShareEncoding);let a=r?.simulcast,o=r?.scalabilityMode,s=r?.videoCodec;if(!i&&!a&&!o||!t||!n)return[{}];i||(i=aC(e,t,n,s),I.debug(`using video encoding`,i));let c=i.maxFramerate,l=new W(t,n,i.maxBitrate,i.maxFramerate,i.priority);if(o&&db(s)){let e=new uC(o),t=[];if(e.spatial>3)throw Error(`unsupported scalabilityMode: ${o}`);let n=sy();if(_b()||Cb()||n?.name===`Chrome`&&kb(n?.version,`113`)<0){let r=e.suffix==`h`?2:3,a=yb(n);for(let n=0;n<e.spatial;n+=1)t.push({rid:nC[2-n],maxBitrate:i.maxBitrate/r**+n,maxFramerate:l.encoding.maxFramerate,scaleResolutionDownBy:a?2**n:void 0});t[0].scalabilityMode=o}else t.push({maxBitrate:i.maxBitrate,maxFramerate:l.encoding.maxFramerate,scalabilityMode:o});return l.encoding.priority&&(t[0].priority=l.encoding.priority,t[0].networkPriority=l.encoding.priority),I.debug(`using svc encoding`,{encodings:t}),t}if(!a)return[i];let u=[];u=e?lC(r?.screenShareSimulcastLayers)??sC(e,l):lC(r?.videoSimulcastLayers)??sC(e,l);let d;if(u.length>0){let e=u[0];u.length>1&&([,d]=u);let r=Math.max(t,n);if(r>=960&&d)return cC(t,n,[e,d,l],c);if(r>=480)return cC(t,n,[e,l],c)}return cC(t,n,[l])}function iC(e,t,n){if(!n.backupCodec||n.backupCodec===!0||n.backupCodec.codec===n.videoCodec)return;t!==n.backupCodec.codec&&I.warn(`requested a different codec than specified as backup`,{serverRequested:t,backup:n.backupCodec.codec}),n.videoCodec=t,n.videoEncoding=n.backupCodec.encoding;let r=e.mediaStreamTrack.getSettings(),i=r.width??e.dimensions?.width,a=r.height??e.dimensions?.height;return e.source===K.Source.ScreenShare&&n.simulcast&&(n.simulcast=!1),rC(e.source===K.Source.ScreenShare,i,a,n)}function aC(e,t,n,r){let i=oC(e,t,n),{encoding:a}=i[0],o=Math.max(t,n);for(let e=0;e<i.length;e+=1){let t=i[e];if(a=t.encoding,t.width>=o)break}if(r)switch(r){case`av1`:case`h265`:a=Object.assign({},a),a.maxBitrate*=.7;break;case`vp9`:a=Object.assign({},a),a.maxBitrate*=.85;break}return a}function oC(e,t,n){if(e)return QS;let r=t>n?t/n:n/t;return Math.abs(r-16/9)<Math.abs(r-4/3)?XS:ZS}function sC(e,t){if(e)return tC(t);let{width:n,height:r}=t,i=n>r?n/r:r/n;return Math.abs(i-16/9)<Math.abs(i-4/3)?$S:eC}function cC(e,t,n,r){let i=[];if(n.forEach((n,a)=>{if(a>=nC.length)return;let o=Math.min(e,t),s={rid:nC[a],scaleResolutionDownBy:Math.max(1,o/Math.min(n.width,n.height)),maxBitrate:n.encoding.maxBitrate},c=r&&n.encoding.maxFramerate?Math.min(r,n.encoding.maxFramerate):n.encoding.maxFramerate;c&&(s.maxFramerate=c);let l=mb()||a===0;n.encoding.priority&&l&&(s.priority=n.encoding.priority,s.networkPriority=n.encoding.priority),i.push(s)}),Cb()&&Db()===`ios`){let e;i.forEach(t=>{e?t.maxFramerate&&t.maxFramerate>e&&(e=t.maxFramerate):e=t.maxFramerate});let t=!0;i.forEach(n=>{n.maxFramerate!=e&&(t&&(t=!1,I.info(`Simulcast on iOS React-Native requires all encodings to share the same framerate.`)),I.info(`Setting framerate of encoding "${n.rid??``}" to ${e}`),n.maxFramerate=e)})}return i}function lC(e){if(e)return e.sort((e,t)=>{let{encoding:n}=e,{encoding:r}=t;return n.maxBitrate>r.maxBitrate?1:n.maxBitrate<r.maxBitrate?-1:n.maxBitrate===r.maxBitrate&&n.maxFramerate&&r.maxFramerate?n.maxFramerate>r.maxFramerate?1:-1:0})}var uC=class{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(){return`L${this.spatial}T${this.temporal}${this.suffix??``}`}};function dC(e){return e.source===K.Source.ScreenShare||e.constraints.height&&Hb(e.constraints.height)>=1080?`maintain-resolution`:`balanced`}var fC=5e3,pC=class extends qS{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0;super(e,K.Kind.Video,t,n,r),this.simulcastCodecs=new Map,this.degradationPreference=`balanced`,this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>L(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let e;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])),n=e.some(e=>e.qualityLimitationReason===`cpu`);if(n!==this.isCpuConstrained&&(this.isCpuConstrained=n,this.isCpuConstrained&&this.emit(U.CpuConstrained)),this.prevStats){let e=0;t.forEach((t,n)=>{let r=this.prevStats?.get(n);e+=BS(t,r)}),this._currentBitrate=e}this.prevStats=t}),this.senderLock=new hp}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){if(this.signalClient=e,!Sb())return;let t=this.sender?.getParameters();t&&(this.encodings=t.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},zS))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){let e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return L(this,void 0,void 0,function*(){var t,n,r,i;yield e.pauseUpstream.call(this);try{for(var a=!0,o=H_(this.simulcastCodecs.values()),s;s=yield o.next(),t=s.done,!t;a=!0)i=s.value,a=!1,yield i.sender?.replaceTrack(null)}catch(e){n={error:e}}finally{try{!a&&!t&&(r=o.return)&&(yield r.call(o))}finally{if(n)throw n.error}}})}resumeUpstream(){let e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return L(this,void 0,void 0,function*(){var t,n,r,i;yield e.resumeUpstream.call(this);try{for(var a=!0,o=H_(this.simulcastCodecs.values()),s;s=yield o.next(),t=s.done,!t;a=!0){i=s.value,a=!1;let e=i;yield e.sender?.replaceTrack(e.mediaStreamTrack)}}catch(e){n={error:e}}finally{try{!a&&!t&&(r=o.return)&&(yield r.call(o))}finally{if(n)throw n.error}}})}mute(){let e=Object.create(null,{mute:{get:()=>super.mute}});return L(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug(`Track already muted`,this.logContext),this):(this.source===K.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 L(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{return this.isMuted?(this.source===K.Source.Camera&&!this.isUserProvided&&(this.log.debug(`reacquiring camera track`,this.logContext),yield this.restart(void 0,!0)),yield e.unmute.call(this),this):(this.log.debug(`Track already unmuted`,this.logContext),this)}finally{t()}})}setTrackMuted(e){super.setTrackMuted(e);for(let t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return L(this,void 0,void 0,function*(){if(!this.sender?.getStats)return[];let e=[],t=yield this.sender.getStats();return t.forEach(n=>{if(n.type===`outbound-rtp`){let r={type:`video`,streamId:n.id,frameHeight:n.frameHeight,frameWidth:n.frameWidth,framesPerSecond:n.framesPerSecond,framesSent:n.framesSent,firCount:n.firCount,pliCount:n.pliCount,nackCount:n.nackCount,packetsSent:n.packetsSent,bytesSent:n.bytesSent,qualityLimitationReason:n.qualityLimitationReason,qualityLimitationDurations:n.qualityLimitationDurations,qualityLimitationResolutionChanges:n.qualityLimitationResolutionChanges,rid:n.rid??n.id,retransmittedPacketsSent:n.retransmittedPacketsSent,targetBitrate:n.targetBitrate,timestamp:n.timestamp},i=t.get(n.remoteId);i&&(r.jitter=i.jitter,r.packetsLost=i.packetsLost,r.roundTripTime=i.roundTripTime),e.push(r)}}),e.sort((e,t)=>(t.frameWidth??0)-(e.frameWidth??0)),e})}setPublishingQuality(e){let t=[];for(let n=eb.LOW;n<=eb.HIGH;n+=1)t.push(new $g({quality:n,enabled:n<=e}));this.log.debug(`setting publishing quality. max quality ${e}`,this.logContext),this.setPublishingLayers(db(this.codec),t)}restartTrack(e){return L(this,void 0,void 0,function*(){var t,n,r,i;let a;if(e){let t=Ry({video:e});typeof t.video!=`boolean`&&(a=t.video)}yield this.restart(a),this.isCpuConstrained=!1;try{for(var o=!0,s=H_(this.simulcastCodecs.values()),c;c=yield s.next(),t=c.done,!t;o=!0){i=c.value,o=!1;let e=i;e.sender&&e.sender.transport?.state!==`closed`&&(e.mediaStreamTrack=this.mediaStreamTrack.clone(),yield e.sender.replaceTrack(e.mediaStreamTrack))}}catch(e){n={error:e}}finally{try{!o&&!t&&(r=s.return)&&(yield r.call(s))}finally{if(n)throw n.error}}})}setProcessor(e){let t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return L(this,arguments,void 0,function(e){var n=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var i,a,o,s;if(yield t.setProcessor.call(n,e,r),n.processor?.processedTrack)try{for(var c=!0,l=H_(n.simulcastCodecs.values()),u;u=yield l.next(),i=u.done,!i;c=!0)s=u.value,c=!1,yield s.sender?.replaceTrack(n.processor.processedTrack)}catch(e){a={error:e}}finally{try{!c&&!i&&(o=l.return)&&(yield o.call(l))}finally{if(a)throw a.error}}}()})}setDegradationPreference(e){return L(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug(`setting degradationPreference to ${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(`${e} already added, skipping adding simulcast codec`,this.logContext);return}let n={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,n),n}setSimulcastTrackSender(e,t){let n=this.simulcastCodecs.get(e);n&&(n.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},fC))}setPublishingCodecs(e){return L(this,void 0,void 0,function*(){var t,n,r,i,a,o,s;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(db(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;let c=[];try{for(t=!0,n=H_(e);r=yield n.next(),i=r.done,!i;t=!0){s=r.value,t=!1;let e=s;if(!this.codec||this.codec===e.codec)yield this.setPublishingLayers(db(e.codec),e.qualities);else{let t=this.simulcastCodecs.get(e.codec);if(this.log.debug(`try setPublishingCodec for ${e.codec}`,Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:t})),!t||!t.sender){for(let t of e.qualities)if(t.enabled){c.push(e.codec);break}}else t.encodings&&(this.log.debug(`try setPublishingLayersForSender ${e.codec}`,this.logContext),yield mC(t.sender,t.encodings,e.qualities,this.senderLock,db(e.codec),this.log,this.logContext))}}}catch(e){a={error:e}}finally{try{!t&&!i&&(o=n.return)&&(yield o.call(n))}finally{if(a)throw a.error}}return c})}setPublishingLayers(e,t){return L(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 mC(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext))})}prioritizePerformance(){return L(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)=>Object.assign(Object.assign({},e),{active:t===0,scaleResolutionDownBy:Math.max(1,Math.ceil((this.mediaStreamTrack.getSettings().height??360)/360)),scalabilityMode:t===0&&db(this.codec)?`L1T3`:void 0,maxFramerate:t===0?15:0,maxBitrate:t===0?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 L(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),bb()&&this.isInBackground&&this.source===K.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}};function mC(e,t,n,r,i,a,o){return L(this,void 0,void 0,function*(){let s=yield r.lock();a.debug(`setPublishingLayersForSender`,Object.assign(Object.assign({},o),{sender:e,qualities:n,senderEncodings:t}));try{let r=e.getParameters(),{encodings:s}=r;if(!s)return;if(s.length!==t.length){a.warn(`cannot set publishing layers, encodings mismatch`,Object.assign(Object.assign({},o),{encodings:s,senderEncodings:t}));return}let c=!1;i&&n.some(e=>e.enabled)&&n.forEach(e=>e.enabled=!0),s.forEach((e,r)=>{let i=e.rid??``;i===``&&(i=`q`);let s=hC(i),l=n.find(e=>e.quality===s);l&&e.active!==l.enabled&&(c=!0,e.active=l.enabled,a.debug(`setting layer ${l.quality} to ${e.active?`enabled`:`disabled`}`,o),mb()&&(l.enabled?(e.scaleResolutionDownBy=t[r].scaleResolutionDownBy,e.maxBitrate=t[r].maxBitrate,e.maxFrameRate=t[r].maxFrameRate):(e.scaleResolutionDownBy=4,e.maxBitrate=10,e.maxFrameRate=2)))}),c&&(r.encodings=s,a.debug(`setting encodings`,Object.assign(Object.assign({},o),{encodings:r.encodings})),yield e.setParameters(r))}finally{s()}})}function hC(e){switch(e){case`f`:return eb.HIGH;case`h`:return eb.MEDIUM;case`q`:return eb.LOW;default:return eb.HIGH}}function gC(e,t,n,r){if(!n)return[new Ih({quality:eb.HIGH,width:e,height:t,bitrate:0,ssrc:0})];if(r){let r=n[0].scalabilityMode,i=new uC(r),a=[],o=i.suffix==`h`?1.5:2,s=i.suffix==`h`?2:3;for(let r=0;r<i.spatial;r+=1)a.push(new Ih({quality:Math.min(eb.HIGH,i.spatial-1)-r,width:Math.ceil(e/o**+r),height:Math.ceil(t/o**+r),bitrate:n[0].maxBitrate?Math.ceil(n[0].maxBitrate/s**+r):0,ssrc:0}));return a}return n.map(n=>{let r=n.scaleResolutionDownBy??1;return new Ih({quality:hC(n.rid??``),width:Math.ceil(e/r),height:Math.ceil(t/r),bitrate:n.maxBitrate??0,ssrc:0})})}var _C=`_lossy`,vC=`_reliable`,yC=`_data_track`,bC=2*1e3,xC=`leave-reconnect`,SC=3e4,CC=8*1024,wC=256*1024,TC=3,EC=3,DC;(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`})(DC||={});var J;(function(e){e[e.RELIABLE=0]=`RELIABLE`,e[e.LOSSY=1]=`LOSSY`,e[e.DATA_TRACK_LOSSY=2]=`DATA_TRACK_LOSSY`})(J||={});var OC=class extends K_.EventEmitter{get isClosed(){return this._isClosed}get isNewlyCreated(){return this._isNewlyCreated}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=OS.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=DC.New,this._isClosed=!0,this._isNewlyCreated=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.log=I,this.reliableDataSequence=1,this.reliableMessageBuffer=new $x,this.reliableReceivedState=new eS(SC),this.lossyDataStatCurrentBytes=0,this.lossyDataStatByterate=0,this.lossyDataDropCount=0,this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.handleDataChannel=e=>L(this,[e],void 0,function(e){var t=this;let{channel:n}=e;return function*(){if(!n)return;let e;if(n.label===vC)t.reliableDCSub=n,e=t.handleDataMessage;else if(n.label===_C)t.lossyDCSub=n,e=t.handleDataMessage;else if(n.label===yC)t.dataTrackDCSub=n,e=t.handleDataTrackMessage;else return;t.log.debug(`on data channel ${n.id}, ${n.label}`,t.logContext),n.onmessage=e}()}),this.handleDataMessage=e=>L(this,void 0,void 0,function*(){let t=yield this.dataProcessLock.lock();try{let t;if(e.data instanceof ArrayBuffer)t=e.data;else if(e.data instanceof Blob)t=yield e.data.arrayBuffer();else{this.log.error(`unsupported data type`,Object.assign(Object.assign({},this.logContext),{data:e.data}));return}let n=Rh.fromBinary(new Uint8Array(t));if(n.sequence>0&&n.participantSid!==``){let e=this.reliableReceivedState.get(n.participantSid);if(e&&n.sequence<=e)return;this.reliableReceivedState.set(n.participantSid,n.sequence)}if(n.value?.case===`speaker`)this.emit(H.ActiveSpeakersUpdate,n.value.value.speakers);else if(n.value?.case===`encryptedPacket`){if(!this.e2eeManager){this.log.error(`Received encrypted packet but E2EE not set up`,this.logContext);return}let e=yield this.e2eeManager?.handleEncryptedData(n.value.value.encryptedValue,n.value.value.iv,n.participantIdentity,n.value.value.keyIndex),t=new Rh({value:Vh.fromBinary(e.payload).value,participantIdentity:n.participantIdentity,participantSid:n.participantSid});t.value?.case===`user`&&kC(t,t.value.value),this.emit(H.DataPacketReceived,t,n.value.value.encryptionType)}else n.value?.case===`user`&&kC(n,n.value.value),this.emit(H.DataPacketReceived,n,F.NONE)}finally{t()}}),this.handleDataTrackMessage=e=>L(this,void 0,void 0,function*(){let t;if(e.data instanceof ArrayBuffer)t=e.data;else if(e.data instanceof Blob)t=yield e.data.arrayBuffer();else{this.log.error(`unsupported data type`,Object.assign(Object.assign({},this.logContext),{data:e.data}));return}this.emit(`dataTrackPacketReceived`,new Uint8Array(t))}),this.handleDataError=e=>{let t=e.currentTarget.maxRetransmits===0?`lossy`:`reliable`;if(e instanceof ErrorEvent&&e.error){let{error:n}=e.error;this.log.error(`DataChannel error on ${t}: ${e.message}`,Object.assign(Object.assign({},this.logContext),{error:n}))}else this.log.error(`Unknown DataChannel error on ${t}`,Object.assign(Object.assign({},this.logContext),{event:e}))},this.handleBufferedAmountLow=e=>{this.updateAndEmitDCBufferStatus(e)},this.handleDisconnect=(e,t)=>{if(this._isClosed)return;this.log.warn(`${e} disconnected`,this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());let n=e=>{this.log.warn(`could not recover connection after ${this.reconnectAttempts} attempts, ${e}ms. giving up`,this.logContext),this.emit(H.Disconnected),this.close()},r=Date.now()-this.reconnectStart,i=this.getNextRetryDelay({elapsedMs:r,retryCount:this.reconnectAttempts});if(i===null){n(r);return}e===xC&&(i=0),this.log.debug(`reconnecting in ${i}ms`,this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=Ty.setTimeout(()=>this.attemptReconnect(t).finally(()=>this.reconnectTimeout=void 0),i)},this.waitForRestarted=()=>new Promise((e,t)=>{this.pcState===DC.Connected&&e();let n=()=>{this.off(H.Disconnected,r),e()},r=()=>{this.off(H.Restarted,n),t()};this.once(H.Restarted,n),this.once(H.Disconnected,r)}),this.updateAndEmitDCBufferStatus=e=>{if(e===J.RELIABLE){let t=this.dataChannelForKind(e);t&&this.reliableMessageBuffer.alignBufferedAmount(t.bufferedAmount)}let t=this.isBufferStatusLow(e);t!==void 0&&t!==this.dcBufferStatus.get(e)&&(this.dcBufferStatus.set(e,t),this.emit(H.DCBufferStatusChanged,t,e))},this.isBufferStatusLow=e=>{let t=this.dataChannelForKind(e);if(t)return t.bufferedAmount<=t.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>L(this,void 0,void 0,function*(){this.url&&(yield fetch(Wb(this.url),{method:`HEAD`}).then(e=>e.ok).catch(()=>!1))&&(this.log.info(`detected network reconnected`),(this.client.currentState===q.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===q.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(Sh.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))}),this.handleBrowserOffline=()=>L(this,void 0,void 0,function*(){if(this.url)try{yield Promise.race([fetch(Wb(this.url),{method:`HEAD`}),ob(4e3).then(()=>Promise.reject())])}catch{window.navigator.onLine===!1&&(this.log.info(`detected network interruption`),this.isWaitingForNetworkReconnect=!0)}}),this.log=M_(e.loggerName??j_.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new Jx(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new hp,this.dataProcessLock=new hp,this.dcBufferStatus=new Map([[J.RELIABLE,!0],[J.LOSSY,!0],[J.DATA_TRACK_LOSSY,!0]]),this.client.onParticipantUpdate=e=>this.emit(H.ParticipantUpdate,e),this.client.onConnectionQuality=e=>this.emit(H.ConnectionQualityUpdate,e),this.client.onRoomUpdate=e=>this.emit(H.RoomUpdate,e),this.client.onSubscriptionError=e=>this.emit(H.SubscriptionError,e),this.client.onSubscriptionPermissionUpdate=e=>this.emit(H.SubscriptionPermissionUpdate,e),this.client.onSpeakersChanged=e=>this.emit(H.SpeakersChanged,e),this.client.onStreamStateUpdate=e=>this.emit(H.StreamStateChanged,e),this.client.onRequestResponse=e=>this.emit(H.SignalRequestResponse,e),this.client.onParticipantUpdate=e=>this.emit(H.ParticipantUpdate,e),this.client.onJoined=e=>this.emit(H.Joined,e)}get logContext(){return{room:this.latestJoinResponse?.room?.name,roomID:this.latestJoinResponse?.room?.sid,participant:this.latestJoinResponse?.participant?.identity,participantID:this.participantSid}}join(e,t,n,r){return L(this,arguments,void 0,function(e,t,n,r){var i=this;let a=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return function*(){var o;i._isNewlyCreated=!1,i.url=e,i.token=t,i.signalOpts=n,i.maxJoinAttempts=n.maxRetries;try{i.joinAttempts+=1,i.setupSignalClientCallbacks();let s;if(!a&&sx()){i.pcManager||(yield i.configure(),i.createDataChannels(),i.addMediaSections(TC,EC));let e=yield i.pcManager?.publisher.createInitialOffer();e&&(s=Xx(e.offer,e.offerId))}if(r?.aborted)throw z.cancelled(`Connection aborted`);let c=yield i.client.join(e,t,n,r,a,s);return i._isClosed=!1,i.latestJoinResponse=c,i.participantSid=c.participant?.sid,i.subscriberPrimary=c.subscriberPrimary,!a&&sx()?(o=i.pcManager)==null||o.updateConfiguration(i.makeRTCConfiguration(c)):(i.pcManager||(yield i.configure(c,!a)),(!i.subscriberPrimary||c.fastPublish)&&i.negotiate().catch(e=>{I.error(e,i.logContext)})),i.registerOnLineListener(),i.clientConfiguration=c.clientConfiguration,i.emit(H.SignalConnected,c),c}catch(o){if(o instanceof z){if(o.reason===R.ServerUnreachable){if(i.log.warn(`Couldn't connect to server, attempt ${i.joinAttempts} of ${i.maxJoinAttempts}`,i.logContext),i.joinAttempts<i.maxJoinAttempts)return i.join(e,t,n,r,a)}else if(o.reason===R.ServiceNotFound)return i.log.warn(`Initial connection failed: ${o.message} – Retrying`),i.join(e,t,n,r,!0)}throw o}}()})}close(){return L(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(H.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return L(this,void 0,void 0,function*(){yield this.pcManager?.close(),this.pcManager=void 0;let e=e=>{e&&(e.close(),e.onbufferedamountlow=null,e.onclose=null,e.onclosing=null,e.onerror=null,e.onmessage=null,e.onopen=null)};e(this.lossyDC),e(this.lossyDCSub),e(this.reliableDC),e(this.reliableDCSub),e(this.dataTrackDC),e(this.dataTrackDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.dataTrackDC=void 0,this.dataTrackDCSub=void 0,this.reliableMessageBuffer=new $x,this.reliableDataSequence=1,this.reliableReceivedState.clear()})}cleanupLossyDataStats(){this.lossyDataStatByterate=0,this.lossyDataStatCurrentBytes=0,this.lossyDataStatInterval&&=(clearInterval(this.lossyDataStatInterval),void 0),this.lossyDataDropCount=0}cleanupClient(){return L(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new hy(`a track with the same ID has already been published`);return new Promise((t,n)=>{let r=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],n(z.timeout(`publication of local track timed out, no response from server`))},1e4);this.pendingTrackResolvers[e.cid]={resolve:e=>{clearTimeout(r),t(e)},reject:()=>{clearTimeout(r),n(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(){return this.reliableDCSub?.readyState}getConnectedServerAddress(){return L(this,void 0,void 0,function*(){return this.pcManager?.getConnectedAddress()})}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e,t){return L(this,void 0,void 0,function*(){if(!(this.pcManager&&this.pcManager.currentState!==kS.NEW)){if(e){this.participantSid=e.participant?.sid;let n=this.makeRTCConfiguration(e);this.pcManager=new AS(t?`publisher-only`:e.subscriberPrimary?`subscriber-primary`:`publisher-primary`,this.loggerOptions,n)}else{let e=this.makeRTCConfiguration();this.pcManager=new AS(`publisher-only`,this.loggerOptions,e)}this.emit(H.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=(e,t,n)=>L(this,void 0,void 0,function*(){if(this.log.debug(`primary PC state changed ${e}`,this.logContext),[`closed`,`disconnected`,`failed`].includes(t)&&(this.publisherConnectionPromise=void 0),e===kS.CONNECTED){let e=this.pcState===DC.New;this.pcState=DC.Connected,e&&this.emit(H.Connected,this.latestJoinResponse)}else e===kS.FAILED&&(this.pcState===DC.Connected||this.pcState===DC.Reconnecting)&&(this.pcState=DC.Disconnected,this.handleDisconnect(`peerconnection failed`,n===`failed`?Sh.RR_SUBSCRIBER_FAILED:Sh.RR_PUBLISHER_FAILED));let r=this.client.isDisconnected||this.client.currentState===q.RECONNECTING,i=[kS.FAILED,kS.CLOSING,kS.CLOSED].includes(e);r&&i&&!this._isClosed&&this.emit(H.Offline)}),this.pcManager.onTrack=e=>{e.streams.length!==0&&this.emit(H.MediaTrackAdded,e.track,e.streams[0],e.receiver)}}})}setupSignalClientCallbacks(){this.client.onAnswer=(e,t,n)=>L(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug(`received server answer`,Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,midToTrackId:n})),this.midToTrackId=n,yield this.pcManager.setPublisherAnswer(e,t))}),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.debug(`got ICE candidate from peer`,Object.assign(Object.assign({},this.logContext),{candidate:e,target:t})),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=(e,t,n)=>L(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;this.midToTrackId=n;let r=yield this.pcManager.createSubscriberAnswerFromOffer(e,t);r&&this.client.sendAnswer(r,t)}),this.client.onLocalTrackPublished=e=>{if(this.log.debug(`received trackPublishedResponse`,Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:e.track?.sid})),!this.pendingTrackResolvers[e.cid]){this.log.error(`missing track resolver for ${e.cid}`,Object.assign(Object.assign({},this.logContext),{cid:e.cid}));return}let{resolve:t}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],t(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(H.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(H.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{var t;this.token=e,(t=this.regionUrlProvider)==null||t.updateToken(e)},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(H.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(H.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{this.participantSid=e.participant?.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=e.room),this.emit(H.RoomMoved,e)},this.client.onMediaSectionsRequirement=e=>{this.addMediaSections(e.numAudios,e.numVideos),this.negotiate()},this.client.onPublishDataTrackResponse=e=>{this.emit(H.PublishDataTrackResponse,e)},this.client.onUnPublishDataTrackResponse=e=>{this.emit(H.UnPublishDataTrackResponse,e)},this.client.onDataTrackSubscriberHandles=e=>{this.emit(H.DataTrackSubscriberHandles,e)},this.client.onClose=()=>{this.handleDisconnect(`signal`,Sh.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.debug(`client leave request`,Object.assign(Object.assign({},this.logContext),{reason:e?.reason})),e.regions&&this.regionUrlProvider&&(this.log.debug(`updating regions`,this.logContext),this.regionUrlProvider.setServerReportedRegions({updatedAtInMs:Date.now(),maxAgeInMs:jS,regionSettings:e.regions})),e.action){case Ug.DISCONNECT:this.emit(H.Disconnected,e?.reason),this.close();break;case Ug.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(xC);break;case Ug.RESUME:this.handleDisconnect(xC)}}}makeRTCConfiguration(e){let t=Object.assign({},this.rtcConfig);if(this.signalOpts?.e2eeEnabled&&(this.log.debug(`E2EE - setting up transports with insertable streams`,this.logContext),t.encodedInsertableStreams=!0),t.sdpSemantics=`unified-plan`,t.continualGatheringPolicy=`gather_continually`,!e)return t;if(e.iceServers&&!t.iceServers){let n=[];e.iceServers.forEach(e=>{let t={urls:e.urls};e.username&&(t.username=e.username),e.credential&&(t.credential=e.credential),n.push(t)}),t.iceServers=n}return e.clientConfiguration&&e.clientConfiguration.forceRelay===bh.ENABLED&&(t.iceTransportPolicy=`relay`),t}addMediaSections(e,t){var n,r;let i={direction:`recvonly`};for(let t=0;t<e;t++)(n=this.pcManager)==null||n.addPublisherTransceiverOfKind(`audio`,i);for(let e=0;e<t;e++)(r=this.pcManager)==null||r.addPublisherTransceiverOfKind(`video`,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.dataTrackDC&&(this.dataTrackDC.onmessage=null,this.dataTrackDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(_C,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(vC,{ordered:!0}),this.dataTrackDC=this.pcManager.createPublisherDataChannel(yC,{ordered:!1,maxRetransmits:0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.dataTrackDC.onmessage=this.handleDataTrackMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.dataTrackDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.dataTrackDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=()=>this.handleBufferedAmountLow(J.LOSSY),this.reliableDC.onbufferedamountlow=()=>this.handleBufferedAmountLow(J.RELIABLE),this.dataTrackDC.onbufferedamountlow=()=>this.handleBufferedAmountLow(J.DATA_TRACK_LOSSY),this.cleanupLossyDataStats(),this.lossyDataStatInterval=setInterval(()=>{this.lossyDataStatByterate=this.lossyDataStatCurrentBytes,this.lossyDataStatCurrentBytes=0;let e=this.dataChannelForKind(J.LOSSY);if(e){let t=this.lossyDataStatByterate/10;e.bufferedAmountLowThreshold=Math.min(Math.max(t,CC),wC)}},1e3))}createSender(e,t,n){return L(this,void 0,void 0,function*(){if(sb())return yield this.createTransceiverRTCRtpSender(e,t,n);if(cb())return this.log.warn(`using add-track fallback`,this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new _y(`Required webRTC APIs not supported on this device`)})}createSimulcastSender(e,t,n,r){return L(this,void 0,void 0,function*(){if(sb())return this.createSimulcastTransceiverSender(e,t,n,r);if(cb())return this.log.debug(`using add-track fallback`,this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new _y(`Cannot stream on this device`)})}createTransceiverRTCRtpSender(e,t,n){return L(this,void 0,void 0,function*(){if(!this.pcManager)throw new _y(`publisher is closed`);let r=[];e.mediaStream&&r.push(e.mediaStream),Qb(e)&&(e.codec=t.videoCodec);let i={direction:`sendonly`,streams:r};return n&&(i.sendEncodings=n),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,i)).sender})}createSimulcastTransceiverSender(e,t,n,r){return L(this,void 0,void 0,function*(){if(!this.pcManager)throw new _y(`publisher is closed`);let i={direction:`sendonly`};r&&(i.sendEncodings=r);let a=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,i);if(n.videoCodec)return e.setSimulcastTrackSender(n.videoCodec,a.sender),a.sender})}createRTCRtpSender(e){return L(this,void 0,void 0,function*(){if(!this.pcManager)throw new _y(`publisher is closed`);return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return L(this,void 0,void 0,function*(){if(!this._isClosed){if(this.attemptingReconnect){I.warn(`already attempting reconnect, returning early`,this.logContext);return}(this.clientConfiguration?.resumeConnection===bh.DISABLED||(this.pcManager?.currentState??kS.NEW)===kS.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(e){this.reconnectAttempts+=1;let t=!0;e instanceof _y?(this.log.debug(`received unrecoverable error`,Object.assign(Object.assign({},this.logContext),{error:e})),t=!1):e instanceof Cy||(this.fullReconnectOnNext=!0),t?this.handleDisconnect(`reconnect`,Sh.RR_UNKNOWN):(this.log.info(`could not recover connection after ${this.reconnectAttempts} attempts, ${Date.now()-this.reconnectStart}ms. giving up`,this.logContext),this.emit(H.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 L(this,void 0,void 0,function*(){var t,n;try{if(!this.url||!this.token)throw new _y(`could not reconnect, url or token not saved`);this.log.info(`reconnecting, attempt: ${this.reconnectAttempts}`,this.logContext),this.emit(H.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let n;try{if(!this.signalOpts)throw this.log.warn(`attempted connection restart, without signal options present`,this.logContext),new Cy;n=yield this.join(e??this.url,this.token,this.signalOpts,void 0,!this.options.singlePeerConnection)}catch(e){throw e instanceof z&&e.reason===R.NotAllowed?new _y(`could not reconnect, token might be expired`):new Cy}if(this.shouldFailNext)throw this.shouldFailNext=!1,Error(`simulated failure`);if(this.client.setReconnected(),this.emit(H.SignalRestarted,n),yield this.waitForPCReconnected(),this.client.currentState!==q.CONNECTED)throw new Cy(`Signal connection got severed during reconnect`);(t=this.regionUrlProvider)==null||t.resetAttempts(),this.emit(H.Restarted)}catch(e){let t=yield this.regionUrlProvider?.getNextBestRegionUrl();if(t){yield this.restartConnection(t);return}else throw(n=this.regionUrlProvider)==null||n.resetAttempts(),e}})}resumeConnection(e){return L(this,void 0,void 0,function*(){if(!this.url||!this.token)throw new _y(`could not reconnect, url or token not saved`);if(!this.pcManager)throw new _y(`publisher and subscriber connections unset`);this.log.info(`resuming signal connection, attempt ${this.reconnectAttempts}`,this.logContext),this.emit(H.Resuming);let t;try{this.setupSignalClientCallbacks(),t=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(e){let t=``;throw e instanceof Error&&(t=e.message,this.log.error(e.message,Object.assign(Object.assign({},this.logContext),{error:e}))),e instanceof z&&e.reason===R.NotAllowed?new _y(`could not reconnect, token might be expired`):e instanceof z&&e.reason===R.LeaveRequest?e:new Cy(t)}if(this.emit(H.SignalResumed),t){let e=this.makeRTCConfiguration(t);this.pcManager.updateConfiguration(e),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=t.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!==q.CONNECTED)throw new Cy(`Signal connection got severed during reconnect`);this.client.setReconnected(),this.reliableDC?.readyState===`open`&&this.reliableDC.id===null&&this.createDataChannels(),t?.lastMessageSeq&&this.resendReliableMessagesForResume(t.lastMessageSeq),this.emit(H.Resumed)})}waitForPCInitialConnection(e,t){return L(this,void 0,void 0,function*(){if(!this.pcManager)throw new _y(`PC manager is closed`);yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return L(this,void 0,void 0,function*(){this.pcState=DC.Reconnecting,this.log.debug(`waiting for peer connection to reconnect`,this.logContext);try{if(yield ob(bC),!this.pcManager)throw new _y(`PC manager is closed`);yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=DC.Connected}catch(e){throw this.pcState=DC.Disconnected,z.internal(`could not establish PC connection, ${e.message}`)}})}publishRpcResponse(e,t,n,r){return L(this,void 0,void 0,function*(){let i=new Rh({destinationIdentities:[e],kind:zh.RELIABLE,value:{case:`rpcResponse`,value:new Zh({requestId:t,value:r?{case:`error`,value:r.toProto()}:{case:`payload`,value:n??``}})}});yield this.sendDataPacket(i,J.RELIABLE)})}publishRpcAck(e,t){return L(this,void 0,void 0,function*(){let n=new Rh({destinationIdentities:[e],kind:zh.RELIABLE,value:{case:`rpcAck`,value:new Xh({requestId:t})}});yield this.sendDataPacket(n,J.RELIABLE)})}sendDataPacket(e,t){return L(this,void 0,void 0,function*(){if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){let t=Cx(e);if(t){let n=yield this.e2eeManager.encryptData(t.toBinary());e.value={case:`encryptedPacket`,value:new Bh({encryptedValue:n.payload,iv:n.iv,keyIndex:n.keyIndex})}}}t===J.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);let n=e.toBinary();switch(t){case J.LOSSY:case J.DATA_TRACK_LOSSY:return this.sendLossyBytes(n,t);case J.RELIABLE:let r=this.dataChannelForKind(t);if(r){if(yield this.waitForBufferStatusLow(t),this.reliableMessageBuffer.push({data:n,sequence:e.sequence}),this.attemptingReconnect)return;r.send(n)}this.updateAndEmitDCBufferStatus(t);break}})}sendLossyBytes(e,t){return L(this,arguments,void 0,function(e,t){var n=this;let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:`drop`;return function*(){yield n.ensurePublisherConnected(t);let i=n.dataChannelForKind(t);if(i){if(!n.isBufferStatusLow(t))switch(r){case`wait`:yield n.waitForBufferStatusLow(t);break;case`drop`:n.lossyDataDropCount+=1,n.lossyDataDropCount%100==0&&n.log.warn(`dropping lossy data channel messages, total dropped: ${n.lossyDataDropCount}`,n.logContext);return}if(n.lossyDataStatCurrentBytes+=e.byteLength,n.attemptingReconnect)return;i.send(e)}n.updateAndEmitDCBufferStatus(t)}()})}resendReliableMessagesForResume(e){return L(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(J.RELIABLE);let t=this.dataChannelForKind(J.RELIABLE);t&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach(e=>{t.send(e.data)})),this.updateAndEmitDCBufferStatus(J.RELIABLE)})}waitForBufferStatusLow(e){return new iy((t,n)=>L(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))t();else{let r=()=>n(new _y(`engine closed`));for(this.once(H.Closing,r);!this.dcBufferStatus.get(e);)yield ob(10);this.off(H.Closing,r),t()}}))}ensureDataTransportConnected(e){return L(this,arguments,void 0,function(e){var t=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return function*(){if(!t.pcManager)throw new _y(`PC manager is closed`);let r=n?t.pcManager.subscriber:t.pcManager.publisher,i=n?`Subscriber`:`Publisher`;if(!r)throw z.internal(`${i} connection not set`);let a=!1;if(!n&&!t.dataChannelForKind(e,n)&&(t.createDataChannels(),a=!0),!a&&!n&&!t.pcManager.publisher.isICEConnected&&t.pcManager.publisher.getICEConnectionState()!==`checking`&&(a=!0),a&&t.negotiate().catch(e=>{I.error(e,t.logContext)}),t.dataChannelForKind(e,n)?.readyState===`open`)return;let o=new Date().getTime()+t.peerConnectionTimeout;for(;new Date().getTime()<o;){if(r.isICEConnected&&t.dataChannelForKind(e,n)?.readyState===`open`)return;yield ob(50)}throw z.internal(`could not establish ${i} connection, state: ${r.getICEConnectionState()}`)}()})}ensurePublisherConnected(e){return L(this,void 0,void 0,function*(){this.publisherConnectionPromise||=this.ensureDataTransportConnected(e,!1),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||![kS.CONNECTING,kS.CONNECTED].includes(this.pcManager.currentState)||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return L(this,void 0,void 0,function*(){return new iy((e,t)=>L(this,void 0,void 0,function*(){if(!this.pcManager){t(new vy(`PC manager is closed`));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&!this.dataTrackDC&&this.createDataChannels();let n=new AbortController,r=()=>{n.abort(),this.log.debug(`engine disconnected while negotiation was ongoing`,this.logContext),e()};this.isClosed&&t(new vy(`cannot negotiate on closed engine`)),this.on(H.Closing,r),this.on(H.Restarting,r),this.pcManager.publisher.once(_S.RTPVideoPayloadTypes,e=>{let t=new Map;e.forEach(e=>{let n=e.codec.toLowerCase();Vb(n)&&t.set(e.payload,n)}),this.emit(H.RTPVideoMapUpdate,t)});try{yield this.pcManager.negotiate(n),e()}catch(r){if(n.signal.aborted){e();return}r instanceof vy&&(this.fullReconnectOnNext=!0),this.handleDisconnect(`negotiation`,Sh.RR_UNKNOWN),r instanceof Error?t(r):t(Error(String(r)))}finally{this.off(H.Closing,r),this.off(H.Restarting,r)}}))})}dataChannelForKind(e,t){switch(e){case J.RELIABLE:return t?this.reliableDCSub:this.reliableDC;case J.LOSSY:return t?this.lossyDCSub:this.lossyDC;case J.DATA_TRACK_LOSSY:return t?this.dataTrackDCSub:this.dataTrackDC}}sendSyncState(e,t,n){if(!this.pcManager){this.log.warn(`sync state cannot be sent without peer connection setup`,this.logContext);return}let r=this.pcManager.publisher.getLocalDescription(),i=this.pcManager.publisher.getRemoteDescription(),a=this.pcManager.subscriber?.getRemoteDescription(),o=this.pcManager.subscriber?.getLocalDescription(),s=this.signalOpts?.autoSubscribe??!0,c=[],l=[];e.forEach(e=>{e.isDesired!==s&&c.push(e.trackSid),e.isEnabled||l.push(e.trackSid)}),this.client.sendSyncState(new s_({answer:this.pcManager.mode===`publisher-only`?i?Xx({sdp:i.sdp,type:i.type}):void 0:o?Xx({sdp:o.sdp,type:o.type}):void 0,offer:this.pcManager.mode===`publisher-only`?r?Xx({sdp:r.sdp,type:r.type}):void 0:a?Xx({sdp:a.sdp,type:a.type}):void 0,subscription:new Ig({trackSids:c,subscribe:!s,participantTracks:[]}),publishTracks:Gy(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:l,datachannelReceiveStates:this.reliableReceivedState.map((e,t)=>new c_({publisherSid:t,lastSeq:e})),publishDataTracks:n.map(e=>new Cg({info:Vx.toProtobuf(e)}))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){let e=[],t=(t,n)=>{t?.id!==void 0&&t.id!==null&&e.push(new l_({label:t.label,id:t.id,target:n}))};return t(this.dataChannelForKind(J.LOSSY),hg.PUBLISHER),t(this.dataChannelForKind(J.RELIABLE),hg.PUBLISHER),t(this.dataChannelForKind(J.LOSSY,!0),hg.SUBSCRIBER),t(this.dataChannelForKind(J.RELIABLE,!0),hg.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&Ty.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){Sb()&&(window.addEventListener(`online`,this.handleBrowserOnLine),window.addEventListener(`offline`,this.handleBrowserOffline))}deregisterOnLineListener(){Sb()&&(window.removeEventListener(`online`,this.handleBrowserOnLine),window.removeEventListener(`offline`,this.handleBrowserOffline))}getTrackIdForReceiver(e){let t=this.pcManager?.getMidForReceiver(e);if(t){let e=Object.entries(this.midToTrackId).find(e=>{let[n]=e;return n===t});if(e)return e[1]}}};function kC(e,t){let n=e.participantIdentity?e.participantIdentity:t.participantIdentity;e.participantIdentity=n,t.participantIdentity=n;let r=e.destinationIdentities.length===0?t.destinationIdentities:e.destinationIdentities;e.destinationIdentities=r,t.destinationIdentities=r}var AC=class{get info(){return this._info}validateBytesReceived(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;if(!(typeof this.totalByteSize!=`number`||this.totalByteSize===0)){if(e&&this.bytesReceived<this.totalByteSize)throw new Sy(`Not enough chunk(s) received - expected ${this.totalByteSize} bytes of data total, only received ${this.bytesReceived} bytes`,xy.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new Sy(`Extra chunk(s) received - expected ${this.totalByteSize} bytes of data total, received ${this.bytesReceived} bytes`,xy.LengthExceeded)}}constructor(e,t,n){this.reader=t,this.totalByteSize=n,this._info=e,this.bytesReceived=0}},jC=class extends AC{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();let n=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)==null||t.call(this,n)}[Symbol.asyncIterator](){let e=this.reader.getReader();e.closed.catch(()=>{});let t=()=>{e.releaseLock(),this.signal=void 0};return{next:()=>L(this,void 0,void 0,function*(){try{let t=this.signal;if(t?.aborted)throw t.reason;let n=yield new Promise((n,r)=>{if(t){let i=()=>r(t.reason);t.addEventListener(`abort`,i,{once:!0}),e.read().then(n,r).finally(()=>{t.removeEventListener(`abort`,i)})}else e.read().then(n,r)});return n.done?(this.validateBytesReceived(!0),{done:!0,value:void 0}):(this.handleChunkReceived(n.value),{done:!1,value:n.value.content})}catch(e){throw t(),e}}),return(){return L(this,void 0,void 0,function*(){return t(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return L(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return function*(){var n,r,i,a;let o=new Set,s=t.signal?e.withAbortSignal(t.signal):e;try{for(var c=!0,l=H_(s),u;u=yield l.next(),n=u.done,!n;c=!0){a=u.value,c=!1;let e=a;o.add(e)}}catch(e){r={error:e}}finally{try{!c&&!n&&(i=l.return)&&(yield i.call(l))}finally{if(r)throw r.error}}return Array.from(o)}()})}},MC=class extends AC{constructor(e,t,n){super(e,t,n),this.receivedChunks=new Map}handleChunkReceived(e){var t;let n=Jb(e.chunkIndex),r=this.receivedChunks.get(n);if(r&&r.version>e.version)return;this.receivedChunks.set(n,e),this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();let i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)==null||t.call(this,i)}[Symbol.asyncIterator](){let e=this.reader.getReader();e.closed.catch(()=>{});let t=new TextDecoder(`utf-8`,{fatal:!0}),n=this.signal,r=()=>{e.releaseLock(),this.signal=void 0};return{next:()=>L(this,void 0,void 0,function*(){try{if(n?.aborted)throw n.reason;let r=yield new Promise((t,r)=>{if(n){let i=()=>r(n.reason);n.addEventListener(`abort`,i,{once:!0}),e.read().then(t,r).finally(()=>{n.removeEventListener(`abort`,i)})}else e.read().then(t,r)});if(r.done)return this.validateBytesReceived(!0),{done:!0,value:void 0};{this.handleChunkReceived(r.value);let e;try{e=t.decode(r.value.content)}catch(e){throw new Sy(`Cannot decode datastream chunk ${r.value.chunkIndex} as text: ${e}`,xy.DecodeFailed)}return{done:!1,value:e}}}catch(e){throw r(),e}}),return(){return L(this,void 0,void 0,function*(){return r(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return L(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return function*(){var n,r,i,a;let o=``,s=t.signal?e.withAbortSignal(t.signal):e;try{for(var c=!0,l=H_(s),u;u=yield l.next(),n=u.done,!n;c=!0)a=u.value,c=!1,o+=a}catch(e){r={error:e}}finally{try{!c&&!n&&(i=l.return)&&(yield i.call(l))}finally{if(r)throw r.error}}return o}()})}},NC=class{constructor(){this.log=I,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new Sy(`A text stream handler for topic "${e}" has already been set.`,xy.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new Sy(`A byte stream handler for topic "${e}" has already been set.`,xy.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear()}validateParticipantHasNoActiveDataStreams(e){let t=Array.from(this.textStreamControllers.entries()).filter(t=>t[1].sendingParticipantIdentity===e),n=Array.from(this.byteStreamControllers.entries()).filter(t=>t[1].sendingParticipantIdentity===e);if(t.length>0||n.length>0){let r=new Sy(`Participant ${e} unexpectedly disconnected in the middle of sending data`,xy.AbnormalEnd);for(let[e,t]of n)t.controller.error(r),this.byteStreamControllers.delete(e);for(let[e,n]of t)n.controller.error(r),this.textStreamControllers.delete(e)}}handleDataStreamPacket(e,t){return L(this,void 0,void 0,function*(){switch(e.value.case){case`streamHeader`:return this.handleStreamHeader(e.value.value,e.participantIdentity,t);case`streamChunk`:return this.handleStreamChunk(e.value.value,t);case`streamTrailer`:return this.handleStreamTrailer(e.value.value,t);default:throw Error(`DataPacket of value "${e.value.case}" is not data stream related!`)}})}handleStreamHeader(e,t,n){return L(this,void 0,void 0,function*(){if(e.contentHeader.case===`byteHeader`){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 i,a={id:e.streamId,name:e.contentHeader.value.name??`unknown`,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Jb(e.timestamp),attributes:e.attributes,encryptionType:n};r(new jC(a,new ReadableStream({start:n=>{if(i=n,this.textStreamControllers.has(e.streamId))throw new Sy(`A data stream read is already in progress for a stream with id ${e.streamId}.`,xy.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:a,controller:i,startTime:Date.now(),sendingParticipantIdentity:t})}}),Jb(e.totalLength)),{identity:t})}else if(e.contentHeader.case===`textHeader`){let r=this.textStreamHandlers.get(e.topic);if(!r){this.log.debug(`ignoring incoming text stream due to no handler for topic`,e.topic);return}let i,a={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes,encryptionType:n,attachedStreamIds:e.contentHeader.value.attachedStreamIds};r(new MC(a,new ReadableStream({start:n=>{if(i=n,this.textStreamControllers.has(e.streamId))throw new Sy(`A data stream read is already in progress for a stream with id ${e.streamId}.`,xy.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:a,controller:i,startTime:Date.now(),sendingParticipantIdentity:t})}}),Jb(e.totalLength)),{identity:t})}})}handleStreamChunk(e,t){let n=this.byteStreamControllers.get(e.streamId);n&&(n.info.encryptionType===t?e.content.length>0&&n.controller.enqueue(e):(n.controller.error(new Sy(`Encryption type mismatch for stream ${e.streamId}. Expected ${t}, got ${n.info.encryptionType}`,xy.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId)));let r=this.textStreamControllers.get(e.streamId);r&&(r.info.encryptionType===t?e.content.length>0&&r.controller.enqueue(e):(r.controller.error(new Sy(`Encryption type mismatch for stream ${e.streamId}. Expected ${t}, got ${r.info.encryptionType}`,xy.EncryptionTypeMismatch)),this.textStreamControllers.delete(e.streamId)))}handleStreamTrailer(e,t){let n=this.textStreamControllers.get(e.streamId);n&&(n.info.encryptionType===t?(n.info.attributes=Object.assign(Object.assign({},n.info.attributes),e.attributes),n.controller.close(),this.textStreamControllers.delete(e.streamId)):n.controller.error(new Sy(`Encryption type mismatch for stream ${e.streamId}. Expected ${t}, got ${n.info.encryptionType}`,xy.EncryptionTypeMismatch)));let r=this.byteStreamControllers.get(e.streamId);r&&(r.info.encryptionType===t?(r.info.attributes=Object.assign(Object.assign({},r.info.attributes),e.attributes),r.controller.close()):r.controller.error(new Sy(`Encryption type mismatch for stream ${e.streamId}. Expected ${t}, got ${r.info.encryptionType}`,xy.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId))}},PC=class{constructor(e,t,n){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=n,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return L(this,void 0,void 0,function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),(e=this.onClose)==null||e.call(this)})}},FC=class extends PC{},IC=class extends PC{},LC=15e3,RC=class{constructor(e,t){this.engine=e,this.log=t}setupEngine(e){this.engine=e}sendText(e,t){return L(this,void 0,void 0,function*(){let n=crypto.randomUUID(),r=new TextEncoder().encode(e).byteLength,i=(t?.attachments)?.map(()=>crypto.randomUUID()),a=Array(i?i.length+1:1).fill(0),o=(e,n)=>{var r;a[n]=e;let i=a.reduce((e,t)=>e+t,0);(r=t?.onProgress)==null||r.call(t,i)},s=yield this.streamText({streamId:n,totalSize:r,destinationIdentities:t?.destinationIdentities,topic:t?.topic,attachedStreamIds:i,attributes:t?.attributes});return yield s.write(e),o(1,0),yield s.close(),t?.attachments&&i&&(yield Promise.all(t.attachments.map((e,n)=>L(this,void 0,void 0,function*(){return this._sendFile(i[n],e,{topic:t.topic,mimeType:e.type,onProgress:e=>{o(e,n+1)}})})))),s.info})}streamText(e){return L(this,void 0,void 0,function*(){let t=e?.streamId??crypto.randomUUID(),n={id:t,mimeType:`text/plain`,timestamp:Date.now(),topic:e?.topic??``,size:e?.totalSize,attributes:e?.attributes,encryptionType:this.engine.e2eeManager?.isDataChannelEncryptionEnabled?F.GCM:F.NONE,attachedStreamIds:e?.attachedStreamIds},r=new dg({streamId:t,mimeType:n.mimeType,topic:n.topic,timestamp:Yb(n.timestamp),totalLength:Yb(n.size),attributes:n.attributes,contentHeader:{case:`textHeader`,value:new lg({version:e?.version,attachedStreamIds:n.attachedStreamIds,replyToStreamId:e?.replyToStreamId,operationType:e?.type===`update`?cg.UPDATE:cg.CREATE})}}),i=e?.destinationIdentities,a=new Rh({destinationIdentities:i,value:{case:`streamHeader`,value:r}});yield this.engine.sendDataPacket(a,J.RELIABLE);let o=0,s=this.engine,c=new WritableStream({write(e){return L(this,void 0,void 0,function*(){for(let n of ax(e,LC)){let e=new Rh({destinationIdentities:i,value:{case:`streamChunk`,value:new fg({content:n,streamId:t,chunkIndex:Yb(o)})}});yield s.sendDataPacket(e,J.RELIABLE),o+=1}})},close(){return L(this,void 0,void 0,function*(){let e=new Rh({destinationIdentities:i,value:{case:`streamTrailer`,value:new pg({streamId:t})}});yield s.sendDataPacket(e,J.RELIABLE)})},abort(e){console.log(`Sink error:`,e)}}),l=()=>L(this,void 0,void 0,function*(){yield u.close()});s.once(H.Closing,l);let u=new FC(c,n,()=>this.engine.off(H.Closing,l));return u})}sendFile(e,t){return L(this,void 0,void 0,function*(){let n=crypto.randomUUID();return yield this._sendFile(n,e,t),{id:n}})}_sendFile(e,t,n){return L(this,void 0,void 0,function*(){let r=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:n?.mimeType??t.type,topic:n?.topic,destinationIdentities:n?.destinationIdentities}),i=t.stream().getReader();for(;;){let{done:e,value:t}=yield i.read();if(e)break;yield r.write(t)}return yield r.close(),r.info})}streamBytes(e){return L(this,void 0,void 0,function*(){let t=e?.streamId??crypto.randomUUID(),n=e?.destinationIdentities,r={id:t,mimeType:e?.mimeType??`application/octet-stream`,topic:e?.topic??``,timestamp:Date.now(),attributes:e?.attributes,size:e?.totalSize,name:e?.name??`unknown`,encryptionType:this.engine.e2eeManager?.isDataChannelEncryptionEnabled?F.GCM:F.NONE},i=new Rh({destinationIdentities:n,value:{case:`streamHeader`,value:new dg({totalLength:Yb(r.size),mimeType:r.mimeType,streamId:t,topic:r.topic,timestamp:Yb(Date.now()),attributes:r.attributes,contentHeader:{case:`byteHeader`,value:new ug({name:r.name})}})}});yield this.engine.sendDataPacket(i,J.RELIABLE);let a=0,o=new hp,s=this.engine,c=this.log;return new IC(new WritableStream({write(e){return L(this,void 0,void 0,function*(){let r=yield o.lock(),i=0;try{for(;i<e.byteLength;){let r=e.slice(i,i+LC),o=new Rh({destinationIdentities:n,value:{case:`streamChunk`,value:new fg({content:r,streamId:t,chunkIndex:Yb(a)})}});yield s.sendDataPacket(o,J.RELIABLE),a+=1,i+=r.byteLength}}finally{r()}})},close(){return L(this,void 0,void 0,function*(){let e=new Rh({destinationIdentities:n,value:{case:`streamTrailer`,value:new pg({streamId:t})}});yield s.sendDataPacket(e,J.RELIABLE)})},abort(e){c.error(`Sink error:`,e)}}),r)})}};function zC(e){if(e.length===0)return new AbortController().signal;if(e.length===1)return e[0];for(let t of e)if(t.aborted)return t;let t=new AbortController,n=Array(e.length),r=()=>{for(let e of n)e()};return e.forEach((e,i)=>{let a=()=>{t.abort(e.reason),r()};e.addEventListener(`abort`,a),n[i]=()=>e.removeEventListener(`abort`,a)}),t.signal}function BC(e){let t=new AbortController;return setTimeout(()=>{t.abort(new DOMException(`signal timed out after ${e} ms`,`TimeoutError`))},e),t.signal}var VC=1,HC=2,UC=4,WC=8,GC=0,KC=12,qC=5,JC=7,YC=3,XC=3,ZC=2,QC=1,$C=0,ew=3,tw=2,nw=2,rw=1,iw=0,aw;(function(e){e[e.TooShort=0]=`TooShort`,e[e.HeaderOverrun=1]=`HeaderOverrun`,e[e.MissingExtWords=2]=`MissingExtWords`,e[e.UnsupportedVersion=3]=`UnsupportedVersion`,e[e.InvalidHandle=4]=`InvalidHandle`,e[e.MalformedExt=5]=`MalformedExt`})(aw||={});var ow=class e extends py{constructor(e,t,n){super(19,e,n),this.name=`DataTrackDeserializeError`,this.reason=t,this.reasonName=aw[t]}static tooShort(){return new e(`Too short to contain a valid header`,aw.TooShort)}static headerOverrun(){return new e(`Header exceeds total packet length`,aw.HeaderOverrun)}static missingExtWords(){return new e(`Extension word indicator is missing`,aw.MissingExtWords)}static unsupportedVersion(t){return new e(`Unsupported version ${t}`,aw.UnsupportedVersion)}static invalidHandle(t){return new e(`invalid track handle: ${t.message}`,aw.InvalidHandle,{cause:t})}static malformedExt(t){return new e(`Extension with tag ${t} is malformed`,aw.MalformedExt)}},sw;(function(e){e[e.TooSmallForHeader=0]=`TooSmallForHeader`,e[e.TooSmallForPayload=1]=`TooSmallForPayload`})(sw||={});var cw=class e extends py{constructor(e,t,n){super(19,e,n),this.name=`DataTrackSerializeError`,this.reason=t,this.reasonName=sw[t]}static tooSmallForHeader(){return new e(`Buffer cannot fit header`,sw.TooSmallForHeader)}static tooSmallForPayload(){return new e(`Buffer cannot fit payload`,sw.TooSmallForPayload)}},lw=class{toBinary(){let e=this.toBinaryLengthBytes(),t=new ArrayBuffer(e),n=new DataView(t),r=this.toBinaryInto(n);if(e!==r)throw Error(`${this.constructor.name}.toBinary: written bytes (${r} bytes) not equal to allocated array buffer length (${e} bytes).`);return new Uint8Array(t)}},uw;(function(e){e[e.UserTimestamp=2]=`UserTimestamp`,e[e.E2ee=1]=`E2ee`})(uw||={});var dw=class extends lw{},fw=class e extends dw{constructor(e){super(),this.timestamp=e}toBinaryLengthBytes(){return VC+VC+e.lengthBytes}toBinaryInto(t){let n=0;t.setUint8(n,e.tag),n+=VC,t.setUint8(n,e.lengthBytes),n+=VC,t.setBigUint64(n,this.timestamp),n+=WC;let r=this.toBinaryLengthBytes();if(n!==r)throw Error(`DataTrackUserTimestampExtension.toBinaryInto: Wrote ${n} bytes but expected length was ${r} bytes`);return n}toJSON(){return{tag:e.tag,lengthBytes:e.lengthBytes,timestamp:this.timestamp}}};fw.tag=uw.UserTimestamp,fw.lengthBytes=8;var pw=class e extends dw{constructor(e,t){super(),this.keyIndex=e,this.iv=t}toBinaryLengthBytes(){return VC+VC+e.lengthBytes}toBinaryInto(t){let n=0;t.setUint8(n,e.tag),n+=VC,t.setUint8(n,e.lengthBytes),n+=VC,t.setUint8(n,this.keyIndex),n+=VC;for(let e=0;e<this.iv.length;e+=1)t.setUint8(n,this.iv[e]),n+=VC;let r=this.toBinaryLengthBytes();if(n!==r)throw Error(`DataTrackE2eeExtension.toBinaryInto: Wrote ${n} bytes but expected length was ${r} bytes`);return n}toJSON(){return{tag:e.tag,lengthBytes:e.lengthBytes,keyIndex:this.keyIndex,iv:this.iv}}};pw.tag=uw.E2ee,pw.lengthBytes=13;var mw=class e extends lw{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.userTimestamp=e.userTimestamp,this.e2ee=e.e2ee}toBinaryLengthBytes(){let e=0;return this.userTimestamp&&(e+=this.userTimestamp.toBinaryLengthBytes()),this.e2ee&&(e+=this.e2ee.toBinaryLengthBytes()),e}toBinaryInto(e){let t=0;if(this.e2ee){let n=this.e2ee.toBinaryInto(e);t+=n}if(this.userTimestamp){let n=this.userTimestamp.toBinaryInto(new DataView(e.buffer,e.byteOffset+t));t+=n}let n=this.toBinaryLengthBytes();if(t!==n)throw Error(`DataTrackExtensions.toBinaryInto: Wrote ${t} bytes but expected length was ${n} bytes`);return t}static fromBinary(t){let n=Ix(t),r,i,a=0;for(;n.byteLength-a>=VC+VC;){let e=n.getUint8(a);a+=VC;let t=n.getUint8(a);if(a+=VC,e!==iw)switch(e){case uw.UserTimestamp:if(n.byteLength-a<fw.lengthBytes)throw ow.malformedExt(e);r=new fw(n.getBigUint64(a)),a+=t;break;case uw.E2ee:if(n.byteLength-a<pw.lengthBytes)throw ow.malformedExt(e);let o=n.getUint8(a),s=new Uint8Array(12);for(let e=0;e<s.length;e+=1){let t=a;t+=VC,t+=e*VC,s[e]=n.getUint8(t)}i=new pw(o,s),a+=t;break;default:if(n.byteLength-a<t)throw ow.malformedExt(e);a+=t;break}}return[new e({userTimestamp:r,e2ee:i}),n.byteLength]}toJSON(){return{userTimestamp:this.userTimestamp?.toJSON()??null,e2ee:this.e2ee?.toJSON()??null}}},hw={from(e){return{payload:e.payload,extensions:new mw({userTimestamp:e.userTimestamp?new fw(e.userTimestamp):void 0})}},lossyIntoFrame(e){return{payload:e.payload,userTimestamp:e.extensions.userTimestamp?.timestamp}}},gw=Symbol.for(`lk.track`),_w=Symbol.for(`lk.data-track`),vw=class{constructor(e,t,n){this.trackSymbol=gw,this.isLocal=!1,this.typeSymbol=_w,this.info=e,this.manager=t,this.publisherIdentity=n.publisherIdentity}subscribe(e){try{let[t]=this.manager.openSubscriptionStream(this.info.sid,e?.signal,e?.bufferSize);return t}catch(e){throw e}}},yw=class e extends lw{constructor(e){super(),this.marker=e.marker,this.trackHandle=e.trackHandle,this.sequence=e.sequence,this.frameNumber=e.frameNumber,this.timestamp=e.timestamp,this.extensions=e.extensions??new mw}extensionsMetrics(){let e=this.extensions.toBinaryLengthBytes(),t=Math.ceil(e/4);return{lengthBytes:e,lengthWords:t,paddingLengthBytes:t*4-e}}toBinaryLengthBytes(){let{lengthBytes:e,paddingLengthBytes:t}=this.extensionsMetrics(),n=KC;return e>0&&(n+=tw+e+t),n}toBinaryInto(e){if(e.byteLength<this.toBinaryLengthBytes())throw cw.tooSmallForHeader();let t=GC<<qC,n;switch(this.marker){case bw.Inter:n=$C;break;case bw.Final:n=QC;break;case bw.Start:n=ZC;break;case bw.Single:n=ew;break}t|=n<<YC;let{lengthBytes:r,lengthWords:i,paddingLengthBytes:a}=this.extensionsMetrics();r>0&&(t|=1<<nw);let o=0;if(e.setUint8(o,t),o+=VC,e.setUint8(o,0),o+=VC,e.setUint16(o,this.trackHandle),o+=HC,e.setUint16(o,this.sequence.value),o+=HC,e.setUint16(o,this.frameNumber.value),o+=HC,e.setUint32(o,this.timestamp.asTicks()),o+=UC,r>0){let t=i-1;e.setUint16(o,t),o+=HC;let n=this.extensions.toBinaryInto(new DataView(e.buffer,e.byteOffset+o));o+=n;for(let t=0;t<a;t+=1)e.setUint8(o,0),o+=VC}let s=this.toBinaryLengthBytes();if(o!==s)throw Error(`DataTrackPacketHeader.toBinaryInto: Wrote ${o} bytes but expected length was ${s} bytes`);return s}static fromBinary(t){let n=Ix(t);if(n.byteLength<KC)throw ow.tooShort();let r=0,i=n.getUint8(r);r+=VC;let a=i>>qC&JC;if(a>GC)throw ow.unsupportedVersion(a);let o;switch(i>>YC&XC){case ZC:o=bw.Start;break;case QC:o=bw.Final;break;case ew:o=bw.Single;break;case $C:default:o=bw.Inter;break}let s=(i>>nw&rw)>0;r+=VC;let c;try{c=zx.fromNumber(n.getUint16(r))}catch(e){throw e instanceof Rx&&(e.isReason(Lx.Reserved)||e.isReason(Lx.TooLarge))?ow.invalidHandle(e):e}r+=HC;let l=Nx.u16(n.getUint16(r));r+=HC;let u=Nx.u16(n.getUint16(r));r+=HC;let d=Px.fromRtpTicks(n.getUint32(r));r+=UC;let f=new mw;if(s){if(n.byteLength-r<HC)throw ow.missingExtWords();let e=n.getUint16(r);r+=HC;let t=4*(e+1);if(r+t>n.byteLength)throw ow.headerOverrun();let i=new DataView(n.buffer,n.byteOffset+r,t),[a,o]=mw.fromBinary(i);f=a,r+=o}return[new e({marker:o,trackHandle:c,sequence:l,frameNumber:u,timestamp:d,extensions:f}),r]}toJSON(){return{marker:this.marker,trackHandle:this.trackHandle,sequence:this.sequence.value,frameNumber:this.frameNumber.value,timestamp:this.timestamp.asTicks(),extensions:this.extensions.toJSON()}}},bw;(function(e){e[e.Start=0]=`Start`,e[e.Inter=1]=`Inter`,e[e.Final=2]=`Final`,e[e.Single=3]=`Single`})(bw||={});var xw=class e extends lw{constructor(e,t){super(),this.header=e,this.payload=t}toBinaryLengthBytes(){return this.header.toBinaryLengthBytes()+this.payload.byteLength}toBinaryInto(e){let t=0,n=this.header.toBinaryInto(e);if(t+=n,e.byteLength-t<this.payload.byteLength)throw cw.tooSmallForPayload();for(let n=0;n<this.payload.length;n+=1)e.setUint8(t,this.payload[n]),t+=VC;let r=this.toBinaryLengthBytes();if(t!==r)throw Error(`DataTrackPacket.toBinaryInto: Wrote ${t} bytes but expected length was ${r} bytes`);return r}static fromBinary(t){let n=Ix(t),[r,i]=yw.fromBinary(n),a=n.buffer.slice(n.byteOffset+i,n.byteOffset+n.byteLength);return[new e(r,new Uint8Array(a)),n.byteLength]}toJSON(){return{header:this.header.toJSON(),payload:this.payload}}},Sw=M_(j_.DataTracks),Cw=class e extends py{constructor(e,t,n,r){super(19,`Frame ${n} dropped: ${e}`,r),this.name=`DataTrackDepacketizerDropError`,this.reason=t,this.reasonName=ww[t],this.frameNumber=n}static interrupted(t,n){return new e(`Interrupted by the start of a new frame ${n}`,ww.Interrupted,t)}static unknownFrame(t){return new e(`Initial packet was never received.`,ww.UnknownFrame,t)}static bufferFull(t){return new e(`Reorder buffer is full.`,ww.BufferFull,t)}static incomplete(t,n,r){return new e(`Not all packets received before final packet. Received ${n} packets, expected ${r} packets.`,ww.Incomplete,t)}},ww;(function(e){e[e.Interrupted=0]=`Interrupted`,e[e.UnknownFrame=1]=`UnknownFrame`,e[e.BufferFull=2]=`BufferFull`,e[e.Incomplete=3]=`Incomplete`})(ww||={});var Tw=class e{constructor(){this.partial=null}push(e,t){switch(e.header.marker){case bw.Single:return this.frameFromSingle(e,t);case bw.Start:return this.beginPartial(e,t);case bw.Inter:case bw.Final:return this.pushToPartial(e)}}reset(){this.partial=null}frameFromSingle(e,t){if(e.header.marker!==bw.Single)throw Error(`Depacketizer.frameFromSingle: packet.header.marker was not FrameMarker.Single, found ${e.header.marker}.`);if(this.partial)if(t?.errorOnPartialFrames){let t=this.partial.frameNumber;throw this.reset(),Cw.interrupted(t,e.header.frameNumber.value)}else Sw.warn(`Data track frame ${this.partial.frameNumber} was interrupted by the start of a new frame, dropping.`);return this.reset(),{payload:e.payload,extensions:e.header.extensions}}beginPartial(e,t){if(e.header.marker!==bw.Start)throw Error(`Depacketizer.beginPartial: packet.header.marker was not FrameMarker.Start, found ${e.header.marker}.`);if(this.partial)if(t?.errorOnPartialFrames){let t=this.partial.frameNumber;throw this.reset(),Cw.interrupted(t,e.header.frameNumber.value)}else Sw.warn(`Data track frame ${this.partial.frameNumber} was interrupted by the start of a new frame ${e.header.frameNumber.value}, dropping.`);this.reset();let n=e.header.sequence;return this.partial={frameNumber:e.header.frameNumber.value,startSequence:n,extensions:e.header.extensions,payloads:new Map([[n.value,e.payload]])},null}pushToPartial(t){if(t.header.marker!==bw.Inter&&t.header.marker!==bw.Final)throw Error(`Depacketizer.pushToPartial: packet.header.marker was not FrameMarker.Inter or FrameMarker.Final, found ${t.header.marker}.`);if(!this.partial)throw this.reset(),Cw.unknownFrame(t.header.frameNumber.value);if(t.header.frameNumber.value!==this.partial.frameNumber){let e=this.partial.frameNumber;throw this.reset(),Cw.interrupted(e,t.header.frameNumber.value)}if(this.partial.payloads.size>=e.MAX_BUFFER_PACKETS){let e=this.partial.frameNumber;throw this.reset(),Cw.bufferFull(e)}return this.partial.payloads.has(t.header.sequence.value)&&Sw.warn(`Data track frame ${this.partial.frameNumber} received duplicate packet for sequence ${t.header.sequence.value}, so replacing with newly received packet.`),this.partial.payloads.set(t.header.sequence.value,t.payload),t.header.marker===bw.Final?this.finalize(this.partial,t.header.sequence.value):null}finalize(e,t){let n=e.payloads.size,r=0;for(let t of e.payloads.values())r+=t.length;let i=new Uint8Array(r),a=e.startSequence.clone(),o=0;for(;;){let n=e.payloads.get(a.value);if(!n)break;e.payloads.delete(a.value);let r=i.length-o;if(n.length>r)throw Error(`Depacketizer.finalize: Expected at least ${n.length} more bytes left in the payload buffer, only got ${r} bytes.`);if(i.set(n,o),o+=n.length,a.value!=t){a.increment();continue}return this.reset(),{payload:i,extensions:e.extensions}}throw this.reset(),Cw.incomplete(e.frameNumber,n,t-e.startSequence.value+1)}};Tw.MAX_BUFFER_PACKETS=128;var Ew;(function(e){e[e.Unpublished=0]=`Unpublished`,e[e.Timeout=1]=`Timeout`,e[e.Disconnected=2]=`Disconnected`,e[e.Cancelled=4]=`Cancelled`})(Ew||={});var Dw=class e extends py{constructor(e,t,n){super(22,e,n),this.name=`DataTrackSubscribeError`,this.reason=t,this.reasonName=Ew[t]}static unpublished(){return new e(`The track has been unpublished and is no longer available`,Ew.Unpublished)}static timeout(){return new e(`Request to subscribe to data track timed-out`,Ew.Timeout)}static disconnected(){return new e(`Cannot subscribe to data track when disconnected`,Ew.Disconnected)}static cancelled(){return new e(`Subscription to data track cancelled by caller`,Ew.Cancelled)}},Ow=M_(j_.DataTracks),kw=class{constructor(e){let t=e.e2eeManager!==null;if(e.info.usesE2ee!==t)throw Error(`IncomingDataTrackPipeline: DataTrackInfo.usesE2ee must match presence of decryptionProvider`);let n=new Tw;this.publisherIdentity=e.publisherIdentity,this.e2eeManager=e.e2eeManager??null,this.depacketizer=n}updateE2eeManager(e){this.e2eeManager=e}processPacket(e){return L(this,void 0,void 0,function*(){let t=this.depacketize(e);return t&&(yield this.decryptIfNeeded(t))||null})}depacketize(e){let t;try{t=this.depacketizer.push(e)}catch(e){return Ow.warn(`Data frame depacketize error: ${e}`),null}return t}decryptIfNeeded(e){return L(this,void 0,void 0,function*(){let t=this.e2eeManager;if(!t)return e;let n=e.extensions?.e2ee??null;if(!n)return Ow.error(`Missing E2EE meta`),null;let r;try{r=yield t.handleEncryptedData(e.payload,n.iv,this.publisherIdentity,n.keyIndex)}catch(e){return Ow.error(`Error decrypting packet: ${e}`),null}return e.payload=r.payload,e})}},Aw=M_(j_.DataTracks),jw=1e4,Mw=16,Nw=class extends K_.EventEmitter{constructor(e){super(),this.descriptors=new Map,this.subscriptionHandles=new Map,this.e2eeManager=e?.e2eeManager??null}updateE2eeManager(e){this.e2eeManager=e;for(let t of this.descriptors.values())t.subscription.type===`active`&&t.subscription.pipeline.updateE2eeManager(e)}openSubscriptionStream(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Mw,r=null,i=new Bb;return[new ReadableStream({start:n=>{r=n;let a=()=>{var e;n.error(Dw.cancelled()),(e=i.reject)==null||e.call(i,Dw.cancelled())};this.subscribeRequest(e,t).then(()=>L(this,void 0,void 0,function*(){var r;t?.addEventListener(`abort`,a);let o=this.descriptors.get(e);if(!o){Aw.error(`Unknown track ${e}`);return}if(o.subscription.type!==`active`){Aw.error(`Subscription for track ${e} is not active`);return}o.subscription.streamControllers.add(n),(r=i.resolve)==null||r.call(i)})).catch(e=>{var t;n.error(e),(t=i.reject)==null||t.call(i,e)}).finally(()=>{t?.removeEventListener(`abort`,a)})},cancel:()=>{if(!r){Aw.warn(`ReadableStream subscribed to ${e} was not started.`);return}let t=this.descriptors.get(e);if(!t){Aw.warn(`Unknown track ${e}, skipping cancel...`);return}if(t.subscription.type!==`active`){Aw.warn(`Subscription for track ${e} is not active, skipping cancel...`);return}t.subscription.streamControllers.delete(r),t.subscription.streamControllers.size===0&&this.unSubscribeRequest(t.info.sid)}},new CountQueuingStrategy({highWaterMark:n})),i.promise]}subscribeRequest(e,t){return L(this,void 0,void 0,function*(){let n=this.descriptors.get(e);if(!n)throw Error(`Cannot subscribe to unknown track`);let r=(t,n,r)=>L(this,void 0,void 0,function*(){if(t.subscription.type===`active`)return;if(t.subscription.type!==`pending`)throw Error(`Descriptor for track ${e} is not pending, found ${t.subscription.type}`);let i=zC([n,r].filter(e=>e!==void 0)),a=new Bb;t.subscription.completionFuture.promise.then(()=>a.resolve?.call(a)).catch(e=>a.reject?.call(a,e));let o=()=>{var e;if(t.subscription.type===`pending`){if(--t.subscription.pendingRequestCount,r?.aborted){t.subscription.cancel();return}if(t.subscription.pendingRequestCount<=0){t.subscription.cancel();return}(e=a.reject)==null||e.call(a,Dw.cancelled())}};i.aborted&&o(),i.addEventListener(`abort`,o),yield a.promise,i.removeEventListener(`abort`,o)});switch(n.subscription.type){case`none`:{n.subscription={type:`pending`,completionFuture:new Bb,pendingRequestCount:1,cancel:()=>{var t,r;let a=n.subscription;n.subscription={type:`none`},this.emit(`sfuUpdateSubscription`,{sid:e,subscribe:!1}),a.type===`pending`&&((r=(t=a.completionFuture).reject)==null||r.call(t,i.aborted?Dw.timeout():Dw.cancelled()))}},this.emit(`sfuUpdateSubscription`,{sid:e,subscribe:!0});let i=BC(jw);yield r(n,t,i);return}case`pending`:n.subscription.pendingRequestCount+=1,yield r(n,t);return;case`active`:return}})}querySubscribed(){return L(this,void 0,void 0,function*(){return Array.from(this.descriptors.values()).filter(e=>e.subscription.type===`active`).map(e=>[e.info,e.publisherIdentity])})}unSubscribeRequest(e){let t=this.descriptors.get(e);if(!t)throw Error(`Cannot subscribe to unknown track`);if(t.subscription.type!==`active`){Aw.warn(`Unexpected descriptor state in unSubscribeRequest, expected active, found ${t.subscription?.type}`);return}for(let e of t.subscription.streamControllers)e.close();let n=t.subscription;t.subscription={type:`none`},this.subscriptionHandles.delete(n.subcriptionHandle),this.emit(`sfuUpdateSubscription`,{sid:e,subscribe:!1})}receiveSfuPublicationUpdates(e){return L(this,void 0,void 0,function*(){if(e.size===0)return;let t=new Map;for(let[n,r]of e.entries()){let e=new Set;for(let t of r)e.add(t.sid),!this.descriptors.has(t.sid)&&(yield this.handleTrackPublished(n,t));t.set(n,e)}for(let[e,n]of t.entries()){let t=Array.from(this.descriptors.entries()).filter(t=>{let[n,r]=t;return r.publisherIdentity===e}).map(e=>{let[t]=e;return t}).filter(e=>!n.has(e));for(let e of t)this.handleTrackUnpublished(e)}})}queryPublications(){return L(this,void 0,void 0,function*(){return Array.from(this.descriptors.values()).map(e=>e.info)})}handleTrackPublished(e,t){return L(this,void 0,void 0,function*(){if(this.descriptors.has(t.sid)){Aw.error(`Existing descriptor for track ${t.sid}`);return}let n={info:t,publisherIdentity:e,subscription:{type:`none`}};this.descriptors.set(n.info.sid,n);let r=new vw(n.info,this,{publisherIdentity:e});this.emit(`trackPublished`,{track:r})})}handleTrackUnpublished(e){let t=this.descriptors.get(e);if(!t){Aw.error(`Unknown track ${e}`);return}this.descriptors.delete(e),t.subscription.type===`active`&&this.subscriptionHandles.delete(t.subscription.subcriptionHandle),this.emit(`trackUnpublished`,{sid:e,publisherIdentity:t.publisherIdentity})}receivedSfuSubscriberHandles(e){for(let[t,n]of e.entries())this.registerSubscriberHandle(t,n)}registerSubscriberHandle(e,t){var n,r;let i=this.descriptors.get(t);if(!i){Aw.error(`Unknown track ${t}`);return}switch(i.subscription.type){case`none`:Aw.warn(`No subscription for ${t}`);return;case`active`:i.subscription.subcriptionHandle=e,this.subscriptionHandles.set(e,t);return;case`pending`:{let a=new kw({info:i.info,publisherIdentity:i.publisherIdentity,e2eeManager:this.e2eeManager}),o=i.subscription;i.subscription={type:`active`,subcriptionHandle:e,pipeline:a,streamControllers:new Set},this.subscriptionHandles.set(e,t),(r=(n=o.completionFuture).resolve)==null||r.call(n)}}}packetReceived(e){return L(this,void 0,void 0,function*(){let t;try{[t]=xw.fromBinary(e)}catch(e){Aw.error(`Failed to deserialize packet: ${e}`);return}let n=this.subscriptionHandles.get(t.header.trackHandle);if(!n){Aw.warn(`Unknown subscriber handle ${t.header.trackHandle}`);return}let r=this.descriptors.get(n);if(!r){Aw.error(`Missing descriptor for track ${n}`);return}if(r.subscription.type!==`active`){Aw.warn(`Received packet for track ${n} without active subscription`);return}let i=yield r.subscription.pipeline.processPacket(t);if(i)for(let e of r.subscription.streamControllers){if(e.desiredSize!==null&&e.desiredSize<=0){Aw.warn(`Cannot send frame to subscribers: readable stream is full (desiredSize is ${e.desiredSize}). To increase this threshold, set a higher 'options.highWaterMark' when calling .subscribe().`);continue}let t=hw.lossyIntoFrame(i);e.enqueue(t)}})}resendSubscriptionUpdates(){for(let[e,t]of this.descriptors)t.subscription.type!==`none`&&this.emit(`sfuUpdateSubscription`,{sid:e,subscribe:!0})}handleRemoteParticipantDisconnected(e){var t,n;for(let r of this.descriptors.values())if(r.publisherIdentity===e)switch(r.subscription.type){case`none`:break;case`pending`:(n=(t=r.subscription.completionFuture).reject)==null||n.call(t,Dw.disconnected());break;case`active`:this.unSubscribeRequest(r.info.sid);break}}shutdown(){var e,t;for(let n of this.descriptors.values())this.emit(`trackUnpublished`,{sid:n.info.sid,publisherIdentity:n.publisherIdentity}),n.subscription.type===`pending`&&((t=(e=n.subscription.completionFuture).reject)==null||t.call(e,Dw.disconnected()));this.descriptors.clear()}},Pw=class e extends py{constructor(e,t,n){super(19,e,n),this.name=`DataTrackPacketizerError`,this.reason=t,this.reasonName=Fw[t]}static mtuTooShort(){return new e(`MTU is too short to send frame`,Fw.MtuTooShort)}},Fw;(function(e){e[e.MtuTooShort=0]=`MtuTooShort`})(Fw||={});var Iw=class e{constructor(e,t){this.sequence=Nx.u16(0),this.frameNumber=Nx.u16(0),this.clock=Fx.rtpStartingNow(Px.rtpRandom()),this.handle=e,this.mtuSizeBytes=t}static computeFrameMarker(e,t){return t<=1?bw.Single:e===0?bw.Start:e===t-1?bw.Final:bw.Inter}*packetize(t,n){let r=this.frameNumber.getThenIncrement(),i={marker:bw.Inter,trackHandle:this.handle,sequence:Nx.u16(0),frameNumber:r,timestamp:n?.now??this.clock.now(),extensions:t.extensions},a=new yw(i).toBinaryLengthBytes();if(a>=this.mtuSizeBytes)throw Pw.mtuTooShort();let o=this.mtuSizeBytes-a,s=Math.ceil(t.payload.byteLength/o);for(let n=0,r=0;r<t.payload.byteLength;[n,r]=[n+1,r+o]){let a=this.sequence.getThenIncrement(),c=new yw(Object.assign(Object.assign({},i),{marker:e.computeFrameMarker(n,s),sequence:a})),l=Math.min(o,t.payload.byteLength-r);yield new xw(c,new Uint8Array(t.payload.buffer,t.payload.byteOffset+r,l))}}},Lw;(function(e){e[e.NotAllowed=0]=`NotAllowed`,e[e.DuplicateName=1]=`DuplicateName`,e[e.Timeout=2]=`Timeout`,e[e.LimitReached=3]=`LimitReached`,e[e.Disconnected=4]=`Disconnected`,e[e.Cancelled=5]=`Cancelled`,e[e.InvalidName=6]=`InvalidName`,e[e.Unknown=7]=`Unknown`})(Lw||={});var Rw=class e extends py{constructor(e,t,n){super(21,e,n),this.name=`DataTrackPublishError`,this.reason=t,this.reasonName=Lw[t],this.rawMessage=n?.rawMessage}static notAllowed(t){return new e(`Data track publishing unauthorized`,Lw.NotAllowed,{rawMessage:t})}static duplicateName(t){return new e(`Track name already taken`,Lw.DuplicateName,{rawMessage:t})}static invalidName(t){return new e(`Track name is invalid`,Lw.InvalidName,{rawMessage:t})}static timeout(){return new e(`Publish data track timed-out. Does the LiveKit server support data tracks?`,Lw.Timeout)}static limitReached(t){return new e(`Data track publication limit reached`,Lw.LimitReached,{rawMessage:t})}static unknown(t,n){return new e(`Received RequestResponse for publishDataTrack, but reason was unrecognised (${t}, ${n})`,Lw.Unknown)}static disconnected(){return new e(`Room disconnected`,Lw.Disconnected)}static cancelled(){return new e(`Publish data track cancelled by caller`,Lw.Cancelled)}},zw;(function(e){e[e.TrackUnpublished=0]=`TrackUnpublished`,e[e.Dropped=1]=`Dropped`})(zw||={});var Bw=class e extends py{constructor(e,t,n){super(22,e,n),this.name=`DataTrackPushFrameError`,this.reason=t,this.reasonName=zw[t]}static trackUnpublished(){return new e(`Track is no longer published`,zw.TrackUnpublished)}static dropped(t){return new e(`Frame was dropped`,zw.Dropped,{cause:t})}},Vw;(function(e){e[e.Packetizer=0]=`Packetizer`,e[e.Encryption=1]=`Encryption`})(Vw||={});var Hw=class e extends py{constructor(e,t,n){super(21,e,n),this.name=`DataTrackOutgoingPipelineError`,this.reason=t,this.reasonName=Vw[t]}static packetizer(t){return new e(`Error packetizing frame`,Vw.Packetizer,{cause:t})}static encryption(t){return new e(`Error encrypting frame`,Vw.Encryption,{cause:t})}},Uw=class e{constructor(e,t){this.trackSymbol=gw,this.isLocal=!0,this.typeSymbol=_w,this.handle=null,this.log=I,this.options=e,this.manager=t,this.log=M_(j_.DataTracks)}static withExplicitHandle(t,n,r){let i=new e(t,n);return i.handle=r,i}get info(){let e=this.descriptor;if(e?.type===`active`)return e.info}get descriptor(){return this.handle?this.manager.getDescriptor(this.handle):null}publish(e){return L(this,void 0,void 0,function*(){try{this.handle=yield this.manager.publishRequest(this.options,e)}catch(e){throw e}})}isPublished(){return this.descriptor?.type===`active`&&this.descriptor.publishState!==`unpublished`}tryPush(e){if(!this.handle)throw Bw.trackUnpublished();let t=hw.from(e);try{return this.manager.tryProcessAndSend(this.handle,t)}catch(e){throw e}}unpublish(){return L(this,void 0,void 0,function*(){if(!this.handle){I.warn(`Data track "${this.options.name}" is not published, so unpublishing has no effect.`);return}try{yield this.manager.unpublishRequest(this.handle)}catch(e){throw e}})}},Ww=class e{constructor(t){this.e2eeManager=t.e2eeManager,this.packetizer=new Iw(t.info.pubHandle,e.TRANSPORT_MTU_BYTES)}updateE2eeManager(e){this.e2eeManager=e}processFrame(e){return B_(this,arguments,function*(){let t=yield z_(this.encryptIfNeeded(e));try{yield z_(yield*V_(H_(this.packetizer.packetize(t))))}catch(e){throw e instanceof Pw?Hw.packetizer(e):e}})}encryptIfNeeded(e){return L(this,void 0,void 0,function*(){if(!this.e2eeManager)return e;let t;try{t=yield this.e2eeManager.encryptData(e.payload)}catch(e){throw Hw.encryption(e)}return e.payload=t.payload,e.extensions.e2ee=new pw(t.keyIndex,t.iv),e})}};Ww.TRANSPORT_MTU_BYTES=16e3;var Gw=M_(j_.DataTracks),Kw={pending(){return{type:`pending`,completionFuture:new Bb}},active(e,t){return{type:`active`,info:e,publishState:`published`,pipeline:new Ww({info:e,e2eeManager:t}),unpublishingFuture:new Bb}}},qw=1e4,Jw=class e extends K_.EventEmitter{constructor(e){super(),this.handleAllocator=new Bx,this.descriptors=new Map,this.e2eeManager=e?.e2eeManager??null}static withDescriptors(t){let n=new e;return n.descriptors=t,n}updateE2eeManager(e){this.e2eeManager=e;for(let t of this.descriptors.values())t.type===`active`&&t.pipeline.updateE2eeManager(e)}getDescriptor(e){return this.descriptors.get(e)??null}tryProcessAndSend(e,t){return L(this,void 0,void 0,function*(){var n,r,i,a;let o=this.getDescriptor(e);if(o?.type!==`active`||o.publishState===`unpublished`)throw Bw.trackUnpublished();if(o.publishState===`republishing`)throw Bw.dropped(`Data track republishing`);try{try{for(var s=!0,c=H_(o.pipeline.processFrame(t)),l;l=yield c.next(),n=l.done,!n;s=!0){a=l.value,s=!1;let e=a;this.emit(`packetAvailable`,{bytes:e.toBinary()})}}catch(e){r={error:e}}finally{try{!s&&!n&&(i=c.return)&&(yield i.call(c))}finally{if(r)throw r.error}}}catch(e){throw Bw.dropped(e)}})}publishRequest(e,t){return L(this,void 0,void 0,function*(){let n=this.handleAllocator.get();if(!n)throw Rw.limitReached();let r=BC(qw),i=t?zC([t,r]):r;if(this.descriptors.has(n))throw Error(`Descriptor for handle already exists`);let a=Kw.pending();this.descriptors.set(n,a);let o=()=>{var e,t;let i=this.descriptors.get(n);if(!i){Gw.warn(`No descriptor for ${n}`);return}this.descriptors.delete(n),this.emit(`sfuUnpublishRequest`,{handle:n}),i.type===`pending`&&((t=(e=i.completionFuture).reject)==null||t.call(e,r.aborted?Rw.timeout():Rw.cancelled()))};return i.aborted?(o(),a.completionFuture.promise.then(()=>n)):(i.addEventListener(`abort`,o),this.emit(`sfuPublishRequest`,{handle:n,name:e.name,usesE2ee:this.e2eeManager!==null}),yield a.completionFuture.promise,i.removeEventListener(`abort`,o),this.emit(`trackPublished`,{track:Uw.withExplicitHandle(e,this,n)}),n)})}queryPublished(){return Array.from(this.descriptors.values()).filter(e=>e.type===`active`).map(e=>e.info)}unpublishRequest(e){return L(this,void 0,void 0,function*(){let t=this.descriptors.get(e);if(!t){Gw.warn(`No descriptor for ${e}`);return}if(t.type!==`active`){Gw.warn(`Track ${e} not active`);return}this.emit(`sfuUnpublishRequest`,{handle:e}),yield t.unpublishingFuture.promise,this.emit(`trackUnpublished`,{sid:t.info.sid})})}receivedSfuPublishResponse(e,t){var n,r,i,a;let o=this.descriptors.get(e);if(!o){Gw.warn(`No descriptor for ${e}`);return}switch(this.descriptors.delete(e),o.type){case`pending`:if(t.type===`ok`){let e=t.data,i=e.usesE2ee?this.e2eeManager:null;this.descriptors.set(e.pubHandle,Kw.active(e,i)),(r=(n=o.completionFuture).resolve)==null||r.call(n)}else (a=(i=o.completionFuture).reject)==null||a.call(i,t.error);return;case`active`:if(o.publishState!==`republishing`){Gw.warn(`Track ${e} already active`);return}if(t.type===`error`){Gw.warn(`Republish failed for track ${e}`);return}Gw.debug(`Track ${e} republished`),o.info.sid=t.data.sid,o.publishState=`published`,this.descriptors.set(o.info.pubHandle,o)}}receivedSfuUnpublishResponse(e){var t,n;let r=this.descriptors.get(e);if(!r){Gw.warn(`No descriptor for ${e}`);return}if(this.descriptors.delete(e),r.type!==`active`){Gw.warn(`Track ${e} not active`);return}r.publishState=`unpublished`,(n=(t=r.unpublishingFuture).resolve)==null||n.call(t)}sfuWillRepublishTracks(){var e,t;for(let[n,r]of this.descriptors.entries())switch(r.type){case`pending`:this.descriptors.delete(n),(t=(e=r.completionFuture).reject)==null||t.call(e,Rw.disconnected());break;case`active`:r.publishState=`republishing`,this.emit(`sfuPublishRequest`,{handle:r.info.pubHandle,name:r.info.name,usesE2ee:r.info.usesE2ee})}}shutdown(){return L(this,void 0,void 0,function*(){var e,t,n,r;for(let i of this.descriptors.values())switch(i.type){case`pending`:(t=(e=i.completionFuture).reject)==null||t.call(e,Rw.disconnected());break;case`active`:(r=(n=i.unpublishingFuture).resolve)==null||r.call(n),yield this.unpublishRequest(i.info.pubHandle);break}this.descriptors.clear()})}},Yw=class extends K{constructor(e,t,n,r,i){super(e,n,i),this.sid=t,this.receiver=r}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?U.Muted:U.Unmuted,this))}setMediaStream(e){this.mediaStream=e;let t=n=>{n.track===this._mediaStreamTrack&&(e.removeEventListener(`removetrack`,t),this.receiver&&`playoutDelayHint`in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(U.Ended,this))};e.addEventListener(`removetrack`,t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return L(this,void 0,void 0,function*(){if(this.receiver?.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||=setInterval(()=>this.monitorReceiver(),zS),Ky()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){let e=()=>{this.timeSyncHandle=requestAnimationFrame(()=>e());let t=this.receiver?.getSynchronizationSources()[0];if(t){let{timestamp:e,rtpTimestamp:n}=t;n&&this.rtpTimestamp!==n&&(this.emit(U.TimeSyncUpdate,{timestamp:e,rtpTimestamp:n}),this.rtpTimestamp=n)}};e()}},Xw=class extends Yw{constructor(e,t,n,r,i,a){super(e,t,K.Kind.Audio,n,a),this.monitorReceiver=()=>L(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=BS(e,this.prevStats)),this.prevStats=e}),this.audioContext=r,this.webAudioPluginNodes=[],i&&(this.sinkId=i.deviceId)}setVolume(e){var t;for(let n of this.attachedElements)this.audioContext?(t=this.gainNode)==null||t.gain.setTargetAtTime(e,0,.1):n.volume=e;Cb()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(Cb())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return L(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(fb(t))return t.setSinkId(e)}))})}attach(e){let t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&fb(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 n=this.sourceNode;this.webAudioPluginNodes.forEach(e=>{n.connect(e),n=e}),this.gainNode=e.createGain(),n.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),e.state!==`running`&&e.resume().then(()=>{e.state!==`running`&&this.emit(U.AudioPlaybackFailed,Error(`Audio Context couldn't be started automatically`))}).catch(e=>{this.emit(U.AudioPlaybackFailed,e)})}disconnectWebAudio(){var e,t;(e=this.gainNode)==null||e.disconnect(),(t=this.sourceNode)==null||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return L(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;let e=yield this.receiver.getStats(),t;return e.forEach(e=>{e.type===`inbound-rtp`&&(t={type:`audio`,streamId:e.id,timestamp:e.timestamp,jitter:e.jitter,bytesReceived:e.bytesReceived,concealedSamples:e.concealedSamples,concealmentEvents:e.concealmentEvents,silentConcealedSamples:e.silentConcealedSamples,silentConcealmentEvents:e.silentConcealmentEvents,totalAudioEnergy:e.totalAudioEnergy,totalSamplesDuration:e.totalSamplesDuration})}),t})}},Zw=100,Qw=class extends Yw{constructor(e,t,n,r,i){super(e,t,K.Kind.Video,n,i),this.elementInfos=[],this.monitorReceiver=()=>L(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=BS(e,this.prevStats)),this.prevStats=e}),this.debouncedHandleResize=mS(()=>{this.updateDimensions()},Zw),this.adaptiveStreamSettings=r}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}setStreamState(e){super.setStreamState(e),this.log.debug(`setStreamState`,e),this.isAdaptiveStream&&e===K.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?nb(this._mediaStreamTrack,t):tb(this._mediaStreamTrack,t)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(t=>t.element===e)===void 0){let t=new $w(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&this.elementInfos.find(t=>t===e)===void 0?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn(`visibility resize observer not triggered`,this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream){this.log.warn(`stopObservingElementInfo ignored`,this.logContext);return}let t=this.elementInfos.filter(t=>t===e);for(let e of t)e.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);t=super.detach();for(let e of t)this.stopObservingElement(e);return t}getDecoderImplementation(){return this.prevStats?.decoderImplementation}getReceiverStats(){return L(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;let e=yield this.receiver.getStats(),t,n=``,r=new Map;return e.forEach(e=>{e.type===`inbound-rtp`?(n=e.codecId,t={type:`video`,streamId:e.id,framesDecoded:e.framesDecoded,framesDropped:e.framesDropped,framesReceived:e.framesReceived,packetsReceived:e.packetsReceived,packetsLost:e.packetsLost,frameWidth:e.frameWidth,frameHeight:e.frameHeight,pliCount:e.pliCount,firCount:e.firCount,nackCount:e.nackCount,jitter:e.jitter,timestamp:e.timestamp,bytesReceived:e.bytesReceived,decoderImplementation:e.decoderImplementation}):e.type===`codec`&&r.set(e.id,e)}),t&&n!==``&&r.get(n)&&(t.mimeType=r.get(n).mimeType),t})}stopObservingElement(e){let t=this.elementInfos.filter(t=>t.element===e);for(let e of t)this.stopObservingElementInfo(e)}handleAppVisibilityChanged(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return L(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(e){let t=this.elementInfos.reduce((e,t)=>Math.max(e,t.visibilityChangedAt||0),0),n=this.adaptiveStreamSettings?.pauseVideoInBackground??!0?this.isInBackground:!1,r=this.elementInfos.some(e=>e.pictureInPicture),i=this.elementInfos.some(e=>e.visible)&&!n||r;if(!(this.lastVisible===i&&!e)){if(!i&&Date.now()-t<Zw){Ty.setTimeout(()=>{this.updateVisibility()},Zw);return}this.lastVisible=i,this.emit(U.VisibilityChanged,i,this)}}updateDimensions(){let e=0,t=0,n=this.getPixelDensity();for(let r of this.elementInfos){let i=r.width()*n,a=r.height()*n;i+a>e+t&&(e=i,t=a)}this.lastDimensions?.width===e&&this.lastDimensions?.height===t||(this.lastDimensions={width:e,height:t},this.emit(U.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){let e=this.adaptiveStreamSettings?.pixelDensity;return e===`screen`?Ob():e||(Ob()>2?2:1)}},$w=class{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=e=>{var t;let{target:n,isIntersecting:r}=e;n===this.element&&(this.isIntersecting=r,this.isPiP=eT(this.element),this.visibilityChangedAt=Date.now(),(t=this.handleVisibilityChanged)==null||t.call(this))},this.onEnterPiP=()=>{var e,t;(e=window.documentPictureInPicture?.window)==null||e.addEventListener(`pagehide`,this.onLeavePiP),this.isPiP=eT(this.element),(t=this.handleVisibilityChanged)==null||t.call(this)},this.onLeavePiP=()=>{var e;this.isPiP=eT(this.element),(e=this.handleVisibilityChanged)==null||e.call(this)},this.element=e,this.isIntersecting=t??tT(e),this.isPiP=Sb()&&eT(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t;this.isIntersecting=tT(this.element),this.isPiP=eT(this.element),this.element.handleResize=()=>{var e;(e=this.handleResize)==null||e.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,Fb().observe(this.element),Nb().observe(this.element),this.element.addEventListener(`enterpictureinpicture`,this.onEnterPiP),this.element.addEventListener(`leavepictureinpicture`,this.onLeavePiP),(e=window.documentPictureInPicture)==null||e.addEventListener(`enter`,this.onEnterPiP),(t=window.documentPictureInPicture?.window)==null||t.addEventListener(`pagehide`,this.onLeavePiP)}stopObserving(){var e,t,n,r;(e=Fb())==null||e.unobserve(this.element),(t=Nb())==null||t.unobserve(this.element),this.element.removeEventListener(`enterpictureinpicture`,this.onEnterPiP),this.element.removeEventListener(`leavepictureinpicture`,this.onLeavePiP),(n=window.documentPictureInPicture)==null||n.removeEventListener(`enter`,this.onEnterPiP),(r=window.documentPictureInPicture?.window)==null||r.removeEventListener(`pagehide`,this.onLeavePiP)}};function eT(e){return document.pictureInPictureElement===e?!0:window.documentPictureInPicture?.window?tT(e,window.documentPictureInPicture?.window):!1}function tT(e,t){let n=t||window,r=e.offsetTop,i=e.offsetLeft,a=e.offsetWidth,o=e.offsetHeight,{hidden:s}=e,{display:c}=getComputedStyle(e);for(;e.offsetParent;)e=e.offsetParent,r+=e.offsetTop,i+=e.offsetLeft;return r<n.pageYOffset+n.innerHeight&&i<n.pageXOffset+n.innerWidth&&r+o>n.pageYOffset&&i+a>n.pageXOffset&&!s&&c!==`none`}var nT=class extends K_.EventEmitter{constructor(e,t,n,r){super(),this.metadataMuted=!1,this.encryption=F.NONE,this.log=I,this.handleMuted=()=>{this.emit(U.Muted)},this.handleUnmuted=()=>{this.emit(U.Unmuted)},this.log=M_(r?.loggerName??j_.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=n,this.source=K.Source.Unknown}setTrack(e){this.track&&(this.track.off(U.Muted,this.handleMuted),this.track.off(U.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(U.Muted,this.handleMuted),e.on(U.Unmuted,this.handleUnmuted))}get logContext(){return Object.assign(Object.assign({},this.loggerContextCb?.call(this)),G(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==F.NONE}get audioTrack(){if(Zb(this.track))return this.track}get videoTrack(){if(Qb(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=K.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===K.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){(function(e){e.Desired=`desired`,e.Subscribed=`subscribed`,e.Unsubscribed=`unsubscribed`})(e.SubscriptionStatus||={}),(function(e){e.Allowed=`allowed`,e.NotAllowed=`not_allowed`})(e.PermissionStatus||={})})(nT||={});var rT=class extends nT{get isUpstreamPaused(){return this.track?.isUpstreamPaused}constructor(e,t,n,r){super(e,t.sid,t.name,r),this.track=void 0,this.handleTrackEnded=()=>{this.emit(U.Ended)},this.handleCpuConstrained=()=>{this.track&&Qb(this.track)&&this.emit(U.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(n)}setTrack(e){this.track&&(this.track.off(U.Ended,this.handleTrackEnded),this.track.off(U.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(U.Ended,this.handleTrackEnded),e.on(U.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 L(this,void 0,void 0,function*(){return this.track?.mute()})}unmute(){return L(this,void 0,void 0,function*(){return this.track?.unmute()})}pauseUpstream(){return L(this,void 0,void 0,function*(){yield this.track?.pauseUpstream()})}resumeUpstream(){return L(this,void 0,void 0,function*(){yield this.track?.resumeUpstream()})}getTrackFeatures(){if(Zb(this.track)){let e=this.track.getSourceTrackSettings(),t=new Set;return e.autoGainControl&&t.add(wh.TF_AUTO_GAIN_CONTROL),e.echoCancellation&&t.add(wh.TF_ECHO_CANCELLATION),e.noiseSuppression&&t.add(wh.TF_NOISE_SUPPRESSION),e.channelCount&&e.channelCount>1&&t.add(wh.TF_STEREO),this.options?.dtx||t.add(wh.TF_NO_DTX),this.track.enhancedNoiseCancellation&&t.add(wh.TF_ENHANCED_NOISE_CANCELLATION),Array.from(t.values())}else return[]}};function iT(e,t){return L(this,void 0,void 0,function*(){e??={};let n=!1,{audioProcessor:r,videoProcessor:i,optionsWithoutProcessor:a}=Jy(e),o=a.audio,s=a.video;if(r&&typeof a.audio==`object`&&(a.audio.processor=r),i&&typeof a.video==`object`&&(a.video.processor=i),e.audio&&typeof a.audio==`object`&&typeof a.audio.deviceId==`string`){let e=a.audio.deviceId;a.audio.deviceId={exact:e},n=!0,o=Object.assign(Object.assign({},a.audio),{deviceId:{ideal:e}})}if(a.video&&typeof a.video==`object`&&typeof a.video.deviceId==`string`){let e=a.video.deviceId;a.video.deviceId={exact:e},n=!0,s=Object.assign(Object.assign({},a.video),{deviceId:{ideal:e}})}a.audio===!0?a.audio={deviceId:`default`}:typeof a.audio==`object`&&a.audio!==null&&(a.audio=Object.assign(Object.assign({},a.audio),{deviceId:a.audio.deviceId||`default`})),a.video===!0?a.video={deviceId:`default`}:typeof a.video==`object`&&!a.video.deviceId&&(a.video.deviceId=`default`);let c=Iy(a,TS,ES),l=Ry(c),u=navigator.mediaDevices.getUserMedia(l);a.audio&&(Ax.userMediaPromiseMap.set(`audioinput`,u),u.catch(()=>Ax.userMediaPromiseMap.delete(`audioinput`))),a.video&&(Ax.userMediaPromiseMap.set(`videoinput`,u),u.catch(()=>Ax.userMediaPromiseMap.delete(`videoinput`)));try{let e=yield u;return yield Promise.all(e.getTracks().map(n=>L(this,void 0,void 0,function*(){let a=n.kind===`audio`,o=a?c.audio:c.video;(typeof o==`boolean`||!o)&&(o={});let s,u=a?l.audio:l.video;typeof u!=`boolean`&&(s=u);let d=n.getSettings().deviceId;s?.deviceId&&Hb(s.deviceId)!==d?s.deviceId=d:s||={deviceId:d};let f=YS(n,s,t);return f.kind===K.Kind.Video?f.source=K.Source.Camera:f.kind===K.Kind.Audio&&(f.source=K.Source.Microphone),f.mediaStream=e,Zb(f)&&r?yield f.setProcessor(r):Qb(f)&&i&&(yield f.setProcessor(i)),f})))}catch(r){if(!n)throw r;return iT(Object.assign(Object.assign({},e),{audio:o,video:s}),t)}})}function aT(e){return L(this,void 0,void 0,function*(){return(yield iT({audio:e??!0,video:!1}))[0]})}var oT;(function(e){e.Excellent=`excellent`,e.Good=`good`,e.Poor=`poor`,e.Lost=`lost`,e.Unknown=`unknown`})(oT||={});function sT(e){switch(e){case yh.EXCELLENT:return oT.Excellent;case yh.GOOD:return oT.Good;case yh.POOR:return oT.Poor;case yh.LOST:return oT.Lost;default:return oT.Unknown}}var cT=class extends K_.EventEmitter{get logContext(){var e;return Object.assign({},((e=this.loggerOptions)?.loggerContextCb)?.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every(e=>e.isEncrypted)}get isAgent(){return this.permissions?.agent||this.kind===Ah.AGENT}get isActive(){return this.participantInfo?.state===kh.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,n,r,i,a){let o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:Ah.STANDARD;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=oT.Unknown,this.log=I,this.log=M_(a?.loggerName??j_.Participant),this.loggerOptions=a,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=n,this.metadata=r,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=o,this._attributes=i??{}}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.promise:(this.activeFuture=new Bb,this.once(V.Active,()=>{var e,t;(t=(e=this.activeFuture)?.resolve)==null||t.call(e),this.activeFuture=void 0}),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){return!(this.getTrackPublication(K.Source.Camera)?.isMuted??!0)}get isMicrophoneEnabled(){return!(this.getTrackPublication(K.Source.Microphone)?.isMuted??!0)}get isScreenShareEnabled(){return!!this.getTrackPublication(K.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(Number.parseInt(this.participantInfo.joinedAt.toString())*1e3):new Date}updateInfo(e){return this.participantInfo&&this.participantInfo.sid===e.sid&&this.participantInfo.version>e.version?!1:(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),this._setAttributes(e.attributes),e.state===kh.ACTIVE&&this.participantInfo?.state!==kh.ACTIVE&&this.emit(V.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){let t=this.metadata!==e,n=this.metadata;this.metadata=e,t&&this.emit(V.ParticipantMetadataChanged,n)}_setName(e){let t=this.name!==e;this.name=e,t&&this.emit(V.ParticipantNameChanged,e)}_setAttributes(e){let t=qy(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(V.AttributesChanged,t)}setPermissions(e){let t=this.permissions,n=e.canPublish!==this.permissions?.canPublish||e.canSubscribe!==this.permissions?.canSubscribe||e.canPublishData!==this.permissions?.canPublishData||e.hidden!==this.permissions?.hidden||e.recorder!==this.permissions?.recorder||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((e,t)=>e!==this.permissions?.canPublishSources[t])||e.canSubscribeMetrics!==this.permissions?.canSubscribeMetrics;return this.permissions=e,n&&this.emit(V.ParticipantPermissionsChanged,t),n}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(V.IsSpeakingChanged,e))}setConnectionQuality(e){let t=this._connectionQuality;this._connectionQuality=sT(e),t!==this._connectionQuality&&this.emit(V.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,t;this.activeFuture&&=((t=(e=this.activeFuture).reject)==null||t.call(e,Error(`Participant disconnected`)),void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(t=>Zb(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(U.Muted,()=>{this.emit(V.TrackMuted,e)}),e.on(U.Unmuted,()=>{this.emit(V.TrackUnmuted,e)});let t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case K.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case K.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}};function lT(e){if(!e.participantSid&&!e.participantIdentity)throw Error(`Invalid track permission, must provide at least one of participantIdentity and participantSid`);return new r_({participantIdentity:e.participantIdentity??``,participantSid:e.participantSid??``,allTracks:e.allowAll??!1,trackSids:e.allowedTrackSids||[]})}var uT=class extends cT{constructor(e,t,n,r,i,a,o){super(e,t,void 0,void 0,void 0,{loggerName:r.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=F.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||=new Bb},this.handleReconnected=()=>{var e,t;(t=(e=this.reconnectFuture)?.resolve)==null||t.call(e),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var e,t,n,r,i,a;this.reconnectFuture&&=(this.reconnectFuture.promise.catch(e=>this.log.warn(e.message,this.logContext)),(t=(e=this.reconnectFuture)?.reject)==null||t.call(e,Error(`Got disconnected during reconnection attempt`)),void 0),this.signalConnectedFuture&&=((r=(n=this.signalConnectedFuture).reject)==null||r.call(n,Error(`Got disconnected without signal connected`)),void 0),(a=(i=this.activeAgentFuture)?.reject)==null||a.call(i,Error(`Got disconnected without active agent present`)),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=e=>{var t,n;e.participant&&this.updateInfo(e.participant),this.signalConnectedFuture||=new Bb,(n=(t=this.signalConnectedFuture).resolve)==null||n.call(t)},this.handleSignalRequestResponse=e=>{let{requestId:t,reason:n,message:r}=e,i=this.pendingSignalRequests.get(t);switch(i&&(n!==__.OK&&i.reject(new by(r,n)),this.pendingSignalRequests.delete(t)),e.request.case){case`publishDataTrack`:{let t;switch(e.reason){case __.NOT_ALLOWED:t=Rw.notAllowed(e.message);break;case __.DUPLICATE_NAME:t=Rw.duplicateName(e.message);break;case __.INVALID_NAME:t=Rw.invalidName(e.message);break;case __.LIMIT_EXCEEDED:t=Rw.limitReached(e.message);break;default:t=Rw.unknown(e.reason,e.message);return}this.roomOutgoingDataTrackManager.receivedSfuPublishResponse(e.request.value.pubHandle,{type:`error`,error:t});break}}},this.handleDataPacket=e=>{switch(e.value.case){case`rpcResponse`:let t=e.value.value,n=null,r=null;t.value.case===`payload`?n=t.value.value:t.value.case===`error`&&(r=FS.fromProto(t.value.value)),this.handleIncomingRpcResponse(t.requestId,n,r);break;case`rpcAck`:let i=e.value.value;this.handleIncomingRpcAck(i.requestId);break}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug(`updating track subscription permissions`,Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(e=>lT(e)))},this.onTrackUnmuted=e=>{this.onTrackMuted(e,e.isUpstreamPaused)},this.onTrackMuted=(e,t)=>{if(t===void 0&&(t=!0),!e.sid){this.log.error(`could not update mute status for unpublished track`,Object.assign(Object.assign({},this.logContext),G(e)));return}this.engine.updateMuteStatus(e.sid,t)},this.onTrackUpstreamPaused=e=>{this.log.debug(`upstream paused`,Object.assign(Object.assign({},this.logContext),G(e))),this.onTrackMuted(e,!0)},this.onTrackUpstreamResumed=e=>{this.log.debug(`upstream resumed`,Object.assign(Object.assign({},this.logContext),G(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 ${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),G(t))),this.emit(V.LocalTrackCpuConstrained,e,t)},this.handleSubscribedQualityUpdate=e=>L(this,void 0,void 0,function*(){var t,n,r,i;if(!this.roomOptions?.dynacast)return;let a=this.videoTrackPublications.get(e.trackSid);if(!a){this.log.warn(`received subscribed quality update for unknown track`,Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}));return}if(!a.videoTrack)return;let o=yield a.videoTrack.setPublishingCodecs(e.subscribedCodecs);try{for(var s=!0,c=H_(o),l;l=yield c.next(),t=l.done,!t;s=!0){i=l.value,s=!1;let e=i;Ay(e)&&(this.log.debug(`publish ${e} for ${a.videoTrack.sid}`,Object.assign(Object.assign({},this.logContext),G(a))),yield this.publishAdditionalCodecForTrack(a.videoTrack,e,a.options))}}catch(e){n={error:e}}finally{try{!s&&!t&&(r=c.return)&&(yield r.call(c))}finally{if(n)throw n.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=>L(this,void 0,void 0,function*(){if(e.source===K.Source.ScreenShare||e.source===K.Source.ScreenShareAudio)this.log.debug(`unpublishing local track due to TrackEnded`,Object.assign(Object.assign({},this.logContext),G(e))),this.unpublishTrack(e);else if(e.isUserProvided)yield e.mute();else if(ex(e)||$b(e))try{if(Sb())try{let t=yield navigator==null?void 0:navigator.permissions.query({name:e.source===K.Source.Camera?`camera`:`microphone`});if(t&&t.state===`denied`)throw this.log.warn(`user has revoked access to ${e.source}`,Object.assign(Object.assign({},this.logContext),G(e))),t.onchange=()=>{t.state!==`denied`&&(e.isMuted||e.restartTrack(),t.onchange=null)},Error(`GetUserMedia Permission denied`)}catch{}e.isMuted||(this.log.debug(`track ended, attempting to use a different device`,Object.assign(Object.assign({},this.logContext),G(e))),ex(e)?yield e.restartTrack({deviceId:`default`}):yield e.restartTrack())}catch{this.log.warn(`could not restart track, muting instead`,Object.assign(Object.assign({},this.logContext),G(e))),yield e.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=n,this.roomOptions=r,this.setupEngine(n),this.activeDeviceMap=new Map([[`audioinput`,`default`],[`videoinput`,`default`],[`audiooutput`,`default`]]),this.pendingSignalRequests=new Map,this.rpcHandlers=i,this.roomOutgoingDataStreamManager=a,this.roomOutgoingDataTrackManager=o}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==F.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){this.engine=e,this.engine.on(H.RemoteMute,(e,t)=>{let n=this.trackPublications.get(e);!n||!n.track||(t?n.mute():n.unmute())}),this.signalConnectedFuture?.isResolved&&(this.signalConnectedFuture=void 0),this.engine.on(H.Connected,this.handleReconnected).on(H.SignalConnected,this.handleSignalConnected).on(H.SignalRestarted,this.handleReconnected).on(H.SignalResumed,this.handleReconnected).on(H.Restarting,this.handleReconnecting).on(H.Resuming,this.handleReconnecting).on(H.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(H.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(H.Closing,this.handleClosing).on(H.SignalRequestResponse,this.handleSignalRequestResponse).on(H.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return L(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return L(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return L(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return L(this,arguments,void 0,function(e){var t=this;let{metadata:n,name:r,attributes:i}=e;return function*(){return new iy((e,a)=>L(t,void 0,void 0,function*(){try{let t=!1,o=yield this.engine.client.sendUpdateLocalMetadata(n??this.metadata??``,r??this.name??``,i),s=performance.now();for(this.pendingSignalRequests.set(o,{resolve:e,reject:e=>{a(e),t=!0},values:{name:r,metadata:n,attributes:i}});performance.now()-s<5e3&&!t;){if((!r||this.name===r)&&(!n||this.metadata===n)&&(!i||Object.entries(i).every(e=>{let[t,n]=e;return this.attributes[t]===n||n===``&&!this.attributes[t]}))){this.pendingSignalRequests.delete(o),e();return}yield ob(50)}a(new by(`Request to update local metadata timed out`,`TimeoutError`))}catch(e){e instanceof Error?a(e):a(Error(String(e)))}}))}()})}setCameraEnabled(e,t,n){return this.setTrackEnabled(K.Source.Camera,e,t,n)}setMicrophoneEnabled(e,t,n){return this.setTrackEnabled(K.Source.Microphone,e,t,n)}setScreenShareEnabled(e,t,n){return this.setTrackEnabled(K.Source.ScreenShare,e,t,n)}setE2EEEnabled(e){return L(this,void 0,void 0,function*(){this.encryptionType=e?F.GCM:F.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,n,r){return L(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 i=this.getTrackPublication(e);if(t)if(i)yield i.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 t?.unmute(),t}this.pendingPublishing.add(e);try{switch(e){case K.Source.Camera:t=yield this.createTracks({video:n??!0});break;case K.Source.Microphone:t=yield this.createTracks({audio:n??!0});break;case K.Source.ScreenShare:t=yield this.createScreenTracks(Object.assign({},n));break;default:throw new hy(e)}}catch(n){throw t?.forEach(e=>{e.stop()}),n instanceof Error&&this.emit(V.MediaDevicesError,n,Hy(e)),this.pendingPublishing.delete(e),n}for(let r of t){let t=Object.assign(Object.assign({},this.roomOptions.publishDefaults),n);e===K.Source.Microphone&&Zb(r)&&t.preConnectBuffer&&(this.log.info(`starting preconnect buffer for microphone`,Object.assign({},this.logContext)),r.startPreConnectBuffer())}try{let e=[];for(let n of t)this.log.info(`publishing track`,Object.assign(Object.assign({},this.logContext),G(n))),e.push(this.publishTrack(n,r));let n=yield Promise.all(e);[i]=n}catch(e){throw t?.forEach(e=>{e.stop()}),e}finally{this.pendingPublishing.delete(e)}}else if(!i?.track&&this.pendingPublishing.has(e)&&(i=yield this.waitForPendingPublicationOfSource(e),i||this.log.info(`waiting for pending publication promise timed out`,Object.assign(Object.assign({},this.logContext),{source:e}))),i&&i.track)if(e===K.Source.ScreenShare){i=yield this.unpublishTrack(i.track);let e=this.getTrackPublication(K.Source.ScreenShareAudio);e&&e.track&&this.unpublishTrack(e.track)}else yield i.mute();return i})}enableCameraAndMicrophone(){return L(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(K.Source.Camera)||this.pendingPublishing.has(K.Source.Microphone))){this.pendingPublishing.add(K.Source.Camera),this.pendingPublishing.add(K.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(K.Source.Camera),this.pendingPublishing.delete(K.Source.Microphone)}}})}createTracks(e){return L(this,void 0,void 0,function*(){e??={};let t=Iy(e,this.roomOptions?.audioCaptureDefaults,this.roomOptions?.videoCaptureDefaults);try{return(yield iT(t,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(e=>(Zb(e)&&(this.microphoneError=void 0,e.setAudioContext(this.audioContext),e.source=K.Source.Microphone,this.emit(V.AudioStreamAcquired)),Qb(e)&&(this.cameraError=void 0,e.source=K.Source.Camera),e))}catch(t){throw t instanceof Error&&(e.audio&&(this.microphoneError=t),e.video&&(this.cameraError=t)),t}})}createScreenTracks(e){return L(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new my(`getDisplayMedia not supported`);e.resolution===void 0&&!vb()&&(e.resolution=Fy.h1080fps30.resolution);let t=Uy(e),n=yield navigator.mediaDevices.getDisplayMedia(t),r=n.getVideoTracks();if(r.length===0)throw new hy(`no video track found`);let i=new pC(r[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});i.source=K.Source.ScreenShare,e.contentHint&&(i.mediaStreamTrack.contentHint=e.contentHint);let a=[i];if(n.getAudioTracks().length>0){this.emit(V.AudioStreamAcquired);let e=new JS(n.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});e.source=K.Source.ScreenShareAudio,a.push(e)}return a})}publishTrack(e,t){return L(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}publishOrRepublishTrack(e,t){return L(this,arguments,void 0,function(e,t){var n=this;let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return function*(){ex(e)&&e.setAudioContext(n.audioContext),yield n.reconnectFuture?.promise,n.republishPromise&&!r&&(yield n.republishPromise),Xb(e)&&n.pendingPublishPromises.has(e)&&(yield n.pendingPublishPromises.get(e));let i;if(e instanceof MediaStreamTrack)i=e.getConstraints();else{i=e.constraints;let t;switch(e.source){case K.Source.Microphone:t=`audioinput`;break;case K.Source.Camera:t=`videoinput`}t&&n.activeDeviceMap.has(t)&&(i=Object.assign(Object.assign({},i),{deviceId:n.activeDeviceMap.get(t)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case`audio`:e=new JS(e,i,!0,n.audioContext,{loggerName:n.roomOptions.loggerName,loggerContextCb:()=>n.logContext});break;case`video`:e=new pC(e,i,!0,{loggerName:n.roomOptions.loggerName,loggerContextCb:()=>n.logContext});break;default:throw new hy(`unsupported MediaStreamTrack kind ${e.kind}`)}else e.updateLoggerOptions({loggerName:n.roomOptions.loggerName,loggerContextCb:()=>n.logContext});let a;if(n.trackPublications.forEach(t=>{t.track&&t.track===e&&(a=t)}),a)return n.log.warn(`track has already been published, skipping`,Object.assign(Object.assign({},n.logContext),G(a))),a;let o=Object.assign(Object.assign({},n.roomOptions.publishDefaults),t),s=`channelCount`in e.mediaStreamTrack.getSettings()&&e.mediaStreamTrack.getSettings().channelCount===2||e.mediaStreamTrack.getConstraints().channelCount===2,c=o.forceStereo??s;c&&(o.dtx===void 0&&n.log.info(`Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.`,Object.assign(Object.assign({},n.logContext),G(e))),o.red===void 0&&n.log.info(`Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work.`),o.dtx??=!1,o.red??=!1),!xb()&&n.roomOptions.e2ee&&(n.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({},n.logContext)),o.simulcast=!1),o.source&&(e.source=o.source);let l=new Promise((t,r)=>L(n,void 0,void 0,function*(){try{if(this.engine.client.currentState!==q.CONNECTED){this.log.debug(`deferring track publication until signal is connected`,Object.assign(Object.assign({},this.logContext),{track:G(e)}));let n=!1,i=setTimeout(()=>{n=!0,e.stop(),r(new yy(`publishing rejected as engine not connected within timeout`,408))},15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(i),n)return;t(yield this.publish(e,o,c))}else try{t(yield this.publish(e,o,c))}catch(e){r(e)}}catch(e){r(e)}}));n.pendingPublishPromises.set(e,l);try{return yield l}catch(e){throw e}finally{n.pendingPublishPromises.delete(e)}}()})}waitUntilEngineConnected(){return this.signalConnectedFuture||=new Bb,this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn(`no permissions present for publishing track`,Object.assign(Object.assign({},this.logContext),G(e))),!1;let{canPublish:t,canPublishSources:n}=this.permissions;return t&&(n.length===0||n.map(e=>Yy(e)).includes(e.source))?!0:(this.log.warn(`insufficient permissions to publish`,Object.assign(Object.assign({},this.logContext),G(e))),!1)}publish(e,t,n){return L(this,void 0,void 0,function*(){if(!this.hasPermissionsToPublish(e))throw new yy(`failed to publish track, insufficient permissions`,403);Array.from(this.trackPublications.values()).find(t=>Xb(e)&&t.source===e.source)&&e.source!==K.Source.Unknown&&this.log.info(`publishing a second track with the same source: ${e.source}`,Object.assign(Object.assign({},this.logContext),G(e))),t.stopMicTrackOnMute&&Zb(e)&&(e.stopOnMute=!0),e.source===K.Source.ScreenShare&&mb()&&(t.simulcast=!1),t.videoCodec===`av1`&&!lb()&&(t.videoCodec=void 0),t.videoCodec===`vp9`&&!ub()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=CS),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(e=>t.videoCodec===Wy(e.mime))||(t.videoCodec=Wy(this.enabledPublishVideoCodecs[0].mime)));let r=t.videoCodec;e.on(U.Muted,this.onTrackMuted),e.on(U.Unmuted,this.onTrackUnmuted),e.on(U.Ended,this.handleTrackEnded),e.on(U.UpstreamPaused,this.onTrackUpstreamPaused),e.on(U.UpstreamResumed,this.onTrackUpstreamResumed),e.on(U.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);let i=[],a=!(t.dtx??!0),o=e.getSourceTrackSettings();o.autoGainControl&&i.push(wh.TF_AUTO_GAIN_CONTROL),o.echoCancellation&&i.push(wh.TF_ECHO_CANCELLATION),o.noiseSuppression&&i.push(wh.TF_NOISE_SUPPRESSION),o.channelCount&&o.channelCount>1&&i.push(wh.TF_STEREO),a&&i.push(wh.TF_NO_DTX),ex(e)&&e.hasPreConnectBuffer&&i.push(wh.TF_PRECONNECT_BUFFER);let s=new xg({cid:e.mediaStreamTrack.id,name:t.name,type:K.kindToProto(e.kind),muted:e.isMuted,source:K.sourceToProto(e.source),disableDtx:a,encryption:this.encryptionType,stereo:n,disableRed:this.isE2EEEnabled||!(t.red??!0),stream:t?.stream,backupCodecPolicy:t?.backupCodecPolicy,audioFeatures:i}),c;if(e.kind===K.Kind.Video){let n={width:0,height:0};try{n=yield e.waitForDimensions()}catch{let t=this.roomOptions.videoCaptureDefaults?.resolution??Ny.h720.resolution;n={width:t.width,height:t.height},this.log.error(`could not determine track dimensions, using defaults`,Object.assign(Object.assign(Object.assign({},this.logContext),G(e)),{dims:n}))}s.width=n.width,s.height=n.height,$b(e)&&(db(r)&&(e.source===K.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),G(e))))),t.scalabilityMode=t.scalabilityMode??`L3T3_KEY`),s.simulcastCodecs=[new bg({codec:r,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:CS}),t.backupCodec&&r!==t.backupCodec.codec&&s.encryption===F.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),s.simulcastCodecs.push(new bg({codec:t.backupCodec.codec,cid:``})))),c=rC(e.source===K.Source.ScreenShare,s.width,s.height,t),s.layers=gC(s.width,s.height,c,db(t.videoCodec))}else e.kind===K.Kind.Audio&&(c=[{maxBitrate:t.audioPreset?.maxBitrate,priority:t.audioPreset?.priority??`high`,networkPriority:t.audioPreset?.priority??`high`}]);if(!this.engine||this.engine.isClosed)throw new _y(`cannot publish track when not connected`);let l=()=>L(this,void 0,void 0,function*(){if(!this.engine.pcManager)throw new _y(`pcManager is not ready`);if(e.sender=yield this.engine.createSender(e,t,c),this.emit(V.LocalSenderCreated,e.sender,e),$b(e)&&(t.degradationPreference??=dC(e),e.setDegradationPreference(t.degradationPreference)),c)if(mb()&&e.kind===K.Kind.Audio){let t;for(let n of this.engine.pcManager.publisher.getTransceivers())if(n.sender===e.sender){t=n;break}t&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:t,codec:`opus`,maxbr:c[0]?.maxBitrate?c[0].maxBitrate/1e3:0})}else e.codec&&db(e.codec)&&c[0]?.maxBitrate&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:s.cid,codec:e.codec,maxbr:c[0].maxBitrate/1e3});yield this.engine.negotiate()}),u,d=new Promise((t,n)=>L(this,void 0,void 0,function*(){try{u=yield this.engine.addTrack(s),t(u)}catch(t){e.sender&&this.engine.pcManager?.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),G(e)),{error:t}))})),n(t)}}));if(this.enabledPublishVideoCodecs.length>0)u=(yield Promise.all([d,l()]))[0];else{u=yield d;let n;if(u.codecs.forEach(e=>{n===void 0&&(n=e.mimeType)}),n&&e.kind===K.Kind.Video){let i=Wy(n);i!==r&&(this.log.debug(`falling back to server selected codec`,Object.assign(Object.assign(Object.assign({},this.logContext),G(e)),{codec:i})),t.videoCodec=i,c=rC(e.source===K.Source.ScreenShare,s.width,s.height,t))}yield l()}let f=new rT(e.kind,u,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(f.on(U.CpuConstrained,e=>this.onTrackCpuConstrained(e,f)),f.options=t,e.sid=u.sid,this.log.debug(`publishing ${e.kind} with encodings`,Object.assign(Object.assign({},this.logContext),{encodings:c,trackInfo:u})),$b(e)?e.startMonitor(this.engine.client):ex(e)&&e.startMonitor(),this.addTrackPublication(f),this.emit(V.LocalTrackPublished,f),ex(e)&&u.audioFeatures.includes(wh.TF_PRECONNECT_BUFFER)){let t=e.getPreConnectBuffer(),n=e.getPreConnectBufferMimeType();this.on(V.LocalTrackSubscribed,t=>{if(t.trackSid===u.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),G(e))),e.stopPreConnectBuffer()}}),t&&new Promise((r,i)=>L(this,void 0,void 0,function*(){var a,s,c,l;try{this.log.debug(`waiting for agent`,Object.assign(Object.assign({},this.logContext),G(e)));let m=setTimeout(()=>{i(Error(`agent not active within 10 seconds`))},1e4),h=yield this.waitUntilActiveAgentPresent();clearTimeout(m),this.log.debug(`sending preconnect buffer`,Object.assign(Object.assign({},this.logContext),G(e)));let g=yield this.streamBytes({name:`preconnect-buffer`,mimeType:n,topic:`lk.agent.pre-connect-audio-buffer`,destinationIdentities:[h.identity],attributes:{trackId:f.trackSid,sampleRate:String(o.sampleRate??`48000`),channels:String(o.channelCount??`1`)}});try{for(var u=!0,d=H_(t),p;p=yield d.next(),a=p.done,!a;u=!0){l=p.value,u=!1;let e=l;yield g.write(e)}}catch(e){s={error:e}}finally{try{!u&&!a&&(c=d.return)&&(yield c.call(d))}finally{if(s)throw s.error}}yield g.close(),r()}catch(e){i(e)}})).then(()=>{this.log.debug(`preconnect buffer sent successfully`,Object.assign(Object.assign({},this.logContext),G(e)))}).catch(t=>{this.log.error(`error sending preconnect buffer`,Object.assign(Object.assign(Object.assign({},this.logContext),G(e)),{error:t}))})}return f})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,n){return L(this,void 0,void 0,function*(){if(this.encryptionType!==F.NONE)return;let r;if(this.trackPublications.forEach(t=>{t.track&&t.track===e&&(r=t)}),!r)throw new hy(`track is not published`);if(!$b(e))throw new hy(`track is not a video track`);let i=Object.assign(Object.assign({},this.roomOptions?.publishDefaults),n),a=iC(e,t,i);if(!a){this.log.info(`backup codec has been disabled, ignoring request to add additional codec for track`,Object.assign(Object.assign({},this.logContext),G(e)));return}let o=e.addSimulcastTrack(t,a);if(!o)return;let s=new xg({cid:o.mediaStreamTrack.id,type:K.kindToProto(e.kind),muted:e.isMuted,source:K.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:i.videoCodec,cid:o.mediaStreamTrack.id}]});if(s.layers=gC(s.width,s.height,a),!this.engine||this.engine.isClosed)throw new _y(`cannot publish track when not connected`);let c=(yield Promise.all([this.engine.addTrack(s),L(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,o,i,a),yield this.engine.negotiate()})]))[0];this.log.debug(`published ${t} for track ${e.sid}`,Object.assign(Object.assign({},this.logContext),{encodings:a,trackInfo:c}))})}unpublishTrack(e,t){return L(this,void 0,void 0,function*(){if(Xb(e)){let t=this.pendingPublishPromises.get(e);t&&(this.log.info(`awaiting publish promise before attempting to unpublish`,Object.assign(Object.assign({},this.logContext),G(e))),yield t)}let n=this.getPublicationForTrack(e),r=n?G(n):void 0;if(this.log.debug(`unpublishing track`,Object.assign(Object.assign({},this.logContext),r)),!n||!n.track){this.log.warn(`track was not unpublished because no publication was found`,Object.assign(Object.assign({},this.logContext),r));return}e=n.track,e.off(U.Muted,this.onTrackMuted),e.off(U.Unmuted,this.onTrackUnmuted),e.off(U.Ended,this.handleTrackEnded),e.off(U.UpstreamPaused,this.onTrackUpstreamPaused),e.off(U.UpstreamResumed,this.onTrackUpstreamResumed),e.off(U.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),t===void 0&&(t=this.roomOptions?.stopLocalTrackOnUnpublish??!0),t?e.stop():e.stopMonitor();let i=!1,a=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<kS.FAILED&&a)try{for(let e of this.engine.pcManager.publisher.getTransceivers())e.sender===a&&(e.direction=`inactive`,i=!0);if(this.engine.removeTrack(a)&&(i=!0),$b(e)){for(let[,t]of e.simulcastCodecs)t.sender&&=(this.engine.removeTrack(t.sender)&&(i=!0),void 0);e.simulcastCodecs.clear()}}catch(e){this.log.warn(`failed to unpublish track`,Object.assign(Object.assign(Object.assign({},this.logContext),r),{error:e}))}switch(this.trackPublications.delete(n.trackSid),n.kind){case K.Kind.Audio:this.audioTrackPublications.delete(n.trackSid);break;case K.Kind.Video:this.videoTrackPublications.delete(n.trackSid);break}return this.emit(V.LocalTrackUnpublished,n),n.setTrack(void 0),i&&(yield this.engine.negotiate()),n})}unpublishTracks(e){return L(this,void 0,void 0,function*(){return(yield Promise.all(e.map(e=>this.unpublishTrack(e)))).filter(e=>!!e)})}republishAllTracks(e){return L(this,arguments,void 0,function(e){var t=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){t.republishPromise&&(yield t.republishPromise),t.republishPromise=new iy((r,i)=>L(t,void 0,void 0,function*(){try{let t=[];this.trackPublications.forEach(n=>{n.track&&(e&&(n.options=Object.assign(Object.assign({},n.options),e)),t.push(n))}),yield Promise.all(t.map(e=>L(this,void 0,void 0,function*(){let t=e.track;yield this.unpublishTrack(t,!1),n&&!t.isMuted&&t.source!==K.Source.ScreenShare&&t.source!==K.Source.ScreenShareAudio&&(ex(t)||$b(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)}))),r()}catch(e){e instanceof Error?i(e):i(Error(String(e)))}finally{this.republishPromise=void 0}})),yield t.republishPromise}()})}publishData(e){return L(this,arguments,void 0,function(e){var t=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return function*(){let r=n.reliable?J.RELIABLE:J.LOSSY,i=n.reliable?zh.RELIABLE:zh.LOSSY,a=n.destinationIdentities,o=n.topic,s=new Rh({kind:i,value:{case:`user`,value:new Wh({participantIdentity:t.identity,payload:e,destinationIdentities:a,topic:o})}});yield t.engine.sendDataPacket(s,r)}()})}publishDtmf(e,t){return L(this,void 0,void 0,function*(){let n=new Rh({kind:zh.RELIABLE,value:{case:`sipDtmf`,value:new Gh({code:e,digit:t})}});yield this.engine.sendDataPacket(n,J.RELIABLE)})}sendChatMessage(e,t){return L(this,void 0,void 0,function*(){let n={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:t?.attachments},r=new Rh({value:{case:`chatMessage`,value:new Jh(Object.assign(Object.assign({},n),{timestamp:Kp.parse(n.timestamp)}))}});return yield this.engine.sendDataPacket(r,J.RELIABLE),this.emit(V.ChatMessage,n),n})}editChatMessage(e,t){return L(this,void 0,void 0,function*(){let n=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),r=new Rh({value:{case:`chatMessage`,value:new Jh(Object.assign(Object.assign({},n),{timestamp:Kp.parse(n.timestamp),editTimestamp:Kp.parse(n.editTimestamp)}))}});return yield this.engine.sendDataPacket(r,J.RELIABLE),this.emit(V.ChatMessage,n),n})}sendText(e,t){return L(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)})}streamText(e){return L(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,t){return L(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)})}streamBytes(e){return L(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)})}performRpc(e){let{destinationIdentity:t,method:n,payload:r,responseTimeout:i=15e3}=e,a=7e3;return a+1e3,new iy((e,o)=>L(this,void 0,void 0,function*(){if(LS(r)>IS){o(FS.builtIn(`REQUEST_PAYLOAD_TOO_LARGE`));return}if(this.engine.latestJoinResponse?.serverInfo?.version&&kb(this.engine.latestJoinResponse?.serverInfo?.version,`1.8.0`)<0){o(FS.builtIn(`UNSUPPORTED_SERVER`));return}let s=Math.max(i,8e3),c=crypto.randomUUID();yield this.publishRpcRequest(t,c,n,r,s);let l=setTimeout(()=>{this.pendingAcks.delete(c),o(FS.builtIn(`CONNECTION_TIMEOUT`)),this.pendingResponses.delete(c),clearTimeout(u)},a);this.pendingAcks.set(c,{resolve:()=>{clearTimeout(l)},participantIdentity:t});let u=setTimeout(()=>{this.pendingResponses.delete(c),o(FS.builtIn(`RESPONSE_TIMEOUT`))},i);this.pendingResponses.set(c,{resolve:(t,n)=>{clearTimeout(u),this.pendingAcks.has(c)&&(this.log.warn(`RPC response received before ack`,c),this.pendingAcks.delete(c),clearTimeout(l)),n?o(n):e(t??``)},participantIdentity:t})}))}registerRpcMethod(e,t){this.rpcHandlers.has(e)&&this.log.warn(`you're overriding the RPC handler for method ${e}, in the future this will throw an error`),this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){this.participantTrackPermissions=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[],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,n){let r=this.pendingResponses.get(e);r?(r.resolve(t,n),this.pendingResponses.delete(e)):console.error(`Response received for unexpected RPC request`,e)}publishRpcRequest(e,t,n,r,i){return L(this,void 0,void 0,function*(){let a=new Rh({destinationIdentities:[e],kind:zh.RELIABLE,value:{case:`rpcRequest`,value:new Yh({id:t,method:n,payload:r,responseTimeoutMs:i,version:1})}});yield this.engine.sendDataPacket(a,J.RELIABLE)})}handleParticipantDisconnected(e){for(let[t,{participantIdentity:n}]of this.pendingAcks)n===e&&this.pendingAcks.delete(t);for(let[t,{participantIdentity:n,resolve:r}]of this.pendingResponses)n===e&&(r(null,FS.builtIn(`RECIPIENT_DISCONNECTED`)),this.pendingResponses.delete(t))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(e=>e.mime.split(`/`)[0].toLowerCase()===`video`)}updateInfo(e){return super.updateInfo(e)?(e.tracks.forEach(e=>{let t=this.trackPublications.get(e.sid);if(t){let n=t.isMuted||(t.track?.isUpstreamPaused??!1);n!==e.muted&&(this.log.debug(`updating server mute state after reconcile`,Object.assign(Object.assign(Object.assign({},this.logContext),G(t)),{mutedOnServer:n})),this.engine.client.sendMuteTrack(e.sid,n))}}),!0):!1}setActiveAgent(e){var t,n,r,i;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?(n=(t=this.activeAgentFuture)?.resolve)==null||n.call(t,e):(i=(r=this.activeAgentFuture)?.reject)==null||i.call(r,Error(`Agent disconnected`)),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||=new Bb,this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(n=>{let r=n.track;r&&(e instanceof MediaStreamTrack?(ex(r)||$b(r))&&r.mediaStreamTrack===e&&(t=n):e===r&&(t=n))}),t}waitForPendingPublicationOfSource(e){return L(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[n]=t;return n.source===e});if(t)return t[1];yield ob(20)}})}publishDataTrack(e){return L(this,void 0,void 0,function*(){let t=new Uw(e,this.roomOutgoingDataTrackManager);return yield t.publish(),t})}},dT=class extends DOMException{constructor(e,t){super(e,`AbortError`),this.reason=t}},fT=class extends Map{constructor(){super(...arguments),this.pending=new Map}set(e,t){var n;super.set(e,t);let r=this.pending.get(e);if(r){for(let e of r)e.isResolved||(n=e.resolve)==null||n.call(e,t);this.pending.delete(e)}return this}get[Symbol.toStringTag](){return`WaitableMap`}getDeferred(e,t){return L(this,void 0,void 0,function*(){let n=this.get(e);if(n!==void 0)return n;if(t?.aborted)throw new dT(`The operation was aborted.`,t.reason);let r=new Bb(void 0,()=>{let t=this.pending.get(e);if(!t)return;let n=t.indexOf(r);n!==-1&&t.splice(n,1),t.length===0&&this.pending.delete(e)}),i=this.pending.get(e);if(i?i.push(r):this.pending.set(e,[r]),t){let e=()=>{var e;r.isResolved||(e=r.reject)==null||e.call(r,new dT(`The operation was aborted.`,t.reason))};t.addEventListener(`abort`,e,{once:!0}),r.promise.finally(()=>{t.removeEventListener(`abort`,e)})}return r.promise})}},pT=class extends nT{constructor(e,t,n,r){super(e,t.sid,t.name,r),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=e=>{this.setTrack(void 0),this.emit(U.Ended,e)},this.handleVisibilityChange=e=>{this.log.debug(`adaptivestream video visibility ${this.trackSid}, visible=${e}`,this.logContext),this.visible=e,this.emitTrackUpdate()},this.handleVideoDimensionsChange=e=>{this.log.debug(`adaptivestream video dimensions ${e.width}x${e.height}`,this.logContext),this.videoDimensionsAdaptiveStream=e,this.emitTrackUpdate()},this.subscribed=n,this.updateInfo(t)}setSubscribed(e){let t=this.subscriptionStatus,n=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);let r=new Ig({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new $h({participantSid:``,trackSids:[this.trackSid]})]});this.emit(U.UpdateSubscription,r),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(n)}get subscriptionStatus(){return this.subscribed===!1?nT.SubscriptionStatus.Unsubscribed:super.isSubscribed?nT.SubscriptionStatus.Subscribed:nT.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?nT.PermissionStatus.Allowed:nT.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed===!1?!1:super.isSubscribed}get isDesired(){return this.subscribed!==!1}get isEnabled(){return this.requestedDisabled===void 0?this.isAdaptiveStream?this.visible:!0:!this.requestedDisabled}get isLocal(){return!1}setEnabled(e){!this.isManualOperationAllowed()||this.requestedDisabled===!e||(this.requestedDisabled=!e,this.emitTrackUpdate())}setVideoQuality(e){!this.isManualOperationAllowed()||this.requestedMaxQuality===e||(this.requestedMaxQuality=e,this.requestedVideoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){this.isManualOperationAllowed()&&(this.requestedVideoDimensions?.width===e.width&&this.requestedVideoDimensions?.height===e.height||(rx(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&rx(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){return this.requestedMaxQuality??eb.HIGH}setTrack(e){let t=this.subscriptionStatus,n=this.permissionStatus,r=this.track;r!==e&&(r&&(r.off(U.VideoDimensionsChanged,this.handleVideoDimensionsChange),r.off(U.VisibilityChanged,this.handleVisibilityChange),r.off(U.Ended,this.handleEnded),r.detach(),r.stopMonitor(),this.emit(U.Unsubscribed,r)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(U.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(U.VisibilityChanged,this.handleVisibilityChange),e.on(U.Ended,this.handleEnded),this.emit(U.Subscribed,e)),this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){let t=this.subscriptionStatus,n=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(U.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?U.Muted:U.Unmuted)}emitSubscriptionUpdateIfChanged(e){let t=this.subscriptionStatus;e!==t&&this.emit(U.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(U.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.isDesired?!0:(this.log.warn(`cannot update track settings when not subscribed`,this.logContext),!1)}get isAdaptiveStream(){return rx(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){let e=new zg({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===K.Kind.Video){let t=this.requestedVideoDimensions;if(this.videoDimensionsAdaptiveStream!==void 0)if(t)Xy(this.videoDimensionsAdaptiveStream,t)&&(this.log.debug(`using adaptive stream dimensions instead of requested`,Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream);else if(this.requestedMaxQuality!==void 0&&this.trackInfo){let e=Zy(this.trackInfo,this.requestedMaxQuality);e&&Xy(this.videoDimensionsAdaptiveStream,e)&&(this.log.debug(`using adaptive stream dimensions instead of max quality layer`,Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream)}else this.log.debug(`using adaptive stream dimensions`,Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream;t?(e.width=Math.ceil(t.width),e.height=Math.ceil(t.height)):this.requestedMaxQuality===void 0?(this.log.debug(`using default quality`,Object.assign(Object.assign({},this.logContext),{quality:eb.HIGH})),e.quality=eb.HIGH):(this.log.debug(`using requested max quality`,Object.assign(Object.assign({},this.logContext),{quality:this.requestedMaxQuality})),e.quality=this.requestedMaxQuality)}this.emit(U.UpdateSettings,e)}},mT=class e extends cT{static fromParticipantInfo(t,n,r){return new e(t,n.sid,n.identity,n.name,n.metadata,n.attributes,r,n.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{remoteParticipantID:this.sid,remoteParticipant:this.identity})}constructor(e,t,n,r,i,a,o){let s=arguments.length>7&&arguments[7]!==void 0?arguments[7]:Ah.STANDARD;super(t,n||``,r,i,a,o,s),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.dataTracks=new fT,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(U.UpdateSettings,t=>{this.log.debug(`send update settings`,Object.assign(Object.assign(Object.assign({},this.logContext),G(e)),{settings:t})),this.signalClient.sendUpdateTrackSettings(t)}),e.on(U.UpdateSubscription,e=>{e.participantTracks.forEach(e=>{e.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(e)}),e.on(U.SubscriptionPermissionChanged,t=>{this.emit(V.TrackSubscriptionPermissionChanged,e,t)}),e.on(U.SubscriptionStatusChanged,t=>{this.emit(V.TrackSubscriptionStatusChanged,e,t)}),e.on(U.Subscribed,t=>{this.emit(V.TrackSubscribed,t,e)}),e.on(U.Unsubscribed,t=>{this.emit(V.TrackUnsubscribed,t,e)}),e.on(U.SubscriptionFailed,t=>{this.emit(V.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&&arguments[1]!==void 0?arguments[1]:K.Source.Microphone;this.volumeMap.set(t,e);let n=this.getTrackPublication(t);n&&n.track&&n.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:K.Source.Microphone,t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,n,r,i,a){let o=this.getTrackPublicationBySid(t);if(o||t.startsWith(`TR`)||this.trackPublications.forEach(t=>{!o&&e.kind===t.kind.toString()&&(o=t)}),!o){if(a===0){this.log.error(`could not find published track`,Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(V.TrackSubscriptionFailed,t);return}a===void 0&&(a=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,n,r,i,a-1)},150);return}if(e.readyState===`ended`){this.log.error(`unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()`,Object.assign(Object.assign({},this.logContext),G(o))),this.emit(V.TrackSubscriptionFailed,t);return}let s=e.kind===`video`,c;return c=s?new Qw(e,t,r,i):new Xw(e,t,r,this.audioContext,this.audioOutput),c.source=o.source,c.isMuted=o.isMuted,c.setMediaStream(n),c.start(),o.setTrack(c),this.volumeMap.has(o.source)&&tx(c)&&Zb(c)&&c.setVolume(this.volumeMap.get(o.source)),o}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;let t=new Map,n=new Map;return e.tracks.forEach(e=>{let r=this.getTrackPublicationBySid(e.sid);if(r)r.updateInfo(e);else{let t=K.kindFromProto(e.type);if(!t)return;r=new pT(t,e,this.signalClient.connectOptions?.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:this.loggerOptions?.loggerName}),r.updateInfo(e),n.set(e.sid,r);let i=Array.from(this.trackPublications.values()).find(e=>e.source===r?.source);i&&r.source!==K.Source.Unknown&&this.log.debug(`received a second track publication for ${this.identity} with the same source: ${r.source}`,Object.assign(Object.assign({},this.logContext),{oldTrack:G(i),newTrack:G(r)})),this.addTrackPublication(r)}t.set(e.sid,r)}),this.trackPublications.forEach(e=>{t.has(e.trackSid)||(this.log.trace(`detected removed track on remote participant, unpublishing`,Object.assign(Object.assign({},this.logContext),G(e))),this.unpublishTrack(e.trackSid,!0))}),n.forEach(e=>{this.emit(V.TrackPublished,e)}),!0}unpublishTrack(e,t){let n=this.trackPublications.get(e);if(!n)return;let{track:r}=n;switch(r&&(r.stop(),n.setTrack(void 0)),this.trackPublications.delete(e),n.kind){case K.Kind.Audio:this.audioTrackPublications.delete(e);break;case K.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(V.TrackUnpublished,n)}setAudioOutput(e){return L(this,void 0,void 0,function*(){this.audioOutput=e;let t=[];this.audioTrackPublications.forEach(n=>{Zb(n.track)&&tx(n.track)&&t.push(n.track.setSinkId(e.deviceId??`default`))}),yield Promise.all(t)})}addRemoteDataTrack(e){this.dataTracks.set(e.info.name,e)}removeRemoteDataTrack(e){for(let[t,n]of this.dataTracks.entries())e===n.info.sid&&this.dataTracks.delete(t)}emit(e){var t=[...arguments].slice(1);return this.log.trace(`participant event`,Object.assign(Object.assign({},this.logContext),{event:e,args:t})),super.emit(e,...t)}},Y;(function(e){e.Disconnected=`disconnected`,e.Connecting=`connecting`,e.Connected=`connected`,e.Reconnecting=`reconnecting`,e.SignalReconnecting=`signalReconnecting`})(Y||={});var hT=4*1e3,gT=class e extends K_.EventEmitter{get hasE2EESetup(){return this.e2eeManager!==void 0}constructor(t){var n,r,i;if(super(),n=this,this.state=Y.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=I,this.bufferedEvents=[],this.isResuming=!1,this.rpcHandlers=new Map,this.connect=(e,t,n)=>L(this,void 0,void 0,function*(){if(!pb())throw Cb()?Error(`WebRTC isn't detected, have you called registerGlobals?`):Error(`LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.`);let r=yield this.disconnectLock.lock();if(this.state===Y.Connected)return this.log.info(`already connected to room ${this.name}`,this.logContext),r(),Promise.resolve();if(this.connectFuture)return r(),this.connectFuture.promise;this.setAndEmitConnectionState(Y.Connecting),this.regionUrlProvider?.getServerUrl().toString()!==dx(e)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),wb(new URL(e))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new NS(e,t):this.regionUrlProvider.updateToken(t),this.regionUrlProvider.fetchRegionSettings().then(e=>{var t;(t=this.regionUrlProvider)==null||t.setServerReportedRegions(e)}).catch(e=>{this.log.warn(`could not fetch region settings`,Object.assign(Object.assign({},this.logContext),{error:e}))}));let i=(a,o,s)=>L(this,void 0,void 0,function*(){this.abortController&&this.abortController.abort();let c=new AbortController;this.abortController=c,r?.();try{if(yield Ox.getInstance().getBackOffPromise(e),c.signal.aborted)throw z.cancelled(`Connection attempt aborted`);yield this.attemptConnection(s??e,t,n,c),this.abortController=void 0,a()}catch(t){if(this.regionUrlProvider&&t instanceof z&&t.reason!==R.Cancelled&&t.reason!==R.NotAllowed){let n=null;try{this.log.debug(`Fetching next region`),n=yield this.regionUrlProvider.getNextBestRegionUrl(this.abortController?.signal)}catch(e){if(e instanceof z&&(e.status===401||e.reason===R.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),o(e);return}}[R.InternalError,R.ServerUnreachable,R.Timeout].includes(t.reason)&&(this.log.debug(`Adding failed connection attempt to back off`),Ox.getInstance().addFailedConnectionAttempt(e)),n&&!this.abortController?.signal.aborted?(this.log.info(`Initial connection failed with ConnectionError: ${t.message}. Retrying with another region: ${n}`,this.logContext),this.recreateEngine(!0),yield i(a,o,n)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,qb(t)),o(t))}else{let e=xh.UNKNOWN_REASON;t instanceof z&&(e=qb(t)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e),o(t)}}}),a=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Bb((e,t)=>{i(e,t,a)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(e,t,n,r,i,a)=>L(this,void 0,void 0,function*(){let o=yield n.join(e,t,{autoSubscribe:r.autoSubscribe,adaptiveStream:typeof i.adaptiveStream==`object`?!0:i.adaptiveStream,maxRetries:r.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:r.websocketTimeout},a.signal,!i.singlePeerConnection),s=o.serverInfo;if(s||={version:o.serverVersion,region:o.serverRegion},this.serverInfo=s,this.log.debug(`connected to Livekit Server ${Object.entries(s).map(e=>{let[t,n]=e;return`${t}: ${n}`}).join(`, `)}`,{room:o.room?.name,roomSid:o.room?.sid,identity:o.participant?.identity}),!s.version)throw new gy(`unknown server version`);return s.version===`0.15.1`&&this.options.dynacast&&(this.log.debug(`disabling dynacast due to server version`,this.logContext),i.dynacast=!1),o}),this.applyJoinResponse=e=>{let t=e.participant;if(this.localParticipant.sid=t.sid,this.localParticipant.identity=t.identity,this.localParticipant.setEnabledPublishCodecs(e.enabledPublishCodecs),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,n,r)=>L(this,void 0,void 0,function*(){this.state===Y.Reconnecting||this.isResuming||this.engine?.pendingReconnect?(this.log.info(`Reconnection attempt replaced by new connection attempt`,this.logContext),this.recreateEngine(!0)):this.maybeCreateEngine(),this.regionUrlProvider?.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},OS),n),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{let n=yield this.connectSignal(e,t,this.engine,this.connOptions,this.options,r);this.applyJoinResponse(n),this.setupLocalParticipantEvents(),this.emit(B.SignalConnected)}catch(e){yield this.engine.close(),this.recreateEngine();let t=r.signal.aborted?z.cancelled(`Signal connection aborted`):z.serverUnreachable(`could not establish signal connection`);throw e instanceof Error&&(t.message=`${t.message}: ${e.message}`),e instanceof z&&(t.reason=e.reason,t.status=e.status),this.log.debug(`error trying to establish signal connection`,Object.assign(Object.assign({},this.logContext),{error:e})),t}if(r.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),z.cancelled(`Connection attempt aborted`);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,r)}catch(e){throw yield this.engine.close(),this.recreateEngine(),e}Sb()&&this.options.disconnectOnPageLeave&&(window.addEventListener(`pagehide`,this.onPageLeave),window.addEventListener(`beforeunload`,this.onPageLeave)),Sb()&&window.addEventListener(`freeze`,this.onPageLeave),this.setAndEmitConnectionState(Y.Connected),this.emit(B.Connected),Ox.getInstance().resetFailedConnectionAttempts(e),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()}),this.disconnect=function(){return L(n,[...[...arguments]],void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var n,r,i;let a=yield e.disconnectLock.lock();try{if(e.state===Y.Disconnected){e.log.debug(`already disconnected`,e.logContext);return}if(e.log.info(`disconnect from room`,Object.assign({},e.logContext)),e.state===Y.Connecting||e.state===Y.Reconnecting||e.isResuming){let t=`Abort connection attempt due to user initiated disconnect`;e.log.warn(t,e.logContext),(n=e.abortController)==null||n.abort(t),(i=(r=e.connectFuture)?.reject)==null||i.call(r,z.cancelled(`Client initiated disconnect`)),e.connectFuture=void 0}e.engine&&(e.engine.client.isDisconnected||(yield e.engine.client.sendLeave()),yield e.engine.close()),e.handleDisconnect(t,xh.CLIENT_INITIATED),e.engine=void 0}finally{a()}}()})},this.onPageLeave=()=>L(this,void 0,void 0,function*(){this.log.info(`Page leave detected, disconnecting`,this.logContext),yield this.disconnect()}),this.startAudio=()=>L(this,void 0,void 0,function*(){let e=[],t=sy();if(t&&t.os===`iOS`){let t=`livekit-dummy-audio-el`,n=document.getElementById(t);if(!n){n=document.createElement(`audio`),n.id=t,n.autoplay=!0,n.hidden=!0;let e=zb();e.enabled=!0;let r=new MediaStream([e]);n.srcObject=r,document.addEventListener(`visibilitychange`,()=>{n&&(n.srcObject=document.hidden?null:r,document.hidden||(this.log.debug(`page visible again, triggering startAudio to resume playback and update playback status`,this.logContext),this.startAudio()))}),document.body.append(n),this.once(B.Disconnected,()=>{n?.remove(),n=null})}e.push(n)}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=()=>L(this,void 0,void 0,function*(){let e=[];for(let t of this.remoteParticipants.values())t.videoTrackPublications.forEach(t=>{var n;(n=t.track)==null||n.attachedElements.forEach(t=>{e.includes(t)||e.push(t)})});yield Promise.all(e.map(e=>e.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(e=>{e.name===`NotAllowedError`?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)})}),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(let e of this.remoteParticipants.values())this.handleParticipantDisconnected(e.identity,e);this.setAndEmitConnectionState(Y.Reconnecting)&&this.emit(B.Reconnecting)},this.handleRestarted=()=>{this.outgoingDataTrackManager.sfuWillRepublishTracks(),this.incomingDataTrackManager.resendSubscriptionUpdates()},this.handleSignalRestarted=e=>L(this,void 0,void 0,function*(){this.log.debug(`signal reconnected to server, region ${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{return}this.setAndEmitConnectionState(Y.Connected),this.emit(B.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=e=>{for(let t of e){if(t.identity===this.localParticipant.identity){this.localParticipant.updateInfo(t);continue}t.identity===``&&(t.identity=this.sidToIdentity.get(t.sid)??``);let e=this.remoteParticipants.get(t.identity);t.state===kh.DISCONNECTED?this.handleParticipantDisconnected(t.identity,e):e=this.getOrCreateParticipant(t.identity,t)}let t=new Map(e.filter(e=>e.identity!==this.localParticipant.identity).map(e=>[e.identity,e.dataTracks.map(e=>Vx.from(e))]));this.incomingDataTrackManager.receiveSfuPublicationUpdates(t)},this.handleActiveSpeakersUpdate=e=>{let t=[],n={};e.forEach(e=>{if(n[e.sid]=!0,e.sid===this.localParticipant.sid)this.localParticipant.audioLevel=e.level,this.localParticipant.setIsSpeaking(!0),t.push(this.localParticipant);else{let n=this.getRemoteParticipantBySid(e.sid);n&&(n.audioLevel=e.level,n.setIsSpeaking(!0),t.push(n))}}),n[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(e=>{n[e.sid]||(e.audioLevel=0,e.setIsSpeaking(!1))}),this.activeSpeakers=t,this.emitWhenConnected(B.ActiveSpeakersChanged,t)},this.handleSpeakersChanged=e=>{let t=new Map;this.activeSpeakers.forEach(e=>{let n=this.remoteParticipants.get(e.identity);n&&n.sid!==e.sid||t.set(e.sid,e)}),e.forEach(e=>{let n=this.getRemoteParticipantBySid(e.sid);e.sid===this.localParticipant.sid&&(n=this.localParticipant),n&&(n.audioLevel=e.level,n.setIsSpeaking(e.active),e.active?t.set(e.sid,n):t.delete(e.sid))});let n=Array.from(t.values());n.sort((e,t)=>t.audioLevel-e.audioLevel),this.activeSpeakers=n,this.emitWhenConnected(B.ActiveSpeakersChanged,n)},this.handleStreamStateUpdate=e=>{e.streamStates.forEach(e=>{let t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;let n=t.getTrackPublicationBySid(e.trackSid);if(!n||!n.track)return;let r=K.streamStateFromProto(e.state);n.track.setStreamState(r),r!==n.track.streamState&&(t.emit(V.TrackStreamStateChanged,n,n.track.streamState),this.emitWhenConnected(B.TrackStreamStateChanged,n,n.track.streamState,t))})},this.handleSubscriptionPermissionUpdate=e=>{let t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;let n=t.getTrackPublicationBySid(e.trackSid);n&&n.setAllowed(e.allowed)},this.handleSubscriptionError=e=>{let t=Array.from(this.remoteParticipants.values()).find(t=>t.trackPublications.has(e.trackSid));if(!t)return;let n=t.getTrackPublicationBySid(e.trackSid);n&&n.setSubscriptionError(e.err)},this.handleDataPacket=(e,t)=>{let n=this.remoteParticipants.get(e.participantIdentity);if(e.value.case===`user`)this.handleUserPacket(n,e.value.value,e.kind,t);else if(e.value.case===`transcription`)this.handleTranscription(n,e.value.value);else if(e.value.case===`sipDtmf`)this.handleSipDtmf(n,e.value.value);else if(e.value.case===`chatMessage`)this.handleChatMessage(n,e.value.value);else if(e.value.case===`metrics`)this.handleMetrics(e.value.value,n);else if(e.value.case===`streamHeader`||e.value.case===`streamChunk`||e.value.case===`streamTrailer`)this.handleDataStream(e,t);else if(e.value.case===`rpcRequest`){let t=e.value.value;this.handleIncomingRpcRequest(e.participantIdentity,t.id,t.method,t.payload,t.responseTimeoutMs,t.version)}},this.handleUserPacket=(e,t,n,r)=>{this.emit(B.DataReceived,t.payload,e,n,t.topic,r),e?.emit(V.DataReceived,t.payload,n,r)},this.handleSipDtmf=(e,t)=>{this.emit(B.SipDTMFReceived,t,e),e?.emit(V.SipDTMFReceived,t)},this.handleTranscription=(e,t)=>{let n=t.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(t.transcribedParticipantIdentity),r=n?.trackPublications.get(t.trackId),i=Gb(t,this.transcriptionReceivedTimes);r?.emit(U.TranscriptionReceived,i),n?.emit(V.TranscriptionReceived,i,r),this.emit(B.TranscriptionReceived,i,n,r)},this.handleChatMessage=(e,t)=>{let n=Kb(t);this.emit(B.ChatMessage,n,e)},this.handleMetrics=(e,t)=>{this.emit(B.MetricsReceived,e,t)},this.handleDataStream=(e,t)=>{this.incomingDataStreamManager.handleDataStreamPacket(e,t)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(B.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(B.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(B.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(B.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>L(this,void 0,void 0,function*(){sy()?.os!==`iOS`&&(yield this.selectDefaultDevices()),this.emit(B.MediaDevicesChanged)}),this.handleRoomUpdate=e=>{let t=this.roomInfo;this.roomInfo=e,t&&t.metadata!==e.metadata&&this.emitWhenConnected(B.RoomMetadataChanged,e.metadata),t?.activeRecording!==e.activeRecording&&this.emitWhenConnected(B.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(B.ParticipantMetadataChanged,e,this.localParticipant)},this.onLocalParticipantNameChanged=e=>{this.emit(B.ParticipantNameChanged,e,this.localParticipant)},this.onLocalAttributesChanged=e=>{this.emit(B.ParticipantAttributesChanged,e,this.localParticipant)},this.onLocalTrackMuted=e=>{this.emit(B.TrackMuted,e,this.localParticipant)},this.onLocalTrackUnmuted=e=>{this.emit(B.TrackUnmuted,e,this.localParticipant)},this.onTrackProcessorUpdate=e=>{var t;(t=e?.onPublish)==null||t.call(e,this)},this.onLocalTrackPublished=e=>L(this,void 0,void 0,function*(){var t,n,r,i;(t=e.track)==null||t.on(U.TrackProcessorUpdate,this.onTrackProcessorUpdate),(n=e.track)==null||n.on(U.Restarted,this.onLocalTrackRestarted),(i=(r=e.track?.getProcessor())?.onPublish)==null||i.call(r,this),this.emit(B.LocalTrackPublished,e,this.localParticipant),ex(e.track)&&(yield e.track.checkForSilence())&&this.emit(B.LocalAudioSilenceDetected,e);let a=yield e.track?.getDeviceId(!1),o=Hy(e.source);o&&a&&a!==this.localParticipant.activeDeviceMap.get(o)&&(this.localParticipant.activeDeviceMap.set(o,a),this.emit(B.ActiveDeviceChanged,o,a))}),this.onLocalTrackUnpublished=e=>{var t,n;(t=e.track)==null||t.off(U.TrackProcessorUpdate,this.onTrackProcessorUpdate),(n=e.track)==null||n.off(U.Restarted,this.onLocalTrackRestarted),this.emit(B.LocalTrackUnpublished,e,this.localParticipant)},this.onLocalTrackRestarted=e=>L(this,void 0,void 0,function*(){let t=yield e.getDeviceId(!1),n=Hy(e.source);n&&t&&t!==this.localParticipant.activeDeviceMap.get(n)&&(this.log.debug(`local track restarted, setting ${n} ${t} active`,this.logContext),this.localParticipant.activeDeviceMap.set(n,t),this.emit(B.ActiveDeviceChanged,n,t))}),this.onLocalConnectionQualityChanged=e=>{this.emit(B.ConnectionQualityChanged,e,this.localParticipant)},this.onMediaDevicesError=(e,t)=>{this.emit(B.MediaDevicesError,e,t)},this.onLocalParticipantPermissionsChanged=e=>{this.emit(B.ParticipantPermissionsChanged,e,this.localParticipant)},this.onLocalChatMessageSent=e=>{this.emit(B.ChatMessage,e,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},DS),t),this.log=M_(this.options.loggerName??j_.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},TS),t?.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},ES),t?.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},wS),t?.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new NC,this.outgoingDataStreamManager=new RC(this.engine,this.log),this.incomingDataTrackManager=new Nw({e2eeManager:this.e2eeManager}),this.incomingDataTrackManager.on(`sfuUpdateSubscription`,e=>{this.engine.client.sendUpdateDataSubscription(e.sid,e.subscribe)}).on(`trackPublished`,e=>{var t;e.track.publisherIdentity!==this.localParticipant.identity&&(this.emit(B.DataTrackPublished,e.track),(t=this.remoteParticipants.get(e.track.publisherIdentity))==null||t.addRemoteDataTrack(e.track))}).on(`trackUnpublished`,e=>{var t;e.publisherIdentity!==this.localParticipant.identity&&(this.emit(B.DataTrackUnpublished,e.sid),(t=this.remoteParticipants.get(e.publisherIdentity))==null||t.removeRemoteDataTrack(e.sid))}),this.outgoingDataTrackManager=new Jw({e2eeManager:this.e2eeManager}),this.outgoingDataTrackManager.on(`sfuPublishRequest`,e=>{this.engine.client.sendPublishDataTrackRequest(e.handle,e.name,e.usesE2ee)}).on(`sfuUnpublishRequest`,e=>{this.engine.client.sendUnPublishDataTrackRequest(e.handle)}).on(`trackPublished`,e=>{this.emit(B.LocalDataTrackPublished,e.track)}).on(`trackUnpublished`,e=>{this.emit(B.LocalDataTrackUnpublished,e.sid)}).on(`packetAvailable`,e=>{let{bytes:t}=e;this.engine.sendLossyBytes(t,J.DATA_TRACK_LOSSY,`wait`)}),this.disconnectLock=new hp,this.localParticipant=new uT(``,``,this.engine,this.options,this.rpcHandlers,this.outgoingDataStreamManager,this.outgoingDataTrackManager),(this.options.e2ee||this.options.encryption)&&this.setupE2EE(),this.engine.e2eeManager=this.e2eeManager,this.incomingDataTrackManager.updateE2eeManager(this.e2eeManager??null),this.outgoingDataTrackManager.updateE2eeManager(this.e2eeManager??null),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set(`videoinput`,Hb(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set(`audioinput`,Hb(this.options.audioCaptureDefaults.deviceId)),this.options.audioOutput?.deviceId&&this.switchActiveDevice(`audiooutput`,Hb(this.options.audioOutput.deviceId)).catch(e=>this.log.warn(`Could not set audio output: ${e.message}`,this.logContext)),Sb()){let t=new AbortController;(i=(r=navigator.mediaDevices)?.addEventListener)==null||i.call(r,`devicechange`,this.handleDeviceChange,{signal:t.signal}),e.cleanupRegistry&&e.cleanupRegistry.register(this,()=>{t.abort()})}}registerTextStreamHandler(e,t){return this.incomingDataStreamManager.registerTextStreamHandler(e,t)}unregisterTextStreamHandler(e){return this.incomingDataStreamManager.unregisterTextStreamHandler(e)}registerByteStreamHandler(e,t){return this.incomingDataStreamManager.registerByteStreamHandler(e,t)}unregisterByteStreamHandler(e){return this.incomingDataStreamManager.unregisterByteStreamHandler(e)}registerRpcMethod(e,t){if(this.rpcHandlers.has(e))throw Error(`RPC handler already registered for method ${e}, unregisterRpcMethod before trying to register again`);this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setE2EEEnabled(e){return L(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;let t=!!this.options.encryption,n=this.options.encryption||this.options.e2ee;n&&(`e2eeManager`in n?(this.e2eeManager=n.e2eeManager,this.e2eeManager.isDataChannelEncryptionEnabled=t):this.e2eeManager=new Tx(n,t),this.e2eeManager.on(vx.ParticipantEncryptionStatusChanged,(e,t)=>{ix(t)&&(this.isE2EEEnabled=e),this.emit(B.ParticipantEncryptionStatusChanged,e,t)}),this.e2eeManager.on(vx.EncryptionError,(e,t)=>{let n=t?this.getParticipantByIdentity(t):void 0;this.emit(B.EncryptionError,e,n)}),(e=this.e2eeManager)==null||e.setup(this))}get logContext(){return{room:this.name,roomID:this.roomInfo?.sid,participant:this.localParticipant.identity,participantID:this.localParticipant.sid}}get isRecording(){return this.roomInfo?.activeRecording??!1}getSid(){return this.state===Y.Disconnected?iy.resolve(``):this.roomInfo&&this.roomInfo.sid!==``?iy.resolve(this.roomInfo.sid):new iy((e,t)=>{let n=t=>{t.sid!==``&&(this.engine.off(H.RoomUpdate,n),e(t.sid))};this.engine.on(H.RoomUpdate,n),this.once(B.Disconnected,()=>{this.engine.off(H.RoomUpdate,n),t(new _y(`Room disconnected before room server id was available`))})})}get name(){return this.roomInfo?.name??``}get metadata(){return this.roomInfo?.metadata}get numParticipants(){return this.roomInfo?.numParticipants??0}get numPublishers(){return this.roomInfo?.numPublishers??0}maybeCreateEngine(){this.engine&&(this.engine.isNewlyCreated||!this.engine.isClosed)||(this.engine=new OC(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(H.ParticipantUpdate,this.handleParticipantUpdates).on(H.RoomUpdate,this.handleRoomUpdate).on(H.SpeakersChanged,this.handleSpeakersChanged).on(H.StreamStateChanged,this.handleStreamStateUpdate).on(H.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(H.SubscriptionError,this.handleSubscriptionError).on(H.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(H.MediaTrackAdded,(e,t,n)=>{this.onTrackAdded(e,t,n)}).on(H.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(H.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(H.DataPacketReceived,this.handleDataPacket).on(H.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info(`Resuming signal connection`,this.logContext),this.setAndEmitConnectionState(Y.SignalReconnecting)&&this.emit(B.SignalReconnecting)}).on(H.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info(`Resumed signal connection`,this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(Y.Connected)&&this.emit(B.Reconnected)}).on(H.SignalResumed,()=>{this.bufferedEvents=[],(this.state===Y.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(H.Restarting,this.handleRestarting).on(H.Restarted,this.handleRestarted).on(H.SignalRestarted,this.handleSignalRestarted).on(H.Offline,()=>{this.setAndEmitConnectionState(Y.Reconnecting)&&this.emit(B.Reconnecting)}).on(H.DCBufferStatusChanged,(e,t)=>{this.emit(B.DCBufferStatusChanged,e,t)}).on(H.LocalTrackSubscribed,e=>{let t=this.localParticipant.getTrackPublications().find(t=>{let{trackSid:n}=t;return n===e});if(!t){this.log.warn(`could not find local track subscription for subscribed event`,this.logContext);return}this.localParticipant.emit(V.LocalTrackSubscribed,t),this.emitWhenConnected(B.LocalTrackSubscribed,t,this.localParticipant)}).on(H.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(B.Moved,e.room.name),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)}).on(H.PublishDataTrackResponse,e=>{if(!e.info){this.log.warn(`received PublishDataTrackResponse, but event.info was ${e.info}, so skipping.`,this.logContext);return}this.outgoingDataTrackManager.receivedSfuPublishResponse(e.info.pubHandle,{type:`ok`,data:{sid:e.info.sid,pubHandle:e.info.pubHandle,name:e.info.name,usesE2ee:e.info.encryption!==F.NONE}})}).on(H.UnPublishDataTrackResponse,e=>{if(!e.info){this.log.warn(`received UnPublishDataTrackResponse, but event.info was ${e.info}, so skipping.`,this.logContext);return}this.outgoingDataTrackManager.receivedSfuUnpublishResponse(e.info.pubHandle)}).on(H.DataTrackSubscriberHandles,e=>{let t=new Map(Object.entries(e.subHandles).map(e=>{let[t,n]=e;return[parseInt(t,10),n.trackSid]}));this.incomingDataTrackManager.receivedSfuSubscriberHandles(t)}).on(H.DataTrackPacketReceived,e=>{try{this.incomingDataTrackManager.packetReceived(e)}catch(e){throw e}}).on(H.Joined,e=>{let t=new Map(e.otherParticipants.map(e=>[e.identity,e.dataTracks.map(e=>Vx.from(e))]));this.incomingDataTrackManager.receiveSfuPublicationUpdates(t)}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine),this.outgoingDataStreamManager&&this.outgoingDataStreamManager.setupEngine(this.engine))}static getLocalDevices(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return Ax.getInstance().getDevices(e,t)}prepareConnection(e,t){return L(this,void 0,void 0,function*(){if(this.state===Y.Disconnected){this.log.debug(`prepareConnection to ${e}`,this.logContext);try{if(wb(new URL(e))&&t){this.regionUrlProvider=new NS(e,t);let n=yield this.regionUrlProvider.getNextBestRegionUrl();n&&this.state===Y.Disconnected&&(this.regionUrl=n,yield fetch(Wb(n),{method:`HEAD`}),this.log.debug(`prepared connection to ${n}`,this.logContext))}else yield fetch(Wb(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 L(this,void 0,void 0,function*(){let n=()=>L(this,void 0,void 0,function*(){}),r;switch(e){case`signal-reconnect`:yield this.engine.client.handleOnClose(`simulate disconnect`);break;case`speaker`:r=new u_({scenario:{case:`speakerUpdate`,value:3}});break;case`node-failure`:r=new u_({scenario:{case:`nodeFailure`,value:!0}});break;case`server-leave`:r=new u_({scenario:{case:`serverLeave`,value:!0}});break;case`migration`:r=new u_({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=()=>L(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose(`simulate resume-disconnect`)}),r=new u_({scenario:{case:`disconnectSignalOnResume`,value:!0}});break;case`disconnect-signal-on-resume-no-messages`:n=()=>L(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose(`simulate resume-disconnect`)}),r=new u_({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`:r=new u_({scenario:{case:`switchCandidateProtocol`,value:e===`force-tls`?2:1}}),n=()=>L(this,void 0,void 0,function*(){let e=this.engine.client.onLeave;e&&e(new Hg({reason:xh.CLIENT_INITIATED,action:Ug.RECONNECT}))});break;case`subscriber-bandwidth`:if(t===void 0||typeof t!=`number`)throw Error(`subscriber-bandwidth requires a number as argument`);r=new u_({scenario:{case:`subscriberBandwidth`,value:Yb(t)}});break;case`leave-full-reconnect`:r=new u_({scenario:{case:`leaveRequestFullReconnect`,value:!0}})}r&&(yield this.engine.client.sendSimulateScenario(r),yield n())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return L(this,arguments,void 0,function(e,t){var n=this;let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return function*(){var i,a;let o=!0,s=!1,c=r?{exact:t}:t;if(e===`audioinput`){s=n.localParticipant.audioTrackPublications.size===0;let t=n.getActiveDevice(e)??n.options.audioCaptureDefaults.deviceId;n.options.audioCaptureDefaults.deviceId=c;let r=Array.from(n.localParticipant.audioTrackPublications.values()).filter(e=>e.source===K.Source.Microphone);try{o=(yield Promise.all(r.map(e=>e.audioTrack?.setDeviceId(c)))).every(e=>e===!0)}catch(e){throw n.options.audioCaptureDefaults.deviceId=t,e}let i=r.some(e=>e.track?.isMuted??!1);o&&i&&(s=!0)}else if(e===`videoinput`){s=n.localParticipant.videoTrackPublications.size===0;let t=n.getActiveDevice(e)??n.options.videoCaptureDefaults.deviceId;n.options.videoCaptureDefaults.deviceId=c;let r=Array.from(n.localParticipant.videoTrackPublications.values()).filter(e=>e.source===K.Source.Camera);try{o=(yield Promise.all(r.map(e=>e.videoTrack?.setDeviceId(c)))).every(e=>e===!0)}catch(e){throw n.options.videoCaptureDefaults.deviceId=t,e}let i=r.some(e=>e.track?.isMuted??!1);o&&i&&(s=!0)}else if(e===`audiooutput`){if(s=!0,!fb()&&!n.options.webAudioMix||n.options.webAudioMix&&n.audioContext&&!(`setSinkId`in n.audioContext))throw Error(`cannot switch audio output, the current browser does not support it`);n.options.webAudioMix&&(t=(yield Ax.getInstance().normalizeDeviceId(`audiooutput`,t))??``),(a=n.options).audioOutput??(a.audioOutput={});let r=n.getActiveDevice(e)??n.options.audioOutput.deviceId;n.options.audioOutput.deviceId=t;try{n.options.webAudioMix&&((i=n.audioContext)==null||i.setSinkId(t)),yield Promise.all(Array.from(n.remoteParticipants.values()).map(e=>e.setAudioOutput({deviceId:t})))}catch(e){throw n.options.audioOutput.deviceId=r,e}}return s&&(n.localParticipant.activeDeviceMap.set(e,t),n.emit(B.ActiveDeviceChanged,e,t)),o}()})}setupLocalParticipantEvents(){this.localParticipant.on(V.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(V.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(V.AttributesChanged,this.onLocalAttributesChanged).on(V.TrackMuted,this.onLocalTrackMuted).on(V.TrackUnmuted,this.onLocalTrackUnmuted).on(V.LocalTrackPublished,this.onLocalTrackPublished).on(V.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(V.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(V.MediaDevicesError,this.onMediaDevicesError).on(V.AudioStreamAcquired,this.startAudio).on(V.ChatMessage,this.onLocalChatMessageSent).on(V.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(e){let t=this.engine;e&&t&&!t.client.isDisconnected?t.client.sendLeave().finally(()=>t.close()):t?.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,n){if(this.state===Y.Connecting||this.state===Y.Reconnecting){let r=()=>{this.log.debug(`deferring on track for later`,{mediaTrackId:e.id,mediaStreamId:t.id,tracksInStream:t.getTracks().map(e=>e.id)}),this.onTrackAdded(e,t,n),i()},i=()=>{this.off(B.Reconnected,r),this.off(B.Connected,r),this.off(B.Disconnected,i)};this.once(B.Reconnected,r),this.once(B.Connected,r),this.once(B.Disconnected,i);return}if(this.state===Y.Disconnected){this.log.warn(`skipping incoming track after Room disconnected`,this.logContext);return}if(e.readyState===`ended`){this.log.info(`skipping incoming track as it already ended`,this.logContext);return}let r=ab(t.id),i=r[0],a=r[1],o=e.id;if(a&&a.startsWith(`TR`)&&(o=a),i===this.localParticipant.sid){this.log.warn(`tried to create RemoteParticipant for local participant`,this.logContext);return}let s=Array.from(this.remoteParticipants.values()).find(e=>e.sid===i);if(!s){i.startsWith(`PA`)&&this.log.error(`Tried to add a track for a participant, that's not present. Sid: ${i}`,this.logContext);return}if(!o.startsWith(`TR`)){let e=this.engine.getTrackIdForReceiver(n);if(!e){this.log.error(`Tried to add a track whose 'sid' could not be found for a participant, that's not present. Sid: ${i}`,this.logContext);return}o=e}o.startsWith(`TR`)||this.log.warn(`Tried to add a track whose 'sid' could not be determined for a participant, that's not present. Sid: ${i}, streamId: ${a}, trackId: ${o}`,Object.assign(Object.assign({},this.logContext),{remoteParticipantID:i,streamId:a,trackId:o}));let c;this.options.adaptiveStream&&(c=typeof this.options.adaptiveStream==`object`?this.options.adaptiveStream:{});let l=s.addSubscribedMediaTrack(e,o,t,n,c);l?.isEncrypted&&!this.e2eeManager&&this.emit(B.EncryptionError,Error(`Encrypted ${l.source} track received from participant ${s.sid}, but room does not have encryption enabled!`))}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1?arguments[1]:void 0;var n,r;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearControllers(),this.state!==Y.Disconnected){this.regionUrl=void 0,this.regionUrlProvider&&this.regionUrlProvider.notifyDisconnected();try{this.remoteParticipants.forEach(e=>{e.trackPublications.forEach(t=>{e.unpublishTrack(t.trackSid)})}),this.localParticipant.trackPublications.forEach(t=>{var n,r,i;t.track&&this.localParticipant.unpublishTrack(t.track,e),e?((n=t.track)==null||n.detach(),(r=t.track)==null||r.stop()):(i=t.track)==null||i.stopMonitor()}),this.localParticipant.off(V.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(V.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(V.AttributesChanged,this.onLocalAttributesChanged).off(V.TrackMuted,this.onLocalTrackMuted).off(V.TrackUnmuted,this.onLocalTrackUnmuted).off(V.LocalTrackPublished,this.onLocalTrackPublished).off(V.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(V.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(V.MediaDevicesError,this.onMediaDevicesError).off(V.AudioStreamAcquired,this.startAudio).off(V.ChatMessage,this.onLocalChatMessageSent).off(V.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.trackPublications.clear(),this.localParticipant.videoTrackPublications.clear(),this.localParticipant.audioTrackPublications.clear(),this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.activeSpeakers=[],this.audioContext&&typeof this.options.webAudioMix==`boolean`&&(this.audioContext.close(),this.audioContext=void 0),Sb()&&(window.removeEventListener(`beforeunload`,this.onPageLeave),window.removeEventListener(`pagehide`,this.onPageLeave),window.removeEventListener(`freeze`,this.onPageLeave),(r=(n=navigator.mediaDevices)?.removeEventListener)==null||r.call(n,`devicechange`,this.handleDeviceChange))}finally{this.setAndEmitConnectionState(Y.Disconnected),this.emit(B.Disconnected,t)}}}handleParticipantDisconnected(e,t){var n;this.remoteParticipants.delete(e),t&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(e),this.incomingDataTrackManager.handleRemoteParticipantDisconnected(e),t.trackPublications.forEach(e=>{t.unpublishTrack(e.trackSid,!0)}),this.emit(B.ParticipantDisconnected,t),t.setDisconnected(),(n=this.localParticipant)==null||n.handleParticipantDisconnected(t.identity))}handleIncomingRpcRequest(e,t,n,r,i,a){return L(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,t),a!==1){yield this.engine.publishRpcResponse(e,t,null,FS.builtIn(`UNSUPPORTED_VERSION`));return}let o=this.rpcHandlers.get(n);if(!o){yield this.engine.publishRpcResponse(e,t,null,FS.builtIn(`UNSUPPORTED_METHOD`));return}let s=null,c=null;try{let a=yield o({requestId:t,callerIdentity:e,payload:r,responseTimeout:i});LS(a)>IS?(s=FS.builtIn(`RESPONSE_PAYLOAD_TOO_LARGE`),this.log.warn(`RPC Response payload too large for ${n}`)):c=a}catch(e){e instanceof FS?s=e:(this.log.warn(`Uncaught error returned by RPC handler for ${n}. Returning APPLICATION_ERROR instead.`,e),s=FS.builtIn(`APPLICATION_ERROR`))}yield this.engine.publishRpcResponse(e,t,c,s)})}selectDefaultDevices(){return L(this,void 0,void 0,function*(){let e=Ax.getInstance().previousDevices,t=yield Ax.getInstance().getDevices(void 0,!1),n=sy();if(n?.name===`Chrome`&&n.os!==`iOS`)for(let n of t){let t=e.find(e=>e.deviceId===n.deviceId);t&&t.label!==``&&t.kind===n.kind&&t.label!==n.label&&this.getActiveDevice(n.kind)===`default`&&this.emit(B.ActiveDeviceChanged,n.kind,n.deviceId)}for(let n of[`audiooutput`,`audioinput`,`videoinput`]){let r=Vy(n),i=this.localParticipant.getTrackPublication(r);if(i&&i.track?.isUserProvided)continue;let a=t.filter(e=>e.kind===n),o=this.getActiveDevice(n);if(o===e.filter(e=>e.kind===n)[0]?.deviceId&&a.length>0&&a[0]?.deviceId!==o){yield this.switchActiveDevice(n,a[0].deviceId);continue}n===`audioinput`&&!_b()||n===`videoinput`||a.length>0&&!a.find(e=>e.deviceId===this.getActiveDevice(n))&&(n!==`audiooutput`||!_b())&&(yield this.switchActiveDevice(n,a[0].deviceId))}})}acquireAudioContext(){return L(this,void 0,void 0,function*(){if(typeof this.options.webAudioMix!=`boolean`&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:(!this.audioContext||this.audioContext.state===`closed`)&&(this.audioContext=By()??void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(e=>e.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state===`suspended`)try{yield Promise.race([this.audioContext.resume(),ob(200)])}catch(e){this.log.warn(`Could not resume audio context`,Object.assign(Object.assign({},this.logContext),{error:e}))}let e=this.audioContext?.state===`running`;e!==this.canPlaybackAudio&&(this.audioEnabled=e,this.emit(B.AudioPlaybackStatusChanged,e))})}createParticipant(e,t){let n;return n=t?mT.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):new mT(this.engine.client,``,e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&n.setAudioContext(this.audioContext),this.options.audioOutput?.deviceId&&n.setAudioOutput(this.options.audioOutput).catch(e=>this.log.warn(`Could not set audio output: ${e.message}`,this.logContext)),n}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){let n=this.remoteParticipants.get(e);return t&&n.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),n}let n=this.createParticipant(e,t);return this.remoteParticipants.set(e,n),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(B.ParticipantConnected,n),n.on(V.TrackPublished,e=>{this.emitWhenConnected(B.TrackPublished,e,n)}).on(V.TrackSubscribed,(e,t)=>{e.kind===K.Kind.Audio?(e.on(U.AudioPlaybackStarted,this.handleAudioPlaybackStarted),e.on(U.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):e.kind===K.Kind.Video&&(e.on(U.VideoPlaybackFailed,this.handleVideoPlaybackFailed),e.on(U.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emitWhenConnected(B.TrackSubscribed,e,t,n)}).on(V.TrackUnpublished,e=>{this.emit(B.TrackUnpublished,e,n)}).on(V.TrackUnsubscribed,(e,t)=>{this.emit(B.TrackUnsubscribed,e,t,n)}).on(V.TrackMuted,e=>{this.emitWhenConnected(B.TrackMuted,e,n)}).on(V.TrackUnmuted,e=>{this.emitWhenConnected(B.TrackUnmuted,e,n)}).on(V.ParticipantMetadataChanged,e=>{this.emitWhenConnected(B.ParticipantMetadataChanged,e,n)}).on(V.ParticipantNameChanged,e=>{this.emitWhenConnected(B.ParticipantNameChanged,e,n)}).on(V.AttributesChanged,e=>{this.emitWhenConnected(B.ParticipantAttributesChanged,e,n)}).on(V.ConnectionQualityChanged,e=>{this.emitWhenConnected(B.ConnectionQualityChanged,e,n)}).on(V.ParticipantPermissionsChanged,e=>{this.emitWhenConnected(B.ParticipantPermissionsChanged,e,n)}).on(V.TrackSubscriptionStatusChanged,(e,t)=>{this.emitWhenConnected(B.TrackSubscriptionStatusChanged,e,t,n)}).on(V.TrackSubscriptionFailed,(e,t)=>{this.emit(B.TrackSubscriptionFailed,e,n,t)}).on(V.TrackSubscriptionPermissionChanged,(e,t)=>{this.emitWhenConnected(B.TrackSubscriptionPermissionChanged,e,t,n)}).on(V.Active,()=>{this.emitWhenConnected(B.ParticipantActive,n),n.kind===Ah.AGENT&&this.localParticipant.setActiveAgent(n)}),t&&n.updateInfo(t),n}sendSyncState(){let e=Array.from(this.remoteParticipants.values()).reduce((e,t)=>(e.push(...t.getTrackPublications()),e),[]),t=this.localParticipant.getTrackPublications(),n=this.outgoingDataTrackManager.queryPublished();this.engine.sendSyncState(e,t,n)}updateSubscriptions(){for(let e of this.remoteParticipants.values())for(let t of e.videoTrackPublications.values())t.isSubscribed&&nx(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){let t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=Ty.setInterval(()=>{!this.engine||this.engine.isClosed||!this.engine.verifyTransport()?(e++,this.log.warn(`detected connection state mismatch`,Object.assign(Object.assign({},this.logContext),{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnectedOrConnecting:this.engine.verifyTransport()}:void 0})),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,xh.STATE_MISMATCH))):e=0},hT)}clearConnectionReconcile(){this.connectionReconcileInterval&&Ty.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(B.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[t,n]=e;this.emit(t,...n)}),this.bufferedEvents=[]}emitWhenConnected(e){var t=[...arguments].slice(1);if(this.state===Y.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,t]);else if(this.state===Y.Connected)return this.emit(e,...t);return!1}simulateParticipants(e){return L(this,void 0,void 0,function*(){let t=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),n=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new Th({sid:`RM_SIMULATED`,name:`simulated-room`,emptyTimeout:0,maxParticipants:0,creationTime:Kp.parse(new Date().getTime()),metadata:``,numParticipants:1,numPublishers:1,turnPassword:``,enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new Oh({identity:`simulated-local`,name:`local-name`})),this.setupLocalParticipantEvents(),this.emit(B.SignalConnected),this.emit(B.Connected),this.setAndEmitConnectionState(Y.Connected),t.video){let e=new rT(K.Kind.Video,new Nh({source:_h.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:gh.AUDIO,name:`video-dummy`}),new pC(t.useRealTracks&&window.navigator.mediaDevices?.getUserMedia?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Lb(160*(n.aspectRatios[0]??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(V.LocalTrackPublished,e)}if(t.audio){let e=new rT(K.Kind.Audio,new Nh({source:_h.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:gh.AUDIO}),new JS(t.useRealTracks&&navigator.mediaDevices?.getUserMedia?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:zb(),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(V.LocalTrackPublished,e)}for(let e=0;e<n.count-1;e+=1){let t=new Oh({sid:Math.floor(Math.random()*1e4).toString(),identity:`simulated-${e}`,state:kh.ACTIVE,tracks:[],joinedAt:Kp.parse(Date.now())}),r=this.getOrCreateParticipant(t.identity,t);if(n.video){let i=Lb(160*(n.aspectRatios[e%n.aspectRatios.length]??1),160,!1,!0),a=new Nh({source:_h.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:gh.AUDIO});r.addSubscribedMediaTrack(i,a.sid,new MediaStream([i]),new RTCRtpReceiver),t.tracks=[...t.tracks,a]}if(n.audio){let e=zb(),n=new Nh({source:_h.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:gh.AUDIO});r.addSubscribedMediaTrack(e,n.sid,new MediaStream([e]),new RTCRtpReceiver),t.tracks=[...t.tracks,n]}r.updateInfo(t)}})}emit(e){var t=[...arguments].slice(1);if(e!==B.ActiveSpeakersChanged&&e!==B.TranscriptionReceived){let n=_T(t).filter(e=>e!==void 0);(e===B.TrackSubscribed||e===B.TrackUnsubscribed)&&this.log.trace(`subscribe trace: ${e}`,Object.assign(Object.assign({},this.logContext),{event:e,args:n})),this.log.debug(`room event ${e}`,Object.assign(Object.assign({},this.logContext),{event:e,args:n}))}return super.emit(e,...t)}};gT.cleanupRegistry=typeof FinalizationRegistry<`u`&&new FinalizationRegistry(e=>{e()});function _T(e){return e.map(e=>{if(e)return Array.isArray(e)?_T(e):typeof e==`object`?`logContext`in e?e.logContext:void 0:e})}var vT;(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`})(vT||={}),K_.EventEmitter,K_.EventEmitter;function X(e,t,n){return(t=bT(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function yT(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function bT(e){var t=yT(e,`string`);return typeof t==`symbol`?t:t+``}new TextEncoder,new TextDecoder;var xT=class extends Error{constructor(e,t){var n;super(e,t),X(this,`code`,`ERR_JOSE_GENERIC`),this.name=this.constructor.name,(n=Error.captureStackTrace)==null||n.call(Error,this,this.constructor)}};X(xT,`code`,`ERR_JOSE_GENERIC`),X(class extends xT{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:`unspecified`,r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:`unspecified`;super(e,{cause:{claim:n,reason:r,payload:t}}),X(this,`code`,`ERR_JWT_CLAIM_VALIDATION_FAILED`),X(this,`claim`,void 0),X(this,`reason`,void 0),X(this,`payload`,void 0),this.claim=n,this.reason=r,this.payload=t}},`code`,`ERR_JWT_CLAIM_VALIDATION_FAILED`),X(class extends xT{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:`unspecified`,r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:`unspecified`;super(e,{cause:{claim:n,reason:r,payload:t}}),X(this,`code`,`ERR_JWT_EXPIRED`),X(this,`claim`,void 0),X(this,`reason`,void 0),X(this,`payload`,void 0),this.claim=n,this.reason=r,this.payload=t}},`code`,`ERR_JWT_EXPIRED`),X(class extends xT{constructor(){super(...arguments),X(this,`code`,`ERR_JOSE_ALG_NOT_ALLOWED`)}},`code`,`ERR_JOSE_ALG_NOT_ALLOWED`),X(class extends xT{constructor(){super(...arguments),X(this,`code`,`ERR_JOSE_NOT_SUPPORTED`)}},`code`,`ERR_JOSE_NOT_SUPPORTED`),X(class extends xT{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:`decryption operation failed`,t=arguments.length>1?arguments[1]:void 0;super(e,t),X(this,`code`,`ERR_JWE_DECRYPTION_FAILED`)}},`code`,`ERR_JWE_DECRYPTION_FAILED`),X(class extends xT{constructor(){super(...arguments),X(this,`code`,`ERR_JWE_INVALID`)}},`code`,`ERR_JWE_INVALID`),X(class extends xT{constructor(){super(...arguments),X(this,`code`,`ERR_JWS_INVALID`)}},`code`,`ERR_JWS_INVALID`),X(class extends xT{constructor(){super(...arguments),X(this,`code`,`ERR_JWT_INVALID`)}},`code`,`ERR_JWT_INVALID`),X(class extends xT{constructor(){super(...arguments),X(this,`code`,`ERR_JWK_INVALID`)}},`code`,`ERR_JWK_INVALID`),X(class extends xT{constructor(){super(...arguments),X(this,`code`,`ERR_JWKS_INVALID`)}},`code`,`ERR_JWKS_INVALID`),X(class extends xT{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:`no applicable key found in the JSON Web Key Set`,t=arguments.length>1?arguments[1]:void 0;super(e,t),X(this,`code`,`ERR_JWKS_NO_MATCHING_KEY`)}},`code`,`ERR_JWKS_NO_MATCHING_KEY`),X(class extends xT{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:`multiple matching keys found in the JSON Web Key Set`,t=arguments.length>1?arguments[1]:void 0;super(e,t),X(this,Symbol.asyncIterator,void 0),X(this,`code`,`ERR_JWKS_MULTIPLE_MATCHING_KEYS`)}},`code`,`ERR_JWKS_MULTIPLE_MATCHING_KEYS`),X(class extends xT{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:`request timed out`,t=arguments.length>1?arguments[1]:void 0;super(e,t),X(this,`code`,`ERR_JWKS_TIMEOUT`)}},`code`,`ERR_JWKS_TIMEOUT`),X(class extends xT{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:`signature verification failed`,t=arguments.length>1?arguments[1]:void 0;super(e,t),X(this,`code`,`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`)}},`code`,`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`);function ST(){return ST=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},ST.apply(null,arguments)}var CT=new Uint8Array,wT=class{static getFullOptions(e){return ST({clientTools:{},onConnect:()=>{},onDebug:()=>{},onDisconnect:()=>{},onError:()=>{},onMessage:()=>{},onAudio:()=>{},onModeChange:()=>{},onStatusChange:()=>{},onCanSendFeedbackChange:()=>{},onInterruption:()=>{}},e)}constructor(e,t){var n=this;this.options=void 0,this.connection=void 0,this.lastInterruptTimestamp=0,this.mode=`listening`,this.status=`connecting`,this.volume=1,this.currentEventId=1,this.lastFeedbackEventId=0,this.canSendFeedback=!1,this.endSessionWithDetails=async function(e){n.status!==`connected`&&n.status!==`connecting`||(n.updateStatus(`disconnecting`),await n.handleEndSession(),n.updateStatus(`disconnected`),n.options.onDisconnect&&n.options.onDisconnect(e))},this.onMessage=async function(e){switch(e.type){case`interruption`:n.handleInterruption(e);return;case`agent_response`:n.handleAgentResponse(e);return;case`user_transcript`:n.handleUserTranscript(e);return;case`internal_tentative_agent_response`:n.handleTentativeAgentResponse(e);return;case`client_tool_call`:try{await n.handleClientToolCall(e)}catch(t){n.onError(`Unexpected error in client tool call handling: ${t instanceof Error?t.message:String(t)}`,{clientToolName:e.client_tool_call.tool_name,toolCallId:e.client_tool_call.tool_call_id})}return;case`audio`:n.handleAudio(e);return;case`vad_score`:n.handleVadScore(e);return;case`ping`:n.connection.sendMessage({type:`pong`,event_id:e.ping_event.event_id});return;case`mcp_tool_call`:n.handleMCPToolCall(e);return;case`mcp_connection_status`:n.handleMCPConnectionStatus(e);return;case`agent_tool_request`:n.handleAgentToolRequest(e);return;case`agent_tool_response`:n.handleAgentToolResponse(e);return;case`conversation_initiation_metadata`:n.handleConversationMetadata(e);return;case`asr_initiation_metadata`:n.handleAsrInitiationMetadata(e);return;case`agent_chat_response_part`:n.handleAgentChatResponsePart(e);return;case`error`:n.handleErrorEvent(e);return;default:n.options.onDebug&&n.options.onDebug(e);return}},this.setVolume=({volume:e})=>{this.volume=e},this.options=e,this.connection=t,this.options.onConnect&&this.options.onConnect({conversationId:t.conversationId}),this.connection.onMessage(this.onMessage),this.connection.onDisconnect(this.endSessionWithDetails),this.connection.onModeChange(e=>this.updateMode(e)),this.updateStatus(`connected`)}endSession(){return this.endSessionWithDetails({reason:`user`})}async handleEndSession(){this.connection.close()}updateMode(e){e!==this.mode&&(this.mode=e,this.options.onModeChange&&this.options.onModeChange({mode:e}))}updateStatus(e){e!==this.status&&(this.status=e,this.options.onStatusChange&&this.options.onStatusChange({status:e}))}updateCanSendFeedback(){let e=this.currentEventId!==this.lastFeedbackEventId;this.canSendFeedback!==e&&(this.canSendFeedback=e,this.options.onCanSendFeedbackChange&&this.options.onCanSendFeedbackChange({canSendFeedback:e}))}handleInterruption(e){e.interruption_event&&(this.lastInterruptTimestamp=e.interruption_event.event_id,this.options.onInterruption&&this.options.onInterruption({event_id:e.interruption_event.event_id}))}handleAgentResponse(e){this.options.onMessage&&this.options.onMessage({source:`ai`,role:`agent`,message:e.agent_response_event.agent_response})}handleUserTranscript(e){this.options.onMessage&&this.options.onMessage({source:`user`,role:`user`,message:e.user_transcription_event.user_transcript})}handleTentativeAgentResponse(e){this.options.onDebug&&this.options.onDebug({type:`tentative_agent_response`,response:e.tentative_agent_response_internal_event.tentative_agent_response})}handleVadScore(e){this.options.onVadScore&&this.options.onVadScore({vadScore:e.vad_score_event.vad_score})}async handleClientToolCall(e){if(Object.prototype.hasOwnProperty.call(this.options.clientTools,e.client_tool_call.tool_name))try{let t=await this.options.clientTools[e.client_tool_call.tool_name](e.client_tool_call.parameters)??`Client tool execution successful.`,n=typeof t==`object`?JSON.stringify(t):String(t);this.connection.sendMessage({type:`client_tool_result`,tool_call_id:e.client_tool_call.tool_call_id,result:n,is_error:!1})}catch(t){this.onError(`Client tool execution failed with following error: ${t?.message}`,{clientToolName:e.client_tool_call.tool_name}),this.connection.sendMessage({type:`client_tool_result`,tool_call_id:e.client_tool_call.tool_call_id,result:`Client tool execution failed: ${t?.message}`,is_error:!0})}else{if(this.options.onUnhandledClientToolCall)return void this.options.onUnhandledClientToolCall(e.client_tool_call);this.onError(`Client tool with name ${e.client_tool_call.tool_name} is not defined on client`,{clientToolName:e.client_tool_call.tool_name}),this.connection.sendMessage({type:`client_tool_result`,tool_call_id:e.client_tool_call.tool_call_id,result:`Client tool with name ${e.client_tool_call.tool_name} is not defined on client`,is_error:!0})}}handleAudio(e){}handleMCPToolCall(e){this.options.onMCPToolCall&&this.options.onMCPToolCall(e.mcp_tool_call)}handleMCPConnectionStatus(e){this.options.onMCPConnectionStatus&&this.options.onMCPConnectionStatus(e.mcp_connection_status)}handleAgentToolRequest(e){this.options.onAgentToolRequest&&this.options.onAgentToolRequest(e.agent_tool_request)}handleAgentToolResponse(e){e.agent_tool_response.tool_name===`end_call`&&this.endSessionWithDetails({reason:`agent`,context:new CloseEvent(`end_call`,{reason:`Agent ended the call`})}),this.options.onAgentToolResponse&&this.options.onAgentToolResponse(e.agent_tool_response)}handleConversationMetadata(e){this.options.onConversationMetadata&&this.options.onConversationMetadata(e.conversation_initiation_metadata_event)}handleAsrInitiationMetadata(e){this.options.onAsrInitiationMetadata&&this.options.onAsrInitiationMetadata(e.asr_initiation_metadata_event)}handleAgentChatResponsePart(e){this.options.onAgentChatResponsePart&&this.options.onAgentChatResponsePart(e.text_response_part)}handleErrorEvent(e){let t=e.error_event.error_type,n=e.error_event.message||e.error_event.reason||`Unknown error`;t===`max_duration_exceeded`?this.endSessionWithDetails({reason:`error`,message:n,context:new Event(`max_duration_exceeded`)}):this.onError(`Server error: ${n}`,{errorType:t,code:e.error_event.code,debugMessage:e.error_event.debug_message,details:e.error_event.details})}onError(e,t){console.error(e,t),this.options.onError&&this.options.onError(e,t)}getId(){return this.connection.conversationId}isOpen(){return this.status===`connected`}setMicMuted(e){this.connection.setMicMuted(e)}getInputByteFrequencyData(){return CT}getOutputByteFrequencyData(){return CT}getInputVolume(){return 0}getOutputVolume(){return 0}sendFeedback(e){this.canSendFeedback?(this.connection.sendMessage({type:`feedback`,score:e?`like`:`dislike`,event_id:this.currentEventId}),this.lastFeedbackEventId=this.currentEventId,this.updateCanSendFeedback()):console.warn(this.lastFeedbackEventId===0?`Cannot send feedback: the conversation has not started yet.`:`Cannot send feedback: feedback has already been sent for the current response.`)}sendContextualUpdate(e){this.connection.sendMessage({type:`contextual_update`,text:e})}sendUserMessage(e){this.connection.sendMessage({type:`user_message`,text:e})}sendUserActivity(){this.connection.sendMessage({type:`user_activity`})}sendMCPToolApprovalResult(e,t){this.connection.sendMessage({type:`mcp_tool_approval_result`,tool_call_id:e,is_approved:t})}},TT=class{constructor(e={}){this.queue=[],this.disconnectionDetails=null,this.onDisconnectCallback=null,this.onMessageCallback=null,this.onModeChangeCallback=null,this.onDebug=void 0,this.onDebug=e.onDebug}debug(e){this.onDebug&&this.onDebug(e)}onMessage(e){this.onMessageCallback=e;let t=this.queue;this.queue=[],t.length>0&&queueMicrotask(()=>{t.forEach(e)})}onDisconnect(e){this.onDisconnectCallback=e;let t=this.disconnectionDetails;t&&queueMicrotask(()=>{e(t)})}onModeChange(e){this.onModeChangeCallback=e}updateMode(e){var t;(t=this.onModeChangeCallback)==null||t.call(this,e)}disconnect(e){var t;this.disconnectionDetails||(this.disconnectionDetails=e,(t=this.onDisconnectCallback)==null||t.call(this,e))}handleMessage(e){this.onMessageCallback?this.onMessageCallback(e):this.queue.push(e)}};function ET(e){let[t,n]=e.split(`_`);if(![`pcm`,`ulaw`].includes(t))throw Error(`Invalid format: ${e}`);let r=Number.parseInt(n);if(Number.isNaN(r))throw Error(`Invalid sample rate: ${n}`);return{format:t,sampleRate:r}}var DT=`0.12.2`;function OT(e){return!!e.type}var kT=`conversation_initiation_client_data`;function AT(e){var t;let n={type:kT};return e.overrides&&(n.conversation_config_override={agent:{prompt:e.overrides.agent?.prompt,first_message:e.overrides.agent?.firstMessage,language:e.overrides.agent?.language},tts:{voice_id:e.overrides.tts?.voiceId,speed:e.overrides.tts?.speed},conversation:{text_only:e.overrides.conversation?.textOnly}}),e.customLlmExtraBody&&(n.custom_llm_extra_body=e.customLlmExtraBody),e.dynamicVariables&&(n.dynamic_variables=e.dynamicVariables),e.userId&&(n.user_id=e.userId),(t=e.overrides)!=null&&t.client&&(n.source_info={source:e.overrides.client.source,version:e.overrides.client.version}),n}var jT=class e extends TT{constructor(e,t,n,r){super(),this.socket=void 0,this.conversationId=void 0,this.inputFormat=void 0,this.outputFormat=void 0,this.socket=e,this.conversationId=t,this.inputFormat=n,this.outputFormat=r,this.socket.addEventListener(`error`,e=>{setTimeout(()=>this.disconnect({reason:`error`,message:`The connection was closed due to a socket error.`,context:e}),0)}),this.socket.addEventListener(`close`,e=>{this.disconnect(e.code===1e3?{reason:`agent`,context:e}:{reason:`error`,message:e.reason||`The connection was closed by the server.`,context:e})}),this.socket.addEventListener(`message`,e=>{try{let t=JSON.parse(e.data);if(!OT(t))return void this.debug({type:`invalid_event`,message:`Received invalid socket event`,data:e.data});this.handleMessage(t)}catch(t){this.debug({type:`parsing_error`,message:`Failed to parse socket message`,error:t instanceof Error?t.message:String(t),data:e.data})}})}static async create(t){let n=null;try{var r,i;let a=t.origin??`wss://api.elevenlabs.io`,o,s=((r=t.overrides)==null||(r=r.client)==null?void 0:r.version)||DT,c=((i=t.overrides)==null||(i=i.client)==null?void 0:i.source)||`js_sdk`;if(t.signedUrl){let e=t.signedUrl.includes(`?`)?`&`:`?`;o=`${t.signedUrl}${e}source=${c}&version=${s}`}else o=`${a}/v1/convai/conversation?agent_id=${t.agentId}&source=${c}&version=${s}`;let l=[`convai`];t.authorization&&l.push(`bearer.${t.authorization}`),n=new WebSocket(o,l);let{conversation_id:u,agent_output_audio_format:d,user_input_audio_format:f}=await new Promise((e,r)=>{n.addEventListener(`open`,()=>{var e;let r=AT(t);(e=n)==null||e.send(JSON.stringify(r))},{once:!0}),n.addEventListener(`error`,e=>{setTimeout(()=>r(e),0)}),n.addEventListener(`close`,r),n.addEventListener(`message`,t=>{let n=JSON.parse(t.data);OT(n)&&(n.type===`conversation_initiation_metadata`?e(n.conversation_initiation_metadata_event):console.warn(`First received message is not conversation metadata.`))},{once:!0})}),p=ET(f??`pcm_16000`),m=ET(d);return new e(n,u,p,m)}catch(e){var a;throw(a=n)==null||a.close(),e}}close(){this.socket.close(1e3,`User ended conversation`)}sendMessage(e){this.socket.send(JSON.stringify(e))}async setMicMuted(e){console.warn(`WebSocket connection setMicMuted called with ${e}, but this is handled by VoiceConversation`)}};function MT(e){let t=new Uint8Array(e);return window.btoa(String.fromCharCode(...t))}function NT(e){let t=window.atob(e),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.charCodeAt(e);return r.buffer}var PT=new Map;function FT(e,t){return async(n,r)=>{let i=PT.get(e);if(i)return n.addModule(i);if(r)try{await n.addModule(r),PT.set(e,r);return}catch(t){throw Error(`Failed to load the ${e} worklet module from path: ${r}. Error: ${t}`)}let a=new Blob([t],{type:`application/javascript`}),o=URL.createObjectURL(a);try{await n.addModule(o),PT.set(e,o);return}catch{URL.revokeObjectURL(o)}try{let r=`data:application/javascript;base64,${btoa(t)}`;await n.addModule(r),PT.set(e,r)}catch{throw Error(`Failed to load the ${e} worklet module. Make sure the browser supports AudioWorklets. If you are using a strict CSP, you may need to self-host the worklet files.`)}}}var IT=FT(`rawAudioProcessor`,`/*
63
63
  * ulaw encoding logic taken from the wavefile library
64
64
  * https://github.com/rochars/wavefile/blob/master/lib/codecs/mulaw.js
65
65
  * USED BY @elevenlabs/client
@@ -183,7 +183,7 @@ class RawAudioProcessor extends AudioWorkletProcessor {
183
183
  }
184
184
  }
185
185
  registerProcessor("rawAudioProcessor", RawAudioProcessor);
186
- `),NT=class e extends xT{constructor(e,t,n,r,i={}){super(i),this.conversationId=void 0,this.inputFormat=void 0,this.outputFormat=void 0,this.room=void 0,this.isConnected=!1,this.audioEventId=1,this.audioCaptureContext=null,this.audioElements=[],this.outputDeviceId=null,this.outputAnalyser=null,this.outputFrequencyData=null,this.room=e,this.conversationId=t,this.inputFormat=n,this.outputFormat=r,this.setupRoomEventListeners()}static async create(t){let n;if(`conversationToken`in t&&t.conversationToken)n=t.conversationToken;else{if(!(`agentId`in t)||!t.agentId)throw Error(`Either conversationToken or agentId is required for WebRTC connection`);try{var r,i;let e=((r=t.overrides)==null||(r=r.client)==null?void 0:r.version)||CT,o=((i=t.overrides)==null||(i=i.client)==null?void 0:i.source)||`js_sdk`,s=`${a=t.origin??`https://api.elevenlabs.io`,a.replace(/^wss:\/\//,`https://`)}/v1/convai/conversation/token?agent_id=${t.agentId}&source=${o}&version=${e}`,c=await fetch(s);if(!c.ok)throw Error(`ElevenLabs API returned ${c.status} ${c.statusText}`);if(n=(await c.json()).token,!n)throw Error(`No conversation token received from API`)}catch(e){let n=e instanceof Error?e.message:String(e);throw e instanceof Error&&e.message.includes(`401`)&&(n=`Your agent has authentication enabled, but no signed URL or conversation token was provided.`),Error(`Failed to fetch conversation token for agent ${t.agentId}: ${n}`)}}var a;let o=new fT;try{let r=new e(o,`room_${Date.now()}`,ST(`pcm_48000`),ST(`pcm_48000`),t),i=t.livekitUrl||`wss://livekit.rtc.elevenlabs.io`;await o.connect(i,n),await new Promise(e=>{if(r.isConnected)e();else{let t=()=>{o.off(B.Connected,t),e()};o.on(B.Connected,t)}}),o.name&&(r.conversationId=o.name.match(/(conv_[a-zA-Z0-9]+)/)?.[0]||o.name),await o.localParticipant.setMicrophoneEnabled(!0);let a=ET(t);return r.debug({type:TT,message:a}),await r.sendMessage(a),r}catch(e){throw await o.disconnect(),e}}setupRoomEventListeners(){var e=this;this.room.on(B.Connected,async function(){e.isConnected=!0,console.info(`WebRTC room connected`)}),this.room.on(B.Disconnected,e=>{this.isConnected=!1,this.disconnect({reason:`agent`,context:new CloseEvent(`close`,{reason:e?.toString()})})}),this.room.on(B.ConnectionStateChanged,e=>{e===Y.Disconnected&&(this.isConnected=!1,this.disconnect({reason:`error`,message:`LiveKit connection state changed to ${e}`,context:new Event(`connection_state_changed`)}))}),this.room.on(B.DataReceived,(e,t)=>{try{let t=JSON.parse(new TextDecoder().decode(e));if(t.type===`audio`)return;wT(t)?this.handleMessage(t):console.warn(`Invalid socket event received:`,t)}catch(t){console.warn(`Failed to parse incoming data message:`,t),console.warn(`Raw payload:`,new TextDecoder().decode(e))}}),this.room.on(B.TrackSubscribed,async function(t,n,r){if(t.kind===K.Kind.Audio&&r.identity.includes(`agent`)){let n=t,r=n.attach();if(r.autoplay=!0,r.controls=!1,e.outputDeviceId&&r.setSinkId)try{await r.setSinkId(e.outputDeviceId)}catch(e){console.warn(`Failed to set output device for new audio element:`,e)}r.style.display=`none`,document.body.appendChild(r),e.audioElements.push(r),e.audioElements.length===1&&(e.onDebug==null||e.onDebug({type:`audio_element_ready`})),await e.setupAudioCapture(n)}}),this.room.on(B.ActiveSpeakersChanged,async function(t){e.updateMode(t.length>0&&t[0].identity.startsWith(`agent`)?`speaking`:`listening`)}),this.room.on(B.ParticipantDisconnected,e=>{var t;(t=e.identity)!=null&&t.startsWith(`agent`)&&this.disconnect({reason:`agent`,context:new CloseEvent(`close`,{reason:`agent disconnected`})})})}close(){if(this.isConnected){try{this.room.localParticipant.audioTrackPublications.forEach(e=>{e.track&&e.track.stop()})}catch(e){console.warn(`Error stopping local tracks:`,e)}this.audioCaptureContext&&=(this.audioCaptureContext.close().catch(e=>{console.warn(`Error closing audio capture context:`,e)}),null),this.audioElements.forEach(e=>{e.parentNode&&e.parentNode.removeChild(e)}),this.audioElements=[],this.room.disconnect()}}async sendMessage(e){if(this.isConnected&&this.room.localParticipant){if(!(`user_audio_chunk`in e))try{let t=new TextEncoder().encode(JSON.stringify(e));await this.room.localParticipant.publishData(t,{reliable:!0})}catch(t){this.debug({type:`send_message_error`,message:{message:e,error:t}}),console.error(`Failed to send message via WebRTC:`,t)}}else console.warn(`Cannot send message: room not connected or no local participant`)}getRoom(){return this.room}async setMicMuted(e){if(!this.isConnected||!this.room.localParticipant)return void console.warn(`Cannot set microphone muted: room not connected or no local participant`);let t=this.room.localParticipant.getTrackPublication(K.Source.Microphone);if(t!=null&&t.track)try{e?await t.track.mute():await t.track.unmute()}catch{await this.room.localParticipant.setMicrophoneEnabled(!e)}else await this.room.localParticipant.setMicrophoneEnabled(!e)}async setupAudioCapture(e){try{let t=new AudioContext;this.audioCaptureContext=t,this.outputAnalyser=t.createAnalyser(),this.outputAnalyser.fftSize=2048,this.outputAnalyser.smoothingTimeConstant=.8;let n=new MediaStream([e.mediaStreamTrack]),r=t.createMediaStreamSource(n);r.connect(this.outputAnalyser),await MT(t.audioWorklet);let i=new AudioWorkletNode(t,`rawAudioProcessor`);this.outputAnalyser.connect(i),i.port.postMessage({type:`setFormat`,format:this.outputFormat.format,sampleRate:this.outputFormat.sampleRate}),i.port.onmessage=e=>{let[t,n]=e.data;if(n>.01){let e=OT(t.buffer),n=this.audioEventId++;this.handleMessage({type:`audio`,audio_event:{audio_base_64:e,event_id:n}})}},r.connect(i)}catch(e){console.warn(`Failed to set up audio capture:`,e)}}setAudioVolume(e){this.audioElements.forEach(t=>{t.volume=e})}async setAudioOutputDevice(e){if(!(`setSinkId`in HTMLAudioElement.prototype))throw Error(`setSinkId is not supported in this browser`);let t=this.audioElements.map(async function(t){try{await t.setSinkId(e)}catch(e){throw console.error(`Failed to set sink ID for audio element:`,e),e}});await Promise.all(t),this.outputDeviceId=e}async setAudioInputDevice(e){if(!this.isConnected||!this.room.localParticipant)throw Error(`Cannot change input device: room not connected or no local participant`);try{let t=this.room.localParticipant.getTrackPublication(K.Source.Microphone);t!=null&&t.track&&(await t.track.stop(),await this.room.localParticipant.unpublishTrack(t.track));let n=await tT({deviceId:{exact:e},echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:{ideal:1}});await this.room.localParticipant.publishTrack(n,{name:`microphone`,source:K.Source.Microphone})}catch(e){console.error(`Failed to change input device:`,e);try{await this.room.localParticipant.setMicrophoneEnabled(!0)}catch(e){console.error(`Failed to recover microphone after device switch error:`,e)}throw e}}getOutputByteFrequencyData(){return this.outputAnalyser?(this.outputFrequencyData??=new Uint8Array(this.outputAnalyser.frequencyBinCount),this.outputAnalyser.getByteFrequencyData(this.outputFrequencyData),this.outputFrequencyData):null}};async function PT(e){let t=function(e){return e.connectionType?e.connectionType:`conversationToken`in e&&e.conversationToken?`webrtc`:`websocket`}(e);switch(t){case`websocket`:return DT.create(e);case`webrtc`:return NT.create(e);default:throw Error(`Unknown connection type: ${t}`)}}function FT(){return[`iPad Simulator`,`iPhone Simulator`,`iPod Simulator`,`iPad`,`iPhone`,`iPod`].includes(navigator.platform)||navigator.userAgent.includes(`Mac`)&&`ontouchend`in document}async function IT(e={default:0,android:3e3}){let t=e.default;/android/i.test(navigator.userAgent)?t=e.android??t:FT()&&(t=e.ios??t),t>0&&await new Promise(e=>setTimeout(e,t))}var LT=class e extends bT{static async startSession(t){let n=bT.getFullOptions(t);n.onStatusChange&&n.onStatusChange({status:`connecting`}),n.onCanSendFeedbackChange&&n.onCanSendFeedbackChange({canSendFeedback:!1}),n.onModeChange&&n.onModeChange({mode:`listening`}),n.onCanSendFeedbackChange&&n.onCanSendFeedbackChange({canSendFeedback:!1});let r=null;try{return await IT(n.connectionDelay),r=await PT(t),new e(n,r)}catch(e){var i;throw n.onStatusChange&&n.onStatusChange({status:`disconnected`}),(i=r)==null||i.close(),e}}},RT={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:{ideal:1}},zT=class e{static async create({sampleRate:t,format:n,preferHeadphonesForIosDevices:r,inputDeviceId:i,workletPaths:a,libsampleratePath:o}){let s=null,c=null;try{let l=vT({sampleRate:{ideal:t}},RT);if(FT()&&r){let e=(await window.navigator.mediaDevices.enumerateDevices()).find(e=>e.kind===`audioinput`&&[`airpod`,`headphone`,`earphone`].find(t=>e.label.toLowerCase().includes(t)));e&&(l.deviceId={ideal:e.deviceId})}i&&(l.deviceId=e.getDeviceIdConstraint(i));let u=navigator.mediaDevices.getSupportedConstraints().sampleRate;s=new window.AudioContext(u?{sampleRate:t}:{});let d=s.createAnalyser();if(!u){let e=o||`https://cdn.jsdelivr.net/npm/@alexanderolsen/libsamplerate-js@2.1.2/dist/libsamplerate.worklet.js`;await s.audioWorklet.addModule(e)}await MT(s.audioWorklet,a?.rawAudioProcessor);let f=vT({voiceIsolation:!0},l);c=await navigator.mediaDevices.getUserMedia({audio:f});let p=s.createMediaStreamSource(c),m=new AudioWorkletNode(s,`rawAudioProcessor`);return m.port.postMessage({type:`setFormat`,format:n,sampleRate:t}),p.connect(d),d.connect(m),await s.resume(),new e(s,d,m,c,p)}catch(e){var l,u;throw(l=c)==null||l.getTracks().forEach(e=>{e.stop()}),(u=s)==null||u.close(),e}}static getDeviceIdConstraint(e){if(e)return FT()?{ideal:e}:{exact:e}}constructor(e,t,n,r,i){this.context=void 0,this.analyser=void 0,this.worklet=void 0,this.inputStream=void 0,this.mediaStreamSource=void 0,this.context=e,this.analyser=t,this.worklet=n,this.inputStream=r,this.mediaStreamSource=i}async close(){this.inputStream.getTracks().forEach(e=>{e.stop()}),this.mediaStreamSource.disconnect(),await this.context.close()}setMuted(e){this.worklet.port.postMessage({type:`setMuted`,isMuted:e})}async setInputDevice(t){try{let n=vT({},RT);t&&(n.deviceId=e.getDeviceIdConstraint(t));let r=vT({voiceIsolation:!0},n),i=await navigator.mediaDevices.getUserMedia({audio:r});this.inputStream.getTracks().forEach(e=>{e.stop()}),this.mediaStreamSource.disconnect(),this.inputStream=i,this.mediaStreamSource=this.context.createMediaStreamSource(i),this.mediaStreamSource.connect(this.analyser)}catch(e){throw console.error(`Failed to switch input device:`,e),e}}},BT=jT(`audioConcatProcessor`,`/*
186
+ `),LT=class e extends TT{constructor(e,t,n,r,i={}){super(i),this.conversationId=void 0,this.inputFormat=void 0,this.outputFormat=void 0,this.room=void 0,this.isConnected=!1,this.audioEventId=1,this.audioCaptureContext=null,this.audioElements=[],this.outputDeviceId=null,this.outputAnalyser=null,this.outputFrequencyData=null,this.room=e,this.conversationId=t,this.inputFormat=n,this.outputFormat=r,this.setupRoomEventListeners()}static async create(t){let n;if(`conversationToken`in t&&t.conversationToken)n=t.conversationToken;else{if(!(`agentId`in t)||!t.agentId)throw Error(`Either conversationToken or agentId is required for WebRTC connection`);try{var r,i;let e=((r=t.overrides)==null||(r=r.client)==null?void 0:r.version)||DT,o=((i=t.overrides)==null||(i=i.client)==null?void 0:i.source)||`js_sdk`,s=`${a=t.origin??`https://api.elevenlabs.io`,a.replace(/^wss:\/\//,`https://`)}/v1/convai/conversation/token?agent_id=${t.agentId}&source=${o}&version=${e}`,c=await fetch(s);if(!c.ok)throw Error(`ElevenLabs API returned ${c.status} ${c.statusText}`);if(n=(await c.json()).token,!n)throw Error(`No conversation token received from API`)}catch(e){let n=e instanceof Error?e.message:String(e);throw e instanceof Error&&e.message.includes(`401`)&&(n=`Your agent has authentication enabled, but no signed URL or conversation token was provided.`),Error(`Failed to fetch conversation token for agent ${t.agentId}: ${n}`)}}var a;let o=new gT;try{let r=new e(o,`room_${Date.now()}`,ET(`pcm_48000`),ET(`pcm_48000`),t),i=t.livekitUrl||`wss://livekit.rtc.elevenlabs.io`;await o.connect(i,n),await new Promise(e=>{if(r.isConnected)e();else{let t=()=>{o.off(B.Connected,t),e()};o.on(B.Connected,t)}}),o.name&&(r.conversationId=o.name.match(/(conv_[a-zA-Z0-9]+)/)?.[0]||o.name),await o.localParticipant.setMicrophoneEnabled(!0);let a=AT(t);return r.debug({type:kT,message:a}),await r.sendMessage(a),r}catch(e){throw await o.disconnect(),e}}setupRoomEventListeners(){var e=this;this.room.on(B.Connected,async function(){e.isConnected=!0,console.info(`WebRTC room connected`)}),this.room.on(B.Disconnected,e=>{this.isConnected=!1,this.disconnect({reason:`agent`,context:new CloseEvent(`close`,{reason:e?.toString()})})}),this.room.on(B.ConnectionStateChanged,e=>{e===Y.Disconnected&&(this.isConnected=!1,this.disconnect({reason:`error`,message:`LiveKit connection state changed to ${e}`,context:new Event(`connection_state_changed`)}))}),this.room.on(B.DataReceived,(e,t)=>{try{let t=JSON.parse(new TextDecoder().decode(e));if(t.type===`audio`)return;OT(t)?this.handleMessage(t):console.warn(`Invalid socket event received:`,t)}catch(t){console.warn(`Failed to parse incoming data message:`,t),console.warn(`Raw payload:`,new TextDecoder().decode(e))}}),this.room.on(B.TrackSubscribed,async function(t,n,r){if(t.kind===K.Kind.Audio&&r.identity.includes(`agent`)){let n=t,r=n.attach();if(r.autoplay=!0,r.controls=!1,e.outputDeviceId&&r.setSinkId)try{await r.setSinkId(e.outputDeviceId)}catch(e){console.warn(`Failed to set output device for new audio element:`,e)}r.style.display=`none`,document.body.appendChild(r),e.audioElements.push(r),e.audioElements.length===1&&(e.onDebug==null||e.onDebug({type:`audio_element_ready`})),await e.setupAudioCapture(n)}}),this.room.on(B.ActiveSpeakersChanged,async function(t){e.updateMode(t.length>0&&t[0].identity.startsWith(`agent`)?`speaking`:`listening`)}),this.room.on(B.ParticipantDisconnected,e=>{var t;(t=e.identity)!=null&&t.startsWith(`agent`)&&this.disconnect({reason:`agent`,context:new CloseEvent(`close`,{reason:`agent disconnected`})})})}close(){if(this.isConnected){try{this.room.localParticipant.audioTrackPublications.forEach(e=>{e.track&&e.track.stop()})}catch(e){console.warn(`Error stopping local tracks:`,e)}this.audioCaptureContext&&=(this.audioCaptureContext.close().catch(e=>{console.warn(`Error closing audio capture context:`,e)}),null),this.audioElements.forEach(e=>{e.parentNode&&e.parentNode.removeChild(e)}),this.audioElements=[],this.room.disconnect()}}async sendMessage(e){if(this.isConnected&&this.room.localParticipant){if(!(`user_audio_chunk`in e))try{let t=new TextEncoder().encode(JSON.stringify(e));await this.room.localParticipant.publishData(t,{reliable:!0})}catch(t){this.debug({type:`send_message_error`,message:{message:e,error:t}}),console.error(`Failed to send message via WebRTC:`,t)}}else console.warn(`Cannot send message: room not connected or no local participant`)}getRoom(){return this.room}async setMicMuted(e){if(!this.isConnected||!this.room.localParticipant)return void console.warn(`Cannot set microphone muted: room not connected or no local participant`);let t=this.room.localParticipant.getTrackPublication(K.Source.Microphone);if(t!=null&&t.track)try{e?await t.track.mute():await t.track.unmute()}catch{await this.room.localParticipant.setMicrophoneEnabled(!e)}else await this.room.localParticipant.setMicrophoneEnabled(!e)}async setupAudioCapture(e){try{let t=new AudioContext;this.audioCaptureContext=t,this.outputAnalyser=t.createAnalyser(),this.outputAnalyser.fftSize=2048,this.outputAnalyser.smoothingTimeConstant=.8;let n=new MediaStream([e.mediaStreamTrack]),r=t.createMediaStreamSource(n);r.connect(this.outputAnalyser),await IT(t.audioWorklet);let i=new AudioWorkletNode(t,`rawAudioProcessor`);this.outputAnalyser.connect(i),i.port.postMessage({type:`setFormat`,format:this.outputFormat.format,sampleRate:this.outputFormat.sampleRate}),i.port.onmessage=e=>{let[t,n]=e.data;if(n>.01){let e=MT(t.buffer),n=this.audioEventId++;this.handleMessage({type:`audio`,audio_event:{audio_base_64:e,event_id:n}})}},r.connect(i)}catch(e){console.warn(`Failed to set up audio capture:`,e)}}setAudioVolume(e){this.audioElements.forEach(t=>{t.volume=e})}async setAudioOutputDevice(e){if(!(`setSinkId`in HTMLAudioElement.prototype))throw Error(`setSinkId is not supported in this browser`);let t=this.audioElements.map(async function(t){try{await t.setSinkId(e)}catch(e){throw console.error(`Failed to set sink ID for audio element:`,e),e}});await Promise.all(t),this.outputDeviceId=e}async setAudioInputDevice(e){if(!this.isConnected||!this.room.localParticipant)throw Error(`Cannot change input device: room not connected or no local participant`);try{let t=this.room.localParticipant.getTrackPublication(K.Source.Microphone);t!=null&&t.track&&(await t.track.stop(),await this.room.localParticipant.unpublishTrack(t.track));let n=await aT({deviceId:{exact:e},echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:{ideal:1}});await this.room.localParticipant.publishTrack(n,{name:`microphone`,source:K.Source.Microphone})}catch(e){console.error(`Failed to change input device:`,e);try{await this.room.localParticipant.setMicrophoneEnabled(!0)}catch(e){console.error(`Failed to recover microphone after device switch error:`,e)}throw e}}getOutputByteFrequencyData(){return this.outputAnalyser?(this.outputFrequencyData??=new Uint8Array(this.outputAnalyser.frequencyBinCount),this.outputAnalyser.getByteFrequencyData(this.outputFrequencyData),this.outputFrequencyData):null}};async function RT(e){let t=function(e){return e.connectionType?e.connectionType:`conversationToken`in e&&e.conversationToken?`webrtc`:`websocket`}(e);switch(t){case`websocket`:return jT.create(e);case`webrtc`:return LT.create(e);default:throw Error(`Unknown connection type: ${t}`)}}function zT(){return[`iPad Simulator`,`iPhone Simulator`,`iPod Simulator`,`iPad`,`iPhone`,`iPod`].includes(navigator.platform)||navigator.userAgent.includes(`Mac`)&&`ontouchend`in document}async function BT(e={default:0,android:3e3}){let t=e.default;/android/i.test(navigator.userAgent)?t=e.android??t:zT()&&(t=e.ios??t),t>0&&await new Promise(e=>setTimeout(e,t))}var VT=class e extends wT{static async startSession(t){let n=wT.getFullOptions(t);n.onStatusChange&&n.onStatusChange({status:`connecting`}),n.onCanSendFeedbackChange&&n.onCanSendFeedbackChange({canSendFeedback:!1}),n.onModeChange&&n.onModeChange({mode:`listening`}),n.onCanSendFeedbackChange&&n.onCanSendFeedbackChange({canSendFeedback:!1});let r=null;try{return await BT(n.connectionDelay),r=await RT(t),new e(n,r)}catch(e){var i;throw n.onStatusChange&&n.onStatusChange({status:`disconnected`}),(i=r)==null||i.close(),e}}},HT={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:{ideal:1}},UT=class e{static async create({sampleRate:t,format:n,preferHeadphonesForIosDevices:r,inputDeviceId:i,workletPaths:a,libsampleratePath:o}){let s=null,c=null;try{let l=ST({sampleRate:{ideal:t}},HT);if(zT()&&r){let e=(await window.navigator.mediaDevices.enumerateDevices()).find(e=>e.kind===`audioinput`&&[`airpod`,`headphone`,`earphone`].find(t=>e.label.toLowerCase().includes(t)));e&&(l.deviceId={ideal:e.deviceId})}i&&(l.deviceId=e.getDeviceIdConstraint(i));let u=navigator.mediaDevices.getSupportedConstraints().sampleRate;s=new window.AudioContext(u?{sampleRate:t}:{});let d=s.createAnalyser();if(!u){let e=o||`https://cdn.jsdelivr.net/npm/@alexanderolsen/libsamplerate-js@2.1.2/dist/libsamplerate.worklet.js`;await s.audioWorklet.addModule(e)}await IT(s.audioWorklet,a?.rawAudioProcessor);let f=ST({voiceIsolation:!0},l);c=await navigator.mediaDevices.getUserMedia({audio:f});let p=s.createMediaStreamSource(c),m=new AudioWorkletNode(s,`rawAudioProcessor`);return m.port.postMessage({type:`setFormat`,format:n,sampleRate:t}),p.connect(d),d.connect(m),await s.resume(),new e(s,d,m,c,p)}catch(e){var l,u;throw(l=c)==null||l.getTracks().forEach(e=>{e.stop()}),(u=s)==null||u.close(),e}}static getDeviceIdConstraint(e){if(e)return zT()?{ideal:e}:{exact:e}}constructor(e,t,n,r,i){this.context=void 0,this.analyser=void 0,this.worklet=void 0,this.inputStream=void 0,this.mediaStreamSource=void 0,this.context=e,this.analyser=t,this.worklet=n,this.inputStream=r,this.mediaStreamSource=i}async close(){this.inputStream.getTracks().forEach(e=>{e.stop()}),this.mediaStreamSource.disconnect(),await this.context.close()}setMuted(e){this.worklet.port.postMessage({type:`setMuted`,isMuted:e})}async setInputDevice(t){try{let n=ST({},HT);t&&(n.deviceId=e.getDeviceIdConstraint(t));let r=ST({voiceIsolation:!0},n),i=await navigator.mediaDevices.getUserMedia({audio:r});this.inputStream.getTracks().forEach(e=>{e.stop()}),this.mediaStreamSource.disconnect(),this.inputStream=i,this.mediaStreamSource=this.context.createMediaStreamSource(i),this.mediaStreamSource.connect(this.analyser)}catch(e){throw console.error(`Failed to switch input device:`,e),e}}},WT=FT(`audioConcatProcessor`,`/*
187
187
  * ulaw decoding logic taken from the wavefile library
188
188
  * https://github.com/rochars/wavefile/blob/master/lib/codecs/mulaw.js
189
189
  * USED BY @elevenlabs/client
@@ -275,7 +275,7 @@ class AudioConcatProcessor extends AudioWorkletProcessor {
275
275
  }
276
276
 
277
277
  registerProcessor("audioConcatProcessor", AudioConcatProcessor);
278
- `),VT=class e{static async create({sampleRate:t,format:n,outputDeviceId:r,workletPaths:i}){let a=null,o=null;try{a=new AudioContext({sampleRate:t});let s=a.createAnalyser(),c=a.createGain();o=new Audio,o.src=``,o.load(),o.autoplay=!0,o.style.display=`none`,document.body.appendChild(o);let l=a.createMediaStreamDestination();o.srcObject=l.stream,c.connect(s),s.connect(l),await BT(a.audioWorklet,i?.audioConcatProcessor);let u=new AudioWorkletNode(a,`audioConcatProcessor`);return u.port.postMessage({type:`setFormat`,format:n}),u.connect(c),await a.resume(),r&&o.setSinkId&&await o.setSinkId(r),new e(a,s,c,u,o)}catch(e){var s,c;throw(s=o)!=null&&s.parentNode&&o.parentNode.removeChild(o),(c=o)==null||c.pause(),a&&a.state!==`closed`&&await a.close(),e}}constructor(e,t,n,r,i){this.context=void 0,this.analyser=void 0,this.gain=void 0,this.worklet=void 0,this.audioElement=void 0,this.context=e,this.analyser=t,this.gain=n,this.worklet=r,this.audioElement=i}async setOutputDevice(e){if(!(`setSinkId`in HTMLAudioElement.prototype))throw Error(`setSinkId is not supported in this browser`);await this.audioElement.setSinkId(e||``)}async close(){this.audioElement.parentNode&&this.audioElement.parentNode.removeChild(this.audioElement),this.audioElement.pause(),await this.context.close()}},HT=class e extends bT{static async startSession(t){var n;let r=bT.getFullOptions(t);r.onStatusChange&&r.onStatusChange({status:`connecting`}),r.onCanSendFeedbackChange&&r.onCanSendFeedbackChange({canSendFeedback:!1});let i=null,a=null,o=null,s=null,c=null;if((n=t.useWakeLock)==null||n)try{c=await navigator.wakeLock.request(`screen`)}catch{}try{var l;return s=await navigator.mediaDevices.getUserMedia({audio:!0}),await IT(r.connectionDelay),a=await PT(t),[i,o]=await Promise.all([zT.create(vT({},a.inputFormat,{preferHeadphonesForIosDevices:t.preferHeadphonesForIosDevices,inputDeviceId:t.inputDeviceId,workletPaths:t.workletPaths,libsampleratePath:t.libsampleratePath})),VT.create(vT({},a.outputFormat,{outputDeviceId:t.outputDeviceId,workletPaths:t.workletPaths}))]),(l=s)==null||l.getTracks().forEach(e=>{e.stop()}),s=null,new e(r,a,i,o,c)}catch(e){var u,d;r.onStatusChange&&r.onStatusChange({status:`disconnected`}),(u=s)==null||u.getTracks().forEach(e=>{e.stop()}),(d=a)==null||d.close(),await i?.close(),await o?.close();try{await c?.release(),c=null}catch{}throw e}}constructor(e,t,n,r,i){super(e,t),this.input=void 0,this.output=void 0,this.wakeLock=void 0,this.inputFrequencyData=void 0,this.outputFrequencyData=void 0,this.onInputWorkletMessage=e=>{this.status===`connected`&&this.connection.sendMessage({user_audio_chunk:OT(e.data[0].buffer)})},this.onOutputWorkletMessage=({data:e})=>{e.type===`process`&&this.updateMode(e.finished?`listening`:`speaking`)},this.addAudioBase64Chunk=e=>{this.output.gain.gain.cancelScheduledValues(this.output.context.currentTime),this.output.gain.gain.value=this.volume,this.output.worklet.port.postMessage({type:`clearInterrupted`}),this.output.worklet.port.postMessage({type:`buffer`,buffer:kT(e)})},this.fadeOutAudio=()=>{this.updateMode(`listening`),this.output.worklet.port.postMessage({type:`interrupt`}),this.output.gain.gain.exponentialRampToValueAtTime(1e-4,this.output.context.currentTime+2),setTimeout(()=>{this.output.gain.gain.value=this.volume,this.output.worklet.port.postMessage({type:`clearInterrupted`})},2e3)},this.calculateVolume=e=>{if(e.length===0)return 0;let t=0;for(let n=0;n<e.length;n++)t+=e[n]/255;return t/=e.length,t<0?0:t>1?1:t},this.setVolume=({volume:e})=>{let t=Number.isFinite(e)?Math.min(1,Math.max(0,e)):1;this.volume=t,this.connection instanceof NT?this.connection.setAudioVolume(t):this.output.gain.gain.value=t},this.input=n,this.output=r,this.wakeLock=i,this.input.worklet.port.onmessage=this.onInputWorkletMessage,this.output.worklet.port.onmessage=this.onOutputWorkletMessage}async handleEndSession(){await super.handleEndSession();try{await this.wakeLock?.release(),this.wakeLock=null}catch{}await this.input.close(),await this.output.close()}handleInterruption(e){super.handleInterruption(e),this.fadeOutAudio()}handleAudio(e){var t,n;this.lastInterruptTimestamp<=e.audio_event.event_id&&((t=(n=this.options).onAudio)==null||t.call(n,e.audio_event.audio_base_64),this.connection instanceof NT||this.addAudioBase64Chunk(e.audio_event.audio_base_64),this.currentEventId=e.audio_event.event_id,this.updateCanSendFeedback(),this.updateMode(`speaking`))}setMicMuted(e){this.connection instanceof NT?this.connection.setMicMuted(e):this.input.setMuted(e)}getInputByteFrequencyData(){return this.inputFrequencyData??=new Uint8Array(this.input.analyser.frequencyBinCount),this.input.analyser.getByteFrequencyData(this.inputFrequencyData),this.inputFrequencyData}getOutputByteFrequencyData(){return this.connection instanceof NT?this.connection.getOutputByteFrequencyData()||new Uint8Array(1024):(this.outputFrequencyData??=new Uint8Array(this.output.analyser.frequencyBinCount),this.output.analyser.getByteFrequencyData(this.outputFrequencyData),this.outputFrequencyData)}getInputVolume(){return this.calculateVolume(this.getInputByteFrequencyData())}getOutputVolume(){return this.calculateVolume(this.getOutputByteFrequencyData())}async changeInputDevice({sampleRate:e,format:t,preferHeadphonesForIosDevices:n,inputDeviceId:r}){try{if(this.connection instanceof DT)try{return await this.input.setInputDevice(r),this.input}catch(e){console.warn(`Failed to change device on existing input, recreating:`,e)}return this.connection instanceof NT&&await this.connection.setAudioInputDevice(r||``),await this.input.close(),this.input=await zT.create({sampleRate:e??this.connection.inputFormat.sampleRate,format:t??this.connection.inputFormat.format,preferHeadphonesForIosDevices:n,inputDeviceId:r,workletPaths:this.options.workletPaths,libsampleratePath:this.options.libsampleratePath}),this.input.worklet.port.onmessage=this.onInputWorkletMessage,this.input}catch(e){throw console.error(`Error changing input device`,e),e}}async changeOutputDevice({sampleRate:e,format:t,outputDeviceId:n}){try{if(this.connection instanceof DT)try{return await this.output.setOutputDevice(n),this.output}catch(e){console.warn(`Failed to change device on existing output, recreating:`,e)}return this.connection instanceof NT&&await this.connection.setAudioOutputDevice(n||``),await this.output.close(),this.output=await VT.create({sampleRate:e??this.connection.outputFormat.sampleRate,format:t??this.connection.outputFormat.format,outputDeviceId:n,workletPaths:this.options.workletPaths}),this.output}catch(e){throw console.error(`Error changing output device`,e),e}}},UT=class{constructor(){this.listeners=new Map}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set);let n=this.listeners.get(e);n&&n.add(t)}off(e,t){let n=this.listeners.get(e);n&&n.delete(t)}emit(e,...t){let n=this.listeners.get(e);n&&n.forEach(e=>{e(...t)})}},Z;(function(e){e.SESSION_STARTED=`session_started`,e.PARTIAL_TRANSCRIPT=`partial_transcript`,e.COMMITTED_TRANSCRIPT=`committed_transcript`,e.COMMITTED_TRANSCRIPT_WITH_TIMESTAMPS=`committed_transcript_with_timestamps`,e.AUTH_ERROR=`auth_error`,e.ERROR=`error`,e.OPEN=`open`,e.CLOSE=`close`,e.QUOTA_EXCEEDED=`quota_exceeded`,e.COMMIT_THROTTLED=`commit_throttled`,e.TRANSCRIBER_ERROR=`transcriber_error`,e.UNACCEPTED_TERMS=`unaccepted_terms`,e.RATE_LIMITED=`rate_limited`,e.INPUT_ERROR=`input_error`,e.QUEUE_OVERFLOW=`queue_overflow`,e.RESOURCE_EXHAUSTED=`resource_exhausted`,e.SESSION_TIME_LIMIT_EXCEEDED=`session_time_limit_exceeded`,e.CHUNK_SIZE_EXCEEDED=`chunk_size_exceeded`,e.INSUFFICIENT_AUDIO_ACTIVITY=`insufficient_audio_activity`})(Z||={});var WT=class{constructor(e){this.websocket=null,this.eventEmitter=new UT,this.currentSampleRate=16e3,this._audioCleanup=void 0,this.currentSampleRate=e}setWebSocket(e){this.websocket=e,this.websocket.readyState===WebSocket.OPEN?this.eventEmitter.emit(Z.OPEN):this.websocket.addEventListener(`open`,()=>{this.eventEmitter.emit(Z.OPEN)}),this.websocket.addEventListener(`message`,e=>{try{let t=JSON.parse(e.data);switch(t.message_type){case`session_started`:this.eventEmitter.emit(Z.SESSION_STARTED,t);break;case`partial_transcript`:this.eventEmitter.emit(Z.PARTIAL_TRANSCRIPT,t);break;case`committed_transcript`:this.eventEmitter.emit(Z.COMMITTED_TRANSCRIPT,t);break;case`committed_transcript_with_timestamps`:this.eventEmitter.emit(Z.COMMITTED_TRANSCRIPT_WITH_TIMESTAMPS,t);break;case`auth_error`:this.eventEmitter.emit(Z.AUTH_ERROR,t),this.eventEmitter.emit(Z.ERROR,t);break;case`quota_exceeded`:this.eventEmitter.emit(Z.QUOTA_EXCEEDED,t),this.eventEmitter.emit(Z.ERROR,t);break;case`commit_throttled`:this.eventEmitter.emit(Z.COMMIT_THROTTLED,t),this.eventEmitter.emit(Z.ERROR,t);break;case`transcriber_error`:this.eventEmitter.emit(Z.TRANSCRIBER_ERROR,t),this.eventEmitter.emit(Z.ERROR,t);break;case`unaccepted_terms`:this.eventEmitter.emit(Z.UNACCEPTED_TERMS,t),this.eventEmitter.emit(Z.ERROR,t);break;case`rate_limited`:this.eventEmitter.emit(Z.RATE_LIMITED,t),this.eventEmitter.emit(Z.ERROR,t);break;case`input_error`:this.eventEmitter.emit(Z.INPUT_ERROR,t),this.eventEmitter.emit(Z.ERROR,t);break;case`queue_overflow`:this.eventEmitter.emit(Z.QUEUE_OVERFLOW,t),this.eventEmitter.emit(Z.ERROR,t);break;case`resource_exhausted`:this.eventEmitter.emit(Z.RESOURCE_EXHAUSTED,t),this.eventEmitter.emit(Z.ERROR,t);break;case`session_time_limit_exceeded`:this.eventEmitter.emit(Z.SESSION_TIME_LIMIT_EXCEEDED,t),this.eventEmitter.emit(Z.ERROR,t);break;case`chunk_size_exceeded`:this.eventEmitter.emit(Z.CHUNK_SIZE_EXCEEDED,t),this.eventEmitter.emit(Z.ERROR,t);break;case`insufficient_audio_activity`:this.eventEmitter.emit(Z.INSUFFICIENT_AUDIO_ACTIVITY,t),this.eventEmitter.emit(Z.ERROR,t);break;case`error`:this.eventEmitter.emit(Z.ERROR,t);break;default:console.warn(`Unknown message type:`,t)}}catch(t){console.error(`Failed to parse WebSocket message:`,t,e.data),this.eventEmitter.emit(Z.ERROR,Error(`Failed to parse message: ${t}`))}}),this.websocket.addEventListener(`error`,e=>{console.error(`WebSocket error:`,e),this.eventEmitter.emit(Z.ERROR,e)}),this.websocket.addEventListener(`close`,e=>{if(console.log(`WebSocket closed: code=${e.code}, reason="${e.reason}", wasClean=${e.wasClean}`),!e.wasClean||e.code!==1e3&&e.code!==1005){let t=`WebSocket closed unexpectedly: ${e.code} - ${e.reason||`No reason provided`}`;console.error(t),this.eventEmitter.emit(Z.ERROR,Error(t))}this.eventEmitter.emit(Z.CLOSE,e)})}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}send(e){var t;if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw Error(`WebSocket is not connected`);let n={message_type:`input_audio_chunk`,audio_base_64:e.audioBase64,commit:(t=e.commit)!=null&&t,sample_rate:e.sampleRate??this.currentSampleRate,previous_text:e.previousText};this.websocket.send(JSON.stringify(n))}commit(){if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw Error(`WebSocket is not connected`);this.websocket.send(JSON.stringify({message_type:`input_audio_chunk`,audio_base_64:``,commit:!0,sample_rate:this.currentSampleRate}))}close(){this._audioCleanup&&this._audioCleanup(),this.websocket&&this.websocket.close(1e3,`User ended session`)}},GT=jT(`scribeAudioProcessor`,`/*
278
+ `),GT=class e{static async create({sampleRate:t,format:n,outputDeviceId:r,workletPaths:i}){let a=null,o=null;try{a=new AudioContext({sampleRate:t});let s=a.createAnalyser(),c=a.createGain();o=new Audio,o.src=``,o.load(),o.autoplay=!0,o.style.display=`none`,document.body.appendChild(o);let l=a.createMediaStreamDestination();o.srcObject=l.stream,c.connect(s),s.connect(l),await WT(a.audioWorklet,i?.audioConcatProcessor);let u=new AudioWorkletNode(a,`audioConcatProcessor`);return u.port.postMessage({type:`setFormat`,format:n}),u.connect(c),await a.resume(),r&&o.setSinkId&&await o.setSinkId(r),new e(a,s,c,u,o)}catch(e){var s,c;throw(s=o)!=null&&s.parentNode&&o.parentNode.removeChild(o),(c=o)==null||c.pause(),a&&a.state!==`closed`&&await a.close(),e}}constructor(e,t,n,r,i){this.context=void 0,this.analyser=void 0,this.gain=void 0,this.worklet=void 0,this.audioElement=void 0,this.context=e,this.analyser=t,this.gain=n,this.worklet=r,this.audioElement=i}async setOutputDevice(e){if(!(`setSinkId`in HTMLAudioElement.prototype))throw Error(`setSinkId is not supported in this browser`);await this.audioElement.setSinkId(e||``)}async close(){this.audioElement.parentNode&&this.audioElement.parentNode.removeChild(this.audioElement),this.audioElement.pause(),await this.context.close()}},KT=class e extends wT{static async startSession(t){var n;let r=wT.getFullOptions(t);r.onStatusChange&&r.onStatusChange({status:`connecting`}),r.onCanSendFeedbackChange&&r.onCanSendFeedbackChange({canSendFeedback:!1});let i=null,a=null,o=null,s=null,c=null;if((n=t.useWakeLock)==null||n)try{c=await navigator.wakeLock.request(`screen`)}catch{}try{var l;return s=await navigator.mediaDevices.getUserMedia({audio:!0}),await BT(r.connectionDelay),a=await RT(t),[i,o]=await Promise.all([UT.create(ST({},a.inputFormat,{preferHeadphonesForIosDevices:t.preferHeadphonesForIosDevices,inputDeviceId:t.inputDeviceId,workletPaths:t.workletPaths,libsampleratePath:t.libsampleratePath})),GT.create(ST({},a.outputFormat,{outputDeviceId:t.outputDeviceId,workletPaths:t.workletPaths}))]),(l=s)==null||l.getTracks().forEach(e=>{e.stop()}),s=null,new e(r,a,i,o,c)}catch(e){var u,d;r.onStatusChange&&r.onStatusChange({status:`disconnected`}),(u=s)==null||u.getTracks().forEach(e=>{e.stop()}),(d=a)==null||d.close(),await i?.close(),await o?.close();try{await c?.release(),c=null}catch{}throw e}}constructor(e,t,n,r,i){super(e,t),this.input=void 0,this.output=void 0,this.wakeLock=void 0,this.inputFrequencyData=void 0,this.outputFrequencyData=void 0,this.onInputWorkletMessage=e=>{this.status===`connected`&&this.connection.sendMessage({user_audio_chunk:MT(e.data[0].buffer)})},this.onOutputWorkletMessage=({data:e})=>{e.type===`process`&&this.updateMode(e.finished?`listening`:`speaking`)},this.addAudioBase64Chunk=e=>{this.output.gain.gain.cancelScheduledValues(this.output.context.currentTime),this.output.gain.gain.value=this.volume,this.output.worklet.port.postMessage({type:`clearInterrupted`}),this.output.worklet.port.postMessage({type:`buffer`,buffer:NT(e)})},this.fadeOutAudio=()=>{this.updateMode(`listening`),this.output.worklet.port.postMessage({type:`interrupt`}),this.output.gain.gain.exponentialRampToValueAtTime(1e-4,this.output.context.currentTime+2),setTimeout(()=>{this.output.gain.gain.value=this.volume,this.output.worklet.port.postMessage({type:`clearInterrupted`})},2e3)},this.calculateVolume=e=>{if(e.length===0)return 0;let t=0;for(let n=0;n<e.length;n++)t+=e[n]/255;return t/=e.length,t<0?0:t>1?1:t},this.setVolume=({volume:e})=>{let t=Number.isFinite(e)?Math.min(1,Math.max(0,e)):1;this.volume=t,this.connection instanceof LT?this.connection.setAudioVolume(t):this.output.gain.gain.value=t},this.input=n,this.output=r,this.wakeLock=i,this.input.worklet.port.onmessage=this.onInputWorkletMessage,this.output.worklet.port.onmessage=this.onOutputWorkletMessage}async handleEndSession(){await super.handleEndSession();try{await this.wakeLock?.release(),this.wakeLock=null}catch{}await this.input.close(),await this.output.close()}handleInterruption(e){super.handleInterruption(e),this.fadeOutAudio()}handleAudio(e){var t,n;this.lastInterruptTimestamp<=e.audio_event.event_id&&((t=(n=this.options).onAudio)==null||t.call(n,e.audio_event.audio_base_64),this.connection instanceof LT||this.addAudioBase64Chunk(e.audio_event.audio_base_64),this.currentEventId=e.audio_event.event_id,this.updateCanSendFeedback(),this.updateMode(`speaking`))}setMicMuted(e){this.connection instanceof LT?this.connection.setMicMuted(e):this.input.setMuted(e)}getInputByteFrequencyData(){return this.inputFrequencyData??=new Uint8Array(this.input.analyser.frequencyBinCount),this.input.analyser.getByteFrequencyData(this.inputFrequencyData),this.inputFrequencyData}getOutputByteFrequencyData(){return this.connection instanceof LT?this.connection.getOutputByteFrequencyData()||new Uint8Array(1024):(this.outputFrequencyData??=new Uint8Array(this.output.analyser.frequencyBinCount),this.output.analyser.getByteFrequencyData(this.outputFrequencyData),this.outputFrequencyData)}getInputVolume(){return this.calculateVolume(this.getInputByteFrequencyData())}getOutputVolume(){return this.calculateVolume(this.getOutputByteFrequencyData())}async changeInputDevice({sampleRate:e,format:t,preferHeadphonesForIosDevices:n,inputDeviceId:r}){try{if(this.connection instanceof jT)try{return await this.input.setInputDevice(r),this.input}catch(e){console.warn(`Failed to change device on existing input, recreating:`,e)}return this.connection instanceof LT&&await this.connection.setAudioInputDevice(r||``),await this.input.close(),this.input=await UT.create({sampleRate:e??this.connection.inputFormat.sampleRate,format:t??this.connection.inputFormat.format,preferHeadphonesForIosDevices:n,inputDeviceId:r,workletPaths:this.options.workletPaths,libsampleratePath:this.options.libsampleratePath}),this.input.worklet.port.onmessage=this.onInputWorkletMessage,this.input}catch(e){throw console.error(`Error changing input device`,e),e}}async changeOutputDevice({sampleRate:e,format:t,outputDeviceId:n}){try{if(this.connection instanceof jT)try{return await this.output.setOutputDevice(n),this.output}catch(e){console.warn(`Failed to change device on existing output, recreating:`,e)}return this.connection instanceof LT&&await this.connection.setAudioOutputDevice(n||``),await this.output.close(),this.output=await GT.create({sampleRate:e??this.connection.outputFormat.sampleRate,format:t??this.connection.outputFormat.format,outputDeviceId:n,workletPaths:this.options.workletPaths}),this.output}catch(e){throw console.error(`Error changing output device`,e),e}}},qT=class{constructor(){this.listeners=new Map}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set);let n=this.listeners.get(e);n&&n.add(t)}off(e,t){let n=this.listeners.get(e);n&&n.delete(t)}emit(e,...t){let n=this.listeners.get(e);n&&n.forEach(e=>{e(...t)})}},Z;(function(e){e.SESSION_STARTED=`session_started`,e.PARTIAL_TRANSCRIPT=`partial_transcript`,e.COMMITTED_TRANSCRIPT=`committed_transcript`,e.COMMITTED_TRANSCRIPT_WITH_TIMESTAMPS=`committed_transcript_with_timestamps`,e.AUTH_ERROR=`auth_error`,e.ERROR=`error`,e.OPEN=`open`,e.CLOSE=`close`,e.QUOTA_EXCEEDED=`quota_exceeded`,e.COMMIT_THROTTLED=`commit_throttled`,e.TRANSCRIBER_ERROR=`transcriber_error`,e.UNACCEPTED_TERMS=`unaccepted_terms`,e.RATE_LIMITED=`rate_limited`,e.INPUT_ERROR=`input_error`,e.QUEUE_OVERFLOW=`queue_overflow`,e.RESOURCE_EXHAUSTED=`resource_exhausted`,e.SESSION_TIME_LIMIT_EXCEEDED=`session_time_limit_exceeded`,e.CHUNK_SIZE_EXCEEDED=`chunk_size_exceeded`,e.INSUFFICIENT_AUDIO_ACTIVITY=`insufficient_audio_activity`})(Z||={});var JT=class{constructor(e){this.websocket=null,this.eventEmitter=new qT,this.currentSampleRate=16e3,this._audioCleanup=void 0,this.currentSampleRate=e}setWebSocket(e){this.websocket=e,this.websocket.readyState===WebSocket.OPEN?this.eventEmitter.emit(Z.OPEN):this.websocket.addEventListener(`open`,()=>{this.eventEmitter.emit(Z.OPEN)}),this.websocket.addEventListener(`message`,e=>{try{let t=JSON.parse(e.data);switch(t.message_type){case`session_started`:this.eventEmitter.emit(Z.SESSION_STARTED,t);break;case`partial_transcript`:this.eventEmitter.emit(Z.PARTIAL_TRANSCRIPT,t);break;case`committed_transcript`:this.eventEmitter.emit(Z.COMMITTED_TRANSCRIPT,t);break;case`committed_transcript_with_timestamps`:this.eventEmitter.emit(Z.COMMITTED_TRANSCRIPT_WITH_TIMESTAMPS,t);break;case`auth_error`:this.eventEmitter.emit(Z.AUTH_ERROR,t),this.eventEmitter.emit(Z.ERROR,t);break;case`quota_exceeded`:this.eventEmitter.emit(Z.QUOTA_EXCEEDED,t),this.eventEmitter.emit(Z.ERROR,t);break;case`commit_throttled`:this.eventEmitter.emit(Z.COMMIT_THROTTLED,t),this.eventEmitter.emit(Z.ERROR,t);break;case`transcriber_error`:this.eventEmitter.emit(Z.TRANSCRIBER_ERROR,t),this.eventEmitter.emit(Z.ERROR,t);break;case`unaccepted_terms`:this.eventEmitter.emit(Z.UNACCEPTED_TERMS,t),this.eventEmitter.emit(Z.ERROR,t);break;case`rate_limited`:this.eventEmitter.emit(Z.RATE_LIMITED,t),this.eventEmitter.emit(Z.ERROR,t);break;case`input_error`:this.eventEmitter.emit(Z.INPUT_ERROR,t),this.eventEmitter.emit(Z.ERROR,t);break;case`queue_overflow`:this.eventEmitter.emit(Z.QUEUE_OVERFLOW,t),this.eventEmitter.emit(Z.ERROR,t);break;case`resource_exhausted`:this.eventEmitter.emit(Z.RESOURCE_EXHAUSTED,t),this.eventEmitter.emit(Z.ERROR,t);break;case`session_time_limit_exceeded`:this.eventEmitter.emit(Z.SESSION_TIME_LIMIT_EXCEEDED,t),this.eventEmitter.emit(Z.ERROR,t);break;case`chunk_size_exceeded`:this.eventEmitter.emit(Z.CHUNK_SIZE_EXCEEDED,t),this.eventEmitter.emit(Z.ERROR,t);break;case`insufficient_audio_activity`:this.eventEmitter.emit(Z.INSUFFICIENT_AUDIO_ACTIVITY,t),this.eventEmitter.emit(Z.ERROR,t);break;case`error`:this.eventEmitter.emit(Z.ERROR,t);break;default:console.warn(`Unknown message type:`,t)}}catch(t){console.error(`Failed to parse WebSocket message:`,t,e.data),this.eventEmitter.emit(Z.ERROR,Error(`Failed to parse message: ${t}`))}}),this.websocket.addEventListener(`error`,e=>{console.error(`WebSocket error:`,e),this.eventEmitter.emit(Z.ERROR,e)}),this.websocket.addEventListener(`close`,e=>{if(console.log(`WebSocket closed: code=${e.code}, reason="${e.reason}", wasClean=${e.wasClean}`),!e.wasClean||e.code!==1e3&&e.code!==1005){let t=`WebSocket closed unexpectedly: ${e.code} - ${e.reason||`No reason provided`}`;console.error(t),this.eventEmitter.emit(Z.ERROR,Error(t))}this.eventEmitter.emit(Z.CLOSE,e)})}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}send(e){var t;if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw Error(`WebSocket is not connected`);let n={message_type:`input_audio_chunk`,audio_base_64:e.audioBase64,commit:(t=e.commit)!=null&&t,sample_rate:e.sampleRate??this.currentSampleRate,previous_text:e.previousText};this.websocket.send(JSON.stringify(n))}commit(){if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw Error(`WebSocket is not connected`);this.websocket.send(JSON.stringify({message_type:`input_audio_chunk`,audio_base_64:``,commit:!0,sample_rate:this.currentSampleRate}))}close(){this._audioCleanup&&this._audioCleanup(),this.websocket&&this.websocket.close(1e3,`User ended session`)}},YT=FT(`scribeAudioProcessor`,`/*
279
279
  * Scribe Audio Processor for converting microphone audio to PCM16 format
280
280
  * USED BY @elevenlabs/client
281
281
  */
@@ -327,18 +327,18 @@ class ScribeAudioProcessor extends AudioWorkletProcessor {
327
327
 
328
328
  registerProcessor("scribeAudioProcessor", ScribeAudioProcessor);
329
329
 
330
- `),KT,qT;(function(e){e.PCM_8000=`pcm_8000`,e.PCM_16000=`pcm_16000`,e.PCM_22050=`pcm_22050`,e.PCM_24000=`pcm_24000`,e.PCM_44100=`pcm_44100`,e.PCM_48000=`pcm_48000`,e.ULAW_8000=`ulaw_8000`})(KT||={}),function(e){e.MANUAL=`manual`,e.VAD=`vad`}(qT||={});var JT=class e{static getWebSocketUri(t=e.DEFAULT_BASE_URI){return`${t}/v1/speech-to-text/realtime`}static buildWebSocketUri(t){let n=e.getWebSocketUri(t.baseUri),r=new URLSearchParams;if(r.append(`model_id`,t.modelId),r.append(`token`,t.token),t.commitStrategy!==void 0&&r.append(`commit_strategy`,t.commitStrategy),t.audioFormat!==void 0&&r.append(`audio_format`,t.audioFormat),t.vadSilenceThresholdSecs!==void 0){if(t.vadSilenceThresholdSecs<=.3||t.vadSilenceThresholdSecs>3)throw Error(`vadSilenceThresholdSecs must be between 0.3 and 3.0`);r.append(`vad_silence_threshold_secs`,t.vadSilenceThresholdSecs.toString())}if(t.vadThreshold!==void 0){if(t.vadThreshold<.1||t.vadThreshold>.9)throw Error(`vadThreshold must be between 0.1 and 0.9`);r.append(`vad_threshold`,t.vadThreshold.toString())}if(t.minSpeechDurationMs!==void 0){if(t.minSpeechDurationMs<=50||t.minSpeechDurationMs>2e3)throw Error(`minSpeechDurationMs must be between 50 and 2000`);r.append(`min_speech_duration_ms`,t.minSpeechDurationMs.toString())}if(t.minSilenceDurationMs!==void 0){if(t.minSilenceDurationMs<=50||t.minSilenceDurationMs>2e3)throw Error(`minSilenceDurationMs must be between 50 and 2000`);r.append(`min_silence_duration_ms`,t.minSilenceDurationMs.toString())}t.languageCode!==void 0&&r.append(`language_code`,t.languageCode),t.includeTimestamps!==void 0&&r.append(`include_timestamps`,t.includeTimestamps?`true`:`false`);let i=r.toString();return i?`${n}?${i}`:n}static connect(t){if(!t.modelId)throw Error(`modelId is required`);let n=new WT(`microphone`in t&&t.microphone?16e3:t.sampleRate),r=e.buildWebSocketUri(t),i=new WebSocket(r);return`microphone`in t&&t.microphone&&i.addEventListener(`open`,()=>{e.streamFromMicrophone(t,n)}),n.setWebSocket(i),n}static async streamFromMicrophone(e,t){try{var n,r,i;let a=await navigator.mediaDevices.getUserMedia({audio:{deviceId:e.microphone?.deviceId,echoCancellation:(n=e.microphone?.echoCancellation)==null||n,noiseSuppression:(r=e.microphone?.noiseSuppression)==null||r,autoGainControl:(i=e.microphone?.autoGainControl)==null||i,channelCount:e.microphone?.channelCount??1,sampleRate:{ideal:16e3}}}),o=new AudioContext({sampleRate:16e3});await GT(o.audioWorklet);let s=o.createMediaStreamSource(a),c=new AudioWorkletNode(o,`scribeAudioProcessor`);c.port.onmessage=e=>{let{audioData:n}=e.data,r=new Uint8Array(n),i=``;for(let e=0;e<r.length;e++)i+=String.fromCharCode(r[e]);let a=btoa(i);t.send({audioBase64:a})},s.connect(c),o.state===`suspended`&&await o.resume(),t._audioCleanup=()=>{a.getTracks().forEach(e=>{e.stop()}),s.disconnect(),c.disconnect(),o.close()}}catch(e){throw console.error(`Failed to start microphone streaming:`,e),e}}};JT.DEFAULT_BASE_URI=`wss://api.elevenlabs.io`;var YT=class extends bT{static startSession(e){return e.textOnly?LT.startSession(e):HT.startSession(e)}},XT=({size:e=20})=>(0,f.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`path`,{d:`M10.68 13.31a16 16 0 003.41 2.6l1.27-1.27a2 2 0 012.11-.45 12.84 12.84 0 002.81.7 2 2 0 011.72 2v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07A19.42 19.42 0 013.07 8.62 19.79 19.79 0 01.1 2 2 2 0 012.11 0h3a2 2 0 012 1.72c.127.96.361 1.903.7 2.81a2 2 0 01-.45 2.11L6.18 7.84`}),(0,f.jsx)(`line`,{x1:`23`,y1:`1`,x2:`1`,y2:`23`})]}),ZT=()=>(0,f.jsxs)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`line`,{x1:`12`,y1:`19`,x2:`12`,y2:`5`}),(0,f.jsx)(`polyline`,{points:`5 12 12 5 19 12`})]}),QT=()=>(0,f.jsxs)(`svg`,{width:`14`,height:`14`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`polyline`,{points:`9 17 4 12 9 7`}),(0,f.jsx)(`path`,{d:`M20 18v-2a4 4 0 00-4-4H4`})]}),$T=()=>(0,f.jsx)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,f.jsx)(`path`,{d:`M22 16.92v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07 19.42 19.42 0 01-6.12-6.11A19.79 19.79 0 012 4.11 2 2 0 014.11 2h3a2 2 0 012 1.72c.13.96.37 1.91.71 2.81a2 2 0 01-.45 2.11L8.09 9.91a16 16 0 006 6l1.27-1.27a2 2 0 012.11-.45c.9.34 1.85.58 2.81.71A2 2 0 0122 16.92z`})}),eE=({className:e=``})=>(0,f.jsxs)(`svg`,{className:e,width:`14`,height:`14`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`circle`,{cx:`12`,cy:`12`,r:`10`}),(0,f.jsx)(`line`,{x1:`12`,y1:`8`,x2:`12`,y2:`12`}),(0,f.jsx)(`line`,{x1:`12`,y1:`16`,x2:`12.01`,y2:`16`})]}),tE=({size:e=14})=>(0,f.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`path`,{d:`M12 8V4H8`}),(0,f.jsx)(`rect`,{width:`16`,height:`12`,x:`4`,y:`8`,rx:`2`}),(0,f.jsx)(`path`,{d:`M2 14h2`}),(0,f.jsx)(`path`,{d:`M20 14h2`}),(0,f.jsx)(`path`,{d:`M15 13v2`}),(0,f.jsx)(`path`,{d:`M9 13v2`})]}),nE=({size:e=20,strokeWidth:t=2,color:n=`currentColor`})=>(0,f.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:n,strokeWidth:t,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`line`,{x1:`12`,y1:`5`,x2:`12`,y2:`19`}),(0,f.jsx)(`line`,{x1:`5`,y1:`12`,x2:`19`,y2:`12`})]}),rE=(e=``)=>String(e).replace(/<[^>]+>/g,``).replace(/\s+/g,` `).trim(),iE=(e=``)=>String(e).replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&#39;`);function aE(e){let t=String(e||``).trim();if(!t)return t;let n=/^<p>\s*<strong>([\s\S]*?)<\/strong>\s*<\/p>$/i.exec(t);if(n&&!/<\/?strong\b/i.test(n[1]))return`<p>${n[1]}</p>`;let r=/^<strong>([\s\S]*?)<\/strong>$/i.exec(t);if(r&&!/<\/?strong\b/i.test(r[1])){let e=r[1].trim();return/^<(?:p|ul|ol)\b/i.test(e)?e:`<p>${e}</p>`}return e}var oE=(e=``)=>{let t=String(e||``).trim();if(!t)return``;if(/<(p|br|ul|ol|li|strong|em|a)\b/i.test(t))return aE(t);let n=t.replace(/\r\n/g,`
330
+ `),XT,ZT;(function(e){e.PCM_8000=`pcm_8000`,e.PCM_16000=`pcm_16000`,e.PCM_22050=`pcm_22050`,e.PCM_24000=`pcm_24000`,e.PCM_44100=`pcm_44100`,e.PCM_48000=`pcm_48000`,e.ULAW_8000=`ulaw_8000`})(XT||={}),function(e){e.MANUAL=`manual`,e.VAD=`vad`}(ZT||={});var QT=class e{static getWebSocketUri(t=e.DEFAULT_BASE_URI){return`${t}/v1/speech-to-text/realtime`}static buildWebSocketUri(t){let n=e.getWebSocketUri(t.baseUri),r=new URLSearchParams;if(r.append(`model_id`,t.modelId),r.append(`token`,t.token),t.commitStrategy!==void 0&&r.append(`commit_strategy`,t.commitStrategy),t.audioFormat!==void 0&&r.append(`audio_format`,t.audioFormat),t.vadSilenceThresholdSecs!==void 0){if(t.vadSilenceThresholdSecs<=.3||t.vadSilenceThresholdSecs>3)throw Error(`vadSilenceThresholdSecs must be between 0.3 and 3.0`);r.append(`vad_silence_threshold_secs`,t.vadSilenceThresholdSecs.toString())}if(t.vadThreshold!==void 0){if(t.vadThreshold<.1||t.vadThreshold>.9)throw Error(`vadThreshold must be between 0.1 and 0.9`);r.append(`vad_threshold`,t.vadThreshold.toString())}if(t.minSpeechDurationMs!==void 0){if(t.minSpeechDurationMs<=50||t.minSpeechDurationMs>2e3)throw Error(`minSpeechDurationMs must be between 50 and 2000`);r.append(`min_speech_duration_ms`,t.minSpeechDurationMs.toString())}if(t.minSilenceDurationMs!==void 0){if(t.minSilenceDurationMs<=50||t.minSilenceDurationMs>2e3)throw Error(`minSilenceDurationMs must be between 50 and 2000`);r.append(`min_silence_duration_ms`,t.minSilenceDurationMs.toString())}t.languageCode!==void 0&&r.append(`language_code`,t.languageCode),t.includeTimestamps!==void 0&&r.append(`include_timestamps`,t.includeTimestamps?`true`:`false`);let i=r.toString();return i?`${n}?${i}`:n}static connect(t){if(!t.modelId)throw Error(`modelId is required`);let n=new JT(`microphone`in t&&t.microphone?16e3:t.sampleRate),r=e.buildWebSocketUri(t),i=new WebSocket(r);return`microphone`in t&&t.microphone&&i.addEventListener(`open`,()=>{e.streamFromMicrophone(t,n)}),n.setWebSocket(i),n}static async streamFromMicrophone(e,t){try{var n,r,i;let a=await navigator.mediaDevices.getUserMedia({audio:{deviceId:e.microphone?.deviceId,echoCancellation:(n=e.microphone?.echoCancellation)==null||n,noiseSuppression:(r=e.microphone?.noiseSuppression)==null||r,autoGainControl:(i=e.microphone?.autoGainControl)==null||i,channelCount:e.microphone?.channelCount??1,sampleRate:{ideal:16e3}}}),o=new AudioContext({sampleRate:16e3});await YT(o.audioWorklet);let s=o.createMediaStreamSource(a),c=new AudioWorkletNode(o,`scribeAudioProcessor`);c.port.onmessage=e=>{let{audioData:n}=e.data,r=new Uint8Array(n),i=``;for(let e=0;e<r.length;e++)i+=String.fromCharCode(r[e]);let a=btoa(i);t.send({audioBase64:a})},s.connect(c),o.state===`suspended`&&await o.resume(),t._audioCleanup=()=>{a.getTracks().forEach(e=>{e.stop()}),s.disconnect(),c.disconnect(),o.close()}}catch(e){throw console.error(`Failed to start microphone streaming:`,e),e}}};QT.DEFAULT_BASE_URI=`wss://api.elevenlabs.io`;var $T=class extends wT{static startSession(e){return e.textOnly?VT.startSession(e):KT.startSession(e)}},eE=({size:e=20})=>(0,f.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`path`,{d:`M10.68 13.31a16 16 0 003.41 2.6l1.27-1.27a2 2 0 012.11-.45 12.84 12.84 0 002.81.7 2 2 0 011.72 2v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07A19.42 19.42 0 013.07 8.62 19.79 19.79 0 01.1 2 2 2 0 012.11 0h3a2 2 0 012 1.72c.127.96.361 1.903.7 2.81a2 2 0 01-.45 2.11L6.18 7.84`}),(0,f.jsx)(`line`,{x1:`23`,y1:`1`,x2:`1`,y2:`23`})]}),tE=()=>(0,f.jsxs)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`line`,{x1:`12`,y1:`19`,x2:`12`,y2:`5`}),(0,f.jsx)(`polyline`,{points:`5 12 12 5 19 12`})]}),nE=()=>(0,f.jsxs)(`svg`,{width:`14`,height:`14`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`polyline`,{points:`9 17 4 12 9 7`}),(0,f.jsx)(`path`,{d:`M20 18v-2a4 4 0 00-4-4H4`})]}),rE=()=>(0,f.jsx)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,f.jsx)(`path`,{d:`M22 16.92v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07 19.42 19.42 0 01-6.12-6.11A19.79 19.79 0 012 4.11 2 2 0 014.11 2h3a2 2 0 012 1.72c.13.96.37 1.91.71 2.81a2 2 0 01-.45 2.11L8.09 9.91a16 16 0 006 6l1.27-1.27a2 2 0 012.11-.45c.9.34 1.85.58 2.81.71A2 2 0 0122 16.92z`})}),iE=({className:e=``})=>(0,f.jsxs)(`svg`,{className:e,width:`14`,height:`14`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`circle`,{cx:`12`,cy:`12`,r:`10`}),(0,f.jsx)(`line`,{x1:`12`,y1:`8`,x2:`12`,y2:`12`}),(0,f.jsx)(`line`,{x1:`12`,y1:`16`,x2:`12.01`,y2:`16`})]}),aE=({size:e=14})=>(0,f.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`path`,{d:`M12 8V4H8`}),(0,f.jsx)(`rect`,{width:`16`,height:`12`,x:`4`,y:`8`,rx:`2`}),(0,f.jsx)(`path`,{d:`M2 14h2`}),(0,f.jsx)(`path`,{d:`M20 14h2`}),(0,f.jsx)(`path`,{d:`M15 13v2`}),(0,f.jsx)(`path`,{d:`M9 13v2`})]}),oE=({size:e=20,strokeWidth:t=2,color:n=`currentColor`})=>(0,f.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:n,strokeWidth:t,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`line`,{x1:`12`,y1:`5`,x2:`12`,y2:`19`}),(0,f.jsx)(`line`,{x1:`5`,y1:`12`,x2:`19`,y2:`12`})]}),sE=(e=``)=>String(e).replace(/<[^>]+>/g,``).replace(/\s+/g,` `).trim(),cE=(e=``)=>String(e).replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&#39;`);function lE(e){let t=String(e||``).trim();if(!t)return t;let n=/^<p>\s*<strong>([\s\S]*?)<\/strong>\s*<\/p>$/i.exec(t);if(n&&!/<\/?strong\b/i.test(n[1]))return`<p>${n[1]}</p>`;let r=/^<strong>([\s\S]*?)<\/strong>$/i.exec(t);if(r&&!/<\/?strong\b/i.test(r[1])){let e=r[1].trim();return/^<(?:p|ul|ol)\b/i.test(e)?e:`<p>${e}</p>`}return e}var uE=(e=``)=>{let t=String(e||``).trim();if(!t)return``;if(/<(p|br|ul|ol|li|strong|em|a)\b/i.test(t))return lE(t);let n=t.replace(/\r\n/g,`
331
331
  `).replace(/\n{3,}/g,`
332
332
 
333
- `).split(/\n\s*\n/).map(e=>e.trim()).filter(Boolean),r=e=>iE(e).replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,`<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>`).replace(/\*\*([^*]+)\*\*/g,`<strong>$1</strong>`).replace(/\*([^*\n]+)\*/g,`<em>$1</em>`);return aE(n.map(e=>{let t=e.split(`
334
- `).map(e=>e.trim()).filter(Boolean),n=t.filter(e=>/^[-*]\s+/.test(e));if(n.length>=2&&n.length===t.length)return`<ul>${n.map(e=>`<li>${r(e.replace(/^[-*]\s+/,``))}</li>`).join(``)}</ul>`;let i=e.split(/\s+(?=[-*]\s+\*\*?)/).map(e=>e.trim()).filter(Boolean);return i.length>=2&&i.every(e=>/^[-*]\s+/.test(e))?`<ul>${i.map(e=>`<li>${r(e.replace(/^[-*]\s+/,``))}</li>`).join(``)}</ul>`:`<p>${r(e).replace(/\n/g,`<br />`)}</p>`}).join(``))};function sE(e){if(!e||typeof e!=`string`)return`?`;let t=e.trim();if(!t)return`?`;let n=t.split(/\s+/).filter(Boolean);return n.length>=2?`${n[0][0]}${n[n.length-1][0]}`.toUpperCase():t.slice(0,2).toUpperCase()}function cE({src:e,name:t,imgStyle:n,initialsSpanStyle:r}){let[i,a]=(0,d.useState)(!1),o=typeof e==`string`?e.trim():``;return(0,d.useEffect)(()=>{a(!1)},[o]),o&&!i?(0,f.jsx)(`img`,{src:o,alt:``,onError:()=>a(!0),style:n}):(0,f.jsx)(`span`,{style:r,children:sE(t)})}function lE({chatHistory:e,isAiTyping:t,isAgentTyping:n,setReplyContext:r,TypingDots:i,primaryColor:a=`#3B82F6`,agentHeadshot:o=null,agentDisplayName:s=`Agent`,botAvatarNode:c=null}){let l=(0,d.useRef)(null),u=e=>{if(!e)return`just now`;let t=new Date,n=new Date(e),r=Math.max(0,Math.floor((t-n)/1e3));if(r<60)return`just now`;let i=Math.floor(r/60);if(i<60)return`${i} min${i>1?`s`:``} ago`;let a=Math.floor(i/60);if(a<24)return`${a} hr${a>1?`s`:``} ago`;let o=Math.floor(a/24);return`${o} day${o>1?`s`:``} ago`};return(0,d.useEffect)(()=>{l.current&&l.current.scrollIntoView({behavior:`smooth`})},[e.length,t,n]),(0,f.jsxs)(`div`,{style:{flex:1,overflowY:`auto`,padding:`10px 16px 20px`,display:`flex`,flexDirection:`column`,background:`transparent`},children:[e.map(e=>{let t=e.sender===`system`,n=e.sender===`user`,i=e.sender===`ai`||e.sender===`bot`,l=e.sender===`agent`,d=e.isPending,p=e.agent_name||e.agentName||e.metadata?.agentName||s,m=typeof e.sender_headshot==`string`&&e.sender_headshot.trim()||typeof o==`string`&&o.trim()||null,h=rE(e.replyToContent||e.replyContext?.message||``),g=e.replyToSender===`user`?`You`:e.replyToSender===`agent`?`Agent`:e.replyToSender===`ai`||e.replyToSender===`bot`?`AI Assistant`:`Message`;return t?(0,f.jsx)(`div`,{style:{display:`flex`,justifyContent:`center`,margin:`8px 0`},children:(0,f.jsx)(`div`,{style:{padding:`6px 12px`,borderRadius:`9999px`,background:`#f3f4f6`,color:`#6b7280`,fontSize:`12px`,fontWeight:500},children:e.message})},e.id):(0,f.jsxs)(`div`,{style:{display:`flex`,justifyContent:n?`flex-end`:`flex-start`,alignItems:`flex-start`,marginBottom:`16px`,gap:`8px`,flexDirection:`row`},children:[!n&&(i||l)&&(0,f.jsx)(`div`,{style:{width:`32px`,height:`32px`,flexShrink:0,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`50%`,background:l?`#f3f4f6`:c&&i?`transparent`:`var(--flowengage-primary)`,color:l?a:`#fff`,boxShadow:l?`0 2px 8px rgba(0,0,0,0.06)`:c&&i?`none`:`0 8px 20px rgba(59,130,246,0.24)`,overflow:`hidden`,border:l?`1px solid ${a}22`:`none`,fontSize:`12px`,fontWeight:800,marginTop:!d&&(i||l)?`22px`:`0px`},children:i?c||(0,f.jsx)(tE,{size:16}):(0,f.jsx)(cE,{src:m||``,name:p,imgStyle:{width:`100%`,height:`100%`,objectFit:`cover`},initialsSpanStyle:{lineHeight:1}})}),(0,f.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,alignItems:n?`flex-end`:`flex-start`,maxWidth:`75%`,minWidth:0},children:[!d&&!n&&(i||l)&&(0,f.jsxs)(`button`,{type:`button`,onClick:()=>r(e),style:{opacity:1,marginBottom:`4px`,display:`flex`,alignItems:`center`,gap:`4px`,fontSize:`11px`,color:`#9ca3af`,background:`transparent`,border:0,cursor:`pointer`,padding:0,marginLeft:`2px`},onMouseEnter:e=>{e.currentTarget.style.color=`#4b5563`},onMouseLeave:e=>{e.currentTarget.style.color=`#9ca3af`},children:[(0,f.jsx)(QT,{}),`Reply`]}),(0,f.jsxs)(`div`,{style:{padding:`12px 16px`,borderRadius:n?`20px 6px 20px 20px`:`6px 20px 20px 20px`,lineHeight:1.5,boxShadow:`0 2px 8px rgba(0,0,0,0.06)`,background:n?`var(--flowengage-primary)`:`rgba(255,255,255,0.92)`,color:n?`#fff`:`#111827`,fontSize:`14px`,opacity:d?.55:1,transition:`opacity 0.3s ease`,wordBreak:`break-word`,width:`fit-content`},children:[h&&(0,f.jsxs)(`div`,{style:{marginBottom:`8px`,borderRadius:`14px`,borderLeft:n?`2px solid rgba(255,255,255,0.8)`:`2px solid var(--flowengage-primary)`,padding:`8px 12px`,fontSize:`12px`,background:n?`rgba(255,255,255,0.15)`:`#f9fafb`,color:n?`rgba(255,255,255,0.9)`:`#6b7280`},children:[(0,f.jsx)(`div`,{style:{marginBottom:`2px`,fontWeight:600},children:g}),(0,f.jsx)(`div`,{style:{display:`-webkit-box`,WebkitLineClamp:2,WebkitBoxOrient:`vertical`,overflow:`hidden`},children:h})]}),i?(0,f.jsx)(`div`,{className:`flowengage-message-content fe-bot-message`,dangerouslySetInnerHTML:{__html:oE(e.message)}}):(0,f.jsx)(`div`,{style:{whiteSpace:n||l?`normal`:`pre-wrap`},children:e.message}),d&&(0,f.jsx)(`span`,{style:{fontSize:`10px`,marginLeft:`6px`,opacity:.7},children:`sending…`})]}),(0,f.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`4px`,marginTop:`4px`,padding:`0 4px`,alignSelf:n?`flex-end`:`flex-start`},children:[(0,f.jsx)(`span`,{style:{fontSize:`10px`,color:`#9ca3af`,fontWeight:500},children:u(e.timestamp||e.createdAt)}),(0,f.jsx)(`span`,{style:{fontSize:`10px`,fontWeight:700,color:n?`var(--flowengage-primary)`:`#9ca3af`},children:d?`○`:`✓`})]})]})]},e.id)}),t&&(0,f.jsxs)(`div`,{style:{marginBottom:`16px`,display:`flex`,alignItems:`flex-start`,gap:`8px`},children:[(0,f.jsx)(`div`,{style:{width:`32px`,height:`32px`,flexShrink:0,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`50%`,background:c?`transparent`:`var(--flowengage-primary)`,color:`#fff`,boxShadow:c?`none`:`0 8px 20px rgba(59,130,246,0.24)`,border:`none`,overflow:`hidden`},children:c||(0,f.jsx)(tE,{size:16})}),(0,f.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`5px`,borderRadius:`18px 18px 18px 6px`,background:`#fff`,padding:`12px 16px`,color:`#111827`,boxShadow:`0 2px 6px rgba(0,0,0,0.04)`},children:[0,1,2].map(e=>(0,f.jsx)(`span`,{style:{width:`7px`,height:`7px`,borderRadius:`50%`,background:`#9ca3af`,animation:`fe-dot-bounce 1.2s ease-in-out ${e*.2}s infinite`,display:`inline-block`}},e))})]}),n&&d.default.createElement(i),(0,f.jsx)(`div`,{ref:l})]})}function uE({input:e,setInput:t,onSubmit:n,isConversationEnded:r,callUiActive:i,handleToggleVoice:a,activeScreen:o,inputDisabled:s,replyContext:c,clearReplyContext:l,requiresEmail:u,emailInput:d,setEmailInput:p,emailError:m,showVoiceToggle:h=!1,voiceEnabled:g=!0,inputPlaceholder:_=`Type your message`}){let v=c?.sender===`user`?`You`:c?.sender===`agent`?`Agent`:`AI Assistant`,y=u?!!d?.trim():!!e?.trim(),b=s||!y,x=!u&&g&&h,S=u;return(0,f.jsxs)(`div`,{style:{padding:`0 20px`,background:`transparent`},children:[r&&(0,f.jsx)(`div`,{style:{marginBottom:`8px`,padding:`8px 16px`,borderRadius:`12px`,background:`#f3f4f6`,color:`#6b7280`,fontSize:`12px`,textAlign:`center`,fontWeight:500},children:`This conversation has ended.`}),c&&(0,f.jsxs)(`div`,{style:{marginBottom:`8px`,display:`flex`,alignItems:`flex-start`,justifyContent:`space-between`,gap:`12px`,borderRadius:`16px`,border:`1px solid rgba(0,0,0,0.05)`,background:`#fff`,padding:`12px 16px`,boxShadow:`0 8px 24px rgba(0,0,0,0.05)`},children:[(0,f.jsxs)(`div`,{style:{minWidth:0,flex:1,borderLeft:`2px solid var(--flowengage-primary)`,paddingLeft:`12px`},children:[(0,f.jsxs)(`div`,{style:{fontSize:`12px`,fontWeight:600,color:`var(--flowengage-primary)`},children:[`Replying to `,v]}),(0,f.jsx)(`div`,{style:{overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`,fontSize:`12px`,color:`#6b7280`},children:c.replyToContent||c.message})]}),(0,f.jsx)(`button`,{type:`button`,style:{width:`28px`,height:`28px`,borderRadius:`9999px`,border:0,background:`#f3f4f6`,color:`#6b7280`,transition:`color 0.2s ease, background 0.2s ease`,cursor:`pointer`},onClick:l,"aria-label":`Cancel reply`,onMouseEnter:e=>{e.currentTarget.style.background=`#e5e7eb`,e.currentTarget.style.color=`#374151`},onMouseLeave:e=>{e.currentTarget.style.background=`#f3f4f6`,e.currentTarget.style.color=`#6b7280`},children:`×`})]}),u&&(0,f.jsx)(`div`,{style:{marginBottom:`14px`,padding:`0 8px`},children:(0,f.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,justifyContent:`center`,gap:`8px`,color:`#111827`,fontSize:`14px`,fontWeight:500,textAlign:`center`},children:[(0,f.jsx)(`span`,{style:{display:`inline-flex`,width:`22px`,height:`22px`,borderRadius:`9999px`,alignItems:`center`,justifyContent:`center`,background:`rgba(59,130,246,0.08)`,color:`var(--flowengage-primary)`},children:(0,f.jsx)(tE,{size:13})}),(0,f.jsx)(`span`,{children:`Please provide your email address so we can help you.`})]})}),(0,f.jsxs)(`form`,{style:{display:`flex`,alignItems:`center`,gap:`12px`,padding:`8px`,border:`1px solid rgba(0,0,0,0.06)`,borderRadius:`9999px`,background:`#fff`,boxShadow:`0 4px 14px rgba(0,0,0,0.04)`,opacity:r?.5:1},onSubmit:n,children:[x?(0,f.jsx)(`button`,{type:`button`,style:{width:`36px`,height:`36px`,borderRadius:`9999px`,background:`#f3f4f8`,color:`var(--flowengage-primary)`,display:`flex`,alignItems:`center`,justifyContent:`center`,transition:`background 0.2s ease, opacity 0.2s ease`,border:0,cursor:`pointer`,flexShrink:0},onClick:a,title:`Voice assistant`,"aria-label":`Voice assistant`,disabled:r||i,onMouseEnter:e=>{e.currentTarget.style.opacity=`0.8`},onMouseLeave:e=>{e.currentTarget.style.opacity=`1`},children:(0,f.jsx)(nE,{size:18,color:`currentColor`})}):S?(0,f.jsx)(`span`,{style:{width:`32px`,flexShrink:0},"aria-hidden":!0}):null,(0,f.jsx)(`input`,{className:`flowengage-chat-text-input`,style:{flex:1,minWidth:0,border:`none`,fontFamily:`inherit`,fontSize:`14px`,outline:`none`,padding:`10px 8px 10px 18px`,color:`#111827`,background:`transparent`},value:u?d:e,onChange:e=>{if(u){p(e.target.value);return}t(e.target.value)},placeholder:r?`Conversation ended`:u?`Your email address`:o===`agent`?`Message the agent…`:_,disabled:s,type:u?`email`:`text`,autoComplete:u?`email`:`off`}),(0,f.jsx)(`button`,{type:`submit`,style:{width:`36px`,height:`36px`,borderRadius:`9999px`,background:`var(--flowengage-primary)`,color:`#fff`,border:`none`,display:`flex`,alignItems:`center`,justifyContent:`center`,transition:`opacity 0.2s ease`,cursor:b?`not-allowed`:`pointer`,opacity:b?.45:1},disabled:b,onMouseEnter:e=>{b||(e.currentTarget.style.opacity=`0.85`)},onMouseLeave:e=>{e.currentTarget.style.opacity=`1`},children:(0,f.jsx)(ZT,{})})]}),u&&m&&(0,f.jsx)(`div`,{style:{padding:`8px 16px 0`,fontSize:`12px`,fontWeight:500,color:`#f43f5e`},children:m})]})}var dE=({muted:e=!1})=>(0,f.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`path`,{d:`M12 1a4 4 0 014 4v6a4 4 0 01-6.83 2.83`}),(0,f.jsx)(`path`,{d:`M19 10a7 7 0 01-1.62 4.49M5 10a7 7 0 008.79 6.77`}),(0,f.jsx)(`path`,{d:`M12 19v4M8 23h8`}),e&&(0,f.jsx)(`line`,{x1:`2`,y1:`2`,x2:`22`,y2:`22`})]}),fE=({variant:e,onClick:t,children:n,icon:r,compact:i=!1,iconOnly:a=!1,active:o=!1,ariaLabel:s})=>(0,f.jsxs)(`button`,{type:`button`,className:[`flowengage-call-btn`,`flowengage-call-btn-${e}`,i?`compact`:``,a?`icon-only`:``,o?`active`:``].filter(Boolean).join(` `),onClick:t,"aria-label":s||n,title:s||n,children:[r,!a&&(0,f.jsx)(`span`,{children:n})]});function pE({webRTCError:e,micError:t,setMicError:n,dismissCallError:r,incomingCall:i,rejectCall:a,acceptCall:o,activeCallId:s,callConnectionState:c,formatCallDuration:l,callDurationSeconds:u,endWebRTCCall:p,isCallMuted:m,toggleCallMute:h,isAIVoiceActive:g,currentCallAgentName:_,isRateLimited:v,rateLimitMessage:y}){let b=(0,d.useRef)(null),x=(0,d.useCallback)(()=>{if(!b.current)return;let{audioContext:e,oscillator:t,interval:n,toneTimeout:r}=b.current;window.clearInterval(n),window.clearTimeout(r);try{t.stop()}catch{}try{e.close()}catch{}b.current=null},[]),S=(0,d.useCallback)(()=>{if(b.current||typeof window>`u`)return;let e=window.AudioContext||window.webkitAudioContext||null;if(e)try{let t=new e,n=t.createOscillator(),r=t.createGain();n.connect(r),r.connect(t.destination),n.frequency.value=0,n.type=`sine`,r.gain.value=.3;let i=()=>{b.current&&(window.clearTimeout(b.current.toneTimeout),n.frequency.value=440,b.current.toneTimeout=window.setTimeout(()=>{n.frequency.value=0},400))};t.state===`suspended`&&t.resume().catch(e=>{console.warn(`[FlowEngage] ringtone autoplay blocked`,e)}),n.start(),b.current={audioContext:t,oscillator:n,interval:null,toneTimeout:null},i(),b.current.interval=window.setInterval(i,1e3)}catch(e){console.warn(`[FlowEngage] failed to start ringtone`,e)}},[]);(0,d.useEffect)(()=>{if(i){S();return}x()},[i,S,x]),(0,d.useEffect)(()=>()=>x(),[x]);let ee=g?`header-mode`:`bottom-mode`,te=!!(i||s),C=i?`incoming`:c===`connected`?`connected`:`connecting`,ne=(0,d.useMemo)(()=>C===`incoming`?`Incoming Call`:C===`connected`?`Voice Call Active`:`Connecting Call`,[C]),re=(0,d.useMemo)(()=>C===`incoming`?`${_} wants to join a voice call`:C===`connected`?`You are connected to ${_} from this conversation.`:`Please wait while ${_}'s voice connection finishes setting up.`,[_,C]);return(0,f.jsxs)(f.Fragment,{children:[(e||t)&&(0,f.jsxs)(`div`,{style:{margin:`0 20px 10px`,padding:`12px 16px`,borderRadius:`12px`,background:`#fef2f2`,border:`1px solid #fee2e2`,display:`flex`,alignItems:`flex-start`,gap:`10px`},children:[(0,f.jsx)(eE,{className:``}),(0,f.jsx)(`span`,{style:{fontSize:`12px`,color:`#b91c1c`,lineHeight:1.5,flex:1},children:e||t}),(0,f.jsx)(`button`,{style:{flexShrink:0,background:`transparent`,border:0,color:`#f87171`,cursor:`pointer`,fontSize:`18px`,lineHeight:1},onClick:()=>{n(null),r()},onMouseEnter:e=>{e.currentTarget.style.color=`#dc2626`},onMouseLeave:e=>{e.currentTarget.style.color=`#f87171`},children:`×`})]}),te&&(0,f.jsx)(`div`,{className:`incoming-call-overlay ${ee}`,children:(0,f.jsx)(`div`,{className:[`incoming-call-container`,C===`connected`?`connected-layout`:``].filter(Boolean).join(` `),children:C===`connected`?(0,f.jsxs)(f.Fragment,{children:[(0,f.jsxs)(`div`,{className:`call-connected-top`,children:[(0,f.jsxs)(`div`,{className:`call-connected-identity`,children:[(0,f.jsx)(`div`,{className:`call-icon-wrapper ${C}`,children:(0,f.jsx)(XT,{size:20})}),(0,f.jsxs)(`div`,{className:`call-info-group`,children:[(0,f.jsx)(`h3`,{className:`call-title`,children:ne}),(0,f.jsx)(`p`,{className:`call-subtitle`,children:re})]})]}),(0,f.jsx)(`div`,{className:`call-timer`,children:l(u)})]}),(0,f.jsxs)(`div`,{className:`call-actions connected`,children:[(0,f.jsx)(fE,{variant:`mute`,onClick:h,compact:g,active:m,icon:(0,f.jsx)(dE,{muted:m}),children:m?`Unmute`:`Mute`}),(0,f.jsx)(fE,{variant:`end`,onClick:p,compact:g,icon:(0,f.jsx)(XT,{size:14}),children:`End`})]})]}):(0,f.jsxs)(f.Fragment,{children:[(0,f.jsxs)(`div`,{className:`call-icon-wrapper ${C}`,children:[(0,f.jsx)($T,{}),C===`incoming`&&(0,f.jsx)(`div`,{className:`call-pulse-animation`}),C===`connecting`&&(0,f.jsx)(`div`,{className:`call-connecting-animation`})]}),(0,f.jsxs)(`div`,{className:`call-info-group`,children:[(0,f.jsx)(`h3`,{className:`call-title`,children:ne}),(0,f.jsx)(`p`,{className:`call-subtitle`,children:re})]}),(0,f.jsx)(`div`,{className:`call-actions`,children:C===`incoming`&&(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(fE,{variant:`reject`,onClick:async()=>{x(),await a()},iconOnly:!0,icon:(0,f.jsx)(XT,{size:14}),ariaLabel:`Decline call`,children:`Decline`}),(0,f.jsx)(fE,{variant:`accept`,onClick:async()=>{x(),await o()},iconOnly:!0,icon:(0,f.jsx)($T,{}),ariaLabel:`Accept call`,children:`Accept`})]})})]})})}),v&&(0,f.jsx)(`div`,{style:{margin:`0 20px 10px`,padding:`12px 16px`,fontSize:`13px`,borderRadius:`12px`,background:`#fee2e2`,color:`#991b1b`},children:y})]})}var mE=[`#135bd8`,`#ef334b`,`#ffbd2e`];function hE(e){return!Array.isArray(e)||e.length===0?mE:e.length===1?[e[0],e[0],e[0]]:e.length===2?[e[0],e[1],e[0]]:[e[0],e[1],e[2]]}var gE={idle:3,listening:.75,speaking:1.4,muted:.75,error:.08};function _E(e){if(!e||typeof e!=`string`)return[0,0,0];let t=e.replace(`#`,``),n=t.length===3?t.split(``).map(e=>e+e).join(``):t;return[parseInt(n.slice(0,2),16)/255,parseInt(n.slice(2,4),16)/255,parseInt(n.slice(4,6),16)/255]}function vE(e,t){if(!e||typeof e!=`string`)return`rgba(0,0,0,${t})`;if(e.startsWith(`rgb`))return e.replace(/[\d.]+\)$/,`${t})`);let n=e.replace(`#`,``),r=n.length===3?n.split(``).map(e=>e+e).join(``):n;return`rgba(${parseInt(r.slice(0,2),16)},${parseInt(r.slice(2,4),16)},${parseInt(r.slice(4,6),16)},${t})`}var yE=`
333
+ `).split(/\n\s*\n/).map(e=>e.trim()).filter(Boolean),r=e=>cE(e).replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,`<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>`).replace(/\*\*([^*]+)\*\*/g,`<strong>$1</strong>`).replace(/\*([^*\n]+)\*/g,`<em>$1</em>`);return lE(n.map(e=>{let t=e.split(`
334
+ `).map(e=>e.trim()).filter(Boolean),n=t.filter(e=>/^[-*]\s+/.test(e));if(n.length>=2&&n.length===t.length)return`<ul>${n.map(e=>`<li>${r(e.replace(/^[-*]\s+/,``))}</li>`).join(``)}</ul>`;let i=e.split(/\s+(?=[-*]\s+\*\*?)/).map(e=>e.trim()).filter(Boolean);return i.length>=2&&i.every(e=>/^[-*]\s+/.test(e))?`<ul>${i.map(e=>`<li>${r(e.replace(/^[-*]\s+/,``))}</li>`).join(``)}</ul>`:`<p>${r(e).replace(/\n/g,`<br />`)}</p>`}).join(``))},dE=new Set([`application/pdf`,`application/vnd.openxmlformats-officedocument.wordprocessingml.document`]),fE=new Set([`.pdf`,`.docx`,`.png`,`.jpg`,`.jpeg`]),pE=`image/png,image/jpeg,.pdf,.docx`;function mE(e){if(!e)return!1;let t=typeof e.name==`string`?e.name.toLowerCase():``,n=t.includes(`.`)?`.${t.split(`.`).pop()}`:``,r=typeof e.type==`string`?e.type.toLowerCase():``;return r===`image/png`||r===`image/jpeg`||dE.has(r)||fE.has(n)}function hE(e){return e?mE(e)?e.size>2097152?`File must be 2 MB or smaller.`:``:`Only PNG, JPEG, PDF, and DOCX files are allowed.`:`No file selected.`}function gE(e=0){if(!Number.isFinite(e)||e<=0)return``;let t=[`B`,`KB`,`MB`,`GB`],n=e,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r+=1;let i=n>=10||r===0?0:1;return`${n.toFixed(i)} ${t[r]}`}function _E(e){return e?e.name||`Attachment`:``}function vE(e){if(!e||typeof e!=`string`)return`?`;let t=e.trim();if(!t)return`?`;let n=t.split(/\s+/).filter(Boolean);return n.length>=2?`${n[0][0]}${n[n.length-1][0]}`.toUpperCase():t.slice(0,2).toUpperCase()}function yE({src:e,name:t,imgStyle:n,initialsSpanStyle:r}){let[i,a]=(0,d.useState)(!1),o=typeof e==`string`?e.trim():``;return(0,d.useEffect)(()=>{a(!1)},[o]),o&&!i?(0,f.jsx)(`img`,{src:o,alt:``,onError:()=>a(!0),style:n}):(0,f.jsx)(`span`,{style:r,children:vE(t)})}function bE({chatHistory:e,isAiTyping:t,isAgentTyping:n,setReplyContext:r,TypingDots:i,primaryColor:a=`#3B82F6`,agentHeadshot:o=null,agentDisplayName:s=`Agent`,botAvatarNode:c=null}){let l=(0,d.useRef)(null),u=e=>{if(!e)return`just now`;let t=new Date,n=new Date(e),r=Math.max(0,Math.floor((t-n)/1e3));if(r<60)return`just now`;let i=Math.floor(r/60);if(i<60)return`${i} min${i>1?`s`:``} ago`;let a=Math.floor(i/60);if(a<24)return`${a} hr${a>1?`s`:``} ago`;let o=Math.floor(a/24);return`${o} day${o>1?`s`:``} ago`};return(0,d.useEffect)(()=>{l.current&&l.current.scrollIntoView({behavior:`smooth`})},[e.length,t,n]),(0,f.jsxs)(`div`,{style:{flex:1,overflowY:`auto`,padding:`10px 16px 20px`,display:`flex`,flexDirection:`column`,background:`transparent`},children:[e.map(e=>{let t=e.sender===`system`,n=e.sender===`user`,i=e.sender===`ai`||e.sender===`bot`,l=e.sender===`agent`,d=e.isPending,p=e.type===`file`&&e.metadata?.fileUrl,m=e.agent_name||e.agentName||e.metadata?.agentName||s,h=typeof e.sender_headshot==`string`&&e.sender_headshot.trim()||typeof o==`string`&&o.trim()||null,g=sE(e.replyToContent||e.replyContext?.message||``),_=e.replyToSender===`user`?`You`:e.replyToSender===`agent`?`Agent`:e.replyToSender===`ai`||e.replyToSender===`bot`?`AI Assistant`:`Message`;return t?(0,f.jsx)(`div`,{style:{display:`flex`,justifyContent:`center`,margin:`8px 0`},children:(0,f.jsx)(`div`,{style:{padding:`6px 12px`,borderRadius:`9999px`,background:`#f3f4f6`,color:`#6b7280`,fontSize:`12px`,fontWeight:500},children:e.message})},e.id):(0,f.jsxs)(`div`,{style:{display:`flex`,justifyContent:n?`flex-end`:`flex-start`,alignItems:`flex-start`,marginBottom:`16px`,gap:`8px`,flexDirection:`row`},children:[!n&&(i||l)&&(0,f.jsx)(`div`,{style:{width:`32px`,height:`32px`,flexShrink:0,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`50%`,background:l?`#f3f4f6`:c&&i?`transparent`:`var(--flowengage-primary)`,color:l?a:`#fff`,boxShadow:l?`0 2px 8px rgba(0,0,0,0.06)`:c&&i?`none`:`0 8px 20px rgba(59,130,246,0.24)`,overflow:`hidden`,border:l?`1px solid ${a}22`:`none`,fontSize:`12px`,fontWeight:800,marginTop:!d&&(i||l)?`22px`:`0px`},children:i?c||(0,f.jsx)(aE,{size:16}):(0,f.jsx)(yE,{src:h||``,name:m,imgStyle:{width:`100%`,height:`100%`,objectFit:`cover`},initialsSpanStyle:{lineHeight:1}})}),(0,f.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,alignItems:n?`flex-end`:`flex-start`,maxWidth:`75%`,minWidth:0},children:[!d&&!n&&(i||l)&&(0,f.jsxs)(`button`,{type:`button`,onClick:()=>r(e),style:{opacity:1,marginBottom:`4px`,display:`flex`,alignItems:`center`,gap:`4px`,fontSize:`11px`,color:`#9ca3af`,background:`transparent`,border:0,cursor:`pointer`,padding:0,marginLeft:`2px`},onMouseEnter:e=>{e.currentTarget.style.color=`#4b5563`},onMouseLeave:e=>{e.currentTarget.style.color=`#9ca3af`},children:[(0,f.jsx)(nE,{}),`Reply`]}),(0,f.jsxs)(`div`,{style:{padding:`12px 16px`,borderRadius:n?`20px 6px 20px 20px`:`6px 20px 20px 20px`,lineHeight:1.5,boxShadow:`0 2px 8px rgba(0,0,0,0.06)`,background:n?`var(--flowengage-primary)`:`rgba(255,255,255,0.92)`,color:n?`#fff`:`#111827`,fontSize:`14px`,opacity:d?.55:1,transition:`opacity 0.3s ease`,wordBreak:`break-word`,width:`fit-content`},children:[g&&(0,f.jsxs)(`div`,{style:{marginBottom:`8px`,borderRadius:`14px`,borderLeft:n?`2px solid rgba(255,255,255,0.8)`:`2px solid var(--flowengage-primary)`,padding:`8px 12px`,fontSize:`12px`,background:n?`rgba(255,255,255,0.15)`:`#f9fafb`,color:n?`rgba(255,255,255,0.9)`:`#6b7280`},children:[(0,f.jsx)(`div`,{style:{marginBottom:`2px`,fontWeight:600},children:_}),(0,f.jsx)(`div`,{style:{display:`-webkit-box`,WebkitLineClamp:2,WebkitBoxOrient:`vertical`,overflow:`hidden`},children:g})]}),p?(()=>{let t=e.metadata.fileType||``,r=e.metadata.fileName||e.message||`File`,i=gE(e.metadata.fileSize),a=t.startsWith(`image/`),o=t===`application/pdf`?{color:`#ef4444`,label:`PDF`}:t.includes(`word`)||t.includes(`docx`)?{color:`#3b82f6`,label:`DOCX`}:t.includes(`excel`)||t.includes(`sheet`)||t===`text/csv`?{color:`#10b981`,label:`XLSX`}:{color:`#6b7280`,label:`FILE`};return(0,f.jsx)(`div`,{style:{minWidth:`200px`,maxWidth:`240px`},children:(0,f.jsx)(`a`,{href:e.metadata.fileUrl,target:`_blank`,rel:`noopener noreferrer`,style:{textDecoration:`none`,display:`block`},children:a?(0,f.jsxs)(`div`,{children:[(0,f.jsx)(`img`,{src:e.metadata.fileUrl,alt:r,style:{width:`100%`,borderRadius:`10px`,display:`block`,maxHeight:`180px`,objectFit:`cover`}}),(0,f.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,justifyContent:`space-between`,marginTop:`7px`,gap:`6px`},children:[(0,f.jsx)(`span`,{style:{fontSize:`12px`,color:n?`rgba(255,255,255,0.85)`:`#374151`,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`,flex:1},children:r}),i&&(0,f.jsx)(`span`,{style:{fontSize:`11px`,flexShrink:0,color:n?`rgba(255,255,255,0.6)`:`#9ca3af`},children:i})]})]}):(0,f.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`10px`,background:n?`rgba(255,255,255,0.15)`:`#f3f4f6`,borderRadius:`12px`,padding:`10px 12px`},children:[(0,f.jsxs)(`div`,{style:{width:`38px`,height:`46px`,borderRadius:`8px`,background:n?`rgba(255,255,255,0.22)`:`#fff`,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,flexShrink:0,boxShadow:`0 1px 4px rgba(0,0,0,0.1)`,gap:`3px`},children:[(0,f.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:n?`#fff`:o.color,strokeWidth:`1.8`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`path`,{d:`M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z`}),(0,f.jsx)(`polyline`,{points:`14 2 14 8 20 8`})]}),(0,f.jsx)(`span`,{style:{fontSize:`7px`,fontWeight:800,letterSpacing:`0.04em`,color:n?`#fff`:o.color,lineHeight:1},children:o.label})]}),(0,f.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,f.jsx)(`div`,{style:{fontSize:`13px`,fontWeight:600,color:n?`#fff`:`#111827`,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:r}),i&&(0,f.jsx)(`div`,{style:{fontSize:`11px`,marginTop:`3px`,color:n?`rgba(255,255,255,0.6)`:`#9ca3af`},children:i})]}),(0,f.jsxs)(`svg`,{width:`15`,height:`15`,viewBox:`0 0 24 24`,fill:`none`,stroke:n?`rgba(255,255,255,0.65)`:`#9ca3af`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,style:{flexShrink:0},children:[(0,f.jsx)(`path`,{d:`M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4`}),(0,f.jsx)(`polyline`,{points:`7 10 12 15 17 10`}),(0,f.jsx)(`line`,{x1:`12`,y1:`15`,x2:`12`,y2:`3`})]})]})})})})():i?(0,f.jsx)(`div`,{className:`flowengage-message-content fe-bot-message`,dangerouslySetInnerHTML:{__html:uE(e.message)}}):(0,f.jsx)(`div`,{style:{whiteSpace:n||l?`normal`:`pre-wrap`},children:e.message}),d&&(0,f.jsx)(`span`,{style:{fontSize:`10px`,marginLeft:`6px`,opacity:.7},children:`sending…`})]}),(0,f.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`4px`,marginTop:`4px`,padding:`0 4px`,alignSelf:n?`flex-end`:`flex-start`},children:[(0,f.jsx)(`span`,{style:{fontSize:`10px`,color:`#9ca3af`,fontWeight:500},children:u(e.timestamp||e.createdAt)}),(0,f.jsx)(`span`,{style:{fontSize:`10px`,fontWeight:700,color:n?`var(--flowengage-primary)`:`#9ca3af`},children:d?`○`:`✓`})]})]})]},e.id)}),t&&(0,f.jsxs)(`div`,{style:{marginBottom:`16px`,display:`flex`,alignItems:`center`,gap:`8px`},children:[(0,f.jsx)(`div`,{style:{width:`32px`,height:`32px`,flexShrink:0,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`50%`,background:c?`transparent`:`var(--flowengage-primary)`,color:`#fff`,boxShadow:c?`none`:`0 8px 20px rgba(59,130,246,0.24)`,overflow:`hidden`},children:c||(0,f.jsx)(aE,{size:16})}),(0,f.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`2px`,color:`#374151`,fontSize:`13px`,fontWeight:500,fontStyle:`italic`},children:[`Analysing`,[0,1,2].map(e=>(0,f.jsx)(`span`,{style:{animation:`fe-dot-bounce 1.2s ease-in-out ${e*.2}s infinite`,display:`inline-block`},children:`.`},e))]})]}),n&&(0,f.jsxs)(`div`,{style:{display:`flex`,alignItems:`flex-start`,gap:`8px`,marginBottom:`12px`},children:[(0,f.jsx)(`div`,{style:{width:`32px`,height:`32px`,flexShrink:0,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`50%`,overflow:`hidden`},children:(0,f.jsx)(yE,{src:o||``,name:s,imgStyle:{width:`100%`,height:`100%`,objectFit:`cover`},initialsSpanStyle:{lineHeight:1}})}),(0,f.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`5px`,padding:`12px 16px`,borderRadius:`18px`,background:`#fff`,boxShadow:`0 2px 6px rgba(0,0,0,0.04)`},children:[0,1,2].map(e=>(0,f.jsx)(`span`,{style:{width:`7px`,height:`7px`,borderRadius:`50%`,background:`#9ca3af`,animation:`fe-dot-bounce 1.2s ease-in-out ${e*.2}s infinite`,display:`inline-block`}},e))})]}),(0,f.jsx)(`div`,{ref:l})]})}function xE({input:e,setInput:t,onSubmit:n,isConversationEnded:r,callUiActive:i,handleToggleVoice:a,activeScreen:o,inputDisabled:s,replyContext:c,clearReplyContext:l,requiresEmail:u,emailInput:p,setEmailInput:m,emailError:h,showVoiceToggle:g=!1,voiceEnabled:_=!0,onFileSelect:v,selectedFile:y=null,onRemoveSelectedFile:b,attachmentError:x=``,isUploadingAttachment:S=!1,inputPlaceholder:ee=`Type your message`}){let te=(0,d.useRef)(null),C=c?.sender===`user`?`You`:c?.sender===`agent`?`Agent`:`AI Assistant`,ne=u?!!p?.trim():!!e?.trim()||!!y,re=s||S||!ne,ie=!u&&_&&g;return(0,f.jsxs)(`div`,{style:{padding:`0 20px`,background:`transparent`},children:[r&&(0,f.jsx)(`div`,{style:{marginBottom:`8px`,padding:`8px 16px`,borderRadius:`12px`,background:`#f3f4f6`,color:`#6b7280`,fontSize:`12px`,textAlign:`center`,fontWeight:500},children:`This conversation has ended.`}),c&&(0,f.jsxs)(`div`,{style:{marginBottom:`8px`,display:`flex`,alignItems:`flex-start`,justifyContent:`space-between`,gap:`12px`,borderRadius:`16px`,border:`1px solid rgba(0,0,0,0.05)`,background:`#fff`,padding:`12px 16px`,boxShadow:`0 8px 24px rgba(0,0,0,0.05)`},children:[(0,f.jsxs)(`div`,{style:{minWidth:0,flex:1,borderLeft:`2px solid var(--flowengage-primary)`,paddingLeft:`12px`},children:[(0,f.jsxs)(`div`,{style:{fontSize:`12px`,fontWeight:600,color:`var(--flowengage-primary)`},children:[`Replying to `,C]}),(0,f.jsx)(`div`,{style:{overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`,fontSize:`12px`,color:`#6b7280`},children:c.replyToContent||c.message})]}),(0,f.jsx)(`button`,{type:`button`,style:{width:`28px`,height:`28px`,borderRadius:`9999px`,border:0,background:`#f3f4f6`,color:`#6b7280`,transition:`color 0.2s ease, background 0.2s ease`,cursor:`pointer`},onClick:l,"aria-label":`Cancel reply`,onMouseEnter:e=>{e.currentTarget.style.background=`#e5e7eb`,e.currentTarget.style.color=`#374151`},onMouseLeave:e=>{e.currentTarget.style.background=`#f3f4f6`,e.currentTarget.style.color=`#6b7280`},children:`×`})]}),u&&(0,f.jsx)(`div`,{style:{marginBottom:`8px`,padding:`0 8px`},children:(0,f.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,justifyContent:`center`,gap:`8px`,color:`#111827`,fontSize:`14px`,fontWeight:500,textAlign:`center`},children:[(0,f.jsx)(`span`,{style:{display:`inline-flex`,width:`22px`,height:`22px`,borderRadius:`9999px`,alignItems:`center`,justifyContent:`center`,background:`rgba(59,130,246,0.08)`,color:`var(--flowengage-primary)`},children:(0,f.jsx)(aE,{size:13})}),(0,f.jsx)(`span`,{children:`Please provide your email address so we can help you.`})]})}),y&&!u&&(0,f.jsxs)(`div`,{style:{marginBottom:`10px`,display:`flex`,alignItems:`center`,justifyContent:`space-between`,gap:`12px`,borderRadius:`16px`,border:`1px solid rgba(0,0,0,0.06)`,background:`#fff`,padding:`12px 14px`,boxShadow:`0 8px 24px rgba(0,0,0,0.05)`},children:[(0,f.jsxs)(`div`,{style:{minWidth:0,flex:1},children:[(0,f.jsx)(`div`,{style:{fontSize:`12px`,fontWeight:600,color:`var(--flowengage-primary)`,marginBottom:`2px`},children:`Attachment ready`}),(0,f.jsx)(`div`,{style:{fontSize:`13px`,color:`#111827`,whiteSpace:`nowrap`,overflow:`hidden`,textOverflow:`ellipsis`},children:_E(y)}),(0,f.jsx)(`div`,{style:{fontSize:`12px`,color:`#6b7280`,marginTop:`2px`},children:gE(y.size)})]}),(0,f.jsx)(`button`,{type:`button`,style:{width:`28px`,height:`28px`,borderRadius:`9999px`,border:0,background:`#f3f4f6`,color:`#6b7280`,transition:`color 0.2s ease, background 0.2s ease`,cursor:`pointer`,flexShrink:0},onClick:b,"aria-label":`Remove attachment`,onMouseEnter:e=>{e.currentTarget.style.background=`#e5e7eb`,e.currentTarget.style.color=`#374151`},onMouseLeave:e=>{e.currentTarget.style.background=`#f3f4f6`,e.currentTarget.style.color=`#6b7280`},children:`×`})]}),(0,f.jsxs)(`form`,{style:{display:`flex`,alignItems:`center`,gap:`12px`,padding:`8px`,border:`1px solid rgba(0,0,0,0.06)`,borderRadius:`9999px`,background:`#fff`,boxShadow:`0 4px 14px rgba(0,0,0,0.04)`,opacity:r?.5:1},onSubmit:n,children:[ie?(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(`input`,{ref:te,type:`file`,accept:pE,style:{display:`none`},onChange:e=>{let t=e.target.files?.[0];t&&v?.(t),e.target.value=``}}),(0,f.jsx)(`button`,{type:`button`,style:{width:`36px`,height:`36px`,borderRadius:`9999px`,background:`#f3f4f8`,color:`var(--flowengage-primary)`,display:`flex`,alignItems:`center`,justifyContent:`center`,transition:`background 0.2s ease, opacity 0.2s ease`,border:0,cursor:`pointer`,flexShrink:0},onClick:()=>te.current?.click(),title:`Attach file`,"aria-label":`Attach file`,disabled:r||S,onMouseEnter:e=>{e.currentTarget.style.opacity=`0.8`},onMouseLeave:e=>{e.currentTarget.style.opacity=`1`},children:(0,f.jsx)(oE,{size:18,color:`currentColor`})})]}):null,(0,f.jsx)(`input`,{className:`flowengage-chat-text-input`,style:{flex:1,minWidth:0,border:`none`,fontFamily:`inherit`,fontSize:`14px`,outline:`none`,padding:`6px 0`,paddingLeft:ie?`0`:`8px`,color:`#111827`,background:`transparent`},value:u?p:e,onChange:e=>{if(u){m(e.target.value);return}t(e.target.value)},placeholder:r?`Conversation ended`:u?`Enter your Email`:o===`agent`?`Message the agent…`:ee,disabled:s,type:u?`email`:`text`,autoComplete:u?`email`:`off`}),(0,f.jsx)(`button`,{type:`submit`,style:{width:`36px`,height:`36px`,borderRadius:`9999px`,background:`var(--flowengage-primary)`,color:`#fff`,border:`none`,display:`flex`,alignItems:`center`,justifyContent:`center`,transition:`opacity 0.2s ease`,cursor:re?`not-allowed`:`pointer`,opacity:re?.45:1},disabled:re,onMouseEnter:e=>{re||(e.currentTarget.style.opacity=`0.85`)},onMouseLeave:e=>{e.currentTarget.style.opacity=`1`},children:(0,f.jsx)(tE,{})})]}),!u&&x&&(0,f.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`5px`,padding:`7px 4px 0`},children:[(0,f.jsxs)(`svg`,{width:`13`,height:`13`,viewBox:`0 0 24 24`,fill:`none`,stroke:`#dc2626`,strokeWidth:`2.2`,strokeLinecap:`round`,strokeLinejoin:`round`,style:{flexShrink:0},children:[(0,f.jsx)(`circle`,{cx:`12`,cy:`12`,r:`10`}),(0,f.jsx)(`line`,{x1:`12`,y1:`8`,x2:`12`,y2:`12`}),(0,f.jsx)(`line`,{x1:`12`,y1:`16`,x2:`12.01`,y2:`16`})]}),(0,f.jsx)(`span`,{style:{fontSize:`11px`,color:`#dc2626`,fontWeight:500},children:x})]}),u&&h&&(0,f.jsx)(`div`,{style:{padding:`8px 16px 0`,fontSize:`12px`,fontWeight:500,color:`#f43f5e`},children:h})]})}var SE=({muted:e=!1})=>(0,f.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`path`,{d:`M12 1a4 4 0 014 4v6a4 4 0 01-6.83 2.83`}),(0,f.jsx)(`path`,{d:`M19 10a7 7 0 01-1.62 4.49M5 10a7 7 0 008.79 6.77`}),(0,f.jsx)(`path`,{d:`M12 19v4M8 23h8`}),e&&(0,f.jsx)(`line`,{x1:`2`,y1:`2`,x2:`22`,y2:`22`})]}),CE=({variant:e,onClick:t,children:n,icon:r,compact:i=!1,iconOnly:a=!1,active:o=!1,ariaLabel:s})=>(0,f.jsxs)(`button`,{type:`button`,className:[`flowengage-call-btn`,`flowengage-call-btn-${e}`,i?`compact`:``,a?`icon-only`:``,o?`active`:``].filter(Boolean).join(` `),onClick:t,"aria-label":s||n,title:s||n,children:[r,!a&&(0,f.jsx)(`span`,{children:n})]});function wE({webRTCError:e,micError:t,setMicError:n,dismissCallError:r,incomingCall:i,rejectCall:a,acceptCall:o,activeCallId:s,callConnectionState:c,formatCallDuration:l,callDurationSeconds:u,endWebRTCCall:p,isCallMuted:m,toggleCallMute:h,isAIVoiceActive:g,currentCallAgentName:_,isRateLimited:v,rateLimitMessage:y}){let b=(0,d.useRef)(null),x=(0,d.useCallback)(()=>{if(!b.current)return;let{audioContext:e,oscillator:t,interval:n,toneTimeout:r}=b.current;window.clearInterval(n),window.clearTimeout(r);try{t.stop()}catch{}try{e.close()}catch{}b.current=null},[]),S=(0,d.useCallback)(()=>{if(b.current||typeof window>`u`)return;let e=window.AudioContext||window.webkitAudioContext||null;if(e)try{let t=new e,n=t.createOscillator(),r=t.createGain();n.connect(r),r.connect(t.destination),n.frequency.value=0,n.type=`sine`,r.gain.value=.3;let i=()=>{b.current&&(window.clearTimeout(b.current.toneTimeout),n.frequency.value=440,b.current.toneTimeout=window.setTimeout(()=>{n.frequency.value=0},400))};t.state===`suspended`&&t.resume().catch(e=>{console.warn(`[FlowEngage] ringtone autoplay blocked`,e)}),n.start(),b.current={audioContext:t,oscillator:n,interval:null,toneTimeout:null},i(),b.current.interval=window.setInterval(i,1e3)}catch(e){console.warn(`[FlowEngage] failed to start ringtone`,e)}},[]);(0,d.useEffect)(()=>{if(i){S();return}x()},[i,S,x]),(0,d.useEffect)(()=>()=>x(),[x]);let ee=g?`header-mode`:`bottom-mode`,te=!!(i||s),C=i?`incoming`:c===`connected`?`connected`:`connecting`,ne=(0,d.useMemo)(()=>C===`incoming`?`Incoming Call`:C===`connected`?`Voice Call Active`:`Connecting Call`,[C]),re=(0,d.useMemo)(()=>C===`incoming`?`${_} wants to join a voice call`:C===`connected`?`You are connected to ${_} from this conversation.`:`Please wait while ${_}'s voice connection finishes setting up.`,[_,C]);return(0,f.jsxs)(f.Fragment,{children:[(e||t)&&(0,f.jsxs)(`div`,{style:{margin:`0 20px 10px`,padding:`12px 16px`,borderRadius:`12px`,background:`#fef2f2`,border:`1px solid #fee2e2`,display:`flex`,alignItems:`flex-start`,gap:`10px`},children:[(0,f.jsx)(iE,{className:``}),(0,f.jsx)(`span`,{style:{fontSize:`12px`,color:`#b91c1c`,lineHeight:1.5,flex:1},children:e||t}),(0,f.jsx)(`button`,{style:{flexShrink:0,background:`transparent`,border:0,color:`#f87171`,cursor:`pointer`,fontSize:`18px`,lineHeight:1},onClick:()=>{n(null),r()},onMouseEnter:e=>{e.currentTarget.style.color=`#dc2626`},onMouseLeave:e=>{e.currentTarget.style.color=`#f87171`},children:`×`})]}),te&&(0,f.jsx)(`div`,{className:`incoming-call-overlay ${ee}`,children:(0,f.jsx)(`div`,{className:[`incoming-call-container`,C===`connected`?`connected-layout`:``].filter(Boolean).join(` `),children:C===`connected`?(0,f.jsxs)(f.Fragment,{children:[(0,f.jsxs)(`div`,{className:`call-connected-top`,children:[(0,f.jsxs)(`div`,{className:`call-connected-identity`,children:[(0,f.jsx)(`div`,{className:`call-icon-wrapper ${C}`,children:(0,f.jsx)(eE,{size:20})}),(0,f.jsxs)(`div`,{className:`call-info-group`,children:[(0,f.jsx)(`h3`,{className:`call-title`,children:ne}),(0,f.jsx)(`p`,{className:`call-subtitle`,children:re})]})]}),(0,f.jsx)(`div`,{className:`call-timer`,children:l(u)})]}),(0,f.jsxs)(`div`,{className:`call-actions connected`,children:[(0,f.jsx)(CE,{variant:`mute`,onClick:h,compact:g,active:m,icon:(0,f.jsx)(SE,{muted:m}),children:m?`Unmute`:`Mute`}),(0,f.jsx)(CE,{variant:`end`,onClick:p,compact:g,icon:(0,f.jsx)(eE,{size:14}),children:`End`})]})]}):(0,f.jsxs)(f.Fragment,{children:[(0,f.jsxs)(`div`,{className:`call-icon-wrapper ${C}`,children:[(0,f.jsx)(rE,{}),C===`incoming`&&(0,f.jsx)(`div`,{className:`call-pulse-animation`}),C===`connecting`&&(0,f.jsx)(`div`,{className:`call-connecting-animation`})]}),(0,f.jsxs)(`div`,{className:`call-info-group`,children:[(0,f.jsx)(`h3`,{className:`call-title`,children:ne}),(0,f.jsx)(`p`,{className:`call-subtitle`,children:re})]}),(0,f.jsx)(`div`,{className:`call-actions`,children:C===`incoming`&&(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(CE,{variant:`reject`,onClick:async()=>{x(),await a()},iconOnly:!0,icon:(0,f.jsx)(eE,{size:14}),ariaLabel:`Decline call`,children:`Decline`}),(0,f.jsx)(CE,{variant:`accept`,onClick:async()=>{x(),await o()},iconOnly:!0,icon:(0,f.jsx)(rE,{}),ariaLabel:`Accept call`,children:`Accept`})]})})]})})}),v&&(0,f.jsx)(`div`,{style:{margin:`0 20px 10px`,padding:`12px 16px`,fontSize:`13px`,borderRadius:`12px`,background:`#fee2e2`,color:`#991b1b`},children:y})]})}var TE=[`#135bd8`,`#ef334b`,`#ffbd2e`];function EE(e){return!Array.isArray(e)||e.length===0?TE:e.length===1?[e[0],e[0],e[0]]:e.length===2?[e[0],e[1],e[0]]:[e[0],e[1],e[2]]}var DE={idle:3,listening:.75,speaking:1.4,muted:.75,error:.08};function OE(e){if(!e||typeof e!=`string`)return[0,0,0];let t=e.replace(`#`,``),n=t.length===3?t.split(``).map(e=>e+e).join(``):t;return[parseInt(n.slice(0,2),16)/255,parseInt(n.slice(2,4),16)/255,parseInt(n.slice(4,6),16)/255]}function kE(e,t){if(!e||typeof e!=`string`)return`rgba(0,0,0,${t})`;if(e.startsWith(`rgb`))return e.replace(/[\d.]+\)$/,`${t})`);let n=e.replace(`#`,``),r=n.length===3?n.split(``).map(e=>e+e).join(``):n;return`rgba(${parseInt(r.slice(0,2),16)},${parseInt(r.slice(2,4),16)},${parseInt(r.slice(4,6),16)},${t})`}var AE=`
335
335
  attribute vec2 a_pos;
336
336
  varying vec2 v_uv;
337
337
  void main() {
338
338
  v_uv = a_pos * 0.5 + 0.5;
339
339
  gl_Position = vec4(a_pos, 0.0, 1.0);
340
340
  }
341
- `,bE=`
341
+ `,jE=`
342
342
  precision highp float;
343
343
 
344
344
  varying vec2 v_uv;
@@ -454,7 +454,7 @@ registerProcessor("scribeAudioProcessor", ScribeAudioProcessor);
454
454
 
455
455
  gl_FragColor = vec4(clamp(col, 0.0, 1.0), 1.0);
456
456
  }
457
- `;function xE(e,t,n){let r=(t,n)=>{let r=e.createShader(t);return e.shaderSource(r,n),e.compileShader(r),e.getShaderParameter(r,e.COMPILE_STATUS)?r:(console.error(`[AnimatedOrb shader]`,e.getShaderInfoLog(r)),null)},i=r(e.VERTEX_SHADER,t),a=r(e.FRAGMENT_SHADER,n);if(!i||!a)return null;let o=e.createProgram();return e.attachShader(o,i),e.attachShader(o,a),e.linkProgram(o),e.getProgramParameter(o,e.LINK_STATUS)?o:(console.error(`[AnimatedOrb link]`,e.getProgramInfoLog(o)),null)}function SE({size:e=94,voiceState:t=`idle`,isMuted:n=!1,colors:r,onClick:i,style:a,className:o}){let[s,c,l]=hE(r),u=t===`speaking`,p=e<=50,m=(0,d.useRef)(null),h=(0,d.useRef)(gE[t]??.35);(0,d.useEffect)(()=>{h.current=gE[t]??.35},[t]),(0,d.useEffect)(()=>{let t=m.current;if(!t)return;let n=Math.min(window.devicePixelRatio||1,2);t.width=e*n,t.height=e*n;let r=t.getContext(`webgl`,{alpha:!0,antialias:!0})||t.getContext(`experimental-webgl`,{alpha:!0,antialias:!0});if(!r){console.warn(`[AnimatedOrb] WebGL unavailable.`);return}let i=xE(r,yE,bE);if(!i){console.error(`[AnimatedOrb] WebGL program failed to compile/link`);return}r.useProgram(i);let a=r.createBuffer();r.bindBuffer(r.ARRAY_BUFFER,a),r.bufferData(r.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,-1,1,1,-1,1,1]),r.STATIC_DRAW);let o=r.getAttribLocation(i,`a_pos`);r.enableVertexAttribArray(o),r.vertexAttribPointer(o,2,r.FLOAT,!1,0,0);let u={time:r.getUniformLocation(i,`u_time`),speed:r.getUniformLocation(i,`u_speed`),c1:r.getUniformLocation(i,`u_c1`),c2:r.getUniformLocation(i,`u_c2`),c3:r.getUniformLocation(i,`u_c3`)};r.uniform3fv(u.c1,_E(s)),r.uniform3fv(u.c2,_E(c)),r.uniform3fv(u.c3,_E(l)),r.viewport(0,0,t.width,t.height);let d=performance.now(),f,p=e=>{r.uniform1f(u.time,(e-d)/1e3),r.uniform1f(u.speed,h.current),r.drawArrays(r.TRIANGLES,0,6),f=requestAnimationFrame(p)};return f=requestAnimationFrame(p),()=>{cancelAnimationFrame(f),r.deleteProgram(i),r.deleteBuffer(a)}},[s,c,l,e]);let g=n?`saturate(0.3) brightness(1.1)`:t===`error`?`saturate(0.4) hue-rotate(28deg)`:`none`;return(0,f.jsxs)(`div`,{style:{position:`relative`,width:e,height:e,flexShrink:0,cursor:i?`pointer`:`default`,...a},className:o,onClick:i,children:[u&&!p&&(0,f.jsx)(op.div,{style:{position:`absolute`,inset:-10,borderRadius:`50%`,background:`radial-gradient(circle, ${vE(s,.18)} 0%, transparent 70%)`,pointerEvents:`none`},animate:{opacity:[.3,.75]},transition:{duration:1,repeat:1/0,repeatType:`mirror`,ease:`easeInOut`}}),(0,f.jsx)(`div`,{style:{width:e,height:e,borderRadius:`50%`,overflow:`hidden`,WebkitMaskImage:`-webkit-radial-gradient(white, black)`,filter:g,transition:`filter 1.2s ease`},children:(0,f.jsx)(`canvas`,{ref:m,style:{width:`100%`,height:`100%`,display:`block`}})}),u&&(0,f.jsx)(`div`,{style:{position:`absolute`,inset:0,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`50%`,pointerEvents:`none`,zIndex:1},children:(0,f.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`3px`},children:[4,8,12,8,4].map((e,t)=>(0,f.jsx)(op.div,{style:{width:`3px`,borderRadius:`3px`,background:`rgba(255,255,255,0.85)`},animate:{height:[4,e+8,4]},transition:{duration:.48,delay:t*.08,repeat:1/0,ease:`easeInOut`}},t))})})]})}var CE=375,wE=6e3,TE={wordsSoFar:0,speechStartTime:0,isSpeaking:!1,items:[],timers:[],textDraining:!1,lastHighlightId:null,isVoiceMode:!1};function EE(e,t=5e3){let n={execute:e,wordOffset:TE.wordsSoFar,holdMs:t};if(TE.isVoiceMode)if(TE.speechStartTime>0)DE(n);else{TE.items.push(n);let e=setTimeout(()=>{let e=TE.items.indexOf(n);e!==-1&&(TE.items.splice(e,1),n.execute())},wE);TE.timers.push(e)}else TE.items.push(n),TE.textDraining||OE()}function DE(e){let t=e.wordOffset*CE,n=Date.now()-TE.speechStartTime,r=Math.max(0,t-n),i=setTimeout(e.execute,r);TE.timers.push(i)}function OE(){if(TE.items.length===0){TE.textDraining=!1;return}TE.textDraining=!0;let e=TE.items.shift();setTimeout(()=>e.execute(),300);let t=setTimeout(OE,e.holdMs);TE.timers.push(t)}function kE(){TE.timers.forEach(clearTimeout),TE.wordsSoFar=0,TE.speechStartTime=0,TE.isSpeaking=!1,TE.items=[],TE.timers=[],TE.textDraining=!1,TE.lastHighlightId=null}var AE=80,jE=null;function ME(e){requestAnimationFrame(()=>{let t=e.getBoundingClientRect(),n=t.top+t.height/2,r=AE,i=r+(window.innerHeight-r)/2,a=window.pageYOffset+n-i;window.scrollTo({top:Math.max(0,a),behavior:`smooth`})})}function NE(e){PE(),jE=document.createElement(`div`),jE.id=`fe-spotlight-overlay`,jE.style.cssText=`position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,0.35);z-index:9998;pointer-events:none;transition:opacity 0.4s ease;opacity:0;`,document.body.appendChild(jE),jE.offsetHeight,jE.style.opacity=`1`,e.style.position=`relative`,e.style.zIndex=`9999`}function PE(){if(jE){jE.style.opacity=`0`;let e=jE;setTimeout(()=>{e.parentNode&&e.parentNode.removeChild(e)},400),jE=null}document.querySelectorAll(`[data-fe-highlighted]`).forEach(e=>{e.style.zIndex=``,e.style.position=``})}function FE(e){if(!e||e.hasAttribute(`data-fe-highlighted`))return;IE(),ME(e);let t=e.style.cssText;e.setAttribute(`data-fe-highlighted`,`true`),e.setAttribute(`data-fe-orig-style`,t),e.style.outline=`3px solid #2563eb`,e.style.outlineOffset=`8px`,e.style.background=`rgba(37, 99, 235, 0.08)`,e.style.borderRadius=`8px`,e.style.padding=`12px 16px`,e.style.transition=`all 0.4s ease`,NE(e),setTimeout(()=>IE(),6e4)}function IE(){let e=document.querySelector(`[data-fe-highlighted]`);e&&(e.style.cssText=e.getAttribute(`data-fe-orig-style`)||``,e.removeAttribute(`data-fe-highlighted`),e.removeAttribute(`data-fe-orig-style`)),PE()}var Q=`fe-vv`;function LE(){if(typeof document>`u`||document.getElementById(`${Q}-styles`))return;let e=`
457
+ `;function ME(e,t,n){let r=(t,n)=>{let r=e.createShader(t);return e.shaderSource(r,n),e.compileShader(r),e.getShaderParameter(r,e.COMPILE_STATUS)?r:(console.error(`[AnimatedOrb shader]`,e.getShaderInfoLog(r)),null)},i=r(e.VERTEX_SHADER,t),a=r(e.FRAGMENT_SHADER,n);if(!i||!a)return null;let o=e.createProgram();return e.attachShader(o,i),e.attachShader(o,a),e.linkProgram(o),e.getProgramParameter(o,e.LINK_STATUS)?o:(console.error(`[AnimatedOrb link]`,e.getProgramInfoLog(o)),null)}function NE({size:e=94,voiceState:t=`idle`,isMuted:n=!1,colors:r,onClick:i,style:a,className:o}){let[s,c,l]=EE(r),u=t===`speaking`,p=e<=50,m=(0,d.useRef)(null),h=(0,d.useRef)(DE[t]??.35);(0,d.useEffect)(()=>{h.current=DE[t]??.35},[t]),(0,d.useEffect)(()=>{let t=m.current;if(!t)return;let n=Math.min(window.devicePixelRatio||1,2);t.width=e*n,t.height=e*n;let r=t.getContext(`webgl`,{alpha:!0,antialias:!0})||t.getContext(`experimental-webgl`,{alpha:!0,antialias:!0});if(!r){console.warn(`[AnimatedOrb] WebGL unavailable.`);return}let i=ME(r,AE,jE);if(!i){console.error(`[AnimatedOrb] WebGL program failed to compile/link`);return}r.useProgram(i);let a=r.createBuffer();r.bindBuffer(r.ARRAY_BUFFER,a),r.bufferData(r.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,-1,1,1,-1,1,1]),r.STATIC_DRAW);let o=r.getAttribLocation(i,`a_pos`);r.enableVertexAttribArray(o),r.vertexAttribPointer(o,2,r.FLOAT,!1,0,0);let u={time:r.getUniformLocation(i,`u_time`),speed:r.getUniformLocation(i,`u_speed`),c1:r.getUniformLocation(i,`u_c1`),c2:r.getUniformLocation(i,`u_c2`),c3:r.getUniformLocation(i,`u_c3`)};r.uniform3fv(u.c1,OE(s)),r.uniform3fv(u.c2,OE(c)),r.uniform3fv(u.c3,OE(l)),r.viewport(0,0,t.width,t.height);let d=performance.now(),f,p=e=>{r.uniform1f(u.time,(e-d)/1e3),r.uniform1f(u.speed,h.current),r.drawArrays(r.TRIANGLES,0,6),f=requestAnimationFrame(p)};return f=requestAnimationFrame(p),()=>{cancelAnimationFrame(f),r.deleteProgram(i),r.deleteBuffer(a)}},[s,c,l,e]);let g=n?`saturate(0.3) brightness(1.1)`:t===`error`?`saturate(0.4) hue-rotate(28deg)`:`none`;return(0,f.jsxs)(`div`,{style:{position:`relative`,width:e,height:e,flexShrink:0,cursor:i?`pointer`:`default`,...a},className:o,onClick:i,children:[u&&!p&&(0,f.jsx)(up.div,{style:{position:`absolute`,inset:-10,borderRadius:`50%`,background:`radial-gradient(circle, ${kE(s,.18)} 0%, transparent 70%)`,pointerEvents:`none`},animate:{opacity:[.3,.75]},transition:{duration:1,repeat:1/0,repeatType:`mirror`,ease:`easeInOut`}}),(0,f.jsx)(`div`,{style:{width:e,height:e,borderRadius:`50%`,overflow:`hidden`,WebkitMaskImage:`-webkit-radial-gradient(white, black)`,filter:g,transition:`filter 1.2s ease`},children:(0,f.jsx)(`canvas`,{ref:m,style:{width:`100%`,height:`100%`,display:`block`}})}),u&&(0,f.jsx)(`div`,{style:{position:`absolute`,inset:0,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`50%`,pointerEvents:`none`,zIndex:1},children:(0,f.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`3px`},children:[4,8,12,8,4].map((e,t)=>(0,f.jsx)(up.div,{style:{width:`3px`,borderRadius:`3px`,background:`rgba(255,255,255,0.85)`},animate:{height:[4,e+8,4]},transition:{duration:.48,delay:t*.08,repeat:1/0,ease:`easeInOut`}},t))})})]})}var PE=375,FE=6e3,IE={wordsSoFar:0,speechStartTime:0,isSpeaking:!1,items:[],timers:[],textDraining:!1,lastHighlightId:null,isVoiceMode:!1};function LE(e,t=5e3){let n={execute:e,wordOffset:IE.wordsSoFar,holdMs:t};if(IE.isVoiceMode)if(IE.speechStartTime>0)RE(n);else{IE.items.push(n);let e=setTimeout(()=>{let e=IE.items.indexOf(n);e!==-1&&(IE.items.splice(e,1),n.execute())},FE);IE.timers.push(e)}else IE.items.push(n),IE.textDraining||zE()}function RE(e){let t=e.wordOffset*PE,n=Date.now()-IE.speechStartTime,r=Math.max(0,t-n),i=setTimeout(e.execute,r);IE.timers.push(i)}function zE(){if(IE.items.length===0){IE.textDraining=!1;return}IE.textDraining=!0;let e=IE.items.shift();setTimeout(()=>e.execute(),300);let t=setTimeout(zE,e.holdMs);IE.timers.push(t)}function BE(){IE.timers.forEach(clearTimeout),IE.wordsSoFar=0,IE.speechStartTime=0,IE.isSpeaking=!1,IE.items=[],IE.timers=[],IE.textDraining=!1,IE.lastHighlightId=null}var VE=80,HE=null;function UE(e){requestAnimationFrame(()=>{let t=e.getBoundingClientRect(),n=t.top+t.height/2,r=VE,i=r+(window.innerHeight-r)/2,a=window.pageYOffset+n-i;window.scrollTo({top:Math.max(0,a),behavior:`smooth`})})}function WE(e){GE(),HE=document.createElement(`div`),HE.id=`fe-spotlight-overlay`,HE.style.cssText=`position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,0.35);z-index:9998;pointer-events:none;transition:opacity 0.4s ease;opacity:0;`,document.body.appendChild(HE),HE.offsetHeight,HE.style.opacity=`1`,e.style.position=`relative`,e.style.zIndex=`9999`}function GE(){if(HE){HE.style.opacity=`0`;let e=HE;setTimeout(()=>{e.parentNode&&e.parentNode.removeChild(e)},400),HE=null}document.querySelectorAll(`[data-fe-highlighted]`).forEach(e=>{e.style.zIndex=``,e.style.position=``})}function KE(e){if(!e||e.hasAttribute(`data-fe-highlighted`))return;qE(),UE(e);let t=e.style.cssText;e.setAttribute(`data-fe-highlighted`,`true`),e.setAttribute(`data-fe-orig-style`,t),e.style.outline=`3px solid #2563eb`,e.style.outlineOffset=`8px`,e.style.background=`rgba(37, 99, 235, 0.08)`,e.style.borderRadius=`8px`,e.style.padding=`12px 16px`,e.style.transition=`all 0.4s ease`,WE(e),setTimeout(()=>qE(),6e4)}function qE(){let e=document.querySelector(`[data-fe-highlighted]`);e&&(e.style.cssText=e.getAttribute(`data-fe-orig-style`)||``,e.removeAttribute(`data-fe-highlighted`),e.removeAttribute(`data-fe-orig-style`)),GE()}var Q=`fe-vv`;function JE(){if(typeof document>`u`||document.getElementById(`${Q}-styles`))return;let e=`
458
458
  /* ── Action toast ───────────────────────────────────────────────────────────── */
459
459
  #${Q}-toast {
460
460
  position: fixed;
@@ -594,15 +594,15 @@ registerProcessor("scribeAudioProcessor", ScribeAudioProcessor);
594
594
  50% { transform: translate(-4px,-4px) scale(0.82); }
595
595
  100% { transform: translate(-4px,-4px) scale(1); }
596
596
  }
597
- `,t=document.createElement(`style`);t.id=`${Q}-styles`,t.textContent=e,(document.head||document.documentElement).appendChild(t)}var RE=null,zE=null;function BE(){return(!RE||!RE.isConnected)&&(RE=document.createElement(`div`),RE.id=`${Q}-toast`,document.body.appendChild(RE)),RE}function VE(e,{spinner:t=!0,icon:n=null,duration:r=0}={}){if(typeof document>`u`)return;LE(),zE&&=(clearTimeout(zE),null);let i=BE();if(i.innerHTML=``,n){let e=document.createElement(`span`);e.className=`${Q}-icon`,e.textContent=n,i.appendChild(e)}else if(t){let e=document.createElement(`span`);e.className=`${Q}-spin`,i.appendChild(e)}let a=document.createElement(`span`);a.textContent=e,i.appendChild(a),i.classList.remove(`${Q}-show`),i.offsetHeight,i.classList.add(`${Q}-show`),r>0&&(zE=setTimeout(()=>HE(),r))}function HE(e=0){RE&&(e>0?zE=setTimeout(()=>{RE&&RE.classList.remove(`${Q}-show`)},e):RE&&RE.classList.remove(`${Q}-show`))}var UE=null,WE=[];function GE(){return(!UE||!UE.isConnected)&&(UE=document.createElement(`div`),UE.id=`${Q}-bar`,document.body.appendChild(UE)),UE}function KE(){if(typeof document>`u`)return;LE(),WE.forEach(clearTimeout),WE=[];let e=GE();e.style.transition=`none`,e.style.width=`0%`,e.classList.add(`${Q}-bar-active`),e.offsetHeight,e.style.transition=`width 0.35s ease, opacity 0.25s ease`;let t=[[80,`width 0.6s ease`],[92,`width 1.2s ease`]],n=50;for(let[e,r]of t){let t=n,i=e,a=r;WE.push(setTimeout(()=>{UE&&(UE.style.transition=a,UE.style.width=`${i}%`)},t)),n+=800}}function qE(){UE&&(WE.forEach(clearTimeout),WE=[],UE.style.transition=`width 0.2s ease`,UE.style.width=`100%`,WE.push(setTimeout(()=>{UE&&(UE.style.transition=`opacity 0.35s ease`,UE.style.opacity=`0`,WE.push(setTimeout(()=>{UE&&(UE.style.width=`0%`,UE.classList.remove(`${Q}-bar-active`))},380)))},220)))}function JE(){typeof document>`u`||document.querySelectorAll(`.${Q}-field-active, .${Q}-field-filled`).forEach(e=>e.classList.remove(`${Q}-field-active`,`${Q}-field-filled`))}function YE(e){!e||typeof document>`u`||(LE(),JE(),e.classList.add(`${Q}-field-active`))}function XE(e){e&&(e.classList.remove(`${Q}-field-active`),e.classList.add(`${Q}-field-filled`),setTimeout(()=>{e.isConnected&&e.classList.remove(`${Q}-field-filled`)},1400))}var ZE=`<svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 22 22" fill="none">
597
+ `,t=document.createElement(`style`);t.id=`${Q}-styles`,t.textContent=e,(document.head||document.documentElement).appendChild(t)}var YE=null,XE=null;function ZE(){return(!YE||!YE.isConnected)&&(YE=document.createElement(`div`),YE.id=`${Q}-toast`,document.body.appendChild(YE)),YE}function QE(e,{spinner:t=!0,icon:n=null,duration:r=0}={}){if(typeof document>`u`)return;JE(),XE&&=(clearTimeout(XE),null);let i=ZE();if(i.innerHTML=``,n){let e=document.createElement(`span`);e.className=`${Q}-icon`,e.textContent=n,i.appendChild(e)}else if(t){let e=document.createElement(`span`);e.className=`${Q}-spin`,i.appendChild(e)}let a=document.createElement(`span`);a.textContent=e,i.appendChild(a),i.classList.remove(`${Q}-show`),i.offsetHeight,i.classList.add(`${Q}-show`),r>0&&(XE=setTimeout(()=>$E(),r))}function $E(e=0){YE&&(e>0?XE=setTimeout(()=>{YE&&YE.classList.remove(`${Q}-show`)},e):YE&&YE.classList.remove(`${Q}-show`))}var eD=null,tD=[];function nD(){return(!eD||!eD.isConnected)&&(eD=document.createElement(`div`),eD.id=`${Q}-bar`,document.body.appendChild(eD)),eD}function rD(){if(typeof document>`u`)return;JE(),tD.forEach(clearTimeout),tD=[];let e=nD();e.style.transition=`none`,e.style.width=`0%`,e.classList.add(`${Q}-bar-active`),e.offsetHeight,e.style.transition=`width 0.35s ease, opacity 0.25s ease`;let t=[[80,`width 0.6s ease`],[92,`width 1.2s ease`]],n=50;for(let[e,r]of t){let t=n,i=e,a=r;tD.push(setTimeout(()=>{eD&&(eD.style.transition=a,eD.style.width=`${i}%`)},t)),n+=800}}function iD(){eD&&(tD.forEach(clearTimeout),tD=[],eD.style.transition=`width 0.2s ease`,eD.style.width=`100%`,tD.push(setTimeout(()=>{eD&&(eD.style.transition=`opacity 0.35s ease`,eD.style.opacity=`0`,tD.push(setTimeout(()=>{eD&&(eD.style.width=`0%`,eD.classList.remove(`${Q}-bar-active`))},380)))},220)))}function aD(){typeof document>`u`||document.querySelectorAll(`.${Q}-field-active, .${Q}-field-filled`).forEach(e=>e.classList.remove(`${Q}-field-active`,`${Q}-field-filled`))}function oD(e){!e||typeof document>`u`||(JE(),aD(),e.classList.add(`${Q}-field-active`))}function sD(e){e&&(e.classList.remove(`${Q}-field-active`),e.classList.add(`${Q}-field-filled`),setTimeout(()=>{e.isConnected&&e.classList.remove(`${Q}-field-filled`)},1400))}var cD=`<svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 22 22" fill="none">
598
598
  <filter id="${Q}-csh">
599
599
  <feDropShadow dx="1" dy="2" stdDeviation="1.5" flood-color="#00000060"/>
600
600
  </filter>
601
601
  <path d="M4 2L19 10.5L11 12.8L8 20L4 2Z"
602
602
  fill="white" stroke="#1e1b4b" stroke-width="1.6" stroke-linejoin="round"
603
603
  filter="url(#${Q}-csh)"/>
604
- </svg>`,QE=null,$E=!1;function eD(){return(!QE||!QE.isConnected)&&(QE=document.createElement(`div`),QE.id=`${Q}-cursor`,QE.innerHTML=ZE,document.body.appendChild(QE),$E=!1),QE}async function tD(e){if(typeof document>`u`||!e)return;LE();let t;try{t=e.getBoundingClientRect()}catch{return}let n=t.left+Math.min(16,t.width*.2),r=t.top+Math.min(12,t.height*.25),i=eD();$E||=(i.style.transition=`none`,i.style.left=`${window.innerWidth/2}px`,i.style.top=`${window.innerHeight*.4}px`,i.classList.add(`${Q}-cursor-visible`),i.offsetHeight,i.style.transition=`left 0.32s cubic-bezier(0.25,0.46,0.45,0.94), top 0.32s cubic-bezier(0.25,0.46,0.45,0.94), opacity 0.2s ease`,!0),i.style.left=`${n}px`,i.style.top=`${r}px`,await aD(360)}function nD(e=!1){QE&&(e?(QE.classList.remove(`${Q}-cursor-visible`),$E=!1):(QE.classList.remove(`${Q}-cursor-visible`),setTimeout(()=>{$E=!1},250)))}async function rD(e){QE&&(QE.classList.add(`${Q}-cursor-click`),await aD(280),QE.classList.remove(`${Q}-cursor-click`))}function iD(e){if(!e||typeof document>`u`)return;LE();let t;try{t=e.getBoundingClientRect()}catch{return}let n=e.style.position,r=e.style.overflow,i=window.getComputedStyle(e).position;[`relative`,`absolute`,`fixed`,`sticky`].includes(i)||(e.style.position=`relative`),e.style.overflow=`hidden`;let a=document.createElement(`span`);a.className=`${Q}-ripple`;let o=Math.max(t.width,t.height)*1.2;Object.assign(a.style,{width:`${o}px`,height:`${o}px`,left:`${t.width/2-o/2}px`,top:`${t.height/2-o/2}px`}),e.appendChild(a),setTimeout(()=>{a.remove(),e.style.position=n,e.style.overflow=r},650)}function aD(e){return new Promise(t=>setTimeout(t,e))}function $(...e){Yt()&&console.log(`[FlowEngage:voice-tools]`,...e)}function oD(e){return new Promise(t=>setTimeout(t,e))}var sD=`#flowengage-root, .flowengage-shell, .flowengage-widget-root`;function cD(e){if(!e||typeof e.closest!=`function`)return!1;try{return!!e.closest(sD)}catch{return!1}}function lD(e){try{let t=e.ownerDocument?.defaultView;if(t)return t.getComputedStyle(e)}catch{}return window.getComputedStyle(e)}function uD(e){let t=new Set;function n(r){if(!r||t.has(r))return;t.add(r),e(r);let i=r.querySelectorAll(`iframe`);for(let e of i)if(!cD(e))try{let t=e.contentDocument;t&&n(t)}catch{}}typeof document<`u`&&n(document)}function dD(e){return e==null?null:String(e).replace(/\u00a0/g,` `).replace(/\s*\*+\s*$/u,``).replace(/\s+/g,` `).trim()}function fD(e){let t=e.ownerDocument||document,n=e.getAttribute(`aria-labelledby`);if(n){let e=n.trim().split(/\s+/).filter(Boolean),r=[];for(let n of e)try{let e=t.getElementById(n);e?.textContent&&r.push(e.textContent.trim())}catch{}if(r.length)return dD(r.join(` `))}if(e.labels&&e.labels.length)return dD(e.labels[0].textContent);let r=e.id;if(r)try{let e=t.querySelector(`label[for="${CSS.escape(r)}"]`);if(e)return dD(e.textContent)}catch{let e=t.querySelector(`label[for="${r.replace(/"/g,`\\"`)}"]`);if(e)return dD(e.textContent)}let i=e.previousElementSibling;for(let e=0;e<6&&i;e+=1){if(i.tagName===`LABEL`)return dD(i.textContent);let e=(i.className||``).toString().toLowerCase();if(/chakra-form__label|formlabel|field-label|form-label|mui-form-label/.test(e)){let e=dD(i.textContent);if(e)return e}i=i.previousElementSibling}let a=e.parentElement;for(let e=0;e<5&&a;e+=1){if(a.tagName===`LABEL`)return dD(a.textContent);let e=a.querySelector?.(`:scope > label, :scope > [class*='FormLabel'], :scope > [class*='form__label']`);if(e?.textContent)return dD(e.textContent);a=a.parentElement}let o=e.getAttribute(`aria-label`);return o?dD(o):null}function pD(){let e=[];return uD(t=>{e.push(...Array.from(t.querySelectorAll(`input, select, textarea`)).filter(e=>{if(cD(e))return!1;let t=(e.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`image`].includes(t)||e.disabled||e.readOnly)return!1;try{let t=lD(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))}),e}function mD(){return pD().map((e,t)=>({formIndex:0,fieldIndex:t,tag:e.tagName,type:e.type||`text`,name:e.name||null,id:e.id||null,label:fD(e),placeholder:e.placeholder||null}))}function hD(){let e=[];return uD(t=>{e.push(...Array.from(t.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(cD(e)||e.disabled)return!1;try{let t=lD(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))}),e.slice(0,60).map((e,t)=>({index:t,text:(e.textContent||e.value||``).replace(/\s+/g,` `).trim().slice(0,120)||null,ariaLabel:e.getAttribute(`aria-label`),type:e.type||e.tagName}))}function gD(e){return String(e||``).toLowerCase().replace(/\u00a0/g,` `).replace(/\*/g,``).replace(/\s+/g,` `).trim()}function _D(e){let t=gD(e);return t=t.replace(/\s+field\s*$/i,``).trim(),t}function vD(e,t){let n=_D(t);if(!n)return 0;let r=(e.name||``).toLowerCase(),i=(e.id||``).toLowerCase();if(r===`url`&&/url|website|domain|site|audit/.test(n)||(i===`url-input`||i.endsWith(`-url-input`))&&/url|website|domain|site|audit/.test(n))return 100;let a=[e.name,e.id,e.placeholder,fD(e),e.getAttribute(`aria-label`),e.getAttribute(`title`),e.getAttribute(`data-testid`),e.getAttribute(`autocomplete`)].filter(Boolean).map(e=>gD(e)),o=0;for(let e of a){if(!e)continue;if(e.includes(n)||n.includes(e)){o=Math.max(o,100);continue}let t=n.split(/\s+/).filter(e=>e.length>1);if(!t.length)continue;let r=0;for(let n of t)e.includes(n)&&(r+=1);o=Math.max(o,r/t.length*88)}return o}var yD=28;function bD(e,t){let n=null,r=0;for(let i of e){let e=vD(i,t);e>r&&(r=e,n=i)}return!n||r<yD?null:n}function xD(e,t,n){let r=String(t||``).toLowerCase().trim(),i=String(n||``).trim();if(!(/^https?:\/\//i.test(i)||/\.\w{2,}(\/|\s|$)/.test(i)||r.includes(`url`)||r.includes(`website`)||r.includes(`domain`)||r.includes(`site`)))return null;let a=null,o=0;for(let t of e){if(t.tagName!==`INPUT`&&t.tagName!==`TEXTAREA`)continue;let e=(t.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`checkbox`,`radio`].includes(e))continue;let n=0;(e===`url`||e===`text`||e===`search`)&&(n+=45);let r=[t.name,t.id,t.placeholder,fD(t),t.getAttribute(`aria-label`),t.getAttribute(`autocomplete`)].filter(Boolean).join(` `).toLowerCase();/(website|url|domain|site\s*url)/.test(r)&&(n+=55),n>o&&(o=n,a=t)}return!a||o<42?null:a}function SD(e){let t=String(e??``).trim();return t?/^https?:\/\//i.test(t)?!0:/\.\w{2,}(\/|\s|$)/.test(t):!1}function CD(e){let t=String(e??``).toLowerCase().trim();return t?!!(t===`url`||t===`website`||t===`website url`||t===`website_url`||t===`enter website url`||t.includes(`website`)||t.includes(`domain`)||/(enter\s+website|site\s*url|page\s*url)/.test(t)):!1}function wD(e){if(!e||e.tagName!==`INPUT`&&e.tagName!==`TEXTAREA`)return!1;let t=(e.type||``).toLowerCase();return![`hidden`,`submit`,`button`,`checkbox`,`radio`,`file`].includes(t)}function TD(e){if(!wD(e))return!1;let t=(e.name||``).toLowerCase(),n=(e.id||``).toLowerCase(),r=[e.name,e.id,e.placeholder,fD(e),e.getAttribute(`aria-label`)].filter(Boolean).join(` `).toLowerCase();return t===`url`||n===`url-input`||n.endsWith(`-url-input`)||/(website\s*url|enter\s+website|site\s*url)/.test(r)||/(website|domain)/.test(r)&&/(url|site)/.test(r)}function ED(e,t,n){let r=String(t??``),i=String(n??``),a=kD(e,r)||bD(e,r)||xD(e,r,i);if(!a)return[];let o=new Set([a]);if(SD(i)&&CD(r))for(let t of e)t!==a&&TD(t)&&o.add(t);let s=Array.from(o);return s.sort((e,t)=>{if(e===t)return 0;let n=e.compareDocumentPosition(t);return n&Node.DOCUMENT_POSITION_FOLLOWING?-1:n&Node.DOCUMENT_POSITION_PRECEDING?1:0}),s}function DD(e,t){try{if(!e?.getBoundingClientRect||!t?.getBoundingClientRect)return 1/0;let n=e.getBoundingClientRect(),r=t.getBoundingClientRect(),i={x:n.left+n.width/2,y:n.top+n.height/2},a={x:r.left+r.width/2,y:r.top+r.height/2};return Math.hypot(i.x-a.x,i.y-a.y)}catch{return 1/0}}function OD(e){if(!e||typeof e!=`string`)return null;let t=null;return uD(n=>{try{let r=n.getElementById(e);r&&!cD(r)&&r.matches?.(`input, select, textarea`)&&(t=r)}catch{}}),t}function kD(e,t){let n=String(t??``).trim();if(!n)return null;let r=n.match(/^name:\s*([\w.-]+)$/i);if(r){let t=r[1];for(let n of e)if(n.name===t)return n}let i=n.match(/^id:\s*([\w.-]+)$/i);if(i){let e=OD(i[1]);if(e)return e}let a=n.startsWith(`#`)?n.slice(1):n;if(/^[\w-]+$/.test(a)){let e=OD(a);if(e)return e}let o=n.toLowerCase().replace(/\s+/g,` `);if(o===`url`||o===`website`||o===`website url`||o===`website_url`||o===`enter website url`)for(let t of e){let e=(t.name||``).toLowerCase(),n=(t.id||``).toLowerCase();if(e===`url`||n===`url-input`||n.endsWith(`-url-input`))return t}return null}function AD(e,t){let n=String(t||``).toLowerCase().trim();if(!n)return 0;let r=[e.textContent,e.value,e.getAttribute(`aria-label`),e.getAttribute(`title`)].filter(Boolean).join(` `).toLowerCase().replace(/\s+/g,` `);if(r.includes(n))return 100;let i=n.split(/\s+/).filter(e=>e.length>1);if(!i.length)return 0;let a=0;for(let e of i)r.includes(e)&&(a+=1);return a/i.length*92}function jD(e,t){let n=[];uD(e=>{n.push(...Array.from(e.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(cD(e)||e.disabled)return!1;try{let t=lD(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))});let r=0,i=n.map(t=>({el:t,s:AD(t,e)}));for(let{s:e}of i)e>r&&(r=e);if(r<36)return null;let a=i.filter(({s:e})=>e===r).map(({el:e})=>e);if(a.length===1)return a[0];let o=Array.isArray(t)?t.filter(e=>e&&e.isConnected):[];if(o.length){let e=a[0],t=1/0;for(let n of a)for(let r of o){let i=DD(n,r);i<t&&(t=i,e=n)}return e}return a[0]}function MD(e){if(e==null)return{};if(typeof e==`string`){let t=e.trim();if(!t)return{};try{return JSON.parse(t)}catch{return{url:t}}}return e}function ND(e){let t=MD(e);if(Array.isArray(t)&&t.length>0){let e=t[0];if(e?.field_key!=null||e?.fieldKey!=null)return t.map(e=>({field_key:e.field_key??e.fieldKey,value:e.value}))}if(!t||typeof t!=`object`)return[];let n=t.fields??t.Fields??t.field_list??t.fieldList??t.data?.fields;if(typeof n==`string`)try{n=JSON.parse(n)}catch{n=null}n&&!Array.isArray(n)&&typeof n==`object`&&(n=Object.values(n)),(!n||n.length===0)&&(t.field_key!=null||t.fieldKey!=null)&&t.value!=null&&(n=[{field_key:t.field_key??t.fieldKey,value:t.value}]);let r=t.website_url??t.websiteUrl??t.url??t.website??t.domain??t.site_url??t.siteUrl;return(!n||n.length===0)&&r!=null&&String(r).trim()&&(n=[{field_key:t.field_key??t.fieldKey??`url`,value:String(r).trim()}]),Array.isArray(n)?n.map(e=>({field_key:e?.field_key??e?.fieldKey,value:e?.value??e?.Value})):[]}function PD(e){if(!e||typeof e!=`string`)return[];let t=e.trim();if(!t||/\b[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}\b/i.test(t))return[];let n=t.match(/https?:\/\/[^\s<>"']+/i);if(n)return[{field_key:`url`,value:n[0].replace(/[.,;:)]+$/,``)}];let r=t.match(/\b(?:[\w-]+\.)+[a-z]{2,}\b/i);if(r){let e=r[0].replace(/[.,;:)]+$/,``);return/^https?:/i.test(e)||(e=`https://${e}`),[{field_key:`url`,value:e}]}return[]}function FD(e){if(!e||typeof e!=`string`)return[];let t=e.trim();if(!t)return[];let n=[],r=new Set,i=/\b([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,})\b/i,a=(e,t)=>{let i=String(t??``).trim().replace(/^["']|["']$/g,``);if(!i||i.length>800)return;let a=`${e}\0${i}`;r.has(a)||(r.add(a),n.push({field_key:e,value:i}))},o=t.match(/^\s*([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,})\s*$/i);if(o)return a(`Email Address`,o[1]),n;let s=t.match(/\b(?:please\s+)?(?:enter|type|put)\s+(.+?)\s+in(?:to)?\s+(?:the\s+)?(?:full\s*name|full\s*name\s*field|name\s*field)\b/i);if(s&&a(`Full Name`,s[1]),s=t.match(/\bfull\s*name,?\s*(?:please\s+)?(?:enter|type|put)\s+(.+?)(?:\.|$|!|\?)/i),s&&a(`Full Name`,s[1]),s=t.match(/\bfull\s*name\s*(?:is|:|please\s+enter|-)\s*(.+?)(?:\.|$|(?=\s+(?:and|my\s+email|email|message))\b)/i),s&&a(`Full Name`,s[1]),s=t.match(/\b(.+?)\s+for\s+(?:the\s+)?full\s*name\b/i),s){let e=s[1].trim();e.length>1&&e.length<120&&!/@/.test(e)&&a(`Full Name`,e)}if(s=t.match(/\b(?:email|e-mail)(?:\s*address)?\s*(?:is|:|please\s+use|enter|-)\s*([^\s@]+@[^\s@]+\.[^\s,]+)/i),s&&a(`Email Address`,s[1]),s=t.match(/\b(?:enter|type|put)\s+([^\s@]+@[^\s@]+\.[^\s,]+)\s+in(?:to)?\s+(?:the\s+)?(?:email|e-mail)/i),s&&a(`Email Address`,s[1]),s=t.match(/\b(?:message|comment)\s*(?:is|:|please\s+enter|-)\s*(.+)$/is),s){let e=s[1].trim();e.length>0&&a(`Message`,e)}if(!n.some(e=>/email/i.test(String(e.field_key)))){let e=t.match(i);if(e){let r=t.replace(e[0],``).trim().replace(/^(please|it's|it is|use|is|my email is|e-?mail is)\s*/i,``).replace(/[.,;:!?]+$/,``).trim();if(t.length<=96&&r.length<=36)return a(`Email Address`,e[1]),n}}if(n.length===0){let e=t.split(/\s+/).filter(Boolean).length,n=/[.!?]/.test(t)||e>=6||t.length>=24&&e>=5||t.length>=42,r=/^[A-Z][a-z]+\s+[A-Z][a-z]+$/.test(t.trim());n&&t.length>=16&&!i.test(t)&&!r&&a(`Message`,t)}return n}function ID(e){if(!e||typeof e!=`object`)return null;let t=e.url??e.target_url??e.page_url??e.pageUrl??e.link??e.href??e.path;return t==null?null:String(t).trim()||null}function LD(e){if(!e||typeof e!=`object`)return null;let t=e.query??e.q??e.search??e.text??e.keywords;return t==null?null:String(t).trim()||null}function RD(e,t,n){if(!n?.skipScroll)try{e.scrollIntoView({block:`center`,inline:`nearest`})}catch{try{e.scrollIntoView(!0)}catch{}}try{e.focus({preventScroll:!0})}catch{try{e.focus()}catch{}}let r=e.tagName,i=(e.type||``).toLowerCase();if(r===`SELECT`)return e.value=String(t),e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0})),!0;if(i===`checkbox`||i===`radio`)return e.checked=[`1`,`true`,`yes`,`on`].includes(String(t).toLowerCase().trim()),e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0})),!0;let a=String(t);if(r===`INPUT`||r===`TEXTAREA`){let t=e.ownerDocument?.defaultView||window,n=r===`TEXTAREA`?t.HTMLTextAreaElement.prototype:t.HTMLInputElement.prototype,i=Object.getOwnPropertyDescriptor(n,`value`);i?.set?i.set.call(e,a):e.value=a}else e.value=a;let o={bubbles:!0,cancelable:!0,composed:!0};try{e.dispatchEvent(new InputEvent(`input`,{...o,inputType:`insertText`,data:a}))}catch{e.dispatchEvent(new Event(`input`,o))}e.dispatchEvent(new Event(`change`,o));try{queueMicrotask(()=>{try{e.dispatchEvent(new Event(`input`,o)),e.dispatchEvent(new Event(`change`,o))}catch{}})}catch{}return!0}function zD(){let e={};document.querySelectorAll(`h1, h2, h3, h4, h5, h6`).forEach(t=>{if(t.id)return;let n=t.textContent.trim();if(!n)return;let r=n.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``).substring(0,60);if(e[r]){let t=2;for(;e[r+`-`+t];)t++;r=r+`-`+t}e[r]=!0,t.id=r})}function BD(e){let t=e.siteId||null,n=(e.apiBaseUrl||``).replace(/\/$/,``),r=typeof e.getLastUserVoiceText==`function`?e.getLastUserVoiceText:null,i=[],a={flowengage_navigate:async n=>{$(`flowengage_navigate ▶ raw parameters:`,n);let r=MD(n),i=ID(r),a=r.section_text??r.sectionText??r.section;if($(`flowengage_navigate · coerced:`,{url:i,sectionText:a}),!i){let e=`Missing url: pass a string url, path like /pricing, or JSON with a url field.`;return $(`flowengage_navigate ✖`,e),e}if(!await cn(i,{siteId:t,apiBaseUrl:e.apiBaseUrl})){let e=`That page is not available in the site index; answer without navigating.`;return $(`flowengage_navigate ✖ blocked`,e),e}try{if(VE(`Navigating to ${i}...`,{spinner:!0}),KE(),kE(),IE(),$(`flowengage_navigate → shadowNavigate`,i),await un(i),await oD(400),zD(),a&&typeof a==`string`){let e=nn(null,a);e&&EE(()=>FE(e)),$(`flowengage_navigate · highlight`,{sectionText:a,found:!!e})}let e=`OK_NAVIGATION ${i}`;return $(`flowengage_navigate ✓`,e),VE(`Navigation complete`,{spinner:!1,icon:`✅`,duration:1200}),e}catch(e){let t=`Navigation error: ${e?.message||String(e)}`;return $(`flowengage_navigate ✖`,t),VE(`Navigation failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{qE(),HE(900)}},flowengage_highlight:async e=>{$(`flowengage_highlight ▶`,e);let t=MD(e),n=t?.section_id||t?.sectionId,r=t?.section_text||t?.sectionText,i=nn(n||null,r||null);return i?(EE(()=>FE(i)),$(`flowengage_highlight ✓ (enqueued)`),`Highlighted the section.`):($(`flowengage_highlight ✖ no element`),`Could not find that section on the page.`)},flowengage_read_content:async e=>{$(`flowengage_read_content ▶`,e);let t=MD(e),n=t?.section_text||t?.sectionText||``;try{let e=``;if(n){let t=nn(null,n);if(!t)return`Could not find section "${n}" on the page.`;let r=[t.textContent.trim()],i=t.nextElementSibling;for(;i&&!/^H[1-3]$/i.test(i.tagName);){let e=i.textContent.trim();e&&r.push(e),i=i.nextElementSibling}e=r.join(`
605
- `)}else{let t=(document.querySelector(`main`)||document.querySelector(`article`)||document.querySelector(`[role="main"]`)||document.querySelector(`#content`)||document.querySelector(`.content`)||document.body).cloneNode(!0);t.querySelectorAll(`nav, footer, header, aside, script, style, noscript, .nav, .footer, .header, .sidebar`).forEach(e=>e.remove()),e=t.textContent.replace(/\s+/g,` `).trim()}return e.length>8e3&&(e=e.substring(0,8e3)+`... (truncated)`),$(`flowengage_read_content ✓`,`${e.length} chars`),e||`No readable content found on this page.`}catch(e){return $(`flowengage_read_content ✖`,e.message),`Could not read page content: ${e.message}`}},flowengage_search:async e=>{$(`flowengage_search ▶`,e);let r=LD(MD(e));if($(`flowengage_search · query:`,r,`siteId:`,t,`apiBase:`,n||`(empty)`),!r)return $(`flowengage_search ✖ missing query`),`Missing query parameter.`;if(!t)return $(`flowengage_search ✖ no siteId`),`Site is not configured for search.`;if(!n)return $(`flowengage_search ✖ no api base`),`API base URL is missing; cannot search.`;try{let e=`${n}/api/site-tools/search`;$(`flowengage_search → POST`,e);let i=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({siteId:t,query:r,currentUrl:typeof window<`u`?window.location.href:``})}),a=await i.json();if($(`flowengage_search · HTTP`,i.status,`success:`,a.success),!a.success){let e=a.error||`Search failed.`;return $(`flowengage_search ✖`,e),e}let o=a.results||[];return $(`flowengage_search ✓`,`${o.length} result(s)`,o.slice(0,3).map(e=>e?.url||e)),JSON.stringify(o)}catch(e){let t=`Search error: ${e.message||`network`}`;return $(`flowengage_search ✖`,t),t}},flowengage_page_content:async e=>{$(`flowengage_page_content ▶`,e);let r=MD(e),i=r?.url||r?.page_url||``;if($(`flowengage_page_content · url:`,i,`siteId:`,t,`apiBase:`,n||`(empty)`),!i)return $(`flowengage_page_content ✖ missing url`),`Missing url parameter.`;if(!t)return $(`flowengage_page_content ✖ no siteId`),`Site is not configured.`;if(!n)return $(`flowengage_page_content ✖ no api base`),`API base URL is missing; cannot fetch page content.`;try{let e=`${n}/api/site-tools/page-content`;$(`flowengage_page_content → POST`,e);let r=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({siteId:t,url:i})}),a=await r.json();if($(`flowengage_page_content · HTTP`,r.status,`success:`,a.success),!a.success){let e=a.error||`Failed to get page content.`;return $(`flowengage_page_content ✖`,e),e}return $(`flowengage_page_content ✓`,`title: ${a.title}`,`sections: ${(a.sections||[]).length}`,`content: ${(a.content||``).length} chars`),JSON.stringify({title:a.title,url:a.url,sections:a.sections,content:a.content})}catch(e){let t=`Page content error: ${e.message||`network`}`;return $(`flowengage_page_content ✖`,t),t}},flowengage_end_session:async()=>($(`flowengage_end_session ▶`),typeof e.requestEndSession==`function`&&e.requestEndSession(),`Voice session is ending.`),flowengage_list_forms:async()=>{let e=mD(),t=hD();return $(`flowengage_list_forms ✓`,`${e.length} field(s)`,`${t.length} button(s)`),JSON.stringify({fields:e,buttons:t,hint:`field_key: placeholder/label, name (e.g. url), id (e.g. url-input). If the page has two URL boxes, flowengage_fill_form sets all matching URL inputs. flowengage_click_button picks the Conduct Audit nearest the filled field when labels duplicate.`})},flowengage_fill_form:async e=>{try{$(`flowengage_fill_form ▶ raw:`,e),JE();let t=ND(e);if(!t.length&&r){let e=r(),n=PD(e);n.length?$(`flowengage_fill_form · inferred URL from last user utterance (model omitted usable fields):`,n):(n=FD(e),n.length&&$(`flowengage_fill_form · inferred contact fields from last user utterance (empty tool params):`,n)),n.length&&(t=n)}if($(`flowengage_fill_form · normalized fields:`,t),!t.length)return`No fields provided. Call flowengage_list_forms for field_key strings, then flowengage_fill_form with { "fields": [ { "field_key": "<label or placeholder from list>", "value": "<user value>" } ] }. Never use empty {}. Pass the value the user just said (email, message, name, URL) in fields.`;let n=[];for(let e of t){let t=e?.field_key??e?.fieldKey,r=e?.value;if(t==null||r==null)continue;VE(`Filling ${String(t)}...`,{spinner:!0});let a=pD(),o=ED(a,String(t),r);if(o.length){for(let[e,t]of o.entries())YE(t),await tD(t),RD(t,r,{skipScroll:e>0}),XE(t),await oD(120);i=o,n.push(String(t));continue}let s=kD(a,String(t));s||=bD(a,String(t)),s||=xD(a,String(t),r),s&&(YE(s),await tD(s),RD(s,r),XE(s),await oD(120),i=[s],n.push(String(t)))}if(!n.length)return $(`flowengage_fill_form ✖ no matches`),`Could not match any fields. Call flowengage_list_forms and use field_key values that match placeholder, label, name, or id (e.g. Enter Website URL). Ensure the form is on the page, not the chat panel.`;let a=`OK_FILLED: ${n.join(`, `)}`;return $(`flowengage_fill_form ✓`,a),VE(`Form filled`,{spinner:!1,icon:`✅`,duration:1100}),a}catch(e){let t=`flowengage_fill_form error: ${e?.message||String(e)}`;return $(`flowengage_fill_form ✖`,t),VE(`Failed to fill form`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{nD(),JE(),HE(700)}},flowengage_click_button:async e=>{let t=MD(e),n=(t.button_text??t.buttonText??t.text??``).trim();if($(`flowengage_click_button ▶`,n),!n)return`Missing button_text: pass the visible label, e.g. Conduct Audit.`;let r=jD(n,i);if(!r)return $(`flowengage_click_button ✖ no match`),`Could not find a button matching "${n}". Call flowengage_list_forms to see button texts.`;try{VE(`Clicking ${n}...`,{spinner:!0});try{r.scrollIntoView({block:`center`,inline:`nearest`})}catch{r.scrollIntoView(!0)}await tD(r),r.focus?.(),await rD(r),iD(r),r.click();let e=(r.textContent||r.value||r.getAttribute(`aria-label`)||``).trim().slice(0,80)||`button`,t=`OK_CLICK ${e}`;return $(`flowengage_click_button ✓`,t),VE(`Clicked ${e}`,{spinner:!1,icon:`✅`,duration:1200}),t}catch(e){let t=`Click failed: ${e?.message||String(e)}`;return $(`flowengage_click_button ✖`,t),VE(`Click failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{nD(),HE(700)}}};return{...a,navigateToPage:a.flowengage_navigate,highlightOnPage:a.flowengage_highlight,searchSiteContent:a.flowengage_search,getPageContent:a.flowengage_page_content,endVoiceSession:a.flowengage_end_session,listPageForms:a.flowengage_list_forms,fillFormFields:a.flowengage_fill_form,clickPageButton:a.flowengage_click_button}}function VD(e){return!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,async n=>{let r=Yt();r?console.log(`[FlowEngage:voice-tool] ▶`,e,n):console.info(`[FlowEngage] voice tool » ${e}`);let i;try{i=await t(n)}catch(t){let n=`Tool error: ${t?.message||String(t)}`;return console.error(`[FlowEngage] voice tool ${e} threw:`,t),n}let a=typeof i==`string`?i.length>220?`${i.slice(0,220)}…`:i:String(i);return r?console.log(`[FlowEngage:voice-tool] ◀`,e,a):console.info(`[FlowEngage] voice tool « ${e}:`,a),i}]))}var HD={blue:`#135bd8`,red:`#ef334b`,yellow:`#ffbd2e`,dark:`#0d1b2a`,highlight:`rgba(255,255,255,0.9)`,green:`#10b981`};function UD(e){if(!Array.isArray(e)||e.length<2)return`linear-gradient(145deg, #dce8f022 0%, #e8dff522 45%, #f5e0e022 100%), #f7f8fa`;let[t,n,r]=e;return e.length>=3&&r?[`radial-gradient(ellipse 80% 70% at -10% 50%, ${t}1a 0%, transparent 70%)`,`radial-gradient(ellipse 70% 80% at 110% 30%, ${n}1a 0%, transparent 70%)`,`radial-gradient(ellipse 80% 60% at 50% 110%, ${r}1a 0%, transparent 70%)`,`#f7f8fa`].join(`, `):[`radial-gradient(ellipse 80% 100% at -10% 50%, ${t}1a 0%, transparent 70%)`,`radial-gradient(ellipse 80% 100% at 110% 50%, ${n}1a 0%, transparent 70%)`,`#f7f8fa`].join(`, `)}function WD(e){if(!e||typeof e!=`string`)return`#1a1a1a`;let t=e.replace(`#`,``),n=t.length===3?t.split(``).map(e=>e+e).join(``):t,r=parseInt(n.slice(0,2),16)/255,i=parseInt(n.slice(2,4),16)/255,a=parseInt(n.slice(4,6),16)/255,o=e=>e<=.04045?e/12.92:((e+.055)/1.055)**2.4;return .2126*o(r)+.7152*o(i)+.0722*o(a)>.179?`#1a1a1a`:`#ffffff`}function GD({logo:e,style:t}){if(!e)return null;if(typeof e==`string`)return(0,f.jsx)(`img`,{src:e,alt:``,style:{objectFit:`contain`,flexShrink:0,display:`block`,...t}});let n=typeof e==`function`?d.default.createElement(e):d.default.isValidElement(e)?e:null;return n?(0,f.jsx)(`span`,{className:`fe-logo-slot`,style:{display:`inline-flex`,alignItems:`center`,flexShrink:0,overflow:`hidden`,...t},children:n}):null}function KD({title:e}){return(0,f.jsx)(`div`,{style:{width:`100%`,height:`100%`,borderRadius:`16px`,background:`linear-gradient(135deg, rgba(59,130,246,0.16) 0%, rgba(59,130,246,0.08) 100%)`,color:`#2563eb`,display:`flex`,alignItems:`center`,justifyContent:`center`,fontSize:`18px`,fontWeight:700,letterSpacing:`-0.03em`},children:String(e||`FE`).split(/\s+/).filter(Boolean).slice(0,2).map(e=>e[0]?.toUpperCase()||``).join(``)||`FE`})}function qD(e,t){let n=(t||``).trim();return n?!!(/\b(let'?s|let us)\s+(end|stop|finish|wrap up|close)\s+(the\s+)?(voice\s+)?(session|call|chat)\b/i.test(n)||/\bend\s+(this\s+)?(the\s+)?(voice\s+)?(session|call|chat)\b/i.test(n)||/\b(hang\s+up|disconnect)\b/i.test(n)||/\b(that'?s all|we'?re done)\b/i.test(n)||e===`bot`&&(/\b(I'?ll|I will|Let me|I can|I'?m going to)\s+(end|close)\s+(the\s+)?(voice\s+)?(session|call)\b/i.test(n)||/\b(ending|closing)\s+(the\s+)?(voice\s+)?session\b|\bvoice\s+session\s+(is\s+)?(now\s+)?(ended|over|closing)\b/i.test(n)||/\b(session|call)\s+(is\s+)?(now\s+)?(ended|over)\b/i.test(n)||/\bwe\s+can\s+end\s+(the\s+)?(session|call)?\s*(here|now)\b/i.test(n)||/\b(wrapping\s+up|signing\s+off)\b/i.test(n))||/^(goodbye|bye|that'?s all|we'?re done|hang up|disconnect)\b/i.test(n)):!1}function JD({orbColors:e,...t}){return(0,f.jsx)(SE,{colors:e,...t})}function YD({copy:e,orbColors:t,primaryColor:n,onYes:r,onLater:i}){let a=n||HD.green,o=WD(a);return(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(`div`,{style:{position:`fixed`,inset:0,background:`rgba(0,0,0,0.5)`,zIndex:-1,animation:`fe-orb-fade-in 0.4s ease`}}),(0,f.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`18px`,animation:`fe-orb-slide-up 0.42s cubic-bezier(0.16,1,0.3,1)`},children:[(0,f.jsxs)(`div`,{style:{flex:1},children:[(0,f.jsx)(`p`,{style:{margin:`0 0 16px`,fontSize:`18px`,fontWeight:700,color:`white`,lineHeight:1.4,maxWidth:`210px`,textShadow:`0 1px 4px rgba(0,0,0,0.35)`},children:e.entryPrompt}),(0,f.jsxs)(`div`,{style:{display:`flex`,gap:`10px`,flexWrap:`wrap`},children:[(0,f.jsx)(`button`,{onClick:r,style:{padding:`10px 28px`,borderRadius:`999px`,background:a,color:o,fontWeight:700,fontSize:`15px`,border:`none`,cursor:`pointer`,boxShadow:`0 4px 16px ${a}66`,transition:`transform 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.04)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`},children:e.yesLabel}),(0,f.jsx)(`button`,{onClick:i,style:{padding:`10px 22px`,borderRadius:`999px`,background:`transparent`,color:`white`,fontWeight:600,fontSize:`15px`,border:`2px solid rgba(255,255,255,0.55)`,cursor:`pointer`,transition:`border-color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.borderColor=`rgba(255,255,255,0.9)`},onMouseLeave:e=>{e.currentTarget.style.borderColor=`rgba(255,255,255,0.55)`},children:e.laterLabel})]})]}),(0,f.jsx)(JD,{size:94,orbColors:t})]})]})}function XD({copy:e,orbColors:t,primaryColor:n,onVoice:r,onText:i,onClose:a}){let o=n||HD.green,s=WD(o);return(0,f.jsxs)(op.div,{initial:{scale:50/300,borderRadius:`50%`},animate:{scale:1,borderRadius:`24px`},transition:{type:`spring`,stiffness:260,damping:26},style:{transformOrigin:`bottom right`,background:`white`,padding:`28px 28px 24px`,width:`300px`,display:`flex`,flexDirection:`column`,alignItems:`center`,gap:`20px`,boxShadow:`0 20px 60px rgba(0,0,0,0.2)`,position:`relative`,overflow:`hidden`},children:[(0,f.jsx)(`button`,{onClick:a,style:{position:`absolute`,top:`14px`,right:`14px`,background:`none`,border:`none`,cursor:`pointer`,color:`#9ca3af`,padding:`4px`,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`50%`,transition:`color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.color=`#374151`},onMouseLeave:e=>{e.currentTarget.style.color=`#9ca3af`},children:(0,f.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,f.jsx)(`polyline`,{points:`6 9 12 15 18 9`})})}),(0,f.jsx)(JD,{size:82,orbColors:t}),(0,f.jsx)(`p`,{style:{margin:0,fontSize:`17px`,fontWeight:600,color:`#111827`,textAlign:`center`,lineHeight:1.4},children:e.connectionTitle}),(0,f.jsxs)(`div`,{style:{display:`flex`,gap:`12px`,width:`100%`},children:[(0,f.jsx)(`button`,{onClick:r,style:{flex:1,padding:`12px`,borderRadius:`999px`,background:o,color:s,fontWeight:700,fontSize:`15px`,border:`none`,cursor:`pointer`,transition:`transform 0.15s ease`,boxShadow:`0 4px 12px ${o}55`},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.03)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`},children:e.voiceLabel}),(0,f.jsx)(`button`,{onClick:i,style:{flex:1,padding:`12px`,borderRadius:`999px`,background:`transparent`,color:`#111827`,fontWeight:600,fontSize:`15px`,border:`2px solid #d1d5db`,cursor:`pointer`,transition:`border-color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.borderColor=`#6b7280`},onMouseLeave:e=>{e.currentTarget.style.borderColor=`#d1d5db`},children:e.textLabel})]})]})}function ZD({orbColors:e,onEnterChat:t,onEndChat:n,agentId:r,siteId:i,apiBaseUrl:a,historyRef:o,onMessageSync:s}){let[c,l]=(0,d.useState)(`idle`),[u,p]=(0,d.useState)(!1),[m,h]=(0,d.useState)(!1),g=(0,d.useRef)(null),_=(0,d.useRef)(``),v=(0,d.useRef)(async()=>{}),y=(0,d.useRef)(!1),b=(0,d.useRef)(!1),x=(0,d.useRef)(!1),S=(0,d.useRef)(!1),ee=(0,d.useRef)(`minimized`),te=(0,d.useRef)(null),C=(0,d.useCallback)((e=`minimized`)=>{ee.current=e,S.current=!0,queueMicrotask(()=>{y.current||(y.current=!0,v.current?.())})},[o]),ne=(0,d.useCallback)(async e=>{S.current=!0;try{await g.current?.endSession?.()}catch{}g.current=null,l(`idle`),p(!1),y.current=!1,typeof s==`function`&&await s(o.current),e?.()},[o,s]);return v.current=()=>ne(ee.current===`chat`?t:n),(0,d.useEffect)(()=>{b.current=u},[u]),(0,d.useEffect)(()=>{let e=!1,n=null;return(async()=>{if(!r){l(`error`);return}try{if((await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(e=>e.stop()),e)return;o.current=[],_.current=``,y.current=!1,x.current=!1,S.current=!1,ee.current=`minimized`;let t=VD(BD({siteId:i||null,apiBaseUrl:a||null,getLastUserVoiceText:()=>_.current,requestEndSession:()=>{C()}})),s=await YT.startSession({agentId:r,clientTools:t,onUnhandledClientToolCall:e=>console.error(`[FlowEngage] Unhandled tool:`,e?.tool_name),onModeChange:({mode:t})=>{e||l(t===`speaking`?`speaking`:`listening`)},onMessage:t=>{if(e)return;let n=t.role===`user`?`user`:`bot`,r=t.message||t.text||t.content||``;r&&(n===`user`&&(_.current=r),o.current=[...o.current,{sender:n,message:r,timestamp:new Date().toISOString()}],qD(n,r)&&C(`minimized`))},onError:t=>{if(!e&&!S.current&&!x.current){x.current=!0,console.error(`[FlowEngageVoiceCall] session:error`,{message:t?.message,name:t?.name,raw:t});try{g.current?.setMicMuted?.(!0)}catch{}p(!0),l(`error`),C(`chat`)}},onDisconnect:()=>{if(!e&&!S.current&&!x.current){x.current=!0,console.warn(`[FlowEngageVoiceCall] session:disconnected`,{historyCount:o.current?.length||0,lastUserText:_.current||``,wasMuted:b.current});try{g.current?.setMicMuted?.(!0)}catch{}p(!0),C(`chat`)}}});if(e){s.endSession().catch(()=>{});return}n=s,g.current=s,l(`listening`);try{let e=typeof window<`u`?window.location.href:``,n=`[]`;try{n=await t.list_page_forms()}catch{}s.sendContextualUpdate(`Page: ${e}. SiteId: ${i||`unknown`}. Forms: ${n}. Voice: call end_voice_session or say you are ending the session to stop.`)}catch{}}catch(n){e||(console.error(`[FlowEngage] startSession failed`,n),l(`error`),ee.current=`chat`,window.setTimeout(()=>{e||t?.()},0))}})(),()=>{e=!0,S.current=!0,(n||g.current)?.endSession?.().catch(()=>{})}},[r,i,a,C]),(0,d.useEffect)(()=>{if(!m)return;let e=e=>{te.current&&!te.current.contains(e.target)&&h(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[m]),(0,f.jsx)(f.Fragment,{children:(0,f.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,alignItems:`center`,gap:`14px`,animation:`fe-orb-slide-up 0.42s cubic-bezier(0.16,1,0.3,1)`},children:[(0,f.jsxs)(`div`,{style:{position:`relative`},children:[c===`listening`&&(0,f.jsx)(`span`,{style:{position:`absolute`,right:`100%`,marginRight:`18px`,top:`50%`,transform:`translateY(-50%)`,color:`white`,fontSize:`18px`,fontWeight:600,letterSpacing:`0.01em`,textShadow:`0 2px 4px rgba(0,0,0,0.4)`,whiteSpace:`nowrap`},children:`Listening...`}),(0,f.jsx)(JD,{size:94,voiceState:c,isMuted:u,orbColors:e})]}),c===`error`&&(0,f.jsx)(`span`,{style:{color:`#f87171`,fontSize:`13px`,fontWeight:500},children:`Could not start voice session.`}),(0,f.jsxs)(`div`,{style:{display:`flex`,gap:`12px`,alignItems:`center`},children:[(0,f.jsx)(`button`,{onClick:async()=>{if(g.current)try{u?(await g.current.setMicMuted?.(!1),p(!1)):(await g.current.setMicMuted?.(!0),p(!0))}catch{}},title:u?`Unmute`:`Mute`,style:{width:`44px`,height:`44px`,borderRadius:`50%`,background:u?`#7f1d1d`:`#1f2937`,border:u?`1.5px solid #ef4444`:`1.5px solid #4b5563`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:u?`#f87171`:`white`,transition:`all 0.2s ease`,boxShadow:`0 2px 8px rgba(0,0,0,0.4)`},children:u?(0,f.jsxs)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`line`,{x1:`1`,y1:`1`,x2:`23`,y2:`23`}),(0,f.jsx)(`path`,{d:`M9 9v3a3 3 0 005.12 2.12M15 9.34V4a3 3 0 00-5.94-.6`}),(0,f.jsx)(`path`,{d:`M17 16.95A7 7 0 015 12v-2m14 0v2a7 7 0 01-.11 1.23`}),(0,f.jsx)(`line`,{x1:`12`,y1:`19`,x2:`12`,y2:`23`}),(0,f.jsx)(`line`,{x1:`8`,y1:`23`,x2:`16`,y2:`23`})]}):(0,f.jsxs)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`path`,{d:`M12 1a4 4 0 014 4v6a4 4 0 01-8 0V5a4 4 0 014-4z`,fill:`currentColor`,stroke:`none`}),(0,f.jsx)(`path`,{d:`M19 10a7 7 0 01-14 0M12 19v4M8 23h8`})]})}),(0,f.jsxs)(`div`,{style:{position:`relative`,isolation:`isolate`,zIndex:10},ref:te,children:[(0,f.jsx)(`button`,{onClick:()=>h(e=>!e),style:{width:`44px`,height:`44px`,borderRadius:`50%`,background:`#1f2937`,border:`1.5px solid #4b5563`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:`white`,transition:`background 0.2s ease`,boxShadow:`0 2px 8px rgba(0,0,0,0.4)`},children:(0,f.jsxs)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`currentColor`,children:[(0,f.jsx)(`circle`,{cx:`12`,cy:`5`,r:`1.8`}),(0,f.jsx)(`circle`,{cx:`12`,cy:`12`,r:`1.8`}),(0,f.jsx)(`circle`,{cx:`12`,cy:`19`,r:`1.8`})]})}),m&&(0,f.jsxs)(`div`,{style:{position:`absolute`,bottom:`54px`,right:0,zIndex:9999,background:`rgba(15,22,36,0.96)`,backdropFilter:`blur(14px)`,WebkitBackdropFilter:`blur(14px)`,borderRadius:`16px`,overflow:`hidden`,boxShadow:`0 10px 40px rgba(0,0,0,0.45)`,minWidth:`210px`,border:`1px solid rgba(255,255,255,0.07)`,animation:`fe-orb-fade-in 0.18s ease`},children:[(0,f.jsxs)(`button`,{onClick:()=>{h(!1),ee.current=`chat`,ne(t)},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,f.jsx)(`path`,{d:`M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z`})}),`Enter Chat Mode`]}),(0,f.jsx)(`div`,{style:{height:`1px`,background:`rgba(255,255,255,0.07)`,margin:`0 14px`}}),(0,f.jsxs)(`button`,{onClick:()=>{h(!1),ee.current=`minimized`,ne(n)},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`#f87171`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(248,113,113,0.1)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`path`,{d:`M10.68 13.31a16 16 0 003.41 2.6l1.27-1.27a2 2 0 012.11-.45 12.84 12.84 0 002.81.7 2 2 0 011.72 2v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07A19.42 19.42 0 013.07 8.62 19.79 19.79 0 01.1 2 2 2 0 012.11 0h3a2 2 0 012 1.72c.127.96.361 1.903.7 2.81a2 2 0 01-.45 2.11L6.18 7.84`}),(0,f.jsx)(`line`,{x1:`23`,y1:`1`,x2:`1`,y2:`23`})]}),`End Conversation`]})]})]})]})]})})}function QD({orbColors:e}){return(0,f.jsx)(`div`,{style:{flexShrink:0,width:`36px`,height:`36px`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:(0,f.jsx)(JD,{size:36,orbColors:e})})}var $D=()=>(0,f.jsx)(`div`,{style:{display:`flex`,marginBottom:`12px`,justifyContent:`flex-start`},children:(0,f.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`5px`,padding:`12px 16px`,borderRadius:`18px`,background:`#fff`,boxShadow:`0 2px 6px rgba(0,0,0,0.04)`},children:[0,1,2].map(e=>(0,f.jsx)(`span`,{style:{width:`7px`,height:`7px`,borderRadius:`50%`,background:`#9ca3af`,animation:`fe-dot-bounce 1.2s ease-in-out ${e*.2}s infinite`,display:`inline-block`}},e))})});function eO({copy:e,orbColors:t,primaryColor:n,chatBgGradient:r,logo:i,quickChatOptions:a,onQuickChatSelect:o,isMobile:s,chatHistory:c,isAiTyping:l,isAgentTyping:u,activeScreen:p,agentName:m,agentHeadshot:h,fallbackAgentName:g,input:_,setInput:v,onSubmit:y,isConversationEnded:b,isLoading:x,isRateLimited:S,rateLimitMessage:ee,requiresEmail:te,emailInput:C,setEmailInput:ne,emailError:re,replyContext:ie,setReplyContext:ae,webRTCError:oe,micError:se,setMicError:ce,dismissCallError:le,incomingCall:ue,rejectCall:de,acceptCall:fe,activeCallId:pe,callConnectionState:me,isCallMuted:he,toggleCallMute:ge,endWebRTCCall:_e,formatCallDuration:ve,callDurationSeconds:ye,onCollapse:be,onStartVoice:xe,showPoweredBy:Se}){let Ce=c.length>0,we=x||S||b,Te=!!(ue||pe),[Ee,De]=(0,d.useState)(!1),Oe=(0,d.useRef)(null);return(0,d.useEffect)(()=>{if(!Ee)return;let e=e=>{Oe.current&&!Oe.current.contains(e.target)&&De(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[Ee]),(0,f.jsxs)(`div`,{style:s?{"--flowengage-primary":n,"--flowengage-accent":n,position:`fixed`,inset:0,width:`100%`,height:`100dvh`,background:r,borderRadius:0,display:`flex`,flexDirection:`column`,overflow:`hidden`,animation:`fe-orb-slide-up 0.28s cubic-bezier(0.16,1,0.3,1)`}:{"--flowengage-primary":n,"--flowengage-accent":n,width:`min(390px, calc(100vw - 40px))`,height:`min(640px, calc(100vh - 120px))`,background:r,borderRadius:`22px`,boxShadow:`0 24px 64px rgba(0,0,0,0.18), 0 4px 16px rgba(0,0,0,0.08)`,display:`flex`,flexDirection:`column`,overflow:`hidden`,position:`relative`,animation:`fe-orb-slide-up 0.36s cubic-bezier(0.16,1,0.3,1)`},children:[(0,f.jsxs)(`div`,{style:{display:`grid`,gridTemplateColumns:`40px minmax(0, 1fr) 40px`,alignItems:`center`,columnGap:`14px`,padding:`16px 18px 14px`,background:`transparent`,flexShrink:0},children:[(0,f.jsx)(`button`,{onClick:be,style:{width:`40px`,height:`40px`,background:`none`,border:`none`,cursor:`pointer`,color:`#6b7280`,display:`flex`,alignItems:`center`,justifyContent:`center`,padding:`4px`,borderRadius:`10px`,transition:`color 0.15s ease`,flexShrink:0},onMouseEnter:e=>{e.currentTarget.style.color=`#111827`},onMouseLeave:e=>{e.currentTarget.style.color=`#6b7280`},children:(0,f.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,f.jsx)(`polyline`,{points:`6 9 12 15 18 9`})})}),(0,f.jsxs)(`div`,{style:{minWidth:0,maxWidth:s?`100%`:`250px`,width:`100%`,justifySelf:`center`,display:`grid`,gridTemplateColumns:`minmax(72px, 40%) minmax(0, 60%)`,alignItems:`center`,columnGap:`12px`},children:[(0,f.jsx)(`div`,{style:{minWidth:0,display:`flex`,alignItems:`center`,justifyContent:`center`,height:`40px`},children:i?(0,f.jsx)(GD,{logo:i,style:{height:`34px`,width:`100%`,maxWidth:`96px`}}):(0,f.jsx)(`div`,{style:{width:`40px`,height:`40px`,flexShrink:0},children:(0,f.jsx)(KD,{title:e.chatTitle})})}),(0,f.jsx)(`div`,{style:{minWidth:0,display:`flex`,alignItems:`center`},children:(0,f.jsx)(`span`,{style:{fontSize:`15px`,fontWeight:600,color:`#111827`,letterSpacing:`-0.01em`,lineHeight:1.2,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},title:e.chatTitle,children:e.chatTitle})})]}),(0,f.jsxs)(`div`,{style:{position:`relative`,isolation:`isolate`,zIndex:10},ref:Oe,children:[(0,f.jsx)(`button`,{type:`button`,onClick:()=>De(e=>!e),style:{width:`40px`,height:`40px`,background:`none`,border:`none`,cursor:`pointer`,color:`#6b7280`,display:`flex`,alignItems:`center`,justifyContent:`center`,padding:`4px`,borderRadius:`10px`,transition:`color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.color=`#111827`},onMouseLeave:e=>{e.currentTarget.style.color=`#6b7280`},"aria-label":`Chat options`,children:(0,f.jsxs)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`currentColor`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,f.jsx)(`circle`,{cx:`12`,cy:`5`,r:`1.5`}),(0,f.jsx)(`circle`,{cx:`12`,cy:`12`,r:`1.5`}),(0,f.jsx)(`circle`,{cx:`12`,cy:`19`,r:`1.5`})]})}),Ee&&(0,f.jsxs)(`div`,{style:{position:`absolute`,top:`34px`,right:0,background:`rgba(15,22,36,0.96)`,backdropFilter:`blur(14px)`,WebkitBackdropFilter:`blur(14px)`,borderRadius:`16px`,overflow:`hidden`,boxShadow:`0 10px 40px rgba(0,0,0,0.45)`,minWidth:`210px`,border:`1px solid rgba(255,255,255,0.07)`,animation:`fe-orb-fade-in 0.18s ease`},children:[(0,f.jsxs)(`button`,{type:`button`,onClick:()=>{De(!1),xe?.()},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`path`,{d:`M12 1a4 4 0 014 4v6a4 4 0 01-8 0V5a4 4 0 014-4z`}),(0,f.jsx)(`path`,{d:`M19 10a7 7 0 01-14 0M12 19v4M8 23h8`})]}),`Enter Voice Mode`]}),(0,f.jsx)(`div`,{style:{height:`1px`,background:`rgba(255,255,255,0.07)`,margin:`0 14px`}}),(0,f.jsxs)(`button`,{type:`button`,onClick:()=>{De(!1),be?.()},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`#f87171`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(248,113,113,0.1)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`path`,{d:`M10.68 13.31a16 16 0 003.41 2.6l1.27-1.27a2 2 0 012.11-.45 12.84 12.84 0 002.81.7 2 2 0 011.72 2v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07A19.42 19.42 0 013.07 8.62 19.79 19.79 0 01.1 2 2 2 0 012.11 0h3a2 2 0 012 1.72c.127.96.361 1.903.7 2.81a2 2 0 01-.45 2.11L6.18 7.84`}),(0,f.jsx)(`line`,{x1:`23`,y1:`1`,x2:`1`,y2:`23`})]}),`Close Conversation`]})]})]})]}),(0,f.jsx)(pE,{webRTCError:oe,micError:se,setMicError:ce,dismissCallError:le,incomingCall:ue,rejectCall:de,acceptCall:fe,activeCallId:pe,callConnectionState:me,formatCallDuration:ve,callDurationSeconds:ye,endWebRTCCall:_e,isCallMuted:he,toggleCallMute:ge,isAIVoiceActive:!1,currentCallAgentName:m||g,isRateLimited:S,rateLimitMessage:ee}),(0,f.jsx)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,minHeight:0,background:`transparent`},children:Ce?(0,f.jsx)(lE,{chatHistory:c,isAiTyping:l,isAgentTyping:u,setReplyContext:ae,TypingDots:$D,primaryColor:n,agentHeadshot:h,agentDisplayName:m||g,botAvatarNode:(0,f.jsx)(QD,{orbColors:t})}):(0,f.jsxs)(`div`,{style:{flex:1,overflowY:`auto`,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,gap:`22px`,padding:`28px 24px`},children:[(0,f.jsx)(JD,{size:94,orbColors:t}),(0,f.jsx)(`p`,{style:{margin:0,textAlign:`center`,fontSize:`16px`,color:`#374151`,lineHeight:1.55,maxWidth:`270px`},children:e.introGreeting}),a.length>0&&(0,f.jsx)(`div`,{style:{display:`flex`,flexWrap:`wrap`,gap:`8px`,justifyContent:`center`,maxWidth:`300px`},children:a.map(e=>(0,f.jsx)(`button`,{onClick:()=>o?.(e),style:{padding:`8px 16px`,borderRadius:`999px`,background:`white`,border:`1.5px solid ${n}33`,color:n||`#374151`,fontSize:`13px`,fontWeight:500,cursor:`pointer`,transition:`all 0.15s ease`,boxShadow:`0 1px 4px rgba(0,0,0,0.06)`},onMouseEnter:e=>{e.currentTarget.style.background=`${n}12`,e.currentTarget.style.borderColor=n},onMouseLeave:e=>{e.currentTarget.style.background=`white`,e.currentTarget.style.borderColor=`${n}33`},children:e.label||e.text},e.id))})]})}),(0,f.jsx)(`div`,{style:{background:`transparent`,flexShrink:0,position:`relative`,zIndex:1,padding:`12px 0 0`},children:(0,f.jsx)(uE,{input:_,setInput:v,onSubmit:y,isConversationEnded:b,callUiActive:Te,handleToggleVoice:xe,showVoiceToggle:p===`agent`,activeScreen:p,inputDisabled:we,replyContext:ie,clearReplyContext:()=>ae(null),requiresEmail:te,emailInput:C,setEmailInput:ne,emailError:re,inputPlaceholder:e.inputPlaceholder})}),Se&&(0,f.jsx)(`div`,{style:{flexShrink:0,textAlign:`center`,padding:`12px 20px 18px`,pointerEvents:`none`},children:(0,f.jsxs)(`span`,{style:{fontSize:`11px`,color:`#9ca3af`,letterSpacing:`0.01em`,userSelect:`none`},children:[`Powered by `,(0,f.jsx)(`strong`,{style:{fontWeight:600,color:`#6b7280`},children:`FlowEngage`})]})})]})}function tO(){let{status:e,runtimeConfig:t,resolvedConfig:n,chatHistory:r,isOpen:i,activeScreen:a,isHumanHandled:o,agentName:s,agentHeadshot:c,visitorEmail:l,isAgentTyping:u,isAiTyping:p,isLoading:m,isRateLimited:h,rateLimitMessage:g,isConversationEnded:_,incomingCall:v,activeCallId:y,callConnectionState:b,callConnectedAt:x,isCallMuted:S,webRTCError:ee,language:te,historyRef:C,onMessageSync:ne,sendMessage:re,openWidget:ie,captureVisitorEmail:ae,setVoiceMode:oe,endConversation:se,acceptCall:ce,rejectCall:le,endWebRTCCall:ue,toggleCallMute:de,dismissCallError:fe,startTyping:pe,stopTyping:me,updateTypingDraft:he}=Jt();(0,d.useEffect)(()=>{try{en()}catch{}},[]);let ge=t?.widgetSettings||{},_e=n?.widgetSettings||{},ve={...ge.branding||{},..._e.branding||{}},ye={...ge.theme||{},..._e.theme||{}},be=Array.isArray(ye.orbColors)&&ye.orbColors.length>0?ye.orbColors:null,xe=be?.[0]||ye.primaryColor||`#3B82F6`,Se=ye.position||`bottom-right`,Ce=ve.fallbackAgentName||`Agent`,we=UD(be??ye.chatBgColors),Te=ve.logo||ve.logoUrl||null,Ee=te||`en`,De=ge.recommendations?.[Ee]||[],Oe=(_e.recommendations?.[Ee]??De).filter(e=>String(e?.label??``).trim()).map((e,t)=>({id:e.key||`qr-${t}`,label:e.label,message:e.label,text:e.label})),ke=Array.isArray(ve.quickChatOptions)&&ve.quickChatOptions.length>0?ve.quickChatOptions:Oe,Ae=ve.hideWatermark===!0?!1:ve.showPoweredBy!==!1,je=ve.chatbotEnabled!==!1&&ye.chatbotEnabled!==!1,w=ge.greetings?.[te]||_e.greetings?.[te]||ve.introGreeting||`Hello, I'm here to help you know more about OpenSense Labs.`,T={entryPrompt:ve.entryPrompt||`Do you want to explore in a new way?`,yesLabel:ve.yesLabel||`Yes`,laterLabel:ve.laterLabel||`Later`,connectionTitle:ve.connectionTitle||`How would you like to connect?`,voiceLabel:ve.voiceLabel||`Voice`,textLabel:ve.textLabel||`Text`,chatTitle:ve.headerName||`Chat with FlowEngage`,introGreeting:w,inputPlaceholder:ve.inputPlaceholder||`Type your message`,analysingLabel:ve.analysingLabel||`analysing...`},Me=_e.elevenLabsAgentId||t?.elevenLabsAgentId||null,Ne=t?.siteId||n?.siteId||null,Pe=t?.apiBaseUrl||``,Fe=(0,d.useMemo)(()=>s&&String(s).trim()||t?.ownerName&&String(t.ownerName).trim()||t?.websiteName&&String(t.websiteName).trim()||`Agent`,[s,t?.ownerName,t?.websiteName]),Ie=c&&String(c).trim()||t?.ownerProfileImageUrl&&String(t.ownerProfileImageUrl).trim()||null,Le=r.some(e=>e.sender===`user`),Re=(0,d.useMemo)(()=>{let e=r.findIndex(e=>e.sender===`user`);return e===-1?!1:r.slice(e+1).some(e=>e.sender===`bot`||e.sender===`ai`||e.sender===`agent`)},[r]),ze=!l&&Le&&Re,Be=!!(_e._dashboardLivePreview||ge._dashboardLivePreview),[Ve,E]=(0,d.useState)(()=>Be?`text_chat`:`entry_prompt`),[D,O]=(0,d.useState)(``),[He,Ue]=(0,d.useState)(null),[We,Ge]=(0,d.useState)(l||``),[Ke,qe]=(0,d.useState)(``),[Je,Ye]=(0,d.useState)(0),[Xe,Ze]=(0,d.useState)(null),Qe=(0,d.useRef)(null),$e=(0,d.useRef)(!1);(0,d.useLayoutEffect)(()=>{e!==`ready`||$e.current||($e.current=!0,r.length>0&&E(`minimized_orb`))},[e,r]);let[et,tt]=(0,d.useState)(()=>typeof window<`u`&&window.matchMedia(`(max-width: 640px)`).matches);(0,d.useEffect)(()=>{let e=window.matchMedia(`(max-width: 640px)`),t=e=>tt(e.matches);return e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]),(0,d.useEffect)(()=>{Ge(l||``),l&&qe(``)},[l]),(0,d.useEffect)(()=>{if(!x||b!==`connected`){Ye(0);return}let e=()=>{let e=new Date(x).getTime();isNaN(e)||Ye(Math.max(0,Math.floor((Date.now()-e)/1e3)))};e();let t=window.setInterval(e,1e3);return()=>window.clearInterval(t)},[x,b]),(0,d.useEffect)(()=>{let e=v?.callId||y||null;if(!e){Qe.current=null;return}(v?.callId||b===`connecting`||b===`connected`)&&(!(!i||Ve===`minimized_orb`||Ve===`voice_mode`)&&Qe.current===e||(console.log(`[FlowEngageWidget] forcing call UI to front`,{forcedKey:e,isOpen:i,surface:Ve,hasIncomingCall:!!v?.callId,activeCallId:y,callConnectionState:b}),Qe.current=e,Ve===`voice_mode`&&oe?.(!1),ie?.(),E(`text_chat`)))},[y,b,v?.callId,i,ie,oe,Ve]),(0,d.useEffect)(()=>{if(!o||_){he?.(``),me?.();return}if(!D.trim()){he?.(``),me?.();return}pe?.();let e=window.setTimeout(()=>he?.(D),120),t=window.setTimeout(()=>me?.(),1200);return()=>{window.clearTimeout(e),window.clearTimeout(t)}},[D,o,_,pe,me,he]);let nt=e=>e?{replyTo:e.messageId||e.id||null,replyToContent:(e.replyToContent||e.message||``).replace(/<[^>]+>/g,``).trim().slice(0,200),replyToSender:e.sender||null}:null,rt=async e=>{if(e.preventDefault(),_)return;if(ze){let e=We.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)){qe(`Please enter a valid email so we can continue helping you.`);return}await ae(e),qe(``);return}if(!D.trim())return;let t=D.trim(),n=nt(He);O(``),Ue(null),await re(t,``,n)},it=e=>{let t=Math.floor(e/60);return`${String(t).padStart(2,`0`)}:${String(e%60).padStart(2,`0`)}`},at=(0,d.useCallback)(async e=>{if(_||m)return;let t=e.message||e.label||e.text||``;t.trim()&&await re(t.trim(),``)},[_,m,re]),ot=et&&Ve===`text_chat`?{inset:0}:Se===`bottom-left`?{left:`1.5rem`,bottom:`1.5rem`}:{right:`1.5rem`,bottom:`1.5rem`},st=()=>E(`minimized_orb`),ct=()=>E(`connection_modal`),lt=()=>{ie({notifyChatInitiated:!0}),oe?.(!0),E(`voice_mode`)},ut=()=>{ie({notifyChatInitiated:!0}),oe?.(!1),E(`text_chat`)},dt=()=>{oe?.(!1),st()};return e!==`ready`||!je?null:(0,f.jsxs)(`div`,{className:`flowengage-widget-root`,style:{position:`fixed`,zIndex:999999,...ot},children:[Ve===`entry_prompt`&&(0,f.jsx)(YD,{copy:T,orbColors:be,primaryColor:xe,onYes:lt,onLater:st}),Ve===`minimized_orb`&&(0,f.jsx)(op.div,{layoutId:`fe-main-orb`,initial:{scale:94/50},animate:{scale:1},transition:{type:`spring`,stiffness:220,damping:26},style:{transformOrigin:`bottom right`,display:`inline-block`},children:(0,f.jsx)(JD,{size:50,orbColors:be,onClick:ct})}),Ve===`connection_modal`&&(0,f.jsx)(XD,{copy:T,orbColors:be,primaryColor:xe,onVoice:lt,onText:ut,onClose:st}),Ve===`voice_mode`&&(0,f.jsx)(ZD,{orbColors:be,onEnterChat:ut,onEndChat:dt,agentId:Me,siteId:Ne,apiBaseUrl:Pe,historyRef:C,onMessageSync:ne},`voice`),Ve===`text_chat`&&(0,f.jsx)(eO,{copy:T,orbColors:be,primaryColor:xe,chatBgGradient:we,logo:Te,quickChatOptions:ke,onQuickChatSelect:at,isMobile:et,chatHistory:r,isAiTyping:p,isAgentTyping:u,activeScreen:a,agentName:Fe,agentHeadshot:Ie,fallbackAgentName:Ce,input:D,setInput:O,onSubmit:rt,isConversationEnded:_,isLoading:m,isRateLimited:h,rateLimitMessage:g,requiresEmail:ze,emailInput:We,setEmailInput:Ge,emailError:Ke,replyContext:He,setReplyContext:Ue,webRTCError:ee,micError:Xe,setMicError:Ze,dismissCallError:fe,incomingCall:v,rejectCall:le,acceptCall:ce,activeCallId:y,callConnectionState:b,isCallMuted:S,toggleCallMute:de,endWebRTCCall:ue,formatCallDuration:it,callDurationSeconds:Je,onCollapse:st,onStartVoice:lt,onEndConversation:se,showPoweredBy:Ae}),(0,f.jsx)(`style`,{children:`
604
+ </svg>`,lD=null,uD=!1;function dD(){return(!lD||!lD.isConnected)&&(lD=document.createElement(`div`),lD.id=`${Q}-cursor`,lD.innerHTML=cD,document.body.appendChild(lD),uD=!1),lD}async function fD(e){if(typeof document>`u`||!e)return;JE();let t;try{t=e.getBoundingClientRect()}catch{return}let n=t.left+Math.min(16,t.width*.2),r=t.top+Math.min(12,t.height*.25),i=dD();uD||=(i.style.transition=`none`,i.style.left=`${window.innerWidth/2}px`,i.style.top=`${window.innerHeight*.4}px`,i.classList.add(`${Q}-cursor-visible`),i.offsetHeight,i.style.transition=`left 0.32s cubic-bezier(0.25,0.46,0.45,0.94), top 0.32s cubic-bezier(0.25,0.46,0.45,0.94), opacity 0.2s ease`,!0),i.style.left=`${n}px`,i.style.top=`${r}px`,await gD(360)}function pD(e=!1){lD&&(e?(lD.classList.remove(`${Q}-cursor-visible`),uD=!1):(lD.classList.remove(`${Q}-cursor-visible`),setTimeout(()=>{uD=!1},250)))}async function mD(e){lD&&(lD.classList.add(`${Q}-cursor-click`),await gD(280),lD.classList.remove(`${Q}-cursor-click`))}function hD(e){if(!e||typeof document>`u`)return;JE();let t;try{t=e.getBoundingClientRect()}catch{return}let n=e.style.position,r=e.style.overflow,i=window.getComputedStyle(e).position;[`relative`,`absolute`,`fixed`,`sticky`].includes(i)||(e.style.position=`relative`),e.style.overflow=`hidden`;let a=document.createElement(`span`);a.className=`${Q}-ripple`;let o=Math.max(t.width,t.height)*1.2;Object.assign(a.style,{width:`${o}px`,height:`${o}px`,left:`${t.width/2-o/2}px`,top:`${t.height/2-o/2}px`}),e.appendChild(a),setTimeout(()=>{a.remove(),e.style.position=n,e.style.overflow=r},650)}function gD(e){return new Promise(t=>setTimeout(t,e))}function $(...e){$t()&&console.log(`[FlowEngage:voice-tools]`,...e)}function _D(e){return new Promise(t=>setTimeout(t,e))}var vD=`#flowengage-root, .flowengage-shell, .flowengage-widget-root`;function yD(e){if(!e||typeof e.closest!=`function`)return!1;try{return!!e.closest(vD)}catch{return!1}}function bD(e){try{let t=e.ownerDocument?.defaultView;if(t)return t.getComputedStyle(e)}catch{}return window.getComputedStyle(e)}function xD(e){let t=new Set;function n(r){if(!r||t.has(r))return;t.add(r),e(r);let i=r.querySelectorAll(`iframe`);for(let e of i)if(!yD(e))try{let t=e.contentDocument;t&&n(t)}catch{}}typeof document<`u`&&n(document)}function SD(e){return e==null?null:String(e).replace(/\u00a0/g,` `).replace(/\s*\*+\s*$/u,``).replace(/\s+/g,` `).trim()}function CD(e){let t=e.ownerDocument||document,n=e.getAttribute(`aria-labelledby`);if(n){let e=n.trim().split(/\s+/).filter(Boolean),r=[];for(let n of e)try{let e=t.getElementById(n);e?.textContent&&r.push(e.textContent.trim())}catch{}if(r.length)return SD(r.join(` `))}if(e.labels&&e.labels.length)return SD(e.labels[0].textContent);let r=e.id;if(r)try{let e=t.querySelector(`label[for="${CSS.escape(r)}"]`);if(e)return SD(e.textContent)}catch{let e=t.querySelector(`label[for="${r.replace(/"/g,`\\"`)}"]`);if(e)return SD(e.textContent)}let i=e.previousElementSibling;for(let e=0;e<6&&i;e+=1){if(i.tagName===`LABEL`)return SD(i.textContent);let e=(i.className||``).toString().toLowerCase();if(/chakra-form__label|formlabel|field-label|form-label|mui-form-label/.test(e)){let e=SD(i.textContent);if(e)return e}i=i.previousElementSibling}let a=e.parentElement;for(let e=0;e<5&&a;e+=1){if(a.tagName===`LABEL`)return SD(a.textContent);let e=a.querySelector?.(`:scope > label, :scope > [class*='FormLabel'], :scope > [class*='form__label']`);if(e?.textContent)return SD(e.textContent);a=a.parentElement}let o=e.getAttribute(`aria-label`);return o?SD(o):null}function wD(){let e=[];return xD(t=>{e.push(...Array.from(t.querySelectorAll(`input, select, textarea`)).filter(e=>{if(yD(e))return!1;let t=(e.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`image`].includes(t)||e.disabled||e.readOnly)return!1;try{let t=bD(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))}),e}function TD(){return wD().map((e,t)=>({formIndex:0,fieldIndex:t,tag:e.tagName,type:e.type||`text`,name:e.name||null,id:e.id||null,label:CD(e),placeholder:e.placeholder||null}))}function ED(){let e=[];return xD(t=>{e.push(...Array.from(t.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(yD(e)||e.disabled)return!1;try{let t=bD(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))}),e.slice(0,60).map((e,t)=>({index:t,text:(e.textContent||e.value||``).replace(/\s+/g,` `).trim().slice(0,120)||null,ariaLabel:e.getAttribute(`aria-label`),type:e.type||e.tagName}))}function DD(e){return String(e||``).toLowerCase().replace(/\u00a0/g,` `).replace(/\*/g,``).replace(/\s+/g,` `).trim()}function OD(e){let t=DD(e);return t=t.replace(/\s+field\s*$/i,``).trim(),t}function kD(e,t){let n=OD(t);if(!n)return 0;let r=(e.name||``).toLowerCase(),i=(e.id||``).toLowerCase();if(r===`url`&&/url|website|domain|site|audit/.test(n)||(i===`url-input`||i.endsWith(`-url-input`))&&/url|website|domain|site|audit/.test(n))return 100;let a=[e.name,e.id,e.placeholder,CD(e),e.getAttribute(`aria-label`),e.getAttribute(`title`),e.getAttribute(`data-testid`),e.getAttribute(`autocomplete`)].filter(Boolean).map(e=>DD(e)),o=0;for(let e of a){if(!e)continue;if(e.includes(n)||n.includes(e)){o=Math.max(o,100);continue}let t=n.split(/\s+/).filter(e=>e.length>1);if(!t.length)continue;let r=0;for(let n of t)e.includes(n)&&(r+=1);o=Math.max(o,r/t.length*88)}return o}var AD=28;function jD(e,t){let n=null,r=0;for(let i of e){let e=kD(i,t);e>r&&(r=e,n=i)}return!n||r<AD?null:n}function MD(e,t,n){let r=String(t||``).toLowerCase().trim(),i=String(n||``).trim();if(!(/^https?:\/\//i.test(i)||/\.\w{2,}(\/|\s|$)/.test(i)||r.includes(`url`)||r.includes(`website`)||r.includes(`domain`)||r.includes(`site`)))return null;let a=null,o=0;for(let t of e){if(t.tagName!==`INPUT`&&t.tagName!==`TEXTAREA`)continue;let e=(t.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`checkbox`,`radio`].includes(e))continue;let n=0;(e===`url`||e===`text`||e===`search`)&&(n+=45);let r=[t.name,t.id,t.placeholder,CD(t),t.getAttribute(`aria-label`),t.getAttribute(`autocomplete`)].filter(Boolean).join(` `).toLowerCase();/(website|url|domain|site\s*url)/.test(r)&&(n+=55),n>o&&(o=n,a=t)}return!a||o<42?null:a}function ND(e){let t=String(e??``).trim();return t?/^https?:\/\//i.test(t)?!0:/\.\w{2,}(\/|\s|$)/.test(t):!1}function PD(e){let t=String(e??``).toLowerCase().trim();return t?!!(t===`url`||t===`website`||t===`website url`||t===`website_url`||t===`enter website url`||t.includes(`website`)||t.includes(`domain`)||/(enter\s+website|site\s*url|page\s*url)/.test(t)):!1}function FD(e){if(!e||e.tagName!==`INPUT`&&e.tagName!==`TEXTAREA`)return!1;let t=(e.type||``).toLowerCase();return![`hidden`,`submit`,`button`,`checkbox`,`radio`,`file`].includes(t)}function ID(e){if(!FD(e))return!1;let t=(e.name||``).toLowerCase(),n=(e.id||``).toLowerCase(),r=[e.name,e.id,e.placeholder,CD(e),e.getAttribute(`aria-label`)].filter(Boolean).join(` `).toLowerCase();return t===`url`||n===`url-input`||n.endsWith(`-url-input`)||/(website\s*url|enter\s+website|site\s*url)/.test(r)||/(website|domain)/.test(r)&&/(url|site)/.test(r)}function LD(e,t,n){let r=String(t??``),i=String(n??``),a=BD(e,r)||jD(e,r)||MD(e,r,i);if(!a)return[];let o=new Set([a]);if(ND(i)&&PD(r))for(let t of e)t!==a&&ID(t)&&o.add(t);let s=Array.from(o);return s.sort((e,t)=>{if(e===t)return 0;let n=e.compareDocumentPosition(t);return n&Node.DOCUMENT_POSITION_FOLLOWING?-1:n&Node.DOCUMENT_POSITION_PRECEDING?1:0}),s}function RD(e,t){try{if(!e?.getBoundingClientRect||!t?.getBoundingClientRect)return 1/0;let n=e.getBoundingClientRect(),r=t.getBoundingClientRect(),i={x:n.left+n.width/2,y:n.top+n.height/2},a={x:r.left+r.width/2,y:r.top+r.height/2};return Math.hypot(i.x-a.x,i.y-a.y)}catch{return 1/0}}function zD(e){if(!e||typeof e!=`string`)return null;let t=null;return xD(n=>{try{let r=n.getElementById(e);r&&!yD(r)&&r.matches?.(`input, select, textarea`)&&(t=r)}catch{}}),t}function BD(e,t){let n=String(t??``).trim();if(!n)return null;let r=n.match(/^name:\s*([\w.-]+)$/i);if(r){let t=r[1];for(let n of e)if(n.name===t)return n}let i=n.match(/^id:\s*([\w.-]+)$/i);if(i){let e=zD(i[1]);if(e)return e}let a=n.startsWith(`#`)?n.slice(1):n;if(/^[\w-]+$/.test(a)){let e=zD(a);if(e)return e}let o=n.toLowerCase().replace(/\s+/g,` `);if(o===`url`||o===`website`||o===`website url`||o===`website_url`||o===`enter website url`)for(let t of e){let e=(t.name||``).toLowerCase(),n=(t.id||``).toLowerCase();if(e===`url`||n===`url-input`||n.endsWith(`-url-input`))return t}return null}function VD(e,t){let n=String(t||``).toLowerCase().trim();if(!n)return 0;let r=[e.textContent,e.value,e.getAttribute(`aria-label`),e.getAttribute(`title`)].filter(Boolean).join(` `).toLowerCase().replace(/\s+/g,` `);if(r.includes(n))return 100;let i=n.split(/\s+/).filter(e=>e.length>1);if(!i.length)return 0;let a=0;for(let e of i)r.includes(e)&&(a+=1);return a/i.length*92}function HD(e,t){let n=[];xD(e=>{n.push(...Array.from(e.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(yD(e)||e.disabled)return!1;try{let t=bD(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))});let r=0,i=n.map(t=>({el:t,s:VD(t,e)}));for(let{s:e}of i)e>r&&(r=e);if(r<36)return null;let a=i.filter(({s:e})=>e===r).map(({el:e})=>e);if(a.length===1)return a[0];let o=Array.isArray(t)?t.filter(e=>e&&e.isConnected):[];if(o.length){let e=a[0],t=1/0;for(let n of a)for(let r of o){let i=RD(n,r);i<t&&(t=i,e=n)}return e}return a[0]}function UD(e){if(e==null)return{};if(typeof e==`string`){let t=e.trim();if(!t)return{};try{return JSON.parse(t)}catch{return{url:t}}}return e}function WD(e){let t=UD(e);if(Array.isArray(t)&&t.length>0){let e=t[0];if(e?.field_key!=null||e?.fieldKey!=null)return t.map(e=>({field_key:e.field_key??e.fieldKey,value:e.value}))}if(!t||typeof t!=`object`)return[];let n=t.fields??t.Fields??t.field_list??t.fieldList??t.data?.fields;if(typeof n==`string`)try{n=JSON.parse(n)}catch{n=null}n&&!Array.isArray(n)&&typeof n==`object`&&(n=Object.values(n)),(!n||n.length===0)&&(t.field_key!=null||t.fieldKey!=null)&&t.value!=null&&(n=[{field_key:t.field_key??t.fieldKey,value:t.value}]);let r=t.website_url??t.websiteUrl??t.url??t.website??t.domain??t.site_url??t.siteUrl;return(!n||n.length===0)&&r!=null&&String(r).trim()&&(n=[{field_key:t.field_key??t.fieldKey??`url`,value:String(r).trim()}]),Array.isArray(n)?n.map(e=>({field_key:e?.field_key??e?.fieldKey,value:e?.value??e?.Value})):[]}function GD(e){if(!e||typeof e!=`string`)return[];let t=e.trim();if(!t||/\b[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}\b/i.test(t))return[];let n=t.match(/https?:\/\/[^\s<>"']+/i);if(n)return[{field_key:`url`,value:n[0].replace(/[.,;:)]+$/,``)}];let r=t.match(/\b(?:[\w-]+\.)+[a-z]{2,}\b/i);if(r){let e=r[0].replace(/[.,;:)]+$/,``);return/^https?:/i.test(e)||(e=`https://${e}`),[{field_key:`url`,value:e}]}return[]}function KD(e){if(!e||typeof e!=`string`)return[];let t=e.trim();if(!t)return[];let n=[],r=new Set,i=/\b([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,})\b/i,a=(e,t)=>{let i=String(t??``).trim().replace(/^["']|["']$/g,``);if(!i||i.length>800)return;let a=`${e}\0${i}`;r.has(a)||(r.add(a),n.push({field_key:e,value:i}))},o=t.match(/^\s*([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,})\s*$/i);if(o)return a(`Email Address`,o[1]),n;let s=t.match(/\b(?:please\s+)?(?:enter|type|put)\s+(.+?)\s+in(?:to)?\s+(?:the\s+)?(?:full\s*name|full\s*name\s*field|name\s*field)\b/i);if(s&&a(`Full Name`,s[1]),s=t.match(/\bfull\s*name,?\s*(?:please\s+)?(?:enter|type|put)\s+(.+?)(?:\.|$|!|\?)/i),s&&a(`Full Name`,s[1]),s=t.match(/\bfull\s*name\s*(?:is|:|please\s+enter|-)\s*(.+?)(?:\.|$|(?=\s+(?:and|my\s+email|email|message))\b)/i),s&&a(`Full Name`,s[1]),s=t.match(/\b(.+?)\s+for\s+(?:the\s+)?full\s*name\b/i),s){let e=s[1].trim();e.length>1&&e.length<120&&!/@/.test(e)&&a(`Full Name`,e)}if(s=t.match(/\b(?:email|e-mail)(?:\s*address)?\s*(?:is|:|please\s+use|enter|-)\s*([^\s@]+@[^\s@]+\.[^\s,]+)/i),s&&a(`Email Address`,s[1]),s=t.match(/\b(?:enter|type|put)\s+([^\s@]+@[^\s@]+\.[^\s,]+)\s+in(?:to)?\s+(?:the\s+)?(?:email|e-mail)/i),s&&a(`Email Address`,s[1]),s=t.match(/\b(?:message|comment)\s*(?:is|:|please\s+enter|-)\s*(.+)$/is),s){let e=s[1].trim();e.length>0&&a(`Message`,e)}if(!n.some(e=>/email/i.test(String(e.field_key)))){let e=t.match(i);if(e){let r=t.replace(e[0],``).trim().replace(/^(please|it's|it is|use|is|my email is|e-?mail is)\s*/i,``).replace(/[.,;:!?]+$/,``).trim();if(t.length<=96&&r.length<=36)return a(`Email Address`,e[1]),n}}if(n.length===0){let e=t.split(/\s+/).filter(Boolean).length,n=/[.!?]/.test(t)||e>=6||t.length>=24&&e>=5||t.length>=42,r=/^[A-Z][a-z]+\s+[A-Z][a-z]+$/.test(t.trim());n&&t.length>=16&&!i.test(t)&&!r&&a(`Message`,t)}return n}function qD(e){if(!e||typeof e!=`object`)return null;let t=e.url??e.target_url??e.page_url??e.pageUrl??e.link??e.href??e.path;return t==null?null:String(t).trim()||null}function JD(e){if(!e||typeof e!=`object`)return null;let t=e.query??e.q??e.search??e.text??e.keywords;return t==null?null:String(t).trim()||null}function YD(e,t,n){if(!n?.skipScroll)try{e.scrollIntoView({block:`center`,inline:`nearest`})}catch{try{e.scrollIntoView(!0)}catch{}}try{e.focus({preventScroll:!0})}catch{try{e.focus()}catch{}}let r=e.tagName,i=(e.type||``).toLowerCase();if(r===`SELECT`)return e.value=String(t),e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0})),!0;if(i===`checkbox`||i===`radio`)return e.checked=[`1`,`true`,`yes`,`on`].includes(String(t).toLowerCase().trim()),e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0})),!0;let a=String(t);if(r===`INPUT`||r===`TEXTAREA`){let t=e.ownerDocument?.defaultView||window,n=r===`TEXTAREA`?t.HTMLTextAreaElement.prototype:t.HTMLInputElement.prototype,i=Object.getOwnPropertyDescriptor(n,`value`);i?.set?i.set.call(e,a):e.value=a}else e.value=a;let o={bubbles:!0,cancelable:!0,composed:!0};try{e.dispatchEvent(new InputEvent(`input`,{...o,inputType:`insertText`,data:a}))}catch{e.dispatchEvent(new Event(`input`,o))}e.dispatchEvent(new Event(`change`,o));try{queueMicrotask(()=>{try{e.dispatchEvent(new Event(`input`,o)),e.dispatchEvent(new Event(`change`,o))}catch{}})}catch{}return!0}function XD(){let e={};document.querySelectorAll(`h1, h2, h3, h4, h5, h6`).forEach(t=>{if(t.id)return;let n=t.textContent.trim();if(!n)return;let r=n.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``).substring(0,60);if(e[r]){let t=2;for(;e[r+`-`+t];)t++;r=r+`-`+t}e[r]=!0,t.id=r})}function ZD(e){let t=e.siteId||null,n=(e.apiBaseUrl||``).replace(/\/$/,``),r=typeof e.getLastUserVoiceText==`function`?e.getLastUserVoiceText:null,i=[],a={flowengage_navigate:async n=>{$(`flowengage_navigate ▶ raw parameters:`,n);let r=UD(n),i=qD(r),a=r.section_text??r.sectionText??r.section;if($(`flowengage_navigate · coerced:`,{url:i,sectionText:a}),!i){let e=`Missing url: pass a string url, path like /pricing, or JSON with a url field.`;return $(`flowengage_navigate ✖`,e),e}if(!await fn(i,{siteId:t,apiBaseUrl:e.apiBaseUrl})){let e=`That page is not available in the site index; answer without navigating.`;return $(`flowengage_navigate ✖ blocked`,e),e}try{if(QE(`Navigating to ${i}...`,{spinner:!0}),rD(),BE(),qE(),$(`flowengage_navigate → shadowNavigate`,i),await mn(i),await _D(400),XD(),a&&typeof a==`string`){let e=sn(null,a);e&&LE(()=>KE(e)),$(`flowengage_navigate · highlight`,{sectionText:a,found:!!e})}let e=`OK_NAVIGATION ${i}`;return $(`flowengage_navigate ✓`,e),QE(`Navigation complete`,{spinner:!1,icon:`✅`,duration:1200}),e}catch(e){let t=`Navigation error: ${e?.message||String(e)}`;return $(`flowengage_navigate ✖`,t),QE(`Navigation failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{iD(),$E(900)}},flowengage_highlight:async e=>{$(`flowengage_highlight ▶`,e);let t=UD(e),n=t?.section_id||t?.sectionId,r=t?.section_text||t?.sectionText,i=sn(n||null,r||null);return i?(LE(()=>KE(i)),$(`flowengage_highlight ✓ (enqueued)`),`Highlighted the section.`):($(`flowengage_highlight ✖ no element`),`Could not find that section on the page.`)},flowengage_read_content:async e=>{$(`flowengage_read_content ▶`,e);let t=UD(e),n=t?.section_text||t?.sectionText||``;try{let e=``;if(n){let t=sn(null,n);if(!t)return`Could not find section "${n}" on the page.`;let r=[t.textContent.trim()],i=t.nextElementSibling;for(;i&&!/^H[1-3]$/i.test(i.tagName);){let e=i.textContent.trim();e&&r.push(e),i=i.nextElementSibling}e=r.join(`
605
+ `)}else{let t=(document.querySelector(`main`)||document.querySelector(`article`)||document.querySelector(`[role="main"]`)||document.querySelector(`#content`)||document.querySelector(`.content`)||document.body).cloneNode(!0);t.querySelectorAll(`nav, footer, header, aside, script, style, noscript, .nav, .footer, .header, .sidebar`).forEach(e=>e.remove()),e=t.textContent.replace(/\s+/g,` `).trim()}return e.length>8e3&&(e=e.substring(0,8e3)+`... (truncated)`),$(`flowengage_read_content ✓`,`${e.length} chars`),e||`No readable content found on this page.`}catch(e){return $(`flowengage_read_content ✖`,e.message),`Could not read page content: ${e.message}`}},flowengage_search:async e=>{$(`flowengage_search ▶`,e);let r=JD(UD(e));if($(`flowengage_search · query:`,r,`siteId:`,t,`apiBase:`,n||`(empty)`),!r)return $(`flowengage_search ✖ missing query`),`Missing query parameter.`;if(!t)return $(`flowengage_search ✖ no siteId`),`Site is not configured for search.`;if(!n)return $(`flowengage_search ✖ no api base`),`API base URL is missing; cannot search.`;try{let e=`${n}/api/site-tools/search`;$(`flowengage_search → POST`,e);let i=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({siteId:t,query:r,currentUrl:typeof window<`u`?window.location.href:``})}),a=await i.json();if($(`flowengage_search · HTTP`,i.status,`success:`,a.success),!a.success){let e=a.error||`Search failed.`;return $(`flowengage_search ✖`,e),e}let o=a.results||[];return $(`flowengage_search ✓`,`${o.length} result(s)`,o.slice(0,3).map(e=>e?.url||e)),JSON.stringify(o)}catch(e){let t=`Search error: ${e.message||`network`}`;return $(`flowengage_search ✖`,t),t}},flowengage_page_content:async e=>{$(`flowengage_page_content ▶`,e);let r=UD(e),i=r?.url||r?.page_url||``;if($(`flowengage_page_content · url:`,i,`siteId:`,t,`apiBase:`,n||`(empty)`),!i)return $(`flowengage_page_content ✖ missing url`),`Missing url parameter.`;if(!t)return $(`flowengage_page_content ✖ no siteId`),`Site is not configured.`;if(!n)return $(`flowengage_page_content ✖ no api base`),`API base URL is missing; cannot fetch page content.`;try{let e=`${n}/api/site-tools/page-content`;$(`flowengage_page_content → POST`,e);let r=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({siteId:t,url:i})}),a=await r.json();if($(`flowengage_page_content · HTTP`,r.status,`success:`,a.success),!a.success){let e=a.error||`Failed to get page content.`;return $(`flowengage_page_content ✖`,e),e}return $(`flowengage_page_content ✓`,`title: ${a.title}`,`sections: ${(a.sections||[]).length}`,`content: ${(a.content||``).length} chars`),JSON.stringify({title:a.title,url:a.url,sections:a.sections,content:a.content})}catch(e){let t=`Page content error: ${e.message||`network`}`;return $(`flowengage_page_content ✖`,t),t}},flowengage_end_session:async()=>($(`flowengage_end_session ▶`),typeof e.requestEndSession==`function`&&e.requestEndSession(),`Voice session is ending.`),flowengage_list_forms:async()=>{let e=TD(),t=ED();return $(`flowengage_list_forms ✓`,`${e.length} field(s)`,`${t.length} button(s)`),JSON.stringify({fields:e,buttons:t,hint:`field_key: placeholder/label, name (e.g. url), id (e.g. url-input). If the page has two URL boxes, flowengage_fill_form sets all matching URL inputs. flowengage_click_button picks the Conduct Audit nearest the filled field when labels duplicate.`})},flowengage_fill_form:async e=>{try{$(`flowengage_fill_form ▶ raw:`,e),aD();let t=WD(e);if(!t.length&&r){let e=r(),n=GD(e);n.length?$(`flowengage_fill_form · inferred URL from last user utterance (model omitted usable fields):`,n):(n=KD(e),n.length&&$(`flowengage_fill_form · inferred contact fields from last user utterance (empty tool params):`,n)),n.length&&(t=n)}if($(`flowengage_fill_form · normalized fields:`,t),!t.length)return`No fields provided. Call flowengage_list_forms for field_key strings, then flowengage_fill_form with { "fields": [ { "field_key": "<label or placeholder from list>", "value": "<user value>" } ] }. Never use empty {}. Pass the value the user just said (email, message, name, URL) in fields.`;let n=[];for(let e of t){let t=e?.field_key??e?.fieldKey,r=e?.value;if(t==null||r==null)continue;QE(`Filling ${String(t)}...`,{spinner:!0});let a=wD(),o=LD(a,String(t),r);if(o.length){for(let[e,t]of o.entries())oD(t),await fD(t),YD(t,r,{skipScroll:e>0}),sD(t),await _D(120);i=o,n.push(String(t));continue}let s=BD(a,String(t));s||=jD(a,String(t)),s||=MD(a,String(t),r),s&&(oD(s),await fD(s),YD(s,r),sD(s),await _D(120),i=[s],n.push(String(t)))}if(!n.length)return $(`flowengage_fill_form ✖ no matches`),`Could not match any fields. Call flowengage_list_forms and use field_key values that match placeholder, label, name, or id (e.g. Enter Website URL). Ensure the form is on the page, not the chat panel.`;let a=`OK_FILLED: ${n.join(`, `)}`;return $(`flowengage_fill_form ✓`,a),QE(`Form filled`,{spinner:!1,icon:`✅`,duration:1100}),a}catch(e){let t=`flowengage_fill_form error: ${e?.message||String(e)}`;return $(`flowengage_fill_form ✖`,t),QE(`Failed to fill form`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{pD(),aD(),$E(700)}},flowengage_click_button:async e=>{let t=UD(e),n=(t.button_text??t.buttonText??t.text??``).trim();if($(`flowengage_click_button ▶`,n),!n)return`Missing button_text: pass the visible label, e.g. Conduct Audit.`;let r=HD(n,i);if(!r)return $(`flowengage_click_button ✖ no match`),`Could not find a button matching "${n}". Call flowengage_list_forms to see button texts.`;try{QE(`Clicking ${n}...`,{spinner:!0});try{r.scrollIntoView({block:`center`,inline:`nearest`})}catch{r.scrollIntoView(!0)}await fD(r),r.focus?.(),await mD(r),hD(r),r.click();let e=(r.textContent||r.value||r.getAttribute(`aria-label`)||``).trim().slice(0,80)||`button`,t=`OK_CLICK ${e}`;return $(`flowengage_click_button ✓`,t),QE(`Clicked ${e}`,{spinner:!1,icon:`✅`,duration:1200}),t}catch(e){let t=`Click failed: ${e?.message||String(e)}`;return $(`flowengage_click_button ✖`,t),QE(`Click failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{pD(),$E(700)}}};return{...a,navigateToPage:a.flowengage_navigate,highlightOnPage:a.flowengage_highlight,searchSiteContent:a.flowengage_search,getPageContent:a.flowengage_page_content,endVoiceSession:a.flowengage_end_session,listPageForms:a.flowengage_list_forms,fillFormFields:a.flowengage_fill_form,clickPageButton:a.flowengage_click_button}}function QD(e){return!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,async n=>{let r=$t();r?console.log(`[FlowEngage:voice-tool] ▶`,e,n):console.info(`[FlowEngage] voice tool » ${e}`);let i;try{i=await t(n)}catch(t){let n=`Tool error: ${t?.message||String(t)}`;return console.error(`[FlowEngage] voice tool ${e} threw:`,t),n}let a=typeof i==`string`?i.length>220?`${i.slice(0,220)}…`:i:String(i);return r?console.log(`[FlowEngage:voice-tool] ◀`,e,a):console.info(`[FlowEngage] voice tool « ${e}:`,a),i}]))}var $D={blue:`#135bd8`,red:`#ef334b`,yellow:`#ffbd2e`,dark:`#0d1b2a`,highlight:`rgba(255,255,255,0.9)`,green:`#10b981`};function eO(e){if(!Array.isArray(e)||e.length<2)return`linear-gradient(145deg, #dce8f022 0%, #e8dff522 45%, #f5e0e022 100%), #f7f8fa`;let[t,n,r]=e;return e.length>=3&&r?[`radial-gradient(ellipse 80% 70% at -10% 50%, ${t}1a 0%, transparent 70%)`,`radial-gradient(ellipse 70% 80% at 110% 30%, ${n}1a 0%, transparent 70%)`,`radial-gradient(ellipse 80% 60% at 50% 110%, ${r}1a 0%, transparent 70%)`,`#f7f8fa`].join(`, `):[`radial-gradient(ellipse 80% 100% at -10% 50%, ${t}1a 0%, transparent 70%)`,`radial-gradient(ellipse 80% 100% at 110% 50%, ${n}1a 0%, transparent 70%)`,`#f7f8fa`].join(`, `)}function tO(e){if(!e||typeof e!=`string`)return`#1a1a1a`;let t=e.replace(`#`,``),n=t.length===3?t.split(``).map(e=>e+e).join(``):t,r=parseInt(n.slice(0,2),16)/255,i=parseInt(n.slice(2,4),16)/255,a=parseInt(n.slice(4,6),16)/255,o=e=>e<=.04045?e/12.92:((e+.055)/1.055)**2.4;return .2126*o(r)+.7152*o(i)+.0722*o(a)>.179?`#1a1a1a`:`#ffffff`}function nO({logo:e,style:t}){if(!e)return null;if(typeof e==`string`)return(0,f.jsx)(`img`,{src:e,alt:``,style:{objectFit:`contain`,flexShrink:0,display:`block`,...t}});let n=typeof e==`function`?d.default.createElement(e):d.default.isValidElement(e)?e:null;return n?(0,f.jsx)(`span`,{className:`fe-logo-slot`,style:{display:`inline-flex`,alignItems:`center`,flexShrink:0,overflow:`hidden`,...t},children:n}):null}function rO({title:e}){return(0,f.jsx)(`div`,{style:{width:`100%`,height:`100%`,borderRadius:`16px`,background:`linear-gradient(135deg, rgba(59,130,246,0.16) 0%, rgba(59,130,246,0.08) 100%)`,color:`#2563eb`,display:`flex`,alignItems:`center`,justifyContent:`center`,fontSize:`18px`,fontWeight:700,letterSpacing:`-0.03em`},children:String(e||`FE`).split(/\s+/).filter(Boolean).slice(0,2).map(e=>e[0]?.toUpperCase()||``).join(``)||`FE`})}function iO(e,t){let n=(t||``).trim();return n?!!(/\b(let'?s|let us)\s+(end|stop|finish|wrap up|close)\s+(the\s+)?(voice\s+)?(session|call|chat)\b/i.test(n)||/\bend\s+(this\s+)?(the\s+)?(voice\s+)?(session|call|chat)\b/i.test(n)||/\b(hang\s+up|disconnect)\b/i.test(n)||/\b(that'?s all|we'?re done)\b/i.test(n)||e===`bot`&&(/\b(I'?ll|I will|Let me|I can|I'?m going to)\s+(end|close)\s+(the\s+)?(voice\s+)?(session|call)\b/i.test(n)||/\b(ending|closing)\s+(the\s+)?(voice\s+)?session\b|\bvoice\s+session\s+(is\s+)?(now\s+)?(ended|over|closing)\b/i.test(n)||/\b(session|call)\s+(is\s+)?(now\s+)?(ended|over)\b/i.test(n)||/\bwe\s+can\s+end\s+(the\s+)?(session|call)?\s*(here|now)\b/i.test(n)||/\b(wrapping\s+up|signing\s+off)\b/i.test(n))||/^(goodbye|bye|that'?s all|we'?re done|hang up|disconnect)\b/i.test(n)):!1}function aO({orbColors:e,...t}){return(0,f.jsx)(NE,{colors:e,...t})}function oO({copy:e,orbColors:t,primaryColor:n,onYes:r,onLater:i,isMobile:a}){let o=n||$D.green,s=tO(o),c=a?72:94,l=(0,f.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:a?`14px`:`18px`},children:[(0,f.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,f.jsx)(up.p,{initial:{x:-16,opacity:0},animate:{x:0,opacity:1},transition:{type:`spring`,stiffness:260,damping:24,delay:.36},style:{margin:`0 0 14px`,fontSize:a?`16px`:`18px`,fontWeight:700,color:`white`,lineHeight:1.4,textShadow:`0 1px 4px rgba(0,0,0,0.35)`,maxWidth:a?void 0:`210px`},children:e.entryPrompt}),(0,f.jsxs)(up.div,{initial:{y:10,opacity:0},animate:{y:0,opacity:1},transition:{type:`spring`,stiffness:260,damping:24,delay:.54},style:{display:`flex`,gap:`8px`,flexWrap:`nowrap`},children:[(0,f.jsx)(`button`,{onClick:r,style:{padding:a?`9px 20px`:`10px 28px`,borderRadius:`999px`,background:o,color:s,fontWeight:700,fontSize:a?`14px`:`15px`,border:`none`,cursor:`pointer`,whiteSpace:`nowrap`,boxShadow:`0 4px 16px ${o}66`,transition:`transform 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.04)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`},children:e.yesLabel}),(0,f.jsx)(`button`,{onClick:i,style:{padding:a?`9px 16px`:`10px 22px`,borderRadius:`999px`,background:`transparent`,color:`white`,fontWeight:600,fontSize:a?`14px`:`15px`,border:`2px solid rgba(255,255,255,0.55)`,cursor:`pointer`,whiteSpace:`nowrap`,transition:`border-color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.borderColor=`rgba(255,255,255,0.9)`},onMouseLeave:e=>{e.currentTarget.style.borderColor=`rgba(255,255,255,0.55)`},children:e.laterLabel})]})]}),(0,f.jsx)(up.div,{initial:{x:120,opacity:0},animate:{x:0,opacity:1},transition:{type:`spring`,stiffness:220,damping:22,delay:0},style:{flexShrink:0},children:(0,f.jsx)(aO,{size:c,orbColors:t})})]});return(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(up.div,{initial:{opacity:0},animate:{opacity:1},transition:{duration:.4},style:{position:`fixed`,inset:0,background:`rgba(0,0,0,0.72)`,zIndex:-1}}),a?(0,f.jsx)(`div`,{style:{position:`absolute`,bottom:0,left:0,right:0,padding:`24px 20px 40px`,overflow:`hidden`},children:l}):l]})}function sO({copy:e,orbColors:t,primaryColor:n,onVoice:r,onText:i,onClose:a}){let o=n||$D.green,s=tO(o);return(0,f.jsxs)(up.div,{initial:{scale:50/300,borderRadius:`50%`},animate:{scale:1,borderRadius:`24px`},transition:{type:`spring`,stiffness:260,damping:26},style:{transformOrigin:`bottom right`,background:`white`,padding:`28px 28px 24px`,width:`300px`,display:`flex`,flexDirection:`column`,alignItems:`center`,gap:`20px`,boxShadow:`0 20px 60px rgba(0,0,0,0.2)`,position:`relative`,overflow:`hidden`},children:[(0,f.jsx)(`button`,{onClick:a,style:{position:`absolute`,top:`14px`,right:`14px`,background:`none`,border:`none`,cursor:`pointer`,color:`#9ca3af`,padding:`4px`,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`50%`,transition:`color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.color=`#374151`},onMouseLeave:e=>{e.currentTarget.style.color=`#9ca3af`},children:(0,f.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,f.jsx)(`polyline`,{points:`6 9 12 15 18 9`})})}),(0,f.jsx)(aO,{size:82,orbColors:t}),(0,f.jsx)(`p`,{style:{margin:0,fontSize:`17px`,fontWeight:600,color:`#111827`,textAlign:`center`,lineHeight:1.4},children:e.connectionTitle}),(0,f.jsxs)(`div`,{style:{display:`flex`,gap:`12px`,width:`100%`},children:[(0,f.jsx)(`button`,{onClick:r,style:{flex:1,padding:`12px`,borderRadius:`999px`,background:o,color:s,fontWeight:700,fontSize:`15px`,border:`none`,cursor:`pointer`,transition:`transform 0.15s ease`,boxShadow:`0 4px 12px ${o}55`},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.03)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`},children:e.voiceLabel}),(0,f.jsx)(`button`,{onClick:i,style:{flex:1,padding:`12px`,borderRadius:`999px`,background:`transparent`,color:`#111827`,fontWeight:600,fontSize:`15px`,border:`2px solid #d1d5db`,cursor:`pointer`,transition:`border-color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.borderColor=`#6b7280`},onMouseLeave:e=>{e.currentTarget.style.borderColor=`#d1d5db`},children:e.textLabel})]})]})}function cO({orbColors:e,onEnterChat:t,onEndChat:n,agentId:r,siteId:i,apiBaseUrl:a,historyRef:o,onMessageSync:s}){let[c,l]=(0,d.useState)(`idle`),[u,p]=(0,d.useState)(!1),[m,h]=(0,d.useState)(!1),g=(0,d.useRef)(null),_=(0,d.useRef)(``),v=(0,d.useRef)(async()=>{}),y=(0,d.useRef)(!1),b=(0,d.useRef)(!1),x=(0,d.useRef)(!1),S=(0,d.useRef)(!1),ee=(0,d.useRef)(`minimized`),te=(0,d.useRef)(null),C=(0,d.useCallback)((e=`minimized`)=>{ee.current=e,S.current=!0,queueMicrotask(()=>{y.current||(y.current=!0,v.current?.())})},[o]),ne=(0,d.useCallback)(async e=>{S.current=!0;try{await g.current?.endSession?.()}catch{}g.current=null,l(`idle`),p(!1),y.current=!1,typeof s==`function`&&await s(o.current),e?.()},[o,s]);return v.current=()=>ne(ee.current===`chat`?t:n),(0,d.useEffect)(()=>{b.current=u},[u]),(0,d.useEffect)(()=>{let e=!1,n=null;return(async()=>{if(!r){l(`error`);return}try{if((await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(e=>e.stop()),e)return;o.current=[],_.current=``,y.current=!1,x.current=!1,S.current=!1,ee.current=`minimized`;let t=QD(ZD({siteId:i||null,apiBaseUrl:a||null,getLastUserVoiceText:()=>_.current,requestEndSession:()=>{C()}})),s=await $T.startSession({agentId:r,clientTools:t,onUnhandledClientToolCall:e=>console.error(`[FlowEngage] Unhandled tool:`,e?.tool_name),onModeChange:({mode:t})=>{e||l(t===`speaking`?`speaking`:`listening`)},onMessage:t=>{if(e)return;let n=t.role===`user`?`user`:`bot`,r=t.message||t.text||t.content||``;r&&(n===`user`&&(_.current=r),o.current=[...o.current,{sender:n,message:r,timestamp:new Date().toISOString()}],iO(n,r)&&C(`minimized`))},onError:t=>{if(!e&&!S.current&&!x.current){x.current=!0,console.error(`[FlowEngageVoiceCall] session:error`,{message:t?.message,name:t?.name,raw:t});try{g.current?.setMicMuted?.(!0)}catch{}p(!0),l(`error`),C(`chat`)}},onDisconnect:()=>{if(!e&&!S.current&&!x.current){x.current=!0,console.warn(`[FlowEngageVoiceCall] session:disconnected`,{historyCount:o.current?.length||0,lastUserText:_.current||``,wasMuted:b.current});try{g.current?.setMicMuted?.(!0)}catch{}p(!0),C(`chat`)}}});if(e){s.endSession().catch(()=>{});return}n=s,g.current=s,l(`listening`);try{let e=typeof window<`u`?window.location.href:``,n=`[]`;try{n=await t.list_page_forms()}catch{}s.sendContextualUpdate(`Page: ${e}. SiteId: ${i||`unknown`}. Forms: ${n}. Voice: call end_voice_session or say you are ending the session to stop.`)}catch{}}catch(n){e||(console.error(`[FlowEngage] startSession failed`,n),l(`error`),ee.current=`chat`,window.setTimeout(()=>{e||t?.()},0))}})(),()=>{e=!0,S.current=!0,(n||g.current)?.endSession?.().catch(()=>{})}},[r,i,a,C]),(0,d.useEffect)(()=>{if(!m)return;let e=e=>{te.current&&!te.current.contains(e.target)&&h(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[m]),(0,f.jsx)(f.Fragment,{children:(0,f.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,alignItems:`center`,gap:`14px`,animation:`fe-orb-slide-up 0.42s cubic-bezier(0.16,1,0.3,1)`},children:[(0,f.jsxs)(`div`,{style:{position:`relative`},children:[c===`listening`&&(0,f.jsx)(`span`,{style:{position:`absolute`,right:`100%`,marginRight:`18px`,top:`50%`,transform:`translateY(-50%)`,color:`white`,fontSize:`18px`,fontWeight:600,letterSpacing:`0.01em`,textShadow:`0 2px 4px rgba(0,0,0,0.4)`,whiteSpace:`nowrap`},children:`Listening...`}),(0,f.jsx)(aO,{size:94,voiceState:c,isMuted:u,orbColors:e})]}),c===`error`&&(0,f.jsx)(`span`,{style:{color:`#f87171`,fontSize:`13px`,fontWeight:500},children:`Could not start voice session.`}),(0,f.jsxs)(`div`,{style:{display:`flex`,gap:`12px`,alignItems:`center`},children:[(0,f.jsx)(`button`,{onClick:async()=>{if(g.current)try{u?(await g.current.setMicMuted?.(!1),p(!1)):(await g.current.setMicMuted?.(!0),p(!0))}catch{}},title:u?`Unmute`:`Mute`,style:{width:`44px`,height:`44px`,borderRadius:`50%`,background:u?`#7f1d1d`:`#1f2937`,border:u?`1.5px solid #ef4444`:`1.5px solid #4b5563`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:u?`#f87171`:`white`,transition:`all 0.2s ease`,boxShadow:`0 2px 8px rgba(0,0,0,0.4)`},children:u?(0,f.jsxs)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`line`,{x1:`1`,y1:`1`,x2:`23`,y2:`23`}),(0,f.jsx)(`path`,{d:`M9 9v3a3 3 0 005.12 2.12M15 9.34V4a3 3 0 00-5.94-.6`}),(0,f.jsx)(`path`,{d:`M17 16.95A7 7 0 015 12v-2m14 0v2a7 7 0 01-.11 1.23`}),(0,f.jsx)(`line`,{x1:`12`,y1:`19`,x2:`12`,y2:`23`}),(0,f.jsx)(`line`,{x1:`8`,y1:`23`,x2:`16`,y2:`23`})]}):(0,f.jsxs)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`path`,{d:`M12 1a4 4 0 014 4v6a4 4 0 01-8 0V5a4 4 0 014-4z`,fill:`currentColor`,stroke:`none`}),(0,f.jsx)(`path`,{d:`M19 10a7 7 0 01-14 0M12 19v4M8 23h8`})]})}),(0,f.jsxs)(`div`,{style:{position:`relative`,isolation:`isolate`,zIndex:10},ref:te,children:[(0,f.jsx)(`button`,{onClick:()=>h(e=>!e),style:{width:`44px`,height:`44px`,borderRadius:`50%`,background:`#1f2937`,border:`1.5px solid #4b5563`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:`white`,transition:`background 0.2s ease`,boxShadow:`0 2px 8px rgba(0,0,0,0.4)`},children:(0,f.jsxs)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`currentColor`,children:[(0,f.jsx)(`circle`,{cx:`12`,cy:`5`,r:`1.8`}),(0,f.jsx)(`circle`,{cx:`12`,cy:`12`,r:`1.8`}),(0,f.jsx)(`circle`,{cx:`12`,cy:`19`,r:`1.8`})]})}),m&&(0,f.jsxs)(`div`,{style:{position:`absolute`,bottom:`54px`,right:0,zIndex:9999,background:`rgba(15,22,36,0.96)`,backdropFilter:`blur(14px)`,WebkitBackdropFilter:`blur(14px)`,borderRadius:`16px`,overflow:`hidden`,boxShadow:`0 10px 40px rgba(0,0,0,0.45)`,minWidth:`210px`,border:`1px solid rgba(255,255,255,0.07)`,animation:`fe-orb-fade-in 0.18s ease`},children:[(0,f.jsxs)(`button`,{onClick:()=>{h(!1),ee.current=`chat`,ne(t)},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,f.jsx)(`path`,{d:`M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z`})}),`Enter Chat Mode`]}),(0,f.jsx)(`div`,{style:{height:`1px`,background:`rgba(255,255,255,0.07)`,margin:`0 14px`}}),(0,f.jsxs)(`button`,{onClick:()=>{h(!1),ee.current=`minimized`,ne(n)},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`#f87171`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(248,113,113,0.1)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`path`,{d:`M10.68 13.31a16 16 0 003.41 2.6l1.27-1.27a2 2 0 012.11-.45 12.84 12.84 0 002.81.7 2 2 0 011.72 2v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07A19.42 19.42 0 013.07 8.62 19.79 19.79 0 01.1 2 2 2 0 012.11 0h3a2 2 0 012 1.72c.127.96.361 1.903.7 2.81a2 2 0 01-.45 2.11L6.18 7.84`}),(0,f.jsx)(`line`,{x1:`23`,y1:`1`,x2:`1`,y2:`23`})]}),`End Conversation`]})]})]})]})]})})}function lO({orbColors:e}){return(0,f.jsx)(`div`,{style:{flexShrink:0,width:`36px`,height:`36px`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:(0,f.jsx)(aO,{size:36,orbColors:e})})}var uO=()=>(0,f.jsx)(`div`,{style:{display:`flex`,marginBottom:`12px`,justifyContent:`flex-start`},children:(0,f.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`5px`,padding:`12px 16px`,borderRadius:`18px`,background:`#fff`,boxShadow:`0 2px 6px rgba(0,0,0,0.04)`},children:[0,1,2].map(e=>(0,f.jsx)(`span`,{style:{width:`7px`,height:`7px`,borderRadius:`50%`,background:`#9ca3af`,animation:`fe-dot-bounce 1.2s ease-in-out ${e*.2}s infinite`,display:`inline-block`}},e))})});function dO({copy:e,orbColors:t,primaryColor:n,chatBgGradient:r,logo:i,quickChatOptions:a,onQuickChatSelect:o,isMobile:s,chatHistory:c,isAiTyping:l,isAgentTyping:u,activeScreen:p,agentName:m,agentHeadshot:h,fallbackAgentName:g,input:_,setInput:v,onSubmit:y,isConversationEnded:b,isLoading:x,isRateLimited:S,rateLimitMessage:ee,selectedFile:te,onFileSelect:C,onRemoveSelectedFile:ne,attachmentError:re,isUploadingAttachment:ie,requiresEmail:ae,emailInput:oe,setEmailInput:se,emailError:ce,replyContext:le,setReplyContext:ue,webRTCError:de,micError:fe,setMicError:pe,dismissCallError:me,incomingCall:he,rejectCall:ge,acceptCall:_e,activeCallId:ve,callConnectionState:ye,isCallMuted:be,toggleCallMute:xe,endWebRTCCall:Se,formatCallDuration:Ce,callDurationSeconds:we,onCollapse:Te,onStartVoice:Ee,showPoweredBy:De}){let Oe=c.length>0,ke=x||S||b,Ae=!!(he||ve),[je,Me]=(0,d.useState)(!1),Ne=(0,d.useRef)(null);return(0,d.useEffect)(()=>{if(!je)return;let e=e=>{Ne.current&&!Ne.current.contains(e.target)&&Me(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[je]),(0,f.jsxs)(`div`,{style:s?{"--flowengage-primary":n,"--flowengage-accent":n,position:`fixed`,inset:0,width:`100%`,height:`100dvh`,background:r,borderRadius:0,display:`flex`,flexDirection:`column`,overflow:`hidden`,animation:`fe-orb-slide-up 0.28s cubic-bezier(0.16,1,0.3,1)`}:{"--flowengage-primary":n,"--flowengage-accent":n,width:`min(390px, calc(100vw - 40px))`,height:`min(640px, calc(100vh - 120px))`,background:r,borderRadius:`22px`,boxShadow:`0 24px 64px rgba(0,0,0,0.18), 0 4px 16px rgba(0,0,0,0.08)`,display:`flex`,flexDirection:`column`,overflow:`hidden`,position:`relative`,animation:`fe-orb-slide-up 0.36s cubic-bezier(0.16,1,0.3,1)`},children:[(0,f.jsxs)(`div`,{style:{display:`grid`,gridTemplateColumns:`40px minmax(0, 1fr) 40px`,alignItems:`center`,columnGap:`14px`,padding:`16px 18px 14px`,background:`transparent`,flexShrink:0},children:[(0,f.jsx)(`button`,{onClick:Te,style:{width:`40px`,height:`40px`,background:`none`,border:`none`,cursor:`pointer`,color:`#6b7280`,display:`flex`,alignItems:`center`,justifyContent:`center`,padding:`4px`,borderRadius:`10px`,transition:`color 0.15s ease`,flexShrink:0},onMouseEnter:e=>{e.currentTarget.style.color=`#111827`},onMouseLeave:e=>{e.currentTarget.style.color=`#6b7280`},children:(0,f.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,f.jsx)(`polyline`,{points:`6 9 12 15 18 9`})})}),(0,f.jsxs)(`div`,{style:{minWidth:0,maxWidth:s?`100%`:`250px`,width:`100%`,justifySelf:`center`,display:`grid`,gridTemplateColumns:`minmax(72px, 40%) minmax(0, 60%)`,alignItems:`center`},children:[(0,f.jsx)(`div`,{style:{minWidth:0,display:`flex`,alignItems:`center`,justifyContent:`center`,height:`40px`},children:i?(0,f.jsx)(nO,{logo:i,style:{height:`34px`,width:`100%`,maxWidth:`96px`}}):(0,f.jsx)(`div`,{style:{width:`40px`,height:`40px`,flexShrink:0},children:(0,f.jsx)(rO,{title:e.chatTitle})})}),(0,f.jsx)(`div`,{style:{minWidth:0,display:`flex`,alignItems:`center`},children:(0,f.jsx)(`span`,{style:{fontSize:`15px`,fontWeight:600,color:`#111827`,letterSpacing:`-0.01em`,lineHeight:1.2,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},title:e.chatTitle,children:e.chatTitle})})]}),(0,f.jsxs)(`div`,{style:{position:`relative`,isolation:`isolate`,zIndex:10},ref:Ne,children:[(0,f.jsx)(`button`,{type:`button`,onClick:()=>Me(e=>!e),style:{width:`40px`,height:`40px`,background:`none`,border:`none`,cursor:`pointer`,color:`#6b7280`,display:`flex`,alignItems:`center`,justifyContent:`center`,padding:`4px`,borderRadius:`10px`,transition:`color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.color=`#111827`},onMouseLeave:e=>{e.currentTarget.style.color=`#6b7280`},"aria-label":`Chat options`,children:(0,f.jsxs)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`currentColor`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,f.jsx)(`circle`,{cx:`12`,cy:`5`,r:`1.5`}),(0,f.jsx)(`circle`,{cx:`12`,cy:`12`,r:`1.5`}),(0,f.jsx)(`circle`,{cx:`12`,cy:`19`,r:`1.5`})]})}),je&&(0,f.jsxs)(`div`,{style:{position:`absolute`,top:`34px`,right:0,background:`rgba(15,22,36,0.96)`,backdropFilter:`blur(14px)`,WebkitBackdropFilter:`blur(14px)`,borderRadius:`16px`,overflow:`hidden`,boxShadow:`0 10px 40px rgba(0,0,0,0.45)`,minWidth:`210px`,border:`1px solid rgba(255,255,255,0.07)`,animation:`fe-orb-fade-in 0.18s ease`},children:[(0,f.jsxs)(`button`,{type:`button`,onClick:()=>{Me(!1),Ee?.()},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`path`,{d:`M12 1a4 4 0 014 4v6a4 4 0 01-8 0V5a4 4 0 014-4z`}),(0,f.jsx)(`path`,{d:`M19 10a7 7 0 01-14 0M12 19v4M8 23h8`})]}),`Enter Voice Mode`]}),(0,f.jsx)(`div`,{style:{height:`1px`,background:`rgba(255,255,255,0.07)`,margin:`0 14px`}}),(0,f.jsxs)(`button`,{type:`button`,onClick:()=>{Me(!1),Te?.()},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`#f87171`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(248,113,113,0.1)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`path`,{d:`M10.68 13.31a16 16 0 003.41 2.6l1.27-1.27a2 2 0 012.11-.45 12.84 12.84 0 002.81.7 2 2 0 011.72 2v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07A19.42 19.42 0 013.07 8.62 19.79 19.79 0 01.1 2 2 2 0 012.11 0h3a2 2 0 012 1.72c.127.96.361 1.903.7 2.81a2 2 0 01-.45 2.11L6.18 7.84`}),(0,f.jsx)(`line`,{x1:`23`,y1:`1`,x2:`1`,y2:`23`})]}),`Close Conversation`]})]})]})]}),(0,f.jsx)(wE,{webRTCError:de,micError:fe,setMicError:pe,dismissCallError:me,incomingCall:he,rejectCall:ge,acceptCall:_e,activeCallId:ve,callConnectionState:ye,formatCallDuration:Ce,callDurationSeconds:we,endWebRTCCall:Se,isCallMuted:be,toggleCallMute:xe,isAIVoiceActive:!1,currentCallAgentName:m||g,isRateLimited:S,rateLimitMessage:ee}),(0,f.jsx)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,minHeight:0,background:`transparent`},children:Oe?(0,f.jsx)(bE,{chatHistory:c,isAiTyping:l,isAgentTyping:u,setReplyContext:ue,TypingDots:uO,primaryColor:n,agentHeadshot:h,agentDisplayName:m||g,botAvatarNode:(0,f.jsx)(lO,{orbColors:t})}):(0,f.jsxs)(`div`,{style:{flex:1,overflowY:`auto`,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,gap:`22px`,padding:`28px 24px`},children:[(0,f.jsx)(aO,{size:94,orbColors:t}),(0,f.jsx)(`p`,{style:{margin:0,textAlign:`center`,fontSize:`16px`,color:`#374151`,lineHeight:1.55,maxWidth:`270px`},children:e.introGreeting}),a.length>0&&(0,f.jsx)(`div`,{style:{display:`flex`,flexWrap:`wrap`,gap:`8px`,justifyContent:`center`,width:`100%`,padding:`0 8px`},children:a.map(e=>(0,f.jsx)(`button`,{onClick:()=>o?.(e),style:{padding:`8px 16px`,borderRadius:`999px`,background:`white`,border:`1.5px solid ${n}33`,color:n||`#374151`,fontSize:`13px`,fontWeight:500,cursor:`pointer`,transition:`all 0.15s ease`,boxShadow:`0 1px 4px rgba(0,0,0,0.06)`},onMouseEnter:e=>{e.currentTarget.style.background=`${n}12`,e.currentTarget.style.borderColor=n},onMouseLeave:e=>{e.currentTarget.style.background=`white`,e.currentTarget.style.borderColor=`${n}33`},children:e.label||e.text},e.id))})]})}),(0,f.jsx)(`div`,{style:{background:`transparent`,flexShrink:0,position:`relative`,zIndex:1,padding:ae?`6px 0 0`:`12px 0 0`},children:(0,f.jsx)(xE,{input:_,setInput:v,onSubmit:y,isConversationEnded:b,callUiActive:Ae,handleToggleVoice:Ee,showVoiceToggle:p===`agent`,activeScreen:p,inputDisabled:ke,replyContext:le,clearReplyContext:()=>ue(null),onFileSelect:C,selectedFile:te,onRemoveSelectedFile:ne,attachmentError:re,isUploadingAttachment:ie,requiresEmail:ae,emailInput:oe,setEmailInput:se,emailError:ce,inputPlaceholder:e.inputPlaceholder})}),(0,f.jsx)(`div`,{style:{flexShrink:0,textAlign:`center`,padding:`12px 20px 18px`,pointerEvents:`none`},children:De&&(0,f.jsxs)(`span`,{style:{fontSize:`11px`,color:`#9ca3af`,letterSpacing:`0.01em`,userSelect:`none`},children:[`Powered by `,(0,f.jsx)(`strong`,{style:{fontWeight:600,color:`#6b7280`},children:`FlowEngage`})]})})]})}function fO(){let{status:e,runtimeConfig:t,resolvedConfig:n,chatHistory:r,isOpen:i,activeScreen:a,isHumanHandled:o,agentName:s,agentHeadshot:c,visitorEmail:l,isAgentTyping:u,isAiTyping:p,isLoading:m,isRateLimited:h,rateLimitMessage:g,isConversationEnded:_,incomingCall:v,activeCallId:y,callConnectionState:b,callConnectedAt:x,isCallMuted:S,webRTCError:ee,language:te,historyRef:C,onMessageSync:ne,sendMessage:re,uploadChatFile:ie,openWidget:ae,captureVisitorEmail:oe,setVoiceMode:se,endConversation:ce,acceptCall:le,rejectCall:ue,endWebRTCCall:de,toggleCallMute:fe,dismissCallError:pe,startTyping:me,stopTyping:he,updateTypingDraft:ge}=Qt();(0,d.useEffect)(()=>{try{an()}catch{}},[]);let _e=t?.widgetSettings||{},ve=n?.widgetSettings||{},ye={..._e.branding||{},...ve.branding||{}},be={..._e.theme||{},...ve.theme||{}},xe=Array.isArray(be.orbColors)&&be.orbColors.length>0?be.orbColors:null,Se=xe?.[0]||be.primaryColor||`#3B82F6`,Ce=be.position||`bottom-right`,we=ye.fallbackAgentName||`Agent`,Te=eO(xe??be.chatBgColors),Ee=ye.logo||ye.logoUrl||null,De=te||`en`,Oe=_e.recommendations?.[De]||[],ke=(ve.recommendations?.[De]??Oe).filter(e=>String(e?.label??``).trim()).map((e,t)=>({id:e.key||`qr-${t}`,label:e.label,message:e.label,text:e.label})),Ae=Array.isArray(ye.quickChatOptions)&&ye.quickChatOptions.length>0?ye.quickChatOptions:ke,je=ye.hideWatermark===!0?!1:ye.showPoweredBy!==!1,Me=ye.chatbotEnabled!==!1&&be.chatbotEnabled!==!1,Ne=_e.greetings?.[te]||ve.greetings?.[te]||ye.introGreeting||`Hello, I'm here to help you know more about OpenSense Labs.`,Pe={entryPrompt:ye.entryPrompt||`Do you want to explore in a new way?`,yesLabel:ye.yesLabel||`Yes`,laterLabel:ye.laterLabel||`Later`,connectionTitle:ye.connectionTitle||`How would you like to connect?`,voiceLabel:ye.voiceLabel||`Voice`,textLabel:ye.textLabel||`Text`,chatTitle:ye.headerName||`Chat with FlowEngage`,introGreeting:Ne,inputPlaceholder:ye.inputPlaceholder||`Type your message`,analysingLabel:ye.analysingLabel||`analysing...`},w=ve.elevenLabsAgentId||t?.elevenLabsAgentId||null,Fe=t?.siteId||n?.siteId||null,T=t?.apiBaseUrl||``,Ie=(0,d.useMemo)(()=>s&&String(s).trim()||t?.ownerName&&String(t.ownerName).trim()||t?.websiteName&&String(t.websiteName).trim()||`Agent`,[s,t?.ownerName,t?.websiteName]),Le=c&&String(c).trim()||t?.ownerProfileImageUrl&&String(t.ownerProfileImageUrl).trim()||null,E=r.some(e=>e.sender===`user`),Re=(0,d.useMemo)(()=>{let e=r.findIndex(e=>e.sender===`user`);return e===-1?!1:r.slice(e+1).some(e=>e.sender===`bot`||e.sender===`ai`||e.sender===`agent`)},[r]),ze=!l&&E&&Re,Be=!!(ve._dashboardLivePreview||_e._dashboardLivePreview),[Ve,He]=(0,d.useState)(()=>Be?`text_chat`:`entry_prompt`),[Ue,We]=(0,d.useState)(``),[D,O]=(0,d.useState)(null),[Ge,Ke]=(0,d.useState)(l||``),[qe,Je]=(0,d.useState)(``),[Ye,Xe]=(0,d.useState)(0),[Ze,Qe]=(0,d.useState)(null),[$e,et]=(0,d.useState)(null),[tt,nt]=(0,d.useState)(``),[rt,it]=(0,d.useState)(!1),at=(0,d.useRef)(null),ot=(0,d.useRef)(!1);(0,d.useLayoutEffect)(()=>{e!==`ready`||ot.current||(ot.current=!0,r.length>0&&He(`minimized_orb`))},[e,r]);let[st,ct]=(0,d.useState)(()=>typeof window<`u`&&window.matchMedia(`(max-width: 640px)`).matches);(0,d.useEffect)(()=>{let e=window.matchMedia(`(max-width: 640px)`),t=e=>ct(e.matches);return e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]),(0,d.useEffect)(()=>{Ke(l||``),l&&Je(``)},[l]);let lt=(0,d.useCallback)(()=>{et(null),nt(``)},[]),ut=(0,d.useCallback)(e=>{let t=hE(e);if(t){et(null),nt(t);return}et(e),nt(``)},[]);(0,d.useEffect)(()=>{if(!x||b!==`connected`){Xe(0);return}let e=()=>{let e=new Date(x).getTime();isNaN(e)||Xe(Math.max(0,Math.floor((Date.now()-e)/1e3)))};e();let t=window.setInterval(e,1e3);return()=>window.clearInterval(t)},[x,b]),(0,d.useEffect)(()=>{let e=v?.callId||y||null;if(!e){at.current=null;return}(v?.callId||b===`connecting`||b===`connected`)&&(!(!i||Ve===`minimized_orb`||Ve===`voice_mode`)&&at.current===e||(console.log(`[FlowEngageWidget] forcing call UI to front`,{forcedKey:e,isOpen:i,surface:Ve,hasIncomingCall:!!v?.callId,activeCallId:y,callConnectionState:b}),at.current=e,Ve===`voice_mode`&&se?.(!1),ae?.(),He(`text_chat`)))},[y,b,v?.callId,i,ae,se,Ve]),(0,d.useEffect)(()=>{if(!o||_){ge?.(``),he?.();return}if(!Ue.trim()||$e){ge?.(``),he?.();return}me?.();let e=window.setTimeout(()=>ge?.(Ue),120),t=window.setTimeout(()=>he?.(),1200);return()=>{window.clearTimeout(e),window.clearTimeout(t)}},[Ue,$e,o,_,me,he,ge]);let dt=e=>e?{replyTo:e.messageId||e.id||null,replyToContent:(e.replyToContent||e.message||``).replace(/<[^>]+>/g,``).trim().slice(0,200),replyToSender:e.sender||null}:null,ft=async e=>{if(e.preventDefault(),_)return;if(ze){let e=Ge.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)){Je(`Please enter a valid email so we can continue helping you.`);return}await oe(e),Je(``);return}let t=dt(D);if(!Ue.trim()&&!$e)return;if($e){try{it(!0),nt(``);let e=await ie($e),n=e?.data||e,r=Ue.trim()||`Shared file: ${_E($e)}`;We(``),O(null),lt(),await re(r,``,t,{type:`file`,metadata:{fileUrl:n?.fileUrl,fileName:n?.fileName||$e.name,fileType:n?.fileType||$e.type,fileSize:n?.fileSize||$e.size}})}catch(e){nt(e?.message||`Failed to upload the selected file.`)}finally{it(!1)}return}let n=Ue.trim();We(``),O(null),await re(n,``,t)},pt=e=>{let t=Math.floor(e/60);return`${String(t).padStart(2,`0`)}:${String(e%60).padStart(2,`0`)}`},mt=(0,d.useCallback)(async e=>{if(_||m)return;let t=e.message||e.label||e.text||``;t.trim()&&await re(t.trim(),``)},[_,m,re]),ht=st&&(Ve===`text_chat`||Ve===`entry_prompt`)?{inset:0}:Ce===`bottom-left`?{left:`1.5rem`,bottom:`1.5rem`}:{right:`1.5rem`,bottom:`1.5rem`},gt=()=>He(`minimized_orb`),_t=()=>He(`connection_modal`),vt=()=>{ae({notifyChatInitiated:!0}),se?.(!0),He(`voice_mode`)},yt=()=>{ae({notifyChatInitiated:!0}),se?.(!1),He(`text_chat`)},bt=()=>{se?.(!1),gt()};return e!==`ready`||!Me?null:(0,f.jsxs)(`div`,{className:`flowengage-widget-root`,style:{position:`fixed`,zIndex:999999,...ht},children:[Ve===`entry_prompt`&&(0,f.jsx)(oO,{copy:Pe,orbColors:xe,primaryColor:Se,onYes:vt,onLater:gt,isMobile:st}),Ve===`minimized_orb`&&(0,f.jsx)(up.div,{layoutId:`fe-main-orb`,initial:{scale:94/50},animate:{scale:1},transition:{type:`spring`,stiffness:220,damping:26},style:{transformOrigin:`bottom right`,display:`inline-block`},children:(0,f.jsx)(aO,{size:50,orbColors:xe,onClick:_t})}),Ve===`connection_modal`&&(0,f.jsx)(sO,{copy:Pe,orbColors:xe,primaryColor:Se,onVoice:vt,onText:yt,onClose:gt}),Ve===`voice_mode`&&(0,f.jsx)(cO,{orbColors:xe,onEnterChat:yt,onEndChat:bt,agentId:w,siteId:Fe,apiBaseUrl:T,historyRef:C,onMessageSync:ne},`voice`),Ve===`text_chat`&&(0,f.jsx)(dO,{copy:Pe,orbColors:xe,primaryColor:Se,chatBgGradient:Te,logo:Ee,quickChatOptions:Ae,onQuickChatSelect:mt,isMobile:st,chatHistory:r,isAiTyping:p,isAgentTyping:u,activeScreen:a,agentName:Ie,agentHeadshot:Le,fallbackAgentName:we,input:Ue,setInput:We,onSubmit:ft,isConversationEnded:_,isLoading:m,isRateLimited:h,rateLimitMessage:g,selectedFile:$e,onFileSelect:ut,onRemoveSelectedFile:lt,attachmentError:tt,isUploadingAttachment:rt,requiresEmail:ze,emailInput:Ge,setEmailInput:Ke,emailError:qe,replyContext:D,setReplyContext:O,webRTCError:ee,micError:Ze,setMicError:Qe,dismissCallError:pe,incomingCall:v,rejectCall:ue,acceptCall:le,activeCallId:y,callConnectionState:b,isCallMuted:S,toggleCallMute:fe,endWebRTCCall:de,formatCallDuration:pt,callDurationSeconds:Ye,onCollapse:gt,onStartVoice:vt,onEndConversation:ce,showPoweredBy:je}),(0,f.jsx)(`style`,{children:`
606
606
  /* Force any SVG (or img) inside LogoSlot to fill the container height
607
607
  regardless of whether the component forwards its style prop. */
608
608
  .fe-logo-slot svg,
@@ -620,4 +620,4 @@ registerProcessor("scribeAudioProcessor", ScribeAudioProcessor);
620
620
  @keyframes fe-orb-bar-3 { from{height:8px} to{height:20px} }
621
621
  @keyframes fe-orb-bar-4 { from{height:6px} to{height:16px} }
622
622
  @keyframes fe-dot-bounce { 0%,80%,100%{transform:translateY(0);opacity:.5} 40%{transform:translateY(-5px);opacity:1} }
623
- `})]})}exports.AnimatedOrb=SE,exports.FlowEngageProvider=vn,exports.FlowEngageWidget=tO,exports.useFlowEngage=Jt;
623
+ `})]})}exports.AnimatedOrb=NE,exports.FlowEngageProvider=Sn,exports.FlowEngageWidget=fO,exports.useFlowEngage=Qt;