@flowengage/react-chatbot 0.2.20 → 0.2.22
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.
package/dist/flowengage-embed.js
CHANGED
|
@@ -13,12 +13,12 @@ Error generating stack: `+e.message+`
|
|
|
13
13
|
transition: all 0.3s ease !important;
|
|
14
14
|
border-radius: 8px !important;
|
|
15
15
|
}
|
|
16
|
-
`,document.head.appendChild(e)};function tn(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 nn(e){!e||typeof document>`u`||(en(),rn(),e.classList.add(`fe-highlight-section`),e.scrollIntoView({behavior:`smooth`,block:`center`}))}function rn(){typeof document>`u`||document.querySelectorAll(`.fe-highlight-section`).forEach(e=>e.classList.remove(`fe-highlight-section`))}function an(e){if(typeof window>`u`)return e;try{let t=new URL(String(e).trim(),window.location.href);return!/^https?:$/i.test(t.protocol)||t.origin===window.location.origin?t.href:new URL(t.pathname+t.search+t.hash,window.location.origin).href}catch{return e}}async function on(e){if(typeof window>`u`)return!1;try{let t=new URL(String(e).trim(),window.location.href);return t.origin===window.location.origin?(await fetch(t.href,{method:`HEAD`,mode:`same-origin`,cache:`no-store`})).ok:!1}catch{return!1}}async function sn(e,{siteId:t,apiBaseUrl:n}){if(!e)return!1;if(!t||!n)return console.warn(`[FlowEngage] shouldProceedWithNavigation: missing siteId or apiBaseUrl`),!1;let r=String(n).replace(/\/$/,``),i=new URLSearchParams({siteId:String(t),url:String(e).trim()});try{let t=await(await fetch(`${r}/api/widget/navigate-allowed?${i.toString()}`)).json().catch(()=>({}));return t.success?t.allowed?!0:t.hasIndex===!1?on(e):!1:!1}catch(e){return console.warn(`[FlowEngage] navigate-allowed check failed:`,e?.message),!1}}async function cn(e){if(typeof window>`u`)return!1;try{let t=an(e),n=new URL(t,window.location.origin);if($t(`input:`,e,`→ normalized:`,t,`href:`,n.href),n.hash&&n.pathname===window.location.pathname){let e=n.hash.slice(1),t=document.getElementById(e);if(t)return $t(`branch: hash scroll (same path)`),t.scrollIntoView({behavior:`smooth`,block:`start`}),!0}if(n.pathname===window.location.pathname&&n.search===window.location.search&&!n.hash)return $t(`branch: already on page (no nav)`),!1;let r=n.pathname+n.search+n.hash,i=window.next?.router;if(i?.push)return $t(`branch: Next.js Pages router.push`,r),new Promise(e=>{let t=()=>{i.events?.off(`routeChangeComplete`,t),e(!0)};i.events?.on(`routeChangeComplete`,t),i.push(r),setTimeout(t,4e3)});let a=window.__NEXT_ROUTER__;return a?.push?($t(`branch: __NEXT_ROUTER__.push`,r),a.push(r),!0):($t(`branch: location.assign (full navigation)`,n.href),window.location.assign(n.href),!0)}catch(t){console.warn(`[FlowEngage] shadowNavigate error:`,t);try{window.location.href=an(e)}catch{window.location.href=e}return!0}}var ln=o((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.fragment`);function r(e,n,r){var i=null;if(r!==void 0&&(i=``+r),n.key!==void 0&&(i=``+n.key),`key`in n)for(var a in r={},n)a!==`key`&&(r[a]=n[a]);else r=n;return n=r.ref,{$$typeof:t,type:e,key:i,ref:n===void 0?null:n,props:r}}e.Fragment=n,e.jsx=r,e.jsxs=r})),A=o(((e,t)=>{t.exports=ln()}))(),un=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(),dn=(e=[])=>e.map(e=>({...e,message:un(e.message),isPending:!1,id:e.messageId||`${e.sender}-${e.timestamp||Date.now()}-${Math.random()}`})),fn=(e,t)=>e?typeof e==`string`?e:e.message||e.error||e.reason||t:t,pn=(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}:{}}},mn=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}},hn=(e=[],t=`Agent`)=>{for(let t of e)if(typeof t==`string`&&t.trim())return t.trim();return t};function gn({siteId:e,config:t,children:n,language:r=`en`}){let i=(0,v.useMemo)(()=>e?{...t||{},siteId:e}:t||null,[e,t]),a=(0,v.useMemo)(()=>hn([i?.widgetSettings?.branding?.fallbackAgentName,i?.widgetSettings?.branding?.headerName],`Agent`),[i]),[o,s]=(0,v.useState)(`booting`),[c,l]=(0,v.useState)(null),[u,d]=(0,v.useState)(null),[f,p]=(0,v.useState)(``),[m,h]=(0,v.useState)([]),[g,_]=(0,v.useState)(re().isOpen),[y,x]=(0,v.useState)(re().activeScreen),[ee,S]=(0,v.useState)(re().isHumanHandled),[se,ce]=(0,v.useState)(re().agentName),[de,fe]=(0,v.useState)(re().agentHeadshot),[C,w]=(0,v.useState)(ae()),[pe,me]=(0,v.useState)(!1),[he,ge]=(0,v.useState)(!1),[_e,T]=(0,v.useState)(`idle`),[ve,ye]=(0,v.useState)(!1),[be,xe]=(0,v.useState)(!1),[Se,Ce]=(0,v.useState)(``),[we,Te]=(0,v.useState)(!1),[Ee,De]=(0,v.useState)(!1),[E,Oe]=(0,v.useState)(null),[ke,Ae]=(0,v.useState)(null),[je,Me]=(0,v.useState)(`idle`),[D,Ne]=(0,v.useState)(null),[Pe,Fe]=(0,v.useState)(!1),[Ie,Le]=(0,v.useState)(``),Re=(0,v.useRef)(null),ze=(0,v.useRef)(null),O=(0,v.useRef)(``),Be=(0,v.useRef)(null),Ve=(0,v.useRef)(null),He=(0,v.useRef)(null),Ue=(0,v.useRef)(null),We=(0,v.useRef)(null),Ge=(0,v.useRef)([]),Ke=(0,v.useRef)(null),qe=(0,v.useRef)(null),Je=(0,v.useRef)(!1),Ye=(0,v.useRef)(!1),Xe=(0,v.useRef)(``),Ze=(0,v.useRef)([]),Qe=(0,v.useRef)(!1),$e=(0,v.useRef)({notifyRouteChange:()=>{},cleanup:()=>{}}),et=(0,v.useMemo)(()=>{let e=u?.widgetSettings?.call?.maxDurationSeconds??i?.widgetSettings?.call?.maxDurationSeconds??i?.callMaxDurationSeconds,t=Number(e);return Number.isFinite(t)&&t>0?t:900},[i,u]);(0,v.useEffect)(()=>{Be.current=E},[E]);let tt=()=>{Le(``)},nt=e=>{let t=typeof e==`string`?e.trim().toLowerCase():``;return w(t),oe(t),t},rt=()=>{Ve.current&&=(Ve.current.close(),null),He.current&&=(He.current.getTracks().forEach(e=>e.stop()),null),Ue.current&&=(Ue.current.srcObject=null,Ue.current.remove(),null),We.current=null,Ge.current=[],Ke.current=null,qe.current=null,Je.current=!1,Fe(!1),Oe(null),Ae(null),Me(`idle`),Ne(null)},it=(e=new Date().toISOString())=>{let t=Re.current,n=Ke.current||We.current?.callId;if(!t?.connected||!n||Je.current){console.log(`[FlowEngageProvider] skipping call:connected emit`,{callId:n,chatId:O.current,socketConnected:!!t?.connected,alreadyReported:Je.current});return}console.log(`[FlowEngageProvider] emitting call:connected`,{callId:n,chatId:O.current,connectedAt:e}),Je.current=!0,t.emit(`call:connected`,{callId:n,chatId:O.current,connectedAt:e})},at=(e={})=>{if(!e.callId)return;let t=qe.current===e.callId,n=Ke.current===e.callId,r=Be.current?.callId===e.callId;if(!(!t&&!n&&!r)){if(console.log(`[FlowEngageProvider] syncing accepted call state`,{callId:e.callId,chatId:e.chatId||O.current,isAcceptingHere:t,isAlreadyActive:n,isIncomingHere:r}),Oe(null),t||n){Ke.current=e.callId,Ae(e.callId),Me(e=>e===`connected`?e:`connecting`),_(!0);return}Me(`idle`)}},ot=(e={})=>{if(!e.callId)return;let t=qe.current===e.callId,n=Ke.current===e.callId,r=Be.current?.callId===e.callId;if(!(!t&&!n&&!r)){if(console.log(`[FlowEngageProvider] syncing ended incoming call state`,{callId:e.callId,chatId:e.chatId||O.current,isAcceptingHere:t,isAlreadyActive:n,isIncomingHere:r,reason:e.reason||e.status||null}),n){rt();return}qe.current=null,We.current=null,Ge.current=[],Oe(null),Me(`idle`)}},st=async(e={})=>{let t=Ve.current,n=Re.current,r=e.sdpOffer||e.offer?.sdp;if(!t||!n?.connected||!r||!e.callId){console.log(`[FlowEngageProvider] deferring remote offer until peer/socket ready`,{callId:e.callId,chatId:O.current,hasPeerConnection:!!t,socketConnected:!!n?.connected,hasOffer:!!r}),We.current=e;return}if(console.log(`[FlowEngageProvider] applying remote offer`,{callId:e.callId,chatId:O.current,offerLength:r.length,signalingState:t.signalingState}),await t.setRemoteDescription(new RTCSessionDescription({type:`offer`,sdp:r})),Ge.current.length>0){console.log(`[FlowEngageProvider] flushing queued agent ICE candidates after remote offer`,{callId:e.callId,chatId:O.current,queuedCount:Ge.current.length});for(let e of Ge.current)await t.addIceCandidate(new RTCIceCandidate(e));Ge.current=[]}let i=await t.createAnswer();await t.setLocalDescription(i),console.log(`[FlowEngageProvider] created local answer`,{callId:e.callId,chatId:O.current,answerLength:i.sdp?.length||0,signalingState:t.signalingState}),n.emit(`call:answer`,{callId:e.callId,sdpAnswer:i.sdp,chatId:O.current})};(0,v.useEffect)(()=>{ie({isOpen:g,activeScreen:y,isHumanHandled:ee,agentName:se,agentHeadshot:de})},[g,y,ee,se,de]),(0,v.useEffect)(()=>{let e=!0;return(async()=>{try{console.log(`[FlowEngageProvider] boot start`,{resolvedConfig:i,language:r});let t=b(i);console.log(`[FlowEngageProvider] config validated`,t);let n=await le(t);if(!e)return;let o=ne();O.current=o;let c=ue({apiBaseUrl:t.apiBaseUrl,userId:n.userId,siteId:t.siteId});ze.current=c,d({...n,apiBaseUrl:t.apiBaseUrl}),p(o),console.log(`[FlowEngageProvider] bootstrap resolved`,{bootstrapData:n,resolvedChatId:o});let l=Jt({apiBaseUrl:t.apiBaseUrl,userId:n.userId,chatId:o,siteId:t.siteId});Re.current=l,l.on(`connect`,()=>{console.log(`[FlowEngageProvider] socket connected`),T(`connected`)}),l.on(`disconnect`,()=>{console.log(`[FlowEngageProvider] socket disconnected`),T(`disconnected`)}),l.on(`aiTyping`,()=>{console.log(`[FlowEngageProvider] received aiTyping`,{chatId:O.current}),ge(!0)}),l.on(`ai:typing`,()=>{console.log(`[FlowEngageProvider] received ai:typing`,{chatId:O.current}),ge(!0)}),l.on(`messageReceived`,e=>{let t=e.message||e,n={...t,message:un(t.message)};ge(!1),me(!1),h(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&&h(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:un(t.message)};ge(!1),(n.sender===`agent`||n.agent_name||n.sender===`ai`||n.sender===`bot`)&&me(!1),h(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)&&(S(!0),x(`agent`),ce(hn([n.agent_name,n.agentName,n.metadata?.agentName],a)),n.sender_headshot&&fe(n.sender_headshot),_(!0))}),l.on(`agent:joined`,e=>{let t=hn([e.agent?.name,e.agentName],a);S(!0),x(`agent`),ce(t),fe(e.agent?.headshot||null),_(!0),h(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=hn([e.agent?.name,e.agentName],a);S(!0),x(`agent`),ce(t),fe(e.agent?.headshot||null),_(!0),h(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`,(e={})=>{let t=hn([e.agent?.name,e.agentName,se],a);S(!1),x(`ai`),h(e=>[...e,{id:`agent-left-${Date.now()}`,sender:`system`,message:`${t} has left the chat.`,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`agentLeft`,(e={})=>{let t=hn([e.agent?.name,e.agentName,se],a);S(!1),x(`ai`),h(e=>[...e,{id:`agent-left-${Date.now()}`,sender:`system`,message:`${t} has left the chat.`,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`conversationEnded`,e=>{De(!0);let t=e?.message||`This conversation has ended. Thank you for reaching out!`;h(e=>[...e,{id:`conversation-ended-${Date.now()}`,sender:`system`,message:t,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`chat:history_update`,e=>{h(dn(e.chat_history||[]))}),l.on(`typing:start`,e=>{console.log(`[FlowEngageProvider] received typing:start`,{chatId:e?.chatId||O.current,sender:e?.sender}),e.sender===`agent`&&me(!0)}),l.on(`typing:stop`,e=>{console.log(`[FlowEngageProvider] received typing:stop`,{chatId:e?.chatId||O.current,sender:e?.sender}),e.sender===`agent`&&me(!1)}),l.on(`call:incoming`,(e={})=>{let t=hn([e.agentName,e.ownerName,e.agent?.name,se],a);console.log(`[FlowEngageProvider] received call:incoming`,{callId:e.callId,chatId:O.current,agentName:t}),tt(),Je.current=!1,Oe({callId:e.callId,from:e.from||`owner`,agentId:e.agentId||null,agentName:t}),ce(e=>hn([t,e],a)),Me(`incoming`),Ne(null),_(!0)}),l.on(`call:offer`,async(e={})=>{console.log(`[FlowEngageProvider] received call:offer`,{callId:e.callId,chatId:e.chatId||O.current,offerLength:(e.sdpOffer||e.offer?.sdp||``).length}),We.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||O.current,hasPeerConnection:!!Ve.current,hasCandidate:!!e.candidate});return}try{let t=pn(e);if(!t){console.warn(`[FlowEngageProvider] ignoring invalid ICE candidate payload`,e);return}if(console.log(`[FlowEngageProvider] adding agent ICE candidate`,{callId:e.callId,chatId:e.chatId||O.current,candidate:mn(t),hasRemoteDescription:!!Ve.current?.remoteDescription}),!Ve.current||!Ve.current.remoteDescription){console.log(`[FlowEngageProvider] queueing agent ICE candidate until peer/remote description is ready`,{callId:e.callId,chatId:e.chatId||O.current,queueSize:Ge.current.length+1}),Ge.current.push(t);return}await Ve.current.addIceCandidate(new RTCIceCandidate(t))}catch(e){console.error(`[FlowEngageProvider] failed to add ICE candidate`,e)}}),l.on(`call:ended`,()=>{tt(),rt()}),l.on(`call:accepted`,(e={})=>{console.log(`[FlowEngageProvider] received call:accepted`,{callId:e.callId,chatId:e.chatId||O.current}),at(e)}),l.on(`call:accepted_by_other`,(e={})=>{console.log(`[FlowEngageProvider] received call:accepted_by_other`,{callId:e.callId,chatId:e.chatId||O.current}),at(e)}),l.on(`call:rejected`,(e={})=>{console.log(`[FlowEngageProvider] received call:rejected`,{callId:e.callId,chatId:e.chatId||O.current,reason:e.reason}),ot(e)}),l.on(`call:missed`,(e={})=>{console.log(`[FlowEngageProvider] received call:missed`,{callId:e.callId,chatId:e.chatId||O.current,reason:e.reason}),ot(e)}),l.on(`call:failed`,(e={})=>{console.log(`[FlowEngageProvider] received call:failed`,{callId:e.callId,chatId:e.chatId||O.current,reason:e.reason}),ot(e)}),l.on(`call:connected`,(e={})=>{if(!e.callId)return;let t=qe.current===e.callId,n=Ke.current===e.callId,r=Be.current?.callId===e.callId;if(console.log(`[FlowEngageProvider] received call:connected`,{callId:e.callId,chatId:e.chatId||O.current,connectedAt:e.connectedAt,status:e.status,isAcceptingHere:t,isAlreadyActive:n,isIncomingHere:r}),!t&&!n){r&&(Oe(null),Me(`idle`));return}Je.current=!0,qe.current=null,Ke.current=e.callId,Ae(e.callId),Oe(null),Me(`connected`),Ne(e.connectedAt||new Date().toISOString()),_(!0)}),l.on(`call:unavailable`,(e={})=>{rt(),Le(fn(e,`This visitor is not available for a call right now.`)),_(!0)}),l.on(`call:error`,(e={})=>{rt(),Le(fn(e,`We couldn't connect the call right now.`)),_(!0)}),l.on(`visitor:navigate`,async({url:e,section:n,highlight:r}={})=>{if(e){if(console.log(`[FlowEngageProvider] visitor:navigate`,{url:e,section:n,highlight:r}),!await sn(e,{siteId:t.siteId,apiBaseUrl:t.apiBaseUrl})){console.warn(`[FlowEngageProvider] visitor:navigate blocked (not indexed)`,e);return}cn(e).then(e=>{let t=n||r;t&&setTimeout(()=>{let e=tn(null,t);e&&nn(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=tn(e||null,t||null);n&&nn(n)}),l.on(`visitor:clear_highlight`,()=>{rn()}),$e.current=Yt({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||(h(dn(u.chat_history||[])),S(!!u.is_human_handled),x(u.is_human_handled?`agent`:y),await new Promise(e=>setTimeout(e,500)),!e))return;s(`ready`),console.log(`[FlowEngageProvider] status ready`)}catch(t){if(!e)return;console.error(`[FlowEngageProvider] boot failed`,t),l(t),s(`error`)}})(),()=>{e=!1,$e.current?.cleanup?.(),rt(),Re.current?.disconnect()}},[i,r]),(0,v.useEffect)(()=>()=>{if(we&&!Qe.current&&Ze.current.length>0){let e=O.current,t=Ze.current,n=ze.current,r=u?.apiBaseUrl||``,i=u?.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(()=>{}),Qe.current=!0)}},[we,u]),(0,v.useEffect)(()=>{if(!ze.current||!f||o!==`ready`||ee)return;let e=window.setInterval(async()=>{try{let e=await ze.current.checkHumanHandled(f);S(!!e.is_human_handled),e.is_human_handled&&(x(`agent`),e.agent_info?.name&&ce(e.agent_info.name),e.agent_info?.headshot&&fe(e.agent_info.headshot))}catch{}},1e4);return()=>window.clearInterval(e)},[f,o,ee]);let ct=async()=>{if(!(!E?.callId||!ze.current||!Re.current||!f)){tt(),qe.current=E.callId,console.log(`[FlowEngageProvider] acceptCall started`,{callId:E?.callId,chatId:f,socketConnected:!!Re.current?.connected,hasPendingOffer:!!We.current});try{let e=await navigator.mediaDevices.getUserMedia({audio:!0});console.log(`[FlowEngageProvider] microphone stream acquired`,{callId:E.callId,chatId:f,trackCount:e.getTracks().length}),He.current=e;let t=new RTCPeerConnection({iceServers:[{urls:`stun:stun.l.google.com:19302`}]});Ve.current=t,t.onconnectionstatechange=()=>{let e=t.connectionState;if(console.log(`[FlowEngageProvider] peer connection state changed`,{callId:E.callId,chatId:f,connectionState:e,iceConnectionState:t.iceConnectionState,signalingState:t.signalingState}),e===`connected`){let e=new Date().toISOString();Me(`connected`),Ne(t=>t||e),it(e);return}e===`connecting`&&Me(e=>e===`connected`?e:`connecting`)},t.oniceconnectionstatechange=()=>{let e=t.iceConnectionState;if(console.log(`[FlowEngageProvider] ICE connection state changed`,{callId:E.callId,chatId:f,iceConnectionState:e,connectionState:t.connectionState,signalingState:t.signalingState}),e===`connected`||e===`completed`){let e=new Date().toISOString();Me(`connected`),Ne(t=>t||e),it(e);return}(e===`checking`||e===`new`)&&Me(e=>e===`connected`?e:`connecting`)},e.getTracks().forEach(n=>{t.addTrack(n,e)}),t.onicecandidate=e=>{if(!e.candidate||!Re.current?.connected){console.log(`[FlowEngageProvider] local ICE candidate skipped`,{callId:E.callId,chatId:f,hasCandidate:!!e.candidate,socketConnected:!!Re.current?.connected});return}console.log(`[FlowEngageProvider] emitting local ICE candidate`,{callId:E.callId,chatId:f,candidate:mn(e.candidate)}),Re.current.emit(`call:ice-candidate`,{callId:E.callId,candidate:e.candidate,chatId:f,from:`customer`})},t.ontrack=e=>{if(console.log(`[FlowEngageProvider] remote audio track received`,{callId:E.callId,chatId:f,streamCount:e.streams?.length||0}),!Ue.current){let e=document.createElement(`audio`);e.id=`flowengage-remote-audio`,e.autoplay=!0,Ue.current=e,document.body.appendChild(e)}Ue.current.srcObject=e.streams[0]};let n=We.current;n&&(console.log(`[FlowEngageProvider] found pending remote offer during accept`,{callId:n.callId||E.callId,chatId:f}),await st({...n,callId:n.callId||E.callId})),await ze.current.acceptCall(E.callId,f),console.log(`[FlowEngageProvider] acceptCall API succeeded`,{callId:E.callId,chatId:f}),Ke.current=E.callId,Ae(E.callId),Me(`connecting`),Oe(null),_(!0)}catch(e){if(console.error(`[FlowEngageProvider] acceptCall failed`,e),qe.current=null,rt(),e?.status===404||e?.status===409||e?.status===422){Le(fn(e,`This visitor call is no longer available.`));return}if(e?.name===`NotAllowedError`||e?.name===`PermissionDeniedError`){try{await ze.current.rejectCall(E.callId,f)}catch(e){console.error(`[FlowEngageProvider] failed to reject call after microphone denial`,e)}Le(`Microphone access was denied. Please allow microphone access to accept the call.`);return}Le(`We couldn't connect the call right now. Please try again.`)}}},lt=async()=>{if(!E?.callId||!ze.current||!f){rt();return}tt();try{await ze.current.rejectCall(E.callId,f)}catch(e){console.error(`[FlowEngageProvider] rejectCall failed`,e),Le(fn(e,`We couldn't decline the call cleanly.`))}finally{rt()}},ut=async()=>{if(!ke||!ze.current||!f){rt();return}tt();try{await ze.current.endWebRTCCall(ke,f)}catch(e){console.error(`[FlowEngageProvider] endWebRTCCall failed`,e),Le(fn(e,`The call ended locally, but the server could not be updated.`))}finally{rt()}},dt=()=>{let e=He.current?.getAudioTracks?.()||[],t=Ve.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=!Pe;n.forEach(e=>{e.enabled=!r}),console.log(`[FlowEngageProvider] toggled local mute`,{nextMuted:r,trackCount:n.length}),Fe(r)},ft=async(e={})=>{let t=e.notifyChatInitiated===!0;if(_(!0),!(!t||!ze.current||!f||typeof window>`u`)){try{await ze.current.trackVisitor({chatId:f,currentPagePath:window.location.pathname||`/`})}catch{}try{await ze.current.updateChatStatus(f,`open`)}catch{}}},pt=async e=>{let t=nt(e);if(!t||!ze.current||!O.current)return t;try{await ze.current.trackVisitor({chatId:O.current,currentPagePath:typeof window<`u`&&window.location.pathname||`/`,email:t})}catch(e){console.error(`[FlowEngageProvider] failed to persist visitor email`,e)}return t},mt=()=>{if(!f||!Re.current?.connected||Ye.current){console.log(`[FlowEngageProvider] skipped typing:start emit`,{chatId:f,socketConnected:!!Re.current?.connected,alreadyTyping:Ye.current});return}Ye.current=!0,console.log(`[FlowEngageProvider] emitting typing:start`,{chatId:f,sender:`user`}),Re.current.emit(`typing:start`,{chatId:f,sender:`user`})},ht=()=>{if(f&&Re.current?.connected&&Xe.current!==``&&(console.log(`[FlowEngageProvider] clearing typing draft`,{chatId:f,sender:`user`}),Re.current.emit(`typing:update`,{chatId:f,sender:`user`,text:``}),Xe.current=``),!f||!Re.current?.connected||!Ye.current){console.log(`[FlowEngageProvider] skipped typing:stop emit`,{chatId:f,socketConnected:!!Re.current?.connected,wasTyping:Ye.current});return}Ye.current=!1,console.log(`[FlowEngageProvider] emitting typing:stop`,{chatId:f,sender:`user`}),Re.current.emit(`typing:stop`,{chatId:f,sender:`user`})},gt=(e=``)=>{let t=typeof e==`string`?e:``;if(!f||!Re.current?.connected){console.log(`[FlowEngageProvider] skipped typing:update emit`,{chatId:f,socketConnected:!!Re.current?.connected,textLength:t.length});return}Xe.current!==t&&(Xe.current=t,console.log(`[FlowEngageProvider] emitting typing:update`,{chatId:f,sender:`user`,textLength:t.length}),Re.current.emit(`typing:update`,{chatId:f,sender:`user`,text:t}))},_t=async(e,t=``,n=null)=>{if(!e.trim()||!ze.current||!f||o!==`ready`||Ee)return;ht();let i=`pending-user-${Date.now()}`,a={id:i,sender:`user`,message:e,timestamp:new Date().toISOString(),isPending:!0,...n||{}};if(h(e=>[...e,a]),ee&&Re.current?.connected){Re.current.emit(`customer:message`,{chatId:f,content:e,sender:`user`,email:C||void 0,...n||{}});return}ye(!0);try{let i=await ze.current.sendAiMessage(f,e,r,t,{...n||{},...C?{email:C}:{}});h(dn(i.chat_history||[])),S(!!i.is_human_handled),x(i.is_human_handled?`agent`:`ai`),ge(!1),await ze.current.updateChatStatus(f,`messageSent`)}catch(e){h(e=>e.filter(e=>e.id!==i)),ge(!1),e.status===429?(xe(!0),Ce(e.message),window.setTimeout(()=>{xe(!1),Ce(``)},te)):l(e)}finally{ye(!1)}},vt=async e=>{if(!(!ze.current||!f)){try{let t=e?`voice`:`text`;await ze.current.setChatMode(f,t)}catch(e){console.error(`[FlowEngageProvider] setVoiceMode failed`,e)}Te(e),e&&(Qe.current=!1)}},yt=async e=>{if(!Qe.current){if(Qe.current=!0,!ze.current||!f||!e?.length){Te(!1);return}try{let t=await ze.current.syncVoice(f,e);t?.chat_history&&h(dn(t.chat_history))}catch{}finally{Te(!1)}}},bt=async()=>{if(!(!ze.current||!f)){we&&!Qe.current&&Ze.current.length>0&&await yt(Ze.current);try{await ze.current.endConversation(f)}catch{try{await ze.current.updateChatStatus(f,`ended`)}catch{}}De(!0),h(e=>[...e,{id:`conversation-ended-${Date.now()}`,sender:`system`,message:`This conversation has ended. Thank you for reaching out!`,timestamp:new Date().toISOString(),isPending:!1}])}};(0,v.useEffect)(()=>{if(je!==`connected`||!ke||!f||!D||!et)return;let e=new Date(D).getTime(),t=Number.isFinite(e)?Date.now()-e:0,n=Math.max(0,et*1e3-t),r=window.setTimeout(()=>{Le(`The call ended because it reached the time limit.`),ut()},n);return()=>window.clearTimeout(r)},[ke,D,je,f,ut,et]),(0,v.useEffect)(()=>{let e=()=>{let e=O.current,t=ze.current;if(!t||!e)return;if(Ke.current){t.beaconEndWebRTCCall(Ke.current,e);return}let n=qe.current||Be.current?.callId;n&&t.beaconCustomerUnavailable(n,e)};return window.addEventListener(`pagehide`,e),window.addEventListener(`beforeunload`,e),()=>{window.removeEventListener(`pagehide`,e),window.removeEventListener(`beforeunload`,e)}},[]);let xt=(0,v.useMemo)(()=>({status:o,error:c,runtimeConfig:u,resolvedConfig:i,chatId:f,chatHistory:m,isOpen:g,activeScreen:y,isHumanHandled:ee,agentName:se,agentHeadshot:de,visitorEmail:C,isAgentTyping:pe,isAiTyping:he,connectionStatus:_e,isLoading:ve,isVoiceMode:we,isRateLimited:be,rateLimitMessage:Se,isConversationEnded:Ee,incomingCall:E,activeCallId:ke,callConnectionState:je,callConnectedAt:D,isCallMuted:Pe,webRTCError:Ie,language:r,historyRef:Ze,hasSyncedRef:Qe,dismissCallError:tt,captureVisitorEmail:pt,startTyping:mt,stopTyping:ht,updateTypingDraft:gt,notifyRouteChange:()=>$e.current?.notifyRouteChange?.(),openWidget:ft,closeWidget:()=>_(!1),toggleWidget:()=>{if(g){_(!1);return}ft({notifyChatInitiated:!0})},sendMessage:_t,setVoiceMode:vt,onMessageSync:yt,endConversation:bt,acceptCall:ct,rejectCall:lt,endWebRTCCall:ut,toggleCallMute:dt,startTyping:mt,stopTyping:ht,updateTypingDraft:gt}),[o,c,u,i,f,m,g,y,ee,se,de,C,pe,he,_e,ve,we,be,Se,Ee,E,ke,je,D,Pe,Ie,r,pt,mt,ht,gt,ct,lt,ut,dt,ft,_t,vt,yt,bt,tt]);return(0,A.jsx)(Xt.Provider,{value:xt,children:n})}var _n=({color:e=`#3888FF`})=>(0,A.jsxs)(`svg`,{width:`40`,height:`40`,viewBox:`0 0 40 40`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,A.jsx)(`rect`,{width:`40`,height:`40`,rx:`20`,fill:e}),(0,A.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,A.jsx)(`path`,{d:`M18 32L18 26L24 26L18 32Z`,fill:`#ECF0F0`}),(0,A.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`})]}),vn=({size:e=18,color:t=`currentColor`})=>(0,A.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,A.jsx)(`path`,{d:`M12 1a4 4 0 014 4v6a4 4 0 01-8 0V5a4 4 0 014-4z`,fill:t}),(0,A.jsx)(`path`,{d:`M19 10a7 7 0 01-14 0M12 19v4M8 23h8`,stroke:t,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})]}),yn=({size:e=20})=>(0,A.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,A.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,A.jsx)(`line`,{x1:`23`,y1:`1`,x2:`1`,y2:`23`})]}),bn=()=>(0,A.jsxs)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,A.jsx)(`line`,{x1:`12`,y1:`19`,x2:`12`,y2:`5`}),(0,A.jsx)(`polyline`,{points:`5 12 12 5 19 12`})]}),xn=()=>(0,A.jsxs)(`svg`,{width:`14`,height:`14`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,A.jsx)(`polyline`,{points:`9 17 4 12 9 7`}),(0,A.jsx)(`path`,{d:`M20 18v-2a4 4 0 00-4-4H4`})]}),Sn=()=>(0,A.jsx)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,A.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`})}),Cn=({className:e=``})=>(0,A.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,A.jsx)(`circle`,{cx:`12`,cy:`12`,r:`10`}),(0,A.jsx)(`line`,{x1:`12`,y1:`8`,x2:`12`,y2:`12`}),(0,A.jsx)(`line`,{x1:`12`,y1:`16`,x2:`12.01`,y2:`16`})]}),wn=({size:e=18,strokeWidth:t=2.5})=>(0,A.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:t,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,A.jsx)(`line`,{x1:`18`,y1:`6`,x2:`6`,y2:`18`}),(0,A.jsx)(`line`,{x1:`6`,y1:`6`,x2:`18`,y2:`18`})]}),Tn=({size:e=14})=>(0,A.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,A.jsx)(`path`,{d:`M12 8V4H8`}),(0,A.jsx)(`rect`,{width:`16`,height:`12`,x:`4`,y:`8`,rx:`2`}),(0,A.jsx)(`path`,{d:`M2 14h2`}),(0,A.jsx)(`path`,{d:`M20 14h2`}),(0,A.jsx)(`path`,{d:`M15 13v2`}),(0,A.jsx)(`path`,{d:`M9 13v2`})]});function En({isOpen:e,openWidget:t,launcherText:n,primaryColor:r,posInline:i}){return e?null:(0,A.jsxs)(`button`,{type:`button`,onClick:()=>t({notifyChatInitiated:!0}),"aria-label":n,style:{position:`fixed`,...i,zIndex:999999,display:`flex`,alignItems:`center`,gap:`12px`,padding:`14px 24px`,border:`none`,borderRadius:`9999px`,background:r,color:`#fff`,fontSize:`16px`,fontWeight:`600`,fontFamily:`ui-sans-serif, system-ui, sans-serif`,cursor:`pointer`,boxShadow:`0 8px 24px rgba(0,0,0,0.18)`,transition:`transform 0.2s ease, box-shadow 0.2s ease`,outline:`none`,whiteSpace:`nowrap`},onMouseEnter:e=>{e.currentTarget.style.transform=`translateY(-2px)`,e.currentTarget.style.boxShadow=`0 12px 28px rgba(0,0,0,0.22)`},onMouseLeave:e=>{e.currentTarget.style.transform=`translateY(0)`,e.currentTarget.style.boxShadow=`0 8px 24px rgba(0,0,0,0.18)`},children:[(0,A.jsx)(`span`,{children:n}),(0,A.jsx)(_n,{color:`#fff`})]})}function Dn(e){if(!e||typeof e!=`string`)return`?`;let t=e.trim();if(!t)return`?`;let n=t.split(/\s+/).filter(Boolean);return n.length>=2?`${n[0][0]}${n[n.length-1][0]}`.toUpperCase():t.slice(0,2).toUpperCase()}function On(e){if(!e||typeof e!=`string`)return`?`;let t=e.split(`@`)[0]||``,n=t.replace(/[^a-z0-9]+/gi,` `).trim().split(/\s+/).filter(Boolean);return n.length>=2?`${n[0][0]}${n[1][0]}`.toUpperCase():t.length>=2?t.slice(0,2).toUpperCase():t.slice(0,1).toUpperCase()||`?`}function kn(e){return typeof e==`string`?e.trim():e&&typeof e==`object`&&typeof e.src==`string`?e.src.trim():``}function An(e){let[t,n]=(0,v.useState)(`loading`),r=kn(e);return(0,v.useEffect)(()=>{if(v.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 jn({logoUrl:e,brandName:t,agentName:n,fallbackAgentName:r,activeScreen:i,branding:a,isConversationEnded:o,closeWidget:s,isInitial:c,botLabel:l=`AI`,agentAvatarUrl:u=null,primaryColor:d=`#3B82F6`}){let{state:f,resolvedLogoUrl:p}=An(e),m=i===`agent`,h=Dn(n||r||a?.fallbackAgentName||`Agent`);return(0,A.jsxs)(`div`,{style:{display:`flex`,justifyContent:`space-between`,alignItems:`center`,padding:`16px 20px`,borderTopLeftRadius:`inherit`,borderTopRightRadius:`inherit`,border:`none`,transition:`all 0.3s ease`,background:c?`transparent`:`#fff`,color:c?`#fff`:`#111827`,boxShadow:c?`none`:`0 1px 0 rgba(0,0,0,0.05), 0 10px 24px rgba(0,0,0,0.04)`,borderBottom:c?`none`:`1px solid rgba(0,0,0,0.05)`},children:[(0,A.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`12px`},children:[m?(0,A.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0,overflow:`hidden`,display:`flex`,alignItems:`center`,justifyContent:`center`,background:c?`rgba(255,255,255,0.2)`:`#f3f4f6`,color:c?`#fff`:d,fontWeight:800,fontSize:`15px`,border:c?`2px solid rgba(255,255,255,0.35)`:`1px solid rgba(0,0,0,0.06)`},children:typeof u==`string`&&u.trim()?(0,A.jsx)(`img`,{src:u.trim(),alt:``,style:{width:`100%`,height:`100%`,objectFit:`cover`}}):(0,A.jsx)(`span`,{style:{lineHeight:1},children:h})}):(0,A.jsxs)(A.Fragment,{children:[f!==`loading`&&(f===`error`||!p&&!e?(0,A.jsx)(`div`,{className:`flowengage-logo-fallback`,style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0}}):v.isValidElement(e)?(0,A.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0,overflow:`hidden`,display:`flex`,alignItems:`center`,justifyContent:`center`,background:`#fff`},children:e}):typeof e==`function`?(0,A.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0,overflow:`hidden`,display:`flex`,alignItems:`center`,justifyContent:`center`,background:`#fff`},children:(0,A.jsx)(e,{})}):f===`wide`?(0,A.jsx)(`div`,{style:{height:`36px`,maxWidth:`88px`,flexShrink:0,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`12px`,padding:`4px 8px`,background:c?`rgba(255,255,255,0.15)`:`#f9fafb`,backdropFilter:c?`blur(12px)`:`none`,border:c?`none`:`1px solid rgba(0,0,0,0.05)`},children:(0,A.jsx)(`img`,{src:p,alt:`Logo`,style:{height:`100%`,width:`auto`,maxWidth:`100%`,objectFit:`contain`}})}):(0,A.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0,overflow:`hidden`,display:`flex`,alignItems:`center`,justifyContent:`center`,background:`#fff`},children:(0,A.jsx)(`img`,{src:p,alt:`Logo`,style:{width:`100%`,height:`100%`,objectFit:`contain`,padding:p.toLowerCase().includes(`.svg`)||p.startsWith(`data:image/svg`)?0:`2px`}})})),f===`loading`&&(0,A.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,background:`rgba(255,255,255,0.2)`,flexShrink:0}})]}),(0,A.jsxs)(`div`,{children:[(0,A.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`8px`},children:[(0,A.jsx)(`div`,{style:{fontSize:`16px`,fontWeight:700},children:i===`agent`?n||r||a.fallbackAgentName||`Agent`:t}),i!==`agent`&&(0,A.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`4px`,borderRadius:`6px`,background:`rgba(255,255,255,0.95)`,padding:`3px 6px`,fontSize:`10px`,fontWeight:800,letterSpacing:`0.5px`,color:`var(--flowengage-primary)`},children:[(0,A.jsx)(Tn,{size:11}),(0,A.jsx)(`span`,{children:l})]})]}),(0,A.jsxs)(`div`,{style:{fontSize:`13px`,opacity:.95,marginTop:`2px`},children:[i===`agent`?`Live support`:`Usually replies `,i!==`agent`&&(0,A.jsx)(`span`,{style:{color:`#10b981`,fontWeight:600},children:`instantly`})]})]})]}),(0,A.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`4px`},children:(0,A.jsx)(`button`,{style:{width:`36px`,height:`36px`,borderRadius:`9999px`,background:`transparent`,display:`flex`,alignItems:`center`,justifyContent:`center`,transition:`all 0.2s ease`,border:0,cursor:`pointer`,color:c?`#fff`:`#000`},onClick:s,"aria-label":`Close chat`,onMouseEnter:e=>{e.currentTarget.style.background=c?`rgba(255,255,255,0.1)`:`rgba(0,0,0,0.05)`},onMouseLeave:e=>{e.currentTarget.style.background=`transparent`},children:(0,A.jsx)(wn,{})})})]})}var Mn=(e=``)=>String(e).replace(/<[^>]+>/g,``).replace(/\s+/g,` `).trim(),Nn=(e=``)=>String(e).replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`),Pn=(e=``)=>{let t=String(e||``).trim();if(!t)return``;if(/<(p|br|ul|ol|li|strong|em|a)\b/i.test(t))return t;let n=t.replace(/\r\n/g,`
|
|
16
|
+
`,document.head.appendChild(e)};function tn(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 nn(e){!e||typeof document>`u`||(en(),rn(),e.classList.add(`fe-highlight-section`),e.scrollIntoView({behavior:`smooth`,block:`center`}))}function rn(){typeof document>`u`||document.querySelectorAll(`.fe-highlight-section`).forEach(e=>e.classList.remove(`fe-highlight-section`))}function an(e){if(typeof window>`u`)return e;try{let t=new URL(String(e).trim(),window.location.href);return!/^https?:$/i.test(t.protocol)||t.origin===window.location.origin?t.href:new URL(t.pathname+t.search+t.hash,window.location.origin).href}catch{return e}}async function on(e){if(typeof window>`u`)return!1;try{let t=new URL(String(e).trim(),window.location.href);return t.origin===window.location.origin?(await fetch(t.href,{method:`HEAD`,mode:`same-origin`,cache:`no-store`})).ok:!1}catch{return!1}}async function sn(e,{siteId:t,apiBaseUrl:n}){if(!e)return!1;if(!t||!n)return console.warn(`[FlowEngage] shouldProceedWithNavigation: missing siteId or apiBaseUrl`),!1;let r=String(n).replace(/\/$/,``),i=new URLSearchParams({siteId:String(t),url:String(e).trim()});try{let t=await(await fetch(`${r}/api/widget/navigate-allowed?${i.toString()}`)).json().catch(()=>({}));return t.success?t.allowed?!0:t.hasIndex===!1?on(e):!1:!1}catch(e){return console.warn(`[FlowEngage] navigate-allowed check failed:`,e?.message),!1}}async function cn(e){if(typeof window>`u`)return!1;try{let t=an(e),n=new URL(t,window.location.origin);if($t(`input:`,e,`→ normalized:`,t,`href:`,n.href),n.hash&&n.pathname===window.location.pathname){let e=n.hash.slice(1),t=document.getElementById(e);if(t)return $t(`branch: hash scroll (same path)`),t.scrollIntoView({behavior:`smooth`,block:`start`}),!0}if(n.pathname===window.location.pathname&&n.search===window.location.search&&!n.hash)return $t(`branch: already on page (no nav)`),!1;let r=n.pathname+n.search+n.hash,i=window.next?.router;if(i?.push)return $t(`branch: Next.js Pages router.push`,r),new Promise(e=>{let t=()=>{i.events?.off(`routeChangeComplete`,t),e(!0)};i.events?.on(`routeChangeComplete`,t),i.push(r),setTimeout(t,4e3)});let a=window.__NEXT_ROUTER__;return a?.push?($t(`branch: __NEXT_ROUTER__.push`,r),a.push(r),!0):($t(`branch: location.assign (full navigation)`,n.href),window.location.assign(n.href),!0)}catch(t){console.warn(`[FlowEngage] shadowNavigate error:`,t);try{window.location.href=an(e)}catch{window.location.href=e}return!0}}var ln=o((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.fragment`);function r(e,n,r){var i=null;if(r!==void 0&&(i=``+r),n.key!==void 0&&(i=``+n.key),`key`in n)for(var a in r={},n)a!==`key`&&(r[a]=n[a]);else r=n;return n=r.ref,{$$typeof:t,type:e,key:i,ref:n===void 0?null:n,props:r}}e.Fragment=n,e.jsx=r,e.jsxs=r})),A=o(((e,t)=>{t.exports=ln()}))(),un=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(),dn=(e=[])=>e.map(e=>({...e,message:un(e.message),isPending:!1,id:e.messageId||`${e.sender}-${e.timestamp||Date.now()}-${Math.random()}`})),fn=(e,t)=>e?typeof e==`string`?e:e.message||e.error||e.reason||t:t,pn=(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}:{}}},mn=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}},hn=(e=[],t=`Agent`)=>{for(let t of e)if(typeof t==`string`&&t.trim())return t.trim();return t};function gn({siteId:e,config:t,children:n,language:r=`en`}){let i=(0,v.useMemo)(()=>e?{...t||{},siteId:e}:t||null,[e,t]),a=(0,v.useMemo)(()=>hn([i?.widgetSettings?.branding?.fallbackAgentName,i?.widgetSettings?.branding?.headerName],`Agent`),[i]),[o,s]=(0,v.useState)(`booting`),[c,l]=(0,v.useState)(null),[u,d]=(0,v.useState)(null),[f,p]=(0,v.useState)(``),[m,h]=(0,v.useState)([]),[g,_]=(0,v.useState)(re().isOpen),[y,x]=(0,v.useState)(re().activeScreen),[ee,S]=(0,v.useState)(re().isHumanHandled),[se,ce]=(0,v.useState)(re().agentName),[de,fe]=(0,v.useState)(re().agentHeadshot),[C,w]=(0,v.useState)(ae()),[pe,me]=(0,v.useState)(!1),[he,ge]=(0,v.useState)(!1),[_e,T]=(0,v.useState)(`idle`),[ve,ye]=(0,v.useState)(!1),[be,xe]=(0,v.useState)(!1),[Se,Ce]=(0,v.useState)(``),[we,Te]=(0,v.useState)(!1),[Ee,De]=(0,v.useState)(!1),[E,Oe]=(0,v.useState)(null),[ke,Ae]=(0,v.useState)(null),[je,Me]=(0,v.useState)(`idle`),[D,Ne]=(0,v.useState)(null),[Pe,Fe]=(0,v.useState)(!1),[Ie,Le]=(0,v.useState)(``),Re=(0,v.useRef)(null),ze=(0,v.useRef)(null),O=(0,v.useRef)(``),Be=(0,v.useRef)(null),Ve=(0,v.useRef)(null),He=(0,v.useRef)(null),Ue=(0,v.useRef)(null),We=(0,v.useRef)(null),Ge=(0,v.useRef)([]),Ke=(0,v.useRef)(null),qe=(0,v.useRef)(null),Je=(0,v.useRef)(!1),Ye=(0,v.useRef)(!1),Xe=(0,v.useRef)(``),Ze=(0,v.useRef)([]),Qe=(0,v.useRef)(!1),$e=(0,v.useRef)({notifyRouteChange:()=>{},cleanup:()=>{}}),et=(0,v.useMemo)(()=>{let e=u?.widgetSettings?.call?.maxDurationSeconds??i?.widgetSettings?.call?.maxDurationSeconds??i?.callMaxDurationSeconds,t=Number(e);return Number.isFinite(t)&&t>0?t:30},[i,u]);(0,v.useEffect)(()=>{Be.current=E},[E]);let tt=()=>{Le(``)},nt=e=>{let t=typeof e==`string`?e.trim().toLowerCase():``;return w(t),oe(t),t},rt=()=>{Ve.current&&=(Ve.current.close(),null),He.current&&=(He.current.getTracks().forEach(e=>e.stop()),null),Ue.current&&=(Ue.current.srcObject=null,Ue.current.remove(),null),We.current=null,Ge.current=[],Ke.current=null,qe.current=null,Je.current=!1,Fe(!1),Oe(null),Ae(null),Me(`idle`),Ne(null)},it=(e=new Date().toISOString())=>{let t=Re.current,n=Ke.current||We.current?.callId;if(!t?.connected||!n||Je.current){console.log(`[FlowEngageProvider] skipping call:connected emit`,{callId:n,chatId:O.current,socketConnected:!!t?.connected,alreadyReported:Je.current});return}console.log(`[FlowEngageProvider] emitting call:connected`,{callId:n,chatId:O.current,connectedAt:e}),Je.current=!0,t.emit(`call:connected`,{callId:n,chatId:O.current,connectedAt:e})},at=(e={})=>{if(!e.callId)return;let t=qe.current===e.callId,n=Ke.current===e.callId,r=Be.current?.callId===e.callId;if(!(!t&&!n&&!r)){if(console.log(`[FlowEngageProvider] syncing accepted call state`,{callId:e.callId,chatId:e.chatId||O.current,isAcceptingHere:t,isAlreadyActive:n,isIncomingHere:r}),Oe(null),t||n){Ke.current=e.callId,Ae(e.callId),Me(e=>e===`connected`?e:`connecting`),_(!0);return}Me(`idle`)}},ot=(e={})=>{if(!e.callId)return;let t=qe.current===e.callId,n=Ke.current===e.callId,r=Be.current?.callId===e.callId;if(!(!t&&!n&&!r)){if(console.log(`[FlowEngageProvider] syncing ended incoming call state`,{callId:e.callId,chatId:e.chatId||O.current,isAcceptingHere:t,isAlreadyActive:n,isIncomingHere:r,reason:e.reason||e.status||null}),n){rt();return}qe.current=null,We.current=null,Ge.current=[],Oe(null),Me(`idle`)}},st=async(e={})=>{let t=Ve.current,n=Re.current,r=e.sdpOffer||e.offer?.sdp;if(!t||!n?.connected||!r||!e.callId){console.log(`[FlowEngageProvider] deferring remote offer until peer/socket ready`,{callId:e.callId,chatId:O.current,hasPeerConnection:!!t,socketConnected:!!n?.connected,hasOffer:!!r}),We.current=e;return}if(console.log(`[FlowEngageProvider] applying remote offer`,{callId:e.callId,chatId:O.current,offerLength:r.length,signalingState:t.signalingState}),await t.setRemoteDescription(new RTCSessionDescription({type:`offer`,sdp:r})),Ge.current.length>0){console.log(`[FlowEngageProvider] flushing queued agent ICE candidates after remote offer`,{callId:e.callId,chatId:O.current,queuedCount:Ge.current.length});for(let e of Ge.current)await t.addIceCandidate(new RTCIceCandidate(e));Ge.current=[]}let i=await t.createAnswer();await t.setLocalDescription(i),console.log(`[FlowEngageProvider] created local answer`,{callId:e.callId,chatId:O.current,answerLength:i.sdp?.length||0,signalingState:t.signalingState}),n.emit(`call:answer`,{callId:e.callId,sdpAnswer:i.sdp,chatId:O.current})};(0,v.useEffect)(()=>{ie({isOpen:g,activeScreen:y,isHumanHandled:ee,agentName:se,agentHeadshot:de})},[g,y,ee,se,de]),(0,v.useEffect)(()=>{let e=!0;return(async()=>{try{console.log(`[FlowEngageProvider] boot start`,{resolvedConfig:i,language:r});let t=b(i);console.log(`[FlowEngageProvider] config validated`,t);let n=await le(t);if(!e)return;let o=ne();O.current=o;let c=ue({apiBaseUrl:t.apiBaseUrl,userId:n.userId,siteId:t.siteId});ze.current=c,d({...n,apiBaseUrl:t.apiBaseUrl}),p(o),console.log(`[FlowEngageProvider] bootstrap resolved`,{bootstrapData:n,resolvedChatId:o});let l=Jt({apiBaseUrl:t.apiBaseUrl,userId:n.userId,chatId:o,siteId:t.siteId});Re.current=l,l.on(`connect`,()=>{console.log(`[FlowEngageProvider] socket connected`),T(`connected`)}),l.on(`disconnect`,()=>{console.log(`[FlowEngageProvider] socket disconnected`),T(`disconnected`)}),l.on(`aiTyping`,()=>{console.log(`[FlowEngageProvider] received aiTyping`,{chatId:O.current}),ge(!0)}),l.on(`ai:typing`,()=>{console.log(`[FlowEngageProvider] received ai:typing`,{chatId:O.current}),ge(!0)}),l.on(`messageReceived`,e=>{let t=e.message||e,n={...t,message:un(t.message)};ge(!1),me(!1),h(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&&h(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:un(t.message)};ge(!1),(n.sender===`agent`||n.agent_name||n.sender===`ai`||n.sender===`bot`)&&me(!1),h(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)&&(S(!0),x(`agent`),ce(hn([n.agent_name,n.agentName,n.metadata?.agentName],a)),n.sender_headshot&&fe(n.sender_headshot),_(!0))}),l.on(`agent:joined`,e=>{let t=hn([e.agent?.name,e.agentName],a);S(!0),x(`agent`),ce(t),fe(e.agent?.headshot||null),_(!0),h(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=hn([e.agent?.name,e.agentName],a);S(!0),x(`agent`),ce(t),fe(e.agent?.headshot||null),_(!0),h(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`,(e={})=>{let t=hn([e.agent?.name,e.agentName,se],a);S(!1),x(`ai`),h(e=>[...e,{id:`agent-left-${Date.now()}`,sender:`system`,message:`${t} has left the chat.`,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`agentLeft`,(e={})=>{let t=hn([e.agent?.name,e.agentName,se],a);S(!1),x(`ai`),h(e=>[...e,{id:`agent-left-${Date.now()}`,sender:`system`,message:`${t} has left the chat.`,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`conversationEnded`,e=>{De(!0);let t=e?.message||`This conversation has ended. Thank you for reaching out!`;h(e=>[...e,{id:`conversation-ended-${Date.now()}`,sender:`system`,message:t,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`chat:history_update`,e=>{h(dn(e.chat_history||[]))}),l.on(`typing:start`,e=>{console.log(`[FlowEngageProvider] received typing:start`,{chatId:e?.chatId||O.current,sender:e?.sender}),e.sender===`agent`&&me(!0)}),l.on(`typing:stop`,e=>{console.log(`[FlowEngageProvider] received typing:stop`,{chatId:e?.chatId||O.current,sender:e?.sender}),e.sender===`agent`&&me(!1)}),l.on(`call:incoming`,(e={})=>{let t=hn([e.agentName,e.ownerName,e.agent?.name,se],a);console.log(`[FlowEngageProvider] received call:incoming`,{callId:e.callId,chatId:O.current,agentName:t}),tt(),Je.current=!1,Oe({callId:e.callId,from:e.from||`owner`,agentId:e.agentId||null,agentName:t}),ce(e=>hn([t,e],a)),Me(`incoming`),Ne(null),_(!0)}),l.on(`call:offer`,async(e={})=>{console.log(`[FlowEngageProvider] received call:offer`,{callId:e.callId,chatId:e.chatId||O.current,offerLength:(e.sdpOffer||e.offer?.sdp||``).length}),We.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||O.current,hasPeerConnection:!!Ve.current,hasCandidate:!!e.candidate});return}try{let t=pn(e);if(!t){console.warn(`[FlowEngageProvider] ignoring invalid ICE candidate payload`,e);return}if(console.log(`[FlowEngageProvider] adding agent ICE candidate`,{callId:e.callId,chatId:e.chatId||O.current,candidate:mn(t),hasRemoteDescription:!!Ve.current?.remoteDescription}),!Ve.current||!Ve.current.remoteDescription){console.log(`[FlowEngageProvider] queueing agent ICE candidate until peer/remote description is ready`,{callId:e.callId,chatId:e.chatId||O.current,queueSize:Ge.current.length+1}),Ge.current.push(t);return}await Ve.current.addIceCandidate(new RTCIceCandidate(t))}catch(e){console.error(`[FlowEngageProvider] failed to add ICE candidate`,e)}}),l.on(`call:ended`,()=>{tt(),rt()}),l.on(`call:accepted`,(e={})=>{console.log(`[FlowEngageProvider] received call:accepted`,{callId:e.callId,chatId:e.chatId||O.current}),at(e)}),l.on(`call:accepted_by_other`,(e={})=>{console.log(`[FlowEngageProvider] received call:accepted_by_other`,{callId:e.callId,chatId:e.chatId||O.current}),at(e)}),l.on(`call:rejected`,(e={})=>{console.log(`[FlowEngageProvider] received call:rejected`,{callId:e.callId,chatId:e.chatId||O.current,reason:e.reason}),ot(e)}),l.on(`call:missed`,(e={})=>{console.log(`[FlowEngageProvider] received call:missed`,{callId:e.callId,chatId:e.chatId||O.current,reason:e.reason}),ot(e)}),l.on(`call:failed`,(e={})=>{console.log(`[FlowEngageProvider] received call:failed`,{callId:e.callId,chatId:e.chatId||O.current,reason:e.reason}),ot(e)}),l.on(`call:connected`,(e={})=>{if(!e.callId)return;let t=qe.current===e.callId,n=Ke.current===e.callId,r=Be.current?.callId===e.callId;if(console.log(`[FlowEngageProvider] received call:connected`,{callId:e.callId,chatId:e.chatId||O.current,connectedAt:e.connectedAt,status:e.status,isAcceptingHere:t,isAlreadyActive:n,isIncomingHere:r}),!t&&!n){r&&(Oe(null),Me(`idle`));return}Je.current=!0,qe.current=null,Ke.current=e.callId,Ae(e.callId),Oe(null),Me(`connected`),Ne(e.connectedAt||new Date().toISOString()),_(!0)}),l.on(`call:unavailable`,(e={})=>{rt(),Le(fn(e,`This visitor is not available for a call right now.`)),_(!0)}),l.on(`call:error`,(e={})=>{rt(),Le(fn(e,`We couldn't connect the call right now.`)),_(!0)}),l.on(`visitor:navigate`,async({url:e,section:n,highlight:r}={})=>{if(e){if(console.log(`[FlowEngageProvider] visitor:navigate`,{url:e,section:n,highlight:r}),!await sn(e,{siteId:t.siteId,apiBaseUrl:t.apiBaseUrl})){console.warn(`[FlowEngageProvider] visitor:navigate blocked (not indexed)`,e);return}cn(e).then(e=>{let t=n||r;t&&setTimeout(()=>{let e=tn(null,t);e&&nn(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=tn(e||null,t||null);n&&nn(n)}),l.on(`visitor:clear_highlight`,()=>{rn()}),$e.current=Yt({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||(h(dn(u.chat_history||[])),S(!!u.is_human_handled),x(u.is_human_handled?`agent`:y),await new Promise(e=>setTimeout(e,500)),!e))return;s(`ready`),console.log(`[FlowEngageProvider] status ready`)}catch(t){if(!e)return;console.error(`[FlowEngageProvider] boot failed`,t),l(t),s(`error`)}})(),()=>{e=!1,$e.current?.cleanup?.(),rt(),Re.current?.disconnect()}},[i,r]),(0,v.useEffect)(()=>()=>{if(we&&!Qe.current&&Ze.current.length>0){let e=O.current,t=Ze.current,n=ze.current,r=u?.apiBaseUrl||``,i=u?.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(()=>{}),Qe.current=!0)}},[we,u]),(0,v.useEffect)(()=>{if(!ze.current||!f||o!==`ready`||ee)return;let e=window.setInterval(async()=>{try{let e=await ze.current.checkHumanHandled(f);S(!!e.is_human_handled),e.is_human_handled&&(x(`agent`),e.agent_info?.name&&ce(e.agent_info.name),e.agent_info?.headshot&&fe(e.agent_info.headshot))}catch{}},1e4);return()=>window.clearInterval(e)},[f,o,ee]);let ct=async()=>{if(!(!E?.callId||!ze.current||!Re.current||!f)){tt(),qe.current=E.callId,console.log(`[FlowEngageProvider] acceptCall started`,{callId:E?.callId,chatId:f,socketConnected:!!Re.current?.connected,hasPendingOffer:!!We.current});try{let e=await navigator.mediaDevices.getUserMedia({audio:!0});console.log(`[FlowEngageProvider] microphone stream acquired`,{callId:E.callId,chatId:f,trackCount:e.getTracks().length}),He.current=e;let t=new RTCPeerConnection({iceServers:[{urls:`stun:stun.l.google.com:19302`}]});Ve.current=t,t.onconnectionstatechange=()=>{let e=t.connectionState;if(console.log(`[FlowEngageProvider] peer connection state changed`,{callId:E.callId,chatId:f,connectionState:e,iceConnectionState:t.iceConnectionState,signalingState:t.signalingState}),e===`connected`){let e=new Date().toISOString();Me(`connected`),Ne(t=>t||e),it(e);return}e===`connecting`&&Me(e=>e===`connected`?e:`connecting`)},t.oniceconnectionstatechange=()=>{let e=t.iceConnectionState;if(console.log(`[FlowEngageProvider] ICE connection state changed`,{callId:E.callId,chatId:f,iceConnectionState:e,connectionState:t.connectionState,signalingState:t.signalingState}),e===`connected`||e===`completed`){let e=new Date().toISOString();Me(`connected`),Ne(t=>t||e),it(e);return}(e===`checking`||e===`new`)&&Me(e=>e===`connected`?e:`connecting`)},e.getTracks().forEach(n=>{t.addTrack(n,e)}),t.onicecandidate=e=>{if(!e.candidate||!Re.current?.connected){console.log(`[FlowEngageProvider] local ICE candidate skipped`,{callId:E.callId,chatId:f,hasCandidate:!!e.candidate,socketConnected:!!Re.current?.connected});return}console.log(`[FlowEngageProvider] emitting local ICE candidate`,{callId:E.callId,chatId:f,candidate:mn(e.candidate)}),Re.current.emit(`call:ice-candidate`,{callId:E.callId,candidate:e.candidate,chatId:f,from:`customer`})},t.ontrack=e=>{if(console.log(`[FlowEngageProvider] remote audio track received`,{callId:E.callId,chatId:f,streamCount:e.streams?.length||0}),!Ue.current){let e=document.createElement(`audio`);e.id=`flowengage-remote-audio`,e.autoplay=!0,Ue.current=e,document.body.appendChild(e)}Ue.current.srcObject=e.streams[0]};let n=We.current;n&&(console.log(`[FlowEngageProvider] found pending remote offer during accept`,{callId:n.callId||E.callId,chatId:f}),await st({...n,callId:n.callId||E.callId})),await ze.current.acceptCall(E.callId,f),console.log(`[FlowEngageProvider] acceptCall API succeeded`,{callId:E.callId,chatId:f}),Ke.current=E.callId,Ae(E.callId),Me(`connecting`),Oe(null),_(!0)}catch(e){if(console.error(`[FlowEngageProvider] acceptCall failed`,e),qe.current=null,rt(),e?.status===404||e?.status===409||e?.status===422){Le(fn(e,`This visitor call is no longer available.`));return}if(e?.name===`NotAllowedError`||e?.name===`PermissionDeniedError`){try{await ze.current.rejectCall(E.callId,f)}catch(e){console.error(`[FlowEngageProvider] failed to reject call after microphone denial`,e)}Le(`Microphone access was denied. Please allow microphone access to accept the call.`);return}Le(`We couldn't connect the call right now. Please try again.`)}}},lt=async()=>{if(!E?.callId||!ze.current||!f){rt();return}tt();try{await ze.current.rejectCall(E.callId,f)}catch(e){console.error(`[FlowEngageProvider] rejectCall failed`,e),Le(fn(e,`We couldn't decline the call cleanly.`))}finally{rt()}},ut=async()=>{if(!ke||!ze.current||!f){rt();return}tt();try{await ze.current.endWebRTCCall(ke,f)}catch(e){console.error(`[FlowEngageProvider] endWebRTCCall failed`,e),Le(fn(e,`The call ended locally, but the server could not be updated.`))}finally{rt()}},dt=()=>{let e=He.current?.getAudioTracks?.()||[],t=Ve.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=!Pe;n.forEach(e=>{e.enabled=!r}),console.log(`[FlowEngageProvider] toggled local mute`,{nextMuted:r,trackCount:n.length}),Fe(r)},ft=async(e={})=>{let t=e.notifyChatInitiated===!0;if(_(!0),!(!t||!ze.current||!f||typeof window>`u`)){try{await ze.current.trackVisitor({chatId:f,currentPagePath:window.location.pathname||`/`})}catch{}try{await ze.current.updateChatStatus(f,`open`)}catch{}}},pt=async e=>{let t=nt(e);if(!t||!ze.current||!O.current)return t;try{await ze.current.trackVisitor({chatId:O.current,currentPagePath:typeof window<`u`&&window.location.pathname||`/`,email:t})}catch(e){console.error(`[FlowEngageProvider] failed to persist visitor email`,e)}return t},mt=()=>{if(!f||!Re.current?.connected||Ye.current){console.log(`[FlowEngageProvider] skipped typing:start emit`,{chatId:f,socketConnected:!!Re.current?.connected,alreadyTyping:Ye.current});return}Ye.current=!0,console.log(`[FlowEngageProvider] emitting typing:start`,{chatId:f,sender:`user`}),Re.current.emit(`typing:start`,{chatId:f,sender:`user`})},ht=()=>{if(f&&Re.current?.connected&&Xe.current!==``&&(console.log(`[FlowEngageProvider] clearing typing draft`,{chatId:f,sender:`user`}),Re.current.emit(`typing:update`,{chatId:f,sender:`user`,text:``}),Xe.current=``),!f||!Re.current?.connected||!Ye.current){console.log(`[FlowEngageProvider] skipped typing:stop emit`,{chatId:f,socketConnected:!!Re.current?.connected,wasTyping:Ye.current});return}Ye.current=!1,console.log(`[FlowEngageProvider] emitting typing:stop`,{chatId:f,sender:`user`}),Re.current.emit(`typing:stop`,{chatId:f,sender:`user`})},gt=(e=``)=>{let t=typeof e==`string`?e:``;if(!f||!Re.current?.connected){console.log(`[FlowEngageProvider] skipped typing:update emit`,{chatId:f,socketConnected:!!Re.current?.connected,textLength:t.length});return}Xe.current!==t&&(Xe.current=t,console.log(`[FlowEngageProvider] emitting typing:update`,{chatId:f,sender:`user`,textLength:t.length}),Re.current.emit(`typing:update`,{chatId:f,sender:`user`,text:t}))},_t=async(e,t=``,n=null)=>{if(!e.trim()||!ze.current||!f||o!==`ready`||Ee)return;ht();let i=`pending-user-${Date.now()}`,a={id:i,sender:`user`,message:e,timestamp:new Date().toISOString(),isPending:!0,...n||{}};if(h(e=>[...e,a]),ee&&Re.current?.connected){Re.current.emit(`customer:message`,{chatId:f,content:e,sender:`user`,email:C||void 0,...n||{}});return}ye(!0);try{let i=await ze.current.sendAiMessage(f,e,r,t,{...n||{},...C?{email:C}:{}});h(dn(i.chat_history||[])),S(!!i.is_human_handled),x(i.is_human_handled?`agent`:`ai`),ge(!1),await ze.current.updateChatStatus(f,`messageSent`)}catch(e){h(e=>e.filter(e=>e.id!==i)),ge(!1),e.status===429?(xe(!0),Ce(e.message),window.setTimeout(()=>{xe(!1),Ce(``)},te)):l(e)}finally{ye(!1)}},vt=async e=>{if(!(!ze.current||!f)){try{let t=e?`voice`:`text`;await ze.current.setChatMode(f,t)}catch(e){console.error(`[FlowEngageProvider] setVoiceMode failed`,e)}Te(e),e&&(Qe.current=!1)}},yt=async e=>{if(!Qe.current){if(Qe.current=!0,!ze.current||!f||!e?.length){Te(!1);return}try{let t=await ze.current.syncVoice(f,e);t?.chat_history&&h(dn(t.chat_history))}catch{}finally{Te(!1)}}},bt=async()=>{if(!(!ze.current||!f)){we&&!Qe.current&&Ze.current.length>0&&await yt(Ze.current);try{await ze.current.endConversation(f)}catch{try{await ze.current.updateChatStatus(f,`ended`)}catch{}}De(!0),h(e=>[...e,{id:`conversation-ended-${Date.now()}`,sender:`system`,message:`This conversation has ended. Thank you for reaching out!`,timestamp:new Date().toISOString(),isPending:!1}])}};(0,v.useEffect)(()=>{if(je!==`connected`||!ke||!f||!D||!et)return;let e=new Date(D).getTime(),t=Number.isFinite(e)?Date.now()-e:0,n=Math.max(0,et*1e3-t),r=window.setTimeout(()=>{Le(`The call ended because it reached the time limit.`),ut()},n);return()=>window.clearTimeout(r)},[ke,D,je,f,ut,et]),(0,v.useEffect)(()=>{let e=()=>{let e=O.current,t=ze.current;if(!t||!e)return;if(Ke.current){t.beaconEndWebRTCCall(Ke.current,e);return}let n=qe.current||Be.current?.callId;n&&t.beaconCustomerUnavailable(n,e)};return window.addEventListener(`pagehide`,e),window.addEventListener(`beforeunload`,e),()=>{window.removeEventListener(`pagehide`,e),window.removeEventListener(`beforeunload`,e)}},[]);let xt=(0,v.useMemo)(()=>({status:o,error:c,runtimeConfig:u,resolvedConfig:i,chatId:f,chatHistory:m,isOpen:g,activeScreen:y,isHumanHandled:ee,agentName:se,agentHeadshot:de,visitorEmail:C,isAgentTyping:pe,isAiTyping:he,connectionStatus:_e,isLoading:ve,isVoiceMode:we,isRateLimited:be,rateLimitMessage:Se,isConversationEnded:Ee,incomingCall:E,activeCallId:ke,callConnectionState:je,callConnectedAt:D,isCallMuted:Pe,webRTCError:Ie,language:r,historyRef:Ze,hasSyncedRef:Qe,dismissCallError:tt,captureVisitorEmail:pt,startTyping:mt,stopTyping:ht,updateTypingDraft:gt,notifyRouteChange:()=>$e.current?.notifyRouteChange?.(),openWidget:ft,closeWidget:()=>_(!1),toggleWidget:()=>{if(g){_(!1);return}ft({notifyChatInitiated:!0})},sendMessage:_t,setVoiceMode:vt,onMessageSync:yt,endConversation:bt,acceptCall:ct,rejectCall:lt,endWebRTCCall:ut,toggleCallMute:dt,startTyping:mt,stopTyping:ht,updateTypingDraft:gt}),[o,c,u,i,f,m,g,y,ee,se,de,C,pe,he,_e,ve,we,be,Se,Ee,E,ke,je,D,Pe,Ie,r,pt,mt,ht,gt,ct,lt,ut,dt,ft,_t,vt,yt,bt,tt]);return(0,A.jsx)(Xt.Provider,{value:xt,children:n})}var _n=({color:e=`#3888FF`})=>(0,A.jsxs)(`svg`,{width:`40`,height:`40`,viewBox:`0 0 40 40`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,A.jsx)(`rect`,{width:`40`,height:`40`,rx:`20`,fill:e}),(0,A.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,A.jsx)(`path`,{d:`M18 32L18 26L24 26L18 32Z`,fill:`#ECF0F0`}),(0,A.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`})]}),vn=()=>(0,A.jsx)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:(0,A.jsx)(`path`,{d:`M2.01 21L23 12 2.01 3 2 10l15 2-15 2z`,fill:`currentColor`})}),yn=({size:e=18,color:t=`currentColor`})=>(0,A.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,A.jsx)(`path`,{d:`M12 1a4 4 0 014 4v6a4 4 0 01-8 0V5a4 4 0 014-4z`,fill:t}),(0,A.jsx)(`path`,{d:`M19 10a7 7 0 01-14 0M12 19v4M8 23h8`,stroke:t,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})]}),bn=({size:e=20})=>(0,A.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,A.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,A.jsx)(`line`,{x1:`23`,y1:`1`,x2:`1`,y2:`23`})]}),xn=()=>(0,A.jsxs)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,A.jsx)(`line`,{x1:`12`,y1:`19`,x2:`12`,y2:`5`}),(0,A.jsx)(`polyline`,{points:`5 12 12 5 19 12`})]}),Sn=()=>(0,A.jsxs)(`svg`,{width:`14`,height:`14`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,A.jsx)(`polyline`,{points:`9 17 4 12 9 7`}),(0,A.jsx)(`path`,{d:`M20 18v-2a4 4 0 00-4-4H4`})]}),Cn=()=>(0,A.jsx)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,A.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`})}),wn=({className:e=``})=>(0,A.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,A.jsx)(`circle`,{cx:`12`,cy:`12`,r:`10`}),(0,A.jsx)(`line`,{x1:`12`,y1:`8`,x2:`12`,y2:`12`}),(0,A.jsx)(`line`,{x1:`12`,y1:`16`,x2:`12.01`,y2:`16`})]}),Tn=({size:e=18,strokeWidth:t=2.5})=>(0,A.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:t,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,A.jsx)(`line`,{x1:`18`,y1:`6`,x2:`6`,y2:`18`}),(0,A.jsx)(`line`,{x1:`6`,y1:`6`,x2:`18`,y2:`18`})]}),En=({size:e=14})=>(0,A.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,A.jsx)(`path`,{d:`M12 8V4H8`}),(0,A.jsx)(`rect`,{width:`16`,height:`12`,x:`4`,y:`8`,rx:`2`}),(0,A.jsx)(`path`,{d:`M2 14h2`}),(0,A.jsx)(`path`,{d:`M20 14h2`}),(0,A.jsx)(`path`,{d:`M15 13v2`}),(0,A.jsx)(`path`,{d:`M9 13v2`})]});function Dn({isOpen:e,openWidget:t,launcherText:n,primaryColor:r,posInline:i}){let[a,o]=(0,v.useState)(!1);return(0,v.useEffect)(()=>{if(typeof window>`u`)return;let e=window.matchMedia(`(max-width: 640px)`),t=e=>{o(e.matches)};return o(e.matches),typeof e.addEventListener==`function`?(e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)):(e.addListener(t),()=>e.removeListener(t))},[]),e?null:(0,A.jsxs)(`button`,{type:`button`,onClick:()=>t({notifyChatInitiated:!0}),"aria-label":n,style:{position:`fixed`,...i,zIndex:999999,display:`flex`,alignItems:`center`,justifyContent:`center`,gap:a?`0`:`14px`,width:a?`60px`:`auto`,minWidth:a?`60px`:`unset`,height:a?`60px`:`auto`,padding:a?`0`:`14px 24px`,border:`none`,borderRadius:`9999px`,background:r,color:`#fff`,fontSize:`16px`,fontWeight:`600`,fontFamily:`ui-sans-serif, system-ui, sans-serif`,cursor:`pointer`,boxShadow:`0 8px 24px rgba(0,0,0,0.18)`,transition:`transform 0.2s ease, box-shadow 0.2s ease`,outline:`none`,whiteSpace:`nowrap`},onMouseEnter:e=>{e.currentTarget.style.transform=`translateY(-2px)`,e.currentTarget.style.boxShadow=`0 12px 28px rgba(0,0,0,0.22)`},onMouseLeave:e=>{e.currentTarget.style.transform=`translateY(0)`,e.currentTarget.style.boxShadow=`0 8px 24px rgba(0,0,0,0.18)`},children:[a?null:(0,A.jsx)(`span`,{children:n}),a?(0,A.jsx)(_n,{color:`#fff`}):(0,A.jsx)(`span`,{style:{width:`42px`,height:`42px`,borderRadius:`9999px`,background:`#fff`,color:r,display:`inline-flex`,alignItems:`center`,justifyContent:`center`,flexShrink:0},children:(0,A.jsx)(vn,{})})]})}function On(e){if(!e||typeof e!=`string`)return`?`;let t=e.trim();if(!t)return`?`;let n=t.split(/\s+/).filter(Boolean);return n.length>=2?`${n[0][0]}${n[n.length-1][0]}`.toUpperCase():t.slice(0,2).toUpperCase()}function kn(e){return typeof e==`string`?e.trim():e&&typeof e==`object`&&typeof e.src==`string`?e.src.trim():``}function An(e){let[t,n]=(0,v.useState)(`loading`),r=kn(e);return(0,v.useEffect)(()=>{if(v.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 jn({logoUrl:e,brandName:t,agentName:n,fallbackAgentName:r,activeScreen:i,branding:a,isConversationEnded:o,closeWidget:s,isInitial:c,botLabel:l=`AI`,agentAvatarUrl:u=null,primaryColor:d=`#3B82F6`}){let{state:f,resolvedLogoUrl:p}=An(e),m=i===`agent`,h=On(n||r||a?.fallbackAgentName||`Agent`);return(0,A.jsxs)(`div`,{style:{display:`flex`,justifyContent:`space-between`,alignItems:`center`,padding:`16px 20px`,borderTopLeftRadius:`inherit`,borderTopRightRadius:`inherit`,border:`none`,transition:`all 0.3s ease`,background:c?`transparent`:`#fff`,color:c?`#fff`:`#111827`,boxShadow:c?`none`:`0 1px 0 rgba(0,0,0,0.05), 0 10px 24px rgba(0,0,0,0.04)`,borderBottom:c?`none`:`1px solid rgba(0,0,0,0.05)`},children:[(0,A.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`12px`},children:[m?(0,A.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0,overflow:`hidden`,display:`flex`,alignItems:`center`,justifyContent:`center`,background:c?`rgba(255,255,255,0.2)`:`#f3f4f6`,color:c?`#fff`:d,fontWeight:800,fontSize:`15px`,border:c?`2px solid rgba(255,255,255,0.35)`:`1px solid rgba(0,0,0,0.06)`},children:typeof u==`string`&&u.trim()?(0,A.jsx)(`img`,{src:u.trim(),alt:``,style:{width:`100%`,height:`100%`,objectFit:`cover`}}):(0,A.jsx)(`span`,{style:{lineHeight:1},children:h})}):(0,A.jsxs)(A.Fragment,{children:[f!==`loading`&&(f===`error`||!p&&!e?(0,A.jsx)(`div`,{className:`flowengage-logo-fallback`,style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0}}):v.isValidElement(e)?(0,A.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0,overflow:`hidden`,display:`flex`,alignItems:`center`,justifyContent:`center`,background:`#fff`},children:e}):typeof e==`function`?(0,A.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0,overflow:`hidden`,display:`flex`,alignItems:`center`,justifyContent:`center`,background:`#fff`},children:(0,A.jsx)(e,{})}):f===`wide`?(0,A.jsx)(`div`,{style:{height:`36px`,maxWidth:`88px`,flexShrink:0,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`12px`,padding:`4px 8px`,background:c?`rgba(255,255,255,0.15)`:`#f9fafb`,backdropFilter:c?`blur(12px)`:`none`,border:c?`none`:`1px solid rgba(0,0,0,0.05)`},children:(0,A.jsx)(`img`,{src:p,alt:`Logo`,style:{height:`100%`,width:`auto`,maxWidth:`100%`,objectFit:`contain`}})}):(0,A.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0,overflow:`hidden`,display:`flex`,alignItems:`center`,justifyContent:`center`,background:`#fff`},children:(0,A.jsx)(`img`,{src:p,alt:`Logo`,style:{width:`100%`,height:`100%`,objectFit:`contain`,padding:p.toLowerCase().includes(`.svg`)||p.startsWith(`data:image/svg`)?0:`2px`}})})),f===`loading`&&(0,A.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,background:`rgba(255,255,255,0.2)`,flexShrink:0}})]}),(0,A.jsxs)(`div`,{children:[(0,A.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`8px`},children:[(0,A.jsx)(`div`,{style:{fontSize:`16px`,fontWeight:700},children:i===`agent`?n||r||a.fallbackAgentName||`Agent`:t}),i!==`agent`&&(0,A.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`4px`,borderRadius:`6px`,background:`rgba(255,255,255,0.95)`,padding:`3px 6px`,fontSize:`10px`,fontWeight:800,letterSpacing:`0.5px`,color:`var(--flowengage-primary)`},children:[(0,A.jsx)(En,{size:11}),(0,A.jsx)(`span`,{children:l})]})]}),(0,A.jsxs)(`div`,{style:{fontSize:`13px`,opacity:.95,marginTop:`2px`},children:[i===`agent`?`Live support`:`Usually replies `,i!==`agent`&&(0,A.jsx)(`span`,{style:{color:`#10b981`,fontWeight:600},children:`instantly`})]})]})]}),(0,A.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`4px`},children:(0,A.jsx)(`button`,{style:{width:`36px`,height:`36px`,borderRadius:`9999px`,background:`transparent`,display:`flex`,alignItems:`center`,justifyContent:`center`,transition:`all 0.2s ease`,border:0,cursor:`pointer`,color:c?`#fff`:`#000`},onClick:s,"aria-label":`Close chat`,onMouseEnter:e=>{e.currentTarget.style.background=c?`rgba(255,255,255,0.1)`:`rgba(0,0,0,0.05)`},onMouseLeave:e=>{e.currentTarget.style.background=`transparent`},children:(0,A.jsx)(Tn,{})})})]})}var Mn=(e=``)=>String(e).replace(/<[^>]+>/g,``).replace(/\s+/g,` `).trim(),Nn=(e=``)=>String(e).replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`),Pn=(e=``)=>{let t=String(e||``).trim();if(!t)return``;if(/<(p|br|ul|ol|li|strong|em|a)\b/i.test(t))return t;let n=t.replace(/\r\n/g,`
|
|
17
17
|
`).replace(/\n{3,}/g,`
|
|
18
18
|
|
|
19
19
|
`).split(/\n\s*\n/).map(e=>e.trim()).filter(Boolean),r=e=>Nn(e).replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,`<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>`).replace(/\*\*([^*]+)\*\*/g,`<strong>$1</strong>`).replace(/\*([^*\n]+)\*/g,`<em>$1</em>`);return n.map(e=>{let t=e.split(`
|
|
20
|
-
`).map(e=>e.trim()).filter(Boolean),n=t.filter(e=>/^[-*]\s+/.test(e));if(n.length>=2&&n.length===t.length)return`<ul>${n.map(e=>`<li>${r(e.replace(/^[-*]\s+/,``))}</li>`).join(``)}</ul>`;let i=e.split(/\s+(?=[-*]\s+\*\*?)/).map(e=>e.trim()).filter(Boolean);return i.length>=2&&i.every(e=>/^[-*]\s+/.test(e))?`<ul>${i.map(e=>`<li>${r(e.replace(/^[-*]\s+/,``))}</li>`).join(``)}</ul>`:`<p>${r(e).replace(/\n/g,`<br />`)}</p>`}).join(``)};function Fn({chatHistory:e,isAiTyping:t,isAgentTyping:n,setReplyContext:r,TypingDots:i,
|
|
21
|
-
`).map((e,t)=>(0,A.jsx)(`div`,{children:e},t))||(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`div`,{children:`Hi there 👋`}),(0,A.jsx)(`div`,{children:`How can we help?`})]})}),(0,A.jsxs)(`div`,{style:{marginTop:`20px`,borderRadius:`22px`,border:`1px solid rgba(255,255,255,0.2)`,background:`rgba(255,255,255,0.12)`,padding:`16px`,color:`#fff`,backdropFilter:`blur(12px)`},children:[(0,A.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`8px`,fontSize:`12px`,fontWeight:600,textTransform:`uppercase`,letterSpacing:`0.18em`,color:`rgba(255,255,255,0.8)`},children:[(0,A.jsx)(`span`,{style:{display:`inline-flex`,width:`24px`,height:`24px`,alignItems:`center`,justifyContent:`center`,borderRadius:`9999px`,background:`rgba(255,255,255,0.18)`,color:`#fff`},children:(0,A.jsx)(Tn,{size:14})}),(0,A.jsxs)(`span`,{children:[l,` • Start With Email`]})]}),(0,A.jsx)(`div`,{style:{marginTop:`8px`,fontSize:`14px`,lineHeight:`24px`,color:`rgba(255,255,255,0.85)`},children:r?`Using ${r} for this chat.`:`Please share your email first so the conversation and calling flow can start cleanly.`}),!r&&(0,A.jsxs)(`form`,{style:{marginTop:`16px`,display:`flex`,flexDirection:`column`,gap:`12px`},onSubmit:async e=>{e.preventDefault();let t=i.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)){s(`Please enter a valid email to start the chat.`);return}s(``),await c(t)},children:[(0,A.jsx)(`input`,{type:`email`,value:i,onChange:e=>{a(e.target.value),o&&s(``)},placeholder:`Enter your email`,style:{height:`48px`,borderRadius:`16px`,border:`1px solid rgba(255,255,255,0.2)`,background:`#fff`,padding:`0 16px`,fontSize:`14px`,color:`#111827`,outline:`none`},autoComplete:`email`}),o&&(0,A.jsx)(`div`,{style:{fontSize:`12px`,fontWeight:500,color:`#ffe4e6`},children:o}),(0,A.jsx)(`button`,{type:`submit`,style:{height:`44px`,borderRadius:`16px`,border:0,background:`#fff`,fontSize:`14px`,fontWeight:600,color:`#111827`,transition:`transform 0.2s ease`,cursor:`pointer`},onMouseEnter:e=>{e.currentTarget.style.transform=`translateY(-2px)`},onMouseLeave:e=>{e.currentTarget.style.transform=`translateY(0)`},children:`Continue`})]})]})]}),(0,A.jsx)(`div`,{style:{display:`flex`,flexDirection:`column`,alignItems:`flex-end`,gap:`12px`,marginBottom:`6px`,padding:`0 20px 20px`},children:t.map(e=>(0,A.jsx)(`button`,{style:{padding:`12px 18px`,borderRadius:`20px`,background:`#fff`,color:`#111827`,fontWeight:500,fontSize:`14px`,boxShadow:`0 4px 12px rgba(0,0,0,0.06)`,border:`1px solid rgba(0,0,0,0.05)`,transition:`transform 0.2s ease, box-shadow 0.2s ease`,cursor:r?`pointer`:`not-allowed`,textAlign:`left`,opacity:r?1:.6},onClick:()=>n(e.label,e.key),disabled:!r,onMouseEnter:e=>{r&&(e.currentTarget.style.transform=`translateY(-2px)`,e.currentTarget.style.boxShadow=`0 6px 16px rgba(0,0,0,0.1)`)},onMouseLeave:e=>{e.currentTarget.style.transform=`translateY(0)`,e.currentTarget.style.boxShadow=`0 4px 12px rgba(0,0,0,0.06)`},children:e.label},e.key))})]})}function Ln({input:e,setInput:t,onSubmit:n,isConversationEnded:r,callUiActive:i,handleToggleVoice:a,activeScreen:o,inputDisabled:s,replyContext:c,clearReplyContext:l,requiresEmail:u,emailInput:d,setEmailInput:f,emailError:p}){let m=c?.sender===`user`?`You`:c?.sender===`agent`?`Agent`:`AI Assistant`;return(0,A.jsxs)(`div`,{style:{padding:`0 20px 4px`,background:`transparent`},children:[r&&(0,A.jsx)(`div`,{style:{marginBottom:`8px`,padding:`8px 16px`,borderRadius:`12px`,background:`#f3f4f6`,color:`#6b7280`,fontSize:`12px`,textAlign:`center`,fontWeight:500},children:`This conversation has ended.`}),c&&(0,A.jsxs)(`div`,{style:{marginBottom:`8px`,display:`flex`,alignItems:`flex-start`,justifyContent:`space-between`,gap:`12px`,borderRadius:`16px`,border:`1px solid rgba(0,0,0,0.05)`,background:`#fff`,padding:`12px 16px`,boxShadow:`0 8px 24px rgba(0,0,0,0.05)`},children:[(0,A.jsxs)(`div`,{style:{minWidth:0,flex:1,borderLeft:`2px solid var(--flowengage-primary)`,paddingLeft:`12px`},children:[(0,A.jsxs)(`div`,{style:{fontSize:`12px`,fontWeight:600,color:`var(--flowengage-primary)`},children:[`Replying to `,m]}),(0,A.jsx)(`div`,{style:{overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`,fontSize:`12px`,color:`#6b7280`},children:c.replyToContent||c.message})]}),(0,A.jsx)(`button`,{type:`button`,style:{width:`28px`,height:`28px`,borderRadius:`9999px`,border:0,background:`#f3f4f6`,color:`#6b7280`,transition:`color 0.2s ease, background 0.2s ease`,cursor:`pointer`},onClick:l,"aria-label":`Cancel reply`,onMouseEnter:e=>{e.currentTarget.style.background=`#e5e7eb`,e.currentTarget.style.color=`#374151`},onMouseLeave:e=>{e.currentTarget.style.background=`#f3f4f6`,e.currentTarget.style.color=`#6b7280`},children:`×`})]}),(0,A.jsxs)(`form`,{style:{display:`flex`,alignItems:`center`,gap:`8px`,padding:`6px 10px`,border:`1px solid rgba(0,0,0,0.05)`,borderRadius:`9999px`,background:`#fff`,boxShadow:`0 8px 24px rgba(0,0,0,0.05)`,opacity:r?.5:1},onSubmit:n,children:[(0,A.jsx)(`button`,{type:`button`,style:{width:`32px`,height:`32px`,borderRadius:`9999px`,background:`transparent`,color:`#9ca3af`,display:`flex`,alignItems:`center`,justifyContent:`center`,transition:`background 0.2s ease, color 0.2s ease`,border:0,cursor:`pointer`},onClick:a,title:`Start voice call`,disabled:r||i||u,onMouseEnter:e=>{e.currentTarget.style.background=`#f3f4f6`},onMouseLeave:e=>{e.currentTarget.style.background=`transparent`},children:(0,A.jsx)(Sn,{})}),(0,A.jsx)(`input`,{style:{flex:1,minWidth:0,border:`none`,fontFamily:`inherit`,fontSize:`14px`,outline:`none`,padding:`6px 0`,color:`#111827`,background:`transparent`},value:u?d:e,onChange:e=>{if(u){f(e.target.value);return}t(e.target.value)},placeholder:r?`Conversation ended`:u?`Enter your email to start`:o===`agent`?`Message the agent…`:`Type a reply…`,disabled:s,type:u?`email`:`text`,autoComplete:u?`email`:`off`}),(0,A.jsx)(`button`,{type:`submit`,style:{width:`34px`,height:`34px`,borderRadius:`9999px`,background:`transparent`,color:`var(--flowengage-primary)`,border:`1px solid var(--flowengage-primary)`,display:`flex`,alignItems:`center`,justifyContent:`center`,transition:`all 0.2s ease`,cursor:s?`not-allowed`:`pointer`,marginLeft:`4px`,opacity:s?.5:1},disabled:s,onMouseEnter:e=>{s||(e.currentTarget.style.background=`var(--flowengage-primary)`,e.currentTarget.style.color=`#fff`)},onMouseLeave:e=>{e.currentTarget.style.background=`transparent`,e.currentTarget.style.color=s?`#d1d5db`:`var(--flowengage-primary)`},children:(0,A.jsx)(bn,{})})]}),u&&p&&(0,A.jsx)(`div`,{style:{padding:`8px 16px 0`,fontSize:`12px`,fontWeight:500,color:`#f43f5e`},children:p})]})}var Rn=({muted:e=!1})=>(0,A.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,A.jsx)(`path`,{d:`M12 1a4 4 0 014 4v6a4 4 0 01-6.83 2.83`}),(0,A.jsx)(`path`,{d:`M19 10a7 7 0 01-1.62 4.49M5 10a7 7 0 008.79 6.77`}),(0,A.jsx)(`path`,{d:`M12 19v4M8 23h8`}),e&&(0,A.jsx)(`line`,{x1:`2`,y1:`2`,x2:`22`,y2:`22`})]}),zn=({variant:e,onClick:t,children:n,icon:r,compact:i=!1,iconOnly:a=!1,active:o=!1,ariaLabel:s})=>(0,A.jsxs)(`button`,{type:`button`,className:[`flowengage-call-btn`,`flowengage-call-btn-${e}`,i?`compact`:``,a?`icon-only`:``,o?`active`:``].filter(Boolean).join(` `),onClick:t,"aria-label":s||n,title:s||n,children:[r,!a&&(0,A.jsx)(`span`,{children:n})]});function Bn({webRTCError:e,micError:t,setMicError:n,dismissCallError:r,incomingCall:i,rejectCall:a,acceptCall:o,activeCallId:s,callConnectionState:c,formatCallDuration:l,callDurationSeconds:u,endWebRTCCall:d,isCallMuted:f,toggleCallMute:p,isAIVoiceActive:m,currentCallAgentName:h,isRateLimited:g,rateLimitMessage:_}){let y=(0,v.useRef)(null),b=(0,v.useCallback)(()=>{if(!y.current)return;let{audioContext:e,oscillator:t,interval:n,toneTimeout:r}=y.current;window.clearInterval(n),window.clearTimeout(r);try{t.stop()}catch{}try{e.close()}catch{}y.current=null},[]),x=(0,v.useCallback)(()=>{if(y.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=()=>{y.current&&(window.clearTimeout(y.current.toneTimeout),n.frequency.value=440,y.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(),y.current={audioContext:t,oscillator:n,interval:null,toneTimeout:null},i(),y.current.interval=window.setInterval(i,1e3)}catch(e){console.warn(`[FlowEngage] failed to start ringtone`,e)}},[]);(0,v.useEffect)(()=>{if(i){x();return}b()},[i,x,b]),(0,v.useEffect)(()=>()=>b(),[b]);let ee=m?`header-mode`:`bottom-mode`,te=!!(i||s),S=i?`incoming`:c===`connected`?`connected`:`connecting`,ne=(0,v.useMemo)(()=>S===`incoming`?`Incoming Call`:S===`connected`?`Voice Call Active`:`Connecting Call`,[S]),re=(0,v.useMemo)(()=>S===`incoming`?`${h} wants to join a voice call`:S===`connected`?`You are connected to ${h} from this conversation.`:`Please wait while ${h}'s voice connection finishes setting up.`,[h,S]);return(0,A.jsxs)(A.Fragment,{children:[(e||t)&&(0,A.jsxs)(`div`,{style:{margin:`0 20px 10px`,padding:`12px 16px`,borderRadius:`12px`,background:`#fef2f2`,border:`1px solid #fee2e2`,display:`flex`,alignItems:`flex-start`,gap:`10px`},children:[(0,A.jsx)(Cn,{className:``}),(0,A.jsx)(`span`,{style:{fontSize:`12px`,color:`#b91c1c`,lineHeight:1.5,flex:1},children:e||t}),(0,A.jsx)(`button`,{style:{flexShrink:0,background:`transparent`,border:0,color:`#f87171`,cursor:`pointer`,fontSize:`18px`,lineHeight:1},onClick:()=>{n(null),r()},onMouseEnter:e=>{e.currentTarget.style.color=`#dc2626`},onMouseLeave:e=>{e.currentTarget.style.color=`#f87171`},children:`×`})]}),te&&(0,A.jsx)(`div`,{className:`incoming-call-overlay ${ee}`,children:(0,A.jsx)(`div`,{className:[`incoming-call-container`,S===`connected`?`connected-layout`:``].filter(Boolean).join(` `),children:S===`connected`?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{className:`call-connected-top`,children:[(0,A.jsxs)(`div`,{className:`call-connected-identity`,children:[(0,A.jsx)(`div`,{className:`call-icon-wrapper ${S}`,children:(0,A.jsx)(yn,{size:20})}),(0,A.jsxs)(`div`,{className:`call-info-group`,children:[(0,A.jsx)(`h3`,{className:`call-title`,children:ne}),(0,A.jsx)(`p`,{className:`call-subtitle`,children:re})]})]}),(0,A.jsx)(`div`,{className:`call-timer`,children:l(u)})]}),(0,A.jsxs)(`div`,{className:`call-actions connected`,children:[(0,A.jsx)(zn,{variant:`mute`,onClick:p,compact:m,active:f,icon:(0,A.jsx)(Rn,{muted:f}),children:f?`Unmute`:`Mute`}),(0,A.jsx)(zn,{variant:`end`,onClick:d,compact:m,icon:(0,A.jsx)(yn,{size:14}),children:`End`})]})]}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{className:`call-icon-wrapper ${S}`,children:[(0,A.jsx)(Sn,{}),S===`incoming`&&(0,A.jsx)(`div`,{className:`call-pulse-animation`}),S===`connecting`&&(0,A.jsx)(`div`,{className:`call-connecting-animation`})]}),(0,A.jsxs)(`div`,{className:`call-info-group`,children:[(0,A.jsx)(`h3`,{className:`call-title`,children:ne}),(0,A.jsx)(`p`,{className:`call-subtitle`,children:re})]}),(0,A.jsx)(`div`,{className:`call-actions`,children:S===`incoming`&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(zn,{variant:`reject`,onClick:async()=>{b(),await a()},iconOnly:!0,icon:(0,A.jsx)(yn,{size:14}),ariaLabel:`Decline call`,children:`Decline`}),(0,A.jsx)(zn,{variant:`accept`,onClick:async()=>{b(),await o()},iconOnly:!0,icon:(0,A.jsx)(Sn,{}),ariaLabel:`Accept call`,children:`Accept`})]})})]})})}),g&&(0,A.jsx)(`div`,{style:{margin:`0 20px 10px`,padding:`12px 16px`,fontSize:`13px`,borderRadius:`12px`,background:`#fee2e2`,color:`#991b1b`},children:_})]})}function Vn(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 Hn=Object.defineProperty,Un=(e,t,n)=>t in e?Hn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Wn=(e,t,n)=>Un(e,typeof t==`symbol`?t:t+``,n),Gn=class{constructor(){Wn(this,`_locking`),Wn(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 Kn(e,t){if(!e)throw Error(t)}var qn=34028234663852886e22,Jn=-34028234663852886e22,Yn=4294967295,Xn=2147483647,Zn=-2147483648;function Qn(e){if(typeof e!=`number`)throw Error(`invalid int 32: `+typeof e);if(!Number.isInteger(e)||e>Xn||e<Zn)throw Error(`invalid int 32: `+e)}function $n(e){if(typeof e!=`number`)throw Error(`invalid uint 32: `+typeof e);if(!Number.isInteger(e)||e>Yn||e<0)throw Error(`invalid uint 32: `+e)}function er(e){if(typeof e!=`number`)throw Error(`invalid float 32: `+typeof e);if(Number.isFinite(e)&&(e>qn||e<Jn))throw Error(`invalid float 32: `+e)}var tr=Symbol(`@bufbuild/protobuf/enum-type`);function nr(e){let t=e[tr];return Kn(t,`missing enum type on enum object`),t}function rr(e,t,n,r){e[tr]=ir(t,n.map(t=>({no:t.no,name:t.name,localName:e[t.no]})))}function ir(e,t,n){let r=Object.create(null),i=Object.create(null),a=[];for(let e of t){let t=or(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 ar(e,t,n){let r={};for(let e of t){let t=or(e);r[t.localName]=t.no,r[t.no]=t.localName}return rr(r,e,t),r}function or(e){return`localName`in e?e:Object.assign(Object.assign({},e),{localName:e.name})}var sr=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 cr(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 sr),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 lr(){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 ur(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 dr=4294967296;function fr(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>=dr&&(i+=r/dr|0,r%=dr)}return a(-24,-18),a(-18,-12),a(-12,-6),a(-6),t?_r(r,i):gr(r,i)}function pr(e,t){let n=gr(e,t),r=n.hi&2147483648;r&&(n=_r(n.lo,n.hi));let i=mr(n.lo,n.hi);return r?`-`+i:i}function mr(e,t){if({lo:e,hi:t}=hr(e,t),t<=2097151)return String(dr*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()+vr(o)+vr(a)}function hr(e,t){return{lo:e>>>0,hi:t>>>0}}function gr(e,t){return{lo:e|0,hi:t|0}}function _r(e,t){return t=~t,e?e=~e+1:t+=1,gr(e,t)}var vr=e=>{let t=String(e);return`0000000`.slice(t.length)+t};function yr(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 br(){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 xr(){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=>Kn(/^-?[0-9]+$/.test(e),`int64 invalid: ${e}`),n=e=>Kn(/^[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),fr(e)},uEnc(e){return typeof e!=`string`&&(e=e.toString()),n(e),fr(e)},dec(e,t){return pr(e,t)},uDec(e,t){return mr(e,t)}}}var Sr=xr(),j;(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`})(j||={});var Cr;(function(e){e[e.BIGINT=0]=`BIGINT`,e[e.STRING=1]=`STRING`})(Cr||={});function wr(e,t,n){if(t===n)return!0;if(e==j.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 j.UINT64:case j.FIXED64:case j.INT64:case j.SFIXED64:case j.SINT64:return t==n}return!1}function Tr(e,t){switch(e){case j.BOOL:return!1;case j.UINT64:case j.FIXED64:case j.INT64:case j.SFIXED64:case j.SINT64:return t==0?Sr.zero:`0`;case j.DOUBLE:case j.FLOAT:return 0;case j.BYTES:return new Uint8Array;case j.STRING:return``;default:return 0}}function Er(e,t){switch(e){case j.BOOL:return t===!1;case j.STRING:return t===``;case j.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return t==0}}var Dr;(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`})(Dr||={});var Or=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($n(e);e>127;)this.buf.push(e&127|128),e>>>=7;return this.buf.push(e),this}int32(e){return Qn(e),yr(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){er(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){$n(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){Qn(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return Qn(e),e=(e<<1^e>>31)>>>0,yr(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),r=Sr.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=Sr.uEnc(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(t)}int64(e){let t=Sr.enc(e);return ur(t.lo,t.hi,this.buf),this}sint64(e){let t=Sr.enc(e),n=t.hi>>31;return ur(t.lo<<1^n,(t.hi<<1|t.lo>>>31)^n,this.buf),this}uint64(e){let t=Sr.uEnc(e);return ur(t.lo,t.hi,this.buf),this}},kr=class{constructor(e,t){this.varint64=lr,this.uint32=br,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 Dr.Varint:for(;this.buf[this.pos++]&128;);break;case Dr.Bit64:this.pos+=4;case Dr.Bit32:this.pos+=4;break;case Dr.LengthDelimited:let n=this.uint32();this.pos+=n;break;case Dr.StartGroup:for(;;){let[e,n]=this.tag();if(n===Dr.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 Sr.dec(...this.varint64())}uint64(){return Sr.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),n=-(e&1);return e=(e>>>1|(t&1)<<31)^n,t=t>>>1^n,Sr.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 Sr.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return Sr.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 Ar(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 jr(e){let t=e.field.localName,n=Object.create(null);return n[t]=Mr(e),[n,()=>n[t]]}function Mr(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 Tr(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 Nr(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 Pr=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`.split(``),Fr=[];for(let e=0;e<Pr.length;e++)Fr[Pr[e].charCodeAt(0)]=e;Fr[45]=Pr.indexOf(`+`),Fr[95]=Pr.indexOf(`/`);var Ir={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=Fr[e.charCodeAt(t)],a===void 0)switch(e[t]){case`=`:i=0;case`
|
|
20
|
+
`).map(e=>e.trim()).filter(Boolean),n=t.filter(e=>/^[-*]\s+/.test(e));if(n.length>=2&&n.length===t.length)return`<ul>${n.map(e=>`<li>${r(e.replace(/^[-*]\s+/,``))}</li>`).join(``)}</ul>`;let i=e.split(/\s+(?=[-*]\s+\*\*?)/).map(e=>e.trim()).filter(Boolean);return i.length>=2&&i.every(e=>/^[-*]\s+/.test(e))?`<ul>${i.map(e=>`<li>${r(e.replace(/^[-*]\s+/,``))}</li>`).join(``)}</ul>`:`<p>${r(e).replace(/\n/g,`<br />`)}</p>`}).join(``)};function Fn({chatHistory:e,isAiTyping:t,isAgentTyping:n,setReplyContext:r,TypingDots:i,primaryColor:a=`#3B82F6`,agentHeadshot:o=null,agentDisplayName:s=`Agent`}){let c=(0,v.useRef)(null),l=e=>{if(!e)return`just now`;let t=new Date,n=new Date(e),r=Math.max(0,Math.floor((t-n)/1e3));if(r<60)return`just now`;let i=Math.floor(r/60);if(i<60)return`${i} min${i>1?`s`:``} ago`;let a=Math.floor(i/60);if(a<24)return`${a} hr${a>1?`s`:``} ago`;let o=Math.floor(a/24);return`${o} day${o>1?`s`:``} ago`};return(0,v.useEffect)(()=>{c.current&&c.current.scrollIntoView({behavior:`smooth`})},[e.length,t,n]),(0,A.jsxs)(`div`,{style:{flex:1,overflowY:`auto`,padding:`10px 20px 20px`,display:`flex`,flexDirection:`column`},children:[e.map(e=>{let t=e.sender===`system`,n=e.sender===`user`,i=e.sender===`ai`||e.sender===`bot`,c=e.sender===`agent`,u=e.isPending,d=e.agent_name||e.agentName||e.metadata?.agentName||s,f=typeof e.sender_headshot==`string`&&e.sender_headshot.trim()||typeof o==`string`&&o.trim()||null,p=Mn(e.replyToContent||e.replyContext?.message||``),m=e.replyToSender===`user`?`You`:e.replyToSender===`agent`?`Agent`:e.replyToSender===`ai`||e.replyToSender===`bot`?`AI Assistant`:`Message`;return t?(0,A.jsx)(`div`,{style:{display:`flex`,justifyContent:`center`,margin:`8px 0`},children:(0,A.jsx)(`div`,{style:{padding:`6px 12px`,borderRadius:`9999px`,background:`#f3f4f6`,color:`#6b7280`,fontSize:`12px`,fontWeight:500},children:e.message})},e.id):(0,A.jsxs)(`div`,{style:{display:`flex`,justifyContent:n?`flex-end`:`flex-start`,marginBottom:`12px`,position:`relative`},children:[!n&&(i||c)&&(0,A.jsx)(`div`,{style:{marginRight:`10px`,marginTop:`34px`,width:`36px`,height:`36px`,flexShrink:0,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`9999px`,background:c?`#f3f4f6`:`var(--flowengage-primary)`,color:c?a:`#fff`,boxShadow:c?`0 2px 8px rgba(0,0,0,0.06)`:`0 8px 20px rgba(59,130,246,0.24)`,overflow:`hidden`,border:c?`1px solid ${a}22`:`none`,fontSize:`12px`,fontWeight:800},children:i?(0,A.jsx)(En,{size:16}):f?(0,A.jsx)(`img`,{src:f,alt:``,style:{width:`100%`,height:`100%`,objectFit:`cover`}}):(0,A.jsx)(`span`,{style:{lineHeight:1},children:On(d)})}),(0,A.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,alignItems:n?`flex-end`:`flex-start`,maxWidth:`85%`},children:[!u&&(0,A.jsxs)(`button`,{onClick:()=>r(e),style:{opacity:1,marginBottom:`6px`,display:`flex`,alignItems:`center`,gap:`4px`,fontSize:`11px`,color:`#9ca3af`,background:`transparent`,border:0,cursor:`pointer`,padding:0,marginLeft:n?0:`2px`},onMouseEnter:e=>{e.currentTarget.style.color=`#4b5563`},onMouseLeave:e=>{e.currentTarget.style.color=`#9ca3af`},children:[(0,A.jsx)(Sn,{}),`Reply`]}),(0,A.jsxs)(`div`,{style:{padding:`12px 16px`,borderRadius:`18px`,lineHeight:1.5,boxShadow:`0 2px 6px rgba(0,0,0,0.04)`,background:n?`var(--flowengage-primary)`:`#fff`,color:n?`#fff`:`#111827`,whiteSpace:n?`pre-wrap`:`normal`,opacity:u?.55:1,transition:`opacity 0.3s ease`},children:[p&&(0,A.jsxs)(`div`,{style:{marginBottom:`8px`,borderRadius:`14px`,borderLeft:n?`2px solid rgba(255,255,255,0.8)`:`2px solid var(--flowengage-primary)`,padding:`8px 12px`,fontSize:`12px`,background:n?`rgba(255,255,255,0.15)`:`#f9fafb`,color:n?`rgba(255,255,255,0.9)`:`#6b7280`},children:[(0,A.jsx)(`div`,{style:{marginBottom:`2px`,fontWeight:600},children:m}),(0,A.jsx)(`div`,{style:{display:`-webkit-box`,WebkitLineClamp:2,WebkitBoxOrient:`vertical`,overflow:`hidden`},children:p})]}),i?(0,A.jsx)(`div`,{className:`flowengage-message-content`,dangerouslySetInnerHTML:{__html:Pn(e.message)}}):(0,A.jsx)(`div`,{style:{whiteSpace:n||c?`normal`:`pre-wrap`},children:e.message}),u&&(0,A.jsx)(`span`,{style:{fontSize:`10px`,marginLeft:`6px`,opacity:.7,whiteSpace:`nowrap`},children:`sending…`})]}),(0,A.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`4px`,marginTop:`4px`,padding:`0 4px`,justifyContent:n?`flex-end`:`flex-start`,marginLeft:n?0:`2px`},children:[(0,A.jsx)(`span`,{style:{fontSize:`10px`,color:`#9ca3af`,fontWeight:500,whiteSpace:`nowrap`},children:l(e.timestamp||e.createdAt||Date.now())}),(0,A.jsx)(`span`,{style:{fontSize:`10px`,fontWeight:700,color:n?`var(--flowengage-primary)`:`#9ca3af`},children:u?`○`:`✓`})]})]})]},e.id)}),t&&(0,A.jsxs)(`div`,{style:{marginBottom:`12px`,display:`flex`,justifyContent:`flex-start`},children:[(0,A.jsx)(`div`,{style:{marginRight:`8px`,marginTop:`auto`,width:`36px`,height:`36px`,flexShrink:0,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`9999px`,background:`var(--flowengage-primary)`,color:`#fff`,boxShadow:`0 8px 20px rgba(59,130,246,0.24)`},children:(0,A.jsx)(En,{size:16})}),(0,A.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`5px`,borderRadius:`18px`,background:`#fff`,padding:`12px 16px`,color:`#111827`,boxShadow:`0 2px 6px rgba(0,0,0,0.04)`},children:[0,1,2].map(e=>(0,A.jsx)(`span`,{style:{width:`7px`,height:`7px`,borderRadius:`50%`,background:`#9ca3af`,animation:`fe-dot-bounce 1.2s ease-in-out ${e*.2}s infinite`,display:`inline-block`}},e))})]}),n&&(0,A.jsx)(i,{}),(0,A.jsx)(`div`,{ref:c})]})}function In({greetings:e,recommendations:t,onSendMessage:n}){return(0,A.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`},children:[(0,A.jsx)(`div`,{style:{marginTop:`30px`,marginBottom:`auto`,padding:`0 20px`},children:(0,A.jsx)(`div`,{style:{fontSize:`34px`,fontWeight:700,color:`#fff`,lineHeight:1.15},children:e?.split(`
|
|
21
|
+
`).map((e,t)=>(0,A.jsx)(`div`,{children:e},t))||(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`div`,{children:`Hi there 👋`}),(0,A.jsx)(`div`,{children:`How can we help?`})]})})}),(0,A.jsx)(`div`,{style:{display:`flex`,flexDirection:`column`,alignItems:`flex-end`,gap:`12px`,marginBottom:`6px`,padding:`0 20px 20px`},children:t.map(e=>(0,A.jsx)(`button`,{style:{padding:`12px 18px`,borderRadius:`20px`,background:`#fff`,color:`#111827`,fontWeight:500,fontSize:`14px`,boxShadow:`0 4px 12px rgba(0,0,0,0.06)`,border:`1px solid rgba(0,0,0,0.05)`,transition:`transform 0.2s ease, box-shadow 0.2s ease`,cursor:`pointer`,textAlign:`left`},onClick:()=>n(e.label,e.key),onMouseEnter:e=>{e.currentTarget.style.transform=`translateY(-2px)`,e.currentTarget.style.boxShadow=`0 6px 16px rgba(0,0,0,0.1)`},onMouseLeave:e=>{e.currentTarget.style.transform=`translateY(0)`,e.currentTarget.style.boxShadow=`0 4px 12px rgba(0,0,0,0.06)`},children:e.label},e.key))})]})}function Ln({input:e,setInput:t,onSubmit:n,isConversationEnded:r,callUiActive:i,handleToggleVoice:a,activeScreen:o,inputDisabled:s,replyContext:c,clearReplyContext:l,requiresEmail:u,emailInput:d,setEmailInput:f,emailError:p}){let m=c?.sender===`user`?`You`:c?.sender===`agent`?`Agent`:`AI Assistant`;return(0,A.jsxs)(`div`,{style:{padding:`0 20px 4px`,background:`transparent`},children:[r&&(0,A.jsx)(`div`,{style:{marginBottom:`8px`,padding:`8px 16px`,borderRadius:`12px`,background:`#f3f4f6`,color:`#6b7280`,fontSize:`12px`,textAlign:`center`,fontWeight:500},children:`This conversation has ended.`}),c&&(0,A.jsxs)(`div`,{style:{marginBottom:`8px`,display:`flex`,alignItems:`flex-start`,justifyContent:`space-between`,gap:`12px`,borderRadius:`16px`,border:`1px solid rgba(0,0,0,0.05)`,background:`#fff`,padding:`12px 16px`,boxShadow:`0 8px 24px rgba(0,0,0,0.05)`},children:[(0,A.jsxs)(`div`,{style:{minWidth:0,flex:1,borderLeft:`2px solid var(--flowengage-primary)`,paddingLeft:`12px`},children:[(0,A.jsxs)(`div`,{style:{fontSize:`12px`,fontWeight:600,color:`var(--flowengage-primary)`},children:[`Replying to `,m]}),(0,A.jsx)(`div`,{style:{overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`,fontSize:`12px`,color:`#6b7280`},children:c.replyToContent||c.message})]}),(0,A.jsx)(`button`,{type:`button`,style:{width:`28px`,height:`28px`,borderRadius:`9999px`,border:0,background:`#f3f4f6`,color:`#6b7280`,transition:`color 0.2s ease, background 0.2s ease`,cursor:`pointer`},onClick:l,"aria-label":`Cancel reply`,onMouseEnter:e=>{e.currentTarget.style.background=`#e5e7eb`,e.currentTarget.style.color=`#374151`},onMouseLeave:e=>{e.currentTarget.style.background=`#f3f4f6`,e.currentTarget.style.color=`#6b7280`},children:`×`})]}),u&&(0,A.jsx)(`div`,{style:{marginBottom:`14px`,padding:`0 8px`},children:(0,A.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,justifyContent:`center`,gap:`8px`,color:`#111827`,fontSize:`14px`,fontWeight:500,textAlign:`center`},children:[(0,A.jsx)(`span`,{style:{display:`inline-flex`,width:`22px`,height:`22px`,borderRadius:`9999px`,alignItems:`center`,justifyContent:`center`,background:`rgba(59,130,246,0.08)`,color:`var(--flowengage-primary)`},children:(0,A.jsx)(En,{size:13})}),(0,A.jsx)(`span`,{children:`Please provide your email address so we can help you.`})]})}),(0,A.jsxs)(`form`,{style:{display:`flex`,alignItems:`center`,gap:`8px`,padding:`6px 10px`,border:`1px solid rgba(0,0,0,0.05)`,borderRadius:`9999px`,background:`#fff`,boxShadow:`0 8px 24px rgba(0,0,0,0.05)`,opacity:r?.5:1},onSubmit:n,children:[(0,A.jsx)(`button`,{type:`button`,style:{width:`32px`,height:`32px`,borderRadius:`9999px`,background:`transparent`,color:`#9ca3af`,display:`flex`,alignItems:`center`,justifyContent:`center`,transition:`background 0.2s ease, color 0.2s ease`,border:0,cursor:`pointer`},onClick:a,title:`Start voice call`,disabled:r||i||u,onMouseEnter:e=>{e.currentTarget.style.background=`#f3f4f6`},onMouseLeave:e=>{e.currentTarget.style.background=`transparent`},children:(0,A.jsx)(Cn,{})}),(0,A.jsx)(`input`,{style:{flex:1,minWidth:0,border:`none`,fontFamily:`inherit`,fontSize:`14px`,outline:`none`,padding:`6px 0`,color:`#111827`,background:`transparent`},value:u?d:e,onChange:e=>{if(u){f(e.target.value);return}t(e.target.value)},placeholder:r?`Conversation ended`:u?`Your email address`:o===`agent`?`Message the agent…`:`Type a reply…`,disabled:s,type:u?`email`:`text`,autoComplete:u?`email`:`off`}),(0,A.jsx)(`button`,{type:`submit`,style:{width:`34px`,height:`34px`,borderRadius:`9999px`,background:`transparent`,color:`var(--flowengage-primary)`,border:`1px solid var(--flowengage-primary)`,display:`flex`,alignItems:`center`,justifyContent:`center`,transition:`all 0.2s ease`,cursor:s?`not-allowed`:`pointer`,marginLeft:`4px`,opacity:s?.5:1},disabled:s,onMouseEnter:e=>{s||(e.currentTarget.style.background=`var(--flowengage-primary)`,e.currentTarget.style.color=`#fff`)},onMouseLeave:e=>{e.currentTarget.style.background=`transparent`,e.currentTarget.style.color=s?`#d1d5db`:`var(--flowengage-primary)`},children:(0,A.jsx)(xn,{})})]}),u&&p&&(0,A.jsx)(`div`,{style:{padding:`8px 16px 0`,fontSize:`12px`,fontWeight:500,color:`#f43f5e`},children:p})]})}var Rn=({muted:e=!1})=>(0,A.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,A.jsx)(`path`,{d:`M12 1a4 4 0 014 4v6a4 4 0 01-6.83 2.83`}),(0,A.jsx)(`path`,{d:`M19 10a7 7 0 01-1.62 4.49M5 10a7 7 0 008.79 6.77`}),(0,A.jsx)(`path`,{d:`M12 19v4M8 23h8`}),e&&(0,A.jsx)(`line`,{x1:`2`,y1:`2`,x2:`22`,y2:`22`})]}),zn=({variant:e,onClick:t,children:n,icon:r,compact:i=!1,iconOnly:a=!1,active:o=!1,ariaLabel:s})=>(0,A.jsxs)(`button`,{type:`button`,className:[`flowengage-call-btn`,`flowengage-call-btn-${e}`,i?`compact`:``,a?`icon-only`:``,o?`active`:``].filter(Boolean).join(` `),onClick:t,"aria-label":s||n,title:s||n,children:[r,!a&&(0,A.jsx)(`span`,{children:n})]});function Bn({webRTCError:e,micError:t,setMicError:n,dismissCallError:r,incomingCall:i,rejectCall:a,acceptCall:o,activeCallId:s,callConnectionState:c,formatCallDuration:l,callDurationSeconds:u,endWebRTCCall:d,isCallMuted:f,toggleCallMute:p,isAIVoiceActive:m,currentCallAgentName:h,isRateLimited:g,rateLimitMessage:_}){let y=(0,v.useRef)(null),b=(0,v.useCallback)(()=>{if(!y.current)return;let{audioContext:e,oscillator:t,interval:n,toneTimeout:r}=y.current;window.clearInterval(n),window.clearTimeout(r);try{t.stop()}catch{}try{e.close()}catch{}y.current=null},[]),x=(0,v.useCallback)(()=>{if(y.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=()=>{y.current&&(window.clearTimeout(y.current.toneTimeout),n.frequency.value=440,y.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(),y.current={audioContext:t,oscillator:n,interval:null,toneTimeout:null},i(),y.current.interval=window.setInterval(i,1e3)}catch(e){console.warn(`[FlowEngage] failed to start ringtone`,e)}},[]);(0,v.useEffect)(()=>{if(i){x();return}b()},[i,x,b]),(0,v.useEffect)(()=>()=>b(),[b]);let ee=m?`header-mode`:`bottom-mode`,te=!!(i||s),S=i?`incoming`:c===`connected`?`connected`:`connecting`,ne=(0,v.useMemo)(()=>S===`incoming`?`Incoming Call`:S===`connected`?`Voice Call Active`:`Connecting Call`,[S]),re=(0,v.useMemo)(()=>S===`incoming`?`${h} wants to join a voice call`:S===`connected`?`You are connected to ${h} from this conversation.`:`Please wait while ${h}'s voice connection finishes setting up.`,[h,S]);return(0,A.jsxs)(A.Fragment,{children:[(e||t)&&(0,A.jsxs)(`div`,{style:{margin:`0 20px 10px`,padding:`12px 16px`,borderRadius:`12px`,background:`#fef2f2`,border:`1px solid #fee2e2`,display:`flex`,alignItems:`flex-start`,gap:`10px`},children:[(0,A.jsx)(wn,{className:``}),(0,A.jsx)(`span`,{style:{fontSize:`12px`,color:`#b91c1c`,lineHeight:1.5,flex:1},children:e||t}),(0,A.jsx)(`button`,{style:{flexShrink:0,background:`transparent`,border:0,color:`#f87171`,cursor:`pointer`,fontSize:`18px`,lineHeight:1},onClick:()=>{n(null),r()},onMouseEnter:e=>{e.currentTarget.style.color=`#dc2626`},onMouseLeave:e=>{e.currentTarget.style.color=`#f87171`},children:`×`})]}),te&&(0,A.jsx)(`div`,{className:`incoming-call-overlay ${ee}`,children:(0,A.jsx)(`div`,{className:[`incoming-call-container`,S===`connected`?`connected-layout`:``].filter(Boolean).join(` `),children:S===`connected`?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{className:`call-connected-top`,children:[(0,A.jsxs)(`div`,{className:`call-connected-identity`,children:[(0,A.jsx)(`div`,{className:`call-icon-wrapper ${S}`,children:(0,A.jsx)(bn,{size:20})}),(0,A.jsxs)(`div`,{className:`call-info-group`,children:[(0,A.jsx)(`h3`,{className:`call-title`,children:ne}),(0,A.jsx)(`p`,{className:`call-subtitle`,children:re})]})]}),(0,A.jsx)(`div`,{className:`call-timer`,children:l(u)})]}),(0,A.jsxs)(`div`,{className:`call-actions connected`,children:[(0,A.jsx)(zn,{variant:`mute`,onClick:p,compact:m,active:f,icon:(0,A.jsx)(Rn,{muted:f}),children:f?`Unmute`:`Mute`}),(0,A.jsx)(zn,{variant:`end`,onClick:d,compact:m,icon:(0,A.jsx)(bn,{size:14}),children:`End`})]})]}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{className:`call-icon-wrapper ${S}`,children:[(0,A.jsx)(Cn,{}),S===`incoming`&&(0,A.jsx)(`div`,{className:`call-pulse-animation`}),S===`connecting`&&(0,A.jsx)(`div`,{className:`call-connecting-animation`})]}),(0,A.jsxs)(`div`,{className:`call-info-group`,children:[(0,A.jsx)(`h3`,{className:`call-title`,children:ne}),(0,A.jsx)(`p`,{className:`call-subtitle`,children:re})]}),(0,A.jsx)(`div`,{className:`call-actions`,children:S===`incoming`&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(zn,{variant:`reject`,onClick:async()=>{b(),await a()},iconOnly:!0,icon:(0,A.jsx)(bn,{size:14}),ariaLabel:`Decline call`,children:`Decline`}),(0,A.jsx)(zn,{variant:`accept`,onClick:async()=>{b(),await o()},iconOnly:!0,icon:(0,A.jsx)(Cn,{}),ariaLabel:`Accept call`,children:`Accept`})]})})]})})}),g&&(0,A.jsx)(`div`,{style:{margin:`0 20px 10px`,padding:`12px 16px`,fontSize:`13px`,borderRadius:`12px`,background:`#fee2e2`,color:`#991b1b`},children:_})]})}function Vn(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 Hn=Object.defineProperty,Un=(e,t,n)=>t in e?Hn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Wn=(e,t,n)=>Un(e,typeof t==`symbol`?t:t+``,n),Gn=class{constructor(){Wn(this,`_locking`),Wn(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 Kn(e,t){if(!e)throw Error(t)}var qn=34028234663852886e22,Jn=-34028234663852886e22,Yn=4294967295,Xn=2147483647,Zn=-2147483648;function Qn(e){if(typeof e!=`number`)throw Error(`invalid int 32: `+typeof e);if(!Number.isInteger(e)||e>Xn||e<Zn)throw Error(`invalid int 32: `+e)}function $n(e){if(typeof e!=`number`)throw Error(`invalid uint 32: `+typeof e);if(!Number.isInteger(e)||e>Yn||e<0)throw Error(`invalid uint 32: `+e)}function er(e){if(typeof e!=`number`)throw Error(`invalid float 32: `+typeof e);if(Number.isFinite(e)&&(e>qn||e<Jn))throw Error(`invalid float 32: `+e)}var tr=Symbol(`@bufbuild/protobuf/enum-type`);function nr(e){let t=e[tr];return Kn(t,`missing enum type on enum object`),t}function rr(e,t,n,r){e[tr]=ir(t,n.map(t=>({no:t.no,name:t.name,localName:e[t.no]})))}function ir(e,t,n){let r=Object.create(null),i=Object.create(null),a=[];for(let e of t){let t=or(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 ar(e,t,n){let r={};for(let e of t){let t=or(e);r[t.localName]=t.no,r[t.no]=t.localName}return rr(r,e,t),r}function or(e){return`localName`in e?e:Object.assign(Object.assign({},e),{localName:e.name})}var sr=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 cr(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 sr),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 lr(){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 ur(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 dr=4294967296;function fr(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>=dr&&(i+=r/dr|0,r%=dr)}return a(-24,-18),a(-18,-12),a(-12,-6),a(-6),t?_r(r,i):gr(r,i)}function pr(e,t){let n=gr(e,t),r=n.hi&2147483648;r&&(n=_r(n.lo,n.hi));let i=mr(n.lo,n.hi);return r?`-`+i:i}function mr(e,t){if({lo:e,hi:t}=hr(e,t),t<=2097151)return String(dr*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()+vr(o)+vr(a)}function hr(e,t){return{lo:e>>>0,hi:t>>>0}}function gr(e,t){return{lo:e|0,hi:t|0}}function _r(e,t){return t=~t,e?e=~e+1:t+=1,gr(e,t)}var vr=e=>{let t=String(e);return`0000000`.slice(t.length)+t};function yr(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 br(){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 xr(){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=>Kn(/^-?[0-9]+$/.test(e),`int64 invalid: ${e}`),n=e=>Kn(/^[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),fr(e)},uEnc(e){return typeof e!=`string`&&(e=e.toString()),n(e),fr(e)},dec(e,t){return pr(e,t)},uDec(e,t){return mr(e,t)}}}var Sr=xr(),j;(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`})(j||={});var Cr;(function(e){e[e.BIGINT=0]=`BIGINT`,e[e.STRING=1]=`STRING`})(Cr||={});function wr(e,t,n){if(t===n)return!0;if(e==j.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 j.UINT64:case j.FIXED64:case j.INT64:case j.SFIXED64:case j.SINT64:return t==n}return!1}function Tr(e,t){switch(e){case j.BOOL:return!1;case j.UINT64:case j.FIXED64:case j.INT64:case j.SFIXED64:case j.SINT64:return t==0?Sr.zero:`0`;case j.DOUBLE:case j.FLOAT:return 0;case j.BYTES:return new Uint8Array;case j.STRING:return``;default:return 0}}function Er(e,t){switch(e){case j.BOOL:return t===!1;case j.STRING:return t===``;case j.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return t==0}}var Dr;(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`})(Dr||={});var Or=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($n(e);e>127;)this.buf.push(e&127|128),e>>>=7;return this.buf.push(e),this}int32(e){return Qn(e),yr(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){er(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){$n(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){Qn(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return Qn(e),e=(e<<1^e>>31)>>>0,yr(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),r=Sr.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=Sr.uEnc(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(t)}int64(e){let t=Sr.enc(e);return ur(t.lo,t.hi,this.buf),this}sint64(e){let t=Sr.enc(e),n=t.hi>>31;return ur(t.lo<<1^n,(t.hi<<1|t.lo>>>31)^n,this.buf),this}uint64(e){let t=Sr.uEnc(e);return ur(t.lo,t.hi,this.buf),this}},kr=class{constructor(e,t){this.varint64=lr,this.uint32=br,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 Dr.Varint:for(;this.buf[this.pos++]&128;);break;case Dr.Bit64:this.pos+=4;case Dr.Bit32:this.pos+=4;break;case Dr.LengthDelimited:let n=this.uint32();this.pos+=n;break;case Dr.StartGroup:for(;;){let[e,n]=this.tag();if(n===Dr.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 Sr.dec(...this.varint64())}uint64(){return Sr.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),n=-(e&1);return e=(e>>>1|(t&1)<<31)^n,t=t>>>1^n,Sr.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 Sr.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return Sr.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 Ar(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 jr(e){let t=e.field.localName,n=Object.create(null);return n[t]=Mr(e),[n,()=>n[t]]}function Mr(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 Tr(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 Nr(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 Pr=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`.split(``),Fr=[];for(let e=0;e<Pr.length;e++)Fr[Pr[e].charCodeAt(0)]=e;Fr[45]=Pr.indexOf(`+`),Fr[95]=Pr.indexOf(`/`);var Ir={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=Fr[e.charCodeAt(t)],a===void 0)switch(e[t]){case`=`:i=0;case`
|
|
22
22
|
`: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+=Pr[r>>2],i=(r&3)<<4,n=1;break;case 1:t+=Pr[i|r>>4],i=(r&15)<<2,n=2;break;case 2:t+=Pr[i|r>>6],t+=Pr[r&63],n=0;break}return n&&(t+=Pr[i],t+=`=`,n==1&&(t+=`=`)),t}};function Lr(e,t,n){Br(t,e);let r=t.runtime.bin.makeReadOptions(n),i=Nr(e.getType().runtime.bin.listUnknownFields(e),t.field),[a,o]=jr(t);for(let e of i)t.runtime.bin.readField(a,r.readerFactory(e.data),t.field,e.wireType,r);return o()}function Rr(e,t,n,r){Br(t,e);let i=t.runtime.bin.makeReadOptions(r),a=t.runtime.bin.makeWriteOptions(r);if(zr(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 zr(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){Kn(e.extendee.typeName==t.getType().typeName,`extension ${e.typeName} can only be applied to message ${e.extendee.typeName}`)}function Vr(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:!Er(e.T,t[n]);case`message`:return t[n]!==void 0;case`map`:return Object.keys(t[n]).length>0}}function Hr(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?Tr(e.T,e.L):void 0;break;case`message`:t[n]=void 0;break}}function Ur(e,t){if(typeof e!=`object`||!e||!Object.getOwnPropertyNames(sr.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 Ur(t)||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}j.DOUBLE,j.FLOAT,j.INT64,j.UINT64,j.INT32,j.UINT32,j.BOOL,j.STRING,j.BYTES;var Gr={ignoreUnknownFields:!1},Kr={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function qr(e){return e?Object.assign(Object.assign({},Gr),e):Gr}function Jr(e){return e?Object.assign(Object.assign({},Kr),e):Kr}var Yr=Symbol(),Xr=Symbol();function Zr(){return{makeReadOptions:qr,makeWriteOptions:Jr,readMessage(e,t,n,r){if(t==null||Array.isArray(t)||typeof t!=`object`)throw Error(`cannot decode message ${e.typeName} from JSON: ${Qr(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)}$r(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]=jr(i);$r(e,s,i.field,n,i),Rr(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(!Vr(i,e)){if(i.req)throw`required field not set`;if(!t.emitDefaultValues||!ri(i))continue}let n=i.oneof?e[i.oneof.localName].value:e[i.localName],a=ii(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&&zr(e,o)){let n=Lr(e,o,t),i=ii(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 ti(e,t,n??Cr.BIGINT,!0)},writeScalar(e,t,n){if(t!==void 0&&(n||Er(e,t)))return oi(e,t)},debug:Qr}}function Qr(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 $r(e,t,n,r,i){let a=n.localName;if(n.repeated){if(Kn(n.kind!=`map`),t===null)return;if(!Array.isArray(t))throw Error(`cannot decode field ${i.typeName}.${n.name} from JSON: ${Qr(t)}`);let o=e[a];for(let e of t){if(e===null)throw Error(`cannot decode field ${i.typeName}.${n.name} from JSON: ${Qr(e)}`);switch(n.kind){case`message`:o.push(n.T.fromJson(e,r));break;case`enum`:let t=ni(n.T,e,r.ignoreUnknownFields,!0);t!==Xr&&o.push(t);break;case`scalar`:try{o.push(ti(n.T,e,n.L,!0))}catch(t){let r=`cannot decode field ${i.typeName}.${n.name} from JSON: ${Qr(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: ${Qr(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=ei(n.K,e)}catch(e){let r=`cannot decode map key for field ${i.typeName}.${n.name} from JSON: ${Qr(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=ni(n.V.T,a,r.ignoreUnknownFields,!0);e!==Xr&&(o[s]=e);break;case`scalar`:try{o[s]=ti(n.V.T,a,Cr.BIGINT,!0)}catch(e){let r=`cannot decode map value for field ${i.typeName}.${n.name} from JSON: ${Qr(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];Ur(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=ni(n.T,t,r.ignoreUnknownFields,!1);switch(c){case Yr:Hr(n,e);break;case Xr:break;default:e[a]=c;break}break;case`scalar`:try{let r=ti(n.T,t,n.L,!1);switch(r){case Yr:Hr(n,e);break;default:e[a]=r;break}}catch(e){let r=`cannot decode field ${i.typeName}.${n.name} from JSON: ${Qr(t)}`;throw e instanceof Error&&e.message.length>0&&(r+=`: ${e.message}`),Error(r)}break}}function ei(e,t){if(e===j.BOOL)switch(t){case`true`:t=!0;break;case`false`:t=!1;break}return ti(e,t,Cr.BIGINT,!0).toString()}function ti(e,t,n,r){if(t===null)return r?Tr(e,n):Yr;switch(e){case j.DOUBLE:case j.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==j.FLOAT&&er(r),r;case j.INT32:case j.FIXED32:case j.SFIXED32:case j.SINT32:case j.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==j.UINT32||e==j.FIXED32?$n(i):Qn(i),i;case j.INT64:case j.SFIXED64:case j.SINT64:if(typeof t!=`number`&&typeof t!=`string`)break;let a=Sr.parse(t);return n?a.toString():a;case j.FIXED64:case j.UINT64:if(typeof t!=`number`&&typeof t!=`string`)break;let o=Sr.uParse(t);return n?o.toString():o;case j.BOOL:if(typeof t!=`boolean`)break;return t;case j.STRING:if(typeof t!=`string`)break;return t;case j.BYTES:if(t===``)return new Uint8Array;if(typeof t!=`string`)break;return Ir.dec(t)}throw Error()}function ni(e,t,n,r){if(t===null)return e.typeName==`google.protobuf.NullValue`?0:r?e.values[0].no:Yr;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 Xr;break}throw Error(`cannot decode enum ${e.typeName} from JSON: ${Qr(t)}`)}function ri(e){return e.repeated||e.kind==`map`?!0:!(e.oneof||e.kind==`message`||e.opt||e.req)}function ii(e,t,n){if(e.kind==`map`){Kn(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()]=oi(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()]=ai(t,a,n.enumAsInteger);break}return n.emitDefaultValues||i.length>0?r:void 0}if(e.repeated){Kn(Array.isArray(t));let r=[];switch(e.kind){case`scalar`:for(let n=0;n<t.length;n++)r.push(oi(e.T,t[n]));break;case`enum`:for(let i=0;i<t.length;i++)r.push(ai(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 oi(e.T,t);case`enum`:return ai(e.T,t,n.enumAsInteger);case`message`:return Wr(e.T,t).toJson(n)}}function ai(e,t,n){return Kn(typeof t==`number`),e.typeName==`google.protobuf.NullValue`?null:n?t:e.findNumber(t)?.name??t}function oi(e,t){switch(e){case j.INT32:case j.SFIXED32:case j.SINT32:case j.FIXED32:case j.UINT32:return Kn(typeof t==`number`),t;case j.FLOAT:case j.DOUBLE:return Kn(typeof t==`number`),Number.isNaN(t)?`NaN`:t===1/0?`Infinity`:t===-1/0?`-Infinity`:t;case j.STRING:return Kn(typeof t==`string`),t;case j.BOOL:return Kn(typeof t==`boolean`),t;case j.UINT64:case j.FIXED64:case j.INT64:case j.SFIXED64:case j.SINT64:return Kn(typeof t==`bigint`||typeof t==`string`||typeof t==`number`),t.toString();case j.BYTES:return Kn(t instanceof Uint8Array),Ir.enc(t)}}var si=Symbol(`@bufbuild/protobuf/unknown-fields`),ci={readUnknownFields:!0,readerFactory:e=>new kr(e)},li={writeUnknownFields:!0,writerFactory:()=>new Or};function ui(e){return e?Object.assign(Object.assign({},ci),e):ci}function di(e){return e?Object.assign(Object.assign({},li),e):li}function fi(){return{makeReadOptions:ui,makeWriteOptions:di,listUnknownFields(e){return e[si]??[]},discardUnknownFields(e){delete e[si]},writeUnknownFields(e,t){let n=e[si];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[si])||(i[si]=[]),i[si].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==Dr.EndGroup));){let n=a.fields.find(s);if(!n){let n=t.skip(c,s);r.readUnknownFields&&this.onUnknownField(e,s,c,n);continue}pi(e,t,n,c,r)}if(i&&(c!=Dr.EndGroup||s!==n))throw Error(`invalid end group tag`)},readField:pi,writeMessage(e,t,n){let r=e.getType();for(let i of r.fields.byNumber()){if(!Vr(i,e)){if(i.req)throw Error(`cannot encode field ${r.typeName}.${i.name} to binary: required field not set`);continue}vi(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&&vi(e,t,n,r)}}}function pi(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`?j.INT32:n.T,c=_i;if(n.kind==`scalar`&&n.L>0&&(c=gi),a){let n=e[o];if(r==Dr.LengthDelimited&&s!=j.STRING&&s!=j.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(mi(t,new l,i,n)):Ur(e[o])?mi(t,e[o],i,n):(e[o]=mi(t,new l,i,n),l.fieldWrapper&&!n.oneof&&!n.repeated&&(e[o]=l.fieldWrapper.unwrapField(e[o])));break;case`map`:let[u,d]=hi(n,t,i);e[o][u]=d;break}}function mi(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 hi(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=_i(t,e.K);break;case 2:switch(e.V.kind){case`scalar`:o=_i(t,e.V.T);break;case`enum`:o=t.int32();break;case`message`:o=mi(t,new e.V.T,n,void 0);break}break}}if(a===void 0&&(a=Tr(e.K,Cr.BIGINT)),typeof a!=`string`&&typeof a!=`number`&&(a=a.toString()),o===void 0)switch(e.V.kind){case`scalar`:o=Tr(e.V.T,Cr.BIGINT);break;case`enum`:o=e.V.T.values[0].no;break;case`message`:o=new e.V.T;break}return[a,o]}function gi(e,t){let n=_i(e,t);return typeof n==`bigint`?n.toString():n}function _i(e,t){switch(t){case j.STRING:return e.string();case j.BOOL:return e.bool();case j.DOUBLE:return e.double();case j.FLOAT:return e.float();case j.INT32:return e.int32();case j.INT64:return e.int64();case j.UINT64:return e.uint64();case j.FIXED64:return e.fixed64();case j.BYTES:return e.bytes();case j.FIXED32:return e.fixed32();case j.SFIXED32:return e.sfixed32();case j.SFIXED64:return e.sfixed64();case j.SINT64:return e.sint64();case j.UINT32:return e.uint32();case j.SINT32:return e.sint32()}}function vi(e,t,n,r){Kn(t!==void 0);let i=e.repeated;switch(e.kind){case`scalar`:case`enum`:let a=e.kind==`enum`?j.INT32:e.T;if(i)if(Kn(Array.isArray(t)),e.packed)Si(n,a,e.no,t);else for(let r of t)xi(n,a,e.no,r);else xi(n,a,e.no,t);break;case`message`:if(i){Kn(Array.isArray(t));for(let i of t)bi(n,r,e,i)}else bi(n,r,e,t);break;case`map`:Kn(typeof t==`object`&&!!t);for(let[i,a]of Object.entries(t))yi(n,r,e,i,a);break}}function yi(e,t,n,r,i){e.tag(n.no,Dr.LengthDelimited),e.fork();let a=r;switch(n.K){case j.INT32:case j.FIXED32:case j.UINT32:case j.SFIXED32:case j.SINT32:a=Number.parseInt(r);break;case j.BOOL:Kn(r==`true`||r==`false`),a=r==`true`;break}switch(xi(e,n.K,1,a),n.V.kind){case`scalar`:xi(e,n.V.T,2,i);break;case`enum`:xi(e,j.INT32,2,i);break;case`message`:Kn(i!==void 0),e.tag(2,Dr.LengthDelimited).bytes(i.toBinary(t));break}e.join()}function bi(e,t,n,r){let i=Wr(n.T,r);n.delimited?e.tag(n.no,Dr.StartGroup).raw(i.toBinary(t)).tag(n.no,Dr.EndGroup):e.tag(n.no,Dr.LengthDelimited).bytes(i.toBinary(t))}function xi(e,t,n,r){Kn(r!==void 0);let[i,a]=Ci(t);e.tag(n,i)[a](r)}function Si(e,t,n,r){if(!r.length)return;e.tag(n,Dr.LengthDelimited).fork();let[,i]=Ci(t);for(let t=0;t<r.length;t++)e[i](r[t]);e.join()}function Ci(e){let t=Dr.Varint;switch(e){case j.BYTES:case j.STRING:t=Dr.LengthDelimited;break;case j.DOUBLE:case j.FIXED64:case j.SFIXED64:t=Dr.Bit64;break;case j.FIXED32:case j.SFIXED32:case j.FLOAT:t=Dr.Bit32;break}let n=j[e].toLowerCase();return[t,n]}function wi(){return{setEnumType:rr,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`&&!Ur(o,t.T)?o=new t.T(o):t&&t.kind===`scalar`&&t.T===j.BYTES&&(o=Ei(o)),i[n]={case:e,value:o};break;case`scalar`:case`enum`:let s=a[n];r.T===j.BYTES&&(s=r.repeated?s.map(Ei):Ei(s)),i[n]=s;break;case`map`:switch(r.V.kind){case`scalar`:case`enum`:if(r.V.T===j.BYTES)for(let[e,t]of Object.entries(a[n]))i[n][e]=Ei(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=>Ur(e,c)?e:new c(e));else{let e=a[n];c.fieldWrapper?c.typeName===`google.protobuf.BytesValue`?i[n]=Ei(e):i[n]=e:i[n]=Ur(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)=>wr(e.T,t,i[n]));case`enum`:return r.every((e,t)=>wr(j.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&&!Ur(t)&&(t=e.T.fieldWrapper.wrapField(t)),n!==void 0&&!Ur(n)&&(n=e.T.fieldWrapper.wrapField(n))),e.T.equals(t,n);case`enum`:return wr(j.INT32,r,i);case`scalar`:return wr(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 wr(j.INT32,r.value,i.value);case`scalar`:return wr(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=>wr(j.INT32,r[e],i[e]));case`scalar`:let n=e.V.T;return o.every(e=>wr(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(Ti);else if(n.kind==`map`){i=r[n.localName];for(let[e,n]of Object.entries(t))i[e]=Ti(n)}else i=n.kind==`oneof`?n.findField(t.case)?{case:t.case,value:Ti(t.value)}:{case:void 0}:Ti(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 Ti(e){if(e===void 0)return e;if(Ur(e))return e.clone();if(e instanceof Uint8Array){let t=new Uint8Array(e.byteLength);return t.set(e),t}return e}function Ei(e){return e instanceof Uint8Array?e:new Uint8Array(e)}function Di(e,t,n){return{syntax:e,json:Zr(),bin:fi(),util:Object.assign(Object.assign({},wi()),{newFieldList:t,initFields:n}),makeMessageType(e,t,n){return cr(this,e,t,n)},makeEnum:ar,makeEnumType:ir,getEnumType:nr,makeExtension(e,t,n){return Ar(this,e,t,n)}}}var Oi=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 ki(e,t){let n=Mi(e);return t?n:Li(Ii(n))}function Ai(e){return ki(e,!1)}var ji=Mi;function Mi(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 Ni=new Set([`constructor`,`toString`,`toJSON`,`valueOf`]),Pi=new Set([`getType`,`clone`,`equals`,`fromBinary`,`fromJson`,`fromJsonString`,`toBinary`,`toJson`,`toJsonString`,`toObject`]),Fi=e=>`${e}\$`,Ii=e=>Pi.has(e)?Fi(e):e,Li=e=>Ni.has(e)?Fi(e):e,Ri=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=Ai(e)}addField(e){Kn(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 zi(e,t){let n=[],r;for(let t of typeof e==`function`?e():e){let e=t;if(e.localName=ki(t.name,t.oneof!==void 0),e.jsonName=t.jsonName??ji(t.name),e.repeated=t.repeated??!1,t.kind==`scalar`&&(e.L=t.L??Cr.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!=j.BYTES&&t.T!=j.STRING),t.oneof!==void 0){let n=typeof t.oneof==`string`?t.oneof:t.oneof.name;(!r||r.name!=n)&&(r=new Ri(n)),e.oneof=r,r.addField(e)}n.push(e)}return n}var M=Di(`proto3`,e=>new Oi(e,e=>zi(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]=Tr(t.T,t.L);break}}}),N=class e extends sr{constructor(e){super(),this.seconds=Sr.zero,this.nanos=0,M.util.initPartial(e,this)}fromJson(e,t){if(typeof e!=`string`)throw Error(`cannot decode google.protobuf.Timestamp from JSON: ${M.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=Sr.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:Sr.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 M.util.equals(e,t,n)}};N.runtime=M,N.typeName=`google.protobuf.Timestamp`,N.fields=M.util.newFieldList(()=>[{no:1,name:`seconds`,kind:`scalar`,T:3},{no:2,name:`nanos`,kind:`scalar`,T:5}]);var P=M.makeMessageType(`livekit.MetricsBatch`,()=>[{no:1,name:`timestamp_ms`,kind:`scalar`,T:3},{no:2,name:`normalized_timestamp`,kind:`message`,T:N},{no:3,name:`str_data`,kind:`scalar`,T:9,repeated:!0},{no:4,name:`time_series`,kind:`message`,T:Bi,repeated:!0},{no:5,name:`events`,kind:`message`,T:Hi,repeated:!0}]),Bi=M.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:Vi,repeated:!0},{no:5,name:`rid`,kind:`scalar`,T:13}]),Vi=M.makeMessageType(`livekit.MetricSample`,()=>[{no:1,name:`timestamp_ms`,kind:`scalar`,T:3},{no:2,name:`normalized_timestamp`,kind:`message`,T:N},{no:3,name:`value`,kind:`scalar`,T:2}]),Hi=M.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:N},{no:7,name:`normalized_end_timestamp`,kind:`message`,T:N,opt:!0},{no:8,name:`metadata`,kind:`scalar`,T:9},{no:9,name:`rid`,kind:`scalar`,T:13}]),Ui=M.makeEnum(`livekit.BackupCodecPolicy`,[{no:0,name:`PREFER_REGRESSION`},{no:1,name:`SIMULCAST`},{no:2,name:`REGRESSION`}]),Wi=M.makeEnum(`livekit.TrackType`,[{no:0,name:`AUDIO`},{no:1,name:`VIDEO`},{no:2,name:`DATA`}]),Gi=M.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`}]),Ki=M.makeEnum(`livekit.VideoQuality`,[{no:0,name:`LOW`},{no:1,name:`MEDIUM`},{no:2,name:`HIGH`},{no:3,name:`OFF`}]),qi=M.makeEnum(`livekit.ConnectionQuality`,[{no:0,name:`POOR`},{no:1,name:`GOOD`},{no:2,name:`EXCELLENT`},{no:3,name:`LOST`}]),Ji=M.makeEnum(`livekit.ClientConfigSetting`,[{no:0,name:`UNSET`},{no:1,name:`DISABLED`},{no:2,name:`ENABLED`}]),Yi=M.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`}]),Xi=M.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`}]),Zi=M.makeEnum(`livekit.SubscriptionError`,[{no:0,name:`SE_UNKNOWN`},{no:1,name:`SE_CODEC_UNSUPPORTED`},{no:2,name:`SE_TRACK_NOTFOUND`}]),Qi=M.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`}]),$i=M.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:ea,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:Fa}]),ea=M.makeMessageType(`livekit.Codec`,()=>[{no:1,name:`mime`,kind:`scalar`,T:9},{no:2,name:`fmtp_line`,kind:`scalar`,T:9}]),ta=M.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:M.getEnumType(Gi),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}]),na=M.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:M.getEnumType(ra)},{no:4,name:`tracks`,kind:`message`,T:sa,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:ta},{no:12,name:`region`,kind:`scalar`,T:9},{no:13,name:`is_publisher`,kind:`scalar`,T:8},{no:14,name:`kind`,kind:`enum`,T:M.getEnumType(ia)},{no:15,name:`attributes`,kind:`map`,K:9,V:{kind:`scalar`,T:9}},{no:16,name:`disconnect_reason`,kind:`enum`,T:M.getEnumType(Yi)},{no:18,name:`kind_details`,kind:`enum`,T:M.getEnumType(aa),repeated:!0},{no:19,name:`data_tracks`,kind:`message`,T:ca,repeated:!0}]),ra=M.makeEnum(`livekit.ParticipantInfo.State`,[{no:0,name:`JOINING`},{no:1,name:`JOINED`},{no:2,name:`ACTIVE`},{no:3,name:`DISCONNECTED`}]),ia=M.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`}]),aa=M.makeEnum(`livekit.ParticipantInfo.KindDetail`,[{no:0,name:`CLOUD_AGENT`},{no:1,name:`FORWARDED`},{no:2,name:`CONNECTOR_WHATSAPP`},{no:3,name:`CONNECTOR_TWILIO`},{no:4,name:`BRIDGE_RTSP`}]),F=M.makeEnum(`livekit.Encryption.Type`,[{no:0,name:`NONE`},{no:1,name:`GCM`},{no:2,name:`CUSTOM`}]),oa=M.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:ua,repeated:!0},{no:5,name:`video_layer_mode`,kind:`enum`,T:M.getEnumType(da)},{no:6,name:`sdp_cid`,kind:`scalar`,T:9}]),sa=M.makeMessageType(`livekit.TrackInfo`,()=>[{no:1,name:`sid`,kind:`scalar`,T:9},{no:2,name:`type`,kind:`enum`,T:M.getEnumType(Wi)},{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:M.getEnumType(Gi)},{no:10,name:`layers`,kind:`message`,T:ua,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:oa,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:M.getEnumType(F)},{no:17,name:`stream`,kind:`scalar`,T:9},{no:18,name:`version`,kind:`message`,T:Fa},{no:19,name:`audio_features`,kind:`enum`,T:M.getEnumType(Qi),repeated:!0},{no:20,name:`backup_codec_policy`,kind:`enum`,T:M.getEnumType(Ui)}]),ca=M.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:M.getEnumType(F)}]),la=M.makeMessageType(`livekit.DataTrackSubscriptionOptions`,()=>[{no:1,name:`target_fps`,kind:`scalar`,T:13,opt:!0}]),ua=M.makeMessageType(`livekit.VideoLayer`,()=>[{no:1,name:`quality`,kind:`enum`,T:M.getEnumType(Ki)},{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}]),da=M.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`}]),fa=M.makeMessageType(`livekit.DataPacket`,()=>[{no:1,name:`kind`,kind:`enum`,T:M.getEnumType(pa)},{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:va,oneof:`value`},{no:3,name:`speaker`,kind:`message`,T:ga,oneof:`value`},{no:6,name:`sip_dtmf`,kind:`message`,T:ya,oneof:`value`},{no:7,name:`transcription`,kind:`message`,T:ba,oneof:`value`},{no:8,name:`metrics`,kind:`message`,T:P,oneof:`value`},{no:9,name:`chat_message`,kind:`message`,T:Sa,oneof:`value`},{no:10,name:`rpc_request`,kind:`message`,T:Ca,oneof:`value`},{no:11,name:`rpc_ack`,kind:`message`,T:wa,oneof:`value`},{no:12,name:`rpc_response`,kind:`message`,T:Ta,oneof:`value`},{no:13,name:`stream_header`,kind:`message`,T:za,oneof:`value`},{no:14,name:`stream_chunk`,kind:`message`,T:Ba,oneof:`value`},{no:15,name:`stream_trailer`,kind:`message`,T:Va,oneof:`value`},{no:18,name:`encrypted_packet`,kind:`message`,T:ma,oneof:`value`},{no:16,name:`sequence`,kind:`scalar`,T:13},{no:17,name:`participant_sid`,kind:`scalar`,T:9}]),pa=M.makeEnum(`livekit.DataPacket.Kind`,[{no:0,name:`RELIABLE`},{no:1,name:`LOSSY`}]),ma=M.makeMessageType(`livekit.EncryptedPacket`,()=>[{no:1,name:`encryption_type`,kind:`enum`,T:M.getEnumType(F)},{no:2,name:`iv`,kind:`scalar`,T:12},{no:3,name:`key_index`,kind:`scalar`,T:13},{no:4,name:`encrypted_value`,kind:`scalar`,T:12}]),ha=M.makeMessageType(`livekit.EncryptedPacketPayload`,()=>[{no:1,name:`user`,kind:`message`,T:va,oneof:`value`},{no:3,name:`chat_message`,kind:`message`,T:Sa,oneof:`value`},{no:4,name:`rpc_request`,kind:`message`,T:Ca,oneof:`value`},{no:5,name:`rpc_ack`,kind:`message`,T:wa,oneof:`value`},{no:6,name:`rpc_response`,kind:`message`,T:Ta,oneof:`value`},{no:7,name:`stream_header`,kind:`message`,T:za,oneof:`value`},{no:8,name:`stream_chunk`,kind:`message`,T:Ba,oneof:`value`},{no:9,name:`stream_trailer`,kind:`message`,T:Va,oneof:`value`}]),ga=M.makeMessageType(`livekit.ActiveSpeakerUpdate`,()=>[{no:1,name:`speakers`,kind:`message`,T:_a,repeated:!0}]),_a=M.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}]),va=M.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}]),ya=M.makeMessageType(`livekit.SipDTMF`,()=>[{no:3,name:`code`,kind:`scalar`,T:13},{no:4,name:`digit`,kind:`scalar`,T:9}]),ba=M.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:xa,repeated:!0}]),xa=M.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}]),Sa=M.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}]),Ca=M.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}]),wa=M.makeMessageType(`livekit.RpcAck`,()=>[{no:1,name:`request_id`,kind:`scalar`,T:9}]),Ta=M.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:Ea,oneof:`value`}]),Ea=M.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}]),Da=M.makeMessageType(`livekit.ParticipantTracks`,()=>[{no:1,name:`participant_sid`,kind:`scalar`,T:9},{no:2,name:`track_sids`,kind:`scalar`,T:9,repeated:!0}]),Oa=M.makeMessageType(`livekit.ServerInfo`,()=>[{no:1,name:`edition`,kind:`enum`,T:M.getEnumType(ka)},{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}]),ka=M.makeEnum(`livekit.ServerInfo.Edition`,[{no:0,name:`Standard`},{no:1,name:`Cloud`}]),Aa=M.makeMessageType(`livekit.ClientInfo`,()=>[{no:1,name:`sdk`,kind:`enum`,T:M.getEnumType(ja)},{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}]),ja=M.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`}]),Ma=M.makeMessageType(`livekit.ClientConfiguration`,()=>[{no:1,name:`video`,kind:`message`,T:Na},{no:2,name:`screen`,kind:`message`,T:Na},{no:3,name:`resume_connection`,kind:`enum`,T:M.getEnumType(Ji)},{no:4,name:`disabled_codecs`,kind:`message`,T:Pa},{no:5,name:`force_relay`,kind:`enum`,T:M.getEnumType(Ji)}]),Na=M.makeMessageType(`livekit.VideoConfiguration`,()=>[{no:1,name:`hardware_encoder`,kind:`enum`,T:M.getEnumType(Ji)}]),Pa=M.makeMessageType(`livekit.DisabledCodecs`,()=>[{no:1,name:`codecs`,kind:`message`,T:ea,repeated:!0},{no:2,name:`publish`,kind:`message`,T:ea,repeated:!0}]),Fa=M.makeMessageType(`livekit.TimedVersion`,()=>[{no:1,name:`unix_micro`,kind:`scalar`,T:3},{no:2,name:`ticks`,kind:`scalar`,T:5}]),Ia=M.makeEnum(`livekit.DataStream.OperationType`,[{no:0,name:`CREATE`},{no:1,name:`UPDATE`},{no:2,name:`DELETE`},{no:3,name:`REACTION`}]),La=M.makeMessageType(`livekit.DataStream.TextHeader`,()=>[{no:1,name:`operation_type`,kind:`enum`,T:M.getEnumType(Ia)},{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`}),Ra=M.makeMessageType(`livekit.DataStream.ByteHeader`,()=>[{no:1,name:`name`,kind:`scalar`,T:9}],{localName:`DataStream_ByteHeader`}),za=M.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:M.getEnumType(F)},{no:8,name:`attributes`,kind:`map`,K:9,V:{kind:`scalar`,T:9}},{no:9,name:`text_header`,kind:`message`,T:La,oneof:`content_header`},{no:10,name:`byte_header`,kind:`message`,T:Ra,oneof:`content_header`}],{localName:`DataStream_Header`}),Ba=M.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`}),Va=M.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`}),Ha=M.makeMessageType(`livekit.SubscribedAudioCodec`,()=>[{no:1,name:`codec`,kind:`scalar`,T:9},{no:2,name:`enabled`,kind:`scalar`,T:8}]),Ua=M.makeEnum(`livekit.SignalTarget`,[{no:0,name:`PUBLISHER`},{no:1,name:`SUBSCRIBER`}]),Wa=M.makeEnum(`livekit.StreamState`,[{no:0,name:`ACTIVE`},{no:1,name:`PAUSED`}]),Ga=M.makeEnum(`livekit.CandidateProtocol`,[{no:0,name:`UDP`},{no:1,name:`TCP`},{no:2,name:`TLS`}]),Ka=M.makeMessageType(`livekit.SignalRequest`,()=>[{no:1,name:`offer`,kind:`message`,T:co,oneof:`message`},{no:2,name:`answer`,kind:`message`,T:co,oneof:`message`},{no:3,name:`trickle`,kind:`message`,T:no,oneof:`message`},{no:4,name:`add_track`,kind:`message`,T:Ya,oneof:`message`},{no:5,name:`mute`,kind:`message`,T:ro,oneof:`message`},{no:6,name:`subscription`,kind:`message`,T:uo,oneof:`message`},{no:7,name:`track_setting`,kind:`message`,T:mo,oneof:`message`},{no:8,name:`leave`,kind:`message`,T:_o,oneof:`message`},{no:10,name:`update_layers`,kind:`message`,T:vo,oneof:`message`},{no:11,name:`subscription_permission`,kind:`message`,T:Mo,oneof:`message`},{no:12,name:`sync_state`,kind:`message`,T:Fo,oneof:`message`},{no:13,name:`simulate`,kind:`message`,T:Ro,oneof:`message`},{no:14,name:`ping`,kind:`scalar`,T:3,oneof:`message`},{no:15,name:`update_metadata`,kind:`message`,T:yo,oneof:`message`},{no:16,name:`ping_req`,kind:`message`,T:zo,oneof:`message`},{no:17,name:`update_audio_track`,kind:`message`,T:ho,oneof:`message`},{no:18,name:`update_video_track`,kind:`message`,T:go,oneof:`message`},{no:19,name:`publish_data_track_request`,kind:`message`,T:Xa,oneof:`message`},{no:20,name:`unpublish_data_track_request`,kind:`message`,T:Qa,oneof:`message`},{no:21,name:`update_data_subscription`,kind:`message`,T:fo,oneof:`message`}]),qa=M.makeMessageType(`livekit.SignalResponse`,()=>[{no:1,name:`join`,kind:`message`,T:io,oneof:`message`},{no:2,name:`answer`,kind:`message`,T:co,oneof:`message`},{no:3,name:`offer`,kind:`message`,T:co,oneof:`message`},{no:4,name:`trickle`,kind:`message`,T:no,oneof:`message`},{no:5,name:`update`,kind:`message`,T:lo,oneof:`message`},{no:6,name:`track_published`,kind:`message`,T:oo,oneof:`message`},{no:8,name:`leave`,kind:`message`,T:_o,oneof:`message`},{no:9,name:`mute`,kind:`message`,T:ro,oneof:`message`},{no:10,name:`speakers_changed`,kind:`message`,T:xo,oneof:`message`},{no:11,name:`room_update`,kind:`message`,T:So,oneof:`message`},{no:12,name:`connection_quality`,kind:`message`,T:wo,oneof:`message`},{no:13,name:`stream_state_update`,kind:`message`,T:Eo,oneof:`message`},{no:14,name:`subscribed_quality_update`,kind:`message`,T:ko,oneof:`message`},{no:15,name:`subscription_permission_update`,kind:`message`,T:No,oneof:`message`},{no:16,name:`refresh_token`,kind:`scalar`,T:9,oneof:`message`},{no:17,name:`track_unpublished`,kind:`message`,T:so,oneof:`message`},{no:18,name:`pong`,kind:`scalar`,T:3,oneof:`message`},{no:19,name:`reconnect`,kind:`message`,T:ao,oneof:`message`},{no:20,name:`pong_resp`,kind:`message`,T:Bo,oneof:`message`},{no:21,name:`subscription_response`,kind:`message`,T:Uo,oneof:`message`},{no:22,name:`request_response`,kind:`message`,T:Wo,oneof:`message`},{no:23,name:`track_subscribed`,kind:`message`,T:Ko,oneof:`message`},{no:24,name:`room_moved`,kind:`message`,T:Po,oneof:`message`},{no:25,name:`media_sections_requirement`,kind:`message`,T:Zo,oneof:`message`},{no:26,name:`subscribed_audio_codec_update`,kind:`message`,T:Ao,oneof:`message`},{no:27,name:`publish_data_track_response`,kind:`message`,T:Za,oneof:`message`},{no:28,name:`unpublish_data_track_response`,kind:`message`,T:$a,oneof:`message`},{no:29,name:`data_track_subscriber_handles`,kind:`message`,T:eo,oneof:`message`}]),Ja=M.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:ua,repeated:!0},{no:5,name:`video_layer_mode`,kind:`enum`,T:M.getEnumType(da)}]),Ya=M.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:M.getEnumType(Wi)},{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:M.getEnumType(Gi)},{no:9,name:`layers`,kind:`message`,T:ua,repeated:!0},{no:10,name:`simulcast_codecs`,kind:`message`,T:Ja,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:M.getEnumType(F)},{no:15,name:`stream`,kind:`scalar`,T:9},{no:16,name:`backup_codec_policy`,kind:`enum`,T:M.getEnumType(Ui)},{no:17,name:`audio_features`,kind:`enum`,T:M.getEnumType(Qi),repeated:!0}]),Xa=M.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:M.getEnumType(F)}]),Za=M.makeMessageType(`livekit.PublishDataTrackResponse`,()=>[{no:1,name:`info`,kind:`message`,T:ca}]),Qa=M.makeMessageType(`livekit.UnpublishDataTrackRequest`,()=>[{no:1,name:`pub_handle`,kind:`scalar`,T:13}]),$a=M.makeMessageType(`livekit.UnpublishDataTrackResponse`,()=>[{no:1,name:`info`,kind:`message`,T:ca}]),eo=M.makeMessageType(`livekit.DataTrackSubscriberHandles`,()=>[{no:1,name:`sub_handles`,kind:`map`,K:13,V:{kind:`message`,T:to}}]),to=M.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`}),no=M.makeMessageType(`livekit.TrickleRequest`,()=>[{no:1,name:`candidateInit`,kind:`scalar`,T:9},{no:2,name:`target`,kind:`enum`,T:M.getEnumType(Ua)},{no:3,name:`final`,kind:`scalar`,T:8}]),ro=M.makeMessageType(`livekit.MuteTrackRequest`,()=>[{no:1,name:`sid`,kind:`scalar`,T:9},{no:2,name:`muted`,kind:`scalar`,T:8}]),io=M.makeMessageType(`livekit.JoinResponse`,()=>[{no:1,name:`room`,kind:`message`,T:$i},{no:2,name:`participant`,kind:`message`,T:na},{no:3,name:`other_participants`,kind:`message`,T:na,repeated:!0},{no:4,name:`server_version`,kind:`scalar`,T:9},{no:5,name:`ice_servers`,kind:`message`,T:bo,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:Ma},{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:Oa},{no:13,name:`sif_trailer`,kind:`scalar`,T:12},{no:14,name:`enabled_publish_codecs`,kind:`message`,T:ea,repeated:!0},{no:15,name:`fast_publish`,kind:`scalar`,T:8}]),ao=M.makeMessageType(`livekit.ReconnectResponse`,()=>[{no:1,name:`ice_servers`,kind:`message`,T:bo,repeated:!0},{no:2,name:`client_configuration`,kind:`message`,T:Ma},{no:3,name:`server_info`,kind:`message`,T:Oa},{no:4,name:`last_message_seq`,kind:`scalar`,T:13}]),oo=M.makeMessageType(`livekit.TrackPublishedResponse`,()=>[{no:1,name:`cid`,kind:`scalar`,T:9},{no:2,name:`track`,kind:`message`,T:sa}]),so=M.makeMessageType(`livekit.TrackUnpublishedResponse`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9}]),co=M.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}}]),lo=M.makeMessageType(`livekit.ParticipantUpdate`,()=>[{no:1,name:`participants`,kind:`message`,T:na,repeated:!0}]),uo=M.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:Da,repeated:!0}]),fo=M.makeMessageType(`livekit.UpdateDataSubscription`,()=>[{no:1,name:`updates`,kind:`message`,T:po,repeated:!0}]),po=M.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:la}],{localName:`UpdateDataSubscription_Update`}),mo=M.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:M.getEnumType(Ki)},{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}]),ho=M.makeMessageType(`livekit.UpdateLocalAudioTrack`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`features`,kind:`enum`,T:M.getEnumType(Qi),repeated:!0}]),go=M.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}]),_o=M.makeMessageType(`livekit.LeaveRequest`,()=>[{no:1,name:`can_reconnect`,kind:`scalar`,T:8},{no:2,name:`reason`,kind:`enum`,T:M.getEnumType(Yi)},{no:3,name:`action`,kind:`enum`,T:M.getEnumType(I)},{no:4,name:`regions`,kind:`message`,T:Vo}]),I=M.makeEnum(`livekit.LeaveRequest.Action`,[{no:0,name:`DISCONNECT`},{no:1,name:`RESUME`},{no:2,name:`RECONNECT`}]),vo=M.makeMessageType(`livekit.UpdateVideoLayers`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`layers`,kind:`message`,T:ua,repeated:!0}]),yo=M.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}]),bo=M.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}]),xo=M.makeMessageType(`livekit.SpeakersChanged`,()=>[{no:1,name:`speakers`,kind:`message`,T:_a,repeated:!0}]),So=M.makeMessageType(`livekit.RoomUpdate`,()=>[{no:1,name:`room`,kind:`message`,T:$i}]),Co=M.makeMessageType(`livekit.ConnectionQualityInfo`,()=>[{no:1,name:`participant_sid`,kind:`scalar`,T:9},{no:2,name:`quality`,kind:`enum`,T:M.getEnumType(qi)},{no:3,name:`score`,kind:`scalar`,T:2}]),wo=M.makeMessageType(`livekit.ConnectionQualityUpdate`,()=>[{no:1,name:`updates`,kind:`message`,T:Co,repeated:!0}]),To=M.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:M.getEnumType(Wa)}]),Eo=M.makeMessageType(`livekit.StreamStateUpdate`,()=>[{no:1,name:`stream_states`,kind:`message`,T:To,repeated:!0}]),Do=M.makeMessageType(`livekit.SubscribedQuality`,()=>[{no:1,name:`quality`,kind:`enum`,T:M.getEnumType(Ki)},{no:2,name:`enabled`,kind:`scalar`,T:8}]),Oo=M.makeMessageType(`livekit.SubscribedCodec`,()=>[{no:1,name:`codec`,kind:`scalar`,T:9},{no:2,name:`qualities`,kind:`message`,T:Do,repeated:!0}]),ko=M.makeMessageType(`livekit.SubscribedQualityUpdate`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`subscribed_qualities`,kind:`message`,T:Do,repeated:!0},{no:3,name:`subscribed_codecs`,kind:`message`,T:Oo,repeated:!0}]),Ao=M.makeMessageType(`livekit.SubscribedAudioCodecUpdate`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`subscribed_audio_codecs`,kind:`message`,T:Ha,repeated:!0}]),jo=M.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}]),Mo=M.makeMessageType(`livekit.SubscriptionPermission`,()=>[{no:1,name:`all_participants`,kind:`scalar`,T:8},{no:2,name:`track_permissions`,kind:`message`,T:jo,repeated:!0}]),No=M.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}]),Po=M.makeMessageType(`livekit.RoomMovedResponse`,()=>[{no:1,name:`room`,kind:`message`,T:$i},{no:2,name:`token`,kind:`scalar`,T:9},{no:3,name:`participant`,kind:`message`,T:na},{no:4,name:`other_participants`,kind:`message`,T:na,repeated:!0}]),Fo=M.makeMessageType(`livekit.SyncState`,()=>[{no:1,name:`answer`,kind:`message`,T:co},{no:2,name:`subscription`,kind:`message`,T:uo},{no:3,name:`publish_tracks`,kind:`message`,T:oo,repeated:!0},{no:4,name:`data_channels`,kind:`message`,T:Lo,repeated:!0},{no:5,name:`offer`,kind:`message`,T:co},{no:6,name:`track_sids_disabled`,kind:`scalar`,T:9,repeated:!0},{no:7,name:`datachannel_receive_states`,kind:`message`,T:Io,repeated:!0},{no:8,name:`publish_data_tracks`,kind:`message`,T:Za,repeated:!0}]),Io=M.makeMessageType(`livekit.DataChannelReceiveState`,()=>[{no:1,name:`publisher_sid`,kind:`scalar`,T:9},{no:2,name:`last_seq`,kind:`scalar`,T:13}]),Lo=M.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:M.getEnumType(Ua)}]),Ro=M.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:M.getEnumType(Ga),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`}]),zo=M.makeMessageType(`livekit.Ping`,()=>[{no:1,name:`timestamp`,kind:`scalar`,T:3},{no:2,name:`rtt`,kind:`scalar`,T:3}]),Bo=M.makeMessageType(`livekit.Pong`,()=>[{no:1,name:`last_ping_timestamp`,kind:`scalar`,T:3},{no:2,name:`timestamp`,kind:`scalar`,T:3}]),Vo=M.makeMessageType(`livekit.RegionSettings`,()=>[{no:1,name:`regions`,kind:`message`,T:Ho,repeated:!0}]),Ho=M.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}]),Uo=M.makeMessageType(`livekit.SubscriptionResponse`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`err`,kind:`enum`,T:M.getEnumType(Zi)}]),Wo=M.makeMessageType(`livekit.RequestResponse`,()=>[{no:1,name:`request_id`,kind:`scalar`,T:13},{no:2,name:`reason`,kind:`enum`,T:M.getEnumType(Go)},{no:3,name:`message`,kind:`scalar`,T:9},{no:4,name:`trickle`,kind:`message`,T:no,oneof:`request`},{no:5,name:`add_track`,kind:`message`,T:Ya,oneof:`request`},{no:6,name:`mute`,kind:`message`,T:ro,oneof:`request`},{no:7,name:`update_metadata`,kind:`message`,T:yo,oneof:`request`},{no:8,name:`update_audio_track`,kind:`message`,T:ho,oneof:`request`},{no:9,name:`update_video_track`,kind:`message`,T:go,oneof:`request`},{no:10,name:`publish_data_track`,kind:`message`,T:Xa,oneof:`request`},{no:11,name:`unpublish_data_track`,kind:`message`,T:Qa,oneof:`request`}]),Go=M.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`}]),Ko=M.makeMessageType(`livekit.TrackSubscribed`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9}]),qo=M.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}]),Jo=M.makeMessageType(`livekit.JoinRequest`,()=>[{no:1,name:`client_info`,kind:`message`,T:Aa},{no:2,name:`connection_settings`,kind:`message`,T:qo},{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:Ya,repeated:!0},{no:6,name:`publisher_offer`,kind:`message`,T:co},{no:7,name:`reconnect`,kind:`scalar`,T:8},{no:8,name:`reconnect_reason`,kind:`enum`,T:M.getEnumType(Xi)},{no:9,name:`participant_sid`,kind:`scalar`,T:9},{no:10,name:`sync_state`,kind:`message`,T:Fo}]),Yo=M.makeMessageType(`livekit.WrappedJoinRequest`,()=>[{no:1,name:`compression`,kind:`enum`,T:M.getEnumType(Xo)},{no:2,name:`join_request`,kind:`scalar`,T:12}]),Xo=M.makeEnum(`livekit.WrappedJoinRequest.Compression`,[{no:0,name:`NONE`},{no:1,name:`GZIP`}]),Zo=M.makeMessageType(`livekit.MediaSectionsRequirement`,()=>[{no:1,name:`num_audios`,kind:`scalar`,T:13},{no:2,name:`num_videos`,kind:`scalar`,T:13}]);function Qo(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,`default`)?e.default:e}var $o={exports:{}},es=$o.exports,ts;function ns(){return ts?$o.exports:(ts=1,(function(e){(function(t,n){e.exports?e.exports=n():t.log=n()})(es,function(){var e=function(){},t=`undefined`,n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),r=[`trace`,`debug`,`info`,`warn`,`error`],i={},a=null;function o(e,t){var n=e[t];if(typeof n.bind==`function`)return n.bind(e);try{return Function.prototype.bind.call(n,e)}catch{return function(){return Function.prototype.apply.apply(n,[e,arguments])}}}function s(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(r){return r===`debug`&&(r=`log`),typeof console===t?!1:r===`trace`&&n?s:console[r]===void 0?console.log===void 0?e:o(console,`log`):o(console,r)}function l(){for(var n=this.getLevel(),i=0;i<r.length;i++){var a=r[i];this[a]=i<n?e:this.methodFactory(a,n,this.name)}if(this.log=this.debug,typeof console===t&&n<this.levels.SILENT)return`No console available for logging`}function u(e){return function(){typeof console!==t&&(l.call(this),this[e].apply(this,arguments))}}function d(e,t,n){return c(e)||u.apply(this,arguments)}function f(e,n){var o=this,s,c,u,f=`loglevel`;typeof e==`string`?f+=`:`+e:typeof e==`symbol`&&(f=void 0);function p(e){var n=(r[e]||`silent`).toUpperCase();if(!(typeof window===t||!f)){try{window.localStorage[f]=n;return}catch{}try{window.document.cookie=encodeURIComponent(f)+`=`+n+`;`}catch{}}}function m(){var e;if(!(typeof window===t||!f)){try{e=window.localStorage[f]}catch{}if(typeof e===t)try{var n=window.document.cookie,r=encodeURIComponent(f),i=n.indexOf(r+`=`);i!==-1&&(e=/^([^;]+)/.exec(n.slice(i+r.length+1))[1])}catch{}return o.levels[e]===void 0&&(e=void 0),e}}function h(){if(!(typeof window===t||!f)){try{window.localStorage.removeItem(f)}catch{}try{window.document.cookie=encodeURIComponent(f)+`=; expires=Thu, 01 Jan 1970 00:00:00 UTC`}catch{}}}function g(e){var t=e;if(typeof t==`string`&&o.levels[t.toUpperCase()]!==void 0&&(t=o.levels[t.toUpperCase()]),typeof t==`number`&&t>=0&&t<=o.levels.SILENT)return t;throw TypeError(`log.setLevel() called with invalid level: `+e)}o.name=e,o.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},o.methodFactory=n||d,o.getLevel=function(){return u??c??s},o.setLevel=function(e,t){return u=g(e),t!==!1&&p(u),l.call(o)},o.setDefaultLevel=function(e){c=g(e),m()||o.setLevel(e,!1)},o.resetLevel=function(){u=null,h(),l.call(o)},o.enableAll=function(e){o.setLevel(o.levels.TRACE,e)},o.disableAll=function(e){o.setLevel(o.levels.SILENT,e)},o.rebuild=function(){if(a!==o&&(s=g(a.getLevel())),l.call(o),a===o)for(var e in i)i[e].rebuild()},s=g(a?a.getLevel():`WARN`);var _=m();_!=null&&(u=g(_)),l.call(o)}a=new f,a.getLogger=function(e){if(typeof e!=`symbol`&&typeof e!=`string`||e===``)throw TypeError(`You must supply a name when creating a logger.`);var t=i[e];return t||=i[e]=new f(e,a.methodFactory),t};var p=typeof window===t?void 0:window.log;return a.noConflict=function(){return typeof window!==t&&window.log===a&&(window.log=p),a},a.getLoggers=function(){return i},a.default=a,a})})($o),$o.exports)}var rs=ns(),is;(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`})(is||={});var as;(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`})(as||={});var L=rs.getLogger(`livekit`);Object.values(as).map(e=>rs.getLogger(e)),L.setDefaultLevel(is.info);function os(e){let t=rs.getLogger(e);return t.setDefaultLevel(L.getLevel()),t}var ss=rs.getLogger(`lk-e2ee`),cs=7e3,ls=[0,300,4*300,9*300,16*300,cs,cs,cs,cs,cs],us=class{constructor(e){this._retryDelays=e===void 0?ls:[...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 ds(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 R(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 fs(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 ps(e){return this instanceof ps?(this.v=e,this):new ps(e)}function ms(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 ps?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 hs(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:ps(e[r](t)),done:!1}:i?i(t):t}:i}}function gs(e){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var t=e[Symbol.asyncIterator],n;return t?t.call(e):(e=typeof fs==`function`?fs(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 _s={exports:{}},vs;function ys(){if(vs)return _s.exports;vs=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)}_s.exports=a,_s.exports.once=_,a.EventEmitter=a,a.prototype._events=void 0,a.prototype._eventsCount=0,a.prototype._maxListeners=void 0;var o=10;function s(e){if(typeof e!=`function`)throw TypeError(`The "listener" argument must be of type Function. Received type `+typeof e)}Object.defineProperty(a,`defaultMaxListeners`,{enumerable:!0,get:function(){return o},set:function(e){if(typeof e!=`number`||e<0||i(e))throw RangeError(`The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received `+e+`.`);o=e}}),a.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},a.prototype.setMaxListeners=function(e){if(typeof e!=`number`||e<0||i(e))throw RangeError(`The value of "n" is out of range. It must be a non-negative number. Received `+e+`.`);return this._maxListeners=e,this};function c(e){return e._maxListeners===void 0?a.defaultMaxListeners:e._maxListeners}a.prototype.getMaxListeners=function(){return c(this)},a.prototype.emit=function(e){for(var n=[],r=1;r<arguments.length;r++)n.push(arguments[r]);var i=e===`error`,a=this._events;if(a!==void 0)i&&=a.error===void 0;else if(!i)return!1;if(i){var o;if(n.length>0&&(o=n[0]),o instanceof Error)throw o;var s=Error(`Unhandled error.`+(o?` (`+o.message+`)`:``));throw s.context=o,s}var c=a[e];if(c===void 0)return!1;if(typeof c==`function`)t(c,this,n);else for(var l=c.length,u=m(c,l),r=0;r<l;++r)t(u[r],this,n);return!0};function l(e,t,n,i){var a,o,l;if(s(n),o=e._events,o===void 0?(o=e._events=Object.create(null),e._eventsCount=0):(o.newListener!==void 0&&(e.emit(`newListener`,t,n.listener?n.listener:n),o=e._events),l=o[t]),l===void 0)l=o[t]=n,++e._eventsCount;else if(typeof l==`function`?l=o[t]=i?[n,l]:[l,n]:i?l.unshift(n):l.push(n),a=c(e),a>0&&l.length>a&&!l.warned){l.warned=!0;var u=Error(`Possible EventEmitter memory leak detected. `+l.length+` `+String(t)+` listeners added. Use emitter.setMaxListeners() to increase limit`);u.name=`MaxListenersExceededWarning`,u.emitter=e,u.type=t,u.count=l.length,r(u)}return e}a.prototype.addListener=function(e,t){return l(this,e,t,!1)},a.prototype.on=a.prototype.addListener,a.prototype.prependListener=function(e,t){return l(this,e,t,!0)};function u(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function d(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},i=u.bind(r);return i.listener=n,r.wrapFn=i,i}a.prototype.once=function(e,t){return s(t),this.on(e,d(this,e,t)),this},a.prototype.prependOnceListener=function(e,t){return s(t),this.prependListener(e,d(this,e,t)),this},a.prototype.removeListener=function(e,t){var n,r,i,a,o;if(s(t),r=this._events,r===void 0||(n=r[e],n===void 0))return this;if(n===t||n.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete r[e],r.removeListener&&this.emit(`removeListener`,e,n.listener||t));else if(typeof n!=`function`){for(i=-1,a=n.length-1;a>=0;a--)if(n[a]===t||n[a].listener===t){o=n[a].listener,i=a;break}if(i<0)return this;i===0?n.shift():h(n,i),n.length===1&&(r[e]=n[0]),r.removeListener!==void 0&&this.emit(`removeListener`,e,o||t)}return this},a.prototype.off=a.prototype.removeListener,a.prototype.removeAllListeners=function(e){var t,n=this._events,r;if(n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var i=Object.keys(n),a;for(r=0;r<i.length;++r)a=i[r],a!==`removeListener`&&this.removeAllListeners(a);return this.removeAllListeners(`removeListener`),this._events=Object.create(null),this._eventsCount=0,this}if(t=n[e],typeof t==`function`)this.removeListener(e,t);else if(t!==void 0)for(r=t.length-1;r>=0;r--)this.removeListener(e,t[r]);return this};function f(e,t,n){var r=e._events;if(r===void 0)return[];var i=r[t];return i===void 0?[]:typeof i==`function`?n?[i.listener||i]:[i]:n?g(i):m(i,i.length)}a.prototype.listeners=function(e){return f(this,e,!0)},a.prototype.rawListeners=function(e){return f(this,e,!1)},a.listenerCount=function(e,t){return typeof e.listenerCount==`function`?e.listenerCount(t):p.call(e,t)},a.prototype.listenerCount=p;function p(e){var t=this._events;if(t!==void 0){var n=t[e];if(typeof n==`function`)return 1;if(n!==void 0)return n.length}return 0}a.prototype.eventNames=function(){return this._eventsCount>0?n(this._events):[]};function m(e,t){for(var n=Array(t),r=0;r<t;++r)n[r]=e[r];return n}function h(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}function g(e){for(var t=Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}function _(e,t){return new Promise(function(n,r){function i(n){e.removeListener(t,a),r(n)}function a(){typeof e.removeListener==`function`&&e.removeListener(`error`,i),n([].slice.call(arguments))}y(e,t,a,{once:!0}),t!==`error`&&v(e,i,{once:!0})})}function v(e,t,n){typeof e.on==`function`&&y(e,`error`,t,n)}function y(e,t,n,r){if(typeof e.on==`function`)r.once?e.once(t,n):e.on(t,n);else if(typeof e.addEventListener==`function`)e.addEventListener(t,function i(a){r.once&&e.removeEventListener(t,i),n(a)});else throw TypeError(`The "emitter" argument must be of type EventEmitter. Received type `+typeof e)}return _s.exports}var bs=ys(),xs=!0,Ss=!0;function Cs(e,t,n){let r=e.match(t);return r&&r.length>=n&&parseFloat(r[n],10)}function ws(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 Ts(e){return typeof e==`boolean`?(xs=e,e?`adapter.js logging disabled`:`adapter.js logging enabled`):Error(`Argument type: `+typeof e+`. Please use a boolean.`)}function Es(e){return typeof e==`boolean`?(Ss=!e,`adapter.js deprecation warnings `+(e?`disabled`:`enabled`)):Error(`Argument type: `+typeof e+`. Please use a boolean.`)}function Ds(){if(typeof window==`object`){if(xs)return;typeof console<`u`&&typeof console.log==`function`&&console.log.apply(console,arguments)}}function Os(e,t){Ss&&console.warn(e+` is deprecated, please use `+t+` instead.`)}function ks(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(Cs(n.userAgent,/Firefox\/(\d+)\./,1));else if(n.webkitGetUserMedia||e.isSecureContext===!1&&e.webkitRTCPeerConnection)t.browser=`chrome`,t.version=parseInt(Cs(n.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else if(e.RTCPeerConnection&&n.userAgent.match(/AppleWebKit\/(\d+)\./))t.browser=`safari`,t.version=parseInt(Cs(n.userAgent,/AppleWebKit\/(\d+)\./,1)),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&`currentDirection`in e.RTCRtpTransceiver.prototype,t._safariVersion=Cs(n.userAgent,/Version\/(\d+(\.?\d+))/,1);else return t.browser=`Not a supported browser.`,t;return t}function As(e){return Object.prototype.toString.call(e)===`[object Object]`}function js(e){return As(e)?Object.keys(e).reduce(function(t,n){let r=As(e[n]),i=r?js(e[n]):e[n],a=r&&!Object.keys(i).length;return i===void 0||a?t:Object.assign(t,{[n]:i})},{}):e}function Ms(e,t,n){!t||n.has(t.id)||(n.set(t.id,t),Object.keys(t).forEach(r=>{r.endsWith(`Id`)?Ms(e,e.get(t[r]),n):r.endsWith(`Ids`)&&t[r].forEach(t=>{Ms(e,e.get(t),n)})}))}function Ns(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&&Ms(e,n,i)})}),i}var Ps=Ds;function Fs(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),Ps(`chrome: `+JSON.stringify(e)),i(e)})}e.video=r(e.video)}return Ps(`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 Is(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function Ls(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 ws(e,`track`,e=>(e.transceiver||Object.defineProperty(e,`transceiver`,{value:{receiver:e.receiver}}),e))}function Rs(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 zs(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=>Ns(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}),ws(e,`track`,e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){let e=this;return this._pc.getStats().then(t=>Ns(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 Bs(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 Vs(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return Bs(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 Hs(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 Us(e,t){ws(e,`negotiationneeded`,e=>{let n=e.target;if(!((t.version<72||n.getConfiguration&&n.getConfiguration().sdpSemantics===`plan-b`)&&n.signalingState!==`stable`))return e})}var Ws=Object.freeze({__proto__:null,fixNegotiationNeeded:Us,shimAddTrackRemoveTrack:Vs,shimAddTrackRemoveTrackWithNative:Bs,shimGetSendersWithDtmf:Rs,shimGetUserMedia:Fs,shimMediaStream:Is,shimOnTrack:Ls,shimPeerConnection:Hs,shimSenderReceiverGetStats:zs});function Gs(e,t){let n=e&&e.navigator,r=e&&e.MediaStreamTrack;if(n.getUserMedia=function(e,t,r){Os(`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 Ks(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 qs(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 Js(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 Ys(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 Xs(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}),ws(e,`track`,e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Zs(e){!e.RTCPeerConnection||`removeStream`in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){Os(`removeStream`,`removeTrack`),this.getSenders().forEach(t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)})})}function Qs(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function $s(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 ec(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 tc(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 nc(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 rc=Object.freeze({__proto__:null,shimAddTransceiver:$s,shimCreateAnswer:nc,shimCreateOffer:tc,shimGetDisplayMedia:Ks,shimGetParameters:ec,shimGetUserMedia:Gs,shimOnTrack:qs,shimPeerConnection:Js,shimRTCDataChannel:Qs,shimReceiverGetStats:Xs,shimRemoveStream:Zs,shimSenderGetStats:Ys});function ic(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 ac(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 oc(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 sc(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(cc(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,n,r){t.mediaDevices.getUserMedia(e).then(n,r)}.bind(t))}function cc(e){return e&&e.video!==void 0?Object.assign({},e,{video:js(e.video)}):e}function lc(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?(Os(`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 uc(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 dc(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 fc(e){typeof e!=`object`||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var pc=Object.freeze({__proto__:null,shimAudioContext:fc,shimCallbacksAPI:oc,shimConstraints:cc,shimCreateOfferLegacy:dc,shimGetUserMedia:sc,shimLocalStreamsAPI:ic,shimRTCIceServerUrls:lc,shimRemoteStreamsAPI:ac,shimTrackEventTransceiver:uc}),mc={exports:{}},hc;function gc(){return hc?mc.exports:(hc=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(`
|
|
23
23
|
`).map(e=>e.trim())},t.splitSections=function(e){return e.split(`
|
|
24
24
|
m=`).map((e,t)=>(t>0?`m=`+e:e).trim()+`\r
|
|
@@ -323,7 +323,7 @@ class ScribeAudioProcessor extends AudioWorkletProcessor {
|
|
|
323
323
|
|
|
324
324
|
registerProcessor("scribeAudioProcessor", ScribeAudioProcessor);
|
|
325
325
|
|
|
326
|
-
`),Th,Eh;(function(e){e.PCM_8000=`pcm_8000`,e.PCM_16000=`pcm_16000`,e.PCM_22050=`pcm_22050`,e.PCM_24000=`pcm_24000`,e.PCM_44100=`pcm_44100`,e.PCM_48000=`pcm_48000`,e.ULAW_8000=`ulaw_8000`})(Th||={}),function(e){e.MANUAL=`manual`,e.VAD=`vad`}(Eh||={});var Dh=class e{static getWebSocketUri(t=e.DEFAULT_BASE_URI){return`${t}/v1/speech-to-text/realtime`}static buildWebSocketUri(t){let n=e.getWebSocketUri(t.baseUri),r=new URLSearchParams;if(r.append(`model_id`,t.modelId),r.append(`token`,t.token),t.commitStrategy!==void 0&&r.append(`commit_strategy`,t.commitStrategy),t.audioFormat!==void 0&&r.append(`audio_format`,t.audioFormat),t.vadSilenceThresholdSecs!==void 0){if(t.vadSilenceThresholdSecs<=.3||t.vadSilenceThresholdSecs>3)throw Error(`vadSilenceThresholdSecs must be between 0.3 and 3.0`);r.append(`vad_silence_threshold_secs`,t.vadSilenceThresholdSecs.toString())}if(t.vadThreshold!==void 0){if(t.vadThreshold<.1||t.vadThreshold>.9)throw Error(`vadThreshold must be between 0.1 and 0.9`);r.append(`vad_threshold`,t.vadThreshold.toString())}if(t.minSpeechDurationMs!==void 0){if(t.minSpeechDurationMs<=50||t.minSpeechDurationMs>2e3)throw Error(`minSpeechDurationMs must be between 50 and 2000`);r.append(`min_speech_duration_ms`,t.minSpeechDurationMs.toString())}if(t.minSilenceDurationMs!==void 0){if(t.minSilenceDurationMs<=50||t.minSilenceDurationMs>2e3)throw Error(`minSilenceDurationMs must be between 50 and 2000`);r.append(`min_silence_duration_ms`,t.minSilenceDurationMs.toString())}t.languageCode!==void 0&&r.append(`language_code`,t.languageCode),t.includeTimestamps!==void 0&&r.append(`include_timestamps`,t.includeTimestamps?`true`:`false`);let i=r.toString();return i?`${n}?${i}`:n}static connect(t){if(!t.modelId)throw Error(`modelId is required`);let n=new Ch(`microphone`in t&&t.microphone?16e3:t.sampleRate),r=e.buildWebSocketUri(t),i=new WebSocket(r);return`microphone`in t&&t.microphone&&i.addEventListener(`open`,()=>{e.streamFromMicrophone(t,n)}),n.setWebSocket(i),n}static async streamFromMicrophone(e,t){try{var n,r,i;let a=await navigator.mediaDevices.getUserMedia({audio:{deviceId:e.microphone?.deviceId,echoCancellation:(n=e.microphone?.echoCancellation)==null||n,noiseSuppression:(r=e.microphone?.noiseSuppression)==null||r,autoGainControl:(i=e.microphone?.autoGainControl)==null||i,channelCount:e.microphone?.channelCount??1,sampleRate:{ideal:16e3}}}),o=new AudioContext({sampleRate:16e3});await wh(o.audioWorklet);let s=o.createMediaStreamSource(a),c=new AudioWorkletNode(o,`scribeAudioProcessor`);c.port.onmessage=e=>{let{audioData:n}=e.data,r=new Uint8Array(n),i=``;for(let e=0;e<r.length;e++)i+=String.fromCharCode(r[e]);let a=btoa(i);t.send({audioBase64:a})},s.connect(c),o.state===`suspended`&&await o.resume(),t._audioCleanup=()=>{a.getTracks().forEach(e=>{e.stop()}),s.disconnect(),c.disconnect(),o.close()}}catch(e){throw console.error(`Failed to start microphone streaming:`,e),e}}};Dh.DEFAULT_BASE_URI=`wss://api.elevenlabs.io`;var Oh=class extends $m{static startSession(e){return e.textOnly?gh.startSession(e):xh.startSession(e)}};function $(...e){Qt()&&console.log(`[FlowEngage:voice-tools]`,...e)}var kh=`#flowengage-root, .flowengage-shell`;function Ah(e){if(!e||typeof e.closest!=`function`)return!1;try{return!!e.closest(kh)}catch{return!1}}function jh(e){try{let t=e.ownerDocument?.defaultView;if(t)return t.getComputedStyle(e)}catch{}return window.getComputedStyle(e)}function Mh(e){let t=new Set;function n(r){if(!r||t.has(r))return;t.add(r),e(r);let i=r.querySelectorAll(`iframe`);for(let e of i)if(!Ah(e))try{let t=e.contentDocument;t&&n(t)}catch{}}typeof document<`u`&&n(document)}function Nh(e){return e==null?null:String(e).replace(/\u00a0/g,` `).replace(/\s*\*+\s*$/u,``).replace(/\s+/g,` `).trim()}function Ph(e){let t=e.ownerDocument||document,n=e.getAttribute(`aria-labelledby`);if(n){let e=n.trim().split(/\s+/).filter(Boolean),r=[];for(let n of e)try{let e=t.getElementById(n);e?.textContent&&r.push(e.textContent.trim())}catch{}if(r.length)return Nh(r.join(` `))}if(e.labels&&e.labels.length)return Nh(e.labels[0].textContent);let r=e.id;if(r)try{let e=t.querySelector(`label[for="${CSS.escape(r)}"]`);if(e)return Nh(e.textContent)}catch{let e=t.querySelector(`label[for="${r.replace(/"/g,`\\"`)}"]`);if(e)return Nh(e.textContent)}let i=e.previousElementSibling;for(let e=0;e<6&&i;e+=1){if(i.tagName===`LABEL`)return Nh(i.textContent);let e=(i.className||``).toString().toLowerCase();if(/chakra-form__label|formlabel|field-label|form-label|mui-form-label/.test(e)){let e=Nh(i.textContent);if(e)return e}i=i.previousElementSibling}let a=e.parentElement;for(let e=0;e<5&&a;e+=1){if(a.tagName===`LABEL`)return Nh(a.textContent);let e=a.querySelector?.(`:scope > label, :scope > [class*='FormLabel'], :scope > [class*='form__label']`);if(e?.textContent)return Nh(e.textContent);a=a.parentElement}let o=e.getAttribute(`aria-label`);return o?Nh(o):null}function Fh(){let e=[];return Mh(t=>{e.push(...Array.from(t.querySelectorAll(`input, select, textarea`)).filter(e=>{if(Ah(e))return!1;let t=(e.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`image`].includes(t)||e.disabled||e.readOnly)return!1;try{let t=jh(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))}),e}function Ih(){return Fh().map((e,t)=>({formIndex:0,fieldIndex:t,tag:e.tagName,type:e.type||`text`,name:e.name||null,id:e.id||null,label:Ph(e),placeholder:e.placeholder||null}))}function Lh(){let e=[];return Mh(t=>{e.push(...Array.from(t.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(Ah(e)||e.disabled)return!1;try{let t=jh(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))}),e.slice(0,60).map((e,t)=>({index:t,text:(e.textContent||e.value||``).replace(/\s+/g,` `).trim().slice(0,120)||null,ariaLabel:e.getAttribute(`aria-label`),type:e.type||e.tagName}))}function Rh(e){return String(e||``).toLowerCase().replace(/\u00a0/g,` `).replace(/\*/g,``).replace(/\s+/g,` `).trim()}function zh(e){let t=Rh(e);return t=t.replace(/\s+field\s*$/i,``).trim(),t}function Bh(e,t){let n=zh(t);if(!n)return 0;let r=(e.name||``).toLowerCase(),i=(e.id||``).toLowerCase();if(r===`url`&&/url|website|domain|site|audit/.test(n)||(i===`url-input`||i.endsWith(`-url-input`))&&/url|website|domain|site|audit/.test(n))return 100;let a=[e.name,e.id,e.placeholder,Ph(e),e.getAttribute(`aria-label`),e.getAttribute(`title`),e.getAttribute(`data-testid`),e.getAttribute(`autocomplete`)].filter(Boolean).map(e=>Rh(e)),o=0;for(let e of a){if(!e)continue;if(e.includes(n)||n.includes(e)){o=Math.max(o,100);continue}let t=n.split(/\s+/).filter(e=>e.length>1);if(!t.length)continue;let r=0;for(let n of t)e.includes(n)&&(r+=1);o=Math.max(o,r/t.length*88)}return o}var Vh=28;function Hh(e,t){let n=null,r=0;for(let i of e){let e=Bh(i,t);e>r&&(r=e,n=i)}return!n||r<Vh?null:n}function Uh(e,t,n){let r=String(t||``).toLowerCase().trim(),i=String(n||``).trim();if(!(/^https?:\/\//i.test(i)||/\.\w{2,}(\/|\s|$)/.test(i)||r.includes(`url`)||r.includes(`website`)||r.includes(`domain`)||r.includes(`site`)))return null;let a=null,o=0;for(let t of e){if(t.tagName!==`INPUT`&&t.tagName!==`TEXTAREA`)continue;let e=(t.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`checkbox`,`radio`].includes(e))continue;let n=0;(e===`url`||e===`text`||e===`search`)&&(n+=45);let r=[t.name,t.id,t.placeholder,Ph(t),t.getAttribute(`aria-label`),t.getAttribute(`autocomplete`)].filter(Boolean).join(` `).toLowerCase();/(website|url|domain|site\s*url)/.test(r)&&(n+=55),n>o&&(o=n,a=t)}return!a||o<42?null:a}function Wh(e){let t=String(e??``).trim();return t?/^https?:\/\//i.test(t)?!0:/\.\w{2,}(\/|\s|$)/.test(t):!1}function Gh(e){let t=String(e??``).toLowerCase().trim();return t?!!(t===`url`||t===`website`||t===`website url`||t===`website_url`||t===`enter website url`||t.includes(`website`)||t.includes(`domain`)||/(enter\s+website|site\s*url|page\s*url)/.test(t)):!1}function Kh(e){if(!e||e.tagName!==`INPUT`&&e.tagName!==`TEXTAREA`)return!1;let t=(e.type||``).toLowerCase();return![`hidden`,`submit`,`button`,`checkbox`,`radio`,`file`].includes(t)}function qh(e){if(!Kh(e))return!1;let t=(e.name||``).toLowerCase(),n=(e.id||``).toLowerCase(),r=[e.name,e.id,e.placeholder,Ph(e),e.getAttribute(`aria-label`)].filter(Boolean).join(` `).toLowerCase();return t===`url`||n===`url-input`||n.endsWith(`-url-input`)||/(website\s*url|enter\s+website|site\s*url)/.test(r)||/(website|domain)/.test(r)&&/(url|site)/.test(r)}function Jh(e,t,n){let r=String(t??``),i=String(n??``),a=Zh(e,r)||Hh(e,r)||Uh(e,r,i);if(!a)return[];let o=new Set([a]);if(Wh(i)&&Gh(r))for(let t of e)t!==a&&qh(t)&&o.add(t);let s=Array.from(o);return s.sort((e,t)=>{if(e===t)return 0;let n=e.compareDocumentPosition(t);return n&Node.DOCUMENT_POSITION_FOLLOWING?-1:n&Node.DOCUMENT_POSITION_PRECEDING?1:0}),s}function Yh(e,t){try{if(!e?.getBoundingClientRect||!t?.getBoundingClientRect)return 1/0;let n=e.getBoundingClientRect(),r=t.getBoundingClientRect(),i={x:n.left+n.width/2,y:n.top+n.height/2},a={x:r.left+r.width/2,y:r.top+r.height/2};return Math.hypot(i.x-a.x,i.y-a.y)}catch{return 1/0}}function Xh(e){if(!e||typeof e!=`string`)return null;let t=null;return Mh(n=>{try{let r=n.getElementById(e);r&&!Ah(r)&&r.matches?.(`input, select, textarea`)&&(t=r)}catch{}}),t}function Zh(e,t){let n=String(t??``).trim();if(!n)return null;let r=n.match(/^name:\s*([\w.-]+)$/i);if(r){let t=r[1];for(let n of e)if(n.name===t)return n}let i=n.match(/^id:\s*([\w.-]+)$/i);if(i){let e=Xh(i[1]);if(e)return e}let a=n.startsWith(`#`)?n.slice(1):n;if(/^[\w-]+$/.test(a)){let e=Xh(a);if(e)return e}let o=n.toLowerCase().replace(/\s+/g,` `);if(o===`url`||o===`website`||o===`website url`||o===`website_url`||o===`enter website url`)for(let t of e){let e=(t.name||``).toLowerCase(),n=(t.id||``).toLowerCase();if(e===`url`||n===`url-input`||n.endsWith(`-url-input`))return t}return null}function Qh(e,t){let n=String(t||``).toLowerCase().trim();if(!n)return 0;let r=[e.textContent,e.value,e.getAttribute(`aria-label`),e.getAttribute(`title`)].filter(Boolean).join(` `).toLowerCase().replace(/\s+/g,` `);if(r.includes(n))return 100;let i=n.split(/\s+/).filter(e=>e.length>1);if(!i.length)return 0;let a=0;for(let e of i)r.includes(e)&&(a+=1);return a/i.length*92}function $h(e,t){let n=[];Mh(e=>{n.push(...Array.from(e.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(Ah(e)||e.disabled)return!1;try{let t=jh(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))});let r=0,i=n.map(t=>({el:t,s:Qh(t,e)}));for(let{s:e}of i)e>r&&(r=e);if(r<36)return null;let a=i.filter(({s:e})=>e===r).map(({el:e})=>e);if(a.length===1)return a[0];let o=Array.isArray(t)?t.filter(e=>e&&e.isConnected):[];if(o.length){let e=a[0],t=1/0;for(let n of a)for(let r of o){let i=Yh(n,r);i<t&&(t=i,e=n)}return e}return a[0]}function eg(e){if(e==null)return{};if(typeof e==`string`){let t=e.trim();if(!t)return{};try{return JSON.parse(t)}catch{return{url:t}}}return e}function tg(e){let t=eg(e);if(Array.isArray(t)&&t.length>0){let e=t[0];if(e?.field_key!=null||e?.fieldKey!=null)return t.map(e=>({field_key:e.field_key??e.fieldKey,value:e.value}))}if(!t||typeof t!=`object`)return[];let n=t.fields??t.Fields??t.field_list??t.fieldList??t.data?.fields;if(typeof n==`string`)try{n=JSON.parse(n)}catch{n=null}n&&!Array.isArray(n)&&typeof n==`object`&&(n=Object.values(n)),(!n||n.length===0)&&(t.field_key!=null||t.fieldKey!=null)&&t.value!=null&&(n=[{field_key:t.field_key??t.fieldKey,value:t.value}]);let r=t.website_url??t.websiteUrl??t.url??t.website??t.domain??t.site_url??t.siteUrl;return(!n||n.length===0)&&r!=null&&String(r).trim()&&(n=[{field_key:t.field_key??t.fieldKey??`url`,value:String(r).trim()}]),Array.isArray(n)?n.map(e=>({field_key:e?.field_key??e?.fieldKey,value:e?.value??e?.Value})):[]}function ng(e){if(!e||typeof e!=`string`)return[];let t=e.trim();if(!t||/\b[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}\b/i.test(t))return[];let n=t.match(/https?:\/\/[^\s<>"']+/i);if(n)return[{field_key:`url`,value:n[0].replace(/[.,;:)]+$/,``)}];let r=t.match(/\b(?:[\w-]+\.)+[a-z]{2,}\b/i);if(r){let e=r[0].replace(/[.,;:)]+$/,``);return/^https?:/i.test(e)||(e=`https://${e}`),[{field_key:`url`,value:e}]}return[]}function rg(e){if(!e||typeof e!=`string`)return[];let t=e.trim();if(!t)return[];let n=[],r=new Set,i=/\b([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,})\b/i,a=(e,t)=>{let i=String(t??``).trim().replace(/^["']|["']$/g,``);if(!i||i.length>800)return;let a=`${e}\0${i}`;r.has(a)||(r.add(a),n.push({field_key:e,value:i}))},o=t.match(/^\s*([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,})\s*$/i);if(o)return a(`Email Address`,o[1]),n;let s=t.match(/\b(?:please\s+)?(?:enter|type|put)\s+(.+?)\s+in(?:to)?\s+(?:the\s+)?(?:full\s*name|full\s*name\s*field|name\s*field)\b/i);if(s&&a(`Full Name`,s[1]),s=t.match(/\bfull\s*name,?\s*(?:please\s+)?(?:enter|type|put)\s+(.+?)(?:\.|$|!|\?)/i),s&&a(`Full Name`,s[1]),s=t.match(/\bfull\s*name\s*(?:is|:|please\s+enter|-)\s*(.+?)(?:\.|$|(?=\s+(?:and|my\s+email|email|message))\b)/i),s&&a(`Full Name`,s[1]),s=t.match(/\b(.+?)\s+for\s+(?:the\s+)?full\s*name\b/i),s){let e=s[1].trim();e.length>1&&e.length<120&&!/@/.test(e)&&a(`Full Name`,e)}if(s=t.match(/\b(?:email|e-mail)(?:\s*address)?\s*(?:is|:|please\s+use|enter|-)\s*([^\s@]+@[^\s@]+\.[^\s,]+)/i),s&&a(`Email Address`,s[1]),s=t.match(/\b(?:enter|type|put)\s+([^\s@]+@[^\s@]+\.[^\s,]+)\s+in(?:to)?\s+(?:the\s+)?(?:email|e-mail)/i),s&&a(`Email Address`,s[1]),s=t.match(/\b(?:message|comment)\s*(?:is|:|please\s+enter|-)\s*(.+)$/is),s){let e=s[1].trim();e.length>0&&a(`Message`,e)}if(!n.some(e=>/email/i.test(String(e.field_key)))){let e=t.match(i);if(e){let r=t.replace(e[0],``).trim().replace(/^(please|it's|it is|use|is|my email is|e-?mail is)\s*/i,``).replace(/[.,;:!?]+$/,``).trim();if(t.length<=96&&r.length<=36)return a(`Email Address`,e[1]),n}}if(n.length===0){let e=t.split(/\s+/).filter(Boolean).length,n=/[.!?]/.test(t)||e>=6||t.length>=24&&e>=5||t.length>=42,r=/^[A-Z][a-z]+\s+[A-Z][a-z]+$/.test(t.trim());n&&t.length>=16&&!i.test(t)&&!r&&a(`Message`,t)}return n}function ig(e){if(!e||typeof e!=`object`)return null;let t=e.url??e.target_url??e.page_url??e.pageUrl??e.link??e.href??e.path;return t==null?null:String(t).trim()||null}function ag(e){if(!e||typeof e!=`object`)return null;let t=e.query??e.q??e.search??e.text??e.keywords;return t==null?null:String(t).trim()||null}function og(e,t,n){if(!n?.skipScroll)try{e.scrollIntoView({block:`center`,inline:`nearest`})}catch{try{e.scrollIntoView(!0)}catch{}}try{e.focus({preventScroll:!0})}catch{try{e.focus()}catch{}}let r=e.tagName,i=(e.type||``).toLowerCase();if(r===`SELECT`)return e.value=String(t),e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0})),!0;if(i===`checkbox`||i===`radio`)return e.checked=[`1`,`true`,`yes`,`on`].includes(String(t).toLowerCase().trim()),e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0})),!0;let a=String(t);if(r===`INPUT`||r===`TEXTAREA`){let t=e.ownerDocument?.defaultView||window,n=r===`TEXTAREA`?t.HTMLTextAreaElement.prototype:t.HTMLInputElement.prototype,i=Object.getOwnPropertyDescriptor(n,`value`);i?.set?i.set.call(e,a):e.value=a}else e.value=a;let o={bubbles:!0,cancelable:!0,composed:!0};try{e.dispatchEvent(new InputEvent(`input`,{...o,inputType:`insertText`,data:a}))}catch{e.dispatchEvent(new Event(`input`,o))}e.dispatchEvent(new Event(`change`,o));try{queueMicrotask(()=>{try{e.dispatchEvent(new Event(`input`,o)),e.dispatchEvent(new Event(`change`,o))}catch{}})}catch{}return!0}function sg(e){let t=e.siteId||null,n=(e.apiBaseUrl||``).replace(/\/$/,``),r=typeof e.getLastUserVoiceText==`function`?e.getLastUserVoiceText:null,i=[],a={navigate_to_page:async n=>{$(`navigate_to_page ▶ raw parameters:`,n);let r=eg(n),i=ig(r),a=r.section_text??r.sectionText??r.section;if($(`navigate_to_page · coerced:`,{url:i,sectionText:a}),!i){let e=`Missing url: pass a string url, path like /pricing, or JSON with a url field.`;return $(`navigate_to_page ✖`,e),e}if(!await sn(i,{siteId:t,apiBaseUrl:e.apiBaseUrl})){let e=`That page is not available in the site index; answer without navigating.`;return $(`navigate_to_page ✖ blocked`,e),e}try{if($(`navigate_to_page → shadowNavigate`,i),await cn(i),await new Promise(e=>setTimeout(e,400)),a&&typeof a==`string`){let e=tn(null,a);e&&nn(e),$(`navigate_to_page · highlight`,{sectionText:a,found:!!e})}let e=`OK_NAVIGATION ${i}`;return $(`navigate_to_page ✓`,e),e}catch(e){let t=`Navigation error: ${e?.message||String(e)}`;return $(`navigate_to_page ✖`,t),t}},highlight_on_page:async e=>{$(`highlight_on_page ▶`,e);let t=eg(e),n=t?.section_id||t?.sectionId,r=t?.section_text||t?.sectionText,i=tn(n||null,r||null);return i?(nn(i),$(`highlight_on_page ✓`),`Highlighted the section.`):($(`highlight_on_page ✖ no element`),`Could not find that section on the page.`)},search_site_content:async e=>{$(`search_site_content ▶`,e);let r=ag(eg(e));if($(`search_site_content · query:`,r,`siteId:`,t,`apiBase:`,n||`(empty)`),!r)return $(`search_site_content ✖ missing query`),`Missing query parameter.`;if(!t)return $(`search_site_content ✖ no siteId`),`Site is not configured for search.`;if(!n)return $(`search_site_content ✖ no api base`),`API base URL is missing; cannot search.`;try{let e=`${n}/api/site-tools/search`;$(`search_site_content → POST`,e);let i=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({siteId:t,query:r,currentUrl:typeof window<`u`?window.location.href:``})}),a=await i.json();if($(`search_site_content · HTTP`,i.status,`success:`,a.success),!a.success){let e=a.error||`Search failed.`;return $(`search_site_content ✖`,e),e}let o=a.results||[];return $(`search_site_content ✓`,`${o.length} result(s)`,o.slice(0,3).map(e=>e?.url||e)),JSON.stringify(o)}catch(e){let t=`Search error: ${e.message||`network`}`;return $(`search_site_content ✖`,t),t}},list_page_forms:async()=>{let e=Ih(),t=Lh();return $(`list_page_forms ✓`,`${e.length} field(s)`,`${t.length} button(s)`),JSON.stringify({fields:e,buttons:t,hint:`field_key: placeholder/label, name (e.g. url), id (e.g. url-input). If the page has two URL boxes, fill_form_fields sets all matching URL inputs. click_page_button picks the Conduct Audit nearest the filled field when labels duplicate.`})},fill_form_fields:async e=>{try{$(`fill_form_fields ▶ raw:`,e);let t=tg(e);if(!t.length&&r){let e=r(),n=ng(e);n.length?$(`fill_form_fields · inferred URL from last user utterance (model omitted usable fields):`,n):(n=rg(e),n.length&&$(`fill_form_fields · inferred contact fields from last user utterance (empty tool params):`,n)),n.length&&(t=n)}if($(`fill_form_fields · normalized fields:`,t),!t.length)return`No fields provided. Call list_page_forms for field_key strings, then fill_form_fields with { "fields": [ { "field_key": "<label or placeholder from list>", "value": "<user value>" } ] }. Never use empty {}. Pass the value the user just said (email, message, name, URL) in fields.`;let n=[];for(let e of t){let t=e?.field_key??e?.fieldKey,r=e?.value;if(t==null||r==null)continue;let a=Fh(),o=Jh(a,String(t),r);if(o.length){o.forEach((e,t)=>{og(e,r,{skipScroll:t>0})}),i=o,n.push(String(t));continue}let s=Zh(a,String(t));s||=Hh(a,String(t)),s||=Uh(a,String(t),r),s&&(og(s,r),i=[s],n.push(String(t)))}if(!n.length)return $(`fill_form_fields ✖ no matches`),`Could not match any fields. Call list_page_forms and use field_key values that match placeholder, label, name, or id (e.g. Enter Website URL). Ensure the form is on the page, not the chat panel.`;let a=`OK_FILLED: ${n.join(`, `)}`;return $(`fill_form_fields ✓`,a),a}catch(e){let t=`fill_form_fields error: ${e?.message||String(e)}`;return $(`fill_form_fields ✖`,t),t}},click_page_button:async e=>{let t=eg(e),n=(t.button_text??t.buttonText??t.text??``).trim();if($(`click_page_button ▶`,n),!n)return`Missing button_text: pass the visible label, e.g. Conduct Audit.`;let r=$h(n,i);if(!r)return $(`click_page_button ✖ no match`),`Could not find a button matching "${n}". Call list_page_forms to see button texts.`;try{try{r.scrollIntoView({block:`center`,inline:`nearest`})}catch{r.scrollIntoView(!0)}r.focus?.(),r.click();let e=`OK_CLICK ${(r.textContent||r.value||r.getAttribute(`aria-label`)||``).trim().slice(0,80)||`button`}`;return $(`click_page_button ✓`,e),e}catch(e){let t=`Click failed: ${e?.message||String(e)}`;return $(`click_page_button ✖`,t),t}}};return{...a,navigateToPage:a.navigate_to_page,highlightOnPage:a.highlight_on_page,searchSiteContent:a.search_site_content,listPageForms:a.list_page_forms,fillFormFields:a.fill_form_fields,clickPageButton:a.click_page_button}}function cg(e){return!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,async n=>{let r=Qt();r?console.log(`[FlowEngage:voice-tool] ▶`,e,n):console.info(`[FlowEngage] voice tool » ${e}`);let i=await t(n),a=typeof i==`string`?i.length>220?`${i.slice(0,220)}…`:i:String(i);return r?console.log(`[FlowEngage:voice-tool] ◀`,e,a):console.info(`[FlowEngage] voice tool « ${e}:`,a),i}]))}var lg={idle:`rgba(99,102,241,0.18)`,listening:`rgba(16,185,129,0.25)`,speaking:`rgba(245,158,11,0.25)`,error:`rgba(239,68,68,0.2)`},ug={idle:`#6366f1`,listening:`#10b981`,speaking:`#f59e0b`,error:`#ef4444`};function dg({agentId:e,chatId:t,siteId:n,apiBaseUrl:r,onEnd:i,historyRef:a,hasSyncedRef:o,onMessageSync:s,onStartSync:c}){let[l,u]=(0,v.useState)(`idle`),[d,f]=(0,v.useState)(null),[p,m]=(0,v.useState)(!1),[h,g]=(0,v.useState)([]),_=(0,v.useRef)(null),y=(0,v.useRef)(null),b=(0,v.useRef)(``);(0,v.useEffect)(()=>{let t=!1,i=null;return(async()=>{try{if(await navigator.mediaDevices.getUserMedia({audio:!0}),t)return;g([]),b.current=``;let o=cg(sg({siteId:n||null,apiBaseUrl:r||null,getLastUserVoiceText:()=>b.current})),s=await Oh.startSession({agentId:e,clientTools:o,onUnhandledClientToolCall:e=>{console.error(`[VoiceInterface] ElevenLabs requested a client tool that is not registered in the widget:`,e?.tool_name,e?.parameters,`Add a matching handler in voiceClientTools (snake_case and camelCase are both supported).`)},onModeChange:({mode:e})=>{t||u(e===`speaking`?`speaking`:`listening`)},onMessage:e=>{if(t)return;let n=e.role===`user`?`user`:`bot`,r=e.message||e.text||e.content||``;if(!r)return;let i={sender:n,message:r,timestamp:new Date().toISOString()};n===`user`&&(b.current=r),a.current=[...a.current,i],g(e=>[...e,i])},onError:e=>{t||(console.error(`[VoiceInterface] ElevenLabs error`,e),u(`error`),f(`Voice session encountered an error.`))},onDisconnect:()=>{t||(console.log(`[VoiceInterface] session disconnected`),m(!1),u(`idle`))}});if(t){s.endSession().catch(()=>{});return}i=s,_.current=s,m(!0),u(`listening`);try{let e=typeof window<`u`?window.location.href:``,t=``;try{t=await o.list_page_forms()}catch{t=`[]`}s.sendContextualUpdate(`Current page URL: ${e}. Site ID: ${n||`unknown`}. Page fields/buttons JSON: ${t}. Navigation: search_site_content then navigate_to_page with section_text when relevant — no permission ask. Forms: use fill_form_fields then click_page_button (e.g. Conduct Audit) when the user wants to submit.`)}catch{}typeof c==`function`&&c()}catch(e){t||(console.error(`[VoiceInterface] startSession failed`,e),u(`error`),f(`Could not start voice session. Please try again.`))}})(),()=>{t=!0,i?i.endSession().catch(()=>{}):_.current&&_.current.endSession().catch(()=>{})}},[e,n,r,a,c]);let x=(0,v.useCallback)(async()=>{try{await _.current?.endSession?.()}catch{}_.current=null,m(!1),u(`idle`),typeof s==`function`&&await s(a.current),typeof i==`function`&&i()},[a,s,i]),ee=l===`listening`||l===`speaking`,te=ug[l]||ug.idle,S=lg[l]||lg.idle;return(0,A.jsxs)(`div`,{ref:y,style:{display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,flex:1,gap:`24px`,padding:`24px 20px`,background:`transparent`},children:[(0,A.jsxs)(`div`,{style:{position:`relative`,width:`140px`,height:`140px`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:[ee&&(0,A.jsx)(`div`,{style:{position:`absolute`,inset:`-16px`,borderRadius:`50%`,border:`2px solid ${te}`,animation:`fe-orb-pulse 1.4s ease-in-out infinite`,opacity:.6}}),ee&&(0,A.jsx)(`div`,{style:{position:`absolute`,inset:`-8px`,borderRadius:`50%`,border:`2px solid ${te}`,animation:`fe-orb-pulse 1.4s ease-in-out 0.35s infinite`,opacity:.4}}),(0,A.jsx)(`div`,{style:{width:`140px`,height:`140px`,borderRadius:`50%`,background:S,border:`3px solid ${te}`,display:`flex`,alignItems:`center`,justifyContent:`center`,transition:`all 0.35s ease`,transform:l===`speaking`?`scale(1.08)`:`scale(1)`,boxShadow:`0 0 40px ${S}, 0 8px 32px rgba(0,0,0,0.08)`},children:(0,A.jsx)(vn,{size:44,color:te})})]}),(0,A.jsxs)(`div`,{style:{fontSize:`15px`,fontWeight:600,color:l===`error`?`#ef4444`:`#374151`,letterSpacing:`0.01em`,textAlign:`center`},children:[l===`idle`&&`Starting voice session…`,l===`listening`&&`Listening…`,l===`speaking`&&`AI is speaking…`,l===`error`&&(d||`Error`)]}),h.length>0&&(0,A.jsx)(`div`,{style:{width:`100%`,maxHeight:`160px`,overflowY:`auto`,display:`flex`,flexDirection:`column`,gap:`8px`,padding:`0 4px`},children:h.map((e,t)=>(0,A.jsx)(`div`,{style:{display:`flex`,justifyContent:e.sender===`user`?`flex-end`:`flex-start`},children:(0,A.jsx)(`div`,{style:{maxWidth:`85%`,padding:`8px 12px`,borderRadius:`14px`,fontSize:`13px`,lineHeight:1.5,background:e.sender===`user`?`var(--flowengage-primary)`:`#f3f4f6`,color:e.sender===`user`?`#fff`:`#111827`},children:e.message})},t))}),(0,A.jsxs)(`button`,{onClick:x,style:{display:`flex`,alignItems:`center`,gap:`8px`,padding:`12px 24px`,borderRadius:`999px`,background:`#fee2e2`,color:`#dc2626`,border:`1px solid #fca5a5`,fontWeight:600,fontSize:`14px`,cursor:`pointer`,transition:`all 0.2s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`#fecaca`},onMouseLeave:e=>{e.currentTarget.style.background=`#fee2e2`},children:[(0,A.jsx)(yn,{size:18}),`End Voice Session`]}),(0,A.jsx)(`style`,{children:`
|
|
326
|
+
`),Th,Eh;(function(e){e.PCM_8000=`pcm_8000`,e.PCM_16000=`pcm_16000`,e.PCM_22050=`pcm_22050`,e.PCM_24000=`pcm_24000`,e.PCM_44100=`pcm_44100`,e.PCM_48000=`pcm_48000`,e.ULAW_8000=`ulaw_8000`})(Th||={}),function(e){e.MANUAL=`manual`,e.VAD=`vad`}(Eh||={});var Dh=class e{static getWebSocketUri(t=e.DEFAULT_BASE_URI){return`${t}/v1/speech-to-text/realtime`}static buildWebSocketUri(t){let n=e.getWebSocketUri(t.baseUri),r=new URLSearchParams;if(r.append(`model_id`,t.modelId),r.append(`token`,t.token),t.commitStrategy!==void 0&&r.append(`commit_strategy`,t.commitStrategy),t.audioFormat!==void 0&&r.append(`audio_format`,t.audioFormat),t.vadSilenceThresholdSecs!==void 0){if(t.vadSilenceThresholdSecs<=.3||t.vadSilenceThresholdSecs>3)throw Error(`vadSilenceThresholdSecs must be between 0.3 and 3.0`);r.append(`vad_silence_threshold_secs`,t.vadSilenceThresholdSecs.toString())}if(t.vadThreshold!==void 0){if(t.vadThreshold<.1||t.vadThreshold>.9)throw Error(`vadThreshold must be between 0.1 and 0.9`);r.append(`vad_threshold`,t.vadThreshold.toString())}if(t.minSpeechDurationMs!==void 0){if(t.minSpeechDurationMs<=50||t.minSpeechDurationMs>2e3)throw Error(`minSpeechDurationMs must be between 50 and 2000`);r.append(`min_speech_duration_ms`,t.minSpeechDurationMs.toString())}if(t.minSilenceDurationMs!==void 0){if(t.minSilenceDurationMs<=50||t.minSilenceDurationMs>2e3)throw Error(`minSilenceDurationMs must be between 50 and 2000`);r.append(`min_silence_duration_ms`,t.minSilenceDurationMs.toString())}t.languageCode!==void 0&&r.append(`language_code`,t.languageCode),t.includeTimestamps!==void 0&&r.append(`include_timestamps`,t.includeTimestamps?`true`:`false`);let i=r.toString();return i?`${n}?${i}`:n}static connect(t){if(!t.modelId)throw Error(`modelId is required`);let n=new Ch(`microphone`in t&&t.microphone?16e3:t.sampleRate),r=e.buildWebSocketUri(t),i=new WebSocket(r);return`microphone`in t&&t.microphone&&i.addEventListener(`open`,()=>{e.streamFromMicrophone(t,n)}),n.setWebSocket(i),n}static async streamFromMicrophone(e,t){try{var n,r,i;let a=await navigator.mediaDevices.getUserMedia({audio:{deviceId:e.microphone?.deviceId,echoCancellation:(n=e.microphone?.echoCancellation)==null||n,noiseSuppression:(r=e.microphone?.noiseSuppression)==null||r,autoGainControl:(i=e.microphone?.autoGainControl)==null||i,channelCount:e.microphone?.channelCount??1,sampleRate:{ideal:16e3}}}),o=new AudioContext({sampleRate:16e3});await wh(o.audioWorklet);let s=o.createMediaStreamSource(a),c=new AudioWorkletNode(o,`scribeAudioProcessor`);c.port.onmessage=e=>{let{audioData:n}=e.data,r=new Uint8Array(n),i=``;for(let e=0;e<r.length;e++)i+=String.fromCharCode(r[e]);let a=btoa(i);t.send({audioBase64:a})},s.connect(c),o.state===`suspended`&&await o.resume(),t._audioCleanup=()=>{a.getTracks().forEach(e=>{e.stop()}),s.disconnect(),c.disconnect(),o.close()}}catch(e){throw console.error(`Failed to start microphone streaming:`,e),e}}};Dh.DEFAULT_BASE_URI=`wss://api.elevenlabs.io`;var Oh=class extends $m{static startSession(e){return e.textOnly?gh.startSession(e):xh.startSession(e)}};function $(...e){Qt()&&console.log(`[FlowEngage:voice-tools]`,...e)}var kh=`#flowengage-root, .flowengage-shell`;function Ah(e){if(!e||typeof e.closest!=`function`)return!1;try{return!!e.closest(kh)}catch{return!1}}function jh(e){try{let t=e.ownerDocument?.defaultView;if(t)return t.getComputedStyle(e)}catch{}return window.getComputedStyle(e)}function Mh(e){let t=new Set;function n(r){if(!r||t.has(r))return;t.add(r),e(r);let i=r.querySelectorAll(`iframe`);for(let e of i)if(!Ah(e))try{let t=e.contentDocument;t&&n(t)}catch{}}typeof document<`u`&&n(document)}function Nh(e){return e==null?null:String(e).replace(/\u00a0/g,` `).replace(/\s*\*+\s*$/u,``).replace(/\s+/g,` `).trim()}function Ph(e){let t=e.ownerDocument||document,n=e.getAttribute(`aria-labelledby`);if(n){let e=n.trim().split(/\s+/).filter(Boolean),r=[];for(let n of e)try{let e=t.getElementById(n);e?.textContent&&r.push(e.textContent.trim())}catch{}if(r.length)return Nh(r.join(` `))}if(e.labels&&e.labels.length)return Nh(e.labels[0].textContent);let r=e.id;if(r)try{let e=t.querySelector(`label[for="${CSS.escape(r)}"]`);if(e)return Nh(e.textContent)}catch{let e=t.querySelector(`label[for="${r.replace(/"/g,`\\"`)}"]`);if(e)return Nh(e.textContent)}let i=e.previousElementSibling;for(let e=0;e<6&&i;e+=1){if(i.tagName===`LABEL`)return Nh(i.textContent);let e=(i.className||``).toString().toLowerCase();if(/chakra-form__label|formlabel|field-label|form-label|mui-form-label/.test(e)){let e=Nh(i.textContent);if(e)return e}i=i.previousElementSibling}let a=e.parentElement;for(let e=0;e<5&&a;e+=1){if(a.tagName===`LABEL`)return Nh(a.textContent);let e=a.querySelector?.(`:scope > label, :scope > [class*='FormLabel'], :scope > [class*='form__label']`);if(e?.textContent)return Nh(e.textContent);a=a.parentElement}let o=e.getAttribute(`aria-label`);return o?Nh(o):null}function Fh(){let e=[];return Mh(t=>{e.push(...Array.from(t.querySelectorAll(`input, select, textarea`)).filter(e=>{if(Ah(e))return!1;let t=(e.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`image`].includes(t)||e.disabled||e.readOnly)return!1;try{let t=jh(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))}),e}function Ih(){return Fh().map((e,t)=>({formIndex:0,fieldIndex:t,tag:e.tagName,type:e.type||`text`,name:e.name||null,id:e.id||null,label:Ph(e),placeholder:e.placeholder||null}))}function Lh(){let e=[];return Mh(t=>{e.push(...Array.from(t.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(Ah(e)||e.disabled)return!1;try{let t=jh(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))}),e.slice(0,60).map((e,t)=>({index:t,text:(e.textContent||e.value||``).replace(/\s+/g,` `).trim().slice(0,120)||null,ariaLabel:e.getAttribute(`aria-label`),type:e.type||e.tagName}))}function Rh(e){return String(e||``).toLowerCase().replace(/\u00a0/g,` `).replace(/\*/g,``).replace(/\s+/g,` `).trim()}function zh(e){let t=Rh(e);return t=t.replace(/\s+field\s*$/i,``).trim(),t}function Bh(e,t){let n=zh(t);if(!n)return 0;let r=(e.name||``).toLowerCase(),i=(e.id||``).toLowerCase();if(r===`url`&&/url|website|domain|site|audit/.test(n)||(i===`url-input`||i.endsWith(`-url-input`))&&/url|website|domain|site|audit/.test(n))return 100;let a=[e.name,e.id,e.placeholder,Ph(e),e.getAttribute(`aria-label`),e.getAttribute(`title`),e.getAttribute(`data-testid`),e.getAttribute(`autocomplete`)].filter(Boolean).map(e=>Rh(e)),o=0;for(let e of a){if(!e)continue;if(e.includes(n)||n.includes(e)){o=Math.max(o,100);continue}let t=n.split(/\s+/).filter(e=>e.length>1);if(!t.length)continue;let r=0;for(let n of t)e.includes(n)&&(r+=1);o=Math.max(o,r/t.length*88)}return o}var Vh=28;function Hh(e,t){let n=null,r=0;for(let i of e){let e=Bh(i,t);e>r&&(r=e,n=i)}return!n||r<Vh?null:n}function Uh(e,t,n){let r=String(t||``).toLowerCase().trim(),i=String(n||``).trim();if(!(/^https?:\/\//i.test(i)||/\.\w{2,}(\/|\s|$)/.test(i)||r.includes(`url`)||r.includes(`website`)||r.includes(`domain`)||r.includes(`site`)))return null;let a=null,o=0;for(let t of e){if(t.tagName!==`INPUT`&&t.tagName!==`TEXTAREA`)continue;let e=(t.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`checkbox`,`radio`].includes(e))continue;let n=0;(e===`url`||e===`text`||e===`search`)&&(n+=45);let r=[t.name,t.id,t.placeholder,Ph(t),t.getAttribute(`aria-label`),t.getAttribute(`autocomplete`)].filter(Boolean).join(` `).toLowerCase();/(website|url|domain|site\s*url)/.test(r)&&(n+=55),n>o&&(o=n,a=t)}return!a||o<42?null:a}function Wh(e){let t=String(e??``).trim();return t?/^https?:\/\//i.test(t)?!0:/\.\w{2,}(\/|\s|$)/.test(t):!1}function Gh(e){let t=String(e??``).toLowerCase().trim();return t?!!(t===`url`||t===`website`||t===`website url`||t===`website_url`||t===`enter website url`||t.includes(`website`)||t.includes(`domain`)||/(enter\s+website|site\s*url|page\s*url)/.test(t)):!1}function Kh(e){if(!e||e.tagName!==`INPUT`&&e.tagName!==`TEXTAREA`)return!1;let t=(e.type||``).toLowerCase();return![`hidden`,`submit`,`button`,`checkbox`,`radio`,`file`].includes(t)}function qh(e){if(!Kh(e))return!1;let t=(e.name||``).toLowerCase(),n=(e.id||``).toLowerCase(),r=[e.name,e.id,e.placeholder,Ph(e),e.getAttribute(`aria-label`)].filter(Boolean).join(` `).toLowerCase();return t===`url`||n===`url-input`||n.endsWith(`-url-input`)||/(website\s*url|enter\s+website|site\s*url)/.test(r)||/(website|domain)/.test(r)&&/(url|site)/.test(r)}function Jh(e,t,n){let r=String(t??``),i=String(n??``),a=Zh(e,r)||Hh(e,r)||Uh(e,r,i);if(!a)return[];let o=new Set([a]);if(Wh(i)&&Gh(r))for(let t of e)t!==a&&qh(t)&&o.add(t);let s=Array.from(o);return s.sort((e,t)=>{if(e===t)return 0;let n=e.compareDocumentPosition(t);return n&Node.DOCUMENT_POSITION_FOLLOWING?-1:n&Node.DOCUMENT_POSITION_PRECEDING?1:0}),s}function Yh(e,t){try{if(!e?.getBoundingClientRect||!t?.getBoundingClientRect)return 1/0;let n=e.getBoundingClientRect(),r=t.getBoundingClientRect(),i={x:n.left+n.width/2,y:n.top+n.height/2},a={x:r.left+r.width/2,y:r.top+r.height/2};return Math.hypot(i.x-a.x,i.y-a.y)}catch{return 1/0}}function Xh(e){if(!e||typeof e!=`string`)return null;let t=null;return Mh(n=>{try{let r=n.getElementById(e);r&&!Ah(r)&&r.matches?.(`input, select, textarea`)&&(t=r)}catch{}}),t}function Zh(e,t){let n=String(t??``).trim();if(!n)return null;let r=n.match(/^name:\s*([\w.-]+)$/i);if(r){let t=r[1];for(let n of e)if(n.name===t)return n}let i=n.match(/^id:\s*([\w.-]+)$/i);if(i){let e=Xh(i[1]);if(e)return e}let a=n.startsWith(`#`)?n.slice(1):n;if(/^[\w-]+$/.test(a)){let e=Xh(a);if(e)return e}let o=n.toLowerCase().replace(/\s+/g,` `);if(o===`url`||o===`website`||o===`website url`||o===`website_url`||o===`enter website url`)for(let t of e){let e=(t.name||``).toLowerCase(),n=(t.id||``).toLowerCase();if(e===`url`||n===`url-input`||n.endsWith(`-url-input`))return t}return null}function Qh(e,t){let n=String(t||``).toLowerCase().trim();if(!n)return 0;let r=[e.textContent,e.value,e.getAttribute(`aria-label`),e.getAttribute(`title`)].filter(Boolean).join(` `).toLowerCase().replace(/\s+/g,` `);if(r.includes(n))return 100;let i=n.split(/\s+/).filter(e=>e.length>1);if(!i.length)return 0;let a=0;for(let e of i)r.includes(e)&&(a+=1);return a/i.length*92}function $h(e,t){let n=[];Mh(e=>{n.push(...Array.from(e.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(Ah(e)||e.disabled)return!1;try{let t=jh(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))});let r=0,i=n.map(t=>({el:t,s:Qh(t,e)}));for(let{s:e}of i)e>r&&(r=e);if(r<36)return null;let a=i.filter(({s:e})=>e===r).map(({el:e})=>e);if(a.length===1)return a[0];let o=Array.isArray(t)?t.filter(e=>e&&e.isConnected):[];if(o.length){let e=a[0],t=1/0;for(let n of a)for(let r of o){let i=Yh(n,r);i<t&&(t=i,e=n)}return e}return a[0]}function eg(e){if(e==null)return{};if(typeof e==`string`){let t=e.trim();if(!t)return{};try{return JSON.parse(t)}catch{return{url:t}}}return e}function tg(e){let t=eg(e);if(Array.isArray(t)&&t.length>0){let e=t[0];if(e?.field_key!=null||e?.fieldKey!=null)return t.map(e=>({field_key:e.field_key??e.fieldKey,value:e.value}))}if(!t||typeof t!=`object`)return[];let n=t.fields??t.Fields??t.field_list??t.fieldList??t.data?.fields;if(typeof n==`string`)try{n=JSON.parse(n)}catch{n=null}n&&!Array.isArray(n)&&typeof n==`object`&&(n=Object.values(n)),(!n||n.length===0)&&(t.field_key!=null||t.fieldKey!=null)&&t.value!=null&&(n=[{field_key:t.field_key??t.fieldKey,value:t.value}]);let r=t.website_url??t.websiteUrl??t.url??t.website??t.domain??t.site_url??t.siteUrl;return(!n||n.length===0)&&r!=null&&String(r).trim()&&(n=[{field_key:t.field_key??t.fieldKey??`url`,value:String(r).trim()}]),Array.isArray(n)?n.map(e=>({field_key:e?.field_key??e?.fieldKey,value:e?.value??e?.Value})):[]}function ng(e){if(!e||typeof e!=`string`)return[];let t=e.trim();if(!t||/\b[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}\b/i.test(t))return[];let n=t.match(/https?:\/\/[^\s<>"']+/i);if(n)return[{field_key:`url`,value:n[0].replace(/[.,;:)]+$/,``)}];let r=t.match(/\b(?:[\w-]+\.)+[a-z]{2,}\b/i);if(r){let e=r[0].replace(/[.,;:)]+$/,``);return/^https?:/i.test(e)||(e=`https://${e}`),[{field_key:`url`,value:e}]}return[]}function rg(e){if(!e||typeof e!=`string`)return[];let t=e.trim();if(!t)return[];let n=[],r=new Set,i=/\b([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,})\b/i,a=(e,t)=>{let i=String(t??``).trim().replace(/^["']|["']$/g,``);if(!i||i.length>800)return;let a=`${e}\0${i}`;r.has(a)||(r.add(a),n.push({field_key:e,value:i}))},o=t.match(/^\s*([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,})\s*$/i);if(o)return a(`Email Address`,o[1]),n;let s=t.match(/\b(?:please\s+)?(?:enter|type|put)\s+(.+?)\s+in(?:to)?\s+(?:the\s+)?(?:full\s*name|full\s*name\s*field|name\s*field)\b/i);if(s&&a(`Full Name`,s[1]),s=t.match(/\bfull\s*name,?\s*(?:please\s+)?(?:enter|type|put)\s+(.+?)(?:\.|$|!|\?)/i),s&&a(`Full Name`,s[1]),s=t.match(/\bfull\s*name\s*(?:is|:|please\s+enter|-)\s*(.+?)(?:\.|$|(?=\s+(?:and|my\s+email|email|message))\b)/i),s&&a(`Full Name`,s[1]),s=t.match(/\b(.+?)\s+for\s+(?:the\s+)?full\s*name\b/i),s){let e=s[1].trim();e.length>1&&e.length<120&&!/@/.test(e)&&a(`Full Name`,e)}if(s=t.match(/\b(?:email|e-mail)(?:\s*address)?\s*(?:is|:|please\s+use|enter|-)\s*([^\s@]+@[^\s@]+\.[^\s,]+)/i),s&&a(`Email Address`,s[1]),s=t.match(/\b(?:enter|type|put)\s+([^\s@]+@[^\s@]+\.[^\s,]+)\s+in(?:to)?\s+(?:the\s+)?(?:email|e-mail)/i),s&&a(`Email Address`,s[1]),s=t.match(/\b(?:message|comment)\s*(?:is|:|please\s+enter|-)\s*(.+)$/is),s){let e=s[1].trim();e.length>0&&a(`Message`,e)}if(!n.some(e=>/email/i.test(String(e.field_key)))){let e=t.match(i);if(e){let r=t.replace(e[0],``).trim().replace(/^(please|it's|it is|use|is|my email is|e-?mail is)\s*/i,``).replace(/[.,;:!?]+$/,``).trim();if(t.length<=96&&r.length<=36)return a(`Email Address`,e[1]),n}}if(n.length===0){let e=t.split(/\s+/).filter(Boolean).length,n=/[.!?]/.test(t)||e>=6||t.length>=24&&e>=5||t.length>=42,r=/^[A-Z][a-z]+\s+[A-Z][a-z]+$/.test(t.trim());n&&t.length>=16&&!i.test(t)&&!r&&a(`Message`,t)}return n}function ig(e){if(!e||typeof e!=`object`)return null;let t=e.url??e.target_url??e.page_url??e.pageUrl??e.link??e.href??e.path;return t==null?null:String(t).trim()||null}function ag(e){if(!e||typeof e!=`object`)return null;let t=e.query??e.q??e.search??e.text??e.keywords;return t==null?null:String(t).trim()||null}function og(e,t,n){if(!n?.skipScroll)try{e.scrollIntoView({block:`center`,inline:`nearest`})}catch{try{e.scrollIntoView(!0)}catch{}}try{e.focus({preventScroll:!0})}catch{try{e.focus()}catch{}}let r=e.tagName,i=(e.type||``).toLowerCase();if(r===`SELECT`)return e.value=String(t),e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0})),!0;if(i===`checkbox`||i===`radio`)return e.checked=[`1`,`true`,`yes`,`on`].includes(String(t).toLowerCase().trim()),e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0})),!0;let a=String(t);if(r===`INPUT`||r===`TEXTAREA`){let t=e.ownerDocument?.defaultView||window,n=r===`TEXTAREA`?t.HTMLTextAreaElement.prototype:t.HTMLInputElement.prototype,i=Object.getOwnPropertyDescriptor(n,`value`);i?.set?i.set.call(e,a):e.value=a}else e.value=a;let o={bubbles:!0,cancelable:!0,composed:!0};try{e.dispatchEvent(new InputEvent(`input`,{...o,inputType:`insertText`,data:a}))}catch{e.dispatchEvent(new Event(`input`,o))}e.dispatchEvent(new Event(`change`,o));try{queueMicrotask(()=>{try{e.dispatchEvent(new Event(`input`,o)),e.dispatchEvent(new Event(`change`,o))}catch{}})}catch{}return!0}function sg(e){let t=e.siteId||null,n=(e.apiBaseUrl||``).replace(/\/$/,``),r=typeof e.getLastUserVoiceText==`function`?e.getLastUserVoiceText:null,i=[],a={navigate_to_page:async n=>{$(`navigate_to_page ▶ raw parameters:`,n);let r=eg(n),i=ig(r),a=r.section_text??r.sectionText??r.section;if($(`navigate_to_page · coerced:`,{url:i,sectionText:a}),!i){let e=`Missing url: pass a string url, path like /pricing, or JSON with a url field.`;return $(`navigate_to_page ✖`,e),e}if(!await sn(i,{siteId:t,apiBaseUrl:e.apiBaseUrl})){let e=`That page is not available in the site index; answer without navigating.`;return $(`navigate_to_page ✖ blocked`,e),e}try{if($(`navigate_to_page → shadowNavigate`,i),await cn(i),await new Promise(e=>setTimeout(e,400)),a&&typeof a==`string`){let e=tn(null,a);e&&nn(e),$(`navigate_to_page · highlight`,{sectionText:a,found:!!e})}let e=`OK_NAVIGATION ${i}`;return $(`navigate_to_page ✓`,e),e}catch(e){let t=`Navigation error: ${e?.message||String(e)}`;return $(`navigate_to_page ✖`,t),t}},highlight_on_page:async e=>{$(`highlight_on_page ▶`,e);let t=eg(e),n=t?.section_id||t?.sectionId,r=t?.section_text||t?.sectionText,i=tn(n||null,r||null);return i?(nn(i),$(`highlight_on_page ✓`),`Highlighted the section.`):($(`highlight_on_page ✖ no element`),`Could not find that section on the page.`)},search_site_content:async e=>{$(`search_site_content ▶`,e);let r=ag(eg(e));if($(`search_site_content · query:`,r,`siteId:`,t,`apiBase:`,n||`(empty)`),!r)return $(`search_site_content ✖ missing query`),`Missing query parameter.`;if(!t)return $(`search_site_content ✖ no siteId`),`Site is not configured for search.`;if(!n)return $(`search_site_content ✖ no api base`),`API base URL is missing; cannot search.`;try{let e=`${n}/api/site-tools/search`;$(`search_site_content → POST`,e);let i=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({siteId:t,query:r,currentUrl:typeof window<`u`?window.location.href:``})}),a=await i.json();if($(`search_site_content · HTTP`,i.status,`success:`,a.success),!a.success){let e=a.error||`Search failed.`;return $(`search_site_content ✖`,e),e}let o=a.results||[];return $(`search_site_content ✓`,`${o.length} result(s)`,o.slice(0,3).map(e=>e?.url||e)),JSON.stringify(o)}catch(e){let t=`Search error: ${e.message||`network`}`;return $(`search_site_content ✖`,t),t}},list_page_forms:async()=>{let e=Ih(),t=Lh();return $(`list_page_forms ✓`,`${e.length} field(s)`,`${t.length} button(s)`),JSON.stringify({fields:e,buttons:t,hint:`field_key: placeholder/label, name (e.g. url), id (e.g. url-input). If the page has two URL boxes, fill_form_fields sets all matching URL inputs. click_page_button picks the Conduct Audit nearest the filled field when labels duplicate.`})},fill_form_fields:async e=>{try{$(`fill_form_fields ▶ raw:`,e);let t=tg(e);if(!t.length&&r){let e=r(),n=ng(e);n.length?$(`fill_form_fields · inferred URL from last user utterance (model omitted usable fields):`,n):(n=rg(e),n.length&&$(`fill_form_fields · inferred contact fields from last user utterance (empty tool params):`,n)),n.length&&(t=n)}if($(`fill_form_fields · normalized fields:`,t),!t.length)return`No fields provided. Call list_page_forms for field_key strings, then fill_form_fields with { "fields": [ { "field_key": "<label or placeholder from list>", "value": "<user value>" } ] }. Never use empty {}. Pass the value the user just said (email, message, name, URL) in fields.`;let n=[];for(let e of t){let t=e?.field_key??e?.fieldKey,r=e?.value;if(t==null||r==null)continue;let a=Fh(),o=Jh(a,String(t),r);if(o.length){o.forEach((e,t)=>{og(e,r,{skipScroll:t>0})}),i=o,n.push(String(t));continue}let s=Zh(a,String(t));s||=Hh(a,String(t)),s||=Uh(a,String(t),r),s&&(og(s,r),i=[s],n.push(String(t)))}if(!n.length)return $(`fill_form_fields ✖ no matches`),`Could not match any fields. Call list_page_forms and use field_key values that match placeholder, label, name, or id (e.g. Enter Website URL). Ensure the form is on the page, not the chat panel.`;let a=`OK_FILLED: ${n.join(`, `)}`;return $(`fill_form_fields ✓`,a),a}catch(e){let t=`fill_form_fields error: ${e?.message||String(e)}`;return $(`fill_form_fields ✖`,t),t}},click_page_button:async e=>{let t=eg(e),n=(t.button_text??t.buttonText??t.text??``).trim();if($(`click_page_button ▶`,n),!n)return`Missing button_text: pass the visible label, e.g. Conduct Audit.`;let r=$h(n,i);if(!r)return $(`click_page_button ✖ no match`),`Could not find a button matching "${n}". Call list_page_forms to see button texts.`;try{try{r.scrollIntoView({block:`center`,inline:`nearest`})}catch{r.scrollIntoView(!0)}r.focus?.(),r.click();let e=`OK_CLICK ${(r.textContent||r.value||r.getAttribute(`aria-label`)||``).trim().slice(0,80)||`button`}`;return $(`click_page_button ✓`,e),e}catch(e){let t=`Click failed: ${e?.message||String(e)}`;return $(`click_page_button ✖`,t),t}}};return{...a,navigateToPage:a.navigate_to_page,highlightOnPage:a.highlight_on_page,searchSiteContent:a.search_site_content,listPageForms:a.list_page_forms,fillFormFields:a.fill_form_fields,clickPageButton:a.click_page_button}}function cg(e){return!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,async n=>{let r=Qt();r?console.log(`[FlowEngage:voice-tool] ▶`,e,n):console.info(`[FlowEngage] voice tool » ${e}`);let i=await t(n),a=typeof i==`string`?i.length>220?`${i.slice(0,220)}…`:i:String(i);return r?console.log(`[FlowEngage:voice-tool] ◀`,e,a):console.info(`[FlowEngage] voice tool « ${e}:`,a),i}]))}var lg={idle:`rgba(99,102,241,0.18)`,listening:`rgba(16,185,129,0.25)`,speaking:`rgba(245,158,11,0.25)`,error:`rgba(239,68,68,0.2)`},ug={idle:`#6366f1`,listening:`#10b981`,speaking:`#f59e0b`,error:`#ef4444`};function dg({agentId:e,chatId:t,siteId:n,apiBaseUrl:r,onEnd:i,historyRef:a,hasSyncedRef:o,onMessageSync:s,onStartSync:c}){let[l,u]=(0,v.useState)(`idle`),[d,f]=(0,v.useState)(null),[p,m]=(0,v.useState)(!1),h=(0,v.useRef)(null),g=(0,v.useRef)(null),_=(0,v.useRef)(``);(0,v.useEffect)(()=>{let t=!1,i=null;return(async()=>{try{if(await navigator.mediaDevices.getUserMedia({audio:!0}),t)return;a.current=[],_.current=``;let o=cg(sg({siteId:n||null,apiBaseUrl:r||null,getLastUserVoiceText:()=>_.current})),s=await Oh.startSession({agentId:e,clientTools:o,onUnhandledClientToolCall:e=>{console.error(`[VoiceInterface] ElevenLabs requested a client tool that is not registered in the widget:`,e?.tool_name,e?.parameters,`Add a matching handler in voiceClientTools (snake_case and camelCase are both supported).`)},onModeChange:({mode:e})=>{t||u(e===`speaking`?`speaking`:`listening`)},onMessage:e=>{if(t)return;let n=e.role===`user`?`user`:`bot`,r=e.message||e.text||e.content||``;if(!r)return;let i={sender:n,message:r,timestamp:new Date().toISOString()};n===`user`&&(_.current=r),a.current=[...a.current,i]},onError:e=>{t||(console.error(`[VoiceInterface] ElevenLabs error`,e),u(`error`),f(`Voice session encountered an error.`))},onDisconnect:()=>{t||(console.log(`[VoiceInterface] session disconnected`),m(!1),u(`idle`))}});if(t){s.endSession().catch(()=>{});return}i=s,h.current=s,m(!0),u(`listening`);try{let e=typeof window<`u`?window.location.href:``,t=``;try{t=await o.list_page_forms()}catch{t=`[]`}s.sendContextualUpdate(`Current page URL: ${e}. Site ID: ${n||`unknown`}. Page fields/buttons JSON: ${t}. Navigation: search_site_content then navigate_to_page with section_text when relevant — no permission ask. Forms: use fill_form_fields then click_page_button (e.g. Conduct Audit) when the user wants to submit.`)}catch{}typeof c==`function`&&c()}catch(e){t||(console.error(`[VoiceInterface] startSession failed`,e),u(`error`),f(`Could not start voice session. Please try again.`))}})(),()=>{t=!0,i?i.endSession().catch(()=>{}):h.current&&h.current.endSession().catch(()=>{})}},[e,n,r,a,c]);let y=(0,v.useCallback)(async()=>{try{await h.current?.endSession?.()}catch{}h.current=null,m(!1),u(`idle`),typeof s==`function`&&await s(a.current),typeof i==`function`&&i()},[a,s,i]),b=l===`listening`||l===`speaking`,x=ug[l]||ug.idle,ee=lg[l]||lg.idle;return(0,A.jsxs)(`div`,{ref:g,style:{display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,flex:1,gap:`24px`,padding:`24px 20px`,background:`transparent`},children:[(0,A.jsxs)(`div`,{style:{position:`relative`,width:`140px`,height:`140px`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:[b&&(0,A.jsx)(`div`,{style:{position:`absolute`,inset:`-16px`,borderRadius:`50%`,border:`2px solid ${x}`,animation:`fe-orb-pulse 1.4s ease-in-out infinite`,opacity:.6}}),b&&(0,A.jsx)(`div`,{style:{position:`absolute`,inset:`-8px`,borderRadius:`50%`,border:`2px solid ${x}`,animation:`fe-orb-pulse 1.4s ease-in-out 0.35s infinite`,opacity:.4}}),(0,A.jsx)(`div`,{style:{width:`140px`,height:`140px`,borderRadius:`50%`,background:ee,border:`3px solid ${x}`,display:`flex`,alignItems:`center`,justifyContent:`center`,transition:`all 0.35s ease`,transform:l===`speaking`?`scale(1.08)`:`scale(1)`,boxShadow:`0 0 40px ${ee}, 0 8px 32px rgba(0,0,0,0.08)`},children:(0,A.jsx)(yn,{size:44,color:x})})]}),(0,A.jsxs)(`div`,{style:{fontSize:`15px`,fontWeight:600,color:l===`error`?`#ef4444`:`#374151`,letterSpacing:`0.01em`,textAlign:`center`},children:[l===`idle`&&`Starting voice session…`,l===`listening`&&`Listening…`,l===`speaking`&&`AI is speaking…`,l===`error`&&(d||`Error`)]}),(0,A.jsxs)(`button`,{onClick:y,style:{display:`flex`,alignItems:`center`,gap:`8px`,padding:`12px 24px`,borderRadius:`999px`,background:`#fee2e2`,color:`#dc2626`,border:`1px solid #fca5a5`,fontWeight:600,fontSize:`14px`,cursor:`pointer`,transition:`all 0.2s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`#fecaca`},onMouseLeave:e=>{e.currentTarget.style.background=`#fee2e2`},children:[(0,A.jsx)(bn,{size:18}),`End Voice Session`]}),(0,A.jsx)(`style`,{children:`
|
|
327
327
|
@keyframes fe-orb-pulse {
|
|
328
328
|
0% { transform: scale(1); opacity: 0.6; }
|
|
329
329
|
50% { transform: scale(1.18); opacity: 0.15; }
|
|
@@ -334,5 +334,5 @@ registerProcessor("scribeAudioProcessor", ScribeAudioProcessor);
|
|
|
334
334
|
0%, 80%, 100% { transform: translateY(0); opacity: 0.5; }
|
|
335
335
|
40% { transform: translateY(-5px); opacity: 1; }
|
|
336
336
|
}
|
|
337
|
-
`})]})});function mg(){let{status:e,runtimeConfig:t,resolvedConfig:n,chatId:r,chatHistory:i,isOpen:a,activeScreen:o,isHumanHandled:s,agentName:c,agentHeadshot:l,visitorEmail:u,isAgentTyping:d,isAiTyping:f,isLoading:p,isVoiceMode:m,isRateLimited:h,rateLimitMessage:g,isConversationEnded:_,incomingCall:y,activeCallId:b,callConnectionState:x,callConnectedAt:ee,isCallMuted:te,webRTCError:S,language:ne,historyRef:re,onMessageSync:ie,endConversation:ae,acceptCall:oe,rejectCall:se,endWebRTCCall:ce,toggleCallMute:le,dismissCallError:ue,captureVisitorEmail:de,openWidget:fe,closeWidget:C,sendMessage:w,setVoiceMode:pe,startTyping:me,stopTyping:he,updateTypingDraft:ge}=Zt(),[_e,T]=(0,v.useState)(``),[ve,ye]=(0,v.useState)(null),[be,xe]=(0,v.useState)(null),[Se,Ce]=(0,v.useState)(null),[we,Te]=(0,v.useState)(0),[Ee,De]=(0,v.useState)(u||``),[E,Oe]=(0,v.useState)(``),ke=t?.widgetSettings||{},Ae=n?.widgetSettings||{},je={...ke.branding||{},...Ae.branding||{}},Me={...ke.theme||{},...Ae.theme||{}},D=Me.primaryColor||`#3B82F6`,Ne=Me.accentColor||`#1D4ED8`,Pe=(Me.position||`bottom-right`)===`bottom-left`?{left:`1.5rem`,bottom:`1.5rem`}:{right:`1.5rem`,bottom:`1.5rem`},Fe={"--flowengage-primary":D,"--flowengage-accent":Ne,position:`fixed`,zIndex:999999,border:`none`,outline:`none`,fontFamily:`ui-sans-serif, system-ui, sans-serif`,...a?{}:Pe},Ie=Ae.recommendations?.[ne]||ke.recommendations?.[ne]||fg,Le=Ae.greetings?.[ne]||ke.greetings?.[ne],Re=je.chatButtonText||`Chat with us`,ze=je.headerName||t?.websiteName||`OpenSense Labs`,O=je.logoUrl||null,Be=je.hideWatermark||!1,Ve=Ae.elevenLabsAgentId||t?.elevenLabsAgentId||null,He=t?.siteId||n?.siteId||null,Ue=t?.apiBaseUrl||``,We=je.fallbackAgentName||`Agent`,Ge=je.botLabel||`AI`,Ke=l&&String(l).trim()||t?.ownerProfileImageUrl&&String(t.ownerProfileImageUrl).trim()||null,qe=y?.agentName||c||We,Je=!u&&
|
|
338
|
-
@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-border-style:solid;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-ease:initial}}:root,:host{--spacing:.25rem;--ease-in-out:cubic-bezier(.4, 0, .2, 1);--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1)}.visible{visibility:visible}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.static{position:static}.start{inset-inline-start:var(--spacing)}.end{inset-inline-end:var(--spacing)}.container{width:100%}@media (width>=40rem){.container{max-width:40rem}}@media (width>=48rem){.container{max-width:48rem}}@media (width>=64rem){.container{max-width:64rem}}@media (width>=80rem){.container{max-width:80rem}}@media (width>=96rem){.container{max-width:96rem}}.block{display:block}.flex{display:flex}.hidden{display:none}.inline{display:inline}.inline-block{display:inline-block}.inline-flex{display:inline-flex}.transform{transform:var(--tw-rotate-x,) var(--tw-rotate-y,) var(--tw-rotate-z,) var(--tw-skew-x,) var(--tw-skew-y,)}.border{border-style:var(--tw-border-style);border-width:1px}.uppercase{text-transform:uppercase}.ring{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.outline{outline-style:var(--tw-outline-style);outline-width:1px}.filter{filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.ease-in-out{--tw-ease:var(--ease-in-out);transition-timing-function:var(--ease-in-out)}.flowengage-shell,.flowengage-shell *{font-family:inherit}.flowengage-chat-panel{border:none;border-radius:0;outline:none;flex-direction:column;width:100%;height:100%;display:flex;position:relative;overflow:hidden;box-shadow:0 20px 50px #00000026}@media (width>=768px){.flowengage-chat-panel{border-radius:24px;width:min(423px,100vw - 40px);height:min(700px,100vh - 120px)}}.flowengage-shell[data-open=true]{inset:0}@media (width>=768px){.flowengage-shell[data-open=true]{inset:auto 1.5rem 1.5rem auto}}.flowengage-logo-fallback{background:conic-gradient(from 180deg, var(--flowengage-primary) 0%, #2b70b5 50%, #f59e0b 100%)}.fe-bot-message p{margin:0 0 .5em}.fe-bot-message p:last-child{margin-bottom:0}.fe-bot-message ul,.fe-bot-message ol{margin:.4em 0 .4em 1.2em;padding:0}.fe-bot-message li{margin-bottom:.25em}.fe-bot-message strong{font-weight:600}.fe-bot-message a{color:var(--flowengage-primary);text-decoration:underline}.fe-bot-message a:hover{opacity:.8}.incoming-call-overlay{z-index:1000;-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);background:#1a1a2ef2;justify-content:center;align-items:center;transition:all .3s ease-in-out;display:flex;position:absolute;left:0;right:0}.incoming-call-overlay.bottom-mode{border-top:2px solid #ffffff1a;min-height:120px;animation:.4s cubic-bezier(.16,1,.3,1) slideUpBanner;top:auto;bottom:0;box-shadow:0 -10px 30px #00000080}.incoming-call-overlay.header-mode{border-bottom:2px solid #ffffff1a;min-height:80px;animation:.4s cubic-bezier(.16,1,.3,1) slideDownBanner;top:0;bottom:auto;box-shadow:0 10px 30px #00000080}.incoming-call-container{justify-content:space-between;align-items:center;gap:14px;width:100%;padding:14px 16px;display:flex}.incoming-call-container.connected-layout{flex-direction:column;justify-content:center;align-items:stretch;gap:14px}.call-connected-top{justify-content:space-between;align-items:center;gap:16px;width:100%;display:flex}.call-connected-identity{flex:1;align-items:center;gap:14px;min-width:0;display:flex}.call-icon-wrapper{color:#fff;z-index:1;border-radius:9999px;flex-shrink:0;justify-content:center;align-items:center;width:54px;height:54px;margin-right:4px;display:flex;position:relative}.call-icon-wrapper.incoming{background:linear-gradient(135deg,#4caf50,#45a049);animation:1s ease-in-out infinite bounce}.call-icon-wrapper.connecting{background:linear-gradient(135deg,#2196f3,#1976d2)}.call-icon-wrapper.connected{background:linear-gradient(135deg,#4caf50,#45a049)}.call-pulse-animation{z-index:-1;background:#4caf504d;border-radius:50%;width:120px;height:120px;animation:1.5s ease-out infinite pulse;position:absolute}.call-connecting-animation{z-index:-1;border:3px solid #0000;border-top-color:#2196f3;border-radius:50%;width:100px;height:100px;animation:1s linear infinite spin;position:absolute}.call-info-group{flex-direction:column;flex:1;min-width:0;margin-right:8px;display:flex}.call-title{color:#fff;white-space:normal;text-overflow:clip;margin:0;font-size:16px;font-weight:700;line-height:1.2;overflow:visible}.call-subtitle{color:#ffffffb3;white-space:normal;text-overflow:clip;margin:4px 0 0;font-size:12px;line-height:1.35;overflow:visible}.call-timer{text-align:center;color:#fff;flex-shrink:0;min-width:54px;font-size:13px;font-weight:700}.call-actions{flex-shrink:0;align-items:center;gap:8px;display:flex}.call-actions.connected{justify-content:center;width:100%}.flowengage-call-btn{cursor:pointer;color:#fff;border:none;border-radius:8px;justify-content:center;align-items:center;gap:6px;min-width:92px;padding:8px 12px;font-size:12px;font-weight:600;line-height:1;transition:transform .2s,box-shadow .2s,background .2s;display:flex}.flowengage-call-btn svg{flex-shrink:0;display:block}.flowengage-call-btn span{justify-content:center;align-items:center;line-height:1;display:flex}.flowengage-call-btn.icon-only{border-radius:9999px;width:46px;min-width:46px;height:46px;padding:0}.flowengage-call-btn-accept{background:linear-gradient(135deg,#4caf50,#45a049);box-shadow:0 8px 24px #4caf5066}.flowengage-call-btn-reject,.flowengage-call-btn-end{background:linear-gradient(135deg,#f44336,#d32f2f);box-shadow:0 4px 12px #f4433666}.flowengage-call-btn-mute{background:#ffffff1a;border:2px solid #fff3}.flowengage-call-btn-mute.active{background:#f443364d;border-color:#f44336}.flowengage-call-btn:hover:not(:disabled){transform:scale(1.05)}.incoming-call-overlay.header-mode .flowengage-call-btn{border-radius:9999px!important;width:36px!important;min-width:36px!important;height:36px!important;padding:0!important}.incoming-call-overlay.header-mode .flowengage-call-btn span{display:none!important}.incoming-call-overlay.header-mode .call-icon-wrapper{width:40px;height:40px;margin-right:0}.incoming-call-overlay.header-mode .call-info-group{min-width:0}.incoming-call-overlay.header-mode .call-title,.incoming-call-overlay.header-mode .call-subtitle{white-space:nowrap;text-overflow:ellipsis;overflow:hidden}@media (width<=640px){.incoming-call-container{align-items:flex-start;gap:10px;padding:12px 14px}.incoming-call-container.connected-layout{align-items:stretch}.call-connected-top{flex-direction:column;align-items:flex-start;gap:10px}.call-connected-identity{width:100%}.call-info-group{margin-right:0}.call-actions{flex-wrap:wrap;align-self:stretch;gap:6px}.call-actions.connected{justify-content:stretch}.call-actions.connected .flowengage-call-btn{flex:1}.flowengage-call-btn{min-width:78px;padding:8px 10px}}@keyframes slideUpBanner{0%{transform:translateY(100%)}to{transform:translateY(0)}}@keyframes slideDownBanner{0%{transform:translateY(-100%)}to{transform:translateY(0)}}@keyframes bounce{0%,to{animation-timing-function:cubic-bezier(.8,0,1,1);transform:translateY(-25%)}50%{animation-timing-function:cubic-bezier(0,0,.2,1);transform:none}}@keyframes pulse{50%{opacity:.5}}@keyframes spin{to{transform:rotate(360deg)}}.fe-screen-fade-in{animation:.4s cubic-bezier(.16,1,.3,1) forwards feFadeIn}@keyframes feFadeIn{0%{opacity:0;transform:translateY(12px)}to{opacity:1;transform:translateY(0)}}.flowengage-initial-bg{background-color:#fff;position:relative;overflow:hidden}.flowengage-initial-bg:before{content:"";background:linear-gradient(to bottom, var(--flowengage-primary) 0%, var(--flowengage-primary) 55%, white 82%);opacity:0;pointer-events:none;z-index:0;transition:opacity .6s cubic-bezier(.4,0,.2,1);position:absolute;inset:0}.flowengage-initial-bg.is-initial:before{opacity:1}.flowengage-content-wrapper{z-index:1;flex-direction:column;flex:1;min-height:0;display:flex;position:relative}@property --tw-rotate-x{syntax:"*";inherits:false}@property --tw-rotate-y{syntax:"*";inherits:false}@property --tw-rotate-z{syntax:"*";inherits:false}@property --tw-skew-x{syntax:"*";inherits:false}@property --tw-skew-y{syntax:"*";inherits:false}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"<length>";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-blur{syntax:"*";inherits:false}@property --tw-brightness{syntax:"*";inherits:false}@property --tw-contrast{syntax:"*";inherits:false}@property --tw-grayscale{syntax:"*";inherits:false}@property --tw-hue-rotate{syntax:"*";inherits:false}@property --tw-invert{syntax:"*";inherits:false}@property --tw-opacity{syntax:"*";inherits:false}@property --tw-saturate{syntax:"*";inherits:false}@property --tw-sepia{syntax:"*";inherits:false}@property --tw-drop-shadow{syntax:"*";inherits:false}@property --tw-drop-shadow-color{syntax:"*";inherits:false}@property --tw-drop-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-drop-shadow-size{syntax:"*";inherits:false}@property --tw-ease{syntax:"*";inherits:false}`,gg=null,_g=!1;function vg(){if(typeof document>`u`||document.getElementById(`flowengage-styles`))return;let e=document.createElement(`style`);e.id=`flowengage-styles`,e.innerHTML=hg,document.head.appendChild(e)}function yg(e){if(document.body){e();return}let t=new MutationObserver(()=>{document.body&&(t.disconnect(),e())});t.observe(document.documentElement,{childList:!0})}function bg({siteId:e,language:t=`en`,widgetSettings:n={},apiBaseUrl:r}){if(_g){console.warn(`[FlowEngage] Already initialized. Call FlowEngage.destroy() first to re-initialize.`);return}if(!e){console.error(`[FlowEngage] siteId is required. Pass it via data-site-id attribute or FlowEngage.init({ siteId: 'YOUR_SITE_ID' }).`);return}if(!document.body){console.error(`[FlowEngage] document.body is not available yet. The widget will auto-retry once the DOM is ready.`),yg(()=>bg({siteId:e,language:t,widgetSettings:n,apiBaseUrl:r}));return}if(document.getElementById(`flowengage-root`)){console.warn(`[FlowEngage] #flowengage-root already exists. Skipping duplicate mount.`);return}let i=document.createElement(`div`);i.id=`flowengage-root`,document.body.appendChild(i),vg(),gg=(0,y.createRoot)(i);let a={widgetSettings:n,...r&&{apiBaseUrl:r}};gg.render(v.createElement(gn,{siteId:e,language:t,config:a},v.createElement(mg))),_g=!0}var xg={init({siteId:e,language:t=`en`,widgetSettings:n={},apiBaseUrl:r}={}){document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,()=>yg(()=>bg({siteId:e,language:t,widgetSettings:n,apiBaseUrl:r}))):yg(()=>bg({siteId:e,language:t,widgetSettings:n,apiBaseUrl:r}))},destroy(){gg&&=(gg.unmount(),null);let e=document.getElementById(`flowengage-root`);e&&e.remove();let t=document.getElementById(`flowengage-styles`);t&&t.remove(),_g=!1}},Sg=()=>{let e=document.currentScript;(!e||!e.getAttribute(`data-site-id`))&&(e=document.querySelector(`script[data-site-id]`));let t=e?.getAttribute(`data-site-id`);if(!t)return;let n=e?.getAttribute(`data-language`)||`en`,r=e?.getAttribute(`data-api-url`)||void 0,i={};try{let t=e?.getAttribute(`data-widget-settings`);t&&(i=JSON.parse(t))}catch{}let a={widgetSettings:i,...r&&{apiBaseUrl:r}};yg(()=>bg({siteId:t,language:n,widgetSettings:a.widgetSettings,apiBaseUrl:r}))};return document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,Sg):Sg(),typeof window<`u`&&(window.FlowEngage=xg),xg})();
|
|
337
|
+
`})]})});function mg(){let{status:e,runtimeConfig:t,resolvedConfig:n,chatId:r,chatHistory:i,isOpen:a,activeScreen:o,isHumanHandled:s,agentName:c,agentHeadshot:l,visitorEmail:u,isAgentTyping:d,isAiTyping:f,isLoading:p,isVoiceMode:m,isRateLimited:h,rateLimitMessage:g,isConversationEnded:_,incomingCall:y,activeCallId:b,callConnectionState:x,callConnectedAt:ee,isCallMuted:te,webRTCError:S,language:ne,historyRef:re,onMessageSync:ie,endConversation:ae,acceptCall:oe,rejectCall:se,endWebRTCCall:ce,toggleCallMute:le,dismissCallError:ue,captureVisitorEmail:de,openWidget:fe,closeWidget:C,sendMessage:w,setVoiceMode:pe,startTyping:me,stopTyping:he,updateTypingDraft:ge}=Zt(),[_e,T]=(0,v.useState)(``),[ve,ye]=(0,v.useState)(null),[be,xe]=(0,v.useState)(null),[Se,Ce]=(0,v.useState)(null),[we,Te]=(0,v.useState)(0),[Ee,De]=(0,v.useState)(u||``),[E,Oe]=(0,v.useState)(``),ke=t?.widgetSettings||{},Ae=n?.widgetSettings||{},je={...ke.branding||{},...Ae.branding||{}},Me={...ke.theme||{},...Ae.theme||{}},D=Me.primaryColor||`#3B82F6`,Ne=Me.accentColor||`#1D4ED8`,Pe=(Me.position||`bottom-right`)===`bottom-left`?{left:`1.5rem`,bottom:`1.5rem`}:{right:`1.5rem`,bottom:`1.5rem`},Fe={"--flowengage-primary":D,"--flowengage-accent":Ne,position:`fixed`,zIndex:999999,border:`none`,outline:`none`,fontFamily:`ui-sans-serif, system-ui, sans-serif`,...a?{}:Pe},Ie=Ae.recommendations?.[ne]||ke.recommendations?.[ne]||fg,Le=Ae.greetings?.[ne]||ke.greetings?.[ne],Re=je.chatButtonText||`Chat with us`,ze=je.headerName||t?.websiteName||`OpenSense Labs`,O=je.logoUrl||null,Be=je.hideWatermark||!1,Ve=Ae.elevenLabsAgentId||t?.elevenLabsAgentId||null,He=t?.siteId||n?.siteId||null,Ue=t?.apiBaseUrl||``,We=je.fallbackAgentName||`Agent`,Ge=je.botLabel||`AI`,Ke=l&&String(l).trim()||t?.ownerProfileImageUrl&&String(t.ownerProfileImageUrl).trim()||null,qe=y?.agentName||c||We,Je=i.some(e=>e.sender===`user`),Ye=!u&&Je;(0,v.useEffect)(()=>{De(u||``),u&&Oe(``)},[u]),(0,v.useEffect)(()=>{if(!ee||x!==`connected`){Te(0);return}let e=()=>{let e=new Date(ee).getTime();isNaN(e)||Te(Math.max(0,Math.floor((Date.now()-e)/1e3)))};e();let t=window.setInterval(e,1e3);return()=>window.clearInterval(t)},[ee,x]),(0,v.useEffect)(()=>{if(!s||m||_){ge(``),he();return}if(!_e.trim()){ge(``),he();return}me();let e=window.setTimeout(()=>{ge(_e)},120),t=window.setTimeout(()=>{he()},1200);return()=>{window.clearTimeout(e),window.clearTimeout(t)}},[_e,s,m,_,me,he,ge]);let Xe=e=>e?{replyTo:e.messageId||e.id||null,replyToContent:(e.replyToContent||e.message||``).replace(/<[^>]+>/g,``).trim().slice(0,200),replyToSender:e.sender||null}:null,Ze=async e=>{if(e.preventDefault(),_)return;if(Ye){let e=Ee.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)){Oe(`Please enter a valid email so we can continue helping you.`);return}await de(e),Oe(``);return}if(!_e.trim())return;let t=_e.trim(),n=Xe(Se);T(``),Ce(null),await w(t,``,n)},Qe=async()=>{if(Ye){Oe(`Please share your email before starting a call.`);return}if(m){pe(!1);return}xe(null);try{ye(await navigator.mediaDevices.getUserMedia({audio:!0})),pe(!0)}catch(e){xe(e.message||`Could not access microphone.`)}},$e=()=>{ve&&(ve.getTracks().forEach(e=>e.stop()),ye(null)),pe(!1)},et=e=>{let t=Math.floor(e/60),n=e%60;return`${t.toString().padStart(2,`0`)}:${n.toString().padStart(2,`0`)}`};return e===`ready`?(0,A.jsxs)(`div`,{className:`flowengage-shell`,"data-open":a?`true`:`false`,style:Fe,children:[(0,A.jsx)(Dn,{isOpen:a,openWidget:fe,launcherText:Re,primaryColor:D,posInline:Pe}),a&&(0,A.jsxs)(`div`,{className:`flowengage-chat-panel`,style:{background:i.length===0&&!m?`linear-gradient(to bottom, ${D} 0%, ${D} 70%, white 85%)`:`white`},children:[(0,A.jsx)(jn,{logoUrl:O,brandName:ze,agentName:c,fallbackAgentName:We,activeScreen:o,branding:je,isConversationEnded:_,endConversation:ae,closeWidget:C,isInitial:i.length===0&&!m,botLabel:Ge,agentAvatarUrl:o===`agent`?Ke:null,primaryColor:D}),(0,A.jsx)(`div`,{style:{flex:1,overflowY:`auto`,display:`flex`,flexDirection:`column`},className:`flowengage-content-wrapper`,children:m?(0,A.jsx)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`},className:`fe-screen-fade-in`,children:(0,A.jsx)(dg,{agentId:Ve,chatId:r,siteId:He,apiBaseUrl:Ue,historyRef:re,onMessageSync:ie,onEnd:$e})},`voice`):i.length===0?(0,A.jsx)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`},className:`fe-screen-fade-in`,children:(0,A.jsx)(In,{greetings:Le,recommendations:Ie,onSendMessage:w})},`welcome`):(0,A.jsx)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`},className:`fe-screen-fade-in`,children:(0,A.jsx)(Fn,{chatHistory:i,isAiTyping:f,isAgentTyping:d,setReplyContext:Ce,TypingDots:pg,primaryColor:D,agentHeadshot:Ke,agentDisplayName:c||We})},`history`)}),(0,A.jsx)(Bn,{webRTCError:S,micError:be,setMicError:xe,dismissCallError:ue,incomingCall:y,rejectCall:se,acceptCall:oe,activeCallId:b,callConnectionState:x,formatCallDuration:et,callDurationSeconds:we,endWebRTCCall:ce,isCallMuted:te,toggleCallMute:le,isAIVoiceActive:m,currentCallAgentName:qe,isRateLimited:h,rateLimitMessage:g}),!m&&(0,A.jsx)(`div`,{style:{position:`relative`,zIndex:1},children:(0,A.jsx)(Ln,{input:_e,setInput:T,onSubmit:Ze,isConversationEnded:_,callUiActive:!!(y||b),handleToggleVoice:Qe,activeScreen:o,inputDisabled:p||h||_,replyContext:Se,clearReplyContext:()=>Ce(null),requiresEmail:Ye,emailInput:Ee,setEmailInput:De,emailError:E})}),!Be&&(0,A.jsx)(`div`,{style:{position:`relative`,zIndex:1,display:`flex`,alignItems:`center`,justifyContent:`center`,gap:`12px`,paddingTop:`12px`,paddingBottom:`16px`,fontSize:`12px`,color:`#9ca3af`},children:(0,A.jsxs)(`div`,{children:[`Powered by `,(0,A.jsx)(`span`,{style:{color:`#3b82f6`},children:`Flow`}),(0,A.jsx)(`span`,{style:{color:`#ef4444`},children:`Engage`})]})})]})]}):null}var hg=`/*! tailwindcss v4.2.2 | MIT License | https://tailwindcss.com */
|
|
338
|
+
@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-border-style:solid;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-ease:initial}}:root,:host{--spacing:.25rem;--ease-in-out:cubic-bezier(.4, 0, .2, 1);--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1)}.visible{visibility:visible}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.static{position:static}.start{inset-inline-start:var(--spacing)}.end{inset-inline-end:var(--spacing)}.container{width:100%}@media (width>=40rem){.container{max-width:40rem}}@media (width>=48rem){.container{max-width:48rem}}@media (width>=64rem){.container{max-width:64rem}}@media (width>=80rem){.container{max-width:80rem}}@media (width>=96rem){.container{max-width:96rem}}.block{display:block}.flex{display:flex}.hidden{display:none}.inline{display:inline}.inline-block{display:inline-block}.inline-flex{display:inline-flex}.transform{transform:var(--tw-rotate-x,) var(--tw-rotate-y,) var(--tw-rotate-z,) var(--tw-skew-x,) var(--tw-skew-y,)}.border{border-style:var(--tw-border-style);border-width:1px}.ring{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.outline{outline-style:var(--tw-outline-style);outline-width:1px}.filter{filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.ease-in-out{--tw-ease:var(--ease-in-out);transition-timing-function:var(--ease-in-out)}.flowengage-shell,.flowengage-shell *{font-family:inherit}.flowengage-chat-panel{border:none;border-radius:0;outline:none;flex-direction:column;width:100%;height:100%;display:flex;position:relative;overflow:hidden;box-shadow:0 20px 50px #00000026}@media (width>=768px){.flowengage-chat-panel{border-radius:24px;width:min(423px,100vw - 40px);height:min(700px,100vh - 120px)}}.flowengage-shell[data-open=true]{inset:0}@media (width>=768px){.flowengage-shell[data-open=true]{inset:auto 1.5rem 1.5rem auto}}.flowengage-logo-fallback{background:conic-gradient(from 180deg, var(--flowengage-primary) 0%, #2b70b5 50%, #f59e0b 100%)}.fe-bot-message p{margin:0 0 .5em}.fe-bot-message p:last-child{margin-bottom:0}.fe-bot-message ul,.fe-bot-message ol{margin:.4em 0 .4em 1.2em;padding:0}.fe-bot-message li{margin-bottom:.25em}.fe-bot-message strong{font-weight:600}.fe-bot-message a{color:var(--flowengage-primary);text-decoration:underline}.fe-bot-message a:hover{opacity:.8}.incoming-call-overlay{z-index:1000;-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);background:#1a1a2ef2;justify-content:center;align-items:center;transition:all .3s ease-in-out;display:flex;position:absolute;left:0;right:0}.incoming-call-overlay.bottom-mode{border-top:2px solid #ffffff1a;min-height:120px;animation:.4s cubic-bezier(.16,1,.3,1) slideUpBanner;top:auto;bottom:0;box-shadow:0 -10px 30px #00000080}.incoming-call-overlay.header-mode{border-bottom:2px solid #ffffff1a;min-height:80px;animation:.4s cubic-bezier(.16,1,.3,1) slideDownBanner;top:0;bottom:auto;box-shadow:0 10px 30px #00000080}.incoming-call-container{justify-content:space-between;align-items:center;gap:14px;width:100%;padding:14px 16px;display:flex}.incoming-call-container.connected-layout{flex-direction:column;justify-content:center;align-items:stretch;gap:14px}.call-connected-top{justify-content:space-between;align-items:center;gap:16px;width:100%;display:flex}.call-connected-identity{flex:1;align-items:center;gap:14px;min-width:0;display:flex}.call-icon-wrapper{color:#fff;z-index:1;border-radius:9999px;flex-shrink:0;justify-content:center;align-items:center;width:54px;height:54px;margin-right:4px;display:flex;position:relative}.call-icon-wrapper.incoming{background:linear-gradient(135deg,#4caf50,#45a049);animation:1s ease-in-out infinite bounce}.call-icon-wrapper.connecting{background:linear-gradient(135deg,#2196f3,#1976d2)}.call-icon-wrapper.connected{background:linear-gradient(135deg,#4caf50,#45a049)}.call-pulse-animation{z-index:-1;background:#4caf504d;border-radius:50%;width:120px;height:120px;animation:1.5s ease-out infinite pulse;position:absolute}.call-connecting-animation{z-index:-1;border:3px solid #0000;border-top-color:#2196f3;border-radius:50%;width:100px;height:100px;animation:1s linear infinite spin;position:absolute}.call-info-group{flex-direction:column;flex:1;min-width:0;margin-right:8px;display:flex}.call-title{color:#fff;white-space:normal;text-overflow:clip;margin:0;font-size:16px;font-weight:700;line-height:1.2;overflow:visible}.call-subtitle{color:#ffffffb3;white-space:normal;text-overflow:clip;margin:4px 0 0;font-size:12px;line-height:1.35;overflow:visible}.call-timer{text-align:center;color:#fff;flex-shrink:0;min-width:54px;font-size:13px;font-weight:700}.call-actions{flex-shrink:0;align-items:center;gap:8px;display:flex}.call-actions.connected{justify-content:center;width:100%}.flowengage-call-btn{cursor:pointer;color:#fff;border:none;border-radius:8px;justify-content:center;align-items:center;gap:6px;min-width:92px;padding:8px 12px;font-size:12px;font-weight:600;line-height:1;transition:transform .2s,box-shadow .2s,background .2s;display:flex}.flowengage-call-btn svg{flex-shrink:0;display:block}.flowengage-call-btn span{justify-content:center;align-items:center;line-height:1;display:flex}.flowengage-call-btn.icon-only{border-radius:9999px;width:46px;min-width:46px;height:46px;padding:0}.flowengage-call-btn-accept{background:linear-gradient(135deg,#4caf50,#45a049);box-shadow:0 8px 24px #4caf5066}.flowengage-call-btn-reject,.flowengage-call-btn-end{background:linear-gradient(135deg,#f44336,#d32f2f);box-shadow:0 4px 12px #f4433666}.flowengage-call-btn-mute{background:#ffffff1a;border:2px solid #fff3}.flowengage-call-btn-mute.active{background:#f443364d;border-color:#f44336}.flowengage-call-btn:hover:not(:disabled){transform:scale(1.05)}.incoming-call-overlay.header-mode .flowengage-call-btn{border-radius:9999px!important;width:36px!important;min-width:36px!important;height:36px!important;padding:0!important}.incoming-call-overlay.header-mode .flowengage-call-btn span{display:none!important}.incoming-call-overlay.header-mode .call-icon-wrapper{width:40px;height:40px;margin-right:0}.incoming-call-overlay.header-mode .call-info-group{min-width:0}.incoming-call-overlay.header-mode .call-title,.incoming-call-overlay.header-mode .call-subtitle{white-space:nowrap;text-overflow:ellipsis;overflow:hidden}@media (width<=640px){.incoming-call-container{align-items:flex-start;gap:10px;padding:12px 14px}.incoming-call-container.connected-layout{align-items:stretch}.call-connected-top{flex-direction:column;align-items:flex-start;gap:10px}.call-connected-identity{width:100%}.call-info-group{margin-right:0}.call-actions{flex-wrap:wrap;align-self:stretch;gap:6px}.call-actions.connected{justify-content:stretch}.call-actions.connected .flowengage-call-btn{flex:1}.flowengage-call-btn{min-width:78px;padding:8px 10px}}@keyframes slideUpBanner{0%{transform:translateY(100%)}to{transform:translateY(0)}}@keyframes slideDownBanner{0%{transform:translateY(-100%)}to{transform:translateY(0)}}@keyframes bounce{0%,to{animation-timing-function:cubic-bezier(.8,0,1,1);transform:translateY(-25%)}50%{animation-timing-function:cubic-bezier(0,0,.2,1);transform:none}}@keyframes pulse{50%{opacity:.5}}@keyframes spin{to{transform:rotate(360deg)}}.fe-screen-fade-in{animation:.4s cubic-bezier(.16,1,.3,1) forwards feFadeIn}@keyframes feFadeIn{0%{opacity:0;transform:translateY(12px)}to{opacity:1;transform:translateY(0)}}.flowengage-initial-bg{background-color:#fff;position:relative;overflow:hidden}.flowengage-initial-bg:before{content:"";background:linear-gradient(to bottom, var(--flowengage-primary) 0%, var(--flowengage-primary) 55%, white 82%);opacity:0;pointer-events:none;z-index:0;transition:opacity .6s cubic-bezier(.4,0,.2,1);position:absolute;inset:0}.flowengage-initial-bg.is-initial:before{opacity:1}.flowengage-content-wrapper{z-index:1;flex-direction:column;flex:1;min-height:0;display:flex;position:relative}@property --tw-rotate-x{syntax:"*";inherits:false}@property --tw-rotate-y{syntax:"*";inherits:false}@property --tw-rotate-z{syntax:"*";inherits:false}@property --tw-skew-x{syntax:"*";inherits:false}@property --tw-skew-y{syntax:"*";inherits:false}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"<length>";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-blur{syntax:"*";inherits:false}@property --tw-brightness{syntax:"*";inherits:false}@property --tw-contrast{syntax:"*";inherits:false}@property --tw-grayscale{syntax:"*";inherits:false}@property --tw-hue-rotate{syntax:"*";inherits:false}@property --tw-invert{syntax:"*";inherits:false}@property --tw-opacity{syntax:"*";inherits:false}@property --tw-saturate{syntax:"*";inherits:false}@property --tw-sepia{syntax:"*";inherits:false}@property --tw-drop-shadow{syntax:"*";inherits:false}@property --tw-drop-shadow-color{syntax:"*";inherits:false}@property --tw-drop-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-drop-shadow-size{syntax:"*";inherits:false}@property --tw-ease{syntax:"*";inherits:false}`,gg=null,_g=!1;function vg(){if(typeof document>`u`||document.getElementById(`flowengage-styles`))return;let e=document.createElement(`style`);e.id=`flowengage-styles`,e.innerHTML=hg,document.head.appendChild(e)}function yg(e){if(document.body){e();return}let t=new MutationObserver(()=>{document.body&&(t.disconnect(),e())});t.observe(document.documentElement,{childList:!0})}function bg({siteId:e,language:t=`en`,widgetSettings:n={},apiBaseUrl:r}){if(_g){console.warn(`[FlowEngage] Already initialized. Call FlowEngage.destroy() first to re-initialize.`);return}if(!e){console.error(`[FlowEngage] siteId is required. Pass it via data-site-id attribute or FlowEngage.init({ siteId: 'YOUR_SITE_ID' }).`);return}if(!document.body){console.error(`[FlowEngage] document.body is not available yet. The widget will auto-retry once the DOM is ready.`),yg(()=>bg({siteId:e,language:t,widgetSettings:n,apiBaseUrl:r}));return}if(document.getElementById(`flowengage-root`)){console.warn(`[FlowEngage] #flowengage-root already exists. Skipping duplicate mount.`);return}let i=document.createElement(`div`);i.id=`flowengage-root`,document.body.appendChild(i),vg(),gg=(0,y.createRoot)(i);let a={widgetSettings:n,...r&&{apiBaseUrl:r}};gg.render(v.createElement(gn,{siteId:e,language:t,config:a},v.createElement(mg))),_g=!0}var xg={init({siteId:e,language:t=`en`,widgetSettings:n={},apiBaseUrl:r}={}){document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,()=>yg(()=>bg({siteId:e,language:t,widgetSettings:n,apiBaseUrl:r}))):yg(()=>bg({siteId:e,language:t,widgetSettings:n,apiBaseUrl:r}))},destroy(){gg&&=(gg.unmount(),null);let e=document.getElementById(`flowengage-root`);e&&e.remove();let t=document.getElementById(`flowengage-styles`);t&&t.remove(),_g=!1}},Sg=()=>{let e=document.currentScript;(!e||!e.getAttribute(`data-site-id`))&&(e=document.querySelector(`script[data-site-id]`));let t=e?.getAttribute(`data-site-id`);if(!t)return;let n=e?.getAttribute(`data-language`)||`en`,r=e?.getAttribute(`data-api-url`)||void 0,i={};try{let t=e?.getAttribute(`data-widget-settings`);t&&(i=JSON.parse(t))}catch{}let a={widgetSettings:i,...r&&{apiBaseUrl:r}};yg(()=>bg({siteId:t,language:n,widgetSettings:a.widgetSettings,apiBaseUrl:r}))};return document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,Sg):Sg(),typeof window<`u`&&(window.FlowEngage=xg),xg})();
|