@livelayer/react 0.5.11 → 0.5.12-pr66.0
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.js +3 -3
- package/dist/index.mjs +590 -576
- package/package.json +3 -3
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"),tt=require("livekit-client");class Bt 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,o){var i,s;(s=(i=this.props).onError)==null||s.call(i,n,o)}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 Wt(e){const[n,o]=r.useState("idle"),[i,s]=r.useState("idle"),[a,u]=r.useState([]),[d,p]=r.useState(null),[b,y]=r.useState(null),[l,c]=r.useState(null),[j,S]=r.useState(!1),[k,x]=r.useState(null),v=r.useRef(null),I=r.useRef(e.onDataMessage);I.current=e.onDataMessage,r.useEffect(()=>{const C={onConnectionStateChange:A=>{o(A),A==="connected"&&x(null)},onAgentStateChange:s,onTranscript:A=>u([...A]),onAgentConfig:p,onAudioTrack:A=>c(A),onVideoTrack:A=>y(A),onVideoTrackRemoved:()=>y(null),onError:A=>x(A),onDataMessage:A=>{var L;(L=I.current)==null||L.call(I,A)},onResumabilityChange:S},$=new kn.LiveKitSession({agentId:e.agentId,baseUrl:e.baseUrl,apiKey:e.apiKey,sessionEndpoint:e.sessionEndpoint,sessionBody:e.sessionBody},C);return v.current=$,o("idle"),s("idle"),u([]),p(null),y(null),c(null),S(!1),x(null),()=>{var A;(A=$.destroy)==null||A.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($)),$}},[]),T=r.useCallback(()=>{const C=v.current;C&&C.disconnect()},[]),m=r.useCallback(()=>{var C;return((C=v.current)==null?void 0:C.getRoom())??null},[]);return{connectionState:n,agentState:i,transcript:a,agentConfig:d,videoElement:b,audioElement:l,canResume:j,error:k,connect:E,disconnect:T,getRoom:m,session:v.current}}function Ft(){const e=r.useRef(null),n=r.useRef(null),o=r.useRef(null),i=r.useRef(null),s=r.useRef(new Set),a=r.useRef(null),u=r.useCallback(()=>{const l=n.current;if(!l){i.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 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)}i.current=requestAnimationFrame(u)},[]),d=r.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,n.current=c},[]),p=r.useCallback(l=>{if(d(),!(!e.current||!n.current)){if(o.current){try{o.current.disconnect()}catch{}o.current=null}try{const c=e.current.createMediaElementSource(l);c.connect(n.current),o.current=c}catch(c){console.warn("[useAudioLevel] createMediaElementSource failed:",c);return}i.current===null&&(i.current=requestAnimationFrame(u))}},[d,u]),b=r.useCallback(()=>{if(i.current!==null&&(cancelAnimationFrame(i.current),i.current=null),o.current){try{o.current.disconnect()}catch{}o.current=null}},[]),y=r.useCallback(l=>(s.current.add(l),()=>{s.current.delete(l)}),[]);return r.useEffect(()=>()=>{if(b(),n.current){try{n.current.disconnect()}catch{}n.current=null}if(e.current){try{e.current.close()}catch{}e.current=null}s.current.clear(),a.current=null},[b]),{attach:p,detach:b,subscribe:y}}function Ut(){const[e,n]=r.useState(!1),[o,i]=r.useState(null),s=r.useRef(null),a=r.useRef(null),u=r.useCallback(async y=>{if(s.current&&a.current){try{await a.current.localParticipant.unpublishTrack(s.current)}catch{}s.current.stop(),s.current=null}a.current=y,i(null);try{const l=await tt.createLocalAudioTrack({echoCancellation:!0,noiseSuppression:!0});await y.localParticipant.publishTrack(l),s.current=l,n(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 i(c),l}},[]),d=r.useCallback(()=>{const y=s.current;y&&(y.isMuted?(y.unmute(),n(!1)):(y.mute(),n(!0)))},[]),p=r.useCallback(()=>{const y=s.current,l=a.current;if(y&&l){try{l.localParticipant.unpublishTrack(y)}catch{}y.stop()}s.current=null,a.current=null,n(!1)},[]),b=r.useCallback(()=>i(null),[]);return{isMuted:e,micError:o,toggleMute:d,setupMic:u,teardownMic:p,clearError:b}}const Sn={resolution:{width:640,height:480,frameRate:24}};function Vt(){const[e,n]=r.useState(!1),[o,i]=r.useState(null),[s,a]=r.useState(null),[u,d]=r.useState(""),p=r.useRef(null),b=r.useRef(null),y=r.useCallback(v=>{p.current=v},[]),l=r.useCallback(()=>{const v=p.current,I=b.current;if(I&&v){const E=v.localParticipant.getTrackPublication(tt.Track.Source.Camera);if(E!=null&&E.track){try{v.localParticipant.unpublishTrack(E.track)}catch{}E.track.stop()}else I.stop()}b.current=null,a(null),n(!1)},[]),c=r.useCallback(async v=>{const I=p.current;if(I){i(null);try{const E={...Sn};v&&(E.deviceId=v);const T=await tt.createLocalVideoTrack(E);await I.localParticipant.publishTrack(T),b.current=T;const m=T.attach();a(m),n(!0),v&&d(v);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.";i(T)}}},[]),j=r.useCallback(async()=>{e?l():await c(u||void 0)},[e,u,l,c]),S=r.useCallback(async v=>{l(),await c(v)},[l,c]),k=r.useCallback(()=>{l(),p.current=null,i(null),d("")},[l]),x=r.useCallback(()=>i(null),[]);return r.useEffect(()=>()=>{b.current&&b.current.stop()},[]),{isEnabled:e,error:o,previewEl:s,activeDeviceId:u,toggle:j,switchDevice:S,attachRoom:y,teardown:k,clearError:x}}function Yt(){const[e,n]=r.useState(!1),[o,i]=r.useState(null),[s,a]=r.useState(null),u=r.useRef(null),d=r.useCallback(c=>{u.current=c},[]),p=r.useCallback(()=>a(null),[]),b=r.useCallback(async()=>{const c=u.current;if(c){if(e){try{await c.localParticipant.setScreenShareEnabled(!1)}catch{}p(),n(!1);return}i(null);try{await c.localParticipant.setScreenShareEnabled(!0);let j=0;const S=()=>{const k=c.localParticipant.getTrackPublication(tt.Track.Source.ScreenShare);if(k!=null&&k.track){const x=k.track.attach();a(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"&&i("Screen share unavailable. Try again."),n(!1)}}},[e,p]),y=r.useCallback(()=>{const c=u.current;if(c&&e)try{c.localParticipant.setScreenShareEnabled(!1)}catch{}p(),n(!1),i(null),u.current=null},[e,p]),l=r.useCallback(()=>i(null),[]);return{isEnabled:e,error:o,previewEl:s,toggle:b,attachRoom:d,teardown:y,clearError:l}}function Gt(){const[e,n]=r.useState([]),[o,i]=r.useState([]),s=r.useCallback(async()=>{if(!(typeof navigator>"u"||!navigator.mediaDevices))try{const a=await navigator.mediaDevices.enumerateDevices();n(a.filter(u=>u.kind==="audioinput")),i(a.filter(u=>u.kind==="videoinput"))}catch{}},[]);return r.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:o,refresh:s}}function Jt(e,n,o=!1){const[i,s]=r.useState(null),[a,u]=r.useState(null),[d,p]=r.useState(!o&&!!e);return r.useEffect(()=>{if(o||!e){p(!1);return}const b=new AbortController,y=n||"https://app.livelayer.studio";return p(!0),u(null),fetch(`${y}/api/widget/agent/${encodeURIComponent(e)}`,{signal:b.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=>{b.signal.aborted||(s(l),p(!1))}).catch(l=>{b.signal.aborted||(u(l instanceof Error?l.message:"Agent lookup failed"),p(!1))}),()=>b.abort()},[e,n,o]),{info:i,error:a,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 Kt({value:e,defaultValue:n="expanded",onChange:o}={}){const i=e!==void 0,[s,a]=r.useState(n),u=i?e:s,d=r.useCallback(p=>{p!==u&&(i||a(p),o==null||o(p))},[u,i,o]);return[u,d]}const jn=["hidden","minimized","expanded"];function En(e){return e&&jn.includes(e)?e:null}function Xt({value:e,defaultValue:n="expanded",onChange:o,persistKey:i="ll-widget",disablePersistence:s=!1}={}){const a=`${i}:display-mode`,u=r.useRef(!1),[d,p]=Kt({value:e,defaultValue:n,onChange:b=>{e===void 0&&!s&&Ln(a,b),o==null||o(b)}});return r.useEffect(()=>{if(u.current||(u.current=!0,s||e!==void 0))return;const b=En(Cn(a));b&&b!==d&&p(b)},[]),[d,p]}const Rn=640;function Qt(e=Rn){const[n,o]=r.useState(!1);return r.useEffect(()=>{if(e===!1){o(!1);return}if(typeof window>"u"||typeof window.matchMedia>"u")return;const i=`(max-width: ${e-1}px)`,s=window.matchMedia(i),a=()=>o(s.matches);return a(),typeof s.addEventListener=="function"?(s.addEventListener("change",a),()=>s.removeEventListener("change",a)):(s.addListener(a),()=>{s.removeListener(a)})},[e]),n}const Lt="__llHistoryPatched",nt="ll:pathname";function Nn(){if(typeof window>"u"||window.history[Lt])return;const e=window.history.pushState,n=window.history.replaceState;window.history.pushState=function(...o){const i=e.apply(this,o);return window.dispatchEvent(new Event(nt)),i},window.history.replaceState=function(...o){const i=n.apply(this,o);return window.dispatchEvent(new Event(nt)),i},window.history[Lt]=!0}function jt(){return typeof window>"u"?"/":window.location.pathname||"/"}function Zt(e){const[n,o]=r.useState(()=>e??jt());return r.useEffect(()=>{if(e!==void 0)return;Nn();const i=()=>o(jt());return i(),window.addEventListener("popstate",i),window.addEventListener(nt,i),()=>{window.removeEventListener("popstate",i),window.removeEventListener(nt,i)}},[e]),e??n}const Et=new Map,An=/[\\^$+?.()|{}[\]]/g;function Mn(e){return e.replace(An,"\\$&")}function In(e){const n=Et.get(e);if(n)return n;const o=e.length>1&&e.endsWith("/")?e.slice(0,-1):e,i="",s="",a=o.replace(/\*\*/g,i).replace(/\*/g,s),d=Mn(a).replace(new RegExp(`\\/${i}`,"g"),"(?:\\/.*)?").replace(new RegExp(i,"g"),".*").replace(new RegExp(s,"g"),"[^/]+"),p=new RegExp(`^${d}\\/?$`);return Et.set(e,p),p}function Tn(e,n){const o=n.length>1&&n.endsWith("/")?n.slice(0,-1):n;return In(e).test(o)}function en(e,n){return typeof e=="function"?e(n):e instanceof RegExp?e.test(n):Tn(e,n)}function Rt(e,n){if(!e||e.length===0)return!1;for(const o of e)if(en(o,n))return!0;return!1}function tn(e,n,o){return e===void 0?!0:Rt(o,e)?!1:n&&n.length>0?Rt(n,e):!0}function nn(e,n,o){return r.useMemo(()=>tn(e,n,o),[e,n,o])}const Nt=({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"})}),At=({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},Mt=({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 rn="ll-hidden-tab-center-y",zn=5,It=16;function Hn(){if(typeof window>"u")return null;try{const e=window.localStorage.getItem(rn);if(!e)return null;const n=Number.parseFloat(e);return Number.isFinite(n)?n:null}catch{return null}}function Tt(e){if(!(typeof window>"u"))try{window.localStorage.setItem(rn,String(e))}catch{}}const On=({position:e,isMobile:n,isSpeaking:o,onExpand:i,label:s="Open widget",avatarImageUrl:a,agentName:u})=>{const d=$n(e),p=d==="right"?"left":"right",b=n?80:72,y=!!a,[l,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 P=b/2,z=It+P,W=window.innerHeight-It-P;return W<z?Math.max(z,L):Math.max(z,Math.min(W,L))},[b]);r.useEffect(()=>{const L=Hn();c(v(L??window.innerHeight/2));const P=()=>{c(z=>z===null?null:v(z))};return window.addEventListener("resize",P),()=>window.removeEventListener("resize",P)},[v]);const I=r.useCallback(L=>{if(!(L.pointerType==="mouse"&&L.button!==0)&&l!==null){try{L.currentTarget.setPointerCapture(L.pointerId)}catch{}k.current={startClientY:L.clientY,startCenterY:l,moved:!1}}},[l]),E=r.useCallback(L=>{const P=k.current;if(!P)return;const z=L.clientY-P.startClientY;!P.moved&&Math.abs(z)>zn&&(P.moved=!0,S(!0)),P.moved&&c(v(P.startCenterY+z))},[v]),T=r.useCallback(L=>{const P=k.current;if(P){try{L.currentTarget.releasePointerCapture(L.pointerId)}catch{}k.current=null,P.moved&&(S(!1),x.current=!0,c(z=>(z!==null&&Tt(z),z)))}},[]),m=r.useCallback(()=>{if(x.current){x.current=!1;return}i()},[i]),C=r.useCallback(L=>{if(L.key==="ArrowUp"||L.key==="ArrowDown"){L.preventDefault();const P=L.key==="ArrowUp"?-8:8;c(z=>{if(z===null)return z;const W=v(z+P);return Tt(W),W})}},[v]),$=["ll-hidden",`ll-hidden--${d}`,n?"ll-hidden--mobile":"ll-hidden--desktop",o?"ll-hidden--speaking":null,j?"is-dragging":null,y?"ll-hidden--with-avatar":null].filter(Boolean).join(" "),A=l===null?void 0:{top:`${l-b/2}px`,transform:"none"};return t.jsx("button",{type:"button",className:$,onPointerDown:I,onPointerMove:E,onPointerUp:T,onPointerCancel:T,onClick:m,onKeyDown:C,"aria-label":s,"data-position":e,style:A,children:y?t.jsxs(t.Fragment,{children:[t.jsx(Mt,{direction:p,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(Mt,{direction:p,className:"ll-hidden__chevron"})})},qn=({audioLevel:e,bars:n=20,maxHeight:o=20,minHeight:i=4,className:s,barClassName:a})=>{const u=r.useRef(null),d=r.useRef([]),p=r.useMemo(()=>{const y=(Math.sqrt(5)-1)/2;return Array.from({length:n},(l,c)=>.5+c*y%1*.5)},[n]);r.useEffect(()=>e.subscribe(l=>{for(let c=0;c<n;c++){const j=d.current[c];if(!j)continue;const S=Math.max(i,l*o*p[c]);j.style.height=`${S}px`}}),[e,n,o,i,p]);const b=["ll-waveform",s].filter(Boolean).join(" ");return t.jsx("div",{ref:u,className:b,"aria-hidden":"true",children:Array.from({length:n},(y,l)=>t.jsx("div",{ref:c=>{d.current[l]=c},className:["ll-waveform__bar",a].filter(Boolean).join(" "),style:{height:`${i}px`}},l))})},Bn=({position:e,isMobile:n,agentName:o,avatarImageUrl:i,agentState:s,isMuted:a,audioLevel:u,onExpand:d,onToggleMute:p,onClose:b})=>n?t.jsx("div",{className:"ll-minimized ll-minimized--mobile",role:"region","aria-label":`${o} widget`,children:t.jsxs("button",{type:"button",className:"ll-minimized__surface",onClick:d,"aria-label":`Expand ${o} widget`,children:[i?t.jsx("img",{src:i,alt:o,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:o}),t.jsxs("div",{className:"ll-minimized__controls",children:[t.jsx("span",{className:"ll-minimized__btn",role:"button",tabIndex:0,onClick:y=>{y.stopPropagation(),p()},onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&(y.stopPropagation(),y.preventDefault(),p())},"aria-label":a?"Unmute microphone":"Mute microphone",children:t.jsx(Nt,{muted:a,className:"ll-minimized__icon"})}),t.jsx(At,{className:"ll-minimized__icon ll-minimized__icon--expand"})]})]})}):t.jsx("div",{className:"ll-minimized ll-minimized--desktop","data-position":e,role:"region","aria-label":`${o} widget`,children:t.jsxs("div",{className:"ll-minimized__surface",children:[i?t.jsx("img",{src:i,alt:o,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:o}),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:p,"aria-label":a?"Unmute microphone":"Mute microphone",children:t.jsx(Nt,{muted:a,className:"ll-minimized__icon"})}),t.jsx("button",{type:"button",className:"ll-minimized__btn",onClick:d,"aria-label":`Expand ${o} widget`,children:t.jsx(At,{className:"ll-minimized__icon"})}),t.jsx("button",{type:"button",className:"ll-minimized__btn ll-minimized__btn--close",onClick:b,"aria-label":"Close widget",children:t.jsx(Pn,{className:"ll-minimized__icon"})})]})]})}),Wn=({src:e,alt:n,preCannedPlaying:o=!1,className:i,style:s})=>{const[a,u]=r.useState(!1),d=r.useRef(e);if(r.useEffect(()=>{d.current!==e&&(d.current=e,u(!1))},[e]),!e)return null;const p={position:"absolute",inset:0,width:"100%",height:"100%",objectFit:"cover",objectPosition:"top",transition:"opacity 500ms ease, transform 500ms ease",transform:o?"scale(1.02)":"scale(1)",opacity:a?1:0,...s};return t.jsx("img",{src:e,alt:n,className:i,style:p,loading:"eager",fetchPriority:"high",onLoad:()=>u(!0)})},Fn=({position:e,isMobile:n,agentName:o,avatarImageUrl:i,idleLoopUrl:s,greeting:a,branding:u,teamMembers:d,currentTeamMemberId:p,isSwitchingTeamMember:b,teamSwitcherOpen:y,onToggleTeamSwitcher:l,onSelectTeamMember:c,languageMenuOpen:j,onToggleLanguageMenu:S,connectionState:k,agentState:x,transcript:v,canResume:I,needsUserGesture:E,error:T,isMuted:m,micError:C,micDevices:$,isCameraEnabled:A,cameraPreviewEl:L,cameraDevices:P,activeCameraId:z,isScreenShareEnabled:W,screenPreviewEl:Q,isSpeakerMuted:de,allowCamera:Be,allowScreenShare:We,allowTyping:Fe,avatarVideoContainerRef:Ue,agentVideoEl:X,onConnect:fe,onDisconnect:ge,onRetry:ye,onResumeAudio:be,onToggleMute:xe,onToggleCamera:ve,onSwitchCameraDevice:we,onToggleScreenShare:B,onToggleSpeaker:ot,onSendMessage:Ve,onMinimize:Ye,onClose:ie,onClearMicError:Ne})=>{var Je;const G=v.length>0?v[v.length-1]:null,pe=((d==null?void 0:d.length)??0)>1,_e=k==="connecting"||k==="connected",V=k==="connected",J=k==="idle"||k==="disconnected"||k==="error",[ke,ee]=r.useState(!1);r.useEffect(()=>{if(!X){ee(!1);return}if(!X.paused&&X.readyState>=2){ee(!0);return}ee(!1);const h=()=>ee(!0);return X.addEventListener("playing",h),X.addEventListener("loadeddata",h),()=>{X.removeEventListener("playing",h),X.removeEventListener("loadeddata",h)}},[X]);const[oe,he]=r.useState(!1);r.useEffect(()=>{if(!V){he(!1);return}if(ke)return;const h=setTimeout(()=>he(!0),8e3);return()=>clearTimeout(h)},[V,ke]);const Ae=k==="connecting"||V&&!!i&&!ke&&!oe,Z=r.useRef(null),te=r.useRef(null);r.useEffect(()=>{const h=Z.current;h&&(h.innerHTML="",L&&(L.style.width="100%",L.style.height="100%",L.style.objectFit="cover",L.style.transform="scaleX(-1)",h.appendChild(L)))},[L]),r.useEffect(()=>{const h=te.current;h&&(h.innerHTML="",Q&&(Q.style.width="100%",Q.style.height="100%",Q.style.objectFit="contain",h.appendChild(Q)))},[Q]);const[ne,se]=r.useState(!1),[Se,ae]=r.useState(!1);r.useEffect(()=>{if(!ne&&!Se&&!j&&!y)return;const h=()=>{se(!1),ae(!1),j&&S(),y&&l()};return document.addEventListener("click",h),()=>document.removeEventListener("click",h)},[ne,Se,j,y,S,l]);const[le,Me]=r.useState(""),Ie=r.useCallback(h=>{h.preventDefault();const Y=le.trim();Y&&(Ve(Y),Me(""))},[le,Ve]),Te=u.productName||"Live Layer",Ge=V&&(G!=null&&G.text)?G.text:a||"",it=V&&(G==null?void 0:G.role)==="agent",Pe=["ll-expanded",n?"ll-expanded--mobile":"ll-expanded--desktop"].join(" ");return t.jsxs("div",{className:Pe,"data-position":e,"data-state":V?"connected":_e?"connecting":"idle",role:"dialog","aria-label":`${o} widget`,children:[t.jsxs("div",{className:"ll-expanded__bg",children:[i?t.jsx(Wn,{src:i,alt:o,className:"ll-expanded__bg-img"}):t.jsx("div",{className:"ll-expanded__bg-fallback",children:t.jsx("span",{className:"ll-expanded__bg-initial",children:((Je=o==null?void 0:o.charAt(0))==null?void 0:Je.toUpperCase())||"A"})}),s&&!V&&t.jsx("video",{className:"ll-expanded__bg-idle",src:s,autoPlay:!0,loop:!0,muted:!0,playsInline:!0})]}),t.jsx("div",{ref:Ue,className:"ll-expanded__video"}),Ae&&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:b?"Switching...":"Connecting..."})]}),E&&V&&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"})]}),_e?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:h=>{pe&&(h.stopPropagation(),l())},"aria-haspopup":pe?"listbox":void 0,"aria-expanded":pe?y:void 0,children:[t.jsx("span",{className:"ll-hpill__label",children:o}),pe&&t.jsx(Qe,{})]}),pe&&y&&t.jsx("div",{className:"ll-hmenu",onClick:h=>h.stopPropagation(),role:"listbox",children:d==null?void 0:d.map(h=>t.jsxs("button",{type:"button",className:`ll-hmenu__item ${h.id===p?"is-active":""}`,onClick:()=>c(h.id),role:"option","aria-selected":h.id===p,children:[h.avatarImageUrl&&t.jsx("img",{src:h.avatarImageUrl,alt:"",className:"ll-hmenu__avatar"}),t.jsx("span",{className:"ll-hmenu__name",children:h.name}),h.role&&t.jsx("span",{className:"ll-hmenu__role",children:h.role})]},h.id))})]}),t.jsxs("div",{className:"ll-expanded__pill-wrap",children:[t.jsxs("button",{type:"button",className:"ll-hpill ll-hpill--compact",onClick:h=>{h.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(Qe,{})]}),j&&t.jsx("div",{className:"ll-hmenu",onClick:h=>h.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:Ye,"aria-label":"Minimize widget",title:"Minimize",children:t.jsx(Dt,{})}),t.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--danger",onClick:ie,"aria-label":"End call",title:"End call",children:t.jsx(Pt,{})})]})]}):t.jsxs("div",{className:"ll-expanded__header ll-expanded__header--idle",children:[t.jsx("span",{className:"ll-expanded__brand",children:Te}),t.jsxs("div",{className:"ll-expanded__header-actions",children:[t.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--ghost",onClick:Ye,"aria-label":"Minimize widget",children:t.jsx(Dt,{})}),t.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--danger",onClick:ie,"aria-label":"Close widget",children:t.jsx(Pt,{})})]})]}),J&&(()=>{const h=I?"Restart paused session":k==="disconnected"?"Reconnect to agent":"Start video call",Y=I?"Pick up where you left off":null,De=k==="idle"&&!I&&!T;return t.jsxs(t.Fragment,{children:[De&&t.jsxs("button",{type:"button",className:"ll-expanded__play",onClick:fe,"aria-label":h,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:h})]}),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})}),Y&&t.jsx("p",{className:"ll-expanded__cta-sublabel",children:Y}),t.jsx("button",{type:"button",className:"ll-expanded__cta",onClick:fe,"aria-label":h,children:h})]})]})})(),t.jsxs("div",{className:`ll-expanded__pip ${_e&&(A||W)?"is-visible":""}`,children:[t.jsx("div",{ref:te,className:W?"ll-expanded__pip-host":"ll-expanded__pip-host is-hidden"}),t.jsx("div",{ref:Z,className:!W&&A?"ll-expanded__pip-host":"ll-expanded__pip-host is-hidden"})]}),_e?t.jsxs("div",{className:"ll-expanded__bottom",children:[Ge&&t.jsx("div",{className:`ll-expanded__transcript${it?" ll-expanded__transcript--agent":""}`,"data-role":V?(G==null?void 0:G.role)??"agent":"agent",children:t.jsx("p",{className:"ll-expanded__transcript-text",children:Ge})}),t.jsxs("div",{className:"ll-toolbar",onClick:h=>h.stopPropagation(),children:[We&&t.jsx("button",{type:"button",className:`ll-tool ${W?"is-on":""}`,onClick:B,"aria-label":W?"Stop sharing screen":"Share screen",title:W?"Stop sharing":"Share screen",children:t.jsx(Un,{})}),Be&&t.jsxs("div",{className:"ll-tool-split",children:[t.jsx("button",{type:"button",className:`ll-tool ll-tool--left ${A?"is-on":""}`,onClick:ve,"aria-label":A?"Turn off camera":"Turn on camera",title:A?"Stop camera":"Start camera",children:t.jsx(Vn,{})}),t.jsx("button",{type:"button",className:`ll-tool ll-tool--right ${A?"is-on":""}`,onClick:h=>{h.stopPropagation(),ae(Y=>!Y),se(!1)},"aria-label":"Camera devices","aria-haspopup":"listbox","aria-expanded":Se,children:t.jsx(Qe,{})}),Se&&P.length>0&&t.jsx($t,{label:"Camera",devices:P,activeId:z,onPick:h=>{ae(!1),we(h)}})]}),t.jsxs("div",{className:"ll-tool-split",children:[t.jsx("button",{type:"button",className:`ll-tool ll-tool--left ${m?"is-muted":""}`,onClick:xe,"aria-label":m?"Unmute microphone":"Mute microphone",title:m?"Unmute":"Mute",children:t.jsx(Yn,{muted:m})}),t.jsx("button",{type:"button",className:`ll-tool ll-tool--right ${m?"is-muted":""}`,onClick:h=>{h.stopPropagation(),se(Y=>!Y),ae(!1)},"aria-label":"Microphone devices","aria-haspopup":"listbox","aria-expanded":ne,children:t.jsx(Qe,{})}),ne&&$.length>0&&t.jsx($t,{label:"Microphone",devices:$,activeId:"",onPick:()=>se(!1)})]}),t.jsx("button",{type:"button",className:`ll-tool ${de?"is-muted":""}`,onClick:ot,"aria-label":de?"Unmute speaker":"Mute speaker",title:de?"Unmute speaker":"Mute speaker",children:t.jsx(Gn,{muted:de})}),t.jsx("button",{type:"button",className:"ll-tool ll-tool--danger",onClick:ge,"aria-label":"End conversation",title:"End conversation",children:t.jsx(Kn,{})})]}),Fe&&t.jsxs("form",{className:"ll-message-input",onSubmit:Ie,children:[t.jsx("input",{type:"text",className:"ll-message-input__field",placeholder:"Message...",value:le,onChange:h=>Me(h.target.value),"aria-label":"Message the agent"}),le.trim()&&t.jsx("button",{type:"submit",className:"ll-message-input__send","aria-label":"Send message",children:t.jsx(Jn,{})})]})]}):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:Ne,"aria-label":"Dismiss",children:"×"})]});if(!T||k!=="error")return null;let h="Failed to connect",Y="Try again";return T==="MIC_PERMISSION_DENIED"?h="Microphone blocked. Allow access to talk.":T==="MIC_NOT_FOUND"?h="No microphone found. Plug one in + retry.":T==="MIC_UNAVAILABLE"?h="Mic unavailable. Check other apps using it.":T==="AGENT_TIMEOUT"?h="Agent didn't pick up. Try again.":T==="CONNECT_FAILED"?h="Connection failed. Check your network.":T.length<80&&(h=T),t.jsxs("div",{className:"ll-expanded__banner ll-expanded__banner--error",role:"alert",children:[t.jsx("span",{children:h}),t.jsx("button",{type:"button",className:"ll-expanded__banner-retry",onClick:ye,children:Y})]})})()]})};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 Pt(){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 Dt(){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 Gn({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 Jn(){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 Kn(){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 $t=({label:e,devices:n,activeId:o,onPick:i})=>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,a)=>{const u=o===s.deviceId;return t.jsxs("button",{type:"button",className:`ll-device-menu__item ${u?"is-active":""}`,onClick:()=>i(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)})]}),Xn=['[data-ll-private="true"]',".ll-widget"];function dt(e){let n=e;for(;n;){for(const o of Xn)if(n.matches(o))return!0;n=n.parentElement}return!1}function rt(e){if(dt(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 Ze=4096,Qn=20,Zn=20,er=10,tr=10,nr=30,zt=500,rr=['[data-ll-private="true"]',".ll-widget","script","style","noscript","iframe"];function Oe(e){if(e.getAttribute("aria-hidden")==="true"||e.hasAttribute("hidden"))return!0;let n=e;for(;n;){for(const o of rr)if(n.matches(o))return!0;n=n.parentElement}return!1}function qe(e){if(typeof window>"u")return!0;const n=e.getBoundingClientRect();if(n.width<=0||n.height<=0)return!1;const o=window.innerHeight||document.documentElement.clientHeight,i=window.innerWidth||document.documentElement.clientWidth;return n.bottom>0&&n.right>0&&n.top<o&&n.left<i}function Ht(e){const n=e.getAttribute("id");if(n){const a=document.querySelector(`label[for="${CSS.escape(n)}"]`);if(a!=null&&a.textContent)return a.textContent.trim()}const o=e.getAttribute("aria-label");if(o)return o.trim();const i=e.getAttribute("placeholder");if(i)return i.trim();const s=e.closest("label");return s!=null&&s.textContent?s.textContent.trim():""}function me(e,n){return e.length<=n?e:e.slice(0,n-1)+"…"}function je(e){return e.length}function on(e,n={}){const o=n.doc??(typeof document<"u"?document:null);if(!o)return{url:"",title:"",pathname:"/",regions:[],visibleText:"",visibleLinks:[],visibleFields:[],forms:[],extras:e};const i=typeof window<"u"&&window.location.href||"",s=typeof window<"u"&&window.location.pathname||"/",a=o.title||"",u=Array.from(o.querySelectorAll("[data-ll-region]")),d=[];for(const m of u){if(d.length>=er)break;if(Oe(m)||!qe(m))continue;const C=m.getAttribute("data-ll-region")??"",$=m.getAttribute("data-ll-intent")??void 0,A=me((m.innerText||m.textContent||"").trim(),zt*2);!C||!A||d.push({id:C,intent:$,text:A})}const p=[],b=["H1","H2","H3","H4","H5","H6"],y=Array.from(o.querySelectorAll("h1, h2, h3, h4, h5, h6"));for(const m of y){if(Oe(m)||!qe(m))continue;const C=(m.textContent||"").trim();C&&p.push(`${m.tagName}: ${me(C,200)}`)}const l=Array.from(o.querySelectorAll("p, li"));for(const m of l){if(Oe(m)||!qe(m)||b.includes(m.tagName))continue;const C=(m.textContent||"").trim();C.length>10&&p.push(me(C,zt))}const c=p.join(`
|
|
2
|
-
`),j=[],S=Array.from(o.querySelectorAll("a[href]"));for(const m of S){if(j.length>=Qn)break;if(Oe(m)||!qe(m))continue;const C=m.getAttribute("href")||"",$=(m.textContent||"").trim();!C||!$||j.push({href:C,text:me($,100)})}const k=[],x=Array.from(o.querySelectorAll("input, textarea, select"));for(const m of x){if(k.length>=Zn)break;if(Oe(m)||!rt(m)||!qe(m))continue;const C=Ht(m),$=m instanceof HTMLInputElement?m.type:m.tagName.toLowerCase();C&&k.push({label:me(C,100),type:$})}const v=Array.from(o.querySelectorAll("[data-ll-form]")),I=[];for(const m of v){if(I.length>=tr)break;if(dt(m))continue;const C=m.getAttribute("data-ll-form")||"";if(!C)continue;const $=m.getAttribute("data-ll-intent")||void 0,A=Array.from(m.querySelectorAll("[data-ll-field]")),L=[];for(const P of A){if(L.length>=nr)break;if(!rt(P))continue;const z=P.getAttribute("data-ll-field")||"";if(!z)continue;const W=Ht(P)||z,Q=P instanceof HTMLInputElement?P.type:P.tagName.toLowerCase();L.push({name:z,label:me(W,100),type:Q})}I.push({id:C,intent:$,fields:L})}const E={url:i,title:a,pathname:s,regions:d,visibleText:c,visibleLinks:j,visibleFields:k,forms:I,extras:e};let T=je(JSON.stringify(E.regions))+je(E.visibleText)+je(JSON.stringify(E.visibleLinks))+je(JSON.stringify(E.visibleFields));for(;T>Ze&&E.visibleFields.length>0;)E.visibleFields.pop(),T=je(JSON.stringify(E.visibleFields));for(;T>Ze&&E.visibleLinks.length>0;)E.visibleLinks.pop(),T-=80;return je(E.visibleText)>Ze&&(E.visibleText=me(E.visibleText,Ze-100)),E}let Ee=null;function ut(e,n={}){const o=Date.now(),s=`${typeof window<"u"&&window.location.pathname||"/"}::${typeof window<"u"?window.scrollY:0}`;if(Ee&&Ee.key===s&&o-Ee.at<1e3)return Ee.ctx;const a=on(e,n);return Ee={key:s,at:o,ctx:a},a}function sn(){Ee=null}const or=200;function an(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 ir(e){return!(!e||e.startsWith("#")||e.startsWith("javascript:")||e.startsWith("mailto:")||e.startsWith("tel:"))}function ln(e){const n=e??(typeof document<"u"?document:null);if(!n)return[];const o=typeof window<"u"&&window.location.origin||"",i=new Set,s=[],a=Array.from(n.querySelectorAll("a[href]"));for(const u of a){if(s.length>=or)break;if(dt(u))continue;const d=u.getAttribute("href")||"";if(!ir(d))continue;let p=d,b=!0;try{if(typeof window<"u"){const l=new URL(d,o);b=l.origin===o,b&&d.startsWith("http")&&(p=l.pathname+l.search+l.hash)}}catch{continue}if(i.has(p))continue;i.add(p);const y=(u.textContent||"").trim().slice(0,120);s.push({href:p,text:y,internal:b})}return s}let Re=null;const sr=5e3;function et(){const e=Date.now(),n=typeof window<"u"&&window.location.pathname||"/";if(Re&&Re.pathname===n&&e-Re.at<sr)return Re.routes;const o=ln();return Re={at:e,pathname:n,routes:o},o}function cn(){Re=null}function ar(e,n){const o=e instanceof HTMLInputElement?HTMLInputElement.prototype:e instanceof HTMLTextAreaElement?HTMLTextAreaElement.prototype:HTMLSelectElement.prototype,i=Object.getOwnPropertyDescriptor(o,"value"),s=i==null?void 0:i.set;s?s.call(e,n):e.value=n}function lr(e,n,o={}){const i=o.triggerInput??!0,s=o.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=n==="true"||n==="1"||n==="on";u?u.call(e,d):e.checked=d,i&&e.dispatchEvent(new Event("input",{bubbles:!0})),s&&e.dispatchEvent(new Event("change",{bubbles:!0}));return}ar(e,n),i&&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 o=window.getComputedStyle(e).overflowY;return!(o!=="auto"&&o!=="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,o=0;for(const i of e){if(!ur(i))continue;const s=i.getBoundingClientRect();if(s.bottom<=0||s.top>=window.innerHeight||s.right<=0||s.left>=window.innerWidth||s.width<=0||s.height<=0||i.closest(".ll-widget"))continue;const a=s.width*s.height;a>o&&(o=a,n=i)}return n}function fr(){if(typeof window>"u")return null;if(cr())return window;const e=dr();return e||window}function Ot(e){return e instanceof Window?e.innerHeight||0:e.clientHeight||0}function pr(e){var n,o;return e instanceof Window?typeof document>"u"?0:Math.max(((n=document.body)==null?void 0:n.scrollHeight)??0,((o=document.documentElement)==null?void 0:o.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 bt,xt,vt,wt,_t,kt,St;const{agentId:n,apiKey:o,baseUrl:i="https://app.livelayer.studio",sessionEndpoint:s,sessionBody:a,autoConnect:u=!1,displayMode:d,defaultDisplayMode:p="expanded",onDisplayModeChange:b,position:y="bottom-right",mobileBreakpoint:l=640,persistKey:c="ll-widget",disablePersistence:j=!1,teamMembers:S,currentTeamMemberId:k,onTeamMemberChange:x,idleLoopUrl:v,greeting:I,avatarImageUrl:E,agentName:T,branding:m={},allowCamera:C=!0,allowScreenShare:$=!0,allowTyping:A=!0,showOn:L,hideOn:P,pathname:z,onNavigate:W,onScrollToSelector:Q,getPageContext:de,pageContextExtras:Be,getRoutes:We,onScrollPage:Fe,onClick:Ue,capabilities:X,onConnect:fe,onDisconnect:ge,onTranscript:ye,onAgentState:be,onConnectionStateChange:xe,onAgentEvent:ve,onAgentCommand:we,controlledSession:B,className:ot,style:Ve,zIndex:Ye=2147483647}=e,ie=Zt(z),Ne=nn(ie,L,P);r.useEffect(()=>{sn(),cn()},[ie]);const G=k!==void 0,[pe,_e]=r.useState(()=>{var g;return k??((g=S==null?void 0:S[0])==null?void 0:g.id)}),V=G?k:pe,J=r.useMemo(()=>(S==null?void 0:S.find(g=>g.id===V))??null,[S,V]),ke=(J==null?void 0:J.agentId)??n,[ee,oe]=Xt({value:d,defaultValue:p,onChange:b,persistKey:c,disablePersistence:j}),he=Qt(l),Ae=Ft(),Z=Ut(),te=Vt(),ne=Yt(),se=Gt(),[Se,ae]=r.useState(!1),[le,Me]=r.useState(!1),[Ie,Te]=r.useState(!1),[Ge,it]=r.useState(!1),[Pe,Je]=r.useState(!1),h=r.useRef(W),Y=r.useRef(Q),De=r.useRef(Fe),st=r.useRef(Ue),ft=r.useRef(de),pt=r.useRef(Be),ht=r.useRef(We),at=r.useRef(X),re=r.useRef(null);h.current=W,Y.current=Q,De.current=Fe,st.current=Ue,ft.current=de,pt.current=Be,ht.current=We,at.current=X;function ce(g){const f=at.current;return f?f.includes(g):!0}function ue(g,f){console.warn(`[LiveLayer] Agent command "${g}" blocked — capability "${f}" not in allowlist. See https://livelayer.studio/docs/react/capabilities`)}const $e=r.useCallback(g=>{var F,Ce,Xe,Ct;const f=g;if(!(!f.type||typeof f.type!="string")){if(ve==null||ve({eventName:f.type,data:g}),f.type==="navigate"){if(!ce("navigate")){ue("navigate","navigate");return}const _=typeof f.href=="string"?f.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(h.current){try{h.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(f.type==="scroll_to"){if(!ce("scroll")){ue("scroll_to","scroll");return}const _=typeof f.selector=="string"?f.selector:null;if(!_)return;const R=f.behavior==="instant"?"instant":"smooth";if(Y.current){try{Y.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(f.type==="request_page_context"){if(!ce("read_page")){ue("request_page_context","read_page");return}const _=typeof f.requestId=="string"?f.requestId:void 0,R=(F=re.current)==null?void 0:F.call(re),D=q=>{const N=R,U=N==null?void 0:N.localParticipant;if(U!=null&&U.publishData)try{const K=_?{...q,requestId:_}:q,Le=new TextEncoder().encode(JSON.stringify(K));U.publishData(Le,{reliable:!0})}catch(K){console.warn("[LiveLayer] publishData failed.",K)}},M=pt.current,H=ft.current;try{if(H){const q=H(M);if(q instanceof Promise){D({type:"page_context_pending"}),q.then(N=>D({type:"page_context",context:N})).catch(N=>{console.warn("[LiveLayer] getPageContext rejected; falling back to default walker.",N),D({type:"page_context",context:ut(M)})});return}D({type:"page_context",context:q});return}D({type:"page_context",context:ut(M)})}catch(q){console.warn("[LiveLayer] page-context extraction threw. Sending empty context.",q),D({type:"page_context",context:{url:"",title:"",pathname:"/",regions:[],visibleText:"",visibleLinks:[],visibleFields:[],forms:[],extras:M}})}return}if(f.type==="scroll_page"){if(!ce("scroll")){ue("scroll_page","scroll");return}const _=f.direction;if(_!=="up"&&_!=="down"&&_!=="top"&&_!=="bottom"){console.warn(`[LiveLayer] scroll_page: invalid direction "${String(_)}". Expected up | down | top | bottom.`);return}const R=f.behavior==="instant"?"instant":"smooth";if(De.current){try{De.current(_,R)}catch(N){console.warn("[LiveLayer] onScrollPage threw.",N)}return}if(typeof window>"u")return;const D={behavior:R},M=fr(),H=N=>{M instanceof Window?M.scrollBy({top:N,...D}):M.scrollBy({top:N,...D})},q=N=>{M instanceof Window?M.scrollTo({top:N,...D}):M.scrollTo({top:N,...D})};_==="up"?H(-Ot(M)):_==="down"?H(Ot(M)):q(_==="top"?0:pr(M));return}if(f.type==="click"){if(!ce("click")){ue("click","click");return}const _=typeof f.selector=="string"?f.selector:null;if(!_){console.warn("[LiveLayer] click: missing selector.");return}if(st.current){try{st.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}(Ce=R.click)==null||Ce.call(R);return}if(f.type==="fill_form"||f.type==="focus_field"){if(!ce("fill_forms")){ue(f.type,"fill_forms");return}if(typeof document>"u")return;const _=typeof f.formId=="string"?f.formId:null;if(!_){console.warn(`[LiveLayer] ${f.type}: missing formId.`);return}const R=document.querySelector(`[data-ll-form="${_.replace(/"/g,'\\"')}"]`);if(!R){console.warn(`[LiveLayer] ${f.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] ${f.type}: refusing to touch a form in a private subtree.`);return}if(f.type==="focus_field"){const M=typeof f.fieldName=="string"?f.fieldName:null;if(!M){console.warn("[LiveLayer] focus_field: missing fieldName.");return}const H=R.querySelector(`[data-ll-field="${M.replace(/"/g,'\\"')}"]`);if(!H){console.warn(`[LiveLayer] focus_field: no field "${M}" in form "${_}".`);return}if(!rt(H)){console.warn(`[LiveLayer] focus_field: field "${M}" is privacy-protected and not focusable.`);return}H.focus();return}const D=f.values&&typeof f.values=="object"?f.values:null;if(!D){console.warn("[LiveLayer] fill_form: missing or invalid values.");return}for(const[M,H]of Object.entries(D)){if(typeof H!="string")continue;const q=R.querySelector(`[data-ll-field="${M.replace(/"/g,'\\"')}"]`);if(!q){console.warn(`[LiveLayer] fill_form: no field "${M}" in form "${_}". Skipping.`);continue}if(!rt(q)){console.warn(`[LiveLayer] fill_form: field "${M}" is privacy-protected (password / cc-* / private). Skipping.`);continue}try{lr(q,H)}catch(N){console.warn(`[LiveLayer] fill_form: failed to set "${M}".`,N)}}return}if(f.type==="submit_form"){if(!ce("submit_forms")){ue("submit_form","submit_forms");return}if(typeof document>"u")return;const _=typeof f.formId=="string"?f.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 f.requestId=="string"?f.requestId:void 0,M=(Xe=re.current)==null?void 0:Xe.call(re),H=U=>{const K=M,Le=K==null?void 0:K.localParticipant;if(Le!=null&&Le.publishData)try{const wn=D?{...U,requestId:D}:U,_n=new TextEncoder().encode(JSON.stringify(wn));Le.publishData(_n,{reliable:!0})}catch{}};let q=!1;const N=()=>{q=!0,H({type:"form_submitted",formId:_})};R.addEventListener("submit",N,{once:!0});try{typeof R.requestSubmit=="function"?R.requestSubmit():R.submit()}catch(U){console.warn("[LiveLayer] submit_form: requestSubmit threw.",U),R.removeEventListener("submit",N),H({type:"form_submit_blocked",formId:_,reason:"exception"});return}setTimeout(()=>{q||(R.removeEventListener("submit",N),H({type:"form_submit_blocked",formId:_,reason:"validation"}))},500);return}if(f.type==="request_routes"){if(!ce("read_page")){ue("request_routes","read_page");return}const _=typeof f.requestId=="string"?f.requestId:void 0,D=(Ct=re.current)==null?void 0:Ct.call(re),M=D==null?void 0:D.localParticipant;if(!(M!=null&&M.publishData))return;const H=N=>{try{const U=_?{type:"routes",routes:N,requestId:_}:{type:"routes",routes:N},K=new TextEncoder().encode(JSON.stringify(U));M.publishData(K,{reliable:!0})}catch(U){console.warn("[LiveLayer] request_routes: publishData failed.",U)}},q=ht.current;if(q){try{const N=q(),U=K=>{if(!Array.isArray(K)){H([]);return}H(K.map(an).slice(0,200))};N instanceof Promise?N.then(U).catch(K=>{console.warn("[LiveLayer] getRoutes rejected; falling back to DOM walker.",K),H(et())}):U(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}hr.has(f.type)||we==null||we(f)}},[we,ve]),O=Wt({agentId:B?"__controlled__":ke,baseUrl:i,apiKey:o,sessionEndpoint:s,sessionBody:a,onDataMessage:B?void 0:$e});r.useEffect(()=>{if(B!=null&&B.subscribeToDataMessages)return B.subscribeToDataMessages($e)},[B,$e]),re.current=()=>{var g;return(g=O.getRoom)==null?void 0:g.call(O)},r.useEffect(()=>{var F;if(!ie)return;const g=(F=O.getRoom)==null?void 0:F.call(O),f=g==null?void 0:g.localParticipant;if(f!=null&&f.publishData)try{const Ce=new TextEncoder().encode(JSON.stringify({type:"pathname",pathname:ie}));f.publishData(Ce,{reliable:!0})}catch{}},[ie,O,O.connectionState]),r.useEffect(()=>{var F;if(typeof window>"u")return;const g=((F=window.location)==null?void 0:F.hostname)||"";if(g==="localhost"||g==="127.0.0.1"||g==="0.0.0.0"||g.endsWith(".local")||g.endsWith(".test"))return window.__livelayerSimulateCommand=Ce=>{try{$e(Ce)}catch(Xe){console.warn("[LiveLayer] simulate-command threw:",Xe)}},()=>{delete window.__livelayerSimulateCommand}},[$e]);const w=r.useMemo(()=>B?{connectionState:B.connectionState,agentState:B.agentState,transcript:B.transcript,videoElement:B.videoElement,audioElement:B.audioElement,canResume:B.canResume,error:B.error,agentConfig:null,connect:async()=>{await B.onConnect()},disconnect:()=>B.onDisconnect(),getRoom:O.getRoom,isControlled:!0}:{connectionState:O.connectionState,agentState:O.agentState,transcript:O.transcript,videoElement:O.videoElement,audioElement:O.audioElement,canResume:O.canResume,error:O.error,agentConfig:O.agentConfig,connect:O.connect,disconnect:O.disconnect,getRoom:O.getRoom,isControlled:!1},[B,O]),mt=r.useRef(null);r.useEffect(()=>{const g=w.videoElement,f=mt.current;if(!(!g||!f))return f.appendChild(g),()=>{g.parentNode===f&&f.removeChild(g)}},[w.videoElement]),r.useEffect(()=>{const g=w.audioElement;if(!g)return;Ae.attach(g);const f=g.play();return f&&typeof f.catch=="function"&&f.catch(F=>{(F==null?void 0:F.name)==="NotAllowedError"&&ae(!0)}),()=>{Ae.detach()}},[w.audioElement]),r.useEffect(()=>{if(w.isControlled||w.connectionState!=="connected")return;const g=w.getRoom();if(g)return Z.setupMic(g).catch(()=>{}),te.attachRoom(g),ne.attachRoom(g),se.refresh(),()=>{Z.teardownMic(),te.teardown(),ne.teardown()}},[w.isControlled,w.connectionState]),r.useEffect(()=>{const g=w.audioElement;g&&(g.muted=Pe)},[w.audioElement,Pe]);const un=r.useCallback(g=>{const f=w.getRoom();if(f)try{const F=new TextEncoder().encode(JSON.stringify({type:"user_message",text:g}));f.localParticipant.publishData(F,{reliable:!0})}catch{}},[w]),dn=r.useCallback(()=>{Je(g=>!g)},[]);r.useEffect(()=>{xe==null||xe(w.connectionState),w.connectionState==="connected"?fe==null||fe():w.connectionState==="disconnected"&&(ge==null||ge())},[w.connectionState,fe,ge,xe]),r.useEffect(()=>{ye==null||ye(w.transcript)},[w.transcript,ye]),r.useEffect(()=>{be==null||be(w.agentState)},[w.agentState,be]);const gt=r.useRef(!1);r.useEffect(()=>{w.isControlled||!u||gt.current||Ne&&w.connectionState==="idle"&&(gt.current=!0,w.connect())},[u,w.connectionState,w,Ne]);const fn=r.useCallback(g=>{const f=S==null?void 0:S.find(F=>F.id===g);f&&(Te(!1),g!==V&&(Me(!0),w.disconnect(),G||_e(g),x==null||x(f)))},[S,V,w,G,x]);r.useEffect(()=>{le&&w.connectionState==="connected"&&Me(!1)},[w.connectionState,le]),r.useEffect(()=>{if(!Ie)return;const g=f=>{f.key==="Escape"&&Te(!1)};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[Ie]);const pn=!!E||!!(J!=null&&J.avatarImageUrl)||w.isControlled,ze=Jt(ke,i,pn);X===void 0&&((bt=ze.info)!=null&&bt.capabilities)&&(at.current=ze.info.capabilities);const Ke=(J==null?void 0:J.name)??T??((xt=w.agentConfig)==null?void 0:xt.name)??((vt=ze.info)==null?void 0:vt.name)??"Live Layer",lt=(J==null?void 0:J.avatarImageUrl)??E??((wt=w.agentConfig)==null?void 0:wt.avatarImageUrl)??((_t=ze.info)==null?void 0:_t.avatarImageUrl)??null,hn=v??((kt=w.agentConfig)==null?void 0:kt.idleLoopUrl)??((St=ze.info)==null?void 0:St.idleLoopUrl)??null,mn=I??null,gn=r.useCallback(()=>oe("expanded"),[oe]),yn=r.useCallback(()=>oe("minimized"),[oe]),yt=r.useCallback(()=>{w.disconnect(),oe("hidden")},[w,oe]),bn=r.useCallback(()=>{const g=w.audioElement;g&&g.play().then(()=>ae(!1)).catch(()=>{})},[w.audioElement]),xn=r.useCallback(()=>{ae(!1),w.connect()},[w]),He={...Ve,zIndex:Ye};m.primaryColor&&(He["--ll-color-primary"]=m.primaryColor),m.accentColor&&(He["--ll-color-accent"]=m.accentColor),m.backgroundColor&&(He["--ll-color-bg"]=m.backgroundColor),m.textColor&&(He["--ll-color-fg"]=m.textColor);const vn=["ll-widget",`ll-widget--${ee}`,`ll-widget--${he?"mobile":"desktop"}`,ot].filter(Boolean).join(" ");return Ne?t.jsxs("div",{className:vn,style:He,"data-display-mode":ee,"data-position":y,children:[ee==="hidden"&&t.jsx(On,{position:y,isMobile:he,isSpeaking:w.agentState==="speaking",onExpand:()=>oe("expanded"),label:`Open ${Ke} widget`,avatarImageUrl:lt,agentName:Ke}),ee==="minimized"&&t.jsx(Bn,{position:y,isMobile:he,agentName:Ke,avatarImageUrl:lt,agentState:w.agentState,isMuted:Z.isMuted,audioLevel:Ae,onExpand:gn,onToggleMute:Z.toggleMute,onClose:yt}),ee==="expanded"&&t.jsx(Fn,{position:y,isMobile:he,agentName:Ke,avatarImageUrl:lt,idleLoopUrl:hn,greeting:mn,branding:m,teamMembers:S,currentTeamMemberId:V,isSwitchingTeamMember:le,teamSwitcherOpen:Ie,onToggleTeamSwitcher:()=>Te(g=>!g),onSelectTeamMember:fn,connectionState:w.connectionState,agentState:w.agentState,transcript:w.transcript,isMuted:Z.isMuted,micDevices:se.mics,isCameraEnabled:te.isEnabled,cameraPreviewEl:te.previewEl,cameraDevices:se.cameras,activeCameraId:te.activeDeviceId,isScreenShareEnabled:ne.isEnabled,screenPreviewEl:ne.previewEl,isSpeakerMuted:Pe,allowCamera:C,allowScreenShare:$,allowTyping:A,languageMenuOpen:Ge,onToggleLanguageMenu:()=>it(g=>!g),needsUserGesture:Se,canResume:w.canResume,micError:Z.micError,error:w.error,avatarVideoContainerRef:mt,agentVideoEl:w.videoElement,onConnect:()=>void w.connect(),onDisconnect:()=>w.disconnect(),onRetry:xn,onResumeAudio:bn,onToggleMute:Z.toggleMute,onToggleCamera:()=>void te.toggle(),onSwitchCameraDevice:g=>void te.switchDevice(g),onToggleScreenShare:()=>void ne.toggle(),onToggleSpeaker:dn,onSendMessage:un,onMinimize:yn,onClose:yt,onClearMicError:Z.clearError})]}):null}function gr(e){return t.jsx(Bt,{children:t.jsx(mr,{...e})})}const yr=({agentId:e,baseUrl:n,apiKey:o,mode:i,onAgentEvent:s,className:a,style:u})=>{const d=r.useRef(null),p=r.useRef(null),b=r.useRef(s);b.current=s;const y=r.useCallback(l=>{var j;const c=l.detail;(j=b.current)==null||j.call(b,c)},[]);return r.useEffect(()=>{const l=d.current;if(!l)return;const c=document.createElement("livelayer-widget");return c.setAttribute("agent-id",e),n&&c.setAttribute("base-url",n),o&&c.setAttribute("api-key",o),i&&c.setAttribute("mode",i),c.addEventListener("agent-event",y),l.appendChild(c),p.current=c,()=>{c.removeEventListener("agent-event",y),l.removeChild(c),p.current=null}},[e]),r.useEffect(()=>{p.current&&(i?p.current.setAttribute("mode",i):p.current.removeAttribute("mode"))},[i]),t.jsx("div",{ref:d,className:a,style:u})},br=r.forwardRef(function({id:n,intent:o,as:i="div",className:s,style:a,children:u},d){return r.createElement(i,{ref:d,"data-ll-region":n,"data-ll-intent":o,className:s,style:a},u)}),xr=r.forwardRef(function({id:n,intent:o,children:i,...s},a){return t.jsx("form",{ref:a,"data-ll-form":n,"data-ll-intent":o,...s,children:i})}),vr=r.forwardRef(function(n,o){const{name:i,label:s,labelClassName:a}=n,u={name:i,"data-ll-field":i};let d;if("as"in n&&n.as==="textarea"){const{name:p,label:b,labelClassName:y,as:l,...c}=n;d=t.jsx("textarea",{ref:o,...u,...c})}else if("as"in n&&n.as==="select"){const{name:p,label:b,labelClassName:y,as:l,children:c,...j}=n;d=t.jsx("select",{ref:o,...u,...j,children:c})}else{const{name:p,label:b,labelClassName:y,as:l,...c}=n;d=t.jsx("input",{ref:o,...u,...c})}return s===void 0?d:t.jsxs("label",{className:a,children:[s,d]})});let qt=1;function wr({onMount:e,defaultOpen:n=!1,storageKey:o="ll-debug-open"}){const[i,s]=r.useState(n),[a,u]=r.useState([]),[d,p]=r.useState(""),[b,y]=r.useState(!1),l=r.useRef(new Set),c=r.useRef([]),j=r.useRef(b);j.current=b,r.useEffect(()=>{try{const x=localStorage.getItem(o);x==="1"&&s(!0),x==="0"&&s(!1)}catch{}},[o]),r.useEffect(()=>{try{localStorage.setItem(o,i?"1":"0")}catch{}},[i,o]),r.useEffect(()=>{const x=v=>{(v.metaKey||v.ctrlKey)&&v.shiftKey&&v.key.toLowerCase()==="l"&&(v.preventDefault(),s(I=>!I))};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(I=>[...v.reverse(),...I].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:qt++,ts:Date.now(),kind:"event",type:x.eventName,data:x.data})}))},[e]),r.useEffect(()=>{const x=console.warn,v=console.log,I=(E,T)=>function(...m){try{const C=typeof m[0]=="string"?m[0]:"";C.startsWith("[LiveLayer]")&&c.current.push({id:qt++,ts:Date.now(),kind:E,type:C.slice(0,120),data:{args:m.slice(1).map($=>kr($))}})}catch{}return T.apply(this,m)};return console.warn=I("warn",x),console.log=I("log",v),()=>{console.warn=x,console.log=v}},[]),!i)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=a.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:[a.length," event",a.length===1?"":"s"]}),t.jsx("span",{style:{flex:1}}),t.jsx("button",{type:"button",onClick:()=>y(x=>!x),style:ct(b?"#f59e0b":"transparent"),title:"Pause / resume capture",children:b?"▶ resume":"⏸ pause"}),t.jsx("button",{type:"button",onClick:()=>{u([]),c.current=[]},style:ct("transparent"),title:"Clear buffer",children:"clear"}),t.jsx("button",{type:"button",onClick:()=>s(!1),style:ct("transparent"),"aria-label":"Close",title:"Close (Cmd/Ctrl + Shift + L)",children:"✕"})]}),t.jsx("input",{type:"text",value:d,onChange:x=>p(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"),r=require("react"),kn=require("@livelayer/sdk"),nt=require("livekit-client");class Bt 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 Wt(e){const[n,i]=r.useState("idle"),[o,s]=r.useState("idle"),[l,u]=r.useState([]),[d,p]=r.useState(null),[x,y]=r.useState(null),[a,c]=r.useState(null),[j,S]=r.useState(!1),[k,b]=r.useState(null),v=r.useRef(null),I=r.useRef(e.onDataMessage);I.current=e.onDataMessage,r.useEffect(()=>{const C={onConnectionStateChange:A=>{i(A),A==="connected"&&b(null)},onAgentStateChange:s,onTranscript:A=>u([...A]),onAgentConfig:p,onAudioTrack:A=>c(A),onVideoTrack:A=>y(A),onVideoTrackRemoved:()=>y(null),onError:A=>b(A),onDataMessage:A=>{var L;(L=I.current)==null||L.call(I,A)},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([]),p(null),y(null),c(null),S(!1),b(null),()=>{var A;(A=$.destroy)==null||A.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 b($ instanceof Error?$.message:String($)),$}},[]),T=r.useCallback(()=>{const C=v.current;C&&C.disconnect()},[]),m=r.useCallback(()=>{var C;return((C=v.current)==null?void 0:C.getRoom())??null},[]);return{connectionState:n,agentState:o,transcript:l,agentConfig:d,videoElement:x,audioElement:a,canResume:j,error:k,connect:E,disconnect:T,getRoom:m,session:v.current}}function Ft(){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(b){console.error("[useAudioLevel] subscriber threw:",b)}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},[]),p=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]),x=r.useCallback(()=>{if(o.current!==null&&(cancelAnimationFrame(o.current),o.current=null),i.current){try{i.current.disconnect()}catch{}i.current=null}},[]),y=r.useCallback(a=>(s.current.add(a),()=>{s.current.delete(a)}),[]);return r.useEffect(()=>()=>{if(x(),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},[x]),{attach:p,detach:x,subscribe:y}}function Ut(){const[e,n]=r.useState(!1),[i,o]=r.useState(null),s=r.useRef(null),l=r.useRef(null),u=r.useCallback(async y=>{if(s.current&&l.current){try{await l.current.localParticipant.unpublishTrack(s.current)}catch{}s.current.stop(),s.current=null}l.current=y,o(null);try{const a=await nt.createLocalAudioTrack({echoCancellation:!0,noiseSuppression:!0});await y.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 y=s.current;y&&(y.isMuted?(y.unmute(),n(!1)):(y.mute(),n(!0)))},[]),p=r.useCallback(()=>{const y=s.current,a=l.current;if(y&&a){try{a.localParticipant.unpublishTrack(y)}catch{}y.stop()}s.current=null,l.current=null,n(!1)},[]),x=r.useCallback(()=>o(null),[]);return{isMuted:e,micError:i,toggleMute:d,setupMic:u,teardownMic:p,clearError:x}}const Sn={resolution:{width:640,height:480,frameRate:24}};function Vt(){const[e,n]=r.useState(!1),[i,o]=r.useState(null),[s,l]=r.useState(null),[u,d]=r.useState(""),p=r.useRef(null),x=r.useRef(null),y=r.useCallback(v=>{p.current=v},[]),a=r.useCallback(()=>{const v=p.current,I=x.current;if(I&&v){const E=v.localParticipant.getTrackPublication(nt.Track.Source.Camera);if(E!=null&&E.track){try{v.localParticipant.unpublishTrack(E.track)}catch{}E.track.stop()}else I.stop()}x.current=null,l(null),n(!1)},[]),c=r.useCallback(async v=>{const I=p.current;if(I){o(null);try{const E={...Sn};v&&(E.deviceId=v);const T=await nt.createLocalVideoTrack(E);await I.localParticipant.publishTrack(T),x.current=T;const m=T.attach();l(m),n(!0),v&&d(v);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)}}},[]),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(),p.current=null,o(null),d("")},[a]),b=r.useCallback(()=>o(null),[]);return r.useEffect(()=>()=>{x.current&&x.current.stop()},[]),{isEnabled:e,error:i,previewEl:s,activeDeviceId:u,toggle:j,switchDevice:S,attachRoom:y,teardown:k,clearError:b}}function Yt(){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},[]),p=r.useCallback(()=>l(null),[]),x=r.useCallback(async()=>{const c=u.current;if(c){if(e){try{await c.localParticipant.setScreenShareEnabled(!1)}catch{}p(),n(!1);return}o(null);try{await c.localParticipant.setScreenShareEnabled(!0);let j=0;const S=()=>{const k=c.localParticipant.getTrackPublication(nt.Track.Source.ScreenShare);if(k!=null&&k.track){const b=k.track.attach();l(b),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,p]),y=r.useCallback(()=>{const c=u.current;if(c&&e)try{c.localParticipant.setScreenShareEnabled(!1)}catch{}p(),n(!1),o(null),u.current=null},[e,p]),a=r.useCallback(()=>o(null),[]);return{isEnabled:e,error:i,previewEl:s,toggle:x,attachRoom:d,teardown:y,clearError:a}}function Gt(){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 Jt(e,n,i=!1){const[o,s]=r.useState(null),[l,u]=r.useState(null),[d,p]=r.useState(!i&&!!e);return r.useEffect(()=>{if(i||!e){p(!1);return}const x=new AbortController,y=n||"https://app.livelayer.studio";return p(!0),u(null),fetch(`${y}/api/widget/agent/${encodeURIComponent(e)}`,{signal:x.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=>{x.signal.aborted||(s(a),p(!1))}).catch(a=>{x.signal.aborted||(u(a instanceof Error?a.message:"Agent lookup failed"),p(!1))}),()=>x.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 Kt({value:e,defaultValue:n="expanded",onChange:i}={}){const o=e!==void 0,[s,l]=r.useState(n),u=o?e:s,d=r.useCallback(p=>{p!==u&&(o||l(p),i==null||i(p))},[u,o,i]);return[u,d]}const jn=["hidden","minimized","expanded"];function En(e){return e&&jn.includes(e)?e:null}function Xt({value:e,defaultValue:n="expanded",onChange:i,persistKey:o="ll-widget",disablePersistence:s=!1}={}){const l=`${o}:display-mode`,u=r.useRef(!1),[d,p]=Kt({value:e,defaultValue:n,onChange:x=>{e===void 0&&!s&&Ln(l,x),i==null||i(x)}});return r.useEffect(()=>{if(u.current||(u.current=!0,s||e!==void 0))return;const x=En(Cn(l));x&&x!==d&&p(x)},[]),[d,p]}const Rn=640;function Qt(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 Lt="__llHistoryPatched",rt="ll:pathname";function Nn(){if(typeof window>"u"||window.history[Lt])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(rt)),o},window.history.replaceState=function(...i){const o=n.apply(this,i);return window.dispatchEvent(new Event(rt)),o},window.history[Lt]=!0}function jt(){return typeof window>"u"?"/":window.location.pathname||"/"}function Zt(e){const[n,i]=r.useState(()=>e??jt());return r.useEffect(()=>{if(e!==void 0)return;Nn();const o=()=>i(jt());return o(),window.addEventListener("popstate",o),window.addEventListener(rt,o),()=>{window.removeEventListener("popstate",o),window.removeEventListener(rt,o)}},[e]),e??n}const Et=new Map,An=/[\\^$+?.()|{}[\]]/g;function Mn(e){return e.replace(An,"\\$&")}function In(e){const n=Et.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"),"[^/]+"),p=new RegExp(`^${d}\\/?$`);return Et.set(e,p),p}function Tn(e,n){const i=n.length>1&&n.endsWith("/")?n.slice(0,-1):n;return In(e).test(i)}function en(e,n){return typeof e=="function"?e(n):e instanceof RegExp?e.test(n):Tn(e,n)}function Rt(e,n){if(!e||e.length===0)return!1;for(const i of e)if(en(i,n))return!0;return!1}function tn(e,n,i){return e===void 0?!0:Rt(i,e)?!1:n&&n.length>0?Rt(n,e):!0}function nn(e,n,i){return r.useMemo(()=>tn(e,n,i),[e,n,i])}const Nt=({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"})}),At=({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},Mt=({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 rn="ll-hidden-tab-center-y",zn=5,It=16;function Hn(){if(typeof window>"u")return null;try{const e=window.localStorage.getItem(rn);if(!e)return null;const n=Number.parseFloat(e);return Number.isFinite(n)?n:null}catch{return null}}function Tt(e){if(!(typeof window>"u"))try{window.localStorage.setItem(rn,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),p=d==="right"?"left":"right",x=n?80:72,y=!!l,[a,c]=r.useState(null),[j,S]=r.useState(!1),k=r.useRef(null),b=r.useRef(!1),v=r.useCallback(L=>{if(typeof window>"u")return L;const P=x/2,z=It+P,F=window.innerHeight-It-P;return F<z?Math.max(z,L):Math.max(z,Math.min(F,L))},[x]);r.useEffect(()=>{const L=Hn();c(v(L??window.innerHeight/2));const P=()=>{c(z=>z===null?null:v(z))};return window.addEventListener("resize",P),()=>window.removeEventListener("resize",P)},[v]);const I=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 P=k.current;if(!P)return;const z=L.clientY-P.startClientY;!P.moved&&Math.abs(z)>zn&&(P.moved=!0,S(!0)),P.moved&&c(v(P.startCenterY+z))},[v]),T=r.useCallback(L=>{const P=k.current;if(P){try{L.currentTarget.releasePointerCapture(L.pointerId)}catch{}k.current=null,P.moved&&(S(!1),b.current=!0,c(z=>(z!==null&&Tt(z),z)))}},[]),m=r.useCallback(()=>{if(b.current){b.current=!1;return}o()},[o]),C=r.useCallback(L=>{if(L.key==="ArrowUp"||L.key==="ArrowDown"){L.preventDefault();const P=L.key==="ArrowUp"?-8:8;c(z=>{if(z===null)return z;const F=v(z+P);return Tt(F),F})}},[v]),$=["ll-hidden",`ll-hidden--${d}`,n?"ll-hidden--mobile":"ll-hidden--desktop",i?"ll-hidden--speaking":null,j?"is-dragging":null,y?"ll-hidden--with-avatar":null].filter(Boolean).join(" "),A=a===null?void 0:{top:`${a-x/2}px`,transform:"none"};return t.jsx("button",{type:"button",className:$,onPointerDown:I,onPointerMove:E,onPointerUp:T,onPointerCancel:T,onClick:m,onKeyDown:C,"aria-label":s,"data-position":e,style:A,children:y?t.jsxs(t.Fragment,{children:[t.jsx(Mt,{direction:p,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(Mt,{direction:p,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([]),p=r.useMemo(()=>{const y=(Math.sqrt(5)-1)/2;return Array.from({length:n},(a,c)=>.5+c*y%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*p[c]);j.style.height=`${S}px`}}),[e,n,i,o,p]);const x=["ll-waveform",s].filter(Boolean).join(" ");return t.jsx("div",{ref:u,className:x,"aria-hidden":"true",children:Array.from({length:n},(y,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:p,onClose:x})=>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:y=>{y.stopPropagation(),p()},onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&(y.stopPropagation(),y.preventDefault(),p())},"aria-label":l?"Unmute microphone":"Mute microphone",children:t.jsx(Nt,{muted:l,className:"ll-minimized__icon"})}),t.jsx(At,{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:p,"aria-label":l?"Unmute microphone":"Mute microphone",children:t.jsx(Nt,{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(At,{className:"ll-minimized__icon"})}),t.jsx("button",{type:"button",className:"ll-minimized__btn ll-minimized__btn--close",onClick:x,"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 p={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:p,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:p,isSwitchingTeamMember:x,teamSwitcherOpen:y,onToggleTeamSwitcher:a,onSelectTeamMember:c,languageMenuOpen:j,onToggleLanguageMenu:S,connectionState:k,agentState:b,transcript:v,canResume:I,needsUserGesture:E,error:T,isMuted:m,micError:C,micDevices:$,isCameraEnabled:A,cameraPreviewEl:L,cameraDevices:P,activeCameraId:z,isScreenShareEnabled:F,screenPreviewEl:X,isSpeakerMuted:de,allowCamera:We,allowScreenShare:Fe,allowTyping:Ue,avatarVideoContainerRef:Ve,agentVideoEl:J,onConnect:fe,onDisconnect:ye,onRetry:xe,onResumeAudio:be,onToggleMute:ve,onToggleCamera:we,onSwitchCameraDevice:_e,onToggleScreenShare:B,onToggleSpeaker:ot,onSendMessage:Ye,onMinimize:Ge,onClose:oe,onClearMicError:Pe})=>{var Re;const ie=((d==null?void 0:d.length)??0)>1,ke=k==="connecting"||k==="connected",Z=k==="connected",pe=k==="idle"||k==="disconnected"||k==="error",[U,he]=r.useState(!1);r.useEffect(()=>{if(!J){he(!1);return}if(!J.paused&&J.readyState>=2){he(!0);return}he(!1);const h=()=>he(!0);return J.addEventListener("playing",h),J.addEventListener("loadeddata",h),()=>{J.removeEventListener("playing",h),J.removeEventListener("loadeddata",h)}},[J]);const[me,ee]=r.useState(!1);r.useEffect(()=>{if(!Z){ee(!1);return}if(U)return;const h=setTimeout(()=>ee(!0),8e3);return()=>clearTimeout(h)},[Z,U]);const Se=k==="connecting"||Z&&!!o&&!U&&!me,Ce=r.useRef(null),Q=r.useRef(null);r.useEffect(()=>{const h=Ce.current;h&&(h.innerHTML="",L&&(L.style.width="100%",L.style.height="100%",L.style.objectFit="cover",L.style.transform="scaleX(-1)",h.appendChild(L)))},[L]),r.useEffect(()=>{const h=Q.current;h&&(h.innerHTML="",X&&(X.style.width="100%",X.style.height="100%",X.style.objectFit="contain",h.appendChild(X)))},[X]);const[K,te]=r.useState(!1),[se,Le]=r.useState(!1);r.useEffect(()=>{if(!K&&!se&&!j&&!y)return;const h=()=>{te(!1),Le(!1),j&&S(),y&&a()};return document.addEventListener("click",h),()=>document.removeEventListener("click",h)},[K,se,j,y,S,a]);const[le,je]=r.useState(""),Je=r.useCallback(h=>{h.preventDefault();const W=le.trim();W&&(Ye(W),je(""))},[le,Ye]),De=u.productName||"Live Layer";let ne=null,ae=null;for(let h=v.length-1;h>=0;h--){const W=v[h];if(!ne&&W.role==="agent"?ne=W:!ae&&W.role==="user"&&(ae=W),ne&&ae)break}const Ke=Z?(ne==null?void 0:ne.text)||null:l||null,Ee=Z&&(ae==null?void 0:ae.text)||null,st=["ll-expanded",n?"ll-expanded--mobile":"ll-expanded--desktop"].join(" ");return t.jsxs("div",{className:st,"data-position":e,"data-state":Z?"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:((Re=i==null?void 0:i.charAt(0))==null?void 0:Re.toUpperCase())||"A"})}),s&&!Z&&t.jsx("video",{className:"ll-expanded__bg-idle",src:s,autoPlay:!0,loop:!0,muted:!0,playsInline:!0})]}),t.jsx("div",{ref:Ve,className:"ll-expanded__video"}),Se&&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:x?"Switching...":"Connecting..."})]}),E&&Z&&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:h=>{ie&&(h.stopPropagation(),a())},"aria-haspopup":ie?"listbox":void 0,"aria-expanded":ie?y:void 0,children:[t.jsx("span",{className:"ll-hpill__label",children:i}),ie&&t.jsx(Ze,{})]}),ie&&y&&t.jsx("div",{className:"ll-hmenu",onClick:h=>h.stopPropagation(),role:"listbox",children:d==null?void 0:d.map(h=>t.jsxs("button",{type:"button",className:`ll-hmenu__item ${h.id===p?"is-active":""}`,onClick:()=>c(h.id),role:"option","aria-selected":h.id===p,children:[h.avatarImageUrl&&t.jsx("img",{src:h.avatarImageUrl,alt:"",className:"ll-hmenu__avatar"}),t.jsx("span",{className:"ll-hmenu__name",children:h.name}),h.role&&t.jsx("span",{className:"ll-hmenu__role",children:h.role})]},h.id))})]}),t.jsxs("div",{className:"ll-expanded__pill-wrap",children:[t.jsxs("button",{type:"button",className:"ll-hpill ll-hpill--compact",onClick:h=>{h.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(Ze,{})]}),j&&t.jsx("div",{className:"ll-hmenu",onClick:h=>h.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--${b}`,children:b})]}),t.jsxs("div",{className:"ll-expanded__header-actions",children:[t.jsx("button",{type:"button",className:"ll-hbtn",onClick:Ge,"aria-label":"Minimize widget",title:"Minimize",children:t.jsx(Dt,{})}),t.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--danger",onClick:oe,"aria-label":"End call",title:"End call",children:t.jsx(Pt,{})})]})]}):t.jsxs("div",{className:"ll-expanded__header ll-expanded__header--idle",children:[t.jsx("span",{className:"ll-expanded__brand",children:De}),t.jsxs("div",{className:"ll-expanded__header-actions",children:[t.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--ghost",onClick:Ge,"aria-label":"Minimize widget",children:t.jsx(Dt,{})}),t.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--danger",onClick:oe,"aria-label":"Close widget",children:t.jsx(Pt,{})})]})]}),pe&&(()=>{const h=I?"Restart paused session":k==="disconnected"?"Reconnect to agent":"Start video call",W=I?"Pick up where you left off":null,$e=k==="idle"&&!I&&!T;return t.jsxs(t.Fragment,{children:[$e&&t.jsxs("button",{type:"button",className:"ll-expanded__play",onClick:fe,"aria-label":h,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:h})]}),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})}),W&&t.jsx("p",{className:"ll-expanded__cta-sublabel",children:W}),t.jsx("button",{type:"button",className:"ll-expanded__cta",onClick:fe,"aria-label":h,children:h})]})]})})(),t.jsxs("div",{className:`ll-expanded__pip ${ke&&(A||F)?"is-visible":""}`,children:[t.jsx("div",{ref:Q,className:F?"ll-expanded__pip-host":"ll-expanded__pip-host is-hidden"}),t.jsx("div",{ref:Ce,className:!F&&A?"ll-expanded__pip-host":"ll-expanded__pip-host is-hidden"})]}),ke?t.jsxs("div",{className:"ll-expanded__bottom",children:[Ke&&t.jsx("div",{className:"ll-expanded__transcript ll-expanded__transcript--agent","data-role":"agent",children:t.jsx("p",{className:"ll-expanded__transcript-text",children:Ke})}),Ee&&t.jsx("div",{className:"ll-expanded__transcript ll-expanded__transcript--user","data-role":"user",children:t.jsx("p",{className:"ll-expanded__transcript-text",children:Ee})}),t.jsxs("div",{className:"ll-toolbar",onClick:h=>h.stopPropagation(),children:[Fe&&t.jsx("button",{type:"button",className:`ll-tool ${F?"is-on":""}`,onClick:B,"aria-label":F?"Stop sharing screen":"Share screen",title:F?"Stop sharing":"Share screen",children:t.jsx(Un,{})}),We&&t.jsxs("div",{className:"ll-tool-split",children:[t.jsx("button",{type:"button",className:`ll-tool ll-tool--left ${A?"is-on":""}`,onClick:we,"aria-label":A?"Turn off camera":"Turn on camera",title:A?"Stop camera":"Start camera",children:t.jsx(Vn,{})}),t.jsx("button",{type:"button",className:`ll-tool ll-tool--right ${A?"is-on":""}`,onClick:h=>{h.stopPropagation(),Le(W=>!W),te(!1)},"aria-label":"Camera devices","aria-haspopup":"listbox","aria-expanded":se,children:t.jsx(Ze,{})}),se&&P.length>0&&t.jsx($t,{label:"Camera",devices:P,activeId:z,onPick:h=>{Le(!1),_e(h)}})]}),t.jsxs("div",{className:"ll-tool-split",children:[t.jsx("button",{type:"button",className:`ll-tool ll-tool--left ${m?"is-muted":""}`,onClick:ve,"aria-label":m?"Unmute microphone":"Mute microphone",title:m?"Unmute":"Mute",children:t.jsx(Yn,{muted:m})}),t.jsx("button",{type:"button",className:`ll-tool ll-tool--right ${m?"is-muted":""}`,onClick:h=>{h.stopPropagation(),te(W=>!W),Le(!1)},"aria-label":"Microphone devices","aria-haspopup":"listbox","aria-expanded":K,children:t.jsx(Ze,{})}),K&&$.length>0&&t.jsx($t,{label:"Microphone",devices:$,activeId:"",onPick:()=>te(!1)})]}),t.jsx("button",{type:"button",className:`ll-tool ${de?"is-muted":""}`,onClick:ot,"aria-label":de?"Unmute speaker":"Mute speaker",title:de?"Unmute speaker":"Mute speaker",children:t.jsx(Gn,{muted:de})}),t.jsx("button",{type:"button",className:"ll-tool ll-tool--danger",onClick:ye,"aria-label":"End conversation",title:"End conversation",children:t.jsx(Kn,{})})]}),Ue&&t.jsxs("form",{className:"ll-message-input",onSubmit:Je,children:[t.jsx("input",{type:"text",className:"ll-message-input__field",placeholder:"Message...",value:le,onChange:h=>je(h.target.value),"aria-label":"Message the agent"}),le.trim()&&t.jsx("button",{type:"submit",className:"ll-message-input__send","aria-label":"Send message",children:t.jsx(Jn,{})})]})]}):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:Pe,"aria-label":"Dismiss",children:"×"})]});if(!T||k!=="error")return null;let h="Failed to connect",W="Try again";return T==="MIC_PERMISSION_DENIED"?h="Microphone blocked. Allow access to talk.":T==="MIC_NOT_FOUND"?h="No microphone found. Plug one in + retry.":T==="MIC_UNAVAILABLE"?h="Mic unavailable. Check other apps using it.":T==="AGENT_TIMEOUT"?h="Agent didn't pick up. Try again.":T==="CONNECT_FAILED"?h="Connection failed. Check your network.":T.length<80&&(h=T),t.jsxs("div",{className:"ll-expanded__banner ll-expanded__banner--error",role:"alert",children:[t.jsx("span",{children:h}),t.jsx("button",{type:"button",className:"ll-expanded__banner-retry",onClick:xe,children:W})]})})()]})};function Ze(){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 Pt(){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 Dt(){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 Gn({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 Jn(){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 Kn(){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 $t=({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)})]}),Xn=['[data-ll-private="true"]',".ll-widget"];function dt(e){let n=e;for(;n;){for(const i of Xn)if(n.matches(i))return!0;n=n.parentElement}return!1}function it(e){if(dt(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 et=4096,Qn=20,Zn=20,er=10,tr=10,nr=30,zt=500,rr=['[data-ll-private="true"]',".ll-widget","script","style","noscript","iframe"];function qe(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 Be(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 Ht(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 ge(e,n){return e.length<=n?e:e.slice(0,n-1)+"…"}function Me(e){return e.length}function on(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 m of u){if(d.length>=er)break;if(qe(m)||!Be(m))continue;const C=m.getAttribute("data-ll-region")??"",$=m.getAttribute("data-ll-intent")??void 0,A=ge((m.innerText||m.textContent||"").trim(),zt*2);!C||!A||d.push({id:C,intent:$,text:A})}const p=[],x=["H1","H2","H3","H4","H5","H6"],y=Array.from(i.querySelectorAll("h1, h2, h3, h4, h5, h6"));for(const m of y){if(qe(m)||!Be(m))continue;const C=(m.textContent||"").trim();C&&p.push(`${m.tagName}: ${ge(C,200)}`)}const a=Array.from(i.querySelectorAll("p, li"));for(const m of a){if(qe(m)||!Be(m)||x.includes(m.tagName))continue;const C=(m.textContent||"").trim();C.length>10&&p.push(ge(C,zt))}const c=p.join(`
|
|
2
|
+
`),j=[],S=Array.from(i.querySelectorAll("a[href]"));for(const m of S){if(j.length>=Qn)break;if(qe(m)||!Be(m))continue;const C=m.getAttribute("href")||"",$=(m.textContent||"").trim();!C||!$||j.push({href:C,text:ge($,100)})}const k=[],b=Array.from(i.querySelectorAll("input, textarea, select"));for(const m of b){if(k.length>=Zn)break;if(qe(m)||!it(m)||!Be(m))continue;const C=Ht(m),$=m instanceof HTMLInputElement?m.type:m.tagName.toLowerCase();C&&k.push({label:ge(C,100),type:$})}const v=Array.from(i.querySelectorAll("[data-ll-form]")),I=[];for(const m of v){if(I.length>=tr)break;if(dt(m))continue;const C=m.getAttribute("data-ll-form")||"";if(!C)continue;const $=m.getAttribute("data-ll-intent")||void 0,A=Array.from(m.querySelectorAll("[data-ll-field]")),L=[];for(const P of A){if(L.length>=nr)break;if(!it(P))continue;const z=P.getAttribute("data-ll-field")||"";if(!z)continue;const F=Ht(P)||z,X=P instanceof HTMLInputElement?P.type:P.tagName.toLowerCase();L.push({name:z,label:ge(F,100),type:X})}I.push({id:C,intent:$,fields:L})}const E={url:o,title:l,pathname:s,regions:d,visibleText:c,visibleLinks:j,visibleFields:k,forms:I,extras:e};let T=Me(JSON.stringify(E.regions))+Me(E.visibleText)+Me(JSON.stringify(E.visibleLinks))+Me(JSON.stringify(E.visibleFields));for(;T>et&&E.visibleFields.length>0;)E.visibleFields.pop(),T=Me(JSON.stringify(E.visibleFields));for(;T>et&&E.visibleLinks.length>0;)E.visibleLinks.pop(),T-=80;return Me(E.visibleText)>et&&(E.visibleText=ge(E.visibleText,et-100)),E}let Ie=null;function ut(e,n={}){const i=Date.now(),s=`${typeof window<"u"&&window.location.pathname||"/"}::${typeof window<"u"?window.scrollY:0}`;if(Ie&&Ie.key===s&&i-Ie.at<1e3)return Ie.ctx;const l=on(e,n);return Ie={key:s,at:i,ctx:l},l}function sn(){Ie=null}const ir=200;function ln(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 an(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(dt(u))continue;const d=u.getAttribute("href")||"";if(!or(d))continue;let p=d,x=!0;try{if(typeof window<"u"){const a=new URL(d,i);x=a.origin===i,x&&d.startsWith("http")&&(p=a.pathname+a.search+a.hash)}}catch{continue}if(o.has(p))continue;o.add(p);const y=(u.textContent||"").trim().slice(0,120);s.push({href:p,text:y,internal:x})}return s}let Te=null;const sr=5e3;function tt(){const e=Date.now(),n=typeof window<"u"&&window.location.pathname||"/";if(Te&&Te.pathname===n&&e-Te.at<sr)return Te.routes;const i=an();return Te={at:e,pathname:n,routes:i},i}function cn(){Te=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 Ot(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 xt,bt,vt,wt,_t,kt,St;const{agentId:n,apiKey:i,baseUrl:o="https://app.livelayer.studio",sessionEndpoint:s,sessionBody:l,autoConnect:u=!1,displayMode:d,defaultDisplayMode:p="expanded",onDisplayModeChange:x,position:y="bottom-right",mobileBreakpoint:a=640,persistKey:c="ll-widget",disablePersistence:j=!1,teamMembers:S,currentTeamMemberId:k,onTeamMemberChange:b,idleLoopUrl:v,greeting:I,avatarImageUrl:E,agentName:T,branding:m={},allowCamera:C=!0,allowScreenShare:$=!0,allowTyping:A=!0,showOn:L,hideOn:P,pathname:z,onNavigate:F,onScrollToSelector:X,getPageContext:de,pageContextExtras:We,getRoutes:Fe,onScrollPage:Ue,onClick:Ve,capabilities:J,onConnect:fe,onDisconnect:ye,onTranscript:xe,onAgentState:be,onConnectionStateChange:ve,onAgentEvent:we,onAgentCommand:_e,controlledSession:B,className:ot,style:Ye,zIndex:Ge=2147483647}=e,oe=Zt(z),Pe=nn(oe,L,P);r.useEffect(()=>{sn(),cn()},[oe]);const ie=k!==void 0,[ke,Z]=r.useState(()=>{var g;return k??((g=S==null?void 0:S[0])==null?void 0:g.id)}),pe=ie?k:ke,U=r.useMemo(()=>(S==null?void 0:S.find(g=>g.id===pe))??null,[S,pe]),he=(U==null?void 0:U.agentId)??n,[me,ee]=Xt({value:d,defaultValue:p,onChange:x,persistKey:c,disablePersistence:j}),Se=Qt(a),Ce=Ft(),Q=Ut(),K=Vt(),te=Yt(),se=Gt(),[Le,le]=r.useState(!1),[je,Je]=r.useState(!1),[De,ne]=r.useState(!1),[ae,Ke]=r.useState(!1),[Ee,st]=r.useState(!1),Re=r.useRef(F),h=r.useRef(X),W=r.useRef(Ue),$e=r.useRef(Ve),ft=r.useRef(de),pt=r.useRef(We),ht=r.useRef(Fe),lt=r.useRef(J),re=r.useRef(null);Re.current=F,h.current=X,W.current=Ue,$e.current=Ve,ft.current=de,pt.current=We,ht.current=Fe,lt.current=J;function ce(g){const f=lt.current;return f?f.includes(g):!0}function ue(g,f){console.warn(`[LiveLayer] Agent command "${g}" blocked — capability "${f}" not in allowlist. See https://livelayer.studio/docs/react/capabilities`)}const ze=r.useCallback(g=>{var V,Ne,Qe,Ct;const f=g;if(!(!f.type||typeof f.type!="string")){if(we==null||we({eventName:f.type,data:g}),f.type==="navigate"){if(!ce("navigate")){ue("navigate","navigate");return}const _=typeof f.href=="string"?f.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(Re.current){try{Re.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(f.type==="scroll_to"){if(!ce("scroll")){ue("scroll_to","scroll");return}const _=typeof f.selector=="string"?f.selector:null;if(!_)return;const R=f.behavior==="instant"?"instant":"smooth";if(h.current){try{h.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(f.type==="request_page_context"){if(!ce("read_page")){ue("request_page_context","read_page");return}const _=typeof f.requestId=="string"?f.requestId:void 0,R=(V=re.current)==null?void 0:V.call(re),D=q=>{const N=R,Y=N==null?void 0:N.localParticipant;if(Y!=null&&Y.publishData)try{const G=_?{...q,requestId:_}:q,Ae=new TextEncoder().encode(JSON.stringify(G));Y.publishData(Ae,{reliable:!0})}catch(G){console.warn("[LiveLayer] publishData failed.",G)}},M=pt.current,H=ft.current;try{if(H){const q=H(M);if(q instanceof Promise){D({type:"page_context_pending"}),q.then(N=>D({type:"page_context",context:N})).catch(N=>{console.warn("[LiveLayer] getPageContext rejected; falling back to default walker.",N),D({type:"page_context",context:ut(M)})});return}D({type:"page_context",context:q});return}D({type:"page_context",context:ut(M)})}catch(q){console.warn("[LiveLayer] page-context extraction threw. Sending empty context.",q),D({type:"page_context",context:{url:"",title:"",pathname:"/",regions:[],visibleText:"",visibleLinks:[],visibleFields:[],forms:[],extras:M}})}return}if(f.type==="scroll_page"){if(!ce("scroll")){ue("scroll_page","scroll");return}const _=f.direction;if(_!=="up"&&_!=="down"&&_!=="top"&&_!=="bottom"){console.warn(`[LiveLayer] scroll_page: invalid direction "${String(_)}". Expected up | down | top | bottom.`);return}const R=f.behavior==="instant"?"instant":"smooth";if(W.current){try{W.current(_,R)}catch(N){console.warn("[LiveLayer] onScrollPage threw.",N)}return}if(typeof window>"u")return;const D={behavior:R},M=fr(),H=N=>{M instanceof Window?M.scrollBy({top:N,...D}):M.scrollBy({top:N,...D})},q=N=>{M instanceof Window?M.scrollTo({top:N,...D}):M.scrollTo({top:N,...D})};_==="up"?H(-Ot(M)):_==="down"?H(Ot(M)):q(_==="top"?0:pr(M));return}if(f.type==="click"){if(!ce("click")){ue("click","click");return}const _=typeof f.selector=="string"?f.selector:null;if(!_){console.warn("[LiveLayer] click: missing selector.");return}if($e.current){try{$e.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}(Ne=R.click)==null||Ne.call(R);return}if(f.type==="fill_form"||f.type==="focus_field"){if(!ce("fill_forms")){ue(f.type,"fill_forms");return}if(typeof document>"u")return;const _=typeof f.formId=="string"?f.formId:null;if(!_){console.warn(`[LiveLayer] ${f.type}: missing formId.`);return}const R=document.querySelector(`[data-ll-form="${_.replace(/"/g,'\\"')}"]`);if(!R){console.warn(`[LiveLayer] ${f.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] ${f.type}: refusing to touch a form in a private subtree.`);return}if(f.type==="focus_field"){const M=typeof f.fieldName=="string"?f.fieldName:null;if(!M){console.warn("[LiveLayer] focus_field: missing fieldName.");return}const H=R.querySelector(`[data-ll-field="${M.replace(/"/g,'\\"')}"]`);if(!H){console.warn(`[LiveLayer] focus_field: no field "${M}" in form "${_}".`);return}if(!it(H)){console.warn(`[LiveLayer] focus_field: field "${M}" is privacy-protected and not focusable.`);return}H.focus();return}const D=f.values&&typeof f.values=="object"?f.values:null;if(!D){console.warn("[LiveLayer] fill_form: missing or invalid values.");return}for(const[M,H]of Object.entries(D)){if(typeof H!="string")continue;const q=R.querySelector(`[data-ll-field="${M.replace(/"/g,'\\"')}"]`);if(!q){console.warn(`[LiveLayer] fill_form: no field "${M}" in form "${_}". Skipping.`);continue}if(!it(q)){console.warn(`[LiveLayer] fill_form: field "${M}" is privacy-protected (password / cc-* / private). Skipping.`);continue}try{ar(q,H)}catch(N){console.warn(`[LiveLayer] fill_form: failed to set "${M}".`,N)}}return}if(f.type==="submit_form"){if(!ce("submit_forms")){ue("submit_form","submit_forms");return}if(typeof document>"u")return;const _=typeof f.formId=="string"?f.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 f.requestId=="string"?f.requestId:void 0,M=(Qe=re.current)==null?void 0:Qe.call(re),H=Y=>{const G=M,Ae=G==null?void 0:G.localParticipant;if(Ae!=null&&Ae.publishData)try{const wn=D?{...Y,requestId:D}:Y,_n=new TextEncoder().encode(JSON.stringify(wn));Ae.publishData(_n,{reliable:!0})}catch{}};let q=!1;const N=()=>{q=!0,H({type:"form_submitted",formId:_})};R.addEventListener("submit",N,{once:!0});try{typeof R.requestSubmit=="function"?R.requestSubmit():R.submit()}catch(Y){console.warn("[LiveLayer] submit_form: requestSubmit threw.",Y),R.removeEventListener("submit",N),H({type:"form_submit_blocked",formId:_,reason:"exception"});return}setTimeout(()=>{q||(R.removeEventListener("submit",N),H({type:"form_submit_blocked",formId:_,reason:"validation"}))},500);return}if(f.type==="request_routes"){if(!ce("read_page")){ue("request_routes","read_page");return}const _=typeof f.requestId=="string"?f.requestId:void 0,D=(Ct=re.current)==null?void 0:Ct.call(re),M=D==null?void 0:D.localParticipant;if(!(M!=null&&M.publishData))return;const H=N=>{try{const Y=_?{type:"routes",routes:N,requestId:_}:{type:"routes",routes:N},G=new TextEncoder().encode(JSON.stringify(Y));M.publishData(G,{reliable:!0})}catch(Y){console.warn("[LiveLayer] request_routes: publishData failed.",Y)}},q=ht.current;if(q){try{const N=q(),Y=G=>{if(!Array.isArray(G)){H([]);return}H(G.map(ln).slice(0,200))};N instanceof Promise?N.then(Y).catch(G=>{console.warn("[LiveLayer] getRoutes rejected; falling back to DOM walker.",G),H(tt())}):Y(N)}catch(N){console.warn("[LiveLayer] getRoutes threw; falling back to DOM walker.",N),H(tt())}return}try{H(tt())}catch(N){console.warn("[LiveLayer] request_routes: extractRoutes threw.",N)}return}hr.has(f.type)||_e==null||_e(f)}},[_e,we]),O=Wt({agentId:B?"__controlled__":he,baseUrl:o,apiKey:i,sessionEndpoint:s,sessionBody:l,onDataMessage:B?void 0:ze});r.useEffect(()=>{if(B!=null&&B.subscribeToDataMessages)return B.subscribeToDataMessages(ze)},[B,ze]),re.current=()=>{var g;return(g=O.getRoom)==null?void 0:g.call(O)},r.useEffect(()=>{var V;if(!oe)return;const g=(V=O.getRoom)==null?void 0:V.call(O),f=g==null?void 0:g.localParticipant;if(f!=null&&f.publishData)try{const Ne=new TextEncoder().encode(JSON.stringify({type:"pathname",pathname:oe}));f.publishData(Ne,{reliable:!0})}catch{}},[oe,O,O.connectionState]),r.useEffect(()=>{var V;if(typeof window>"u")return;const g=((V=window.location)==null?void 0:V.hostname)||"";if(g==="localhost"||g==="127.0.0.1"||g==="0.0.0.0"||g.endsWith(".local")||g.endsWith(".test"))return window.__livelayerSimulateCommand=Ne=>{try{ze(Ne)}catch(Qe){console.warn("[LiveLayer] simulate-command threw:",Qe)}},()=>{delete window.__livelayerSimulateCommand}},[ze]);const w=r.useMemo(()=>B?{connectionState:B.connectionState,agentState:B.agentState,transcript:B.transcript,videoElement:B.videoElement,audioElement:B.audioElement,canResume:B.canResume,error:B.error,agentConfig:null,connect:async()=>{await B.onConnect()},disconnect:()=>B.onDisconnect(),getRoom:O.getRoom,isControlled:!0}:{connectionState:O.connectionState,agentState:O.agentState,transcript:O.transcript,videoElement:O.videoElement,audioElement:O.audioElement,canResume:O.canResume,error:O.error,agentConfig:O.agentConfig,connect:O.connect,disconnect:O.disconnect,getRoom:O.getRoom,isControlled:!1},[B,O]),mt=r.useRef(null);r.useEffect(()=>{const g=w.videoElement,f=mt.current;if(!(!g||!f))return f.appendChild(g),()=>{g.parentNode===f&&f.removeChild(g)}},[w.videoElement]),r.useEffect(()=>{const g=w.audioElement;if(!g)return;Ce.attach(g);const f=g.play();return f&&typeof f.catch=="function"&&f.catch(V=>{(V==null?void 0:V.name)==="NotAllowedError"&&le(!0)}),()=>{Ce.detach()}},[w.audioElement]),r.useEffect(()=>{if(w.isControlled||w.connectionState!=="connected")return;const g=w.getRoom();if(g)return Q.setupMic(g).catch(()=>{}),K.attachRoom(g),te.attachRoom(g),se.refresh(),()=>{Q.teardownMic(),K.teardown(),te.teardown()}},[w.isControlled,w.connectionState]),r.useEffect(()=>{const g=w.audioElement;g&&(g.muted=Ee)},[w.audioElement,Ee]);const un=r.useCallback(g=>{const f=w.getRoom();if(f)try{const V=new TextEncoder().encode(JSON.stringify({type:"user_message",text:g}));f.localParticipant.publishData(V,{reliable:!0})}catch{}},[w]),dn=r.useCallback(()=>{st(g=>!g)},[]);r.useEffect(()=>{ve==null||ve(w.connectionState),w.connectionState==="connected"?fe==null||fe():w.connectionState==="disconnected"&&(ye==null||ye())},[w.connectionState,fe,ye,ve]),r.useEffect(()=>{xe==null||xe(w.transcript)},[w.transcript,xe]),r.useEffect(()=>{be==null||be(w.agentState)},[w.agentState,be]);const gt=r.useRef(!1);r.useEffect(()=>{w.isControlled||!u||gt.current||Pe&&w.connectionState==="idle"&&(gt.current=!0,w.connect())},[u,w.connectionState,w,Pe]);const fn=r.useCallback(g=>{const f=S==null?void 0:S.find(V=>V.id===g);f&&(ne(!1),g!==pe&&(Je(!0),w.disconnect(),ie||Z(g),b==null||b(f)))},[S,pe,w,ie,b]);r.useEffect(()=>{je&&w.connectionState==="connected"&&Je(!1)},[w.connectionState,je]),r.useEffect(()=>{if(!De)return;const g=f=>{f.key==="Escape"&&ne(!1)};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[De]);const pn=!!E||!!(U!=null&&U.avatarImageUrl)||w.isControlled,He=Jt(he,o,pn);J===void 0&&((xt=He.info)!=null&&xt.capabilities)&&(lt.current=He.info.capabilities);const Xe=(U==null?void 0:U.name)??T??((bt=w.agentConfig)==null?void 0:bt.name)??((vt=He.info)==null?void 0:vt.name)??"Live Layer",at=(U==null?void 0:U.avatarImageUrl)??E??((wt=w.agentConfig)==null?void 0:wt.avatarImageUrl)??((_t=He.info)==null?void 0:_t.avatarImageUrl)??null,hn=v??((kt=w.agentConfig)==null?void 0:kt.idleLoopUrl)??((St=He.info)==null?void 0:St.idleLoopUrl)??null,mn=I??null,gn=r.useCallback(()=>ee("expanded"),[ee]),yn=r.useCallback(()=>ee("minimized"),[ee]),yt=r.useCallback(()=>{w.disconnect(),ee("hidden")},[w,ee]),xn=r.useCallback(()=>{const g=w.audioElement;g&&g.play().then(()=>le(!1)).catch(()=>{})},[w.audioElement]),bn=r.useCallback(()=>{le(!1),w.connect()},[w]),Oe={...Ye,zIndex:Ge};m.primaryColor&&(Oe["--ll-color-primary"]=m.primaryColor),m.accentColor&&(Oe["--ll-color-accent"]=m.accentColor),m.backgroundColor&&(Oe["--ll-color-bg"]=m.backgroundColor),m.textColor&&(Oe["--ll-color-fg"]=m.textColor);const vn=["ll-widget",`ll-widget--${me}`,`ll-widget--${Se?"mobile":"desktop"}`,ot].filter(Boolean).join(" ");return Pe?t.jsxs("div",{className:vn,style:Oe,"data-display-mode":me,"data-position":y,children:[me==="hidden"&&t.jsx(On,{position:y,isMobile:Se,isSpeaking:w.agentState==="speaking",onExpand:()=>ee("expanded"),label:`Open ${Xe} widget`,avatarImageUrl:at,agentName:Xe}),me==="minimized"&&t.jsx(Bn,{position:y,isMobile:Se,agentName:Xe,avatarImageUrl:at,agentState:w.agentState,isMuted:Q.isMuted,audioLevel:Ce,onExpand:gn,onToggleMute:Q.toggleMute,onClose:yt}),me==="expanded"&&t.jsx(Fn,{position:y,isMobile:Se,agentName:Xe,avatarImageUrl:at,idleLoopUrl:hn,greeting:mn,branding:m,teamMembers:S,currentTeamMemberId:pe,isSwitchingTeamMember:je,teamSwitcherOpen:De,onToggleTeamSwitcher:()=>ne(g=>!g),onSelectTeamMember:fn,connectionState:w.connectionState,agentState:w.agentState,transcript:w.transcript,isMuted:Q.isMuted,micDevices:se.mics,isCameraEnabled:K.isEnabled,cameraPreviewEl:K.previewEl,cameraDevices:se.cameras,activeCameraId:K.activeDeviceId,isScreenShareEnabled:te.isEnabled,screenPreviewEl:te.previewEl,isSpeakerMuted:Ee,allowCamera:C,allowScreenShare:$,allowTyping:A,languageMenuOpen:ae,onToggleLanguageMenu:()=>Ke(g=>!g),needsUserGesture:Le,canResume:w.canResume,micError:Q.micError,error:w.error,avatarVideoContainerRef:mt,agentVideoEl:w.videoElement,onConnect:()=>void w.connect(),onDisconnect:()=>w.disconnect(),onRetry:bn,onResumeAudio:xn,onToggleMute:Q.toggleMute,onToggleCamera:()=>void K.toggle(),onSwitchCameraDevice:g=>void K.switchDevice(g),onToggleScreenShare:()=>void te.toggle(),onToggleSpeaker:dn,onSendMessage:un,onMinimize:yn,onClose:yt,onClearMicError:Q.clearError})]}):null}function gr(e){return t.jsx(Bt,{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),p=r.useRef(null),x=r.useRef(s);x.current=s;const y=r.useCallback(a=>{var j;const c=a.detail;(j=x.current)==null||j.call(x,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",y),a.appendChild(c),p.current=c,()=>{c.removeEventListener("agent-event",y),a.removeChild(c),p.current=null}},[e]),r.useEffect(()=>{p.current&&(o?p.current.setAttribute("mode",o):p.current.removeAttribute("mode"))},[o]),t.jsx("div",{ref:d,className:l,style:u})},xr=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)}),br=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:p,label:x,labelClassName:y,as:a,...c}=n;d=t.jsx("textarea",{ref:i,...u,...c})}else if("as"in n&&n.as==="select"){const{name:p,label:x,labelClassName:y,as:a,children:c,...j}=n;d=t.jsx("select",{ref:i,...u,...j,children:c})}else{const{name:p,label:x,labelClassName:y,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 qt=1;function wr({onMount:e,defaultOpen:n=!1,storageKey:i="ll-debug-open"}){const[o,s]=r.useState(n),[l,u]=r.useState([]),[d,p]=r.useState(""),[x,y]=r.useState(!1),a=r.useRef(new Set),c=r.useRef([]),j=r.useRef(x);j.current=x,r.useEffect(()=>{try{const b=localStorage.getItem(i);b==="1"&&s(!0),b==="0"&&s(!1)}catch{}},[i]),r.useEffect(()=>{try{localStorage.setItem(i,o?"1":"0")}catch{}},[o,i]),r.useEffect(()=>{const b=v=>{(v.metaKey||v.ctrlKey)&&v.shiftKey&&v.key.toLowerCase()==="l"&&(v.preventDefault(),s(I=>!I))};return window.addEventListener("keydown",b),()=>window.removeEventListener("keydown",b)},[]),r.useEffect(()=>{const b=setInterval(()=>{if(c.current.length===0||j.current)return;const v=c.current.splice(0,c.current.length);u(I=>[...v.reverse(),...I].slice(0,200))},100);return()=>clearInterval(b)},[]);const S=r.useRef(!1);if(r.useEffect(()=>{!e||S.current||(S.current=!0,e(b=>{c.current.push({id:qt++,ts:Date.now(),kind:"event",type:b.eventName,data:b.data})}))},[e]),r.useEffect(()=>{const b=console.warn,v=console.log,I=(E,T)=>function(...m){try{const C=typeof m[0]=="string"?m[0]:"";C.startsWith("[LiveLayer]")&&c.current.push({id:qt++,ts:Date.now(),kind:E,type:C.slice(0,120),data:{args:m.slice(1).map($=>kr($))}})}catch{}return T.apply(this,m)};return console.warn=I("warn",b),console.log=I("log",v),()=>{console.warn=b,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(b=>{if(!d)return!0;const v=d.toLowerCase();return b.type.toLowerCase().includes(v)||JSON.stringify(b.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:()=>y(b=>!b),style:ct(x?"#f59e0b":"transparent"),title:"Pause / resume capture",children:x?"▶ resume":"⏸ pause"}),t.jsx("button",{type:"button",onClick:()=>{u([]),c.current=[]},style:ct("transparent"),title:"Clear buffer",children:"clear"}),t.jsx("button",{type:"button",onClick:()=>s(!1),style:ct("transparent"),"aria-label":"Close",title:"Close (Cmd/Ctrl + Shift + L)",children:"✕"})]}),t.jsx("input",{type:"text",value:d,onChange:b=>p(b.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({
|
|
3
3
|
type: "navigate",
|
|
4
4
|
href: "/about"
|
|
5
|
-
})`})]}):k.map(
|
|
5
|
+
})`})]}):k.map(b=>t.jsx(_r,{entry:b,expanded:a.current.has(b.id),onToggle:()=>{a.current.has(b.id)?a.current.delete(b.id):a.current.add(b.id),u(v=>[...v])}},b.id))})]})}function _r({entry:e,expanded:n,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})]}),n&&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 ct(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 kr(e){try{return e instanceof Error?{message:e.message,stack:e.stack}:(JSON.stringify(e),e)}catch{return String(e)}}function Sr(){const[e,n]=r.useState([]),i=r.useCallback(s=>{n(l=>{const u=l.findIndex(d=>d.id===s.id);if(u>=0){const d=l.slice();return d[u]=s,d}return[...l,s]})},[]),o=r.useCallback(()=>n([]),[]);return{entries:e,pushSegment:i,clear:o,latest:e.length>0?e[e.length-1]:null}}exports.AvatarWidget=gr;exports.ErrorBoundary=Bt;exports.LiveLayerDebugPanel=wr;exports.LiveLayerField=vr;exports.LiveLayerForm=br;exports.LiveLayerRegion=xr;exports.LiveLayerWidget=yr;exports.clearPageContextCache=sn;exports.clearRoutesCache=cn;exports.extractPageContext=on;exports.extractRoutes=an;exports.getCachedPageContext=ut;exports.getCachedRoutes=tt;exports.matchesPattern=en;exports.normalizeRouteInput=ln;exports.shouldRenderAtPath=tn;exports.useAgentInfo=Jt;exports.useAudioLevel=Ft;exports.useCameraState=Vt;exports.useDisplayMode=Kt;exports.useDisplayModePersistence=Xt;exports.useIsMobile=Qt;exports.useLiveKitSession=Wt;exports.useMediaDevices=Gt;exports.useMicrophoneState=Ut;exports.usePathname=Zt;exports.useRouteMatch=nn;exports.useScreenShareState=Yt;exports.useTranscript=Sr;
|