@livelayer/react 0.5.5-pr66c.4 → 0.5.5-pr66c.5
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/index.d.ts +13 -0
- package/dist/index.js +3 -3
- package/dist/index.mjs +1285 -1167
- package/dist/styles.css +49 -5
- package/package.json +2 -2
package/dist/index.d.ts
CHANGED
|
@@ -108,6 +108,13 @@ export declare interface AvatarWidgetProps {
|
|
|
108
108
|
baseUrl?: string;
|
|
109
109
|
sessionEndpoint?: string;
|
|
110
110
|
sessionBody?: Record<string, unknown>;
|
|
111
|
+
/**
|
|
112
|
+
* UI sound effects (mirrors the dashboard): a chime on navigate, a
|
|
113
|
+
* confirmation on fill/submit, a soft loop while the agent is
|
|
114
|
+
* thinking. Pass `false` to disable everything, or an object to
|
|
115
|
+
* disable individual categories. Default is enabled.
|
|
116
|
+
*/
|
|
117
|
+
soundEffects?: SoundEffectsConfig;
|
|
111
118
|
experienceMode?: "WIDGET" | "EMBEDDED";
|
|
112
119
|
autoConnect?: boolean;
|
|
113
120
|
displayMode?: DisplayMode;
|
|
@@ -620,6 +627,12 @@ export declare interface ScreenShareStateHandle {
|
|
|
620
627
|
*/
|
|
621
628
|
export declare function shouldRenderAtPath(pathname: string | undefined, showOn: RoutePattern[] | undefined, hideOn: RoutePattern[] | undefined): boolean;
|
|
622
629
|
|
|
630
|
+
export declare type SoundEffectsConfig = boolean | {
|
|
631
|
+
navigate?: boolean;
|
|
632
|
+
thinking?: boolean;
|
|
633
|
+
action?: boolean;
|
|
634
|
+
};
|
|
635
|
+
|
|
623
636
|
declare interface State {
|
|
624
637
|
hasError: boolean;
|
|
625
638
|
error: Error | null;
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("react/jsx-runtime"),r=require("react"),kn=require("@livelayer/sdk"),Ge=require("livekit-client");class Ht extends r.Component{constructor(){super(...arguments),this.state={hasError:!1,error:null},this.reset=()=>{this.setState({hasError:!1,error:null})}}static getDerivedStateFromError(n){return{hasError:!0,error:n}}componentDidCatch(n,i){var o,s;(s=(o=this.props).onError)==null||s.call(o,n,i)}render(){var n;return this.state.hasError?this.props.fallback?this.props.fallback:t.jsxs("div",{className:"ll-error-boundary",role:"alert",children:[t.jsx("p",{className:"ll-error-boundary__title",children:"Widget crashed"}),t.jsx("p",{className:"ll-error-boundary__message",children:((n=this.state.error)==null?void 0:n.message)||"Something went wrong."}),t.jsx("button",{type:"button",className:"ll-error-boundary__retry",onClick:this.reset,children:"Reload widget"})]}):this.props.children}}function Ot(e){const[n,i]=r.useState("idle"),[o,s]=r.useState("idle"),[l,u]=r.useState([]),[d,f]=r.useState(null),[g,m]=r.useState(null),[a,c]=r.useState(null),[j,S]=r.useState(!1),[k,x]=r.useState(null),v=r.useRef(null),T=r.useRef(e.onDataMessage);T.current=e.onDataMessage,r.useEffect(()=>{const C={onConnectionStateChange:M=>{i(M),M==="connected"&&x(null)},onAgentStateChange:s,onTranscript:M=>u([...M]),onAgentConfig:f,onAudioTrack:M=>c(M),onVideoTrack:M=>m(M),onVideoTrackRemoved:()=>m(null),onError:M=>x(M),onDataMessage:M=>{var L;(L=T.current)==null||L.call(T,M)},onResumabilityChange:S},$=new kn.LiveKitSession({agentId:e.agentId,baseUrl:e.baseUrl,apiKey:e.apiKey,sessionEndpoint:e.sessionEndpoint,sessionBody:e.sessionBody},C);return v.current=$,i("idle"),s("idle"),u([]),f(null),m(null),c(null),S(!1),x(null),()=>{var M;(M=$.destroy)==null||M.call($),v.current=null}},[e.agentId,e.baseUrl,e.apiKey,e.sessionEndpoint,JSON.stringify(e.sessionBody??{})]);const E=r.useCallback(async()=>{const C=v.current;if(C)try{await C.connect()}catch($){throw x($ instanceof Error?$.message:String($)),$}},[]),P=r.useCallback(()=>{const C=v.current;C&&C.disconnect()},[]),h=r.useCallback(()=>{var C;return((C=v.current)==null?void 0:C.getRoom())??null},[]);return{connectionState:n,agentState:o,transcript:l,agentConfig:d,videoElement:g,audioElement:a,canResume:j,error:k,connect:E,disconnect:P,getRoom:h,session:v.current}}function qt(){const e=r.useRef(null),n=r.useRef(null),i=r.useRef(null),o=r.useRef(null),s=r.useRef(new Set),l=r.useRef(null),u=r.useCallback(()=>{const a=n.current;if(!a){o.current=null;return}(!l.current||l.current.length!==a.frequencyBinCount)&&(l.current=new Uint8Array(new ArrayBuffer(a.frequencyBinCount)));const c=l.current;a.getByteFrequencyData(c);let j=0;for(let k=0;k<c.length;k++)j+=c[k];const S=j/c.length/255;for(const k of s.current)try{k(S)}catch(x){console.error("[useAudioLevel] subscriber threw:",x)}o.current=requestAnimationFrame(u)},[]),d=r.useCallback(()=>{if(e.current||typeof window>"u"||typeof AudioContext>"u")return;const a=new AudioContext,c=a.createAnalyser();c.fftSize=64,c.connect(a.destination),e.current=a,n.current=c},[]),f=r.useCallback(a=>{if(d(),!(!e.current||!n.current)){if(i.current){try{i.current.disconnect()}catch{}i.current=null}try{const c=e.current.createMediaElementSource(a);c.connect(n.current),i.current=c}catch(c){console.warn("[useAudioLevel] createMediaElementSource failed:",c);return}o.current===null&&(o.current=requestAnimationFrame(u))}},[d,u]),g=r.useCallback(()=>{if(o.current!==null&&(cancelAnimationFrame(o.current),o.current=null),i.current){try{i.current.disconnect()}catch{}i.current=null}},[]),m=r.useCallback(a=>(s.current.add(a),()=>{s.current.delete(a)}),[]);return r.useEffect(()=>()=>{if(g(),n.current){try{n.current.disconnect()}catch{}n.current=null}if(e.current){try{e.current.close()}catch{}e.current=null}s.current.clear(),l.current=null},[g]),{attach:f,detach:g,subscribe:m}}function Bt(){const[e,n]=r.useState(!1),[i,o]=r.useState(null),s=r.useRef(null),l=r.useRef(null),u=r.useCallback(async m=>{if(s.current&&l.current){try{await l.current.localParticipant.unpublishTrack(s.current)}catch{}s.current.stop(),s.current=null}l.current=m,o(null);try{const a=await Ge.createLocalAudioTrack({echoCancellation:!0,noiseSuppression:!0});await m.localParticipant.publishTrack(a),s.current=a,n(a.isMuted)}catch(a){const c=a instanceof Error&&a.name==="NotAllowedError"?"Enable your microphone to talk with the agent.":"Microphone unavailable. Check browser permissions and try again.";throw o(c),a}},[]),d=r.useCallback(()=>{const m=s.current;m&&(m.isMuted?(m.unmute(),n(!1)):(m.mute(),n(!0)))},[]),f=r.useCallback(()=>{const m=s.current,a=l.current;if(m&&a){try{a.localParticipant.unpublishTrack(m)}catch{}m.stop()}s.current=null,l.current=null,n(!1)},[]),g=r.useCallback(()=>o(null),[]);return{isMuted:e,micError:i,toggleMute:d,setupMic:u,teardownMic:f,clearError:g}}const Sn={resolution:{width:640,height:480,frameRate:24}};function Wt(){const[e,n]=r.useState(!1),[i,o]=r.useState(null),[s,l]=r.useState(null),[u,d]=r.useState(""),f=r.useRef(null),g=r.useRef(null),m=r.useCallback(v=>{f.current=v},[]),a=r.useCallback(()=>{const v=f.current,T=g.current;if(T&&v){const E=v.localParticipant.getTrackPublication(Ge.Track.Source.Camera);if(E!=null&&E.track){try{v.localParticipant.unpublishTrack(E.track)}catch{}E.track.stop()}else T.stop()}g.current=null,l(null),n(!1)},[]),c=r.useCallback(async v=>{const T=f.current;if(T){o(null);try{const E={...Sn};v&&(E.deviceId=v);const P=await Ge.createLocalVideoTrack(E);await T.localParticipant.publishTrack(P),g.current=P;const h=P.attach();l(h),n(!0),v&&d(v);try{T.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({type:"user_camera_on"})),{reliable:!0})}catch{}}catch(E){const P=E instanceof Error&&E.name==="NotAllowedError"?"Enable your camera in the browser to share video.":"Camera unavailable. Check permissions and try again.";o(P)}}},[]),j=r.useCallback(async()=>{e?a():await c(u||void 0)},[e,u,a,c]),S=r.useCallback(async v=>{a(),await c(v)},[a,c]),k=r.useCallback(()=>{a(),f.current=null,o(null),d("")},[a]),x=r.useCallback(()=>o(null),[]);return r.useEffect(()=>()=>{g.current&&g.current.stop()},[]),{isEnabled:e,error:i,previewEl:s,activeDeviceId:u,toggle:j,switchDevice:S,attachRoom:m,teardown:k,clearError:x}}function Ft(){const[e,n]=r.useState(!1),[i,o]=r.useState(null),[s,l]=r.useState(null),u=r.useRef(null),d=r.useCallback(c=>{u.current=c},[]),f=r.useCallback(()=>l(null),[]),g=r.useCallback(async()=>{const c=u.current;if(c){if(e){try{await c.localParticipant.setScreenShareEnabled(!1)}catch{}f(),n(!1);return}o(null);try{await c.localParticipant.setScreenShareEnabled(!0);let j=0;const S=()=>{const k=c.localParticipant.getTrackPublication(Ge.Track.Source.ScreenShare);if(k!=null&&k.track){const x=k.track.attach();l(x),n(!0);try{c.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({type:"user_screen_share_on"})),{reliable:!0})}catch{}return}j++<10?setTimeout(S,100):n(!0)};S()}catch(j){const S=j instanceof Error?j.name:"";S!=="NotAllowedError"&&S!=="AbortError"&&o("Screen share unavailable. Try again."),n(!1)}}},[e,f]),m=r.useCallback(()=>{const c=u.current;if(c&&e)try{c.localParticipant.setScreenShareEnabled(!1)}catch{}f(),n(!1),o(null),u.current=null},[e,f]),a=r.useCallback(()=>o(null),[]);return{isEnabled:e,error:i,previewEl:s,toggle:g,attachRoom:d,teardown:m,clearError:a}}function Ut(){const[e,n]=r.useState([]),[i,o]=r.useState([]),s=r.useCallback(async()=>{if(!(typeof navigator>"u"||!navigator.mediaDevices))try{const l=await navigator.mediaDevices.enumerateDevices();n(l.filter(u=>u.kind==="audioinput")),o(l.filter(u=>u.kind==="videoinput"))}catch{}},[]);return r.useEffect(()=>{if(s(),typeof navigator>"u"||!navigator.mediaDevices)return;const l=()=>void s();return navigator.mediaDevices.addEventListener("devicechange",l),()=>navigator.mediaDevices.removeEventListener("devicechange",l)},[s]),{mics:e,cameras:i,refresh:s}}function Vt(e,n,i=!1){const[o,s]=r.useState(null),[l,u]=r.useState(null),[d,f]=r.useState(!i&&!!e);return r.useEffect(()=>{if(i||!e){f(!1);return}const g=new AbortController,m=n||"https://app.livelayer.studio";return f(!0),u(null),fetch(`${m}/api/widget/agent/${encodeURIComponent(e)}`,{signal:g.signal}).then(async a=>{if(!a.ok){const c=await a.json().catch(()=>({}));throw new Error(c.error||`HTTP ${a.status}`)}return a.json()}).then(a=>{g.signal.aborted||(s(a),f(!1))}).catch(a=>{g.signal.aborted||(u(a instanceof Error?a.message:"Agent lookup failed"),f(!1))}),()=>g.abort()},[e,n,i]),{info:o,error:l,loading:d}}function Cn(e){if(typeof window>"u")return null;try{return window.localStorage.getItem(e)}catch{return null}}function Ln(e,n){if(!(typeof window>"u"))try{window.localStorage.setItem(e,n)}catch{}}function Yt({value:e,defaultValue:n="expanded",onChange:i}={}){const o=e!==void 0,[s,l]=r.useState(n),u=o?e:s,d=r.useCallback(f=>{f!==u&&(o||l(f),i==null||i(f))},[u,o,i]);return[u,d]}const jn=["hidden","minimized","expanded"];function En(e){return e&&jn.includes(e)?e:null}function Kt({value:e,defaultValue:n="expanded",onChange:i,persistKey:o="ll-widget",disablePersistence:s=!1}={}){const l=`${o}:display-mode`,u=r.useRef(!1),[d,f]=Yt({value:e,defaultValue:n,onChange:g=>{e===void 0&&!s&&Ln(l,g),i==null||i(g)}});return r.useEffect(()=>{if(u.current||(u.current=!0,s||e!==void 0))return;const g=En(Cn(l));g&&g!==d&&f(g)},[]),[d,f]}const Rn=640;function Xt(e=Rn){const[n,i]=r.useState(!1);return r.useEffect(()=>{if(e===!1){i(!1);return}if(typeof window>"u"||typeof window.matchMedia>"u")return;const o=`(max-width: ${e-1}px)`,s=window.matchMedia(o),l=()=>i(s.matches);return l(),typeof s.addEventListener=="function"?(s.addEventListener("change",l),()=>s.removeEventListener("change",l)):(s.addListener(l),()=>{s.removeListener(l)})},[e]),n}const kt="__llHistoryPatched",Je="ll:pathname";function Nn(){if(typeof window>"u"||window.history[kt])return;const e=window.history.pushState,n=window.history.replaceState;window.history.pushState=function(...i){const o=e.apply(this,i);return window.dispatchEvent(new Event(Je)),o},window.history.replaceState=function(...i){const o=n.apply(this,i);return window.dispatchEvent(new Event(Je)),o},window.history[kt]=!0}function St(){return typeof window>"u"?"/":window.location.pathname||"/"}function Gt(e){const[n,i]=r.useState(()=>e??St());return r.useEffect(()=>{if(e!==void 0)return;Nn();const o=()=>i(St());return o(),window.addEventListener("popstate",o),window.addEventListener(Je,o),()=>{window.removeEventListener("popstate",o),window.removeEventListener(Je,o)}},[e]),e??n}const Ct=new Map,An=/[\\^$+?.()|{}[\]]/g;function Mn(e){return e.replace(An,"\\$&")}function In(e){const n=Ct.get(e);if(n)return n;const i=e.length>1&&e.endsWith("/")?e.slice(0,-1):e,o="",s="",l=i.replace(/\*\*/g,o).replace(/\*/g,s),d=Mn(l).replace(new RegExp(`\\/${o}`,"g"),"(?:\\/.*)?").replace(new RegExp(o,"g"),".*").replace(new RegExp(s,"g"),"[^/]+"),f=new RegExp(`^${d}\\/?$`);return Ct.set(e,f),f}function Tn(e,n){const i=n.length>1&&n.endsWith("/")?n.slice(0,-1):n;return In(e).test(i)}function Jt(e,n){return typeof e=="function"?e(n):e instanceof RegExp?e.test(n):Tn(e,n)}function Lt(e,n){if(!e||e.length===0)return!1;for(const i of e)if(Jt(i,n))return!0;return!1}function Qt(e,n,i){return e===void 0?!0:Lt(i,e)?!1:n&&n.length>0?Lt(n,e):!0}function Zt(e,n,i){return r.useMemo(()=>Qt(e,n,i),[e,n,i])}const jt=({muted:e=!1,className:n})=>e?t.jsxs("svg",{className:n,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,"aria-hidden":"true",children:[t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"}),t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M17 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2"})]}):t.jsx("svg",{className:n,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,"aria-hidden":"true",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19 11a7 7 0 01-7 7m0 0a7 7 0 01-7-7m7 7v4m0 0H8m4 0h4M12 1a3 3 0 00-3 3v4a3 3 0 006 0V4a3 3 0 00-3-3z"})}),Et=({className:e})=>t.jsx("svg",{className:e,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,"aria-hidden":"true",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M4 8V4m0 0h4M4 4l5 5m11-1V4m0 0h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5l-5-5m5 5v-4m0 4h-4"})}),Pn=({className:e})=>t.jsx("svg",{className:e,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,"aria-hidden":"true",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})}),Dn={left:180,right:0,up:-90,down:90},Rt=({direction:e="right",className:n})=>t.jsx("svg",{className:n,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,style:{transform:`rotate(${Dn[e]}deg)`},"aria-hidden":"true",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 6l6 6-6 6"})});function $n(e){return e==="top-left"||e==="bottom-left"?"left":"right"}const en="ll-hidden-tab-center-y",zn=5,Nt=16;function Hn(){if(typeof window>"u")return null;try{const e=window.localStorage.getItem(en);if(!e)return null;const n=Number.parseFloat(e);return Number.isFinite(n)?n:null}catch{return null}}function At(e){if(!(typeof window>"u"))try{window.localStorage.setItem(en,String(e))}catch{}}const On=({position:e,isMobile:n,isSpeaking:i,onExpand:o,label:s="Open widget",avatarImageUrl:l,agentName:u})=>{const d=$n(e),f=d==="right"?"left":"right",g=n?80:72,m=!!l,[a,c]=r.useState(null),[j,S]=r.useState(!1),k=r.useRef(null),x=r.useRef(!1),v=r.useCallback(L=>{if(typeof window>"u")return L;const N=g/2,z=Nt+N,B=window.innerHeight-Nt-N;return B<z?Math.max(z,L):Math.max(z,Math.min(B,L))},[g]);r.useEffect(()=>{const L=Hn();c(v(L??window.innerHeight/2));const N=()=>{c(z=>z===null?null:v(z))};return window.addEventListener("resize",N),()=>window.removeEventListener("resize",N)},[v]);const T=r.useCallback(L=>{if(!(L.pointerType==="mouse"&&L.button!==0)&&a!==null){try{L.currentTarget.setPointerCapture(L.pointerId)}catch{}k.current={startClientY:L.clientY,startCenterY:a,moved:!1}}},[a]),E=r.useCallback(L=>{const N=k.current;if(!N)return;const z=L.clientY-N.startClientY;!N.moved&&Math.abs(z)>zn&&(N.moved=!0,S(!0)),N.moved&&c(v(N.startCenterY+z))},[v]),P=r.useCallback(L=>{const N=k.current;if(N){try{L.currentTarget.releasePointerCapture(L.pointerId)}catch{}k.current=null,N.moved&&(S(!1),x.current=!0,c(z=>(z!==null&&At(z),z)))}},[]),h=r.useCallback(()=>{if(x.current){x.current=!1;return}o()},[o]),C=r.useCallback(L=>{if(L.key==="ArrowUp"||L.key==="ArrowDown"){L.preventDefault();const N=L.key==="ArrowUp"?-8:8;c(z=>{if(z===null)return z;const B=v(z+N);return At(B),B})}},[v]),$=["ll-hidden",`ll-hidden--${d}`,n?"ll-hidden--mobile":"ll-hidden--desktop",i?"ll-hidden--speaking":null,j?"is-dragging":null,m?"ll-hidden--with-avatar":null].filter(Boolean).join(" "),M=a===null?void 0:{top:`${a-g/2}px`,transform:"none"};return t.jsx("button",{type:"button",className:$,onPointerDown:T,onPointerMove:E,onPointerUp:P,onPointerCancel:P,onClick:h,onKeyDown:C,"aria-label":s,"data-position":e,style:M,children:m?t.jsxs(t.Fragment,{children:[t.jsx(Rt,{direction:f,className:"ll-hidden__chevron ll-hidden__chevron--mini"}),t.jsx("img",{src:l,alt:u?`${u} avatar`:"Agent avatar",className:"ll-hidden__avatar",draggable:!1})]}):t.jsx(Rt,{direction:f,className:"ll-hidden__chevron"})})},qn=({audioLevel:e,bars:n=20,maxHeight:i=20,minHeight:o=4,className:s,barClassName:l})=>{const u=r.useRef(null),d=r.useRef([]),f=r.useMemo(()=>{const m=(Math.sqrt(5)-1)/2;return Array.from({length:n},(a,c)=>.5+c*m%1*.5)},[n]);r.useEffect(()=>e.subscribe(a=>{for(let c=0;c<n;c++){const j=d.current[c];if(!j)continue;const S=Math.max(o,a*i*f[c]);j.style.height=`${S}px`}}),[e,n,i,o,f]);const g=["ll-waveform",s].filter(Boolean).join(" ");return t.jsx("div",{ref:u,className:g,"aria-hidden":"true",children:Array.from({length:n},(m,a)=>t.jsx("div",{ref:c=>{d.current[a]=c},className:["ll-waveform__bar",l].filter(Boolean).join(" "),style:{height:`${o}px`}},a))})},Bn=({position:e,isMobile:n,agentName:i,avatarImageUrl:o,agentState:s,isMuted:l,audioLevel:u,onExpand:d,onToggleMute:f,onClose:g})=>n?t.jsx("div",{className:"ll-minimized ll-minimized--mobile",role:"region","aria-label":`${i} widget`,children:t.jsxs("button",{type:"button",className:"ll-minimized__surface",onClick:d,"aria-label":`Expand ${i} widget`,children:[o?t.jsx("img",{src:o,alt:i,className:"ll-minimized__avatar"}):t.jsx("div",{className:"ll-minimized__avatar ll-minimized__avatar--placeholder"}),t.jsx(qn,{audioLevel:u,bars:16,maxHeight:18,className:"ll-minimized__waveform"}),t.jsx("span",{className:"ll-minimized__name",children:i}),t.jsxs("div",{className:"ll-minimized__controls",children:[t.jsx("span",{className:"ll-minimized__btn",role:"button",tabIndex:0,onClick:m=>{m.stopPropagation(),f()},onKeyDown:m=>{(m.key==="Enter"||m.key===" ")&&(m.stopPropagation(),m.preventDefault(),f())},"aria-label":l?"Unmute microphone":"Mute microphone",children:t.jsx(jt,{muted:l,className:"ll-minimized__icon"})}),t.jsx(Et,{className:"ll-minimized__icon ll-minimized__icon--expand"})]})]})}):t.jsx("div",{className:"ll-minimized ll-minimized--desktop","data-position":e,role:"region","aria-label":`${i} widget`,children:t.jsxs("div",{className:"ll-minimized__surface",children:[o?t.jsx("img",{src:o,alt:i,className:"ll-minimized__avatar"}):t.jsx("div",{className:"ll-minimized__avatar ll-minimized__avatar--placeholder"}),t.jsxs("div",{className:"ll-minimized__meta",children:[t.jsx("span",{className:"ll-minimized__name",children:i}),t.jsx("span",{className:"ll-minimized__state",children:s==="speaking"?"Speaking":s==="thinking"?"Thinking":"Listening"})]}),t.jsxs("div",{className:"ll-minimized__controls",children:[t.jsx("button",{type:"button",className:"ll-minimized__btn",onClick:f,"aria-label":l?"Unmute microphone":"Mute microphone",children:t.jsx(jt,{muted:l,className:"ll-minimized__icon"})}),t.jsx("button",{type:"button",className:"ll-minimized__btn",onClick:d,"aria-label":`Expand ${i} widget`,children:t.jsx(Et,{className:"ll-minimized__icon"})}),t.jsx("button",{type:"button",className:"ll-minimized__btn ll-minimized__btn--close",onClick:g,"aria-label":"Close widget",children:t.jsx(Pn,{className:"ll-minimized__icon"})})]})]})}),Wn=({src:e,alt:n,preCannedPlaying:i=!1,className:o,style:s})=>{const[l,u]=r.useState(!1),d=r.useRef(e);if(r.useEffect(()=>{d.current!==e&&(d.current=e,u(!1))},[e]),!e)return null;const f={position:"absolute",inset:0,width:"100%",height:"100%",objectFit:"cover",objectPosition:"top",transition:"opacity 500ms ease, transform 500ms ease",transform:i?"scale(1.02)":"scale(1)",opacity:l?1:0,...s};return t.jsx("img",{src:e,alt:n,className:o,style:f,loading:"eager",fetchPriority:"high",onLoad:()=>u(!0)})},Fn=({position:e,isMobile:n,agentName:i,avatarImageUrl:o,idleLoopUrl:s,greeting:l,branding:u,teamMembers:d,currentTeamMemberId:f,isSwitchingTeamMember:g,teamSwitcherOpen:m,onToggleTeamSwitcher:a,onSelectTeamMember:c,languageMenuOpen:j,onToggleLanguageMenu:S,connectionState:k,agentState:x,transcript:v,canResume:T,needsUserGesture:E,error:P,isMuted:h,micError:C,micDevices:$,isCameraEnabled:M,cameraPreviewEl:L,cameraDevices:N,activeCameraId:z,isScreenShareEnabled:B,screenPreviewEl:Q,isSpeakerMuted:G,allowCamera:he,allowScreenShare:re,allowTyping:ce,avatarVideoContainerRef:ie,onConnect:Z,onDisconnect:oe,onRetry:ye,onResumeAudio:be,onToggleMute:xe,onToggleCamera:ve,onSwitchCameraDevice:we,onToggleScreenShare:_e,onToggleSpeaker:q,onSendMessage:He,onMinimize:Oe,onClose:qe,onClearMicError:Be})=>{var Ce;const ue=v.length>0?v[v.length-1]:null,se=((d==null?void 0:d.length)??0)>1,ke=k==="connecting"||k==="connected",Se=k==="connected",me=k==="idle"||k==="disconnected"||k==="error",U=r.useRef(null),Ne=r.useRef(null);r.useEffect(()=>{const b=U.current;b&&(b.innerHTML="",L&&(L.style.width="100%",L.style.height="100%",L.style.objectFit="cover",L.style.transform="scaleX(-1)",b.appendChild(L)))},[L]),r.useEffect(()=>{const b=Ne.current;b&&(b.innerHTML="",Q&&(Q.style.width="100%",Q.style.height="100%",Q.style.objectFit="contain",b.appendChild(Q)))},[Q]);const[ee,J]=r.useState(!1),[le,de]=r.useState(!1);r.useEffect(()=>{if(!ee&&!le&&!j&&!m)return;const b=()=>{J(!1),de(!1),j&&S(),m&&a()};return document.addEventListener("click",b),()=>document.removeEventListener("click",b)},[ee,le,j,m,S,a]);const[K,te]=r.useState(""),ge=r.useCallback(b=>{b.preventDefault();const V=K.trim();V&&(He(V),te(""))},[K,He]),Ae=u.productName||"Live Layer",We=Se&&(ue!=null&&ue.text)?ue.text:l||"",Me=["ll-expanded",n?"ll-expanded--mobile":"ll-expanded--desktop"].join(" ");return t.jsxs("div",{className:Me,"data-position":e,"data-state":Se?"connected":ke?"connecting":"idle",role:"dialog","aria-label":`${i} widget`,children:[t.jsxs("div",{className:"ll-expanded__bg",children:[o?t.jsx(Wn,{src:o,alt:i,className:"ll-expanded__bg-img"}):t.jsx("div",{className:"ll-expanded__bg-fallback",children:t.jsx("span",{className:"ll-expanded__bg-initial",children:((Ce=i==null?void 0:i.charAt(0))==null?void 0:Ce.toUpperCase())||"A"})}),s&&!Se&&t.jsx("video",{className:"ll-expanded__bg-idle",src:s,autoPlay:!0,loop:!0,muted:!0,playsInline:!0})]}),t.jsx("div",{ref:ie,className:"ll-expanded__video"}),k==="connecting"&&t.jsxs("div",{className:"ll-expanded__overlay ll-expanded__overlay--connecting",children:[t.jsx("div",{className:"ll-expanded__spinner"}),t.jsx("p",{className:"ll-expanded__overlay-text",children:g?"Switching...":"Connecting..."})]}),E&&Se&&t.jsxs("button",{type:"button",className:"ll-expanded__overlay ll-expanded__overlay--gesture",onClick:be,children:[t.jsx("svg",{width:"32",height:"32",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:t.jsx("path",{d:"M3 9v6h4l5 5V4L7 9H3zm13.54.12a5 5 0 0 1 0 5.76l-1.41-1.41a3 3 0 0 0 0-2.94L16.54 9.12z"})}),t.jsx("p",{className:"ll-expanded__overlay-text",children:"Tap to enable audio"})]}),ke?t.jsxs("div",{className:"ll-expanded__topbar",children:[t.jsxs("div",{className:"ll-expanded__topbar-left",children:[t.jsxs("div",{className:"ll-expanded__pill-wrap",children:[t.jsxs("button",{type:"button",className:"ll-hpill",onClick:b=>{se&&(b.stopPropagation(),a())},"aria-haspopup":se?"listbox":void 0,"aria-expanded":se?m:void 0,children:[t.jsx("span",{className:"ll-hpill__label",children:i}),se&&t.jsx(Ye,{})]}),se&&m&&t.jsx("div",{className:"ll-hmenu",onClick:b=>b.stopPropagation(),role:"listbox",children:d==null?void 0:d.map(b=>t.jsxs("button",{type:"button",className:`ll-hmenu__item ${b.id===f?"is-active":""}`,onClick:()=>c(b.id),role:"option","aria-selected":b.id===f,children:[b.avatarImageUrl&&t.jsx("img",{src:b.avatarImageUrl,alt:"",className:"ll-hmenu__avatar"}),t.jsx("span",{className:"ll-hmenu__name",children:b.name}),b.role&&t.jsx("span",{className:"ll-hmenu__role",children:b.role})]},b.id))})]}),t.jsxs("div",{className:"ll-expanded__pill-wrap",children:[t.jsxs("button",{type:"button",className:"ll-hpill ll-hpill--compact",onClick:b=>{b.stopPropagation(),S()},"aria-haspopup":"listbox","aria-expanded":j,"aria-label":"Language: English",title:"Language: English",children:[t.jsx("span",{className:"ll-hpill__label",children:"EN"}),t.jsx(Ye,{})]}),j&&t.jsx("div",{className:"ll-hmenu",onClick:b=>b.stopPropagation(),role:"listbox",children:t.jsx("button",{type:"button",className:"ll-hmenu__item is-active",role:"option","aria-selected":!0,children:t.jsx("span",{className:"ll-hmenu__name",children:"English"})})})]}),t.jsx("span",{className:`ll-expanded__state ll-expanded__state--${x}`,children:x})]}),t.jsxs("div",{className:"ll-expanded__header-actions",children:[t.jsx("button",{type:"button",className:"ll-hbtn",onClick:Oe,"aria-label":"Minimize widget",title:"Minimize",children:t.jsx(It,{})}),t.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--danger",onClick:qe,"aria-label":"End call",title:"End call",children:t.jsx(Mt,{})})]})]}):t.jsxs("div",{className:"ll-expanded__header ll-expanded__header--idle",children:[t.jsx("span",{className:"ll-expanded__brand",children:Ae}),t.jsxs("div",{className:"ll-expanded__header-actions",children:[t.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--ghost",onClick:Oe,"aria-label":"Minimize widget",children:t.jsx(It,{})}),t.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--danger",onClick:qe,"aria-label":"Close widget",children:t.jsx(Mt,{})})]})]}),me&&(()=>{const b=T?"Restart paused session":k==="disconnected"?"Reconnect to agent":"Start video call",V=T?"Pick up where you left off":null,Ie=k==="idle"&&!T&&!P;return t.jsxs(t.Fragment,{children:[Ie&&t.jsxs("button",{type:"button",className:"ll-expanded__play",onClick:Z,"aria-label":b,children:[t.jsx("div",{className:"ll-expanded__play-circle",children:t.jsx("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:t.jsx("polygon",{points:"6 3 20 12 6 21 6 3"})})}),t.jsx("span",{className:"ll-expanded__play-label",children:b})]}),t.jsxs("div",{className:"ll-expanded__bottom ll-expanded__bottom--idle",children:[l&&t.jsx("div",{className:"ll-expanded__transcript",children:t.jsx("p",{className:"ll-expanded__transcript-text",children:l})}),V&&t.jsx("p",{className:"ll-expanded__cta-sublabel",children:V}),t.jsx("button",{type:"button",className:"ll-expanded__cta",onClick:Z,"aria-label":b,children:b})]})]})})(),t.jsxs("div",{className:`ll-expanded__pip ${ke&&(M||B)?"is-visible":""}`,children:[t.jsx("div",{ref:Ne,className:B?"ll-expanded__pip-host":"ll-expanded__pip-host is-hidden"}),t.jsx("div",{ref:U,className:!B&&M?"ll-expanded__pip-host":"ll-expanded__pip-host is-hidden"})]}),ke?t.jsxs("div",{className:"ll-expanded__bottom",children:[We&&t.jsx("div",{className:"ll-expanded__transcript",children:t.jsx("p",{className:"ll-expanded__transcript-text",children:We})}),t.jsxs("div",{className:"ll-toolbar",onClick:b=>b.stopPropagation(),children:[re&&t.jsx("button",{type:"button",className:`ll-tool ${B?"is-on":""}`,onClick:_e,"aria-label":B?"Stop sharing screen":"Share screen",title:B?"Stop sharing":"Share screen",children:t.jsx(Un,{})}),he&&t.jsxs("div",{className:"ll-tool-split",children:[t.jsx("button",{type:"button",className:`ll-tool ll-tool--left ${M?"is-on":""}`,onClick:ve,"aria-label":M?"Turn off camera":"Turn on camera",title:M?"Stop camera":"Start camera",children:t.jsx(Vn,{})}),t.jsx("button",{type:"button",className:`ll-tool ll-tool--right ${M?"is-on":""}`,onClick:b=>{b.stopPropagation(),de(V=>!V),J(!1)},"aria-label":"Camera devices","aria-haspopup":"listbox","aria-expanded":le,children:t.jsx(Ye,{})}),le&&N.length>0&&t.jsx(Tt,{label:"Camera",devices:N,activeId:z,onPick:b=>{de(!1),we(b)}})]}),t.jsxs("div",{className:"ll-tool-split",children:[t.jsx("button",{type:"button",className:`ll-tool ll-tool--left ${h?"is-muted":""}`,onClick:xe,"aria-label":h?"Unmute microphone":"Mute microphone",title:h?"Unmute":"Mute",children:t.jsx(Yn,{muted:h})}),t.jsx("button",{type:"button",className:`ll-tool ll-tool--right ${h?"is-muted":""}`,onClick:b=>{b.stopPropagation(),J(V=>!V),de(!1)},"aria-label":"Microphone devices","aria-haspopup":"listbox","aria-expanded":ee,children:t.jsx(Ye,{})}),ee&&$.length>0&&t.jsx(Tt,{label:"Microphone",devices:$,activeId:"",onPick:()=>J(!1)})]}),t.jsx("button",{type:"button",className:`ll-tool ${G?"is-muted":""}`,onClick:q,"aria-label":G?"Unmute speaker":"Mute speaker",title:G?"Unmute speaker":"Mute speaker",children:t.jsx(Kn,{muted:G})})]}),ce&&t.jsxs("form",{className:"ll-message-input",onSubmit:ge,children:[t.jsx("input",{type:"text",className:"ll-message-input__field",placeholder:"Message...",value:K,onChange:b=>te(b.target.value),"aria-label":"Message the agent"}),K.trim()&&t.jsx("button",{type:"submit",className:"ll-message-input__send","aria-label":"Send message",children:t.jsx(Xn,{})})]}),t.jsx("button",{type:"button",className:"ll-expanded__end",onClick:oe,children:"End conversation"})]}):null,(()=>{if(C&&k!=="error")return t.jsxs("div",{className:"ll-expanded__banner",role:"alert",children:[t.jsx("span",{children:C}),t.jsx("button",{type:"button",className:"ll-expanded__banner-x",onClick:Be,"aria-label":"Dismiss",children:"×"})]});if(!P||k!=="error")return null;let b="Failed to connect",V="Try again";return P==="MIC_PERMISSION_DENIED"?b="Microphone blocked. Allow access to talk.":P==="MIC_NOT_FOUND"?b="No microphone found. Plug one in + retry.":P==="MIC_UNAVAILABLE"?b="Mic unavailable. Check other apps using it.":P==="AGENT_TIMEOUT"?b="Agent didn't pick up. Try again.":P==="CONNECT_FAILED"?b="Connection failed. Check your network.":P.length<80&&(b=P),t.jsxs("div",{className:"ll-expanded__banner ll-expanded__banner--error",role:"alert",children:[t.jsx("span",{children:b}),t.jsx("button",{type:"button",className:"ll-expanded__banner-retry",onClick:ye,children:V})]})})()]})};function Ye(){return t.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":!0,children:t.jsx("polyline",{points:"6 9 12 15 18 9"})})}function Mt(){return t.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round","aria-hidden":!0,children:[t.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),t.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function It(){return t.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round","aria-hidden":!0,children:t.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})})}function Un(){return t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[t.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),t.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),t.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function Vn(){return t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[t.jsx("path",{d:"M23 7l-7 5 7 5V7z"}),t.jsx("rect",{x:"1",y:"5",width:"15",height:"14",rx:"2"})]})}function Yn({muted:e}){return t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[t.jsx("path",{d:"M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"}),t.jsx("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),t.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),e&&t.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function Kn({muted:e}){return t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[t.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),e?t.jsx("line",{x1:"23",y1:"9",x2:"17",y2:"15"}):t.jsxs(t.Fragment,{children:[t.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14"}),t.jsx("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"})]})]})}function Xn(){return t.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[t.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"}),t.jsx("polyline",{points:"12 5 19 12 12 19"})]})}const Tt=({label:e,devices:n,activeId:i,onPick:o})=>t.jsxs("div",{className:"ll-device-menu",onClick:s=>s.stopPropagation(),role:"listbox",children:[t.jsx("p",{className:"ll-device-menu__label",children:e}),n.map((s,l)=>{const u=i===s.deviceId;return t.jsxs("button",{type:"button",className:`ll-device-menu__item ${u?"is-active":""}`,onClick:()=>o(s.deviceId),role:"option","aria-selected":u,children:[u&&t.jsx("span",{className:"ll-device-menu__dot",children:"●"}),t.jsx("span",{className:"ll-device-menu__name",children:s.label||`${e} ${l+1}`})]},s.deviceId||l)})]}),Gn=['[data-ll-private="true"]',".ll-widget"];function at(e){let n=e;for(;n;){for(const i of Gn)if(n.matches(i))return!0;n=n.parentElement}return!1}function Qe(e){if(at(e))return!1;if(e instanceof HTMLInputElement){if(e.type==="password")return!1;const n=(e.getAttribute("autocomplete")||"").toLowerCase();if(n==="off"||n.startsWith("cc-"))return!1}return!0}const Ke=4096,Jn=20,Qn=20,Zn=10,er=10,tr=30,nr=20,Pt=500,rr=['[data-ll-private="true"]',".ll-widget","script","style","noscript","iframe"];function $e(e){if(e.getAttribute("aria-hidden")==="true"||e.hasAttribute("hidden"))return!0;let n=e;for(;n;){for(const i of rr)if(n.matches(i))return!0;n=n.parentElement}return!1}function ze(e){if(typeof window>"u")return!0;const n=e.getBoundingClientRect();if(n.width<=0||n.height<=0)return!1;const i=window.innerHeight||document.documentElement.clientHeight,o=window.innerWidth||document.documentElement.clientWidth;return n.bottom>0&&n.right>0&&n.top<i&&n.left<o}function Dt(e){const n=e.getAttribute("id");if(n){const l=document.querySelector(`label[for="${CSS.escape(n)}"]`);if(l!=null&&l.textContent)return l.textContent.trim()}const i=e.getAttribute("aria-label");if(i)return i.trim();const o=e.getAttribute("placeholder");if(o)return o.trim();const s=e.closest("label");return s!=null&&s.textContent?s.textContent.trim():""}function ae(e,n){return e.length<=n?e:e.slice(0,n-1)+"…"}function je(e){return e.length}function tn(e,n={}){const i=n.doc??(typeof document<"u"?document:null);if(!i)return{url:"",title:"",pathname:"/",regions:[],visibleText:"",visibleLinks:[],visibleFields:[],forms:[],extras:e};const o=typeof window<"u"&&window.location.href||"",s=typeof window<"u"&&window.location.pathname||"/",l=i.title||"",u=Array.from(i.querySelectorAll("[data-ll-region]")),d=[];for(const h of u){if(d.length>=Zn)break;if($e(h)||!ze(h))continue;const C=h.getAttribute("data-ll-region")??"",$=h.getAttribute("data-ll-intent")??void 0,M=ae((h.innerText||h.textContent||"").trim(),Pt*2);!C||!M||d.push({id:C,intent:$,text:M})}const f=[],g=["H1","H2","H3","H4","H5","H6"],m=Array.from(i.querySelectorAll("h1, h2, h3, h4, h5, h6"));for(const h of m){if($e(h)||!ze(h))continue;const C=(h.textContent||"").trim();C&&f.push(`${h.tagName}: ${ae(C,200)}`)}const a=Array.from(i.querySelectorAll("p, li"));for(const h of a){if($e(h)||!ze(h)||g.includes(h.tagName))continue;const C=(h.textContent||"").trim();C.length>10&&f.push(ae(C,Pt))}const c=f.join(`
|
|
2
|
-
`),j=[],S=Array.from(i.querySelectorAll("a[href]"));for(const h of S){if(j.length>=Jn)break;if($e(h)||!ze(h))continue;const C=h.getAttribute("href")||"",$=(h.textContent||"").trim();!C||!$||j.push({href:C,text:ae($,100)})}const k=[],x=Array.from(i.querySelectorAll("input, textarea, select"));for(const h of x){if(k.length>=Qn)break;if($e(h)||!Qe(h)||!ze(h))continue;const C=Dt(h),$=h instanceof HTMLInputElement?h.type:h.tagName.toLowerCase();C&&k.push({label:ae(C,100),type:$})}const v=Array.from(i.querySelectorAll("[data-ll-form]")),T=[];for(const h of v){if(T.length>=er)break;if(at(h))continue;const C=h.getAttribute("data-ll-form")||"";if(!C)continue;const $=h.getAttribute("data-ll-intent")||void 0,M=Array.from(h.querySelectorAll("[data-ll-field]")),L=[];for(const N of M){if(L.length>=tr)break;if(!Qe(N))continue;const z=N.getAttribute("data-ll-field")||"";if(!z)continue;const B=Dt(N)||z,Q=N instanceof HTMLInputElement?N.type:N.tagName.toLowerCase(),G={name:z,label:ae(B,100),type:Q};if(N.required===!0&&(G.required=!0),N instanceof HTMLSelectElement){const re=[];for(let ce=0;ce<N.options.length&&!(re.length>=nr);ce++){const ie=N.options[ce];if(!ie||ie.disabled)continue;const Z=ie.value||"",oe=(ie.textContent||"").trim()||Z;!Z&&!oe||re.push({value:Z,label:ae(oe,60)})}re.length>0&&(G.options=re)}const he=typeof N.validationMessage=="string"?N.validationMessage:"";he&&(G.validationMessage=ae(he,200)),L.push(G)}T.push({id:C,intent:$,fields:L})}const E={url:o,title:l,pathname:s,regions:d,visibleText:c,visibleLinks:j,visibleFields:k,forms:T,extras:e};let P=je(JSON.stringify(E.regions))+je(E.visibleText)+je(JSON.stringify(E.visibleLinks))+je(JSON.stringify(E.visibleFields));for(;P>Ke&&E.visibleFields.length>0;)E.visibleFields.pop(),P=je(JSON.stringify(E.visibleFields));for(;P>Ke&&E.visibleLinks.length>0;)E.visibleLinks.pop(),P-=80;return je(E.visibleText)>Ke&&(E.visibleText=ae(E.visibleText,Ke-100)),E}let Ee=null;function lt(e,n={}){const i=Date.now(),s=`${typeof window<"u"&&window.location.pathname||"/"}::${typeof window<"u"?window.scrollY:0}`;if(Ee&&Ee.key===s&&i-Ee.at<1e3)return Ee.ctx;const l=tn(e,n);return Ee={key:s,at:i,ctx:l},l}function nn(){Ee=null}const ir=200;function rn(e){const n=String(e.href||"");return{href:n,text:String(e.text??e.title??n),internal:e.internal??!0,title:e.title,description:e.description}}function or(e){return!(!e||e.startsWith("#")||e.startsWith("javascript:")||e.startsWith("mailto:")||e.startsWith("tel:"))}function on(e){const n=e??(typeof document<"u"?document:null);if(!n)return[];const i=typeof window<"u"&&window.location.origin||"",o=new Set,s=[],l=Array.from(n.querySelectorAll("a[href]"));for(const u of l){if(s.length>=ir)break;if(at(u))continue;const d=u.getAttribute("href")||"";if(!or(d))continue;let f=d,g=!0;try{if(typeof window<"u"){const a=new URL(d,i);g=a.origin===i,g&&d.startsWith("http")&&(f=a.pathname+a.search+a.hash)}}catch{continue}if(o.has(f))continue;o.add(f);const m=(u.textContent||"").trim().slice(0,120);s.push({href:f,text:m,internal:g})}return s}let Re=null;const sr=5e3;function Xe(){const e=Date.now(),n=typeof window<"u"&&window.location.pathname||"/";if(Re&&Re.pathname===n&&e-Re.at<sr)return Re.routes;const i=on();return Re={at:e,pathname:n,routes:i},i}function sn(){Re=null}function lr(e,n){const i=e instanceof HTMLInputElement?HTMLInputElement.prototype:e instanceof HTMLTextAreaElement?HTMLTextAreaElement.prototype:HTMLSelectElement.prototype,o=Object.getOwnPropertyDescriptor(i,"value"),s=o==null?void 0:o.set;s?s.call(e,n):e.value=n}function ar(e,n,i={}){const o=i.triggerInput??!0,s=i.triggerChange??!0;if(e instanceof HTMLInputElement&&(e.type==="checkbox"||e.type==="radio")){const l=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,"checked"),u=l==null?void 0:l.set,d=n==="true"||n==="1"||n==="on";u?u.call(e,d):e.checked=d,o&&e.dispatchEvent(new Event("input",{bubbles:!0})),s&&e.dispatchEvent(new Event("change",{bubbles:!0}));return}lr(e,n),o&&e.dispatchEvent(new Event("input",{bubbles:!0})),s&&e.dispatchEvent(new Event("change",{bubbles:!0}))}function cr(){if(typeof window>"u"||typeof document>"u")return!1;const e=document.scrollingElement||document.documentElement;if(!e||e.scrollHeight<=e.clientHeight+2)return!1;const n=window.getComputedStyle(e);return!(n.overflowY==="hidden"||n.overflowY==="clip")}function ur(e){if(!(e instanceof HTMLElement))return!1;const i=window.getComputedStyle(e).overflowY;return!(i!=="auto"&&i!=="scroll"||e.scrollHeight<=e.clientHeight+2)}function dr(){if(typeof document>"u")return null;const e=Array.from(document.querySelectorAll("body, body *"));let n=null,i=0;for(const o of e){if(!ur(o))continue;const s=o.getBoundingClientRect();if(s.bottom<=0||s.top>=window.innerHeight||s.right<=0||s.left>=window.innerWidth||s.width<=0||s.height<=0||o.closest(".ll-widget"))continue;const l=s.width*s.height;l>i&&(i=l,n=o)}return n}function fr(){if(typeof window>"u")return null;if(cr())return window;const e=dr();return e||window}function $t(e){return e instanceof Window?e.innerHeight||0:e.clientHeight||0}function pr(e){var n,i;return e instanceof Window?typeof document>"u"?0:Math.max(((n=document.body)==null?void 0:n.scrollHeight)??0,((i=document.documentElement)==null?void 0:i.scrollHeight)??0):e.scrollHeight-e.clientHeight}const hr=new Set(["agent_state","avatar_stream_ready","avatar_active","avatar_idle","bot_ready","agent_error","idle_warning","idle_timeout","navigate","scroll_to","request_page_context","scroll_page","click","fill_form","focus_field","submit_form","request_routes"]);function mr(e){var mt,gt,yt,bt,xt,vt,wt;const{agentId:n,apiKey:i,baseUrl:o="https://app.livelayer.studio",sessionEndpoint:s,sessionBody:l,autoConnect:u=!1,displayMode:d,defaultDisplayMode:f="expanded",onDisplayModeChange:g,position:m="bottom-right",mobileBreakpoint:a=640,persistKey:c="ll-widget",disablePersistence:j=!1,teamMembers:S,currentTeamMemberId:k,onTeamMemberChange:x,idleLoopUrl:v,greeting:T,avatarImageUrl:E,agentName:P,branding:h={},allowCamera:C=!0,allowScreenShare:$=!0,allowTyping:M=!0,showOn:L,hideOn:N,pathname:z,onNavigate:B,onScrollToSelector:Q,getPageContext:G,pageContextExtras:he,getRoutes:re,onScrollPage:ce,onClick:ie,capabilities:Z,onConnect:oe,onDisconnect:ye,onTranscript:be,onAgentState:xe,onConnectionStateChange:ve,onAgentEvent:we,onAgentCommand:_e,controlledSession:q,className:He,style:Oe,zIndex:qe=2147483647}=e,Be=Gt(z),ue=Zt(Be,L,N);r.useEffect(()=>{nn(),sn()},[Be]);const se=k!==void 0,[ke,Se]=r.useState(()=>{var y;return k??((y=S==null?void 0:S[0])==null?void 0:y.id)}),me=se?k:ke,U=r.useMemo(()=>(S==null?void 0:S.find(y=>y.id===me))??null,[S,me]),Ne=(U==null?void 0:U.agentId)??n,[ee,J]=Kt({value:d,defaultValue:f,onChange:g,persistKey:c,disablePersistence:j}),le=Xt(a),de=qt(),K=Bt(),te=Wt(),ge=Ft(),Ae=Ut(),[We,Me]=r.useState(!1),[Ce,b]=r.useState(!1),[V,Ie]=r.useState(!1),[ln,an]=r.useState(!1),[Ze,cn]=r.useState(!1),et=r.useRef(B),tt=r.useRef(Q),nt=r.useRef(ce),rt=r.useRef(ie),ct=r.useRef(G),ut=r.useRef(he),dt=r.useRef(re),it=r.useRef(Z),ne=r.useRef(null);et.current=B,tt.current=Q,nt.current=ce,rt.current=ie,ct.current=G,ut.current=he,dt.current=re,it.current=Z;function fe(y){const p=it.current;return p?p.includes(y):!0}function pe(y,p){console.warn(`[LiveLayer] Agent command "${y}" blocked — capability "${p}" not in allowlist. See https://livelayer.studio/docs/react/capabilities`)}const Te=r.useCallback(y=>{var X,Ue,Ve,_t;const p=y;if(!(!p.type||typeof p.type!="string")){if(we==null||we({eventName:p.type,data:y}),p.type==="navigate"){if(!fe("navigate")){pe("navigate","navigate");return}const _=typeof p.href=="string"?p.href:null;if(!_){console.warn(`[LiveLayer] Agent emitted "navigate" without href. Skipping. Check your agent's tool schema. See https://livelayer.studio/docs/errors/navigate-missing-href`);return}if(et.current){try{et.current(_)}catch(R){console.warn(`[LiveLayer] onNavigate threw for "${_}". Falling back. Error:`,R)}return}if(typeof document<"u"){const R=document.querySelector(`a[href="${_.replace(/"/g,'\\"')}"]`);if(R){R.click();return}}if(typeof window<"u"&&typeof history<"u")try{history.pushState({},"",_),window.dispatchEvent(new PopStateEvent("popstate"))}catch(R){console.warn(`[LiveLayer] history.pushState fallback failed for "${_}". Pass an onNavigate prop to use your router directly. See https://livelayer.studio/docs/react/navigation`,R)}return}if(p.type==="scroll_to"){if(!fe("scroll")){pe("scroll_to","scroll");return}const _=typeof p.selector=="string"?p.selector:null;if(!_)return;const R=p.behavior==="instant"?"instant":"smooth";if(tt.current){try{tt.current(_,R)}catch(D){console.warn("[LiveLayer] onScrollToSelector threw.",D)}return}if(typeof document<"u"){let D=null;try{D=document.querySelector(_)}catch{console.warn(`[LiveLayer] scroll_to: invalid selector "${_}".`);return}if(!D){console.warn(`[LiveLayer] scroll_to: no element matched "${_}". The user may be on a different page. See https://livelayer.studio/docs/errors/scroll-no-match`);return}D.scrollIntoView({behavior:R,block:"start"})}return}if(p.type==="request_page_context"){if(!fe("read_page")){pe("request_page_context","read_page");return}const _=typeof p.requestId=="string"?p.requestId:void 0,R=(X=ne.current)==null?void 0:X.call(ne),D=O=>{const A=R,F=A==null?void 0:A.localParticipant;if(F!=null&&F.publishData)try{const Y=_?{...O,requestId:_}:O,Le=new TextEncoder().encode(JSON.stringify(Y));F.publishData(Le,{reliable:!0})}catch(Y){console.warn("[LiveLayer] publishData failed.",Y)}},I=ut.current,H=ct.current;try{if(H){const O=H(I);if(O instanceof Promise){D({type:"page_context_pending"}),O.then(A=>D({type:"page_context",context:A})).catch(A=>{console.warn("[LiveLayer] getPageContext rejected; falling back to default walker.",A),D({type:"page_context",context:lt(I)})});return}D({type:"page_context",context:O});return}D({type:"page_context",context:lt(I)})}catch(O){console.warn("[LiveLayer] page-context extraction threw. Sending empty context.",O),D({type:"page_context",context:{url:"",title:"",pathname:"/",regions:[],visibleText:"",visibleLinks:[],visibleFields:[],forms:[],extras:I}})}return}if(p.type==="scroll_page"){if(!fe("scroll")){pe("scroll_page","scroll");return}const _=p.direction;if(_!=="up"&&_!=="down"&&_!=="top"&&_!=="bottom"){console.warn(`[LiveLayer] scroll_page: invalid direction "${String(_)}". Expected up | down | top | bottom.`);return}const R=p.behavior==="instant"?"instant":"smooth";if(nt.current){try{nt.current(_,R)}catch(A){console.warn("[LiveLayer] onScrollPage threw.",A)}return}if(typeof window>"u")return;const D={behavior:R},I=fr(),H=A=>{I instanceof Window?I.scrollBy({top:A,...D}):I.scrollBy({top:A,...D})},O=A=>{I instanceof Window?I.scrollTo({top:A,...D}):I.scrollTo({top:A,...D})};_==="up"?H(-$t(I)):_==="down"?H($t(I)):O(_==="top"?0:pr(I));return}if(p.type==="click"){if(!fe("click")){pe("click","click");return}const _=typeof p.selector=="string"?p.selector:null;if(!_){console.warn("[LiveLayer] click: missing selector.");return}if(rt.current){try{rt.current(_)}catch(D){console.warn("[LiveLayer] onClick threw.",D)}return}if(typeof document>"u")return;let R=null;try{R=document.querySelector(_)}catch{console.warn(`[LiveLayer] click: invalid selector "${_}".`);return}if(!R){console.warn(`[LiveLayer] click: no element matched "${_}". See https://livelayer.studio/docs/errors/click-no-match`);return}if(R.closest('[data-ll-private="true"], .ll-widget')){console.warn("[LiveLayer] click: refusing to click element inside a private subtree.");return}(Ue=R.click)==null||Ue.call(R);return}if(p.type==="fill_form"||p.type==="focus_field"){if(!fe("fill_forms")){pe(p.type,"fill_forms");return}if(typeof document>"u")return;const _=typeof p.formId=="string"?p.formId:null;if(!_){console.warn(`[LiveLayer] ${p.type}: missing formId.`);return}const R=document.querySelector(`[data-ll-form="${_.replace(/"/g,'\\"')}"]`);if(!R){console.warn(`[LiveLayer] ${p.type}: no form with data-ll-form="${_}". Tag your form with <LiveLayerForm id> or data-ll-form. See https://livelayer.studio/docs/react/forms`);return}if(R.closest('[data-ll-private="true"], .ll-widget')){console.warn(`[LiveLayer] ${p.type}: refusing to touch a form in a private subtree.`);return}if(p.type==="focus_field"){const I=typeof p.fieldName=="string"?p.fieldName:null;if(!I){console.warn("[LiveLayer] focus_field: missing fieldName.");return}const H=R.querySelector(`[data-ll-field="${I.replace(/"/g,'\\"')}"]`);if(!H){console.warn(`[LiveLayer] focus_field: no field "${I}" in form "${_}".`);return}if(!Qe(H)){console.warn(`[LiveLayer] focus_field: field "${I}" is privacy-protected and not focusable.`);return}H.focus();return}const D=p.values&&typeof p.values=="object"?p.values:null;if(!D){console.warn("[LiveLayer] fill_form: missing or invalid values.");return}for(const[I,H]of Object.entries(D)){if(typeof H!="string")continue;const O=R.querySelector(`[data-ll-field="${I.replace(/"/g,'\\"')}"]`);if(!O){console.warn(`[LiveLayer] fill_form: no field "${I}" in form "${_}". Skipping.`);continue}if(!Qe(O)){console.warn(`[LiveLayer] fill_form: field "${I}" is privacy-protected (password / cc-* / private). Skipping.`);continue}try{ar(O,H)}catch(A){console.warn(`[LiveLayer] fill_form: failed to set "${I}".`,A)}}return}if(p.type==="submit_form"){if(!fe("submit_forms")){pe("submit_form","submit_forms");return}if(typeof document>"u")return;const _=typeof p.formId=="string"?p.formId:null;if(!_){console.warn("[LiveLayer] submit_form: missing formId.");return}const R=document.querySelector(`[data-ll-form="${_.replace(/"/g,'\\"')}"]`);if(!R){console.warn(`[LiveLayer] submit_form: no form with data-ll-form="${_}".`);return}if(R.closest('[data-ll-private="true"], .ll-widget')){console.warn("[LiveLayer] submit_form: refusing to submit a form in a private subtree.");return}const D=typeof p.requestId=="string"?p.requestId:void 0,I=(Ve=ne.current)==null?void 0:Ve.call(ne),H=F=>{const Y=I,Le=Y==null?void 0:Y.localParticipant;if(Le!=null&&Le.publishData)try{const wn=D?{...F,requestId:D}:F,_n=new TextEncoder().encode(JSON.stringify(wn));Le.publishData(_n,{reliable:!0})}catch{}};let O=!1;const A=()=>{O=!0,H({type:"form_submitted",formId:_})};R.addEventListener("submit",A,{once:!0});try{typeof R.requestSubmit=="function"?R.requestSubmit():R.submit()}catch(F){console.warn("[LiveLayer] submit_form: requestSubmit threw.",F),R.removeEventListener("submit",A),H({type:"form_submit_blocked",formId:_,reason:"exception"});return}setTimeout(()=>{O||(R.removeEventListener("submit",A),H({type:"form_submit_blocked",formId:_,reason:"validation"}))},500);return}if(p.type==="request_routes"){if(!fe("read_page")){pe("request_routes","read_page");return}const _=typeof p.requestId=="string"?p.requestId:void 0,D=(_t=ne.current)==null?void 0:_t.call(ne),I=D==null?void 0:D.localParticipant;if(!(I!=null&&I.publishData))return;const H=A=>{try{const F=_?{type:"routes",routes:A,requestId:_}:{type:"routes",routes:A},Y=new TextEncoder().encode(JSON.stringify(F));I.publishData(Y,{reliable:!0})}catch(F){console.warn("[LiveLayer] request_routes: publishData failed.",F)}},O=dt.current;if(O){try{const A=O(),F=Y=>{if(!Array.isArray(Y)){H([]);return}H(Y.map(rn).slice(0,200))};A instanceof Promise?A.then(F).catch(Y=>{console.warn("[LiveLayer] getRoutes rejected; falling back to DOM walker.",Y),H(Xe())}):F(A)}catch(A){console.warn("[LiveLayer] getRoutes threw; falling back to DOM walker.",A),H(Xe())}return}try{H(Xe())}catch(A){console.warn("[LiveLayer] request_routes: extractRoutes threw.",A)}return}hr.has(p.type)||_e==null||_e(p)}},[_e,we]),W=Ot({agentId:q?"__controlled__":Ne,baseUrl:o,apiKey:i,sessionEndpoint:s,sessionBody:l,onDataMessage:q?void 0:Te});r.useEffect(()=>{if(q!=null&&q.subscribeToDataMessages)return q.subscribeToDataMessages(Te)},[q,Te]),ne.current=()=>{var y;return(y=W.getRoom)==null?void 0:y.call(W)},r.useEffect(()=>{var X;if(typeof window>"u")return;const y=((X=window.location)==null?void 0:X.hostname)||"";if(y==="localhost"||y==="127.0.0.1"||y==="0.0.0.0"||y.endsWith(".local")||y.endsWith(".test"))return window.__livelayerSimulateCommand=Ue=>{try{Te(Ue)}catch(Ve){console.warn("[LiveLayer] simulate-command threw:",Ve)}},()=>{delete window.__livelayerSimulateCommand}},[Te]);const w=r.useMemo(()=>q?{connectionState:q.connectionState,agentState:q.agentState,transcript:q.transcript,videoElement:q.videoElement,audioElement:q.audioElement,canResume:q.canResume,error:q.error,agentConfig:null,connect:async()=>{await q.onConnect()},disconnect:()=>q.onDisconnect(),getRoom:W.getRoom,isControlled:!0}:{connectionState:W.connectionState,agentState:W.agentState,transcript:W.transcript,videoElement:W.videoElement,audioElement:W.audioElement,canResume:W.canResume,error:W.error,agentConfig:W.agentConfig,connect:W.connect,disconnect:W.disconnect,getRoom:W.getRoom,isControlled:!1},[q,W]),ft=r.useRef(null);r.useEffect(()=>{const y=w.videoElement,p=ft.current;if(!(!y||!p))return p.appendChild(y),()=>{y.parentNode===p&&p.removeChild(y)}},[w.videoElement]),r.useEffect(()=>{const y=w.audioElement;if(!y)return;de.attach(y);const p=y.play();return p&&typeof p.catch=="function"&&p.catch(X=>{(X==null?void 0:X.name)==="NotAllowedError"&&Me(!0)}),()=>{de.detach()}},[w.audioElement]),r.useEffect(()=>{if(w.isControlled||w.connectionState!=="connected")return;const y=w.getRoom();if(y)return K.setupMic(y).catch(()=>{}),te.attachRoom(y),ge.attachRoom(y),Ae.refresh(),()=>{K.teardownMic(),te.teardown(),ge.teardown()}},[w.isControlled,w.connectionState]),r.useEffect(()=>{const y=w.audioElement;y&&(y.muted=Ze)},[w.audioElement,Ze]);const un=r.useCallback(y=>{const p=w.getRoom();if(p)try{const X=new TextEncoder().encode(JSON.stringify({type:"user_message",text:y}));p.localParticipant.publishData(X,{reliable:!0})}catch{}},[w]),dn=r.useCallback(()=>{cn(y=>!y)},[]);r.useEffect(()=>{ve==null||ve(w.connectionState),w.connectionState==="connected"?oe==null||oe():w.connectionState==="disconnected"&&(ye==null||ye())},[w.connectionState,oe,ye,ve]),r.useEffect(()=>{be==null||be(w.transcript)},[w.transcript,be]),r.useEffect(()=>{xe==null||xe(w.agentState)},[w.agentState,xe]);const pt=r.useRef(!1);r.useEffect(()=>{w.isControlled||!u||pt.current||ue&&w.connectionState==="idle"&&(pt.current=!0,w.connect())},[u,w.connectionState,w,ue]);const fn=r.useCallback(y=>{const p=S==null?void 0:S.find(X=>X.id===y);p&&(Ie(!1),y!==me&&(b(!0),w.disconnect(),se||Se(y),x==null||x(p)))},[S,me,w,se,x]);r.useEffect(()=>{Ce&&w.connectionState==="connected"&&b(!1)},[w.connectionState,Ce]),r.useEffect(()=>{if(!V)return;const y=p=>{p.key==="Escape"&&Ie(!1)};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[V]);const pn=!!E||!!(U!=null&&U.avatarImageUrl)||w.isControlled,Pe=Vt(Ne,o,pn);Z===void 0&&((mt=Pe.info)!=null&&mt.capabilities)&&(it.current=Pe.info.capabilities);const Fe=(U==null?void 0:U.name)??P??((gt=w.agentConfig)==null?void 0:gt.name)??((yt=Pe.info)==null?void 0:yt.name)??"Live Layer",ot=(U==null?void 0:U.avatarImageUrl)??E??((bt=w.agentConfig)==null?void 0:bt.avatarImageUrl)??((xt=Pe.info)==null?void 0:xt.avatarImageUrl)??null,hn=v??((vt=w.agentConfig)==null?void 0:vt.idleLoopUrl)??((wt=Pe.info)==null?void 0:wt.idleLoopUrl)??null,mn=T??null,gn=r.useCallback(()=>J("expanded"),[J]),yn=r.useCallback(()=>J("minimized"),[J]),ht=r.useCallback(()=>{w.disconnect(),J("hidden")},[w,J]),bn=r.useCallback(()=>{const y=w.audioElement;y&&y.play().then(()=>Me(!1)).catch(()=>{})},[w.audioElement]),xn=r.useCallback(()=>{Me(!1),w.connect()},[w]),De={...Oe,zIndex:qe};h.primaryColor&&(De["--ll-color-primary"]=h.primaryColor),h.accentColor&&(De["--ll-color-accent"]=h.accentColor),h.backgroundColor&&(De["--ll-color-bg"]=h.backgroundColor),h.textColor&&(De["--ll-color-fg"]=h.textColor);const vn=["ll-widget",`ll-widget--${ee}`,`ll-widget--${le?"mobile":"desktop"}`,He].filter(Boolean).join(" ");return ue?t.jsxs("div",{className:vn,style:De,"data-display-mode":ee,"data-position":m,children:[ee==="hidden"&&t.jsx(On,{position:m,isMobile:le,isSpeaking:w.agentState==="speaking",onExpand:()=>J("expanded"),label:`Open ${Fe} widget`,avatarImageUrl:ot,agentName:Fe}),ee==="minimized"&&t.jsx(Bn,{position:m,isMobile:le,agentName:Fe,avatarImageUrl:ot,agentState:w.agentState,isMuted:K.isMuted,audioLevel:de,onExpand:gn,onToggleMute:K.toggleMute,onClose:ht}),ee==="expanded"&&t.jsx(Fn,{position:m,isMobile:le,agentName:Fe,avatarImageUrl:ot,idleLoopUrl:hn,greeting:mn,branding:h,teamMembers:S,currentTeamMemberId:me,isSwitchingTeamMember:Ce,teamSwitcherOpen:V,onToggleTeamSwitcher:()=>Ie(y=>!y),onSelectTeamMember:fn,connectionState:w.connectionState,agentState:w.agentState,transcript:w.transcript,isMuted:K.isMuted,micDevices:Ae.mics,isCameraEnabled:te.isEnabled,cameraPreviewEl:te.previewEl,cameraDevices:Ae.cameras,activeCameraId:te.activeDeviceId,isScreenShareEnabled:ge.isEnabled,screenPreviewEl:ge.previewEl,isSpeakerMuted:Ze,allowCamera:C,allowScreenShare:$,allowTyping:M,languageMenuOpen:ln,onToggleLanguageMenu:()=>an(y=>!y),needsUserGesture:We,canResume:w.canResume,micError:K.micError,error:w.error,avatarVideoContainerRef:ft,onConnect:()=>void w.connect(),onDisconnect:()=>w.disconnect(),onRetry:xn,onResumeAudio:bn,onToggleMute:K.toggleMute,onToggleCamera:()=>void te.toggle(),onSwitchCameraDevice:y=>void te.switchDevice(y),onToggleScreenShare:()=>void ge.toggle(),onToggleSpeaker:dn,onSendMessage:un,onMinimize:yn,onClose:ht,onClearMicError:K.clearError})]}):null}function gr(e){return t.jsx(Ht,{children:t.jsx(mr,{...e})})}const yr=({agentId:e,baseUrl:n,apiKey:i,mode:o,onAgentEvent:s,className:l,style:u})=>{const d=r.useRef(null),f=r.useRef(null),g=r.useRef(s);g.current=s;const m=r.useCallback(a=>{var j;const c=a.detail;(j=g.current)==null||j.call(g,c)},[]);return r.useEffect(()=>{const a=d.current;if(!a)return;const c=document.createElement("livelayer-widget");return c.setAttribute("agent-id",e),n&&c.setAttribute("base-url",n),i&&c.setAttribute("api-key",i),o&&c.setAttribute("mode",o),c.addEventListener("agent-event",m),a.appendChild(c),f.current=c,()=>{c.removeEventListener("agent-event",m),a.removeChild(c),f.current=null}},[e]),r.useEffect(()=>{f.current&&(o?f.current.setAttribute("mode",o):f.current.removeAttribute("mode"))},[o]),t.jsx("div",{ref:d,className:l,style:u})},br=r.forwardRef(function({id:n,intent:i,as:o="div",className:s,style:l,children:u},d){return r.createElement(o,{ref:d,"data-ll-region":n,"data-ll-intent":i,className:s,style:l},u)}),xr=r.forwardRef(function({id:n,intent:i,children:o,...s},l){return t.jsx("form",{ref:l,"data-ll-form":n,"data-ll-intent":i,...s,children:o})}),vr=r.forwardRef(function(n,i){const{name:o,label:s,labelClassName:l}=n,u={name:o,"data-ll-field":o};let d;if("as"in n&&n.as==="textarea"){const{name:f,label:g,labelClassName:m,as:a,...c}=n;d=t.jsx("textarea",{ref:i,...u,...c})}else if("as"in n&&n.as==="select"){const{name:f,label:g,labelClassName:m,as:a,children:c,...j}=n;d=t.jsx("select",{ref:i,...u,...j,children:c})}else{const{name:f,label:g,labelClassName:m,as:a,...c}=n;d=t.jsx("input",{ref:i,...u,...c})}return s===void 0?d:t.jsxs("label",{className:l,children:[s,d]})});let zt=1;function wr({onMount:e,defaultOpen:n=!1,storageKey:i="ll-debug-open"}){const[o,s]=r.useState(n),[l,u]=r.useState([]),[d,f]=r.useState(""),[g,m]=r.useState(!1),a=r.useRef(new Set),c=r.useRef([]),j=r.useRef(g);j.current=g,r.useEffect(()=>{try{const x=localStorage.getItem(i);x==="1"&&s(!0),x==="0"&&s(!1)}catch{}},[i]),r.useEffect(()=>{try{localStorage.setItem(i,o?"1":"0")}catch{}},[o,i]),r.useEffect(()=>{const x=v=>{(v.metaKey||v.ctrlKey)&&v.shiftKey&&v.key.toLowerCase()==="l"&&(v.preventDefault(),s(T=>!T))};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[]),r.useEffect(()=>{const x=setInterval(()=>{if(c.current.length===0||j.current)return;const v=c.current.splice(0,c.current.length);u(T=>[...v.reverse(),...T].slice(0,200))},100);return()=>clearInterval(x)},[]);const S=r.useRef(!1);if(r.useEffect(()=>{!e||S.current||(S.current=!0,e(x=>{c.current.push({id:zt++,ts:Date.now(),kind:"event",type:x.eventName,data:x.data})}))},[e]),r.useEffect(()=>{const x=console.warn,v=console.log,T=(E,P)=>function(...h){try{const C=typeof h[0]=="string"?h[0]:"";C.startsWith("[LiveLayer]")&&c.current.push({id:zt++,ts:Date.now(),kind:E,type:C.slice(0,120),data:{args:h.slice(1).map($=>kr($))}})}catch{}return P.apply(this,h)};return console.warn=T("warn",x),console.log=T("log",v),()=>{console.warn=x,console.log=v}},[]),!o)return t.jsx("button",{type:"button",onClick:()=>s(!0),title:"Open LiveLayer debug panel (Cmd/Ctrl + Shift + L)","aria-label":"Open LiveLayer debug panel",style:{position:"fixed",left:16,bottom:16,zIndex:2147483640,background:"#0d0d0d",color:"#fff",border:"1px solid rgba(255,255,255,0.18)",borderRadius:999,padding:"6px 10px",font:"500 11px -apple-system, BlinkMacSystemFont, system-ui, sans-serif",letterSpacing:"-0.1px",cursor:"pointer",boxShadow:"0 4px 12px rgba(0,0,0,0.35)",opacity:.85},children:"🛰 LL debug"});const k=l.filter(x=>{if(!d)return!0;const v=d.toLowerCase();return x.type.toLowerCase().includes(v)||JSON.stringify(x.data||{}).toLowerCase().includes(v)});return t.jsxs("div",{style:{position:"fixed",left:16,bottom:16,zIndex:2147483640,width:380,maxHeight:"60vh",background:"#0d0d0d",color:"#fff",border:"1px solid rgba(255,255,255,0.16)",borderRadius:12,boxShadow:"0 16px 48px rgba(0,0,0,0.5)",font:"500 11px -apple-system, BlinkMacSystemFont, system-ui, sans-serif",letterSpacing:"-0.1px",display:"flex",flexDirection:"column",overflow:"hidden"},children:[t.jsxs("div",{style:{padding:"8px 10px",background:"rgba(255,255,255,0.04)",borderBottom:"1px solid rgba(255,255,255,0.1)",display:"flex",alignItems:"center",gap:8},children:[t.jsx("span",{style:{fontWeight:600,fontSize:12},children:"LiveLayer debug"}),t.jsxs("span",{style:{fontSize:10,color:"rgba(255,255,255,0.4)"},children:[l.length," event",l.length===1?"":"s"]}),t.jsx("span",{style:{flex:1}}),t.jsx("button",{type:"button",onClick:()=>m(x=>!x),style:st(g?"#f59e0b":"transparent"),title:"Pause / resume capture",children:g?"▶ resume":"⏸ pause"}),t.jsx("button",{type:"button",onClick:()=>{u([]),c.current=[]},style:st("transparent"),title:"Clear buffer",children:"clear"}),t.jsx("button",{type:"button",onClick:()=>s(!1),style:st("transparent"),"aria-label":"Close",title:"Close (Cmd/Ctrl + Shift + L)",children:"✕"})]}),t.jsx("input",{type:"text",value:d,onChange:x=>f(x.target.value),placeholder:"filter by type or data…",style:{margin:8,padding:"6px 8px",background:"rgba(255,255,255,0.06)",border:"1px solid rgba(255,255,255,0.1)",borderRadius:6,color:"#fff",fontSize:11,outline:"none"}}),t.jsx("div",{style:{flex:1,overflowY:"auto",padding:"0 8px 8px"},children:k.length===0?t.jsxs("div",{style:{padding:14,fontSize:11,color:"rgba(255,255,255,0.4)",lineHeight:1.5},children:["No events yet. Connect to the agent and trigger a tool call — the events will stream in here. You can also dispatch commands manually in DevTools:",t.jsx("pre",{style:{marginTop:6,background:"rgba(255,255,255,0.04)",padding:6,borderRadius:4,fontSize:10,whiteSpace:"pre-wrap"},children:`window.__livelayerSimulateCommand({
|
|
1
|
+
"use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("react/jsx-runtime"),n=require("react"),Ln=require("@livelayer/sdk"),tt=require("livekit-client");class Ut extends n.Component{constructor(){super(...arguments),this.state={hasError:!1,error:null},this.reset=()=>{this.setState({hasError:!1,error:null})}}static getDerivedStateFromError(r){return{hasError:!0,error:r}}componentDidCatch(r,i){var o,s;(s=(o=this.props).onError)==null||s.call(o,r,i)}render(){var r;return this.state.hasError?this.props.fallback?this.props.fallback:t.jsxs("div",{className:"ll-error-boundary",role:"alert",children:[t.jsx("p",{className:"ll-error-boundary__title",children:"Widget crashed"}),t.jsx("p",{className:"ll-error-boundary__message",children:((r=this.state.error)==null?void 0:r.message)||"Something went wrong."}),t.jsx("button",{type:"button",className:"ll-error-boundary__retry",onClick:this.reset,children:"Reload widget"})]}):this.props.children}}function Vt(e){const[r,i]=n.useState("idle"),[o,s]=n.useState("idle"),[a,u]=n.useState([]),[d,f]=n.useState(null),[h,g]=n.useState(null),[l,c]=n.useState(null),[L,D]=n.useState(!1),[w,_]=n.useState(null),b=n.useRef(null),I=n.useRef(e.onDataMessage);I.current=e.onDataMessage,n.useEffect(()=>{const S={onConnectionStateChange:A=>{i(A),A==="connected"&&_(null)},onAgentStateChange:s,onTranscript:A=>u([...A]),onAgentConfig:f,onAudioTrack:A=>c(A),onVideoTrack:A=>g(A),onVideoTrackRemoved:()=>g(null),onError:A=>_(A),onDataMessage:A=>{var C;(C=I.current)==null||C.call(I,A)},onResumabilityChange:D},$=new Ln.LiveKitSession({agentId:e.agentId,baseUrl:e.baseUrl,apiKey:e.apiKey,sessionEndpoint:e.sessionEndpoint,sessionBody:e.sessionBody},S);return b.current=$,i("idle"),s("idle"),u([]),f(null),g(null),c(null),D(!1),_(null),()=>{var A;(A=$.destroy)==null||A.call($),b.current=null}},[e.agentId,e.baseUrl,e.apiKey,e.sessionEndpoint,JSON.stringify(e.sessionBody??{})]);const E=n.useCallback(async()=>{const S=b.current;if(S)try{await S.connect()}catch($){throw _($ instanceof Error?$.message:String($)),$}},[]),T=n.useCallback(()=>{const S=b.current;S&&S.disconnect()},[]),v=n.useCallback(()=>{var S;return((S=b.current)==null?void 0:S.getRoom())??null},[]);return{connectionState:r,agentState:o,transcript:a,agentConfig:d,videoElement:h,audioElement:l,canResume:L,error:w,connect:E,disconnect:T,getRoom:v,session:b.current}}function Yt(){const e=n.useRef(null),r=n.useRef(null),i=n.useRef(null),o=n.useRef(null),s=n.useRef(new Set),a=n.useRef(null),u=n.useCallback(()=>{const l=r.current;if(!l){o.current=null;return}(!a.current||a.current.length!==l.frequencyBinCount)&&(a.current=new Uint8Array(new ArrayBuffer(l.frequencyBinCount)));const c=a.current;l.getByteFrequencyData(c);let L=0;for(let w=0;w<c.length;w++)L+=c[w];const D=L/c.length/255;for(const w of s.current)try{w(D)}catch(_){console.error("[useAudioLevel] subscriber threw:",_)}o.current=requestAnimationFrame(u)},[]),d=n.useCallback(()=>{if(e.current||typeof window>"u"||typeof AudioContext>"u")return;const l=new AudioContext,c=l.createAnalyser();c.fftSize=64,c.connect(l.destination),e.current=l,r.current=c},[]),f=n.useCallback(l=>{if(d(),!(!e.current||!r.current)){if(i.current){try{i.current.disconnect()}catch{}i.current=null}try{const c=e.current.createMediaElementSource(l);c.connect(r.current),i.current=c}catch(c){console.warn("[useAudioLevel] createMediaElementSource failed:",c);return}o.current===null&&(o.current=requestAnimationFrame(u))}},[d,u]),h=n.useCallback(()=>{if(o.current!==null&&(cancelAnimationFrame(o.current),o.current=null),i.current){try{i.current.disconnect()}catch{}i.current=null}},[]),g=n.useCallback(l=>(s.current.add(l),()=>{s.current.delete(l)}),[]);return n.useEffect(()=>()=>{if(h(),r.current){try{r.current.disconnect()}catch{}r.current=null}if(e.current){try{e.current.close()}catch{}e.current=null}s.current.clear(),a.current=null},[h]),{attach:f,detach:h,subscribe:g}}function Gt(){const[e,r]=n.useState(!1),[i,o]=n.useState(null),s=n.useRef(null),a=n.useRef(null),u=n.useCallback(async g=>{if(s.current&&a.current){try{await a.current.localParticipant.unpublishTrack(s.current)}catch{}s.current.stop(),s.current=null}a.current=g,o(null);try{const l=await tt.createLocalAudioTrack({echoCancellation:!0,noiseSuppression:!0});await g.localParticipant.publishTrack(l),s.current=l,r(l.isMuted)}catch(l){const c=l instanceof Error&&l.name==="NotAllowedError"?"Enable your microphone to talk with the agent.":"Microphone unavailable. Check browser permissions and try again.";throw o(c),l}},[]),d=n.useCallback(()=>{const g=s.current;g&&(g.isMuted?(g.unmute(),r(!1)):(g.mute(),r(!0)))},[]),f=n.useCallback(()=>{const g=s.current,l=a.current;if(g&&l){try{l.localParticipant.unpublishTrack(g)}catch{}g.stop()}s.current=null,a.current=null,r(!1)},[]),h=n.useCallback(()=>o(null),[]);return{isMuted:e,micError:i,toggleMute:d,setupMic:u,teardownMic:f,clearError:h}}const jn={resolution:{width:640,height:480,frameRate:24}};function Kt(){const[e,r]=n.useState(!1),[i,o]=n.useState(null),[s,a]=n.useState(null),[u,d]=n.useState(""),f=n.useRef(null),h=n.useRef(null),g=n.useCallback(b=>{f.current=b},[]),l=n.useCallback(()=>{const b=f.current,I=h.current;if(I&&b){const E=b.localParticipant.getTrackPublication(tt.Track.Source.Camera);if(E!=null&&E.track){try{b.localParticipant.unpublishTrack(E.track)}catch{}E.track.stop()}else I.stop()}h.current=null,a(null),r(!1)},[]),c=n.useCallback(async b=>{const I=f.current;if(I){o(null);try{const E={...jn};b&&(E.deviceId=b);const T=await tt.createLocalVideoTrack(E);await I.localParticipant.publishTrack(T),h.current=T;const v=T.attach();a(v),r(!0),b&&d(b);try{I.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({type:"user_camera_on"})),{reliable:!0})}catch{}}catch(E){const T=E instanceof Error&&E.name==="NotAllowedError"?"Enable your camera in the browser to share video.":"Camera unavailable. Check permissions and try again.";o(T)}}},[]),L=n.useCallback(async()=>{e?l():await c(u||void 0)},[e,u,l,c]),D=n.useCallback(async b=>{l(),await c(b)},[l,c]),w=n.useCallback(()=>{l(),f.current=null,o(null),d("")},[l]),_=n.useCallback(()=>o(null),[]);return n.useEffect(()=>()=>{h.current&&h.current.stop()},[]),{isEnabled:e,error:i,previewEl:s,activeDeviceId:u,toggle:L,switchDevice:D,attachRoom:g,teardown:w,clearError:_}}function Xt(){const[e,r]=n.useState(!1),[i,o]=n.useState(null),[s,a]=n.useState(null),u=n.useRef(null),d=n.useCallback(c=>{u.current=c},[]),f=n.useCallback(()=>a(null),[]),h=n.useCallback(async()=>{const c=u.current;if(c){if(e){try{await c.localParticipant.setScreenShareEnabled(!1)}catch{}f(),r(!1);return}o(null);try{await c.localParticipant.setScreenShareEnabled(!0);let L=0;const D=()=>{const w=c.localParticipant.getTrackPublication(tt.Track.Source.ScreenShare);if(w!=null&&w.track){const _=w.track.attach();a(_),r(!0);try{c.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({type:"user_screen_share_on"})),{reliable:!0})}catch{}return}L++<10?setTimeout(D,100):r(!0)};D()}catch(L){const D=L instanceof Error?L.name:"";D!=="NotAllowedError"&&D!=="AbortError"&&o("Screen share unavailable. Try again."),r(!1)}}},[e,f]),g=n.useCallback(()=>{const c=u.current;if(c&&e)try{c.localParticipant.setScreenShareEnabled(!1)}catch{}f(),r(!1),o(null),u.current=null},[e,f]),l=n.useCallback(()=>o(null),[]);return{isEnabled:e,error:i,previewEl:s,toggle:h,attachRoom:d,teardown:g,clearError:l}}function Jt(){const[e,r]=n.useState([]),[i,o]=n.useState([]),s=n.useCallback(async()=>{if(!(typeof navigator>"u"||!navigator.mediaDevices))try{const a=await navigator.mediaDevices.enumerateDevices();r(a.filter(u=>u.kind==="audioinput")),o(a.filter(u=>u.kind==="videoinput"))}catch{}},[]);return n.useEffect(()=>{if(s(),typeof navigator>"u"||!navigator.mediaDevices)return;const a=()=>void s();return navigator.mediaDevices.addEventListener("devicechange",a),()=>navigator.mediaDevices.removeEventListener("devicechange",a)},[s]),{mics:e,cameras:i,refresh:s}}function Qt(e,r,i=!1){const[o,s]=n.useState(null),[a,u]=n.useState(null),[d,f]=n.useState(!i&&!!e);return n.useEffect(()=>{if(i||!e){f(!1);return}const h=new AbortController,g=r||"https://app.livelayer.studio";return f(!0),u(null),fetch(`${g}/api/widget/agent/${encodeURIComponent(e)}`,{signal:h.signal}).then(async l=>{if(!l.ok){const c=await l.json().catch(()=>({}));throw new Error(c.error||`HTTP ${l.status}`)}return l.json()}).then(l=>{h.signal.aborted||(s(l),f(!1))}).catch(l=>{h.signal.aborted||(u(l instanceof Error?l.message:"Agent lookup failed"),f(!1))}),()=>h.abort()},[e,r,i]),{info:o,error:a,loading:d}}function En(e){if(typeof window>"u")return null;try{return window.localStorage.getItem(e)}catch{return null}}function Rn(e,r){if(!(typeof window>"u"))try{window.localStorage.setItem(e,r)}catch{}}function Zt({value:e,defaultValue:r="expanded",onChange:i}={}){const o=e!==void 0,[s,a]=n.useState(r),u=o?e:s,d=n.useCallback(f=>{f!==u&&(o||a(f),i==null||i(f))},[u,o,i]);return[u,d]}const Nn=["hidden","minimized","expanded"];function An(e){return e&&Nn.includes(e)?e:null}function en({value:e,defaultValue:r="expanded",onChange:i,persistKey:o="ll-widget",disablePersistence:s=!1}={}){const a=`${o}:display-mode`,u=n.useRef(!1),[d,f]=Zt({value:e,defaultValue:r,onChange:h=>{e===void 0&&!s&&Rn(a,h),i==null||i(h)}});return n.useEffect(()=>{if(u.current||(u.current=!0,s||e!==void 0))return;const h=An(En(a));h&&h!==d&&f(h)},[]),[d,f]}const Mn=640;function tn(e=Mn){const[r,i]=n.useState(!1);return n.useEffect(()=>{if(e===!1){i(!1);return}if(typeof window>"u"||typeof window.matchMedia>"u")return;const o=`(max-width: ${e-1}px)`,s=window.matchMedia(o),a=()=>i(s.matches);return a(),typeof s.addEventListener=="function"?(s.addEventListener("change",a),()=>s.removeEventListener("change",a)):(s.addListener(a),()=>{s.removeListener(a)})},[e]),r}const Rt="__llHistoryPatched",nt="ll:pathname";function In(){if(typeof window>"u"||window.history[Rt])return;const e=window.history.pushState,r=window.history.replaceState;window.history.pushState=function(...i){const o=e.apply(this,i);return window.dispatchEvent(new Event(nt)),o},window.history.replaceState=function(...i){const o=r.apply(this,i);return window.dispatchEvent(new Event(nt)),o},window.history[Rt]=!0}function Nt(){return typeof window>"u"?"/":window.location.pathname||"/"}function nn(e){const[r,i]=n.useState(()=>e??Nt());return n.useEffect(()=>{if(e!==void 0)return;In();const o=()=>i(Nt());return o(),window.addEventListener("popstate",o),window.addEventListener(nt,o),()=>{window.removeEventListener("popstate",o),window.removeEventListener(nt,o)}},[e]),e??r}const At=new Map,Tn=/[\\^$+?.()|{}[\]]/g;function Pn(e){return e.replace(Tn,"\\$&")}function Dn(e){const r=At.get(e);if(r)return r;const i=e.length>1&&e.endsWith("/")?e.slice(0,-1):e,o="",s="",a=i.replace(/\*\*/g,o).replace(/\*/g,s),d=Pn(a).replace(new RegExp(`\\/${o}`,"g"),"(?:\\/.*)?").replace(new RegExp(o,"g"),".*").replace(new RegExp(s,"g"),"[^/]+"),f=new RegExp(`^${d}\\/?$`);return At.set(e,f),f}function $n(e,r){const i=r.length>1&&r.endsWith("/")?r.slice(0,-1):r;return Dn(e).test(i)}function rn(e,r){return typeof e=="function"?e(r):e instanceof RegExp?e.test(r):$n(e,r)}function Mt(e,r){if(!e||e.length===0)return!1;for(const i of e)if(rn(i,r))return!0;return!1}function on(e,r,i){return e===void 0?!0:Mt(i,e)?!1:r&&r.length>0?Mt(r,e):!0}function sn(e,r,i){return n.useMemo(()=>on(e,r,i),[e,r,i])}function zn(e){return e===!1?{navigate:!1,thinking:!1,action:!1}:e===void 0||e===!0?{navigate:!0,thinking:!0,action:!0}:{navigate:e.navigate!==!1,thinking:e.thinking!==!1,action:e.action!==!1}}function Hn(e){const r=n.useMemo(()=>zn(e.config),[e.config]),i=e.baseUrl.replace(/\/+$/,""),o=n.useRef(null),s=n.useCallback(f=>{try{new Audio(`${i}${f}`).play().catch(()=>{})}catch{}},[i]),a=n.useCallback(()=>{r.navigate&&s("/audio/page-change-sound.mp3")},[r.navigate,s]),u=n.useCallback(()=>{r.action&&s("/audio/confirmation-sound.mp3")},[r.action,s]),d=n.useCallback(f=>{if(!r.thinking){if(o.current){try{o.current.pause()}catch{}o.current=null}return}if(f){if(o.current)return;try{const h=new Audio(`${i}/audio/thinking-sound.mp3`);h.loop=!0,h.volume=.3,h.play().catch(()=>{o.current=null}),o.current=h}catch{}}else if(o.current){try{o.current.pause()}catch{}o.current=null}},[i,r.thinking]);return n.useEffect(()=>()=>{if(o.current){try{o.current.pause()}catch{}o.current=null}},[]),n.useMemo(()=>({playPageChange:a,playConfirmation:u,setThinking:d}),[a,u,d])}const It=({muted:e=!1,className:r})=>e?t.jsxs("svg",{className:r,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,"aria-hidden":"true",children:[t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"}),t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M17 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2"})]}):t.jsx("svg",{className:r,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,"aria-hidden":"true",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19 11a7 7 0 01-7 7m0 0a7 7 0 01-7-7m7 7v4m0 0H8m4 0h4M12 1a3 3 0 00-3 3v4a3 3 0 006 0V4a3 3 0 00-3-3z"})}),Tt=({className:e})=>t.jsx("svg",{className:e,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,"aria-hidden":"true",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M4 8V4m0 0h4M4 4l5 5m11-1V4m0 0h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5l-5-5m5 5v-4m0 4h-4"})}),On=({className:e})=>t.jsx("svg",{className:e,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,"aria-hidden":"true",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})}),qn={left:180,right:0,up:-90,down:90},Pt=({direction:e="right",className:r})=>t.jsx("svg",{className:r,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,style:{transform:`rotate(${qn[e]}deg)`},"aria-hidden":"true",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 6l6 6-6 6"})});function Bn(e){return e==="top-left"||e==="bottom-left"?"left":"right"}const an="ll-hidden-tab-center-y",Wn=5,Dt=16;function Fn(){if(typeof window>"u")return null;try{const e=window.localStorage.getItem(an);if(!e)return null;const r=Number.parseFloat(e);return Number.isFinite(r)?r:null}catch{return null}}function $t(e){if(!(typeof window>"u"))try{window.localStorage.setItem(an,String(e))}catch{}}const Un=({position:e,isMobile:r,isSpeaking:i,onExpand:o,label:s="Open widget",avatarImageUrl:a,agentName:u})=>{const d=Bn(e),f=d==="right"?"left":"right",h=r?80:72,g=!!a,[l,c]=n.useState(null),[L,D]=n.useState(!1),w=n.useRef(null),_=n.useRef(!1),b=n.useCallback(C=>{if(typeof window>"u")return C;const R=h/2,z=Dt+R,B=window.innerHeight-Dt-R;return B<z?Math.max(z,C):Math.max(z,Math.min(B,C))},[h]);n.useEffect(()=>{const C=Fn();c(b(C??window.innerHeight/2));const R=()=>{c(z=>z===null?null:b(z))};return window.addEventListener("resize",R),()=>window.removeEventListener("resize",R)},[b]);const I=n.useCallback(C=>{if(!(C.pointerType==="mouse"&&C.button!==0)&&l!==null){try{C.currentTarget.setPointerCapture(C.pointerId)}catch{}w.current={startClientY:C.clientY,startCenterY:l,moved:!1}}},[l]),E=n.useCallback(C=>{const R=w.current;if(!R)return;const z=C.clientY-R.startClientY;!R.moved&&Math.abs(z)>Wn&&(R.moved=!0,D(!0)),R.moved&&c(b(R.startCenterY+z))},[b]),T=n.useCallback(C=>{const R=w.current;if(R){try{C.currentTarget.releasePointerCapture(C.pointerId)}catch{}w.current=null,R.moved&&(D(!1),_.current=!0,c(z=>(z!==null&&$t(z),z)))}},[]),v=n.useCallback(()=>{if(_.current){_.current=!1;return}o()},[o]),S=n.useCallback(C=>{if(C.key==="ArrowUp"||C.key==="ArrowDown"){C.preventDefault();const R=C.key==="ArrowUp"?-8:8;c(z=>{if(z===null)return z;const B=b(z+R);return $t(B),B})}},[b]),$=["ll-hidden",`ll-hidden--${d}`,r?"ll-hidden--mobile":"ll-hidden--desktop",i?"ll-hidden--speaking":null,L?"is-dragging":null,g?"ll-hidden--with-avatar":null].filter(Boolean).join(" "),A=l===null?void 0:{top:`${l-h/2}px`,transform:"none"};return t.jsx("button",{type:"button",className:$,onPointerDown:I,onPointerMove:E,onPointerUp:T,onPointerCancel:T,onClick:v,onKeyDown:S,"aria-label":s,"data-position":e,style:A,children:g?t.jsxs(t.Fragment,{children:[t.jsx(Pt,{direction:f,className:"ll-hidden__chevron ll-hidden__chevron--mini"}),t.jsx("img",{src:a,alt:u?`${u} avatar`:"Agent avatar",className:"ll-hidden__avatar",draggable:!1})]}):t.jsx(Pt,{direction:f,className:"ll-hidden__chevron"})})},Vn=({audioLevel:e,bars:r=20,maxHeight:i=20,minHeight:o=4,className:s,barClassName:a})=>{const u=n.useRef(null),d=n.useRef([]),f=n.useMemo(()=>{const g=(Math.sqrt(5)-1)/2;return Array.from({length:r},(l,c)=>.5+c*g%1*.5)},[r]);n.useEffect(()=>e.subscribe(l=>{for(let c=0;c<r;c++){const L=d.current[c];if(!L)continue;const D=Math.max(o,l*i*f[c]);L.style.height=`${D}px`}}),[e,r,i,o,f]);const h=["ll-waveform",s].filter(Boolean).join(" ");return t.jsx("div",{ref:u,className:h,"aria-hidden":"true",children:Array.from({length:r},(g,l)=>t.jsx("div",{ref:c=>{d.current[l]=c},className:["ll-waveform__bar",a].filter(Boolean).join(" "),style:{height:`${o}px`}},l))})},Yn=({position:e,isMobile:r,agentName:i,avatarImageUrl:o,agentState:s,isMuted:a,audioLevel:u,onExpand:d,onToggleMute:f,onClose:h})=>r?t.jsx("div",{className:"ll-minimized ll-minimized--mobile",role:"region","aria-label":`${i} widget`,children:t.jsxs("button",{type:"button",className:"ll-minimized__surface",onClick:d,"aria-label":`Expand ${i} widget`,children:[o?t.jsx("img",{src:o,alt:i,className:"ll-minimized__avatar"}):t.jsx("div",{className:"ll-minimized__avatar ll-minimized__avatar--placeholder"}),t.jsx(Vn,{audioLevel:u,bars:16,maxHeight:18,className:"ll-minimized__waveform"}),t.jsx("span",{className:"ll-minimized__name",children:i}),t.jsxs("div",{className:"ll-minimized__controls",children:[t.jsx("span",{className:"ll-minimized__btn",role:"button",tabIndex:0,onClick:g=>{g.stopPropagation(),f()},onKeyDown:g=>{(g.key==="Enter"||g.key===" ")&&(g.stopPropagation(),g.preventDefault(),f())},"aria-label":a?"Unmute microphone":"Mute microphone",children:t.jsx(It,{muted:a,className:"ll-minimized__icon"})}),t.jsx(Tt,{className:"ll-minimized__icon ll-minimized__icon--expand"})]})]})}):t.jsx("div",{className:"ll-minimized ll-minimized--desktop","data-position":e,role:"region","aria-label":`${i} widget`,children:t.jsxs("div",{className:"ll-minimized__surface",children:[o?t.jsx("img",{src:o,alt:i,className:"ll-minimized__avatar"}):t.jsx("div",{className:"ll-minimized__avatar ll-minimized__avatar--placeholder"}),t.jsxs("div",{className:"ll-minimized__meta",children:[t.jsx("span",{className:"ll-minimized__name",children:i}),t.jsx("span",{className:"ll-minimized__state",children:s==="speaking"?"Speaking":s==="thinking"?"Thinking":"Listening"})]}),t.jsxs("div",{className:"ll-minimized__controls",children:[t.jsx("button",{type:"button",className:"ll-minimized__btn",onClick:f,"aria-label":a?"Unmute microphone":"Mute microphone",children:t.jsx(It,{muted:a,className:"ll-minimized__icon"})}),t.jsx("button",{type:"button",className:"ll-minimized__btn",onClick:d,"aria-label":`Expand ${i} widget`,children:t.jsx(Tt,{className:"ll-minimized__icon"})}),t.jsx("button",{type:"button",className:"ll-minimized__btn ll-minimized__btn--close",onClick:h,"aria-label":"Close widget",children:t.jsx(On,{className:"ll-minimized__icon"})})]})]})}),Gn=({src:e,alt:r,preCannedPlaying:i=!1,className:o,style:s})=>{const[a,u]=n.useState(!1),d=n.useRef(e);if(n.useEffect(()=>{d.current!==e&&(d.current=e,u(!1))},[e]),!e)return null;const f={position:"absolute",inset:0,width:"100%",height:"100%",objectFit:"cover",objectPosition:"top",transition:"opacity 500ms ease, transform 500ms ease",transform:i?"scale(1.02)":"scale(1)",opacity:a?1:0,...s};return t.jsx("img",{src:e,alt:r,className:o,style:f,loading:"eager",fetchPriority:"high",onLoad:()=>u(!0)})},Kn=({position:e,isMobile:r,agentName:i,avatarImageUrl:o,idleLoopUrl:s,greeting:a,branding:u,teamMembers:d,currentTeamMemberId:f,isSwitchingTeamMember:h,teamSwitcherOpen:g,onToggleTeamSwitcher:l,onSelectTeamMember:c,languageMenuOpen:L,onToggleLanguageMenu:D,connectionState:w,agentState:_,transcript:b,canResume:I,needsUserGesture:E,error:T,isMuted:v,micError:S,micDevices:$,isCameraEnabled:A,cameraPreviewEl:C,cameraDevices:R,activeCameraId:z,isScreenShareEnabled:B,screenPreviewEl:Z,isSpeakerMuted:J,allowCamera:me,allowScreenShare:oe,allowTyping:ue,avatarVideoContainerRef:se,agentVideoEl:Y,onConnect:ae,onDisconnect:ve,onRetry:xe,onResumeAudio:we,onToggleMute:_e,onToggleCamera:ke,onSwitchCameraDevice:Se,onToggleScreenShare:Ce,onToggleSpeaker:q,onSendMessage:Fe,onMinimize:Ue,onClose:Ve,onClearMicError:Ye})=>{var Me;const G=b.length>0?b[b.length-1]:null,le=((d==null?void 0:d.length)??0)>1,Le=w==="connecting"||w==="connected",ee=w==="connected",ge=w==="idle"||w==="disconnected"||w==="error",[W,ye]=n.useState(!1);n.useEffect(()=>{if(!Y){ye(!1);return}if(!Y.paused&&Y.readyState>=2){ye(!0);return}ye(!1);const m=()=>ye(!0);return Y.addEventListener("playing",m),Y.addEventListener("loadeddata",m),()=>{Y.removeEventListener("playing",m),Y.removeEventListener("loadeddata",m)}},[Y]);const[be,ne]=n.useState(!1);n.useEffect(()=>{if(!ee){ne(!1);return}if(W)return;const m=setTimeout(()=>ne(!0),8e3);return()=>clearTimeout(m)},[ee,W]);const je=w==="connecting"||ee&&!!o&&!W&&!be,Ee=n.useRef(null),te=n.useRef(null);n.useEffect(()=>{const m=Ee.current;m&&(m.innerHTML="",C&&(C.style.width="100%",C.style.height="100%",C.style.objectFit="cover",C.style.transform="scaleX(-1)",m.appendChild(C)))},[C]),n.useEffect(()=>{const m=te.current;m&&(m.innerHTML="",Z&&(Z.style.width="100%",Z.style.height="100%",Z.style.objectFit="contain",m.appendChild(Z)))},[Z]);const[Q,re]=n.useState(!1),[de,Re]=n.useState(!1);n.useEffect(()=>{if(!Q&&!de&&!L&&!g)return;const m=()=>{re(!1),Re(!1),L&&D(),g&&l()};return document.addEventListener("click",m),()=>document.removeEventListener("click",m)},[Q,de,L,g,D,l]);const[fe,Ne]=n.useState(""),Ge=n.useCallback(m=>{m.preventDefault();const F=fe.trim();F&&(Fe(F),Ne(""))},[fe,Fe]),ze=u.productName||"Live Layer",Ae=ee&&(G!=null&&G.text)?G.text:a||"",it=ee&&(G==null?void 0:G.role)==="agent",ot=["ll-expanded",r?"ll-expanded--mobile":"ll-expanded--desktop"].join(" ");return t.jsxs("div",{className:ot,"data-position":e,"data-state":ee?"connected":Le?"connecting":"idle",role:"dialog","aria-label":`${i} widget`,children:[t.jsxs("div",{className:"ll-expanded__bg",children:[o?t.jsx(Gn,{src:o,alt:i,className:"ll-expanded__bg-img"}):t.jsx("div",{className:"ll-expanded__bg-fallback",children:t.jsx("span",{className:"ll-expanded__bg-initial",children:((Me=i==null?void 0:i.charAt(0))==null?void 0:Me.toUpperCase())||"A"})}),s&&!ee&&t.jsx("video",{className:"ll-expanded__bg-idle",src:s,autoPlay:!0,loop:!0,muted:!0,playsInline:!0})]}),t.jsx("div",{ref:se,className:"ll-expanded__video"}),je&&t.jsxs("div",{className:"ll-expanded__overlay ll-expanded__overlay--connecting",children:[t.jsx("div",{className:"ll-expanded__spinner"}),t.jsx("p",{className:"ll-expanded__overlay-text",children:h?"Switching...":"Connecting..."})]}),E&&ee&&t.jsxs("button",{type:"button",className:"ll-expanded__overlay ll-expanded__overlay--gesture",onClick:we,children:[t.jsx("svg",{width:"32",height:"32",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:t.jsx("path",{d:"M3 9v6h4l5 5V4L7 9H3zm13.54.12a5 5 0 0 1 0 5.76l-1.41-1.41a3 3 0 0 0 0-2.94L16.54 9.12z"})}),t.jsx("p",{className:"ll-expanded__overlay-text",children:"Tap to enable audio"})]}),Le?t.jsxs("div",{className:"ll-expanded__topbar",children:[t.jsxs("div",{className:"ll-expanded__topbar-left",children:[t.jsxs("div",{className:"ll-expanded__pill-wrap",children:[t.jsxs("button",{type:"button",className:"ll-hpill",onClick:m=>{le&&(m.stopPropagation(),l())},"aria-haspopup":le?"listbox":void 0,"aria-expanded":le?g:void 0,children:[t.jsx("span",{className:"ll-hpill__label",children:i}),le&&t.jsx(Qe,{})]}),le&&g&&t.jsx("div",{className:"ll-hmenu",onClick:m=>m.stopPropagation(),role:"listbox",children:d==null?void 0:d.map(m=>t.jsxs("button",{type:"button",className:`ll-hmenu__item ${m.id===f?"is-active":""}`,onClick:()=>c(m.id),role:"option","aria-selected":m.id===f,children:[m.avatarImageUrl&&t.jsx("img",{src:m.avatarImageUrl,alt:"",className:"ll-hmenu__avatar"}),t.jsx("span",{className:"ll-hmenu__name",children:m.name}),m.role&&t.jsx("span",{className:"ll-hmenu__role",children:m.role})]},m.id))})]}),t.jsxs("div",{className:"ll-expanded__pill-wrap",children:[t.jsxs("button",{type:"button",className:"ll-hpill ll-hpill--compact",onClick:m=>{m.stopPropagation(),D()},"aria-haspopup":"listbox","aria-expanded":L,"aria-label":"Language: English",title:"Language: English",children:[t.jsx("span",{className:"ll-hpill__label",children:"EN"}),t.jsx(Qe,{})]}),L&&t.jsx("div",{className:"ll-hmenu",onClick:m=>m.stopPropagation(),role:"listbox",children:t.jsx("button",{type:"button",className:"ll-hmenu__item is-active",role:"option","aria-selected":!0,children:t.jsx("span",{className:"ll-hmenu__name",children:"English"})})})]}),t.jsx("span",{className:`ll-expanded__state ll-expanded__state--${_}`,children:_})]}),t.jsxs("div",{className:"ll-expanded__header-actions",children:[t.jsx("button",{type:"button",className:"ll-hbtn",onClick:Ue,"aria-label":"Minimize widget",title:"Minimize",children:t.jsx(Ht,{})}),t.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--danger",onClick:Ve,"aria-label":"End call",title:"End call",children:t.jsx(zt,{})})]})]}):t.jsxs("div",{className:"ll-expanded__header ll-expanded__header--idle",children:[t.jsx("span",{className:"ll-expanded__brand",children:ze}),t.jsxs("div",{className:"ll-expanded__header-actions",children:[t.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--ghost",onClick:Ue,"aria-label":"Minimize widget",children:t.jsx(Ht,{})}),t.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--danger",onClick:Ve,"aria-label":"Close widget",children:t.jsx(zt,{})})]})]}),ge&&(()=>{const m=I?"Restart paused session":w==="disconnected"?"Reconnect to agent":"Start video call",F=I?"Pick up where you left off":null,Ie=w==="idle"&&!I&&!T;return t.jsxs(t.Fragment,{children:[Ie&&t.jsxs("button",{type:"button",className:"ll-expanded__play",onClick:ae,"aria-label":m,children:[t.jsx("div",{className:"ll-expanded__play-circle",children:t.jsx("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:t.jsx("polygon",{points:"6 3 20 12 6 21 6 3"})})}),t.jsx("span",{className:"ll-expanded__play-label",children:m})]}),t.jsxs("div",{className:"ll-expanded__bottom ll-expanded__bottom--idle",children:[a&&t.jsx("div",{className:"ll-expanded__transcript",children:t.jsx("p",{className:"ll-expanded__transcript-text",children:a})}),F&&t.jsx("p",{className:"ll-expanded__cta-sublabel",children:F}),t.jsx("button",{type:"button",className:"ll-expanded__cta",onClick:ae,"aria-label":m,children:m})]})]})})(),t.jsxs("div",{className:`ll-expanded__pip ${Le&&(A||B)?"is-visible":""}`,children:[t.jsx("div",{ref:te,className:B?"ll-expanded__pip-host":"ll-expanded__pip-host is-hidden"}),t.jsx("div",{ref:Ee,className:!B&&A?"ll-expanded__pip-host":"ll-expanded__pip-host is-hidden"})]}),Le?t.jsxs("div",{className:"ll-expanded__bottom",children:[Ae&&t.jsx("div",{className:`ll-expanded__transcript${it?" ll-expanded__transcript--agent":""}`,"data-role":ee?(G==null?void 0:G.role)??"agent":"agent",children:t.jsx("p",{className:"ll-expanded__transcript-text",children:Ae})}),t.jsxs("div",{className:"ll-toolbar",onClick:m=>m.stopPropagation(),children:[oe&&t.jsx("button",{type:"button",className:`ll-tool ${B?"is-on":""}`,onClick:Ce,"aria-label":B?"Stop sharing screen":"Share screen",title:B?"Stop sharing":"Share screen",children:t.jsx(Xn,{})}),me&&t.jsxs("div",{className:"ll-tool-split",children:[t.jsx("button",{type:"button",className:`ll-tool ll-tool--left ${A?"is-on":""}`,onClick:ke,"aria-label":A?"Turn off camera":"Turn on camera",title:A?"Stop camera":"Start camera",children:t.jsx(Jn,{})}),t.jsx("button",{type:"button",className:`ll-tool ll-tool--right ${A?"is-on":""}`,onClick:m=>{m.stopPropagation(),Re(F=>!F),re(!1)},"aria-label":"Camera devices","aria-haspopup":"listbox","aria-expanded":de,children:t.jsx(Qe,{})}),de&&R.length>0&&t.jsx(Ot,{label:"Camera",devices:R,activeId:z,onPick:m=>{Re(!1),Se(m)}})]}),t.jsxs("div",{className:"ll-tool-split",children:[t.jsx("button",{type:"button",className:`ll-tool ll-tool--left ${v?"is-muted":""}`,onClick:_e,"aria-label":v?"Unmute microphone":"Mute microphone",title:v?"Unmute":"Mute",children:t.jsx(Qn,{muted:v})}),t.jsx("button",{type:"button",className:`ll-tool ll-tool--right ${v?"is-muted":""}`,onClick:m=>{m.stopPropagation(),re(F=>!F),Re(!1)},"aria-label":"Microphone devices","aria-haspopup":"listbox","aria-expanded":Q,children:t.jsx(Qe,{})}),Q&&$.length>0&&t.jsx(Ot,{label:"Microphone",devices:$,activeId:"",onPick:()=>re(!1)})]}),t.jsx("button",{type:"button",className:`ll-tool ${J?"is-muted":""}`,onClick:q,"aria-label":J?"Unmute speaker":"Mute speaker",title:J?"Unmute speaker":"Mute speaker",children:t.jsx(Zn,{muted:J})}),t.jsx("button",{type:"button",className:"ll-tool ll-tool--danger",onClick:ve,"aria-label":"End conversation",title:"End conversation",children:t.jsx(tr,{})})]}),ue&&t.jsxs("form",{className:"ll-message-input",onSubmit:Ge,children:[t.jsx("input",{type:"text",className:"ll-message-input__field",placeholder:"Message...",value:fe,onChange:m=>Ne(m.target.value),"aria-label":"Message the agent"}),fe.trim()&&t.jsx("button",{type:"submit",className:"ll-message-input__send","aria-label":"Send message",children:t.jsx(er,{})})]})]}):null,(()=>{if(S&&w!=="error")return t.jsxs("div",{className:"ll-expanded__banner",role:"alert",children:[t.jsx("span",{children:S}),t.jsx("button",{type:"button",className:"ll-expanded__banner-x",onClick:Ye,"aria-label":"Dismiss",children:"×"})]});if(!T||w!=="error")return null;let m="Failed to connect",F="Try again";return T==="MIC_PERMISSION_DENIED"?m="Microphone blocked. Allow access to talk.":T==="MIC_NOT_FOUND"?m="No microphone found. Plug one in + retry.":T==="MIC_UNAVAILABLE"?m="Mic unavailable. Check other apps using it.":T==="AGENT_TIMEOUT"?m="Agent didn't pick up. Try again.":T==="CONNECT_FAILED"?m="Connection failed. Check your network.":T.length<80&&(m=T),t.jsxs("div",{className:"ll-expanded__banner ll-expanded__banner--error",role:"alert",children:[t.jsx("span",{children:m}),t.jsx("button",{type:"button",className:"ll-expanded__banner-retry",onClick:xe,children:F})]})})()]})};function Qe(){return t.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":!0,children:t.jsx("polyline",{points:"6 9 12 15 18 9"})})}function zt(){return t.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round","aria-hidden":!0,children:[t.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),t.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function Ht(){return t.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round","aria-hidden":!0,children:t.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})})}function Xn(){return t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[t.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),t.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),t.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function Jn(){return t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[t.jsx("path",{d:"M23 7l-7 5 7 5V7z"}),t.jsx("rect",{x:"1",y:"5",width:"15",height:"14",rx:"2"})]})}function Qn({muted:e}){return t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[t.jsx("path",{d:"M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"}),t.jsx("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),t.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),e&&t.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function Zn({muted:e}){return t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[t.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),e?t.jsx("line",{x1:"23",y1:"9",x2:"17",y2:"15"}):t.jsxs(t.Fragment,{children:[t.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14"}),t.jsx("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"})]})]})}function er(){return t.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[t.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"}),t.jsx("polyline",{points:"12 5 19 12 12 19"})]})}function tr(){return t.jsx("svg",{width:"16",height:"16",viewBox:"-4 -4 32 32",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:t.jsx("path",{d:"M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.93.37 1.84.71 2.7a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.38-1.38a2 2 0 0 1 2.11-.45c.86.34 1.77.58 2.7.71A2 2 0 0 1 22 16.92z",transform:"rotate(135 12 12)"})})}const Ot=({label:e,devices:r,activeId:i,onPick:o})=>t.jsxs("div",{className:"ll-device-menu",onClick:s=>s.stopPropagation(),role:"listbox",children:[t.jsx("p",{className:"ll-device-menu__label",children:e}),r.map((s,a)=>{const u=i===s.deviceId;return t.jsxs("button",{type:"button",className:`ll-device-menu__item ${u?"is-active":""}`,onClick:()=>o(s.deviceId),role:"option","aria-selected":u,children:[u&&t.jsx("span",{className:"ll-device-menu__dot",children:"●"}),t.jsx("span",{className:"ll-device-menu__name",children:s.label||`${e} ${a+1}`})]},s.deviceId||a)})]}),nr=['[data-ll-private="true"]',".ll-widget"];function ht(e){let r=e;for(;r;){for(const i of nr)if(r.matches(i))return!0;r=r.parentElement}return!1}function rt(e){if(ht(e))return!1;if(e instanceof HTMLInputElement){if(e.type==="password")return!1;const r=(e.getAttribute("autocomplete")||"").toLowerCase();if(r==="off"||r.startsWith("cc-"))return!1}return!0}const Ze=4096,rr=20,ir=20,or=10,sr=10,ar=30,lr=20,qt=500,cr=['[data-ll-private="true"]',".ll-widget","script","style","noscript","iframe"];function Be(e){if(e.getAttribute("aria-hidden")==="true"||e.hasAttribute("hidden"))return!0;let r=e;for(;r;){for(const i of cr)if(r.matches(i))return!0;r=r.parentElement}return!1}function We(e){if(typeof window>"u")return!0;const r=e.getBoundingClientRect();if(r.width<=0||r.height<=0)return!1;const i=window.innerHeight||document.documentElement.clientHeight,o=window.innerWidth||document.documentElement.clientWidth;return r.bottom>0&&r.right>0&&r.top<i&&r.left<o}function Bt(e){const r=e.getAttribute("id");if(r){const a=document.querySelector(`label[for="${CSS.escape(r)}"]`);if(a!=null&&a.textContent)return a.textContent.trim()}const i=e.getAttribute("aria-label");if(i)return i.trim();const o=e.getAttribute("placeholder");if(o)return o.trim();const s=e.closest("label");return s!=null&&s.textContent?s.textContent.trim():""}function ce(e,r){return e.length<=r?e:e.slice(0,r-1)+"…"}function Pe(e){return e.length}function ln(e,r={}){const i=r.doc??(typeof document<"u"?document:null);if(!i)return{url:"",title:"",pathname:"/",regions:[],visibleText:"",visibleLinks:[],visibleFields:[],forms:[],extras:e};const o=typeof window<"u"&&window.location.href||"",s=typeof window<"u"&&window.location.pathname||"/",a=i.title||"",u=Array.from(i.querySelectorAll("[data-ll-region]")),d=[];for(const v of u){if(d.length>=or)break;if(Be(v)||!We(v))continue;const S=v.getAttribute("data-ll-region")??"",$=v.getAttribute("data-ll-intent")??void 0,A=ce((v.innerText||v.textContent||"").trim(),qt*2);!S||!A||d.push({id:S,intent:$,text:A})}const f=[],h=["H1","H2","H3","H4","H5","H6"],g=Array.from(i.querySelectorAll("h1, h2, h3, h4, h5, h6"));for(const v of g){if(Be(v)||!We(v))continue;const S=(v.textContent||"").trim();S&&f.push(`${v.tagName}: ${ce(S,200)}`)}const l=Array.from(i.querySelectorAll("p, li"));for(const v of l){if(Be(v)||!We(v)||h.includes(v.tagName))continue;const S=(v.textContent||"").trim();S.length>10&&f.push(ce(S,qt))}const c=f.join(`
|
|
2
|
+
`),L=[],D=Array.from(i.querySelectorAll("a[href]"));for(const v of D){if(L.length>=rr)break;if(Be(v)||!We(v))continue;const S=v.getAttribute("href")||"",$=(v.textContent||"").trim();!S||!$||L.push({href:S,text:ce($,100)})}const w=[],_=Array.from(i.querySelectorAll("input, textarea, select"));for(const v of _){if(w.length>=ir)break;if(Be(v)||!rt(v)||!We(v))continue;const S=Bt(v),$=v instanceof HTMLInputElement?v.type:v.tagName.toLowerCase();S&&w.push({label:ce(S,100),type:$})}const b=Array.from(i.querySelectorAll("[data-ll-form]")),I=[];for(const v of b){if(I.length>=sr)break;if(ht(v))continue;const S=v.getAttribute("data-ll-form")||"";if(!S)continue;const $=v.getAttribute("data-ll-intent")||void 0,A=Array.from(v.querySelectorAll("[data-ll-field]")),C=[];for(const R of A){if(C.length>=ar)break;if(!rt(R))continue;const z=R.getAttribute("data-ll-field")||"";if(!z)continue;const B=Bt(R)||z,Z=R instanceof HTMLInputElement?R.type:R.tagName.toLowerCase(),J={name:z,label:ce(B,100),type:Z};if(R.required===!0&&(J.required=!0),R instanceof HTMLSelectElement){const oe=[];for(let ue=0;ue<R.options.length&&!(oe.length>=lr);ue++){const se=R.options[ue];if(!se||se.disabled)continue;const Y=se.value||"",ae=(se.textContent||"").trim()||Y;!Y&&!ae||oe.push({value:Y,label:ce(ae,60)})}oe.length>0&&(J.options=oe)}const me=typeof R.validationMessage=="string"?R.validationMessage:"";me&&(J.validationMessage=ce(me,200)),C.push(J)}I.push({id:S,intent:$,fields:C})}const E={url:o,title:a,pathname:s,regions:d,visibleText:c,visibleLinks:L,visibleFields:w,forms:I,extras:e};let T=Pe(JSON.stringify(E.regions))+Pe(E.visibleText)+Pe(JSON.stringify(E.visibleLinks))+Pe(JSON.stringify(E.visibleFields));for(;T>Ze&&E.visibleFields.length>0;)E.visibleFields.pop(),T=Pe(JSON.stringify(E.visibleFields));for(;T>Ze&&E.visibleLinks.length>0;)E.visibleLinks.pop(),T-=80;return Pe(E.visibleText)>Ze&&(E.visibleText=ce(E.visibleText,Ze-100)),E}let De=null;function pt(e,r={}){const i=Date.now(),s=`${typeof window<"u"&&window.location.pathname||"/"}::${typeof window<"u"?window.scrollY:0}`;if(De&&De.key===s&&i-De.at<1e3)return De.ctx;const a=ln(e,r);return De={key:s,at:i,ctx:a},a}function cn(){De=null}const ur=200;function un(e){const r=String(e.href||"");return{href:r,text:String(e.text??e.title??r),internal:e.internal??!0,title:e.title,description:e.description}}function dr(e){return!(!e||e.startsWith("#")||e.startsWith("javascript:")||e.startsWith("mailto:")||e.startsWith("tel:"))}function dn(e){const r=e??(typeof document<"u"?document:null);if(!r)return[];const i=typeof window<"u"&&window.location.origin||"",o=new Set,s=[],a=Array.from(r.querySelectorAll("a[href]"));for(const u of a){if(s.length>=ur)break;if(ht(u))continue;const d=u.getAttribute("href")||"";if(!dr(d))continue;let f=d,h=!0;try{if(typeof window<"u"){const l=new URL(d,i);h=l.origin===i,h&&d.startsWith("http")&&(f=l.pathname+l.search+l.hash)}}catch{continue}if(o.has(f))continue;o.add(f);const g=(u.textContent||"").trim().slice(0,120);s.push({href:f,text:g,internal:h})}return s}let $e=null;const fr=5e3;function et(){const e=Date.now(),r=typeof window<"u"&&window.location.pathname||"/";if($e&&$e.pathname===r&&e-$e.at<fr)return $e.routes;const i=dn();return $e={at:e,pathname:r,routes:i},i}function fn(){$e=null}function pr(e,r){const i=e instanceof HTMLInputElement?HTMLInputElement.prototype:e instanceof HTMLTextAreaElement?HTMLTextAreaElement.prototype:HTMLSelectElement.prototype,o=Object.getOwnPropertyDescriptor(i,"value"),s=o==null?void 0:o.set;s?s.call(e,r):e.value=r}function hr(e,r,i={}){const o=i.triggerInput??!0,s=i.triggerChange??!0;if(e instanceof HTMLInputElement&&(e.type==="checkbox"||e.type==="radio")){const a=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,"checked"),u=a==null?void 0:a.set,d=r==="true"||r==="1"||r==="on";u?u.call(e,d):e.checked=d,o&&e.dispatchEvent(new Event("input",{bubbles:!0})),s&&e.dispatchEvent(new Event("change",{bubbles:!0}));return}pr(e,r),o&&e.dispatchEvent(new Event("input",{bubbles:!0})),s&&e.dispatchEvent(new Event("change",{bubbles:!0}))}function mr(){if(typeof window>"u"||typeof document>"u")return!1;const e=document.scrollingElement||document.documentElement;if(!e||e.scrollHeight<=e.clientHeight+2)return!1;const r=window.getComputedStyle(e);return!(r.overflowY==="hidden"||r.overflowY==="clip")}function gr(e){if(!(e instanceof HTMLElement))return!1;const i=window.getComputedStyle(e).overflowY;return!(i!=="auto"&&i!=="scroll"||e.scrollHeight<=e.clientHeight+2)}function yr(){if(typeof document>"u")return null;const e=Array.from(document.querySelectorAll("body, body *"));let r=null,i=0;for(const o of e){if(!gr(o))continue;const s=o.getBoundingClientRect();if(s.bottom<=0||s.top>=window.innerHeight||s.right<=0||s.left>=window.innerWidth||s.width<=0||s.height<=0||o.closest(".ll-widget"))continue;const a=s.width*s.height;a>i&&(i=a,r=o)}return r}function br(){if(typeof window>"u")return null;if(mr())return window;const e=yr();return e||window}function Wt(e){return e instanceof Window?e.innerHeight||0:e.clientHeight||0}function vr(e){var r,i;return e instanceof Window?typeof document>"u"?0:Math.max(((r=document.body)==null?void 0:r.scrollHeight)??0,((i=document.documentElement)==null?void 0:i.scrollHeight)??0):e.scrollHeight-e.clientHeight}const xr=new Set(["agent_state","avatar_stream_ready","avatar_active","avatar_idle","bot_ready","agent_error","idle_warning","idle_timeout","navigate","scroll_to","request_page_context","scroll_page","click","fill_form","focus_field","submit_form","request_routes"]);function wr(e){var wt,_t,kt,St,Ct,Lt,jt;const{agentId:r,apiKey:i,baseUrl:o="https://app.livelayer.studio",sessionEndpoint:s,sessionBody:a,soundEffects:u,autoConnect:d=!1,displayMode:f,defaultDisplayMode:h="expanded",onDisplayModeChange:g,position:l="bottom-right",mobileBreakpoint:c=640,persistKey:L="ll-widget",disablePersistence:D=!1,teamMembers:w,currentTeamMemberId:_,onTeamMemberChange:b,idleLoopUrl:I,greeting:E,avatarImageUrl:T,agentName:v,branding:S={},allowCamera:$=!0,allowScreenShare:A=!0,allowTyping:C=!0,showOn:R,hideOn:z,pathname:B,onNavigate:Z,onScrollToSelector:J,getPageContext:me,pageContextExtras:oe,getRoutes:ue,onScrollPage:se,onClick:Y,capabilities:ae,onConnect:ve,onDisconnect:xe,onTranscript:we,onAgentState:_e,onConnectionStateChange:ke,onAgentEvent:Se,onAgentCommand:Ce,controlledSession:q,className:Fe,style:Ue,zIndex:Ve=2147483647}=e,Ye=nn(B),G=sn(Ye,R,z);n.useEffect(()=>{cn(),fn()},[Ye]);const le=_!==void 0,[Le,ee]=n.useState(()=>{var y;return _??((y=w==null?void 0:w[0])==null?void 0:y.id)}),ge=le?_:Le,W=n.useMemo(()=>(w==null?void 0:w.find(y=>y.id===ge))??null,[w,ge]),ye=(W==null?void 0:W.agentId)??r,[be,ne]=en({value:f,defaultValue:h,onChange:g,persistKey:L,disablePersistence:D}),je=tn(c),Ee=Yt(),te=Gt(),Q=Kt(),re=Xt(),de=Jt(),[Re,fe]=n.useState(!1),[Ne,Ge]=n.useState(!1),[ze,Ae]=n.useState(!1),[it,ot]=n.useState(!1),[Me,m]=n.useState(!1),F=Hn({baseUrl:o,config:u}),Ie=n.useRef(F);Ie.current=F;const st=n.useRef(Z),at=n.useRef(J),lt=n.useRef(se),ct=n.useRef(Y),mt=n.useRef(me),gt=n.useRef(oe),yt=n.useRef(ue),ut=n.useRef(ae),ie=n.useRef(null);st.current=Z,at.current=J,lt.current=se,ct.current=Y,mt.current=me,gt.current=oe,yt.current=ue,ut.current=ae;function pe(y){const p=ut.current;return p?p.includes(y):!0}function he(y,p){console.warn(`[LiveLayer] Agent command "${y}" blocked — capability "${p}" not in allowlist. See https://livelayer.studio/docs/react/capabilities`)}const He=n.useCallback(y=>{var X,Xe,Je,Et;const p=y;if(!(!p.type||typeof p.type!="string")){if(Se==null||Se({eventName:p.type,data:y}),p.type==="navigate"){if(!pe("navigate")){he("navigate","navigate");return}const k=typeof p.href=="string"?p.href:null;if(!k){console.warn(`[LiveLayer] Agent emitted "navigate" without href. Skipping. Check your agent's tool schema. See https://livelayer.studio/docs/errors/navigate-missing-href`);return}if(Ie.current.playPageChange(),st.current){try{st.current(k)}catch(j){console.warn(`[LiveLayer] onNavigate threw for "${k}". Falling back. Error:`,j)}return}if(typeof document<"u"){const j=document.querySelector(`a[href="${k.replace(/"/g,'\\"')}"]`);if(j){j.click();return}}if(typeof window<"u"&&typeof history<"u")try{history.pushState({},"",k),window.dispatchEvent(new PopStateEvent("popstate"))}catch(j){console.warn(`[LiveLayer] history.pushState fallback failed for "${k}". Pass an onNavigate prop to use your router directly. See https://livelayer.studio/docs/react/navigation`,j)}return}if(p.type==="scroll_to"){if(!pe("scroll")){he("scroll_to","scroll");return}const k=typeof p.selector=="string"?p.selector:null;if(!k)return;const j=p.behavior==="instant"?"instant":"smooth";if(at.current){try{at.current(k,j)}catch(P){console.warn("[LiveLayer] onScrollToSelector threw.",P)}return}if(typeof document<"u"){let P=null;try{P=document.querySelector(k)}catch{console.warn(`[LiveLayer] scroll_to: invalid selector "${k}".`);return}if(!P){console.warn(`[LiveLayer] scroll_to: no element matched "${k}". The user may be on a different page. See https://livelayer.studio/docs/errors/scroll-no-match`);return}P.scrollIntoView({behavior:j,block:"start"})}return}if(p.type==="request_page_context"){if(!pe("read_page")){he("request_page_context","read_page");return}const k=typeof p.requestId=="string"?p.requestId:void 0,j=(X=ie.current)==null?void 0:X.call(ie),P=O=>{const N=j,V=N==null?void 0:N.localParticipant;if(V!=null&&V.publishData)try{const K=k?{...O,requestId:k}:O,Te=new TextEncoder().encode(JSON.stringify(K));V.publishData(Te,{reliable:!0})}catch(K){console.warn("[LiveLayer] publishData failed.",K)}},M=gt.current,H=mt.current;try{if(H){const O=H(M);if(O instanceof Promise){P({type:"page_context_pending"}),O.then(N=>P({type:"page_context",context:N})).catch(N=>{console.warn("[LiveLayer] getPageContext rejected; falling back to default walker.",N),P({type:"page_context",context:pt(M)})});return}P({type:"page_context",context:O});return}P({type:"page_context",context:pt(M)})}catch(O){console.warn("[LiveLayer] page-context extraction threw. Sending empty context.",O),P({type:"page_context",context:{url:"",title:"",pathname:"/",regions:[],visibleText:"",visibleLinks:[],visibleFields:[],forms:[],extras:M}})}return}if(p.type==="scroll_page"){if(!pe("scroll")){he("scroll_page","scroll");return}const k=p.direction;if(k!=="up"&&k!=="down"&&k!=="top"&&k!=="bottom"){console.warn(`[LiveLayer] scroll_page: invalid direction "${String(k)}". Expected up | down | top | bottom.`);return}const j=p.behavior==="instant"?"instant":"smooth";if(lt.current){try{lt.current(k,j)}catch(N){console.warn("[LiveLayer] onScrollPage threw.",N)}return}if(typeof window>"u")return;const P={behavior:j},M=br(),H=N=>{M instanceof Window?M.scrollBy({top:N,...P}):M.scrollBy({top:N,...P})},O=N=>{M instanceof Window?M.scrollTo({top:N,...P}):M.scrollTo({top:N,...P})};k==="up"?H(-Wt(M)):k==="down"?H(Wt(M)):O(k==="top"?0:vr(M));return}if(p.type==="click"){if(!pe("click")){he("click","click");return}const k=typeof p.selector=="string"?p.selector:null;if(!k){console.warn("[LiveLayer] click: missing selector.");return}if(ct.current){try{ct.current(k)}catch(P){console.warn("[LiveLayer] onClick threw.",P)}return}if(typeof document>"u")return;let j=null;try{j=document.querySelector(k)}catch{console.warn(`[LiveLayer] click: invalid selector "${k}".`);return}if(!j){console.warn(`[LiveLayer] click: no element matched "${k}". See https://livelayer.studio/docs/errors/click-no-match`);return}if(j.closest('[data-ll-private="true"], .ll-widget')){console.warn("[LiveLayer] click: refusing to click element inside a private subtree.");return}(Xe=j.click)==null||Xe.call(j);return}if(p.type==="fill_form"||p.type==="focus_field"){if(!pe("fill_forms")){he(p.type,"fill_forms");return}if(typeof document>"u")return;p.type==="fill_form"&&Ie.current.playConfirmation();const k=typeof p.formId=="string"?p.formId:null;if(!k){console.warn(`[LiveLayer] ${p.type}: missing formId.`);return}const j=document.querySelector(`[data-ll-form="${k.replace(/"/g,'\\"')}"]`);if(!j){console.warn(`[LiveLayer] ${p.type}: no form with data-ll-form="${k}". Tag your form with <LiveLayerForm id> or data-ll-form. See https://livelayer.studio/docs/react/forms`);return}if(j.closest('[data-ll-private="true"], .ll-widget')){console.warn(`[LiveLayer] ${p.type}: refusing to touch a form in a private subtree.`);return}if(p.type==="focus_field"){const M=typeof p.fieldName=="string"?p.fieldName:null;if(!M){console.warn("[LiveLayer] focus_field: missing fieldName.");return}const H=j.querySelector(`[data-ll-field="${M.replace(/"/g,'\\"')}"]`);if(!H){console.warn(`[LiveLayer] focus_field: no field "${M}" in form "${k}".`);return}if(!rt(H)){console.warn(`[LiveLayer] focus_field: field "${M}" is privacy-protected and not focusable.`);return}H.focus();return}const P=p.values&&typeof p.values=="object"?p.values:null;if(!P){console.warn("[LiveLayer] fill_form: missing or invalid values.");return}for(const[M,H]of Object.entries(P)){if(typeof H!="string")continue;const O=j.querySelector(`[data-ll-field="${M.replace(/"/g,'\\"')}"]`);if(!O){console.warn(`[LiveLayer] fill_form: no field "${M}" in form "${k}". Skipping.`);continue}if(!rt(O)){console.warn(`[LiveLayer] fill_form: field "${M}" is privacy-protected (password / cc-* / private). Skipping.`);continue}try{hr(O,H)}catch(N){console.warn(`[LiveLayer] fill_form: failed to set "${M}".`,N)}}return}if(p.type==="submit_form"){if(!pe("submit_forms")){he("submit_form","submit_forms");return}if(typeof document>"u")return;const k=typeof p.formId=="string"?p.formId:null;if(!k){console.warn("[LiveLayer] submit_form: missing formId.");return}Ie.current.playConfirmation();const j=document.querySelector(`[data-ll-form="${k.replace(/"/g,'\\"')}"]`);if(!j){console.warn(`[LiveLayer] submit_form: no form with data-ll-form="${k}".`);return}if(j.closest('[data-ll-private="true"], .ll-widget')){console.warn("[LiveLayer] submit_form: refusing to submit a form in a private subtree.");return}const P=typeof p.requestId=="string"?p.requestId:void 0,M=(Je=ie.current)==null?void 0:Je.call(ie),H=V=>{const K=M,Te=K==null?void 0:K.localParticipant;if(Te!=null&&Te.publishData)try{const Sn=P?{...V,requestId:P}:V,Cn=new TextEncoder().encode(JSON.stringify(Sn));Te.publishData(Cn,{reliable:!0})}catch{}};let O=!1;const N=()=>{O=!0,H({type:"form_submitted",formId:k})};j.addEventListener("submit",N,{once:!0});try{typeof j.requestSubmit=="function"?j.requestSubmit():j.submit()}catch(V){console.warn("[LiveLayer] submit_form: requestSubmit threw.",V),j.removeEventListener("submit",N),H({type:"form_submit_blocked",formId:k,reason:"exception"});return}setTimeout(()=>{O||(j.removeEventListener("submit",N),H({type:"form_submit_blocked",formId:k,reason:"validation"}))},500);return}if(p.type==="request_routes"){if(!pe("read_page")){he("request_routes","read_page");return}const k=typeof p.requestId=="string"?p.requestId:void 0,P=(Et=ie.current)==null?void 0:Et.call(ie),M=P==null?void 0:P.localParticipant;if(!(M!=null&&M.publishData))return;const H=N=>{try{const V=k?{type:"routes",routes:N,requestId:k}:{type:"routes",routes:N},K=new TextEncoder().encode(JSON.stringify(V));M.publishData(K,{reliable:!0})}catch(V){console.warn("[LiveLayer] request_routes: publishData failed.",V)}},O=yt.current;if(O){try{const N=O(),V=K=>{if(!Array.isArray(K)){H([]);return}H(K.map(un).slice(0,200))};N instanceof Promise?N.then(V).catch(K=>{console.warn("[LiveLayer] getRoutes rejected; falling back to DOM walker.",K),H(et())}):V(N)}catch(N){console.warn("[LiveLayer] getRoutes threw; falling back to DOM walker.",N),H(et())}return}try{H(et())}catch(N){console.warn("[LiveLayer] request_routes: extractRoutes threw.",N)}return}xr.has(p.type)||Ce==null||Ce(p)}},[Ce,Se]),U=Vt({agentId:q?"__controlled__":ye,baseUrl:o,apiKey:i,sessionEndpoint:s,sessionBody:a,onDataMessage:q?void 0:He});n.useEffect(()=>{if(q!=null&&q.subscribeToDataMessages)return q.subscribeToDataMessages(He)},[q,He]),ie.current=()=>{var y;return(y=U.getRoom)==null?void 0:y.call(U)},n.useEffect(()=>{var X;if(typeof window>"u")return;const y=((X=window.location)==null?void 0:X.hostname)||"";if(y==="localhost"||y==="127.0.0.1"||y==="0.0.0.0"||y.endsWith(".local")||y.endsWith(".test"))return window.__livelayerSimulateCommand=Xe=>{try{He(Xe)}catch(Je){console.warn("[LiveLayer] simulate-command threw:",Je)}},()=>{delete window.__livelayerSimulateCommand}},[He]);const x=n.useMemo(()=>q?{connectionState:q.connectionState,agentState:q.agentState,transcript:q.transcript,videoElement:q.videoElement,audioElement:q.audioElement,canResume:q.canResume,error:q.error,agentConfig:null,connect:async()=>{await q.onConnect()},disconnect:()=>q.onDisconnect(),getRoom:U.getRoom,isControlled:!0}:{connectionState:U.connectionState,agentState:U.agentState,transcript:U.transcript,videoElement:U.videoElement,audioElement:U.audioElement,canResume:U.canResume,error:U.error,agentConfig:U.agentConfig,connect:U.connect,disconnect:U.disconnect,getRoom:U.getRoom,isControlled:!1},[q,U]),bt=n.useRef(null);n.useEffect(()=>{const y=x.videoElement,p=bt.current;if(!(!y||!p))return p.appendChild(y),()=>{y.parentNode===p&&p.removeChild(y)}},[x.videoElement]),n.useEffect(()=>{const y=x.audioElement;if(!y)return;Ee.attach(y);const p=y.play();return p&&typeof p.catch=="function"&&p.catch(X=>{(X==null?void 0:X.name)==="NotAllowedError"&&fe(!0)}),()=>{Ee.detach()}},[x.audioElement]),n.useEffect(()=>{if(x.isControlled||x.connectionState!=="connected")return;const y=x.getRoom();if(y)return te.setupMic(y).catch(()=>{}),Q.attachRoom(y),re.attachRoom(y),de.refresh(),()=>{te.teardownMic(),Q.teardown(),re.teardown()}},[x.isControlled,x.connectionState]),n.useEffect(()=>{const y=x.audioElement;y&&(y.muted=Me)},[x.audioElement,Me]);const pn=n.useCallback(y=>{const p=x.getRoom();if(p)try{const X=new TextEncoder().encode(JSON.stringify({type:"user_message",text:y}));p.localParticipant.publishData(X,{reliable:!0})}catch{}},[x]),hn=n.useCallback(()=>{m(y=>!y)},[]);n.useEffect(()=>{ke==null||ke(x.connectionState),x.connectionState==="connected"?ve==null||ve():x.connectionState==="disconnected"&&(xe==null||xe())},[x.connectionState,ve,xe,ke]),n.useEffect(()=>{we==null||we(x.transcript)},[x.transcript,we]),n.useEffect(()=>{_e==null||_e(x.agentState)},[x.agentState,_e]),n.useEffect(()=>{F.setThinking(x.agentState==="thinking")},[x.agentState,F]);const vt=n.useRef(!1);n.useEffect(()=>{x.isControlled||!d||vt.current||G&&x.connectionState==="idle"&&(vt.current=!0,x.connect())},[d,x.connectionState,x,G]);const mn=n.useCallback(y=>{const p=w==null?void 0:w.find(X=>X.id===y);p&&(Ae(!1),y!==ge&&(Ge(!0),x.disconnect(),le||ee(y),b==null||b(p)))},[w,ge,x,le,b]);n.useEffect(()=>{Ne&&x.connectionState==="connected"&&Ge(!1)},[x.connectionState,Ne]),n.useEffect(()=>{if(!ze)return;const y=p=>{p.key==="Escape"&&Ae(!1)};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[ze]);const gn=!!T||!!(W!=null&&W.avatarImageUrl)||x.isControlled,Oe=Qt(ye,o,gn);ae===void 0&&((wt=Oe.info)!=null&&wt.capabilities)&&(ut.current=Oe.info.capabilities);const Ke=(W==null?void 0:W.name)??v??((_t=x.agentConfig)==null?void 0:_t.name)??((kt=Oe.info)==null?void 0:kt.name)??"Live Layer",dt=(W==null?void 0:W.avatarImageUrl)??T??((St=x.agentConfig)==null?void 0:St.avatarImageUrl)??((Ct=Oe.info)==null?void 0:Ct.avatarImageUrl)??null,yn=I??((Lt=x.agentConfig)==null?void 0:Lt.idleLoopUrl)??((jt=Oe.info)==null?void 0:jt.idleLoopUrl)??null,bn=E??null,vn=n.useCallback(()=>ne("expanded"),[ne]),xn=n.useCallback(()=>ne("minimized"),[ne]),xt=n.useCallback(()=>{x.disconnect(),ne("hidden")},[x,ne]),wn=n.useCallback(()=>{const y=x.audioElement;y&&y.play().then(()=>fe(!1)).catch(()=>{})},[x.audioElement]),_n=n.useCallback(()=>{fe(!1),x.connect()},[x]),qe={...Ue,zIndex:Ve};S.primaryColor&&(qe["--ll-color-primary"]=S.primaryColor),S.accentColor&&(qe["--ll-color-accent"]=S.accentColor),S.backgroundColor&&(qe["--ll-color-bg"]=S.backgroundColor),S.textColor&&(qe["--ll-color-fg"]=S.textColor);const kn=["ll-widget",`ll-widget--${be}`,`ll-widget--${je?"mobile":"desktop"}`,Fe].filter(Boolean).join(" ");return G?t.jsxs("div",{className:kn,style:qe,"data-display-mode":be,"data-position":l,children:[be==="hidden"&&t.jsx(Un,{position:l,isMobile:je,isSpeaking:x.agentState==="speaking",onExpand:()=>ne("expanded"),label:`Open ${Ke} widget`,avatarImageUrl:dt,agentName:Ke}),be==="minimized"&&t.jsx(Yn,{position:l,isMobile:je,agentName:Ke,avatarImageUrl:dt,agentState:x.agentState,isMuted:te.isMuted,audioLevel:Ee,onExpand:vn,onToggleMute:te.toggleMute,onClose:xt}),be==="expanded"&&t.jsx(Kn,{position:l,isMobile:je,agentName:Ke,avatarImageUrl:dt,idleLoopUrl:yn,greeting:bn,branding:S,teamMembers:w,currentTeamMemberId:ge,isSwitchingTeamMember:Ne,teamSwitcherOpen:ze,onToggleTeamSwitcher:()=>Ae(y=>!y),onSelectTeamMember:mn,connectionState:x.connectionState,agentState:x.agentState,transcript:x.transcript,isMuted:te.isMuted,micDevices:de.mics,isCameraEnabled:Q.isEnabled,cameraPreviewEl:Q.previewEl,cameraDevices:de.cameras,activeCameraId:Q.activeDeviceId,isScreenShareEnabled:re.isEnabled,screenPreviewEl:re.previewEl,isSpeakerMuted:Me,allowCamera:$,allowScreenShare:A,allowTyping:C,languageMenuOpen:it,onToggleLanguageMenu:()=>ot(y=>!y),needsUserGesture:Re,canResume:x.canResume,micError:te.micError,error:x.error,avatarVideoContainerRef:bt,agentVideoEl:x.videoElement,onConnect:()=>void x.connect(),onDisconnect:()=>x.disconnect(),onRetry:_n,onResumeAudio:wn,onToggleMute:te.toggleMute,onToggleCamera:()=>void Q.toggle(),onSwitchCameraDevice:y=>void Q.switchDevice(y),onToggleScreenShare:()=>void re.toggle(),onToggleSpeaker:hn,onSendMessage:pn,onMinimize:xn,onClose:xt,onClearMicError:te.clearError})]}):null}function _r(e){return t.jsx(Ut,{children:t.jsx(wr,{...e})})}const kr=({agentId:e,baseUrl:r,apiKey:i,mode:o,onAgentEvent:s,className:a,style:u})=>{const d=n.useRef(null),f=n.useRef(null),h=n.useRef(s);h.current=s;const g=n.useCallback(l=>{var L;const c=l.detail;(L=h.current)==null||L.call(h,c)},[]);return n.useEffect(()=>{const l=d.current;if(!l)return;const c=document.createElement("livelayer-widget");return c.setAttribute("agent-id",e),r&&c.setAttribute("base-url",r),i&&c.setAttribute("api-key",i),o&&c.setAttribute("mode",o),c.addEventListener("agent-event",g),l.appendChild(c),f.current=c,()=>{c.removeEventListener("agent-event",g),l.removeChild(c),f.current=null}},[e]),n.useEffect(()=>{f.current&&(o?f.current.setAttribute("mode",o):f.current.removeAttribute("mode"))},[o]),t.jsx("div",{ref:d,className:a,style:u})},Sr=n.forwardRef(function({id:r,intent:i,as:o="div",className:s,style:a,children:u},d){return n.createElement(o,{ref:d,"data-ll-region":r,"data-ll-intent":i,className:s,style:a},u)}),Cr=n.forwardRef(function({id:r,intent:i,children:o,...s},a){return t.jsx("form",{ref:a,"data-ll-form":r,"data-ll-intent":i,...s,children:o})}),Lr=n.forwardRef(function(r,i){const{name:o,label:s,labelClassName:a}=r,u={name:o,"data-ll-field":o};let d;if("as"in r&&r.as==="textarea"){const{name:f,label:h,labelClassName:g,as:l,...c}=r;d=t.jsx("textarea",{ref:i,...u,...c})}else if("as"in r&&r.as==="select"){const{name:f,label:h,labelClassName:g,as:l,children:c,...L}=r;d=t.jsx("select",{ref:i,...u,...L,children:c})}else{const{name:f,label:h,labelClassName:g,as:l,...c}=r;d=t.jsx("input",{ref:i,...u,...c})}return s===void 0?d:t.jsxs("label",{className:a,children:[s,d]})});let Ft=1;function jr({onMount:e,defaultOpen:r=!1,storageKey:i="ll-debug-open"}){const[o,s]=n.useState(r),[a,u]=n.useState([]),[d,f]=n.useState(""),[h,g]=n.useState(!1),l=n.useRef(new Set),c=n.useRef([]),L=n.useRef(h);L.current=h,n.useEffect(()=>{try{const _=localStorage.getItem(i);_==="1"&&s(!0),_==="0"&&s(!1)}catch{}},[i]),n.useEffect(()=>{try{localStorage.setItem(i,o?"1":"0")}catch{}},[o,i]),n.useEffect(()=>{const _=b=>{(b.metaKey||b.ctrlKey)&&b.shiftKey&&b.key.toLowerCase()==="l"&&(b.preventDefault(),s(I=>!I))};return window.addEventListener("keydown",_),()=>window.removeEventListener("keydown",_)},[]),n.useEffect(()=>{const _=setInterval(()=>{if(c.current.length===0||L.current)return;const b=c.current.splice(0,c.current.length);u(I=>[...b.reverse(),...I].slice(0,200))},100);return()=>clearInterval(_)},[]);const D=n.useRef(!1);if(n.useEffect(()=>{!e||D.current||(D.current=!0,e(_=>{c.current.push({id:Ft++,ts:Date.now(),kind:"event",type:_.eventName,data:_.data})}))},[e]),n.useEffect(()=>{const _=console.warn,b=console.log,I=(E,T)=>function(...v){try{const S=typeof v[0]=="string"?v[0]:"";S.startsWith("[LiveLayer]")&&c.current.push({id:Ft++,ts:Date.now(),kind:E,type:S.slice(0,120),data:{args:v.slice(1).map($=>Rr($))}})}catch{}return T.apply(this,v)};return console.warn=I("warn",_),console.log=I("log",b),()=>{console.warn=_,console.log=b}},[]),!o)return t.jsx("button",{type:"button",onClick:()=>s(!0),title:"Open LiveLayer debug panel (Cmd/Ctrl + Shift + L)","aria-label":"Open LiveLayer debug panel",style:{position:"fixed",left:16,bottom:16,zIndex:2147483640,background:"#0d0d0d",color:"#fff",border:"1px solid rgba(255,255,255,0.18)",borderRadius:999,padding:"6px 10px",font:"500 11px -apple-system, BlinkMacSystemFont, system-ui, sans-serif",letterSpacing:"-0.1px",cursor:"pointer",boxShadow:"0 4px 12px rgba(0,0,0,0.35)",opacity:.85},children:"🛰 LL debug"});const w=a.filter(_=>{if(!d)return!0;const b=d.toLowerCase();return _.type.toLowerCase().includes(b)||JSON.stringify(_.data||{}).toLowerCase().includes(b)});return t.jsxs("div",{style:{position:"fixed",left:16,bottom:16,zIndex:2147483640,width:380,maxHeight:"60vh",background:"#0d0d0d",color:"#fff",border:"1px solid rgba(255,255,255,0.16)",borderRadius:12,boxShadow:"0 16px 48px rgba(0,0,0,0.5)",font:"500 11px -apple-system, BlinkMacSystemFont, system-ui, sans-serif",letterSpacing:"-0.1px",display:"flex",flexDirection:"column",overflow:"hidden"},children:[t.jsxs("div",{style:{padding:"8px 10px",background:"rgba(255,255,255,0.04)",borderBottom:"1px solid rgba(255,255,255,0.1)",display:"flex",alignItems:"center",gap:8},children:[t.jsx("span",{style:{fontWeight:600,fontSize:12},children:"LiveLayer debug"}),t.jsxs("span",{style:{fontSize:10,color:"rgba(255,255,255,0.4)"},children:[a.length," event",a.length===1?"":"s"]}),t.jsx("span",{style:{flex:1}}),t.jsx("button",{type:"button",onClick:()=>g(_=>!_),style:ft(h?"#f59e0b":"transparent"),title:"Pause / resume capture",children:h?"▶ resume":"⏸ pause"}),t.jsx("button",{type:"button",onClick:()=>{u([]),c.current=[]},style:ft("transparent"),title:"Clear buffer",children:"clear"}),t.jsx("button",{type:"button",onClick:()=>s(!1),style:ft("transparent"),"aria-label":"Close",title:"Close (Cmd/Ctrl + Shift + L)",children:"✕"})]}),t.jsx("input",{type:"text",value:d,onChange:_=>f(_.target.value),placeholder:"filter by type or data…",style:{margin:8,padding:"6px 8px",background:"rgba(255,255,255,0.06)",border:"1px solid rgba(255,255,255,0.1)",borderRadius:6,color:"#fff",fontSize:11,outline:"none"}}),t.jsx("div",{style:{flex:1,overflowY:"auto",padding:"0 8px 8px"},children:w.length===0?t.jsxs("div",{style:{padding:14,fontSize:11,color:"rgba(255,255,255,0.4)",lineHeight:1.5},children:["No events yet. Connect to the agent and trigger a tool call — the events will stream in here. You can also dispatch commands manually in DevTools:",t.jsx("pre",{style:{marginTop:6,background:"rgba(255,255,255,0.04)",padding:6,borderRadius:4,fontSize:10,whiteSpace:"pre-wrap"},children:`window.__livelayerSimulateCommand({
|
|
3
3
|
type: "navigate",
|
|
4
4
|
href: "/about"
|
|
5
|
-
})`})]}):
|
|
5
|
+
})`})]}):w.map(_=>t.jsx(Er,{entry:_,expanded:l.current.has(_.id),onToggle:()=>{l.current.has(_.id)?l.current.delete(_.id):l.current.add(_.id),u(b=>[...b])}},_.id))})]})}function Er({entry:e,expanded:r,onToggle:i}){const o=e.kind==="warn"?"#f59e0b":e.type.startsWith("[LiveLayer]")?"#94a3b8":e.type==="navigate"||e.type==="scroll_page"||e.type==="scroll_to"||e.type==="click"?"#22c55e":e.type==="fill_form"||e.type==="submit_form"||e.type==="focus_field"?"#a78bfa":e.type==="request_page_context"||e.type==="request_routes"?"#38bdf8":e.type==="agent_state"?"#facc15":"#cbd5e1",s=new Date(e.ts).toLocaleTimeString("en-US",{hour12:!1});return t.jsxs("button",{type:"button",onClick:i,style:{textAlign:"left",background:"transparent",border:0,color:"#fff",width:"100%",padding:"6px 4px",cursor:"pointer",borderBottom:"1px solid rgba(255,255,255,0.04)",fontSize:11,lineHeight:1.4},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[t.jsx("span",{style:{color:"rgba(255,255,255,0.4)",fontVariantNumeric:"tabular-nums",fontSize:10},children:s}),t.jsx("span",{style:{color:o,fontWeight:600,flexShrink:0},children:e.type.length>50?e.type.slice(0,50)+"…":e.type})]}),r&&e.data&&t.jsx("pre",{style:{marginTop:6,padding:6,background:"rgba(255,255,255,0.04)",borderRadius:4,fontSize:10,overflowX:"auto",whiteSpace:"pre-wrap",wordBreak:"break-all"},children:JSON.stringify(e.data,null,2)})]})}function ft(e){return{background:e,color:"#fff",border:"1px solid rgba(255,255,255,0.16)",borderRadius:999,padding:"3px 8px",fontSize:10,cursor:"pointer"}}function Rr(e){try{return e instanceof Error?{message:e.message,stack:e.stack}:(JSON.stringify(e),e)}catch{return String(e)}}function Nr(){const[e,r]=n.useState([]),i=n.useCallback(s=>{r(a=>{const u=a.findIndex(d=>d.id===s.id);if(u>=0){const d=a.slice();return d[u]=s,d}return[...a,s]})},[]),o=n.useCallback(()=>r([]),[]);return{entries:e,pushSegment:i,clear:o,latest:e.length>0?e[e.length-1]:null}}exports.AvatarWidget=_r;exports.ErrorBoundary=Ut;exports.LiveLayerDebugPanel=jr;exports.LiveLayerField=Lr;exports.LiveLayerForm=Cr;exports.LiveLayerRegion=Sr;exports.LiveLayerWidget=kr;exports.clearPageContextCache=cn;exports.clearRoutesCache=fn;exports.extractPageContext=ln;exports.extractRoutes=dn;exports.getCachedPageContext=pt;exports.getCachedRoutes=et;exports.matchesPattern=rn;exports.normalizeRouteInput=un;exports.shouldRenderAtPath=on;exports.useAgentInfo=Qt;exports.useAudioLevel=Yt;exports.useCameraState=Kt;exports.useDisplayMode=Zt;exports.useDisplayModePersistence=en;exports.useIsMobile=tn;exports.useLiveKitSession=Vt;exports.useMediaDevices=Jt;exports.useMicrophoneState=Gt;exports.usePathname=nn;exports.useRouteMatch=sn;exports.useScreenShareState=Xt;exports.useTranscript=Nr;
|