@flowengage/react-chatbot 0.1.6 → 0.1.8
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.
|
@@ -5,7 +5,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
|
|
|
5
5
|
transition: all 0.3s ease !important;
|
|
6
6
|
border-radius: 8px !important;
|
|
7
7
|
}
|
|
8
|
-
`,document.head.appendChild(e)};function qt(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=document.querySelectorAll(`h1, h2, h3, h4, h5, h6, [data-section]`);for(let e of r)if(e.textContent.toLowerCase().includes(n))return e;let i=n.split(/\s+/).filter(e=>e.length>2);if(i.length>1){let e=null,t=0;for(let n of r){let r=n.textContent.toLowerCase(),a=0;for(let e of i)r.includes(e)&&a++;let o=a/i.length;o>t&&o>=.6&&(t=o,e=n)}if(e)return e}let a=document.querySelectorAll(`li, strong, blockquote, dt`);for(let e of a){let t=e.textContent.toLowerCase();if(t.includes(n)&&t.length<500)return e.tagName===`STRONG`&&e.parentElement?.tagName===`LI`?e.parentElement:e}let o=document.querySelectorAll(`p`);for(let e of o){let t=e.textContent.toLowerCase();if(t.includes(n)&&t.length<800)return e}return null}function Jt(e){!e||typeof document>`u`||(Kt(),Yt(),e.classList.add(`fe-highlight-section`),e.scrollIntoView({behavior:`smooth`,block:`center`}))}function Yt(){typeof document>`u`||document.querySelectorAll(`.fe-highlight-section`).forEach(e=>e.classList.remove(`fe-highlight-section`))}async function Xt(e){if(typeof window>`u`)return!1;try{let t=new URL(e,window.location.origin);if(t.origin!==window.location.origin)return window.location.href=e,!0;if(t.hash&&t.pathname===window.location.pathname){let e=t.hash.slice(1),n=document.getElementById(e);if(n)return n.scrollIntoView({behavior:`smooth`,block:`start`}),!0}if(t.pathname===window.location.pathname&&t.search===window.location.search&&!t.hash)return!1;let n=t.pathname+t.search+t.hash,r=window.next?.router;if(r?.push)return new Promise(e=>{let t=()=>{r.events?.off(`routeChangeComplete`,t),e(!0)};r.events?.on(`routeChangeComplete`,t),r.push(n),setTimeout(t,4e3)});let i=window.__NEXT_ROUTER__;return i?.push?(i.push(n),!0):window.history?.pushState?(window.history.pushState({},``,n),window.dispatchEvent(new PopStateEvent(`popstate`,{state:{}})),!0):(window.location.href=e,!0)}catch(t){return console.warn(`[FlowEngage] shadowNavigate error:`,t),window.location.href=e,!0}}var Zt=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(),Qt=(e=[])=>e.map(e=>({...e,message:Zt(e.message),isPending:!1,id:e.messageId||`${e.sender}-${e.timestamp||Date.now()}-${Math.random()}`})),$t=(e,t)=>e?typeof e==`string`?e:e.message||e.error||e.reason||t:t,en=(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}:{}}},tn=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}},nn=(e=[],t=`Agent`)=>{for(let t of e)if(typeof t==`string`&&t.trim())return t.trim();return t};function rn({siteId:e,config:t,children:n,language:r=`en`}){let i=(0,l.useMemo)(()=>e?{...t||{},siteId:e}:t||null,[e,t]),a=(0,l.useMemo)(()=>nn([i?.widgetSettings?.branding?.fallbackAgentName,i?.widgetSettings?.branding?.headerName],`Agent`),[i]),[o,s]=(0,l.useState)(`booting`),[c,f]=(0,l.useState)(null),[ee,te]=(0,l.useState)(null),[h,ie]=(0,l.useState)(``),[se,g]=(0,l.useState)([]),[_,ce]=(0,l.useState)(m().isOpen),[le,ue]=(0,l.useState)(m().activeScreen),[de,fe]=(0,l.useState)(m().isHumanHandled),[pe,me]=(0,l.useState)(m().agentName),[he,ge]=(0,l.useState)(m().agentHeadshot),[_e,ve]=(0,l.useState)(!1),[ye,be]=(0,l.useState)(!1),[xe,Se]=(0,l.useState)(`idle`),[Ce,we]=(0,l.useState)(!1),[Te,Ee]=(0,l.useState)(!1),[De,Oe]=(0,l.useState)(``),[ke,Ae]=(0,l.useState)(!1),[v,je]=(0,l.useState)(!1),[y,b]=(0,l.useState)(null),[Me,Ne]=(0,l.useState)(null),[Pe,Fe]=(0,l.useState)(`idle`),[Ie,Le]=(0,l.useState)(null),[Re,ze]=(0,l.useState)(!1),[Be,Ve]=(0,l.useState)(``),x=(0,l.useRef)(null),S=(0,l.useRef)(null),C=(0,l.useRef)(``),He=(0,l.useRef)(null),Ue=(0,l.useRef)(null),We=(0,l.useRef)(null),Ge=(0,l.useRef)(null),Ke=(0,l.useRef)(null),qe=(0,l.useRef)([]),Je=(0,l.useRef)(null),Ye=(0,l.useRef)(null),Xe=(0,l.useRef)(!1),Ze=(0,l.useRef)(!1),Qe=(0,l.useRef)(``),$e=(0,l.useRef)([]),et=(0,l.useRef)(!1),tt=(0,l.useRef)({notifyRouteChange:()=>{},cleanup:()=>{}});(0,l.useEffect)(()=>{He.current=y},[y]);let nt=()=>{Ve(``)},rt=()=>{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),b(null),Ne(null),Fe(`idle`),Le(null)},it=(e=new Date().toISOString())=>{let t=x.current,n=Je.current||Ke.current?.callId;if(!t?.connected||!n||Xe.current){console.log(`[FlowEngageProvider] skipping call:connected emit`,{callId:n,chatId:C.current,socketConnected:!!t?.connected,alreadyReported:Xe.current});return}console.log(`[FlowEngageProvider] emitting call:connected`,{callId:n,chatId:C.current,connectedAt:e}),Xe.current=!0,t.emit(`call:connected`,{callId:n,chatId:C.current,connectedAt:e})},at=(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||C.current,isAcceptingHere:t,isAlreadyActive:n,isIncomingHere:r}),b(null),t||n){Je.current=e.callId,Ne(e.callId),Fe(e=>e===`connected`?e:`connecting`),ce(!0);return}Fe(`idle`)}},ot=(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||C.current,isAcceptingHere:t,isAlreadyActive:n,isIncomingHere:r,reason:e.reason||e.status||null}),n){rt();return}Ye.current=null,Ke.current=null,qe.current=[],b(null),Fe(`idle`)}},st=async(e={})=>{let t=Ue.current,n=x.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:C.current,hasPeerConnection:!!t,socketConnected:!!n?.connected,hasOffer:!!r}),Ke.current=e;return}if(console.log(`[FlowEngageProvider] applying remote offer`,{callId:e.callId,chatId:C.current,offerLength:r.length,signalingState:t.signalingState}),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:C.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(`[FlowEngageProvider] created local answer`,{callId:e.callId,chatId:C.current,answerLength:i.sdp?.length||0,signalingState:t.signalingState}),n.emit(`call:answer`,{callId:e.callId,sdpAnswer:i.sdp,chatId:C.current})};(0,l.useEffect)(()=>{re({isOpen:_,activeScreen:le,isHumanHandled:de,agentName:pe,agentHeadshot:he})},[_,le,de,pe,he]),(0,l.useEffect)(()=>{let e=!0;return(async()=>{try{console.log(`[FlowEngageProvider] boot start`,{resolvedConfig:i,language:r});let t=d(i);console.log(`[FlowEngageProvider] config validated`,t);let n=await ae(t);if(!e)return;let o=ne();C.current=o;let c=oe({apiBaseUrl:t.apiBaseUrl,userId:n.userId,siteId:t.siteId});S.current=c,te({...n,apiBaseUrl:t.apiBaseUrl}),ie(o),console.log(`[FlowEngageProvider] bootstrap resolved`,{bootstrapData:n,resolvedChatId:o});let l=Ht({apiBaseUrl:t.apiBaseUrl,userId:n.userId,chatId:o,siteId:t.siteId});x.current=l,l.on(`connect`,()=>{console.log(`[FlowEngageProvider] socket connected`),Se(`connected`)}),l.on(`disconnect`,()=>{console.log(`[FlowEngageProvider] socket disconnected`),Se(`disconnected`)}),l.on(`aiTyping`,()=>{console.log(`[FlowEngageProvider] received aiTyping`,{chatId:C.current}),be(!0)}),l.on(`ai:typing`,()=>{console.log(`[FlowEngageProvider] received ai:typing`,{chatId:C.current}),be(!0)}),l.on(`messageReceived`,e=>{let t=e.message||e,n={...t,message:Zt(t.message)};be(!1),ve(!1),g(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&&g(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:Zt(t.message)};be(!1),(n.sender===`agent`||n.agent_name||n.sender===`ai`||n.sender===`bot`)&&ve(!1),g(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),ue(`agent`),me(nn([n.agent_name,n.agentName,n.metadata?.agentName],a)),n.sender_headshot&&ge(n.sender_headshot),ce(!0))}),l.on(`agent:joined`,e=>{let t=nn([e.agent?.name,e.agentName],a);fe(!0),ue(`agent`),me(t),ge(e.agent?.headshot||null),ce(!0),g(e=>[...e,{id:`agent-joined-${Date.now()}`,sender:`system`,message:`${t} has joined the chat.`,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`agentJoined`,e=>{let t=nn([e.agent?.name,e.agentName],a);fe(!0),ue(`agent`),me(t),ge(e.agent?.headshot||null),ce(!0),g(e=>[...e,{id:`agent-joined-${Date.now()}`,sender:`system`,message:`${t} has joined the chat.`,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`agent:left`,()=>{fe(!1),ue(`ai`),g(e=>[...e,{id:`agent-left-${Date.now()}`,sender:`system`,message:`The agent has left the chat.`,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`agentLeft`,()=>{fe(!1),ue(`ai`),g(e=>[...e,{id:`agent-left-${Date.now()}`,sender:`system`,message:`The agent has left the chat.`,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`conversationEnded`,e=>{je(!0);let t=e?.message||`This conversation has ended. Thank you for reaching out!`;g(e=>[...e,{id:`conversation-ended-${Date.now()}`,sender:`system`,message:t,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`chat:history_update`,e=>{g(Qt(e.chat_history||[]))}),l.on(`typing:start`,e=>{console.log(`[FlowEngageProvider] received typing:start`,{chatId:e?.chatId||C.current,sender:e?.sender}),e.sender===`agent`&&ve(!0)}),l.on(`typing:stop`,e=>{console.log(`[FlowEngageProvider] received typing:stop`,{chatId:e?.chatId||C.current,sender:e?.sender}),e.sender===`agent`&&ve(!1)}),l.on(`call:incoming`,(e={})=>{let t=nn([e.agentName,e.ownerName,e.agent?.name,pe],a);console.log(`[FlowEngageProvider] received call:incoming`,{callId:e.callId,chatId:C.current,agentName:t}),nt(),Xe.current=!1,b({callId:e.callId,from:e.from||`owner`,agentId:e.agentId||null,agentName:t}),me(e=>nn([t,e],a)),Fe(`incoming`),Le(null),ce(!0)}),l.on(`call:offer`,async(e={})=>{console.log(`[FlowEngageProvider] received call:offer`,{callId:e.callId,chatId:e.chatId||C.current,offerLength:(e.sdpOffer||e.offer?.sdp||``).length}),Ke.current=e;try{await st(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||C.current,hasPeerConnection:!!Ue.current,hasCandidate:!!e.candidate});return}try{let t=en(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||C.current,candidate:tn(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||C.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`,()=>{nt(),rt()}),l.on(`call:accepted`,(e={})=>{console.log(`[FlowEngageProvider] received call:accepted`,{callId:e.callId,chatId:e.chatId||C.current}),at(e)}),l.on(`call:accepted_by_other`,(e={})=>{console.log(`[FlowEngageProvider] received call:accepted_by_other`,{callId:e.callId,chatId:e.chatId||C.current}),at(e)}),l.on(`call:rejected`,(e={})=>{console.log(`[FlowEngageProvider] received call:rejected`,{callId:e.callId,chatId:e.chatId||C.current,reason:e.reason}),ot(e)}),l.on(`call:missed`,(e={})=>{console.log(`[FlowEngageProvider] received call:missed`,{callId:e.callId,chatId:e.chatId||C.current,reason:e.reason}),ot(e)}),l.on(`call:failed`,(e={})=>{console.log(`[FlowEngageProvider] received call:failed`,{callId:e.callId,chatId:e.chatId||C.current,reason:e.reason}),ot(e)}),l.on(`call:connected`,(e={})=>{if(!e.callId)return;let t=Ye.current===e.callId,n=Je.current===e.callId,r=He.current?.callId===e.callId;if(console.log(`[FlowEngageProvider] received call:connected`,{callId:e.callId,chatId:e.chatId||C.current,connectedAt:e.connectedAt,status:e.status,isAcceptingHere:t,isAlreadyActive:n,isIncomingHere:r}),!t&&!n){r&&(b(null),Fe(`idle`));return}Xe.current=!0,Ye.current=null,Je.current=e.callId,Ne(e.callId),b(null),Fe(`connected`),Le(e.connectedAt||new Date().toISOString()),ce(!0)}),l.on(`call:unavailable`,(e={})=>{rt(),Ve($t(e,`This visitor is not available for a call right now.`)),ce(!0)}),l.on(`call:error`,(e={})=>{rt(),Ve($t(e,`We couldn't connect the call right now.`)),ce(!0)}),l.on(`visitor:navigate`,({url:e,section:t,highlight:n}={})=>{e&&(console.log(`[FlowEngageProvider] visitor:navigate`,{url:e,section:t,highlight:n}),Xt(e).then(e=>{let r=t||n;r&&setTimeout(()=>{let e=qt(null,r);e&&Jt(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=qt(e||null,t||null);n&&Jt(n)}),l.on(`visitor:clear_highlight`,()=>{Yt()}),tt.current=Ut({socket:l,chatId:o}),console.log(`[FlowEngageProvider] tracking started`,{chatId:o});let u=await c.loadHistory(o,r);if(console.log(`[FlowEngageProvider] history loaded`,u),!e||(g(Qt(u.chat_history||[])),fe(!!u.is_human_handled),ue(u.is_human_handled?`agent`:le),await new Promise(e=>setTimeout(e,500)),!e))return;try{await c.startConversation(o,r)}catch{}s(`ready`),console.log(`[FlowEngageProvider] status ready`)}catch(t){if(!e)return;console.error(`[FlowEngageProvider] boot failed`,t),f(t),s(`error`)}})(),()=>{e=!1,tt.current?.cleanup?.(),rt(),x.current?.disconnect()}},[i,r]),(0,l.useEffect)(()=>()=>{if(ke&&!et.current&&$e.current.length>0){let e=C.current,t=$e.current,n=S.current,r=ee?.apiBaseUrl||``,i=ee?.userId||``;n&&e&&t.length>0&&(console.log(`[FlowEngageProvider] safety-net: syncing voice transcript on unmount`),n.beaconSyncVoice(r,i,e,t)||n.syncVoice(e,t).catch(()=>{}),et.current=!0)}},[ke,ee]),(0,l.useEffect)(()=>{if(!S.current||!h||o!==`ready`||de)return;let e=window.setInterval(async()=>{try{let e=await S.current.checkHumanHandled(h);fe(!!e.is_human_handled),e.is_human_handled&&(ue(`agent`),e.agent_info?.name&&me(e.agent_info.name),e.agent_info?.headshot&&ge(e.agent_info.headshot))}catch{}},1e4);return()=>window.clearInterval(e)},[h,o,de]);let ct=async()=>{if(!(!y?.callId||!S.current||!x.current||!h)){nt(),Ye.current=y.callId,console.log(`[FlowEngageProvider] acceptCall started`,{callId:y?.callId,chatId:h,socketConnected:!!x.current?.connected,hasPendingOffer:!!Ke.current});try{let e=await navigator.mediaDevices.getUserMedia({audio:!0});console.log(`[FlowEngageProvider] microphone stream acquired`,{callId:y.callId,chatId:h,trackCount:e.getTracks().length}),We.current=e;let t=new RTCPeerConnection({iceServers:[{urls:`stun:stun.l.google.com:19302`}]});Ue.current=t,t.onconnectionstatechange=()=>{let e=t.connectionState;if(console.log(`[FlowEngageProvider] peer connection state changed`,{callId:y.callId,chatId:h,connectionState:e,iceConnectionState:t.iceConnectionState,signalingState:t.signalingState}),e===`connected`){let e=new Date().toISOString();Fe(`connected`),Le(t=>t||e),it(e);return}e===`connecting`&&Fe(e=>e===`connected`?e:`connecting`)},t.oniceconnectionstatechange=()=>{let e=t.iceConnectionState;if(console.log(`[FlowEngageProvider] ICE connection state changed`,{callId:y.callId,chatId:h,iceConnectionState:e,connectionState:t.connectionState,signalingState:t.signalingState}),e===`connected`||e===`completed`){let e=new Date().toISOString();Fe(`connected`),Le(t=>t||e),it(e);return}(e===`checking`||e===`new`)&&Fe(e=>e===`connected`?e:`connecting`)},e.getTracks().forEach(n=>{t.addTrack(n,e)}),t.onicecandidate=e=>{if(!e.candidate||!x.current?.connected){console.log(`[FlowEngageProvider] local ICE candidate skipped`,{callId:y.callId,chatId:h,hasCandidate:!!e.candidate,socketConnected:!!x.current?.connected});return}console.log(`[FlowEngageProvider] emitting local ICE candidate`,{callId:y.callId,chatId:h,candidate:tn(e.candidate)}),x.current.emit(`call:ice-candidate`,{callId:y.callId,candidate:e.candidate,chatId:h,from:`customer`})},t.ontrack=e=>{if(console.log(`[FlowEngageProvider] remote audio track received`,{callId:y.callId,chatId:h,streamCount:e.streams?.length||0}),!Ge.current){let e=document.createElement(`audio`);e.id=`flowengage-remote-audio`,e.autoplay=!0,Ge.current=e,document.body.appendChild(e)}Ge.current.srcObject=e.streams[0]};let n=Ke.current;n&&(console.log(`[FlowEngageProvider] found pending remote offer during accept`,{callId:n.callId||y.callId,chatId:h}),await st({...n,callId:n.callId||y.callId})),await S.current.acceptCall(y.callId,h),console.log(`[FlowEngageProvider] acceptCall API succeeded`,{callId:y.callId,chatId:h}),Je.current=y.callId,Ne(y.callId),Fe(`connecting`),b(null),ce(!0)}catch(e){if(console.error(`[FlowEngageProvider] acceptCall failed`,e),Ye.current=null,rt(),e?.status===404||e?.status===409||e?.status===422){Ve($t(e,`This visitor call is no longer available.`));return}if(e?.name===`NotAllowedError`||e?.name===`PermissionDeniedError`){try{await S.current.rejectCall(y.callId,h)}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.`)}}},lt=async()=>{if(!y?.callId||!S.current||!h){rt();return}nt();try{await S.current.rejectCall(y.callId,h)}catch(e){console.error(`[FlowEngageProvider] rejectCall failed`,e),Ve($t(e,`We couldn't decline the call cleanly.`))}finally{rt()}},ut=async()=>{if(!Me||!S.current||!h){rt();return}nt();try{await S.current.endWebRTCCall(Me,h)}catch(e){console.error(`[FlowEngageProvider] endWebRTCCall failed`,e),Ve($t(e,`The call ended locally, but the server could not be updated.`))}finally{rt()}},dt=()=>{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)},ft=async()=>{if(ce(!0),S.current&&h)try{await S.current.updateChatStatus(h,`open`)}catch{}},pt=()=>{if(!h||!x.current?.connected||Ze.current){console.log(`[FlowEngageProvider] skipped typing:start emit`,{chatId:h,socketConnected:!!x.current?.connected,alreadyTyping:Ze.current});return}Ze.current=!0,console.log(`[FlowEngageProvider] emitting typing:start`,{chatId:h,sender:`user`}),x.current.emit(`typing:start`,{chatId:h,sender:`user`})},mt=()=>{if(h&&x.current?.connected&&Qe.current!==``&&(console.log(`[FlowEngageProvider] clearing typing draft`,{chatId:h,sender:`user`}),x.current.emit(`typing:update`,{chatId:h,sender:`user`,text:``}),Qe.current=``),!h||!x.current?.connected||!Ze.current){console.log(`[FlowEngageProvider] skipped typing:stop emit`,{chatId:h,socketConnected:!!x.current?.connected,wasTyping:Ze.current});return}Ze.current=!1,console.log(`[FlowEngageProvider] emitting typing:stop`,{chatId:h,sender:`user`}),x.current.emit(`typing:stop`,{chatId:h,sender:`user`})},ht=(e=``)=>{let t=typeof e==`string`?e:``;if(!h||!x.current?.connected){console.log(`[FlowEngageProvider] skipped typing:update emit`,{chatId:h,socketConnected:!!x.current?.connected,textLength:t.length});return}Qe.current!==t&&(Qe.current=t,console.log(`[FlowEngageProvider] emitting typing:update`,{chatId:h,sender:`user`,textLength:t.length}),x.current.emit(`typing:update`,{chatId:h,sender:`user`,text:t}))},gt=async(e,t=``,n=null)=>{if(!e.trim()||!S.current||!h||o!==`ready`||v)return;mt();let i=`pending-user-${Date.now()}`,a={id:i,sender:`user`,message:e,timestamp:new Date().toISOString(),isPending:!0,...n||{}};if(g(e=>[...e,a]),de&&x.current?.connected){x.current.emit(`customer:message`,{chatId:h,content:e,sender:`user`,...n||{}});return}we(!0);try{let i=await S.current.sendAiMessage(h,e,r,t,n);g(Qt(i.chat_history||[])),fe(!!i.is_human_handled),ue(i.is_human_handled?`agent`:`ai`),be(!1),await S.current.updateChatStatus(h,`messageSent`)}catch(e){g(e=>e.filter(e=>e.id!==i)),be(!1),e.status===429?(Ee(!0),Oe(e.message),window.setTimeout(()=>{Ee(!1),Oe(``)},p)):f(e)}finally{we(!1)}},_t=async e=>{if(!(!S.current||!h)){try{let t=e?`voice`:`text`;await S.current.setChatMode(h,t)}catch(e){console.error(`[FlowEngageProvider] setVoiceMode failed`,e)}Ae(e),e&&(et.current=!1)}},vt=async e=>{if(!et.current){if(et.current=!0,!S.current||!h||!e?.length){Ae(!1);return}try{let t=await S.current.syncVoice(h,e);if(t?.chat_history)g(Qt(t.chat_history));else{let t=e.map((e,t)=>({id:`voice-${Date.now()}-${t}`,sender:e.role===`user`?`user`:`bot`,message:e.message,timestamp:new Date().toISOString(),isPending:!1,fromVoice:!0}));g(e=>[...e,...t])}}catch{}finally{Ae(!1)}}},yt=async()=>{if(!(!S.current||!h)){ke&&!et.current&&$e.current.length>0&&await vt($e.current);try{await S.current.endConversation(h)}catch{try{await S.current.updateChatStatus(h,`ended`)}catch{}}je(!0),g(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}])}},bt=(0,l.useMemo)(()=>({status:o,error:c,runtimeConfig:ee,resolvedConfig:i,chatId:h,chatHistory:se,isOpen:_,activeScreen:le,isHumanHandled:de,agentName:pe,agentHeadshot:he,isAgentTyping:_e,isAiTyping:ye,connectionStatus:xe,isLoading:Ce,isVoiceMode:ke,isRateLimited:Te,rateLimitMessage:De,isConversationEnded:v,incomingCall:y,activeCallId:Me,callConnectionState:Pe,callConnectedAt:Ie,isCallMuted:Re,webRTCError:Be,language:r,historyRef:$e,hasSyncedRef:et,dismissCallError:nt,startTyping:pt,stopTyping:mt,updateTypingDraft:ht,notifyRouteChange:()=>tt.current?.notifyRouteChange?.(),openWidget:ft,closeWidget:()=>ce(!1),toggleWidget:()=>{if(_){ce(!1);return}ft()},sendMessage:gt,setVoiceMode:_t,onMessageSync:vt,endConversation:yt,acceptCall:ct,rejectCall:lt,endWebRTCCall:ut,toggleCallMute:dt,startTyping:pt,stopTyping:mt,updateTypingDraft:ht}),[o,c,ee,i,h,se,_,le,de,pe,he,_e,ye,xe,Ce,ke,Te,De,v,y,Me,Pe,Ie,Re,Be,r,pt,mt,ht,ct,lt,ut,dt,ft,gt,_t,vt,yt,nt]);return(0,u.jsx)(Wt.Provider,{value:bt,children:n})}var an=({color:e=`#3888FF`})=>(0,u.jsxs)(`svg`,{width:`40`,height:`40`,viewBox:`0 0 40 40`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,u.jsx)(`rect`,{width:`40`,height:`40`,rx:`20`,fill:e}),(0,u.jsx)(`path`,{d:`M26 8H14C12.3431 8 11 9.34315 11 11V23C11 24.6569 12.3431 26 14 26H26C27.6569 26 29 24.6569 29 23V11C29 9.34315 27.6569 8 26 8Z`,fill:`#ECF0F0`}),(0,u.jsx)(`path`,{d:`M18 32L18 26L24 26L18 32Z`,fill:`#ECF0F0`}),(0,u.jsx)(`path`,{d:`M16.4067 20.5924C16.182 20.3674 16.1822 20.003 16.407 19.7783L22.7805 13.4068C23.0051 13.1821 23.3694 13.1823 23.5939 13.4071V13.4071C23.8182 13.6317 23.8181 13.9956 23.5936 14.2201L17.2212 20.5926C16.9962 20.8176 16.6315 20.8174 16.4067 20.5924V20.5924Z`,fill:`#3E87C8`})]}),on=()=>(0,u.jsx)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:(0,u.jsx)(`path`,{d:`M2.01 21L23 12 2.01 3 2 10l15 2-15 2z`,fill:`currentColor`})}),sn=({size:e=18,color:t=`currentColor`})=>(0,u.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,u.jsx)(`path`,{d:`M12 1a4 4 0 014 4v6a4 4 0 01-8 0V5a4 4 0 014-4z`,fill:t}),(0,u.jsx)(`path`,{d:`M19 10a7 7 0 01-14 0M12 19v4M8 23h8`,stroke:t,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})]}),cn=({size:e=20})=>(0,u.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,u.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,u.jsx)(`line`,{x1:`23`,y1:`1`,x2:`1`,y2:`23`})]}),ln=()=>(0,u.jsxs)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,u.jsx)(`line`,{x1:`12`,y1:`19`,x2:`12`,y2:`5`}),(0,u.jsx)(`polyline`,{points:`5 12 12 5 19 12`})]}),un=()=>(0,u.jsxs)(`svg`,{width:`14`,height:`14`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,u.jsx)(`polyline`,{points:`9 17 4 12 9 7`}),(0,u.jsx)(`path`,{d:`M20 18v-2a4 4 0 00-4-4H4`})]}),dn=()=>(0,u.jsx)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,u.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`})}),fn=({className:e=``})=>(0,u.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,u.jsx)(`circle`,{cx:`12`,cy:`12`,r:`10`}),(0,u.jsx)(`line`,{x1:`12`,y1:`8`,x2:`12`,y2:`12`}),(0,u.jsx)(`line`,{x1:`12`,y1:`16`,x2:`12.01`,y2:`16`})]});function pn({isOpen:e,openWidget:t,launcherText:n,primaryColor:r,posClass:i}){return e?null:(0,u.jsxs)(`button`,{className:`flex items-center border-0 cursor-pointer p-0 bg-transparent transition-all duration-200 hover:-translate-y-0.5 group ${i} fixed`,onClick:t,"aria-label":n,children:[(0,u.jsxs)(`div`,{className:`hidden md:flex items-center gap-3 px-6 py-3.5 rounded-full bg-[var(--flowengage-primary)] text-white shadow-[0_8px_24px_rgba(0,0,0,0.15)] font-semibold text-[16px] hover:shadow-[0_12px_28px_rgba(0,0,0,0.2)]`,children:[n,(0,u.jsx)(on,{})]}),(0,u.jsx)(`div`,{className:`md:hidden flex items-center justify-center p-0 shadow-[0_8px_24px_rgba(0,0,0,0.15)] rounded-full hover:shadow-[0_12px_28px_rgba(0,0,0,0.2)] transition-shadow`,children:(0,u.jsx)(an,{color:r})})]})}function mn(e){return typeof e==`string`?e.trim():e&&typeof e==`object`&&typeof e.src==`string`?e.src.trim():``}function hn(e){let[t,n]=(0,l.useState)(`loading`),r=mn(e);return(0,l.useEffect)(()=>{if(l.default.isValidElement(e)||typeof e==`function`){n(`square`);return}if(!r){n(`error`);return}n(`loading`);let t=new Image,i=!1;return t.onload=()=>{i||n(t.naturalWidth/t.naturalHeight>1.3?`wide`:`square`)},t.onerror=()=>{i||n(`error`)},t.src=r,()=>{i=!0}},[e,r]),{state:t,resolvedLogoUrl:r}}function gn({logoUrl:e,brandName:t,agentName:n,fallbackAgentName:r,activeScreen:i,branding:a,isConversationEnded:o,closeWidget:s,isInitial:c}){let{state:d,resolvedLogoUrl:f}=hn(e);return(0,u.jsxs)(`div`,{className:`flex justify-between items-start px-5 pt-4 pb-4 rounded-t-[inherit] border-none transition-all duration-300 ${c?`bg-transparent text-white`:`bg-white text-gray-900 border-b border-black/5 shadow-sm`}`,children:[(0,u.jsxs)(`div`,{className:`flex items-center gap-3`,children:[d!==`loading`&&(d===`error`||!f&&!e?(0,u.jsx)(`div`,{className:`w-11 h-11 rounded-full flowengage-logo-fallback flex-shrink-0`}):l.default.isValidElement(e)?(0,u.jsx)(`div`,{className:`w-11 h-11 rounded-full shrink-0 overflow-hidden flex items-center justify-center bg-white [&>svg]:w-full [&>svg]:h-full`,children:e}):typeof e==`function`?(0,u.jsx)(`div`,{className:`w-11 h-11 rounded-full shrink-0 overflow-hidden flex items-center justify-center bg-white [&>svg]:w-full [&>svg]:h-full`,children:(0,u.jsx)(e,{})}):d===`wide`?(0,u.jsx)(`div`,{className:`h-9 max-w-[88px] flex-shrink-0 flex items-center justify-center rounded-lg px-2 py-1 ${c?`bg-white/15 backdrop-blur-sm`:`bg-gray-50 border border-black/5`}`,children:(0,u.jsx)(`img`,{src:f,alt:`Logo`,className:`h-full w-auto max-w-full object-contain`})}):(0,u.jsx)(`div`,{className:`w-11 h-11 rounded-full shrink-0 overflow-hidden flex items-center justify-center bg-white`,children:(0,u.jsx)(`img`,{src:f,alt:`Logo`,className:`w-full h-full object-contain ${f.toLowerCase().includes(`.svg`)||f.startsWith(`data:image/svg`)?``:`p-[2px]`}`})})),d===`loading`&&(0,u.jsx)(`div`,{className:`w-11 h-11 rounded-full bg-white/20 animate-pulse flex-shrink-0`}),(0,u.jsxs)(`div`,{children:[(0,u.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,u.jsx)(`div`,{className:`text-[16px] font-bold`,children:i===`agent`?n||r||a.fallbackAgentName||`Agent`:t}),i!==`agent`&&(0,u.jsx)(`div`,{className:`bg-white/95 text-(--flowengage-primary) text-[10px] font-extrabold px-1.5 py-[3px] rounded-md tracking-[0.5px]`,children:`● AI`})]}),(0,u.jsxs)(`div`,{className:`text-[13px] opacity-95 mt-0.5`,children:[i===`agent`?`Live support`:`Usually replies `,i!==`agent`&&(0,u.jsx)(`span`,{className:`text-emerald-500 font-semibold`,children:`instantly`})]})]})]}),(0,u.jsx)(`div`,{className:`flex items-center gap-1`,children:(0,u.jsx)(`button`,{className:`w-8 h-8 rounded-full bg-transparent flex items-center justify-center transition-all duration-200 border-0 cursor-pointer text-xl ${c?`text-white hover:bg-white/10`:`text-black hover:bg-black/5`}`,onClick:s,children:`×`})})]})}var _n=(e=``)=>String(e).replace(/<[^>]+>/g,``).replace(/\s+/g,` `).trim();function vn({chatHistory:e,isAiTyping:t,isAgentTyping:n,setReplyContext:r,TypingDots:i}){let a=(0,l.useRef)(null),o=e=>{if(!e)return`just now`;let t=new Date,n=new Date(e),r=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,l.useEffect)(()=>{a.current&&a.current.scrollIntoView({behavior:`smooth`})},[e.length,t,n]),(0,u.jsxs)(`div`,{className:`flex-1 overflow-y-auto px-5 pt-2.5 pb-5 flex flex-col`,children:[e.map(e=>{let t=e.sender===`system`,n=e.sender===`user`,i=e.sender===`ai`||e.sender===`bot`,a=e.isPending,s=_n(e.replyToContent||e.replyContext?.message||``),c=e.replyToSender===`user`?`You`:e.replyToSender===`agent`?`Agent`:e.replyToSender===`ai`||e.replyToSender===`bot`?`AI Assistant`:`Message`;return t?(0,u.jsx)(`div`,{className:`flex justify-center my-2`,children:(0,u.jsx)(`div`,{className:`px-3 py-1.5 rounded-full bg-gray-100 text-gray-500 text-[12px] font-medium`,children:e.message})},e.id):(0,u.jsx)(`div`,{className:`flex mb-3 ${n?`justify-end`:`justify-start`} group`,style:{position:`relative`},children:(0,u.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,alignItems:n?`flex-end`:`flex-start`,maxWidth:`85%`},children:[!a&&(0,u.jsxs)(`button`,{onClick:()=>r(e),className:`opacity-0 group-hover:opacity-100 transition-opacity mb-1 flex items-center gap-1 text-[11px] text-gray-400 bg-transparent border-0 cursor-pointer hover:text-gray-600`,children:[(0,u.jsx)(un,{}),`Reply`]}),(0,u.jsxs)(`div`,{className:`px-4 py-3 rounded-[18px] leading-[1.5] shadow-[0_2px_6px_rgba(0,0,0,0.04)] ${n?`bg-[var(--flowengage-primary)] text-white whitespace-pre-wrap`:`bg-white text-gray-900`}`,style:{opacity:a?.55:1,transition:`opacity 0.3s ease`},children:[s&&(0,u.jsxs)(`div`,{className:`mb-2 rounded-[14px] border-l-2 px-3 py-2 text-[12px] ${n?`border-white/80 bg-white/15 text-white/90`:`border-[var(--flowengage-primary)] bg-gray-50 text-gray-500`}`,children:[(0,u.jsx)(`div`,{className:`mb-0.5 font-semibold`,children:c}),(0,u.jsx)(`div`,{style:{display:`-webkit-box`,WebkitLineClamp:2,WebkitBoxOrient:`vertical`,overflow:`hidden`},children:s})]}),i?(0,u.jsx)(`div`,{className:`flowengage-message-content`,dangerouslySetInnerHTML:{__html:e.message}}):(0,u.jsx)(`div`,{className:n?``:`whitespace-pre-wrap`,children:e.message}),a&&(0,u.jsx)(`span`,{className:`text-[10px] ml-1.5 opacity-70 whitespace-nowrap`,children:`sending…`})]}),(0,u.jsxs)(`div`,{className:`flex items-center gap-1 mt-1 px-1 ${n?`justify-end`:`justify-start`}`,children:[(0,u.jsx)(`span`,{className:`text-[10px] text-gray-400 font-medium whitespace-nowrap`,children:o(e.timestamp||e.createdAt||Date.now())}),(0,u.jsx)(`span`,{className:`text-[10px] font-bold ${n?`text-[var(--flowengage-primary)]`:`text-gray-400`}`,children:a?`○`:`✓`})]})]})},e.id)}),t&&(0,u.jsx)(i,{}),n&&(0,u.jsx)(i,{}),(0,u.jsx)(`div`,{ref:a})]})}function yn({greetings:e,recommendations:t,onSendMessage:n}){return(0,u.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,u.jsx)(`div`,{className:`mt-[30px] mb-auto px-5`,children:(0,u.jsx)(`div`,{className:`text-[34px] font-bold text-white leading-[1.15]`,children:e?.split(`
|
|
8
|
+
`,document.head.appendChild(e)};function qt(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=document.querySelectorAll(`h1, h2, h3, h4, h5, h6, [data-section]`);for(let e of r)if(e.textContent.toLowerCase().includes(n))return e;let i=n.split(/\s+/).filter(e=>e.length>2);if(i.length>1){let e=null,t=0;for(let n of r){let r=n.textContent.toLowerCase(),a=0;for(let e of i)r.includes(e)&&a++;let o=a/i.length;o>t&&o>=.6&&(t=o,e=n)}if(e)return e}let a=document.querySelectorAll(`li, strong, blockquote, dt`);for(let e of a){let t=e.textContent.toLowerCase();if(t.includes(n)&&t.length<500)return e.tagName===`STRONG`&&e.parentElement?.tagName===`LI`?e.parentElement:e}let o=document.querySelectorAll(`p`);for(let e of o){let t=e.textContent.toLowerCase();if(t.includes(n)&&t.length<800)return e}return null}function Jt(e){!e||typeof document>`u`||(Kt(),Yt(),e.classList.add(`fe-highlight-section`),e.scrollIntoView({behavior:`smooth`,block:`center`}))}function Yt(){typeof document>`u`||document.querySelectorAll(`.fe-highlight-section`).forEach(e=>e.classList.remove(`fe-highlight-section`))}async function Xt(e){if(typeof window>`u`)return!1;try{let t=new URL(e,window.location.origin);if(t.origin!==window.location.origin)return window.location.href=e,!0;if(t.hash&&t.pathname===window.location.pathname){let e=t.hash.slice(1),n=document.getElementById(e);if(n)return n.scrollIntoView({behavior:`smooth`,block:`start`}),!0}if(t.pathname===window.location.pathname&&t.search===window.location.search&&!t.hash)return!1;let n=t.pathname+t.search+t.hash,r=window.next?.router;if(r?.push)return new Promise(e=>{let t=()=>{r.events?.off(`routeChangeComplete`,t),e(!0)};r.events?.on(`routeChangeComplete`,t),r.push(n),setTimeout(t,4e3)});let i=window.__NEXT_ROUTER__;return i?.push?(i.push(n),!0):window.history?.pushState?(window.history.pushState({},``,n),window.dispatchEvent(new PopStateEvent(`popstate`,{state:{}})),!0):(window.location.href=e,!0)}catch(t){return console.warn(`[FlowEngage] shadowNavigate error:`,t),window.location.href=e,!0}}var Zt=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(),Qt=(e=[])=>e.map(e=>({...e,message:Zt(e.message),isPending:!1,id:e.messageId||`${e.sender}-${e.timestamp||Date.now()}-${Math.random()}`})),$t=(e,t)=>e?typeof e==`string`?e:e.message||e.error||e.reason||t:t,en=(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}:{}}},tn=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}},nn=(e=[],t=`Agent`)=>{for(let t of e)if(typeof t==`string`&&t.trim())return t.trim();return t};function rn({siteId:e,config:t,children:n,language:r=`en`}){let i=(0,l.useMemo)(()=>e?{...t||{},siteId:e}:t||null,[e,t]),a=(0,l.useMemo)(()=>nn([i?.widgetSettings?.branding?.fallbackAgentName,i?.widgetSettings?.branding?.headerName],`Agent`),[i]),[o,s]=(0,l.useState)(`booting`),[c,f]=(0,l.useState)(null),[ee,te]=(0,l.useState)(null),[h,ie]=(0,l.useState)(``),[se,g]=(0,l.useState)([]),[_,ce]=(0,l.useState)(m().isOpen),[le,ue]=(0,l.useState)(m().activeScreen),[de,fe]=(0,l.useState)(m().isHumanHandled),[pe,me]=(0,l.useState)(m().agentName),[he,ge]=(0,l.useState)(m().agentHeadshot),[_e,ve]=(0,l.useState)(!1),[ye,be]=(0,l.useState)(!1),[xe,Se]=(0,l.useState)(`idle`),[Ce,we]=(0,l.useState)(!1),[Te,Ee]=(0,l.useState)(!1),[De,Oe]=(0,l.useState)(``),[ke,Ae]=(0,l.useState)(!1),[v,je]=(0,l.useState)(!1),[y,b]=(0,l.useState)(null),[Me,Ne]=(0,l.useState)(null),[Pe,Fe]=(0,l.useState)(`idle`),[Ie,Le]=(0,l.useState)(null),[Re,ze]=(0,l.useState)(!1),[Be,Ve]=(0,l.useState)(``),x=(0,l.useRef)(null),S=(0,l.useRef)(null),C=(0,l.useRef)(``),He=(0,l.useRef)(null),Ue=(0,l.useRef)(null),We=(0,l.useRef)(null),Ge=(0,l.useRef)(null),Ke=(0,l.useRef)(null),qe=(0,l.useRef)([]),Je=(0,l.useRef)(null),Ye=(0,l.useRef)(null),Xe=(0,l.useRef)(!1),Ze=(0,l.useRef)(!1),Qe=(0,l.useRef)(``),$e=(0,l.useRef)([]),et=(0,l.useRef)(!1),tt=(0,l.useRef)({notifyRouteChange:()=>{},cleanup:()=>{}});(0,l.useEffect)(()=>{He.current=y},[y]);let nt=()=>{Ve(``)},rt=()=>{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),b(null),Ne(null),Fe(`idle`),Le(null)},it=(e=new Date().toISOString())=>{let t=x.current,n=Je.current||Ke.current?.callId;if(!t?.connected||!n||Xe.current){console.log(`[FlowEngageProvider] skipping call:connected emit`,{callId:n,chatId:C.current,socketConnected:!!t?.connected,alreadyReported:Xe.current});return}console.log(`[FlowEngageProvider] emitting call:connected`,{callId:n,chatId:C.current,connectedAt:e}),Xe.current=!0,t.emit(`call:connected`,{callId:n,chatId:C.current,connectedAt:e})},at=(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||C.current,isAcceptingHere:t,isAlreadyActive:n,isIncomingHere:r}),b(null),t||n){Je.current=e.callId,Ne(e.callId),Fe(e=>e===`connected`?e:`connecting`),ce(!0);return}Fe(`idle`)}},ot=(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||C.current,isAcceptingHere:t,isAlreadyActive:n,isIncomingHere:r,reason:e.reason||e.status||null}),n){rt();return}Ye.current=null,Ke.current=null,qe.current=[],b(null),Fe(`idle`)}},st=async(e={})=>{let t=Ue.current,n=x.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:C.current,hasPeerConnection:!!t,socketConnected:!!n?.connected,hasOffer:!!r}),Ke.current=e;return}if(console.log(`[FlowEngageProvider] applying remote offer`,{callId:e.callId,chatId:C.current,offerLength:r.length,signalingState:t.signalingState}),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:C.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(`[FlowEngageProvider] created local answer`,{callId:e.callId,chatId:C.current,answerLength:i.sdp?.length||0,signalingState:t.signalingState}),n.emit(`call:answer`,{callId:e.callId,sdpAnswer:i.sdp,chatId:C.current})};(0,l.useEffect)(()=>{re({isOpen:_,activeScreen:le,isHumanHandled:de,agentName:pe,agentHeadshot:he})},[_,le,de,pe,he]),(0,l.useEffect)(()=>{let e=!0;return(async()=>{try{console.log(`[FlowEngageProvider] boot start`,{resolvedConfig:i,language:r});let t=d(i);console.log(`[FlowEngageProvider] config validated`,t);let n=await ae(t);if(!e)return;let o=ne();C.current=o;let c=oe({apiBaseUrl:t.apiBaseUrl,userId:n.userId,siteId:t.siteId});S.current=c,te({...n,apiBaseUrl:t.apiBaseUrl}),ie(o),console.log(`[FlowEngageProvider] bootstrap resolved`,{bootstrapData:n,resolvedChatId:o});let l=Ht({apiBaseUrl:t.apiBaseUrl,userId:n.userId,chatId:o,siteId:t.siteId});x.current=l,l.on(`connect`,()=>{console.log(`[FlowEngageProvider] socket connected`),Se(`connected`)}),l.on(`disconnect`,()=>{console.log(`[FlowEngageProvider] socket disconnected`),Se(`disconnected`)}),l.on(`aiTyping`,()=>{console.log(`[FlowEngageProvider] received aiTyping`,{chatId:C.current}),be(!0)}),l.on(`ai:typing`,()=>{console.log(`[FlowEngageProvider] received ai:typing`,{chatId:C.current}),be(!0)}),l.on(`messageReceived`,e=>{let t=e.message||e,n={...t,message:Zt(t.message)};be(!1),ve(!1),g(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&&g(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:Zt(t.message)};be(!1),(n.sender===`agent`||n.agent_name||n.sender===`ai`||n.sender===`bot`)&&ve(!1),g(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),ue(`agent`),me(nn([n.agent_name,n.agentName,n.metadata?.agentName],a)),n.sender_headshot&&ge(n.sender_headshot),ce(!0))}),l.on(`agent:joined`,e=>{let t=nn([e.agent?.name,e.agentName],a);fe(!0),ue(`agent`),me(t),ge(e.agent?.headshot||null),ce(!0),g(e=>[...e,{id:`agent-joined-${Date.now()}`,sender:`system`,message:`${t} has joined the chat.`,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`agentJoined`,e=>{let t=nn([e.agent?.name,e.agentName],a);fe(!0),ue(`agent`),me(t),ge(e.agent?.headshot||null),ce(!0),g(e=>[...e,{id:`agent-joined-${Date.now()}`,sender:`system`,message:`${t} has joined the chat.`,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`agent:left`,()=>{fe(!1),ue(`ai`),g(e=>[...e,{id:`agent-left-${Date.now()}`,sender:`system`,message:`The agent has left the chat.`,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`agentLeft`,()=>{fe(!1),ue(`ai`),g(e=>[...e,{id:`agent-left-${Date.now()}`,sender:`system`,message:`The agent has left the chat.`,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`conversationEnded`,e=>{je(!0);let t=e?.message||`This conversation has ended. Thank you for reaching out!`;g(e=>[...e,{id:`conversation-ended-${Date.now()}`,sender:`system`,message:t,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`chat:history_update`,e=>{g(Qt(e.chat_history||[]))}),l.on(`typing:start`,e=>{console.log(`[FlowEngageProvider] received typing:start`,{chatId:e?.chatId||C.current,sender:e?.sender}),e.sender===`agent`&&ve(!0)}),l.on(`typing:stop`,e=>{console.log(`[FlowEngageProvider] received typing:stop`,{chatId:e?.chatId||C.current,sender:e?.sender}),e.sender===`agent`&&ve(!1)}),l.on(`call:incoming`,(e={})=>{let t=nn([e.agentName,e.ownerName,e.agent?.name,pe],a);console.log(`[FlowEngageProvider] received call:incoming`,{callId:e.callId,chatId:C.current,agentName:t}),nt(),Xe.current=!1,b({callId:e.callId,from:e.from||`owner`,agentId:e.agentId||null,agentName:t}),me(e=>nn([t,e],a)),Fe(`incoming`),Le(null),ce(!0)}),l.on(`call:offer`,async(e={})=>{console.log(`[FlowEngageProvider] received call:offer`,{callId:e.callId,chatId:e.chatId||C.current,offerLength:(e.sdpOffer||e.offer?.sdp||``).length}),Ke.current=e;try{await st(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||C.current,hasPeerConnection:!!Ue.current,hasCandidate:!!e.candidate});return}try{let t=en(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||C.current,candidate:tn(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||C.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`,()=>{nt(),rt()}),l.on(`call:accepted`,(e={})=>{console.log(`[FlowEngageProvider] received call:accepted`,{callId:e.callId,chatId:e.chatId||C.current}),at(e)}),l.on(`call:accepted_by_other`,(e={})=>{console.log(`[FlowEngageProvider] received call:accepted_by_other`,{callId:e.callId,chatId:e.chatId||C.current}),at(e)}),l.on(`call:rejected`,(e={})=>{console.log(`[FlowEngageProvider] received call:rejected`,{callId:e.callId,chatId:e.chatId||C.current,reason:e.reason}),ot(e)}),l.on(`call:missed`,(e={})=>{console.log(`[FlowEngageProvider] received call:missed`,{callId:e.callId,chatId:e.chatId||C.current,reason:e.reason}),ot(e)}),l.on(`call:failed`,(e={})=>{console.log(`[FlowEngageProvider] received call:failed`,{callId:e.callId,chatId:e.chatId||C.current,reason:e.reason}),ot(e)}),l.on(`call:connected`,(e={})=>{if(!e.callId)return;let t=Ye.current===e.callId,n=Je.current===e.callId,r=He.current?.callId===e.callId;if(console.log(`[FlowEngageProvider] received call:connected`,{callId:e.callId,chatId:e.chatId||C.current,connectedAt:e.connectedAt,status:e.status,isAcceptingHere:t,isAlreadyActive:n,isIncomingHere:r}),!t&&!n){r&&(b(null),Fe(`idle`));return}Xe.current=!0,Ye.current=null,Je.current=e.callId,Ne(e.callId),b(null),Fe(`connected`),Le(e.connectedAt||new Date().toISOString()),ce(!0)}),l.on(`call:unavailable`,(e={})=>{rt(),Ve($t(e,`This visitor is not available for a call right now.`)),ce(!0)}),l.on(`call:error`,(e={})=>{rt(),Ve($t(e,`We couldn't connect the call right now.`)),ce(!0)}),l.on(`visitor:navigate`,({url:e,section:t,highlight:n}={})=>{e&&(console.log(`[FlowEngageProvider] visitor:navigate`,{url:e,section:t,highlight:n}),Xt(e).then(e=>{let r=t||n;r&&setTimeout(()=>{let e=qt(null,r);e&&Jt(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=qt(e||null,t||null);n&&Jt(n)}),l.on(`visitor:clear_highlight`,()=>{Yt()}),tt.current=Ut({socket:l,chatId:o}),console.log(`[FlowEngageProvider] tracking started`,{chatId:o});let u=await c.loadHistory(o,r);if(console.log(`[FlowEngageProvider] history loaded`,u),!e||(g(Qt(u.chat_history||[])),fe(!!u.is_human_handled),ue(u.is_human_handled?`agent`:le),await new Promise(e=>setTimeout(e,500)),!e))return;try{await c.startConversation(o,r)}catch{}s(`ready`),console.log(`[FlowEngageProvider] status ready`)}catch(t){if(!e)return;console.error(`[FlowEngageProvider] boot failed`,t),f(t),s(`error`)}})(),()=>{e=!1,tt.current?.cleanup?.(),rt(),x.current?.disconnect()}},[i,r]),(0,l.useEffect)(()=>()=>{if(ke&&!et.current&&$e.current.length>0){let e=C.current,t=$e.current,n=S.current,r=ee?.apiBaseUrl||``,i=ee?.userId||``;n&&e&&t.length>0&&(console.log(`[FlowEngageProvider] safety-net: syncing voice transcript on unmount`),n.beaconSyncVoice(r,i,e,t)||n.syncVoice(e,t).catch(()=>{}),et.current=!0)}},[ke,ee]),(0,l.useEffect)(()=>{if(!S.current||!h||o!==`ready`||de)return;let e=window.setInterval(async()=>{try{let e=await S.current.checkHumanHandled(h);fe(!!e.is_human_handled),e.is_human_handled&&(ue(`agent`),e.agent_info?.name&&me(e.agent_info.name),e.agent_info?.headshot&&ge(e.agent_info.headshot))}catch{}},1e4);return()=>window.clearInterval(e)},[h,o,de]);let ct=async()=>{if(!(!y?.callId||!S.current||!x.current||!h)){nt(),Ye.current=y.callId,console.log(`[FlowEngageProvider] acceptCall started`,{callId:y?.callId,chatId:h,socketConnected:!!x.current?.connected,hasPendingOffer:!!Ke.current});try{let e=await navigator.mediaDevices.getUserMedia({audio:!0});console.log(`[FlowEngageProvider] microphone stream acquired`,{callId:y.callId,chatId:h,trackCount:e.getTracks().length}),We.current=e;let t=new RTCPeerConnection({iceServers:[{urls:`stun:stun.l.google.com:19302`}]});Ue.current=t,t.onconnectionstatechange=()=>{let e=t.connectionState;if(console.log(`[FlowEngageProvider] peer connection state changed`,{callId:y.callId,chatId:h,connectionState:e,iceConnectionState:t.iceConnectionState,signalingState:t.signalingState}),e===`connected`){let e=new Date().toISOString();Fe(`connected`),Le(t=>t||e),it(e);return}e===`connecting`&&Fe(e=>e===`connected`?e:`connecting`)},t.oniceconnectionstatechange=()=>{let e=t.iceConnectionState;if(console.log(`[FlowEngageProvider] ICE connection state changed`,{callId:y.callId,chatId:h,iceConnectionState:e,connectionState:t.connectionState,signalingState:t.signalingState}),e===`connected`||e===`completed`){let e=new Date().toISOString();Fe(`connected`),Le(t=>t||e),it(e);return}(e===`checking`||e===`new`)&&Fe(e=>e===`connected`?e:`connecting`)},e.getTracks().forEach(n=>{t.addTrack(n,e)}),t.onicecandidate=e=>{if(!e.candidate||!x.current?.connected){console.log(`[FlowEngageProvider] local ICE candidate skipped`,{callId:y.callId,chatId:h,hasCandidate:!!e.candidate,socketConnected:!!x.current?.connected});return}console.log(`[FlowEngageProvider] emitting local ICE candidate`,{callId:y.callId,chatId:h,candidate:tn(e.candidate)}),x.current.emit(`call:ice-candidate`,{callId:y.callId,candidate:e.candidate,chatId:h,from:`customer`})},t.ontrack=e=>{if(console.log(`[FlowEngageProvider] remote audio track received`,{callId:y.callId,chatId:h,streamCount:e.streams?.length||0}),!Ge.current){let e=document.createElement(`audio`);e.id=`flowengage-remote-audio`,e.autoplay=!0,Ge.current=e,document.body.appendChild(e)}Ge.current.srcObject=e.streams[0]};let n=Ke.current;n&&(console.log(`[FlowEngageProvider] found pending remote offer during accept`,{callId:n.callId||y.callId,chatId:h}),await st({...n,callId:n.callId||y.callId})),await S.current.acceptCall(y.callId,h),console.log(`[FlowEngageProvider] acceptCall API succeeded`,{callId:y.callId,chatId:h}),Je.current=y.callId,Ne(y.callId),Fe(`connecting`),b(null),ce(!0)}catch(e){if(console.error(`[FlowEngageProvider] acceptCall failed`,e),Ye.current=null,rt(),e?.status===404||e?.status===409||e?.status===422){Ve($t(e,`This visitor call is no longer available.`));return}if(e?.name===`NotAllowedError`||e?.name===`PermissionDeniedError`){try{await S.current.rejectCall(y.callId,h)}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.`)}}},lt=async()=>{if(!y?.callId||!S.current||!h){rt();return}nt();try{await S.current.rejectCall(y.callId,h)}catch(e){console.error(`[FlowEngageProvider] rejectCall failed`,e),Ve($t(e,`We couldn't decline the call cleanly.`))}finally{rt()}},ut=async()=>{if(!Me||!S.current||!h){rt();return}nt();try{await S.current.endWebRTCCall(Me,h)}catch(e){console.error(`[FlowEngageProvider] endWebRTCCall failed`,e),Ve($t(e,`The call ended locally, but the server could not be updated.`))}finally{rt()}},dt=()=>{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)},ft=async()=>{if(ce(!0),S.current&&h)try{await S.current.updateChatStatus(h,`open`)}catch{}},pt=()=>{if(!h||!x.current?.connected||Ze.current){console.log(`[FlowEngageProvider] skipped typing:start emit`,{chatId:h,socketConnected:!!x.current?.connected,alreadyTyping:Ze.current});return}Ze.current=!0,console.log(`[FlowEngageProvider] emitting typing:start`,{chatId:h,sender:`user`}),x.current.emit(`typing:start`,{chatId:h,sender:`user`})},mt=()=>{if(h&&x.current?.connected&&Qe.current!==``&&(console.log(`[FlowEngageProvider] clearing typing draft`,{chatId:h,sender:`user`}),x.current.emit(`typing:update`,{chatId:h,sender:`user`,text:``}),Qe.current=``),!h||!x.current?.connected||!Ze.current){console.log(`[FlowEngageProvider] skipped typing:stop emit`,{chatId:h,socketConnected:!!x.current?.connected,wasTyping:Ze.current});return}Ze.current=!1,console.log(`[FlowEngageProvider] emitting typing:stop`,{chatId:h,sender:`user`}),x.current.emit(`typing:stop`,{chatId:h,sender:`user`})},ht=(e=``)=>{let t=typeof e==`string`?e:``;if(!h||!x.current?.connected){console.log(`[FlowEngageProvider] skipped typing:update emit`,{chatId:h,socketConnected:!!x.current?.connected,textLength:t.length});return}Qe.current!==t&&(Qe.current=t,console.log(`[FlowEngageProvider] emitting typing:update`,{chatId:h,sender:`user`,textLength:t.length}),x.current.emit(`typing:update`,{chatId:h,sender:`user`,text:t}))},gt=async(e,t=``,n=null)=>{if(!e.trim()||!S.current||!h||o!==`ready`||v)return;mt();let i=`pending-user-${Date.now()}`,a={id:i,sender:`user`,message:e,timestamp:new Date().toISOString(),isPending:!0,...n||{}};if(g(e=>[...e,a]),de&&x.current?.connected){x.current.emit(`customer:message`,{chatId:h,content:e,sender:`user`,...n||{}});return}we(!0);try{let i=await S.current.sendAiMessage(h,e,r,t,n);g(Qt(i.chat_history||[])),fe(!!i.is_human_handled),ue(i.is_human_handled?`agent`:`ai`),be(!1),await S.current.updateChatStatus(h,`messageSent`)}catch(e){g(e=>e.filter(e=>e.id!==i)),be(!1),e.status===429?(Ee(!0),Oe(e.message),window.setTimeout(()=>{Ee(!1),Oe(``)},p)):f(e)}finally{we(!1)}},_t=async e=>{if(!(!S.current||!h)){try{let t=e?`voice`:`text`;await S.current.setChatMode(h,t)}catch(e){console.error(`[FlowEngageProvider] setVoiceMode failed`,e)}Ae(e),e&&(et.current=!1)}},vt=async e=>{if(!et.current){if(et.current=!0,!S.current||!h||!e?.length){Ae(!1);return}try{let t=await S.current.syncVoice(h,e);if(t?.chat_history)g(Qt(t.chat_history));else{let t=e.map((e,t)=>({id:`voice-${Date.now()}-${t}`,sender:e.role===`user`?`user`:`bot`,message:e.message,timestamp:new Date().toISOString(),isPending:!1,fromVoice:!0}));g(e=>[...e,...t])}}catch{}finally{Ae(!1)}}},yt=async()=>{if(!(!S.current||!h)){ke&&!et.current&&$e.current.length>0&&await vt($e.current);try{await S.current.endConversation(h)}catch{try{await S.current.updateChatStatus(h,`ended`)}catch{}}je(!0),g(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}])}},bt=(0,l.useMemo)(()=>({status:o,error:c,runtimeConfig:ee,resolvedConfig:i,chatId:h,chatHistory:se,isOpen:_,activeScreen:le,isHumanHandled:de,agentName:pe,agentHeadshot:he,isAgentTyping:_e,isAiTyping:ye,connectionStatus:xe,isLoading:Ce,isVoiceMode:ke,isRateLimited:Te,rateLimitMessage:De,isConversationEnded:v,incomingCall:y,activeCallId:Me,callConnectionState:Pe,callConnectedAt:Ie,isCallMuted:Re,webRTCError:Be,language:r,historyRef:$e,hasSyncedRef:et,dismissCallError:nt,startTyping:pt,stopTyping:mt,updateTypingDraft:ht,notifyRouteChange:()=>tt.current?.notifyRouteChange?.(),openWidget:ft,closeWidget:()=>ce(!1),toggleWidget:()=>{if(_){ce(!1);return}ft()},sendMessage:gt,setVoiceMode:_t,onMessageSync:vt,endConversation:yt,acceptCall:ct,rejectCall:lt,endWebRTCCall:ut,toggleCallMute:dt,startTyping:pt,stopTyping:mt,updateTypingDraft:ht}),[o,c,ee,i,h,se,_,le,de,pe,he,_e,ye,xe,Ce,ke,Te,De,v,y,Me,Pe,Ie,Re,Be,r,pt,mt,ht,ct,lt,ut,dt,ft,gt,_t,vt,yt,nt]);return(0,u.jsx)(Wt.Provider,{value:bt,children:n})}var an=({color:e=`#3888FF`})=>(0,u.jsxs)(`svg`,{width:`40`,height:`40`,viewBox:`0 0 40 40`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,u.jsx)(`rect`,{width:`40`,height:`40`,rx:`20`,fill:e}),(0,u.jsx)(`path`,{d:`M26 8H14C12.3431 8 11 9.34315 11 11V23C11 24.6569 12.3431 26 14 26H26C27.6569 26 29 24.6569 29 23V11C29 9.34315 27.6569 8 26 8Z`,fill:`#ECF0F0`}),(0,u.jsx)(`path`,{d:`M18 32L18 26L24 26L18 32Z`,fill:`#ECF0F0`}),(0,u.jsx)(`path`,{d:`M16.4067 20.5924C16.182 20.3674 16.1822 20.003 16.407 19.7783L22.7805 13.4068C23.0051 13.1821 23.3694 13.1823 23.5939 13.4071V13.4071C23.8182 13.6317 23.8181 13.9956 23.5936 14.2201L17.2212 20.5926C16.9962 20.8176 16.6315 20.8174 16.4067 20.5924V20.5924Z`,fill:`#3E87C8`})]}),on=()=>(0,u.jsx)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:(0,u.jsx)(`path`,{d:`M2.01 21L23 12 2.01 3 2 10l15 2-15 2z`,fill:`currentColor`})}),sn=({size:e=18,color:t=`currentColor`})=>(0,u.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,u.jsx)(`path`,{d:`M12 1a4 4 0 014 4v6a4 4 0 01-8 0V5a4 4 0 014-4z`,fill:t}),(0,u.jsx)(`path`,{d:`M19 10a7 7 0 01-14 0M12 19v4M8 23h8`,stroke:t,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})]}),cn=({size:e=20})=>(0,u.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,u.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,u.jsx)(`line`,{x1:`23`,y1:`1`,x2:`1`,y2:`23`})]}),ln=()=>(0,u.jsxs)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,u.jsx)(`line`,{x1:`12`,y1:`19`,x2:`12`,y2:`5`}),(0,u.jsx)(`polyline`,{points:`5 12 12 5 19 12`})]}),un=()=>(0,u.jsxs)(`svg`,{width:`14`,height:`14`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,u.jsx)(`polyline`,{points:`9 17 4 12 9 7`}),(0,u.jsx)(`path`,{d:`M20 18v-2a4 4 0 00-4-4H4`})]}),dn=()=>(0,u.jsx)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,u.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`})}),fn=({className:e=``})=>(0,u.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,u.jsx)(`circle`,{cx:`12`,cy:`12`,r:`10`}),(0,u.jsx)(`line`,{x1:`12`,y1:`8`,x2:`12`,y2:`12`}),(0,u.jsx)(`line`,{x1:`12`,y1:`16`,x2:`12.01`,y2:`16`})]});function pn({isOpen:e,openWidget:t,launcherText:n,primaryColor:r,posInline:i}){return e?null:(0,u.jsxs)(`button`,{className:`flex items-center border-0 cursor-pointer p-0 bg-transparent group`,style:{position:`fixed`,...i,transition:`transform 0.2s ease`},onMouseEnter:e=>e.currentTarget.style.transform=`translateY(-2px)`,onMouseLeave:e=>e.currentTarget.style.transform=`translateY(0)`,onClick:t,"aria-label":n,children:[(0,u.jsxs)(`div`,{className:`hidden md:flex items-center gap-3 rounded-full text-white font-semibold`,style:{background:r,padding:`0.875rem 1.5rem`,fontSize:`16px`,boxShadow:`0 8px 24px rgba(0,0,0,0.15)`},children:[n,(0,u.jsx)(on,{})]}),(0,u.jsx)(`div`,{className:`md:hidden flex items-center justify-center rounded-full`,style:{padding:0,boxShadow:`0 8px 24px rgba(0,0,0,0.15)`},children:(0,u.jsx)(an,{color:r})})]})}function mn(e){return typeof e==`string`?e.trim():e&&typeof e==`object`&&typeof e.src==`string`?e.src.trim():``}function hn(e){let[t,n]=(0,l.useState)(`loading`),r=mn(e);return(0,l.useEffect)(()=>{if(l.default.isValidElement(e)||typeof e==`function`){n(`square`);return}if(!r){n(`error`);return}n(`loading`);let t=new Image,i=!1;return t.onload=()=>{i||n(t.naturalWidth/t.naturalHeight>1.3?`wide`:`square`)},t.onerror=()=>{i||n(`error`)},t.src=r,()=>{i=!0}},[e,r]),{state:t,resolvedLogoUrl:r}}function gn({logoUrl:e,brandName:t,agentName:n,fallbackAgentName:r,activeScreen:i,branding:a,isConversationEnded:o,closeWidget:s,isInitial:c}){let{state:d,resolvedLogoUrl:f}=hn(e);return(0,u.jsxs)(`div`,{className:`flex justify-between items-start px-5 pt-4 pb-4 rounded-t-[inherit] border-none transition-all duration-300 ${c?`bg-transparent text-white`:`bg-white text-gray-900 border-b border-black/5 shadow-sm`}`,children:[(0,u.jsxs)(`div`,{className:`flex items-center gap-3`,children:[d!==`loading`&&(d===`error`||!f&&!e?(0,u.jsx)(`div`,{className:`w-11 h-11 rounded-full flowengage-logo-fallback flex-shrink-0`}):l.default.isValidElement(e)?(0,u.jsx)(`div`,{className:`w-11 h-11 rounded-full shrink-0 overflow-hidden flex items-center justify-center bg-white [&>svg]:w-full [&>svg]:h-full`,children:e}):typeof e==`function`?(0,u.jsx)(`div`,{className:`w-11 h-11 rounded-full shrink-0 overflow-hidden flex items-center justify-center bg-white [&>svg]:w-full [&>svg]:h-full`,children:(0,u.jsx)(e,{})}):d===`wide`?(0,u.jsx)(`div`,{className:`h-9 max-w-[88px] flex-shrink-0 flex items-center justify-center rounded-lg px-2 py-1 ${c?`bg-white/15 backdrop-blur-sm`:`bg-gray-50 border border-black/5`}`,children:(0,u.jsx)(`img`,{src:f,alt:`Logo`,className:`h-full w-auto max-w-full object-contain`})}):(0,u.jsx)(`div`,{className:`w-11 h-11 rounded-full shrink-0 overflow-hidden flex items-center justify-center bg-white`,children:(0,u.jsx)(`img`,{src:f,alt:`Logo`,className:`w-full h-full object-contain ${f.toLowerCase().includes(`.svg`)||f.startsWith(`data:image/svg`)?``:`p-[2px]`}`})})),d===`loading`&&(0,u.jsx)(`div`,{className:`w-11 h-11 rounded-full bg-white/20 animate-pulse flex-shrink-0`}),(0,u.jsxs)(`div`,{children:[(0,u.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,u.jsx)(`div`,{className:`text-[16px] font-bold`,children:i===`agent`?n||r||a.fallbackAgentName||`Agent`:t}),i!==`agent`&&(0,u.jsx)(`div`,{className:`bg-white/95 text-(--flowengage-primary) text-[10px] font-extrabold px-1.5 py-[3px] rounded-md tracking-[0.5px]`,children:`● AI`})]}),(0,u.jsxs)(`div`,{className:`text-[13px] opacity-95 mt-0.5`,children:[i===`agent`?`Live support`:`Usually replies `,i!==`agent`&&(0,u.jsx)(`span`,{className:`text-emerald-500 font-semibold`,children:`instantly`})]})]})]}),(0,u.jsx)(`div`,{className:`flex items-center gap-1`,children:(0,u.jsx)(`button`,{className:`w-8 h-8 rounded-full bg-transparent flex items-center justify-center transition-all duration-200 border-0 cursor-pointer text-xl ${c?`text-white hover:bg-white/10`:`text-black hover:bg-black/5`}`,onClick:s,children:`×`})})]})}var _n=(e=``)=>String(e).replace(/<[^>]+>/g,``).replace(/\s+/g,` `).trim();function vn({chatHistory:e,isAiTyping:t,isAgentTyping:n,setReplyContext:r,TypingDots:i}){let a=(0,l.useRef)(null),o=e=>{if(!e)return`just now`;let t=new Date,n=new Date(e),r=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,l.useEffect)(()=>{a.current&&a.current.scrollIntoView({behavior:`smooth`})},[e.length,t,n]),(0,u.jsxs)(`div`,{className:`flex-1 overflow-y-auto px-5 pt-2.5 pb-5 flex flex-col`,children:[e.map(e=>{let t=e.sender===`system`,n=e.sender===`user`,i=e.sender===`ai`||e.sender===`bot`,a=e.isPending,s=_n(e.replyToContent||e.replyContext?.message||``),c=e.replyToSender===`user`?`You`:e.replyToSender===`agent`?`Agent`:e.replyToSender===`ai`||e.replyToSender===`bot`?`AI Assistant`:`Message`;return t?(0,u.jsx)(`div`,{className:`flex justify-center my-2`,children:(0,u.jsx)(`div`,{className:`px-3 py-1.5 rounded-full bg-gray-100 text-gray-500 text-[12px] font-medium`,children:e.message})},e.id):(0,u.jsx)(`div`,{className:`flex mb-3 ${n?`justify-end`:`justify-start`} group`,style:{position:`relative`},children:(0,u.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,alignItems:n?`flex-end`:`flex-start`,maxWidth:`85%`},children:[!a&&(0,u.jsxs)(`button`,{onClick:()=>r(e),className:`opacity-0 group-hover:opacity-100 transition-opacity mb-1 flex items-center gap-1 text-[11px] text-gray-400 bg-transparent border-0 cursor-pointer hover:text-gray-600`,children:[(0,u.jsx)(un,{}),`Reply`]}),(0,u.jsxs)(`div`,{className:`px-4 py-3 rounded-[18px] leading-[1.5] shadow-[0_2px_6px_rgba(0,0,0,0.04)] ${n?`bg-[var(--flowengage-primary)] text-white whitespace-pre-wrap`:`bg-white text-gray-900`}`,style:{opacity:a?.55:1,transition:`opacity 0.3s ease`},children:[s&&(0,u.jsxs)(`div`,{className:`mb-2 rounded-[14px] border-l-2 px-3 py-2 text-[12px] ${n?`border-white/80 bg-white/15 text-white/90`:`border-[var(--flowengage-primary)] bg-gray-50 text-gray-500`}`,children:[(0,u.jsx)(`div`,{className:`mb-0.5 font-semibold`,children:c}),(0,u.jsx)(`div`,{style:{display:`-webkit-box`,WebkitLineClamp:2,WebkitBoxOrient:`vertical`,overflow:`hidden`},children:s})]}),i?(0,u.jsx)(`div`,{className:`flowengage-message-content`,dangerouslySetInnerHTML:{__html:e.message}}):(0,u.jsx)(`div`,{className:n?``:`whitespace-pre-wrap`,children:e.message}),a&&(0,u.jsx)(`span`,{className:`text-[10px] ml-1.5 opacity-70 whitespace-nowrap`,children:`sending…`})]}),(0,u.jsxs)(`div`,{className:`flex items-center gap-1 mt-1 px-1 ${n?`justify-end`:`justify-start`}`,children:[(0,u.jsx)(`span`,{className:`text-[10px] text-gray-400 font-medium whitespace-nowrap`,children:o(e.timestamp||e.createdAt||Date.now())}),(0,u.jsx)(`span`,{className:`text-[10px] font-bold ${n?`text-[var(--flowengage-primary)]`:`text-gray-400`}`,children:a?`○`:`✓`})]})]})},e.id)}),t&&(0,u.jsx)(i,{}),n&&(0,u.jsx)(i,{}),(0,u.jsx)(`div`,{ref:a})]})}function yn({greetings:e,recommendations:t,onSendMessage:n}){return(0,u.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,u.jsx)(`div`,{className:`mt-[30px] mb-auto px-5`,children:(0,u.jsx)(`div`,{className:`text-[34px] font-bold text-white leading-[1.15]`,children:e?.split(`
|
|
9
9
|
`).map((e,t)=>(0,u.jsx)(`div`,{children:e},t))||(0,u.jsxs)(u.Fragment,{children:[(0,u.jsx)(`div`,{children:`Hi there 👋`}),(0,u.jsx)(`div`,{children:`How can we help?`})]})})}),(0,u.jsx)(`div`,{className:`flex flex-col items-end gap-3 mb-1.5 px-5 pb-5`,children:t.map(e=>(0,u.jsx)(`button`,{className:`px-[18px] py-3 rounded-[20px] bg-white text-gray-900 font-medium text-[14px] shadow-[0_4px_12px_rgba(0,0,0,0.06)] border border-black/5 transition-transform duration-200 hover:-translate-y-0.5 hover:shadow-[0_6px_16px_rgba(0,0,0,0.1)] cursor-pointer text-left`,onClick:()=>n(e.label,e.key),children:e.label},e.key))})]})}function bn({input:e,setInput:t,onSubmit:n,isConversationEnded:r,callUiActive:i,handleToggleVoice:a,activeScreen:o,inputDisabled:s,replyContext:c,clearReplyContext:l}){let d=c?.sender===`user`?`You`:c?.sender===`agent`?`Agent`:`AI Assistant`;return(0,u.jsxs)(`div`,{className:`px-5 bg-transparent pb-1`,children:[r&&(0,u.jsx)(`div`,{className:`mb-2 px-4 py-2 rounded-xl bg-gray-100 text-gray-500 text-[12px] text-center font-medium`,children:`This conversation has ended.`}),c&&(0,u.jsxs)(`div`,{className:`mb-2 flex items-start justify-between gap-3 rounded-2xl border border-black/5 bg-white px-4 py-3 shadow-[0_8px_24px_rgba(0,0,0,0.05)]`,children:[(0,u.jsxs)(`div`,{className:`min-w-0 flex-1 border-l-2 border-[var(--flowengage-primary)] pl-3`,children:[(0,u.jsxs)(`div`,{className:`text-[12px] font-semibold text-[var(--flowengage-primary)]`,children:[`Replying to `,d]}),(0,u.jsx)(`div`,{className:`truncate text-[12px] text-gray-500`,children:c.replyToContent||c.message})]}),(0,u.jsx)(`button`,{type:`button`,className:`h-7 w-7 rounded-full border-0 bg-gray-100 text-gray-500 transition-colors hover:bg-gray-200 hover:text-gray-700`,onClick:l,"aria-label":`Cancel reply`,children:`×`})]}),(0,u.jsxs)(`form`,{className:`flex items-center gap-2 px-2.5 py-1.5 border border-black/5 rounded-full bg-white shadow-[0_8px_24px_rgba(0,0,0,0.05)]`,onSubmit:n,style:{opacity:r?.5:1},children:[(0,u.jsx)(`button`,{type:`button`,className:`w-8 h-8 rounded-full bg-transparent text-gray-400 flex items-center justify-center transition-colors duration-200 hover:bg-gray-100 border-0 cursor-pointer`,onClick:a,title:`Start voice call`,disabled:r||i,children:(0,u.jsx)(dn,{})}),(0,u.jsx)(`input`,{className:`flex-1 min-w-0 border-none font-[inherit] text-[14px] outline-none py-1.5 text-gray-900 bg-transparent placeholder-gray-400`,value:e,onChange:e=>t(e.target.value),placeholder:r?`Conversation ended`:o===`agent`?`Message the agent…`:`Type a reply…`,disabled:s}),(0,u.jsx)(`button`,{type:`submit`,className:`w-[34px] h-[34px] rounded-full bg-transparent text-[var(--flowengage-primary)] border border-[var(--flowengage-primary)] flex items-center justify-center transition-all duration-200 enabled:hover:bg-[var(--flowengage-primary)] enabled:hover:text-white disabled:opacity-50 disabled:cursor-not-allowed disabled:border-gray-300 disabled:text-gray-300 cursor-pointer ml-1`,disabled:s,children:(0,u.jsx)(ln,{})})]})]})}var xn=({muted:e=!1})=>(0,u.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,u.jsx)(`path`,{d:`M12 1a4 4 0 014 4v6a4 4 0 01-6.83 2.83`}),(0,u.jsx)(`path`,{d:`M19 10a7 7 0 01-1.62 4.49M5 10a7 7 0 008.79 6.77`}),(0,u.jsx)(`path`,{d:`M12 19v4M8 23h8`}),e&&(0,u.jsx)(`line`,{x1:`2`,y1:`2`,x2:`22`,y2:`22`})]}),Sn=({variant:e,onClick:t,children:n,icon:r,compact:i=!1,active:a=!1})=>(0,u.jsxs)(`button`,{type:`button`,className:[`flowengage-call-btn`,`flowengage-call-btn-${e}`,i?`compact`:``,a?`active`:``].filter(Boolean).join(` `),onClick:t,children:[r,(0,u.jsx)(`span`,{children:n})]});function Cn({webRTCError:e,micError:t,setMicError:n,dismissCallError:r,incomingCall:i,rejectCall:a,acceptCall:o,activeCallId:s,callConnectionState:c,formatCallDuration:d,callDurationSeconds:f,endWebRTCCall:ee,isCallMuted:p,toggleCallMute:te,isAIVoiceActive:ne,currentCallAgentName:m,isRateLimited:re,rateLimitMessage:h}){let ie=(0,l.useRef)(null),ae=(0,l.useCallback)(()=>{if(!ie.current)return;let{audioContext:e,oscillator:t,interval:n,toneTimeout:r}=ie.current;window.clearInterval(n),window.clearTimeout(r);try{t.stop()}catch{}try{e.close()}catch{}ie.current=null},[]),oe=(0,l.useCallback)(()=>{if(ie.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=()=>{ie.current&&(window.clearTimeout(ie.current.toneTimeout),n.frequency.value=440,ie.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(),ie.current={audioContext:t,oscillator:n,interval:null,toneTimeout:null},i(),ie.current.interval=window.setInterval(i,1e3)}catch(e){console.warn(`[FlowEngage] failed to start ringtone`,e)}},[]);(0,l.useEffect)(()=>{if(i){oe();return}ae()},[i,oe,ae]),(0,l.useEffect)(()=>()=>ae(),[ae]);let se=ne?`header-mode`:`bottom-mode`,g=!!(i||s),_=i?`incoming`:c===`connected`?`connected`:`connecting`,ce=(0,l.useMemo)(()=>_===`incoming`?`Incoming Call`:_===`connected`?`Voice Call Active`:`Connecting Call`,[_]),le=(0,l.useMemo)(()=>_===`incoming`?`${m} wants to join a voice call`:_===`connected`?`You are connected to ${m} from this conversation.`:`Please wait while ${m}'s voice connection finishes setting up.`,[m,_]);return(0,u.jsxs)(u.Fragment,{children:[(e||t)&&(0,u.jsxs)(`div`,{className:`mx-5 mb-2.5 px-4 py-3 rounded-xl bg-red-50 border border-red-100 flex items-start gap-2.5`,children:[(0,u.jsx)(fn,{className:`shrink-0 mt-0.5`}),(0,u.jsx)(`span`,{className:`text-[12px] text-red-700 leading-[1.5] flex-1`,children:e||t}),(0,u.jsx)(`button`,{className:`shrink-0 bg-transparent border-0 text-red-400 hover:text-red-600 cursor-pointer text-lg leading-none`,onClick:()=>{n(null),r()},children:`×`})]}),g&&(0,u.jsx)(`div`,{className:`incoming-call-overlay ${se}`,children:(0,u.jsx)(`div`,{className:[`incoming-call-container`,_===`connected`?`connected-layout`:``].filter(Boolean).join(` `),children:_===`connected`?(0,u.jsxs)(u.Fragment,{children:[(0,u.jsxs)(`div`,{className:`call-connected-top`,children:[(0,u.jsxs)(`div`,{className:`call-connected-identity`,children:[(0,u.jsx)(`div`,{className:`call-icon-wrapper ${_}`,children:(0,u.jsx)(cn,{size:20})}),(0,u.jsxs)(`div`,{className:`call-info-group`,children:[(0,u.jsx)(`h3`,{className:`call-title`,children:ce}),(0,u.jsx)(`p`,{className:`call-subtitle`,children:le})]})]}),(0,u.jsx)(`div`,{className:`call-timer`,children:d(f)})]}),(0,u.jsxs)(`div`,{className:`call-actions connected`,children:[(0,u.jsx)(Sn,{variant:`mute`,onClick:te,compact:ne,active:p,icon:(0,u.jsx)(xn,{muted:p}),children:p?`Unmute`:`Mute`}),(0,u.jsx)(Sn,{variant:`end`,onClick:ee,compact:ne,icon:(0,u.jsx)(cn,{size:14}),children:`End`})]})]}):(0,u.jsxs)(u.Fragment,{children:[(0,u.jsxs)(`div`,{className:`call-icon-wrapper ${_}`,children:[(0,u.jsx)(dn,{}),_===`incoming`&&(0,u.jsx)(`div`,{className:`call-pulse-animation`}),_===`connecting`&&(0,u.jsx)(`div`,{className:`call-connecting-animation`})]}),(0,u.jsxs)(`div`,{className:`call-info-group`,children:[(0,u.jsx)(`h3`,{className:`call-title`,children:ce}),(0,u.jsx)(`p`,{className:`call-subtitle`,children:le})]}),(0,u.jsx)(`div`,{className:`call-actions`,children:_===`incoming`&&(0,u.jsxs)(u.Fragment,{children:[(0,u.jsx)(Sn,{variant:`reject`,onClick:async()=>{ae(),await a()},compact:ne,icon:(0,u.jsx)(cn,{size:14}),children:`Decline`}),(0,u.jsx)(Sn,{variant:`accept`,onClick:async()=>{ae(),await o()},compact:ne,icon:(0,u.jsx)(dn,{}),children:`Accept`})]})})]})})}),re&&(0,u.jsx)(`div`,{className:`mx-5 mb-2.5 px-4 py-3 text-[13px] rounded-xl bg-red-100 text-red-800`,children:h})]})}function wn(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 Tn=Object.defineProperty,En=(e,t,n)=>t in e?Tn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Dn=(e,t,n)=>En(e,typeof t==`symbol`?t:t+``,n),On=class{constructor(){Dn(this,`_locking`),Dn(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 T(e,t){if(!e)throw Error(t)}var kn=34028234663852886e22,An=-34028234663852886e22,jn=4294967295,Mn=2147483647,Nn=-2147483648;function Pn(e){if(typeof e!=`number`)throw Error(`invalid int 32: `+typeof e);if(!Number.isInteger(e)||e>Mn||e<Nn)throw Error(`invalid int 32: `+e)}function Fn(e){if(typeof e!=`number`)throw Error(`invalid uint 32: `+typeof e);if(!Number.isInteger(e)||e>jn||e<0)throw Error(`invalid uint 32: `+e)}function In(e){if(typeof e!=`number`)throw Error(`invalid float 32: `+typeof e);if(Number.isFinite(e)&&(e>kn||e<An))throw Error(`invalid float 32: `+e)}var Ln=Symbol(`@bufbuild/protobuf/enum-type`);function Rn(e){let t=e[Ln];return T(t,`missing enum type on enum object`),t}function zn(e,t,n,r){e[Ln]=Bn(t,n.map(t=>({no:t.no,name:t.name,localName:e[t.no]})))}function Bn(e,t,n){let r=Object.create(null),i=Object.create(null),a=[];for(let e of t){let t=Hn(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 Vn(e,t,n){let r={};for(let e of t){let t=Hn(e);r[t.localName]=t.no,r[t.no]=t.localName}return zn(r,e,t),r}function Hn(e){return`localName`in e?e:Object.assign(Object.assign({},e),{localName:e.name})}var Un=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 Wn(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 Un),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 Gn(){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 Kn(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 qn=4294967296;function Jn(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>=qn&&(i+=r/qn|0,r%=qn)}return a(-24,-18),a(-18,-12),a(-12,-6),a(-6),t?$n(r,i):Qn(r,i)}function Yn(e,t){let n=Qn(e,t),r=n.hi&2147483648;r&&(n=$n(n.lo,n.hi));let i=Xn(n.lo,n.hi);return r?`-`+i:i}function Xn(e,t){if({lo:e,hi:t}=Zn(e,t),t<=2097151)return String(qn*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()+er(o)+er(a)}function Zn(e,t){return{lo:e>>>0,hi:t>>>0}}function Qn(e,t){return{lo:e|0,hi:t|0}}function $n(e,t){return t=~t,e?e=~e+1:t+=1,Qn(e,t)}var er=e=>{let t=String(e);return`0000000`.slice(t.length)+t};function tr(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 nr(){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 rr(){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=>T(/^-?[0-9]+$/.test(e),`int64 invalid: ${e}`),n=e=>T(/^[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),Jn(e)},uEnc(e){return typeof e!=`string`&&(e=e.toString()),n(e),Jn(e)},dec(e,t){return Yn(e,t)},uDec(e,t){return Xn(e,t)}}}var E=rr(),D;(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`})(D||={});var ir;(function(e){e[e.BIGINT=0]=`BIGINT`,e[e.STRING=1]=`STRING`})(ir||={});function ar(e,t,n){if(t===n)return!0;if(e==D.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 D.UINT64:case D.FIXED64:case D.INT64:case D.SFIXED64:case D.SINT64:return t==n}return!1}function or(e,t){switch(e){case D.BOOL:return!1;case D.UINT64:case D.FIXED64:case D.INT64:case D.SFIXED64:case D.SINT64:return t==0?E.zero:`0`;case D.DOUBLE:case D.FLOAT:return 0;case D.BYTES:return new Uint8Array;case D.STRING:return``;default:return 0}}function sr(e,t){switch(e){case D.BOOL:return t===!1;case D.STRING:return t===``;case D.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return t==0}}var O;(function(e){e[e.Varint=0]=`Varint`,e[e.Bit64=1]=`Bit64`,e[e.LengthDelimited=2]=`LengthDelimited`,e[e.StartGroup=3]=`StartGroup`,e[e.EndGroup=4]=`EndGroup`,e[e.Bit32=5]=`Bit32`})(O||={});var cr=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(Fn(e);e>127;)this.buf.push(e&127|128),e>>>=7;return this.buf.push(e),this}int32(e){return Pn(e),tr(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){In(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){Fn(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){Pn(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return Pn(e),e=(e<<1^e>>31)>>>0,tr(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),r=E.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=E.uEnc(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(t)}int64(e){let t=E.enc(e);return Kn(t.lo,t.hi,this.buf),this}sint64(e){let t=E.enc(e),n=t.hi>>31;return Kn(t.lo<<1^n,(t.hi<<1|t.lo>>>31)^n,this.buf),this}uint64(e){let t=E.uEnc(e);return Kn(t.lo,t.hi,this.buf),this}},lr=class{constructor(e,t){this.varint64=Gn,this.uint32=nr,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 O.Varint:for(;this.buf[this.pos++]&128;);break;case O.Bit64:this.pos+=4;case O.Bit32:this.pos+=4;break;case O.LengthDelimited:let n=this.uint32();this.pos+=n;break;case O.StartGroup:for(;;){let[e,n]=this.tag();if(n===O.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 E.dec(...this.varint64())}uint64(){return E.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),n=-(e&1);return e=(e>>>1|(t&1)<<31)^n,t=t>>>1^n,E.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 E.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return E.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 ur(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 dr(e){let t=e.field.localName,n=Object.create(null);return n[t]=fr(e),[n,()=>n[t]]}function fr(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 or(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 pr(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 mr=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`.split(``),hr=[];for(let e=0;e<mr.length;e++)hr[mr[e].charCodeAt(0)]=e;hr[45]=mr.indexOf(`+`),hr[95]=mr.indexOf(`/`);var gr={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=hr[e.charCodeAt(t)],a===void 0)switch(e[t]){case`=`:i=0;case`
|
|
10
10
|
`: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+=mr[r>>2],i=(r&3)<<4,n=1;break;case 1:t+=mr[i|r>>4],i=(r&15)<<2,n=2;break;case 2:t+=mr[i|r>>6],t+=mr[r&63],n=0;break}return n&&(t+=mr[i],t+=`=`,n==1&&(t+=`=`)),t}};function _r(e,t,n){br(t,e);let r=t.runtime.bin.makeReadOptions(n),i=pr(e.getType().runtime.bin.listUnknownFields(e),t.field),[a,o]=dr(t);for(let e of i)t.runtime.bin.readField(a,r.readerFactory(e.data),t.field,e.wireType,r);return o()}function vr(e,t,n,r){br(t,e);let i=t.runtime.bin.makeReadOptions(r),a=t.runtime.bin.makeWriteOptions(r);if(yr(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 yr(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 br(e,t){T(e.extendee.typeName==t.getType().typeName,`extension ${e.typeName} can only be applied to message ${e.extendee.typeName}`)}function xr(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:!sr(e.T,t[n]);case`message`:return t[n]!==void 0;case`map`:return Object.keys(t[n]).length>0}}function Sr(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?or(e.T,e.L):void 0;break;case`message`:t[n]=void 0;break}}function Cr(e,t){if(typeof e!=`object`||!e||!Object.getOwnPropertyNames(Un.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 wr(e,t){return Cr(t)||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}D.DOUBLE,D.FLOAT,D.INT64,D.UINT64,D.INT32,D.UINT32,D.BOOL,D.STRING,D.BYTES;var Tr={ignoreUnknownFields:!1},Er={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function Dr(e){return e?Object.assign(Object.assign({},Tr),e):Tr}function Or(e){return e?Object.assign(Object.assign({},Er),e):Er}var kr=Symbol(),Ar=Symbol();function jr(){return{makeReadOptions:Dr,makeWriteOptions:Or,readMessage(e,t,n,r){if(t==null||Array.isArray(t)||typeof t!=`object`)throw Error(`cannot decode message ${e.typeName} from JSON: ${Mr(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)}Nr(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]=dr(i);Nr(e,s,i.field,n,i),vr(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(!xr(i,e)){if(i.req)throw`required field not set`;if(!t.emitDefaultValues||!Lr(i))continue}let n=i.oneof?e[i.oneof.localName].value:e[i.localName],a=Rr(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&&yr(e,o)){let n=_r(e,o,t),i=Rr(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 Fr(e,t,n??ir.BIGINT,!0)},writeScalar(e,t,n){if(t!==void 0&&(n||sr(e,t)))return Br(e,t)},debug:Mr}}function Mr(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 Nr(e,t,n,r,i){let a=n.localName;if(n.repeated){if(T(n.kind!=`map`),t===null)return;if(!Array.isArray(t))throw Error(`cannot decode field ${i.typeName}.${n.name} from JSON: ${Mr(t)}`);let o=e[a];for(let e of t){if(e===null)throw Error(`cannot decode field ${i.typeName}.${n.name} from JSON: ${Mr(e)}`);switch(n.kind){case`message`:o.push(n.T.fromJson(e,r));break;case`enum`:let t=Ir(n.T,e,r.ignoreUnknownFields,!0);t!==Ar&&o.push(t);break;case`scalar`:try{o.push(Fr(n.T,e,n.L,!0))}catch(t){let r=`cannot decode field ${i.typeName}.${n.name} from JSON: ${Mr(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: ${Mr(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=Pr(n.K,e)}catch(e){let r=`cannot decode map key for field ${i.typeName}.${n.name} from JSON: ${Mr(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=Ir(n.V.T,a,r.ignoreUnknownFields,!0);e!==Ar&&(o[s]=e);break;case`scalar`:try{o[s]=Fr(n.V.T,a,ir.BIGINT,!0)}catch(e){let r=`cannot decode map value for field ${i.typeName}.${n.name} from JSON: ${Mr(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];Cr(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=Ir(n.T,t,r.ignoreUnknownFields,!1);switch(c){case kr:Sr(n,e);break;case Ar:break;default:e[a]=c;break}break;case`scalar`:try{let r=Fr(n.T,t,n.L,!1);switch(r){case kr:Sr(n,e);break;default:e[a]=r;break}}catch(e){let r=`cannot decode field ${i.typeName}.${n.name} from JSON: ${Mr(t)}`;throw e instanceof Error&&e.message.length>0&&(r+=`: ${e.message}`),Error(r)}break}}function Pr(e,t){if(e===D.BOOL)switch(t){case`true`:t=!0;break;case`false`:t=!1;break}return Fr(e,t,ir.BIGINT,!0).toString()}function Fr(e,t,n,r){if(t===null)return r?or(e,n):kr;switch(e){case D.DOUBLE:case D.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==D.FLOAT&&In(r),r;case D.INT32:case D.FIXED32:case D.SFIXED32:case D.SINT32:case D.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==D.UINT32||e==D.FIXED32?Fn(i):Pn(i),i;case D.INT64:case D.SFIXED64:case D.SINT64:if(typeof t!=`number`&&typeof t!=`string`)break;let a=E.parse(t);return n?a.toString():a;case D.FIXED64:case D.UINT64:if(typeof t!=`number`&&typeof t!=`string`)break;let o=E.uParse(t);return n?o.toString():o;case D.BOOL:if(typeof t!=`boolean`)break;return t;case D.STRING:if(typeof t!=`string`)break;return t;case D.BYTES:if(t===``)return new Uint8Array;if(typeof t!=`string`)break;return gr.dec(t)}throw Error()}function Ir(e,t,n,r){if(t===null)return e.typeName==`google.protobuf.NullValue`?0:r?e.values[0].no:kr;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 Ar;break}throw Error(`cannot decode enum ${e.typeName} from JSON: ${Mr(t)}`)}function Lr(e){return e.repeated||e.kind==`map`?!0:!(e.oneof||e.kind==`message`||e.opt||e.req)}function Rr(e,t,n){if(e.kind==`map`){T(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()]=Br(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()]=zr(t,a,n.enumAsInteger);break}return n.emitDefaultValues||i.length>0?r:void 0}if(e.repeated){T(Array.isArray(t));let r=[];switch(e.kind){case`scalar`:for(let n=0;n<t.length;n++)r.push(Br(e.T,t[n]));break;case`enum`:for(let i=0;i<t.length;i++)r.push(zr(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 Br(e.T,t);case`enum`:return zr(e.T,t,n.enumAsInteger);case`message`:return wr(e.T,t).toJson(n)}}function zr(e,t,n){return T(typeof t==`number`),e.typeName==`google.protobuf.NullValue`?null:n?t:e.findNumber(t)?.name??t}function Br(e,t){switch(e){case D.INT32:case D.SFIXED32:case D.SINT32:case D.FIXED32:case D.UINT32:return T(typeof t==`number`),t;case D.FLOAT:case D.DOUBLE:return T(typeof t==`number`),Number.isNaN(t)?`NaN`:t===1/0?`Infinity`:t===-1/0?`-Infinity`:t;case D.STRING:return T(typeof t==`string`),t;case D.BOOL:return T(typeof t==`boolean`),t;case D.UINT64:case D.FIXED64:case D.INT64:case D.SFIXED64:case D.SINT64:return T(typeof t==`bigint`||typeof t==`string`||typeof t==`number`),t.toString();case D.BYTES:return T(t instanceof Uint8Array),gr.enc(t)}}var Vr=Symbol(`@bufbuild/protobuf/unknown-fields`),Hr={readUnknownFields:!0,readerFactory:e=>new lr(e)},Ur={writeUnknownFields:!0,writerFactory:()=>new cr};function Wr(e){return e?Object.assign(Object.assign({},Hr),e):Hr}function Gr(e){return e?Object.assign(Object.assign({},Ur),e):Ur}function Kr(){return{makeReadOptions:Wr,makeWriteOptions:Gr,listUnknownFields(e){return e[Vr]??[]},discardUnknownFields(e){delete e[Vr]},writeUnknownFields(e,t){let n=e[Vr];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[Vr])||(i[Vr]=[]),i[Vr].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==O.EndGroup));){let n=a.fields.find(s);if(!n){let n=t.skip(c,s);r.readUnknownFields&&this.onUnknownField(e,s,c,n);continue}qr(e,t,n,c,r)}if(i&&(c!=O.EndGroup||s!==n))throw Error(`invalid end group tag`)},readField:qr,writeMessage(e,t,n){let r=e.getType();for(let i of r.fields.byNumber()){if(!xr(i,e)){if(i.req)throw Error(`cannot encode field ${r.typeName}.${i.name} to binary: required field not set`);continue}Qr(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&&Qr(e,t,n,r)}}}function qr(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`?D.INT32:n.T,c=Zr;if(n.kind==`scalar`&&n.L>0&&(c=Xr),a){let n=e[o];if(r==O.LengthDelimited&&s!=D.STRING&&s!=D.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(Jr(t,new l,i,n)):Cr(e[o])?Jr(t,e[o],i,n):(e[o]=Jr(t,new l,i,n),l.fieldWrapper&&!n.oneof&&!n.repeated&&(e[o]=l.fieldWrapper.unwrapField(e[o])));break;case`map`:let[u,d]=Yr(n,t,i);e[o][u]=d;break}}function Jr(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 Yr(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=Zr(t,e.K);break;case 2:switch(e.V.kind){case`scalar`:o=Zr(t,e.V.T);break;case`enum`:o=t.int32();break;case`message`:o=Jr(t,new e.V.T,n,void 0);break}break}}if(a===void 0&&(a=or(e.K,ir.BIGINT)),typeof a!=`string`&&typeof a!=`number`&&(a=a.toString()),o===void 0)switch(e.V.kind){case`scalar`:o=or(e.V.T,ir.BIGINT);break;case`enum`:o=e.V.T.values[0].no;break;case`message`:o=new e.V.T;break}return[a,o]}function Xr(e,t){let n=Zr(e,t);return typeof n==`bigint`?n.toString():n}function Zr(e,t){switch(t){case D.STRING:return e.string();case D.BOOL:return e.bool();case D.DOUBLE:return e.double();case D.FLOAT:return e.float();case D.INT32:return e.int32();case D.INT64:return e.int64();case D.UINT64:return e.uint64();case D.FIXED64:return e.fixed64();case D.BYTES:return e.bytes();case D.FIXED32:return e.fixed32();case D.SFIXED32:return e.sfixed32();case D.SFIXED64:return e.sfixed64();case D.SINT64:return e.sint64();case D.UINT32:return e.uint32();case D.SINT32:return e.sint32()}}function Qr(e,t,n,r){T(t!==void 0);let i=e.repeated;switch(e.kind){case`scalar`:case`enum`:let a=e.kind==`enum`?D.INT32:e.T;if(i)if(T(Array.isArray(t)),e.packed)ni(n,a,e.no,t);else for(let r of t)ti(n,a,e.no,r);else ti(n,a,e.no,t);break;case`message`:if(i){T(Array.isArray(t));for(let i of t)ei(n,r,e,i)}else ei(n,r,e,t);break;case`map`:T(typeof t==`object`&&!!t);for(let[i,a]of Object.entries(t))$r(n,r,e,i,a);break}}function $r(e,t,n,r,i){e.tag(n.no,O.LengthDelimited),e.fork();let a=r;switch(n.K){case D.INT32:case D.FIXED32:case D.UINT32:case D.SFIXED32:case D.SINT32:a=Number.parseInt(r);break;case D.BOOL:T(r==`true`||r==`false`),a=r==`true`;break}switch(ti(e,n.K,1,a),n.V.kind){case`scalar`:ti(e,n.V.T,2,i);break;case`enum`:ti(e,D.INT32,2,i);break;case`message`:T(i!==void 0),e.tag(2,O.LengthDelimited).bytes(i.toBinary(t));break}e.join()}function ei(e,t,n,r){let i=wr(n.T,r);n.delimited?e.tag(n.no,O.StartGroup).raw(i.toBinary(t)).tag(n.no,O.EndGroup):e.tag(n.no,O.LengthDelimited).bytes(i.toBinary(t))}function ti(e,t,n,r){T(r!==void 0);let[i,a]=ri(t);e.tag(n,i)[a](r)}function ni(e,t,n,r){if(!r.length)return;e.tag(n,O.LengthDelimited).fork();let[,i]=ri(t);for(let t=0;t<r.length;t++)e[i](r[t]);e.join()}function ri(e){let t=O.Varint;switch(e){case D.BYTES:case D.STRING:t=O.LengthDelimited;break;case D.DOUBLE:case D.FIXED64:case D.SFIXED64:t=O.Bit64;break;case D.FIXED32:case D.SFIXED32:case D.FLOAT:t=O.Bit32;break}let n=D[e].toLowerCase();return[t,n]}function ii(){return{setEnumType:zn,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`&&!Cr(o,t.T)?o=new t.T(o):t&&t.kind===`scalar`&&t.T===D.BYTES&&(o=oi(o)),i[n]={case:e,value:o};break;case`scalar`:case`enum`:let s=a[n];r.T===D.BYTES&&(s=r.repeated?s.map(oi):oi(s)),i[n]=s;break;case`map`:switch(r.V.kind){case`scalar`:case`enum`:if(r.V.T===D.BYTES)for(let[e,t]of Object.entries(a[n]))i[n][e]=oi(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=>Cr(e,c)?e:new c(e));else{let e=a[n];c.fieldWrapper?c.typeName===`google.protobuf.BytesValue`?i[n]=oi(e):i[n]=e:i[n]=Cr(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)=>ar(e.T,t,i[n]));case`enum`:return r.every((e,t)=>ar(D.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&&!Cr(t)&&(t=e.T.fieldWrapper.wrapField(t)),n!==void 0&&!Cr(n)&&(n=e.T.fieldWrapper.wrapField(n))),e.T.equals(t,n);case`enum`:return ar(D.INT32,r,i);case`scalar`:return ar(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 ar(D.INT32,r.value,i.value);case`scalar`:return ar(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=>ar(D.INT32,r[e],i[e]));case`scalar`:let n=e.V.T;return o.every(e=>ar(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(ai);else if(n.kind==`map`){i=r[n.localName];for(let[e,n]of Object.entries(t))i[e]=ai(n)}else i=n.kind==`oneof`?n.findField(t.case)?{case:t.case,value:ai(t.value)}:{case:void 0}:ai(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 ai(e){if(e===void 0)return e;if(Cr(e))return e.clone();if(e instanceof Uint8Array){let t=new Uint8Array(e.byteLength);return t.set(e),t}return e}function oi(e){return e instanceof Uint8Array?e:new Uint8Array(e)}function si(e,t,n){return{syntax:e,json:jr(),bin:Kr(),util:Object.assign(Object.assign({},ii()),{newFieldList:t,initFields:n}),makeMessageType(e,t,n){return Wn(this,e,t,n)},makeEnum:Vn,makeEnumType:Bn,getEnumType:Rn,makeExtension(e,t,n){return ur(this,e,t,n)}}}var ci=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 li(e,t){let n=fi(e);return t?n:_i(gi(n))}function ui(e){return li(e,!1)}var di=fi;function fi(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 pi=new Set([`constructor`,`toString`,`toJSON`,`valueOf`]),mi=new Set([`getType`,`clone`,`equals`,`fromBinary`,`fromJson`,`fromJsonString`,`toBinary`,`toJson`,`toJsonString`,`toObject`]),hi=e=>`${e}\$`,gi=e=>mi.has(e)?hi(e):e,_i=e=>pi.has(e)?hi(e):e,vi=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=ui(e)}addField(e){T(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 yi(e,t){let n=[],r;for(let t of typeof e==`function`?e():e){let e=t;if(e.localName=li(t.name,t.oneof!==void 0),e.jsonName=t.jsonName??di(t.name),e.repeated=t.repeated??!1,t.kind==`scalar`&&(e.L=t.L??ir.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!=D.BYTES&&t.T!=D.STRING),t.oneof!==void 0){let n=typeof t.oneof==`string`?t.oneof:t.oneof.name;(!r||r.name!=n)&&(r=new vi(n)),e.oneof=r,r.addField(e)}n.push(e)}return n}var k=si(`proto3`,e=>new ci(e,e=>yi(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]=or(t.T,t.L);break}}}),bi=class e extends Un{constructor(e){super(),this.seconds=E.zero,this.nanos=0,k.util.initPartial(e,this)}fromJson(e,t){if(typeof e!=`string`)throw Error(`cannot decode google.protobuf.Timestamp from JSON: ${k.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=E.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:E.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 k.util.equals(e,t,n)}};bi.runtime=k,bi.typeName=`google.protobuf.Timestamp`,bi.fields=k.util.newFieldList(()=>[{no:1,name:`seconds`,kind:`scalar`,T:3},{no:2,name:`nanos`,kind:`scalar`,T:5}]);var xi=k.makeMessageType(`livekit.MetricsBatch`,()=>[{no:1,name:`timestamp_ms`,kind:`scalar`,T:3},{no:2,name:`normalized_timestamp`,kind:`message`,T:bi},{no:3,name:`str_data`,kind:`scalar`,T:9,repeated:!0},{no:4,name:`time_series`,kind:`message`,T:Si,repeated:!0},{no:5,name:`events`,kind:`message`,T:wi,repeated:!0}]),Si=k.makeMessageType(`livekit.TimeSeriesMetric`,()=>[{no:1,name:`label`,kind:`scalar`,T:13},{no:2,name:`participant_identity`,kind:`scalar`,T:13},{no:3,name:`track_sid`,kind:`scalar`,T:13},{no:4,name:`samples`,kind:`message`,T:Ci,repeated:!0},{no:5,name:`rid`,kind:`scalar`,T:13}]),Ci=k.makeMessageType(`livekit.MetricSample`,()=>[{no:1,name:`timestamp_ms`,kind:`scalar`,T:3},{no:2,name:`normalized_timestamp`,kind:`message`,T:bi},{no:3,name:`value`,kind:`scalar`,T:2}]),wi=k.makeMessageType(`livekit.EventMetric`,()=>[{no:1,name:`label`,kind:`scalar`,T:13},{no:2,name:`participant_identity`,kind:`scalar`,T:13},{no:3,name:`track_sid`,kind:`scalar`,T:13},{no:4,name:`start_timestamp_ms`,kind:`scalar`,T:3},{no:5,name:`end_timestamp_ms`,kind:`scalar`,T:3,opt:!0},{no:6,name:`normalized_start_timestamp`,kind:`message`,T:bi},{no:7,name:`normalized_end_timestamp`,kind:`message`,T:bi,opt:!0},{no:8,name:`metadata`,kind:`scalar`,T:9},{no:9,name:`rid`,kind:`scalar`,T:13}]),Ti=k.makeEnum(`livekit.BackupCodecPolicy`,[{no:0,name:`PREFER_REGRESSION`},{no:1,name:`SIMULCAST`},{no:2,name:`REGRESSION`}]),Ei=k.makeEnum(`livekit.TrackType`,[{no:0,name:`AUDIO`},{no:1,name:`VIDEO`},{no:2,name:`DATA`}]),A=k.makeEnum(`livekit.TrackSource`,[{no:0,name:`UNKNOWN`},{no:1,name:`CAMERA`},{no:2,name:`MICROPHONE`},{no:3,name:`SCREEN_SHARE`},{no:4,name:`SCREEN_SHARE_AUDIO`}]),Di=k.makeEnum(`livekit.VideoQuality`,[{no:0,name:`LOW`},{no:1,name:`MEDIUM`},{no:2,name:`HIGH`},{no:3,name:`OFF`}]),Oi=k.makeEnum(`livekit.ConnectionQuality`,[{no:0,name:`POOR`},{no:1,name:`GOOD`},{no:2,name:`EXCELLENT`},{no:3,name:`LOST`}]),ki=k.makeEnum(`livekit.ClientConfigSetting`,[{no:0,name:`UNSET`},{no:1,name:`DISABLED`},{no:2,name:`ENABLED`}]),Ai=k.makeEnum(`livekit.DisconnectReason`,[{no:0,name:`UNKNOWN_REASON`},{no:1,name:`CLIENT_INITIATED`},{no:2,name:`DUPLICATE_IDENTITY`},{no:3,name:`SERVER_SHUTDOWN`},{no:4,name:`PARTICIPANT_REMOVED`},{no:5,name:`ROOM_DELETED`},{no:6,name:`STATE_MISMATCH`},{no:7,name:`JOIN_FAILURE`},{no:8,name:`MIGRATION`},{no:9,name:`SIGNAL_CLOSE`},{no:10,name:`ROOM_CLOSED`},{no:11,name:`USER_UNAVAILABLE`},{no:12,name:`USER_REJECTED`},{no:13,name:`SIP_TRUNK_FAILURE`},{no:14,name:`CONNECTION_TIMEOUT`},{no:15,name:`MEDIA_FAILURE`}]),ji=k.makeEnum(`livekit.ReconnectReason`,[{no:0,name:`RR_UNKNOWN`},{no:1,name:`RR_SIGNAL_DISCONNECTED`},{no:2,name:`RR_PUBLISHER_FAILED`},{no:3,name:`RR_SUBSCRIBER_FAILED`},{no:4,name:`RR_SWITCH_CANDIDATE`}]),Mi=k.makeEnum(`livekit.SubscriptionError`,[{no:0,name:`SE_UNKNOWN`},{no:1,name:`SE_CODEC_UNSUPPORTED`},{no:2,name:`SE_TRACK_NOTFOUND`}]),j=k.makeEnum(`livekit.AudioTrackFeature`,[{no:0,name:`TF_STEREO`},{no:1,name:`TF_NO_DTX`},{no:2,name:`TF_AUTO_GAIN_CONTROL`},{no:3,name:`TF_ECHO_CANCELLATION`},{no:4,name:`TF_NOISE_SUPPRESSION`},{no:5,name:`TF_ENHANCED_NOISE_CANCELLATION`},{no:6,name:`TF_PRECONNECT_BUFFER`}]),Ni=k.makeMessageType(`livekit.Room`,()=>[{no:1,name:`sid`,kind:`scalar`,T:9},{no:2,name:`name`,kind:`scalar`,T:9},{no:3,name:`empty_timeout`,kind:`scalar`,T:13},{no:14,name:`departure_timeout`,kind:`scalar`,T:13},{no:4,name:`max_participants`,kind:`scalar`,T:13},{no:5,name:`creation_time`,kind:`scalar`,T:3},{no:15,name:`creation_time_ms`,kind:`scalar`,T:3},{no:6,name:`turn_password`,kind:`scalar`,T:9},{no:7,name:`enabled_codecs`,kind:`message`,T:Pi,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:ha}]),Pi=k.makeMessageType(`livekit.Codec`,()=>[{no:1,name:`mime`,kind:`scalar`,T:9},{no:2,name:`fmtp_line`,kind:`scalar`,T:9}]),Fi=k.makeMessageType(`livekit.ParticipantPermission`,()=>[{no:1,name:`can_subscribe`,kind:`scalar`,T:8},{no:2,name:`can_publish`,kind:`scalar`,T:8},{no:3,name:`can_publish_data`,kind:`scalar`,T:8},{no:9,name:`can_publish_sources`,kind:`enum`,T:k.getEnumType(A),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}]),Ii=k.makeMessageType(`livekit.ParticipantInfo`,()=>[{no:1,name:`sid`,kind:`scalar`,T:9},{no:2,name:`identity`,kind:`scalar`,T:9},{no:3,name:`state`,kind:`enum`,T:k.getEnumType(Li)},{no:4,name:`tracks`,kind:`message`,T:Vi,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:Fi},{no:12,name:`region`,kind:`scalar`,T:9},{no:13,name:`is_publisher`,kind:`scalar`,T:8},{no:14,name:`kind`,kind:`enum`,T:k.getEnumType(Ri)},{no:15,name:`attributes`,kind:`map`,K:9,V:{kind:`scalar`,T:9}},{no:16,name:`disconnect_reason`,kind:`enum`,T:k.getEnumType(Ai)},{no:18,name:`kind_details`,kind:`enum`,T:k.getEnumType(zi),repeated:!0},{no:19,name:`data_tracks`,kind:`message`,T:Hi,repeated:!0}]),Li=k.makeEnum(`livekit.ParticipantInfo.State`,[{no:0,name:`JOINING`},{no:1,name:`JOINED`},{no:2,name:`ACTIVE`},{no:3,name:`DISCONNECTED`}]),Ri=k.makeEnum(`livekit.ParticipantInfo.Kind`,[{no:0,name:`STANDARD`},{no:1,name:`INGRESS`},{no:2,name:`EGRESS`},{no:3,name:`SIP`},{no:4,name:`AGENT`},{no:7,name:`CONNECTOR`},{no:8,name:`BRIDGE`}]),zi=k.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`}]),M=k.makeEnum(`livekit.Encryption.Type`,[{no:0,name:`NONE`},{no:1,name:`GCM`},{no:2,name:`CUSTOM`}]),Bi=k.makeMessageType(`livekit.SimulcastCodecInfo`,()=>[{no:1,name:`mime_type`,kind:`scalar`,T:9},{no:2,name:`mid`,kind:`scalar`,T:9},{no:3,name:`cid`,kind:`scalar`,T:9},{no:4,name:`layers`,kind:`message`,T:Wi,repeated:!0},{no:5,name:`video_layer_mode`,kind:`enum`,T:k.getEnumType(Gi)},{no:6,name:`sdp_cid`,kind:`scalar`,T:9}]),Vi=k.makeMessageType(`livekit.TrackInfo`,()=>[{no:1,name:`sid`,kind:`scalar`,T:9},{no:2,name:`type`,kind:`enum`,T:k.getEnumType(Ei)},{no:3,name:`name`,kind:`scalar`,T:9},{no:4,name:`muted`,kind:`scalar`,T:8},{no:5,name:`width`,kind:`scalar`,T:13},{no:6,name:`height`,kind:`scalar`,T:13},{no:7,name:`simulcast`,kind:`scalar`,T:8},{no:8,name:`disable_dtx`,kind:`scalar`,T:8},{no:9,name:`source`,kind:`enum`,T:k.getEnumType(A)},{no:10,name:`layers`,kind:`message`,T:Wi,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:Bi,repeated:!0},{no:14,name:`stereo`,kind:`scalar`,T:8},{no:15,name:`disable_red`,kind:`scalar`,T:8},{no:16,name:`encryption`,kind:`enum`,T:k.getEnumType(M)},{no:17,name:`stream`,kind:`scalar`,T:9},{no:18,name:`version`,kind:`message`,T:ha},{no:19,name:`audio_features`,kind:`enum`,T:k.getEnumType(j),repeated:!0},{no:20,name:`backup_codec_policy`,kind:`enum`,T:k.getEnumType(Ti)}]),Hi=k.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:k.getEnumType(M)}]),Ui=k.makeMessageType(`livekit.DataTrackSubscriptionOptions`,()=>[{no:1,name:`target_fps`,kind:`scalar`,T:13,opt:!0}]),Wi=k.makeMessageType(`livekit.VideoLayer`,()=>[{no:1,name:`quality`,kind:`enum`,T:k.getEnumType(Di)},{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}]),Gi=k.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`}]),Ki=k.makeMessageType(`livekit.DataPacket`,()=>[{no:1,name:`kind`,kind:`enum`,T:k.getEnumType(qi)},{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:Qi,oneof:`value`},{no:3,name:`speaker`,kind:`message`,T:Xi,oneof:`value`},{no:6,name:`sip_dtmf`,kind:`message`,T:$i,oneof:`value`},{no:7,name:`transcription`,kind:`message`,T:ea,oneof:`value`},{no:8,name:`metrics`,kind:`message`,T:xi,oneof:`value`},{no:9,name:`chat_message`,kind:`message`,T:na,oneof:`value`},{no:10,name:`rpc_request`,kind:`message`,T:ra,oneof:`value`},{no:11,name:`rpc_ack`,kind:`message`,T:ia,oneof:`value`},{no:12,name:`rpc_response`,kind:`message`,T:aa,oneof:`value`},{no:13,name:`stream_header`,kind:`message`,T:ya,oneof:`value`},{no:14,name:`stream_chunk`,kind:`message`,T:ba,oneof:`value`},{no:15,name:`stream_trailer`,kind:`message`,T:xa,oneof:`value`},{no:18,name:`encrypted_packet`,kind:`message`,T:Ji,oneof:`value`},{no:16,name:`sequence`,kind:`scalar`,T:13},{no:17,name:`participant_sid`,kind:`scalar`,T:9}]),qi=k.makeEnum(`livekit.DataPacket.Kind`,[{no:0,name:`RELIABLE`},{no:1,name:`LOSSY`}]),Ji=k.makeMessageType(`livekit.EncryptedPacket`,()=>[{no:1,name:`encryption_type`,kind:`enum`,T:k.getEnumType(M)},{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}]),Yi=k.makeMessageType(`livekit.EncryptedPacketPayload`,()=>[{no:1,name:`user`,kind:`message`,T:Qi,oneof:`value`},{no:3,name:`chat_message`,kind:`message`,T:na,oneof:`value`},{no:4,name:`rpc_request`,kind:`message`,T:ra,oneof:`value`},{no:5,name:`rpc_ack`,kind:`message`,T:ia,oneof:`value`},{no:6,name:`rpc_response`,kind:`message`,T:aa,oneof:`value`},{no:7,name:`stream_header`,kind:`message`,T:ya,oneof:`value`},{no:8,name:`stream_chunk`,kind:`message`,T:ba,oneof:`value`},{no:9,name:`stream_trailer`,kind:`message`,T:xa,oneof:`value`}]),Xi=k.makeMessageType(`livekit.ActiveSpeakerUpdate`,()=>[{no:1,name:`speakers`,kind:`message`,T:Zi,repeated:!0}]),Zi=k.makeMessageType(`livekit.SpeakerInfo`,()=>[{no:1,name:`sid`,kind:`scalar`,T:9},{no:2,name:`level`,kind:`scalar`,T:2},{no:3,name:`active`,kind:`scalar`,T:8}]),Qi=k.makeMessageType(`livekit.UserPacket`,()=>[{no:1,name:`participant_sid`,kind:`scalar`,T:9},{no:5,name:`participant_identity`,kind:`scalar`,T:9},{no:2,name:`payload`,kind:`scalar`,T:12},{no:3,name:`destination_sids`,kind:`scalar`,T:9,repeated:!0},{no:6,name:`destination_identities`,kind:`scalar`,T:9,repeated:!0},{no:4,name:`topic`,kind:`scalar`,T:9,opt:!0},{no:8,name:`id`,kind:`scalar`,T:9,opt:!0},{no:9,name:`start_time`,kind:`scalar`,T:4,opt:!0},{no:10,name:`end_time`,kind:`scalar`,T:4,opt:!0},{no:11,name:`nonce`,kind:`scalar`,T:12}]),$i=k.makeMessageType(`livekit.SipDTMF`,()=>[{no:3,name:`code`,kind:`scalar`,T:13},{no:4,name:`digit`,kind:`scalar`,T:9}]),ea=k.makeMessageType(`livekit.Transcription`,()=>[{no:2,name:`transcribed_participant_identity`,kind:`scalar`,T:9},{no:3,name:`track_id`,kind:`scalar`,T:9},{no:4,name:`segments`,kind:`message`,T:ta,repeated:!0}]),ta=k.makeMessageType(`livekit.TranscriptionSegment`,()=>[{no:1,name:`id`,kind:`scalar`,T:9},{no:2,name:`text`,kind:`scalar`,T:9},{no:3,name:`start_time`,kind:`scalar`,T:4},{no:4,name:`end_time`,kind:`scalar`,T:4},{no:5,name:`final`,kind:`scalar`,T:8},{no:6,name:`language`,kind:`scalar`,T:9}]),na=k.makeMessageType(`livekit.ChatMessage`,()=>[{no:1,name:`id`,kind:`scalar`,T:9},{no:2,name:`timestamp`,kind:`scalar`,T:3},{no:3,name:`edit_timestamp`,kind:`scalar`,T:3,opt:!0},{no:4,name:`message`,kind:`scalar`,T:9},{no:5,name:`deleted`,kind:`scalar`,T:8},{no:6,name:`generated`,kind:`scalar`,T:8}]),ra=k.makeMessageType(`livekit.RpcRequest`,()=>[{no:1,name:`id`,kind:`scalar`,T:9},{no:2,name:`method`,kind:`scalar`,T:9},{no:3,name:`payload`,kind:`scalar`,T:9},{no:4,name:`response_timeout_ms`,kind:`scalar`,T:13},{no:5,name:`version`,kind:`scalar`,T:13}]),ia=k.makeMessageType(`livekit.RpcAck`,()=>[{no:1,name:`request_id`,kind:`scalar`,T:9}]),aa=k.makeMessageType(`livekit.RpcResponse`,()=>[{no:1,name:`request_id`,kind:`scalar`,T:9},{no:2,name:`payload`,kind:`scalar`,T:9,oneof:`value`},{no:3,name:`error`,kind:`message`,T:oa,oneof:`value`}]),oa=k.makeMessageType(`livekit.RpcError`,()=>[{no:1,name:`code`,kind:`scalar`,T:13},{no:2,name:`message`,kind:`scalar`,T:9},{no:3,name:`data`,kind:`scalar`,T:9}]),sa=k.makeMessageType(`livekit.ParticipantTracks`,()=>[{no:1,name:`participant_sid`,kind:`scalar`,T:9},{no:2,name:`track_sids`,kind:`scalar`,T:9,repeated:!0}]),ca=k.makeMessageType(`livekit.ServerInfo`,()=>[{no:1,name:`edition`,kind:`enum`,T:k.getEnumType(la)},{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}]),la=k.makeEnum(`livekit.ServerInfo.Edition`,[{no:0,name:`Standard`},{no:1,name:`Cloud`}]),ua=k.makeMessageType(`livekit.ClientInfo`,()=>[{no:1,name:`sdk`,kind:`enum`,T:k.getEnumType(da)},{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}]),da=k.makeEnum(`livekit.ClientInfo.SDK`,[{no:0,name:`UNKNOWN`},{no:1,name:`JS`},{no:2,name:`SWIFT`},{no:3,name:`ANDROID`},{no:4,name:`FLUTTER`},{no:5,name:`GO`},{no:6,name:`UNITY`},{no:7,name:`REACT_NATIVE`},{no:8,name:`RUST`},{no:9,name:`PYTHON`},{no:10,name:`CPP`},{no:11,name:`UNITY_WEB`},{no:12,name:`NODE`},{no:13,name:`UNREAL`},{no:14,name:`ESP32`}]),fa=k.makeMessageType(`livekit.ClientConfiguration`,()=>[{no:1,name:`video`,kind:`message`,T:pa},{no:2,name:`screen`,kind:`message`,T:pa},{no:3,name:`resume_connection`,kind:`enum`,T:k.getEnumType(ki)},{no:4,name:`disabled_codecs`,kind:`message`,T:ma},{no:5,name:`force_relay`,kind:`enum`,T:k.getEnumType(ki)}]),pa=k.makeMessageType(`livekit.VideoConfiguration`,()=>[{no:1,name:`hardware_encoder`,kind:`enum`,T:k.getEnumType(ki)}]),ma=k.makeMessageType(`livekit.DisabledCodecs`,()=>[{no:1,name:`codecs`,kind:`message`,T:Pi,repeated:!0},{no:2,name:`publish`,kind:`message`,T:Pi,repeated:!0}]),ha=k.makeMessageType(`livekit.TimedVersion`,()=>[{no:1,name:`unix_micro`,kind:`scalar`,T:3},{no:2,name:`ticks`,kind:`scalar`,T:5}]),ga=k.makeEnum(`livekit.DataStream.OperationType`,[{no:0,name:`CREATE`},{no:1,name:`UPDATE`},{no:2,name:`DELETE`},{no:3,name:`REACTION`}]),_a=k.makeMessageType(`livekit.DataStream.TextHeader`,()=>[{no:1,name:`operation_type`,kind:`enum`,T:k.getEnumType(ga)},{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`}),va=k.makeMessageType(`livekit.DataStream.ByteHeader`,()=>[{no:1,name:`name`,kind:`scalar`,T:9}],{localName:`DataStream_ByteHeader`}),ya=k.makeMessageType(`livekit.DataStream.Header`,()=>[{no:1,name:`stream_id`,kind:`scalar`,T:9},{no:2,name:`timestamp`,kind:`scalar`,T:3},{no:3,name:`topic`,kind:`scalar`,T:9},{no:4,name:`mime_type`,kind:`scalar`,T:9},{no:5,name:`total_length`,kind:`scalar`,T:4,opt:!0},{no:7,name:`encryption_type`,kind:`enum`,T:k.getEnumType(M)},{no:8,name:`attributes`,kind:`map`,K:9,V:{kind:`scalar`,T:9}},{no:9,name:`text_header`,kind:`message`,T:_a,oneof:`content_header`},{no:10,name:`byte_header`,kind:`message`,T:va,oneof:`content_header`}],{localName:`DataStream_Header`}),ba=k.makeMessageType(`livekit.DataStream.Chunk`,()=>[{no:1,name:`stream_id`,kind:`scalar`,T:9},{no:2,name:`chunk_index`,kind:`scalar`,T:4},{no:3,name:`content`,kind:`scalar`,T:12},{no:4,name:`version`,kind:`scalar`,T:5},{no:5,name:`iv`,kind:`scalar`,T:12,opt:!0}],{localName:`DataStream_Chunk`}),xa=k.makeMessageType(`livekit.DataStream.Trailer`,()=>[{no:1,name:`stream_id`,kind:`scalar`,T:9},{no:2,name:`reason`,kind:`scalar`,T:9},{no:3,name:`attributes`,kind:`map`,K:9,V:{kind:`scalar`,T:9}}],{localName:`DataStream_Trailer`}),Sa=k.makeMessageType(`livekit.SubscribedAudioCodec`,()=>[{no:1,name:`codec`,kind:`scalar`,T:9},{no:2,name:`enabled`,kind:`scalar`,T:8}]),Ca=k.makeEnum(`livekit.SignalTarget`,[{no:0,name:`PUBLISHER`},{no:1,name:`SUBSCRIBER`}]),wa=k.makeEnum(`livekit.StreamState`,[{no:0,name:`ACTIVE`},{no:1,name:`PAUSED`}]),Ta=k.makeEnum(`livekit.CandidateProtocol`,[{no:0,name:`UDP`},{no:1,name:`TCP`},{no:2,name:`TLS`}]),Ea=k.makeMessageType(`livekit.SignalRequest`,()=>[{no:1,name:`offer`,kind:`message`,T:Ha,oneof:`message`},{no:2,name:`answer`,kind:`message`,T:Ha,oneof:`message`},{no:3,name:`trickle`,kind:`message`,T:Ia,oneof:`message`},{no:4,name:`add_track`,kind:`message`,T:ka,oneof:`message`},{no:5,name:`mute`,kind:`message`,T:La,oneof:`message`},{no:6,name:`subscription`,kind:`message`,T:Wa,oneof:`message`},{no:7,name:`track_setting`,kind:`message`,T:qa,oneof:`message`},{no:8,name:`leave`,kind:`message`,T:Xa,oneof:`message`},{no:10,name:`update_layers`,kind:`message`,T:Qa,oneof:`message`},{no:11,name:`subscription_permission`,kind:`message`,T:po,oneof:`message`},{no:12,name:`sync_state`,kind:`message`,T:go,oneof:`message`},{no:13,name:`simulate`,kind:`message`,T:yo,oneof:`message`},{no:14,name:`ping`,kind:`scalar`,T:3,oneof:`message`},{no:15,name:`update_metadata`,kind:`message`,T:$a,oneof:`message`},{no:16,name:`ping_req`,kind:`message`,T:bo,oneof:`message`},{no:17,name:`update_audio_track`,kind:`message`,T:Ja,oneof:`message`},{no:18,name:`update_video_track`,kind:`message`,T:Ya,oneof:`message`},{no:19,name:`publish_data_track_request`,kind:`message`,T:Aa,oneof:`message`},{no:20,name:`unpublish_data_track_request`,kind:`message`,T:Ma,oneof:`message`},{no:21,name:`update_data_subscription`,kind:`message`,T:Ga,oneof:`message`}]),Da=k.makeMessageType(`livekit.SignalResponse`,()=>[{no:1,name:`join`,kind:`message`,T:Ra,oneof:`message`},{no:2,name:`answer`,kind:`message`,T:Ha,oneof:`message`},{no:3,name:`offer`,kind:`message`,T:Ha,oneof:`message`},{no:4,name:`trickle`,kind:`message`,T:Ia,oneof:`message`},{no:5,name:`update`,kind:`message`,T:Ua,oneof:`message`},{no:6,name:`track_published`,kind:`message`,T:Ba,oneof:`message`},{no:8,name:`leave`,kind:`message`,T:Xa,oneof:`message`},{no:9,name:`mute`,kind:`message`,T:La,oneof:`message`},{no:10,name:`speakers_changed`,kind:`message`,T:to,oneof:`message`},{no:11,name:`room_update`,kind:`message`,T:no,oneof:`message`},{no:12,name:`connection_quality`,kind:`message`,T:io,oneof:`message`},{no:13,name:`stream_state_update`,kind:`message`,T:oo,oneof:`message`},{no:14,name:`subscribed_quality_update`,kind:`message`,T:lo,oneof:`message`},{no:15,name:`subscription_permission_update`,kind:`message`,T:mo,oneof:`message`},{no:16,name:`refresh_token`,kind:`scalar`,T:9,oneof:`message`},{no:17,name:`track_unpublished`,kind:`message`,T:Va,oneof:`message`},{no:18,name:`pong`,kind:`scalar`,T:3,oneof:`message`},{no:19,name:`reconnect`,kind:`message`,T:za,oneof:`message`},{no:20,name:`pong_resp`,kind:`message`,T:xo,oneof:`message`},{no:21,name:`subscription_response`,kind:`message`,T:wo,oneof:`message`},{no:22,name:`request_response`,kind:`message`,T:To,oneof:`message`},{no:23,name:`track_subscribed`,kind:`message`,T:Do,oneof:`message`},{no:24,name:`room_moved`,kind:`message`,T:ho,oneof:`message`},{no:25,name:`media_sections_requirement`,kind:`message`,T:Mo,oneof:`message`},{no:26,name:`subscribed_audio_codec_update`,kind:`message`,T:uo,oneof:`message`},{no:27,name:`publish_data_track_response`,kind:`message`,T:ja,oneof:`message`},{no:28,name:`unpublish_data_track_response`,kind:`message`,T:Na,oneof:`message`},{no:29,name:`data_track_subscriber_handles`,kind:`message`,T:Pa,oneof:`message`}]),Oa=k.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:Wi,repeated:!0},{no:5,name:`video_layer_mode`,kind:`enum`,T:k.getEnumType(Gi)}]),ka=k.makeMessageType(`livekit.AddTrackRequest`,()=>[{no:1,name:`cid`,kind:`scalar`,T:9},{no:2,name:`name`,kind:`scalar`,T:9},{no:3,name:`type`,kind:`enum`,T:k.getEnumType(Ei)},{no:4,name:`width`,kind:`scalar`,T:13},{no:5,name:`height`,kind:`scalar`,T:13},{no:6,name:`muted`,kind:`scalar`,T:8},{no:7,name:`disable_dtx`,kind:`scalar`,T:8},{no:8,name:`source`,kind:`enum`,T:k.getEnumType(A)},{no:9,name:`layers`,kind:`message`,T:Wi,repeated:!0},{no:10,name:`simulcast_codecs`,kind:`message`,T:Oa,repeated:!0},{no:11,name:`sid`,kind:`scalar`,T:9},{no:12,name:`stereo`,kind:`scalar`,T:8},{no:13,name:`disable_red`,kind:`scalar`,T:8},{no:14,name:`encryption`,kind:`enum`,T:k.getEnumType(M)},{no:15,name:`stream`,kind:`scalar`,T:9},{no:16,name:`backup_codec_policy`,kind:`enum`,T:k.getEnumType(Ti)},{no:17,name:`audio_features`,kind:`enum`,T:k.getEnumType(j),repeated:!0}]),Aa=k.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:k.getEnumType(M)}]),ja=k.makeMessageType(`livekit.PublishDataTrackResponse`,()=>[{no:1,name:`info`,kind:`message`,T:Hi}]),Ma=k.makeMessageType(`livekit.UnpublishDataTrackRequest`,()=>[{no:1,name:`pub_handle`,kind:`scalar`,T:13}]),Na=k.makeMessageType(`livekit.UnpublishDataTrackResponse`,()=>[{no:1,name:`info`,kind:`message`,T:Hi}]),Pa=k.makeMessageType(`livekit.DataTrackSubscriberHandles`,()=>[{no:1,name:`sub_handles`,kind:`map`,K:13,V:{kind:`message`,T:Fa}}]),Fa=k.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`}),Ia=k.makeMessageType(`livekit.TrickleRequest`,()=>[{no:1,name:`candidateInit`,kind:`scalar`,T:9},{no:2,name:`target`,kind:`enum`,T:k.getEnumType(Ca)},{no:3,name:`final`,kind:`scalar`,T:8}]),La=k.makeMessageType(`livekit.MuteTrackRequest`,()=>[{no:1,name:`sid`,kind:`scalar`,T:9},{no:2,name:`muted`,kind:`scalar`,T:8}]),Ra=k.makeMessageType(`livekit.JoinResponse`,()=>[{no:1,name:`room`,kind:`message`,T:Ni},{no:2,name:`participant`,kind:`message`,T:Ii},{no:3,name:`other_participants`,kind:`message`,T:Ii,repeated:!0},{no:4,name:`server_version`,kind:`scalar`,T:9},{no:5,name:`ice_servers`,kind:`message`,T:eo,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:fa},{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:ca},{no:13,name:`sif_trailer`,kind:`scalar`,T:12},{no:14,name:`enabled_publish_codecs`,kind:`message`,T:Pi,repeated:!0},{no:15,name:`fast_publish`,kind:`scalar`,T:8}]),za=k.makeMessageType(`livekit.ReconnectResponse`,()=>[{no:1,name:`ice_servers`,kind:`message`,T:eo,repeated:!0},{no:2,name:`client_configuration`,kind:`message`,T:fa},{no:3,name:`server_info`,kind:`message`,T:ca},{no:4,name:`last_message_seq`,kind:`scalar`,T:13}]),Ba=k.makeMessageType(`livekit.TrackPublishedResponse`,()=>[{no:1,name:`cid`,kind:`scalar`,T:9},{no:2,name:`track`,kind:`message`,T:Vi}]),Va=k.makeMessageType(`livekit.TrackUnpublishedResponse`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9}]),Ha=k.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}}]),Ua=k.makeMessageType(`livekit.ParticipantUpdate`,()=>[{no:1,name:`participants`,kind:`message`,T:Ii,repeated:!0}]),Wa=k.makeMessageType(`livekit.UpdateSubscription`,()=>[{no:1,name:`track_sids`,kind:`scalar`,T:9,repeated:!0},{no:2,name:`subscribe`,kind:`scalar`,T:8},{no:3,name:`participant_tracks`,kind:`message`,T:sa,repeated:!0}]),Ga=k.makeMessageType(`livekit.UpdateDataSubscription`,()=>[{no:1,name:`updates`,kind:`message`,T:Ka,repeated:!0}]),Ka=k.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:Ui}],{localName:`UpdateDataSubscription_Update`}),qa=k.makeMessageType(`livekit.UpdateTrackSettings`,()=>[{no:1,name:`track_sids`,kind:`scalar`,T:9,repeated:!0},{no:3,name:`disabled`,kind:`scalar`,T:8},{no:4,name:`quality`,kind:`enum`,T:k.getEnumType(Di)},{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}]),Ja=k.makeMessageType(`livekit.UpdateLocalAudioTrack`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`features`,kind:`enum`,T:k.getEnumType(j),repeated:!0}]),Ya=k.makeMessageType(`livekit.UpdateLocalVideoTrack`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`width`,kind:`scalar`,T:13},{no:3,name:`height`,kind:`scalar`,T:13}]),Xa=k.makeMessageType(`livekit.LeaveRequest`,()=>[{no:1,name:`can_reconnect`,kind:`scalar`,T:8},{no:2,name:`reason`,kind:`enum`,T:k.getEnumType(Ai)},{no:3,name:`action`,kind:`enum`,T:k.getEnumType(Za)},{no:4,name:`regions`,kind:`message`,T:So}]),Za=k.makeEnum(`livekit.LeaveRequest.Action`,[{no:0,name:`DISCONNECT`},{no:1,name:`RESUME`},{no:2,name:`RECONNECT`}]),Qa=k.makeMessageType(`livekit.UpdateVideoLayers`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`layers`,kind:`message`,T:Wi,repeated:!0}]),$a=k.makeMessageType(`livekit.UpdateParticipantMetadata`,()=>[{no:1,name:`metadata`,kind:`scalar`,T:9},{no:2,name:`name`,kind:`scalar`,T:9},{no:3,name:`attributes`,kind:`map`,K:9,V:{kind:`scalar`,T:9}},{no:4,name:`request_id`,kind:`scalar`,T:13}]),eo=k.makeMessageType(`livekit.ICEServer`,()=>[{no:1,name:`urls`,kind:`scalar`,T:9,repeated:!0},{no:2,name:`username`,kind:`scalar`,T:9},{no:3,name:`credential`,kind:`scalar`,T:9}]),to=k.makeMessageType(`livekit.SpeakersChanged`,()=>[{no:1,name:`speakers`,kind:`message`,T:Zi,repeated:!0}]),no=k.makeMessageType(`livekit.RoomUpdate`,()=>[{no:1,name:`room`,kind:`message`,T:Ni}]),ro=k.makeMessageType(`livekit.ConnectionQualityInfo`,()=>[{no:1,name:`participant_sid`,kind:`scalar`,T:9},{no:2,name:`quality`,kind:`enum`,T:k.getEnumType(Oi)},{no:3,name:`score`,kind:`scalar`,T:2}]),io=k.makeMessageType(`livekit.ConnectionQualityUpdate`,()=>[{no:1,name:`updates`,kind:`message`,T:ro,repeated:!0}]),ao=k.makeMessageType(`livekit.StreamStateInfo`,()=>[{no:1,name:`participant_sid`,kind:`scalar`,T:9},{no:2,name:`track_sid`,kind:`scalar`,T:9},{no:3,name:`state`,kind:`enum`,T:k.getEnumType(wa)}]),oo=k.makeMessageType(`livekit.StreamStateUpdate`,()=>[{no:1,name:`stream_states`,kind:`message`,T:ao,repeated:!0}]),so=k.makeMessageType(`livekit.SubscribedQuality`,()=>[{no:1,name:`quality`,kind:`enum`,T:k.getEnumType(Di)},{no:2,name:`enabled`,kind:`scalar`,T:8}]),co=k.makeMessageType(`livekit.SubscribedCodec`,()=>[{no:1,name:`codec`,kind:`scalar`,T:9},{no:2,name:`qualities`,kind:`message`,T:so,repeated:!0}]),lo=k.makeMessageType(`livekit.SubscribedQualityUpdate`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`subscribed_qualities`,kind:`message`,T:so,repeated:!0},{no:3,name:`subscribed_codecs`,kind:`message`,T:co,repeated:!0}]),uo=k.makeMessageType(`livekit.SubscribedAudioCodecUpdate`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`subscribed_audio_codecs`,kind:`message`,T:Sa,repeated:!0}]),fo=k.makeMessageType(`livekit.TrackPermission`,()=>[{no:1,name:`participant_sid`,kind:`scalar`,T:9},{no:2,name:`all_tracks`,kind:`scalar`,T:8},{no:3,name:`track_sids`,kind:`scalar`,T:9,repeated:!0},{no:4,name:`participant_identity`,kind:`scalar`,T:9}]),po=k.makeMessageType(`livekit.SubscriptionPermission`,()=>[{no:1,name:`all_participants`,kind:`scalar`,T:8},{no:2,name:`track_permissions`,kind:`message`,T:fo,repeated:!0}]),mo=k.makeMessageType(`livekit.SubscriptionPermissionUpdate`,()=>[{no:1,name:`participant_sid`,kind:`scalar`,T:9},{no:2,name:`track_sid`,kind:`scalar`,T:9},{no:3,name:`allowed`,kind:`scalar`,T:8}]),ho=k.makeMessageType(`livekit.RoomMovedResponse`,()=>[{no:1,name:`room`,kind:`message`,T:Ni},{no:2,name:`token`,kind:`scalar`,T:9},{no:3,name:`participant`,kind:`message`,T:Ii},{no:4,name:`other_participants`,kind:`message`,T:Ii,repeated:!0}]),go=k.makeMessageType(`livekit.SyncState`,()=>[{no:1,name:`answer`,kind:`message`,T:Ha},{no:2,name:`subscription`,kind:`message`,T:Wa},{no:3,name:`publish_tracks`,kind:`message`,T:Ba,repeated:!0},{no:4,name:`data_channels`,kind:`message`,T:vo,repeated:!0},{no:5,name:`offer`,kind:`message`,T:Ha},{no:6,name:`track_sids_disabled`,kind:`scalar`,T:9,repeated:!0},{no:7,name:`datachannel_receive_states`,kind:`message`,T:_o,repeated:!0},{no:8,name:`publish_data_tracks`,kind:`message`,T:ja,repeated:!0}]),_o=k.makeMessageType(`livekit.DataChannelReceiveState`,()=>[{no:1,name:`publisher_sid`,kind:`scalar`,T:9},{no:2,name:`last_seq`,kind:`scalar`,T:13}]),vo=k.makeMessageType(`livekit.DataChannelInfo`,()=>[{no:1,name:`label`,kind:`scalar`,T:9},{no:2,name:`id`,kind:`scalar`,T:13},{no:3,name:`target`,kind:`enum`,T:k.getEnumType(Ca)}]),yo=k.makeMessageType(`livekit.SimulateScenario`,()=>[{no:1,name:`speaker_update`,kind:`scalar`,T:5,oneof:`scenario`},{no:2,name:`node_failure`,kind:`scalar`,T:8,oneof:`scenario`},{no:3,name:`migration`,kind:`scalar`,T:8,oneof:`scenario`},{no:4,name:`server_leave`,kind:`scalar`,T:8,oneof:`scenario`},{no:5,name:`switch_candidate_protocol`,kind:`enum`,T:k.getEnumType(Ta),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`}]),bo=k.makeMessageType(`livekit.Ping`,()=>[{no:1,name:`timestamp`,kind:`scalar`,T:3},{no:2,name:`rtt`,kind:`scalar`,T:3}]),xo=k.makeMessageType(`livekit.Pong`,()=>[{no:1,name:`last_ping_timestamp`,kind:`scalar`,T:3},{no:2,name:`timestamp`,kind:`scalar`,T:3}]),So=k.makeMessageType(`livekit.RegionSettings`,()=>[{no:1,name:`regions`,kind:`message`,T:Co,repeated:!0}]),Co=k.makeMessageType(`livekit.RegionInfo`,()=>[{no:1,name:`region`,kind:`scalar`,T:9},{no:2,name:`url`,kind:`scalar`,T:9},{no:3,name:`distance`,kind:`scalar`,T:3}]),wo=k.makeMessageType(`livekit.SubscriptionResponse`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`err`,kind:`enum`,T:k.getEnumType(Mi)}]),To=k.makeMessageType(`livekit.RequestResponse`,()=>[{no:1,name:`request_id`,kind:`scalar`,T:13},{no:2,name:`reason`,kind:`enum`,T:k.getEnumType(Eo)},{no:3,name:`message`,kind:`scalar`,T:9},{no:4,name:`trickle`,kind:`message`,T:Ia,oneof:`request`},{no:5,name:`add_track`,kind:`message`,T:ka,oneof:`request`},{no:6,name:`mute`,kind:`message`,T:La,oneof:`request`},{no:7,name:`update_metadata`,kind:`message`,T:$a,oneof:`request`},{no:8,name:`update_audio_track`,kind:`message`,T:Ja,oneof:`request`},{no:9,name:`update_video_track`,kind:`message`,T:Ya,oneof:`request`},{no:10,name:`publish_data_track`,kind:`message`,T:Aa,oneof:`request`},{no:11,name:`unpublish_data_track`,kind:`message`,T:Ma,oneof:`request`}]),Eo=k.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`}]),Do=k.makeMessageType(`livekit.TrackSubscribed`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9}]),Oo=k.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}]),ko=k.makeMessageType(`livekit.JoinRequest`,()=>[{no:1,name:`client_info`,kind:`message`,T:ua},{no:2,name:`connection_settings`,kind:`message`,T:Oo},{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:ka,repeated:!0},{no:6,name:`publisher_offer`,kind:`message`,T:Ha},{no:7,name:`reconnect`,kind:`scalar`,T:8},{no:8,name:`reconnect_reason`,kind:`enum`,T:k.getEnumType(ji)},{no:9,name:`participant_sid`,kind:`scalar`,T:9},{no:10,name:`sync_state`,kind:`message`,T:go}]),Ao=k.makeMessageType(`livekit.WrappedJoinRequest`,()=>[{no:1,name:`compression`,kind:`enum`,T:k.getEnumType(jo)},{no:2,name:`join_request`,kind:`scalar`,T:12}]),jo=k.makeEnum(`livekit.WrappedJoinRequest.Compression`,[{no:0,name:`NONE`},{no:1,name:`GZIP`}]),Mo=k.makeMessageType(`livekit.MediaSectionsRequirement`,()=>[{no:1,name:`num_audios`,kind:`scalar`,T:13},{no:2,name:`num_videos`,kind:`scalar`,T:13}]);function No(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,`default`)?e.default:e}var Po={exports:{}},Fo=Po.exports,Io;function Lo(){return Io?Po.exports:(Io=1,(function(e){(function(t,n){e.exports?e.exports=n():t.log=n()})(Fo,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 ee(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 p(){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 te(){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 ne(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=ne(e),t!==!1&&ee(u),l.call(o)},o.setDefaultLevel=function(e){c=ne(e),p()||o.setLevel(e,!1)},o.resetLevel=function(){u=null,te(),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=ne(a.getLevel())),l.call(o),a===o)for(var e in i)i[e].rebuild()},s=ne(a?a.getLevel():`WARN`);var m=p();m!=null&&(u=ne(m)),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 ee=typeof window===t?void 0:window.log;return a.noConflict=function(){return typeof window!==t&&window.log===a&&(window.log=ee),a},a.getLoggers=function(){return i},a.default=a,a})})(Po),Po.exports)}var Ro=Lo(),zo;(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`})(zo||={});var Bo;(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`})(Bo||={});var N=Ro.getLogger(`livekit`);Object.values(Bo).map(e=>Ro.getLogger(e)),N.setDefaultLevel(zo.info);function Vo(e){let t=Ro.getLogger(e);return t.setDefaultLevel(N.getLevel()),t}var Ho=Ro.getLogger(`lk-e2ee`),Uo=7e3,Wo=[0,300,4*300,9*300,16*300,Uo,Uo,Uo,Uo,Uo],Go=class{constructor(e){this._retryDelays=e===void 0?Wo:[...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 Ko(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 P(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 qo(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 Jo(e){return this instanceof Jo?(this.v=e,this):new Jo(e)}function Yo(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 Jo?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 Xo(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:Jo(e[r](t)),done:!1}:i?i(t):t}:i}}function Zo(e){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var t=e[Symbol.asyncIterator],n;return t?t.call(e):(e=typeof qo==`function`?qo(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 Qo={exports:{}},$o;function es(){if($o)return Qo.exports;$o=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)}Qo.exports=a,Qo.exports.once=m,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=p(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():te(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?ne(i):p(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):ee.call(e,t)},a.prototype.listenerCount=ee;function ee(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 p(e,t){for(var n=Array(t),r=0;r<t;++r)n[r]=e[r];return n}function te(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}function ne(e){for(var t=Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}function m(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))}h(e,t,a,{once:!0}),t!==`error`&&re(e,i,{once:!0})})}function re(e,t,n){typeof e.on==`function`&&h(e,`error`,t,n)}function h(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 Qo.exports}var ts=es(),ns=!0,rs=!0;function is(e,t,n){let r=e.match(t);return r&&r.length>=n&&parseFloat(r[n],10)}function as(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 os(e){return typeof e==`boolean`?(ns=e,e?`adapter.js logging disabled`:`adapter.js logging enabled`):Error(`Argument type: `+typeof e+`. Please use a boolean.`)}function ss(e){return typeof e==`boolean`?(rs=!e,`adapter.js deprecation warnings `+(e?`disabled`:`enabled`)):Error(`Argument type: `+typeof e+`. Please use a boolean.`)}function cs(){if(typeof window==`object`){if(ns)return;typeof console<`u`&&typeof console.log==`function`&&console.log.apply(console,arguments)}}function ls(e,t){rs&&console.warn(e+` is deprecated, please use `+t+` instead.`)}function us(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(is(n.userAgent,/Firefox\/(\d+)\./,1));else if(n.webkitGetUserMedia||e.isSecureContext===!1&&e.webkitRTCPeerConnection)t.browser=`chrome`,t.version=parseInt(is(n.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else if(e.RTCPeerConnection&&n.userAgent.match(/AppleWebKit\/(\d+)\./))t.browser=`safari`,t.version=parseInt(is(n.userAgent,/AppleWebKit\/(\d+)\./,1)),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&`currentDirection`in e.RTCRtpTransceiver.prototype,t._safariVersion=is(n.userAgent,/Version\/(\d+(\.?\d+))/,1);else return t.browser=`Not a supported browser.`,t;return t}function ds(e){return Object.prototype.toString.call(e)===`[object Object]`}function fs(e){return ds(e)?Object.keys(e).reduce(function(t,n){let r=ds(e[n]),i=r?fs(e[n]):e[n],a=r&&!Object.keys(i).length;return i===void 0||a?t:Object.assign(t,{[n]:i})},{}):e}function ps(e,t,n){!t||n.has(t.id)||(n.set(t.id,t),Object.keys(t).forEach(r=>{r.endsWith(`Id`)?ps(e,e.get(t[r]),n):r.endsWith(`Ids`)&&t[r].forEach(t=>{ps(e,e.get(t),n)})}))}function ms(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&&ps(e,n,i)})}),i}var hs=cs;function gs(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),hs(`chrome: `+JSON.stringify(e)),i(e)})}e.video=r(e.video)}return hs(`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 _s(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function vs(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 as(e,`track`,e=>(e.transceiver||Object.defineProperty(e,`transceiver`,{value:{receiver:e.receiver}}),e))}function ys(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 bs(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=>ms(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}),as(e,`track`,e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){let e=this;return this._pc.getStats().then(t=>ms(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 xs(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 Ss(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return xs(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 Cs(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 ws(e,t){as(e,`negotiationneeded`,e=>{let n=e.target;if(!((t.version<72||n.getConfiguration&&n.getConfiguration().sdpSemantics===`plan-b`)&&n.signalingState!==`stable`))return e})}var Ts=Object.freeze({__proto__:null,fixNegotiationNeeded:ws,shimAddTrackRemoveTrack:Ss,shimAddTrackRemoveTrackWithNative:xs,shimGetSendersWithDtmf:ys,shimGetUserMedia:gs,shimMediaStream:_s,shimOnTrack:vs,shimPeerConnection:Cs,shimSenderReceiverGetStats:bs});function Es(e,t){let n=e&&e.navigator,r=e&&e.MediaStreamTrack;if(n.getUserMedia=function(e,t,r){ls(`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 Ds(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 Os(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 ks(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 As(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 js(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}),as(e,`track`,e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Ms(e){!e.RTCPeerConnection||`removeStream`in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){ls(`removeStream`,`removeTrack`),this.getSenders().forEach(t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)})})}function Ns(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function Ps(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 Fs(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 Is(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 Ls(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 Rs=Object.freeze({__proto__:null,shimAddTransceiver:Ps,shimCreateAnswer:Ls,shimCreateOffer:Is,shimGetDisplayMedia:Ds,shimGetParameters:Fs,shimGetUserMedia:Es,shimOnTrack:Os,shimPeerConnection:ks,shimRTCDataChannel:Ns,shimReceiverGetStats:js,shimRemoveStream:Ms,shimSenderGetStats:As});function zs(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 Bs(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 Vs(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 Hs(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(Us(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,n,r){t.mediaDevices.getUserMedia(e).then(n,r)}.bind(t))}function Us(e){return e&&e.video!==void 0?Object.assign({},e,{video:fs(e.video)}):e}function Ws(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?(ls(`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 Gs(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 Ks(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 qs(e){typeof e!=`object`||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var Js=Object.freeze({__proto__:null,shimAudioContext:qs,shimCallbacksAPI:Vs,shimConstraints:Us,shimCreateOfferLegacy:Ks,shimGetUserMedia:Hs,shimLocalStreamsAPI:zs,shimRTCIceServerUrls:Ws,shimRemoteStreamsAPI:Bs,shimTrackEventTransceiver:Gs}),Ys={exports:{}},Xs;function Zs(){return Xs?Ys.exports:(Xs=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(`
|
|
11
11
|
`).map(e=>e.trim())},t.splitSections=function(e){return e.split(`
|
|
@@ -322,4 +322,4 @@ registerProcessor("scribeAudioProcessor", ScribeAudioProcessor);
|
|
|
322
322
|
0%, 80%, 100% { transform: translateY(0); opacity: 0.5; }
|
|
323
323
|
40% { transform: translateY(-5px); opacity: 1; }
|
|
324
324
|
}
|
|
325
|
-
`})]})});function uh(){let{status:e,runtimeConfig:t,resolvedConfig:n,chatId:r,chatHistory:i,isOpen:a,activeScreen:o,isHumanHandled:s,agentName:c,isAgentTyping:d,isAiTyping:f,isLoading:ee,isVoiceMode:p,isRateLimited:te,rateLimitMessage:ne,isConversationEnded:m,incomingCall:re,activeCallId:h,callConnectionState:ie,callConnectedAt:ae,isCallMuted:oe,webRTCError:se,language:g,historyRef:_,onMessageSync:ce,endConversation:le,acceptCall:ue,rejectCall:de,endWebRTCCall:fe,toggleCallMute:pe,dismissCallError:me,openWidget:he,closeWidget:ge,sendMessage:_e,setVoiceMode:ve,startTyping:ye,stopTyping:be,updateTypingDraft:xe}=Gt(),[Se,Ce]=(0,l.useState)(``),[we,Te]=(0,l.useState)(null),[Ee,De]=(0,l.useState)(null),[Oe,ke]=(0,l.useState)(null),[Ae,v]=(0,l.useState)(0),je=t?.widgetSettings||{},y=n?.widgetSettings||{},b={...je.branding||{},...y.branding||{}},Me={...je.theme||{},...y.theme||{}},Ne=Me.primaryColor||`#3B82F6`,Pe=Me.accentColor||`#1D4ED8`,Fe=(Me.position||`bottom-right`)===`bottom-left
|
|
325
|
+
`})]})});function uh(){let{status:e,runtimeConfig:t,resolvedConfig:n,chatId:r,chatHistory:i,isOpen:a,activeScreen:o,isHumanHandled:s,agentName:c,isAgentTyping:d,isAiTyping:f,isLoading:ee,isVoiceMode:p,isRateLimited:te,rateLimitMessage:ne,isConversationEnded:m,incomingCall:re,activeCallId:h,callConnectionState:ie,callConnectedAt:ae,isCallMuted:oe,webRTCError:se,language:g,historyRef:_,onMessageSync:ce,endConversation:le,acceptCall:ue,rejectCall:de,endWebRTCCall:fe,toggleCallMute:pe,dismissCallError:me,openWidget:he,closeWidget:ge,sendMessage:_e,setVoiceMode:ve,startTyping:ye,stopTyping:be,updateTypingDraft:xe}=Gt(),[Se,Ce]=(0,l.useState)(``),[we,Te]=(0,l.useState)(null),[Ee,De]=(0,l.useState)(null),[Oe,ke]=(0,l.useState)(null),[Ae,v]=(0,l.useState)(0),je=t?.widgetSettings||{},y=n?.widgetSettings||{},b={...je.branding||{},...y.branding||{}},Me={...je.theme||{},...y.theme||{}},Ne=Me.primaryColor||`#3B82F6`,Pe=Me.accentColor||`#1D4ED8`,Fe=(Me.position||`bottom-right`)===`bottom-left`?{left:`1.5rem`,bottom:`1.5rem`}:{right:`1.5rem`,bottom:`1.5rem`},Ie={"--flowengage-primary":Ne,"--flowengage-accent":Pe,position:`fixed`,zIndex:999999,border:`none`,outline:`none`,fontFamily:`ui-sans-serif, system-ui, sans-serif`,...a?{inset:0,...window.innerWidth>=768?{inset:`auto`,right:`1.5rem`,bottom:`1.5rem`}:{}}:Fe},Le=y.recommendations?.[g]||je.recommendations?.[g]||ch,Re=y.greetings?.[g]||je.greetings?.[g],ze=b.chatButtonText||`Chat with us`,Be=b.headerName||t?.websiteName||`OpenSense Labs`,Ve=b.logoUrl||null,x=b.hideWatermark||!1,S=y.elevenLabsAgentId||t?.elevenLabsAgentId||null,C=b.fallbackAgentName||`Agent`,He=re?.agentName||c||C;(0,l.useEffect)(()=>{if(!ae||ie!==`connected`){v(0);return}let e=()=>{let e=new Date(ae).getTime();isNaN(e)||v(Math.max(0,Math.floor((Date.now()-e)/1e3)))};e();let t=window.setInterval(e,1e3);return()=>window.clearInterval(t)},[ae,ie]),(0,l.useEffect)(()=>{if(!s||p||m){xe(``),be();return}if(!Se.trim()){xe(``),be();return}ye();let e=window.setTimeout(()=>{xe(Se)},120),t=window.setTimeout(()=>{be()},1200);return()=>{window.clearTimeout(e),window.clearTimeout(t)}},[Se,s,p,m,ye,be,xe]);let Ue=e=>e?{replyTo:e.messageId||e.id||null,replyToContent:(e.replyToContent||e.message||``).replace(/<[^>]+>/g,``).trim().slice(0,200),replyToSender:e.sender||null}:null;return e===`ready`?(0,u.jsxs)(`div`,{className:`flowengage-shell`,style:Ie,children:[(0,u.jsx)(pn,{isOpen:a,openWidget:he,launcherText:ze,primaryColor:Ne,posInline:Fe}),a&&(0,u.jsxs)(`div`,{className:`relative w-full h-full md:w-[min(423px,calc(100vw-40px))] md:h-[min(700px,calc(100vh-120px))] flex flex-col md:rounded-[24px] overflow-hidden shadow-[0_20px_50px_rgba(0,0,0,0.15)] border-none outline-none transition-all duration-300 ${i.length===0&&!p?`bg-gradient-to-b from-[var(--flowengage-primary)] from-0% via-[var(--flowengage-primary)] via-70% to-white to-85%`:`bg-white`}`,children:[(0,u.jsx)(gn,{logoUrl:Ve,brandName:Be,agentName:c,fallbackAgentName:C,activeScreen:o,branding:b,isConversationEnded:m,endConversation:le,closeWidget:ge,isInitial:i.length===0&&!p}),(0,u.jsx)(`div`,{className:`flex-1 overflow-y-auto flex flex-col`,children:p?(0,u.jsx)(sh,{agentId:S,chatId:r,historyRef:_,onMessageSync:ce,onEnd:()=>{we&&(we.getTracks().forEach(e=>e.stop()),Te(null)),ve(!1)}}):i.length===0?(0,u.jsx)(yn,{greetings:Re,recommendations:Le,onSendMessage:_e}):(0,u.jsx)(vn,{chatHistory:i,isAiTyping:f,isAgentTyping:d,setReplyContext:ke,TypingDots:lh})}),(0,u.jsx)(Cn,{webRTCError:se,micError:Ee,setMicError:De,dismissCallError:me,incomingCall:re,rejectCall:de,acceptCall:ue,activeCallId:h,callConnectionState:ie,formatCallDuration:e=>{let t=Math.floor(e/60),n=e%60;return`${t.toString().padStart(2,`0`)}:${n.toString().padStart(2,`0`)}`},callDurationSeconds:Ae,endWebRTCCall:fe,isCallMuted:oe,toggleCallMute:pe,isAIVoiceActive:p,currentCallAgentName:He,isRateLimited:te,rateLimitMessage:ne}),!p&&(0,u.jsx)(bn,{input:Se,setInput:Ce,onSubmit:async e=>{if(e.preventDefault(),!Se.trim()||m)return;let t=Se.trim(),n=Ue(Oe);Ce(``),ke(null),await _e(t,``,n)},isConversationEnded:m,callUiActive:!!(re||h),handleToggleVoice:async()=>{if(p){ve(!1);return}De(null);try{Te(await navigator.mediaDevices.getUserMedia({audio:!0})),ve(!0)}catch(e){De(e.message||`Could not access microphone.`)}},activeScreen:o,inputDisabled:ee||te||m,replyContext:Oe,clearReplyContext:()=>ke(null)}),!x&&(0,u.jsx)(`div`,{className:`flex items-center justify-center gap-3 pt-3 pb-4 text-[12px] text-gray-400`,children:(0,u.jsxs)(`div`,{children:[`Powered by `,(0,u.jsx)(`span`,{className:`text-blue-500`,children:`Open`}),(0,u.jsx)(`span`,{className:`text-red-500`,children:`Sense`}),` `,(0,u.jsx)(`span`,{className:`text-amber-500`,children:`Labs`})]})})]})]}):null}exports.FlowEngageProvider=rn,exports.FlowEngageWidget=uh,exports.useFlowEngage=Gt;
|