@livelayer/react 0.5.24-debug.1 → 0.5.24-debug.2
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 +1 -1
- package/dist/index.mjs +8 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("react/jsx-runtime"),n=require("react"),An=require("@livelayer/sdk"),pt=require("livekit-client");class Xt extends n.Component{constructor(){super(...arguments),this.state={hasError:!1,error:null},this.reset=()=>{this.setState({hasError:!1,error:null})}}static getDerivedStateFromError(r){return{hasError:!0,error:r}}componentDidCatch(r,o){var i,s;(s=(i=this.props).onError)==null||s.call(i,r,o)}render(){var r;return this.state.hasError?this.props.fallback?this.props.fallback:t.jsxs("div",{className:"ll-error-boundary",role:"alert",children:[t.jsx("p",{className:"ll-error-boundary__title",children:"Widget crashed"}),t.jsx("p",{className:"ll-error-boundary__message",children:((r=this.state.error)==null?void 0:r.message)||"Something went wrong."}),t.jsx("button",{type:"button",className:"ll-error-boundary__retry",onClick:this.reset,children:"Reload widget"})]}):this.props.children}}function Qt(e){const[r,o]=n.useState("idle"),[i,s]=n.useState("idle"),[a,d]=n.useState([]),[f,p]=n.useState(null),[b,w]=n.useState(null),[c,l]=n.useState(null),[S,L]=n.useState(!1),[E,v]=n.useState(null),_=n.useRef(null),I=n.useRef(e.onDataMessage);I.current=e.onDataMessage,n.useEffect(()=>{const R={onConnectionStateChange:M=>{o(M),M==="connected"&&v(null)},onAgentStateChange:s,onTranscript:M=>d([...M]),onAgentConfig:p,onAudioTrack:M=>l(M),onVideoTrack:M=>w(M),onVideoTrackRemoved:()=>w(null),onError:M=>v(M),onDataMessage:M=>{var A;(A=I.current)==null||A.call(I,M)},onResumabilityChange:L},z=new An.LiveKitSession({agentId:e.agentId,baseUrl:e.baseUrl,apiKey:e.apiKey,sessionEndpoint:e.sessionEndpoint,sessionBody:e.sessionBody},R);return _.current=z,o("idle"),s("idle"),d([]),p(null),w(null),l(null),L(!1),v(null),()=>{var M;(M=z.destroy)==null||M.call(z),_.current=null}},[e.agentId,e.baseUrl,e.apiKey,e.sessionEndpoint,JSON.stringify(e.sessionBody??{})]);const D=n.useCallback(async()=>{const R=_.current;if(R)try{await R.connect()}catch(z){throw v(z instanceof Error?z.message:String(z)),z}},[]),P=n.useCallback(()=>{const R=_.current;R&&R.disconnect()},[]),g=n.useCallback(()=>{var R;return((R=_.current)==null?void 0:R.getRoom())??null},[]);return{connectionState:r,agentState:i,transcript:a,agentConfig:f,videoElement:b,audioElement:c,canResume:S,error:E,connect:D,disconnect:P,getRoom:g,session:_.current}}function Zt(){const e=n.useRef(null),r=n.useRef(null),o=n.useRef(null),i=n.useRef(null),s=n.useRef(new Set),a=n.useRef(null),d=n.useCallback(()=>{const c=r.current;if(!c){i.current=null;return}(!a.current||a.current.length!==c.frequencyBinCount)&&(a.current=new Uint8Array(new ArrayBuffer(c.frequencyBinCount)));const l=a.current;c.getByteFrequencyData(l);let S=0;for(let E=0;E<l.length;E++)S+=l[E];const L=S/l.length/255;for(const E of s.current)try{E(L)}catch(v){console.error("[useAudioLevel] subscriber threw:",v)}i.current=requestAnimationFrame(d)},[]),f=n.useCallback(()=>{if(e.current||typeof window>"u"||typeof AudioContext>"u")return;const c=new AudioContext,l=c.createAnalyser();l.fftSize=64,l.connect(c.destination),e.current=c,r.current=l},[]),p=n.useCallback(c=>{if(f(),!(!e.current||!r.current)){if(o.current){try{o.current.disconnect()}catch{}o.current=null}try{const l=e.current.createMediaElementSource(c);l.connect(r.current),o.current=l}catch(l){console.warn("[useAudioLevel] createMediaElementSource failed:",l);return}i.current===null&&(i.current=requestAnimationFrame(d))}},[f,d]),b=n.useCallback(()=>{if(i.current!==null&&(cancelAnimationFrame(i.current),i.current=null),o.current){try{o.current.disconnect()}catch{}o.current=null}},[]),w=n.useCallback(c=>(s.current.add(c),()=>{s.current.delete(c)}),[]);return n.useEffect(()=>()=>{if(b(),r.current){try{r.current.disconnect()}catch{}r.current=null}if(e.current){try{e.current.close()}catch{}e.current=null}s.current.clear(),a.current=null},[b]),{attach:p,detach:b,subscribe:w}}function en(){const[e,r]=n.useState(!1),[o,i]=n.useState(null),s=n.useRef(null),a=n.useRef(null),d=n.useCallback(async(c,l)=>{if(s.current&&a.current){try{await a.current.localParticipant.unpublishTrack(s.current)}catch{}s.current.stop(),s.current=null}a.current=c,i(null);try{const S=await pt.createLocalAudioTrack({echoCancellation:!0,noiseSuppression:!0});l!=null&&l.startMuted&&await S.mute(),await c.localParticipant.publishTrack(S),s.current=S,r(S.isMuted)}catch(S){const L=S instanceof Error&&S.name==="NotAllowedError"?"Enable your microphone to talk with the agent.":"Microphone unavailable. Check browser permissions and try again.";throw i(L),S}},[]),f=n.useCallback(()=>{const c=s.current;c&&(c.isMuted?(c.unmute(),r(!1)):(c.mute(),r(!0)))},[]),p=n.useCallback(c=>{const l=s.current;l&&(c&&!l.isMuted?(l.mute(),r(!0)):!c&&l.isMuted&&(l.unmute(),r(!1)))},[]),b=n.useCallback(()=>{const c=s.current,l=a.current;if(c&&l){try{l.localParticipant.unpublishTrack(c)}catch{}c.stop()}s.current=null,a.current=null,r(!1)},[]),w=n.useCallback(()=>i(null),[]);return{isMuted:e,micError:o,toggleMute:f,setMuted:p,setupMic:d,teardownMic:b,clearError:w}}const Dn={resolution:{width:640,height:480,frameRate:24}};function tn(){const[e,r]=n.useState(!1),[o,i]=n.useState(null),[s,a]=n.useState(null),[d,f]=n.useState(""),p=n.useRef(null),b=n.useRef(null),w=n.useCallback(_=>{p.current=_},[]),c=n.useCallback(()=>{const _=p.current,I=b.current;if(I&&_){const D=_.localParticipant.getTrackPublication(pt.Track.Source.Camera);if(D!=null&&D.track){try{_.localParticipant.unpublishTrack(D.track)}catch{}D.track.stop()}else I.stop()}b.current=null,a(null),r(!1)},[]),l=n.useCallback(async _=>{const I=p.current;if(I){i(null);try{const D={...Dn};_&&(D.deviceId=_);const P=await pt.createLocalVideoTrack(D);await I.localParticipant.publishTrack(P),b.current=P;const g=P.attach();a(g),r(!0),_&&f(_);try{I.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({type:"user_camera_on"})),{reliable:!0})}catch{}}catch(D){const P=D instanceof Error&&D.name==="NotAllowedError"?"Enable your camera in the browser to share video.":"Camera unavailable. Check permissions and try again.";i(P)}}},[]),S=n.useCallback(async()=>{e?c():await l(d||void 0)},[e,d,c,l]),L=n.useCallback(async _=>{c(),await l(_)},[c,l]),E=n.useCallback(()=>{c(),p.current=null,i(null),f("")},[c]),v=n.useCallback(()=>i(null),[]);return n.useEffect(()=>()=>{b.current&&b.current.stop()},[]),{isEnabled:e,error:o,previewEl:s,activeDeviceId:d,toggle:S,switchDevice:L,attachRoom:w,teardown:E,clearError:v}}function nn(){const[e,r]=n.useState(!1),[o,i]=n.useState(null),[s,a]=n.useState(null),d=n.useRef(null),f=n.useCallback(l=>{d.current=l},[]),p=n.useCallback(()=>a(null),[]),b=n.useCallback(async()=>{const l=d.current;if(l){if(e){try{await l.localParticipant.setScreenShareEnabled(!1)}catch{}p(),r(!1);return}i(null);try{await l.localParticipant.setScreenShareEnabled(!0);let S=0;const L=()=>{const E=l.localParticipant.getTrackPublication(pt.Track.Source.ScreenShare);if(E!=null&&E.track){const v=E.track.attach();a(v),r(!0);try{l.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({type:"user_screen_share_on"})),{reliable:!0})}catch{}return}S++<10?setTimeout(L,100):r(!0)};L()}catch(S){const L=S instanceof Error?S.name:"";L!=="NotAllowedError"&&L!=="AbortError"&&i("Screen share unavailable. Try again."),r(!1)}}},[e,p]),w=n.useCallback(()=>{const l=d.current;if(l&&e)try{l.localParticipant.setScreenShareEnabled(!1)}catch{}p(),r(!1),i(null),d.current=null},[e,p]),c=n.useCallback(()=>i(null),[]);return{isEnabled:e,error:o,previewEl:s,toggle:b,attachRoom:f,teardown:w,clearError:c}}function rn(){const[e,r]=n.useState([]),[o,i]=n.useState([]),s=n.useCallback(async()=>{if(!(typeof navigator>"u"||!navigator.mediaDevices))try{const a=await navigator.mediaDevices.enumerateDevices();r(a.filter(d=>d.kind==="audioinput")),i(a.filter(d=>d.kind==="videoinput"))}catch{}},[]);return n.useEffect(()=>{if(s(),typeof navigator>"u"||!navigator.mediaDevices)return;const a=()=>void s();return navigator.mediaDevices.addEventListener("devicechange",a),()=>navigator.mediaDevices.removeEventListener("devicechange",a)},[s]),{mics:e,cameras:o,refresh:s}}function on(e,r,o=!1){const[i,s]=n.useState(null),[a,d]=n.useState(null),[f,p]=n.useState(!o&&!!e);return n.useEffect(()=>{if(o||!e){p(!1);return}const b=new AbortController,w=r||"https://app.livelayer.studio";return p(!0),d(null),fetch(`${w}/api/widget/agent/${encodeURIComponent(e)}`,{signal:b.signal}).then(async c=>{if(!c.ok){const l=await c.json().catch(()=>({}));throw new Error(l.error||`HTTP ${c.status}`)}return c.json()}).then(c=>{b.signal.aborted||(s(c),p(!1))}).catch(c=>{b.signal.aborted||(d(c instanceof Error?c.message:"Agent lookup failed"),p(!1))}),()=>b.abort()},[e,r,o]),{info:i,error:a,loading:f}}function Mn(e){if(typeof window>"u")return null;try{return window.localStorage.getItem(e)}catch{return null}}function Tn(e,r){if(!(typeof window>"u"))try{window.localStorage.setItem(e,r)}catch{}}function sn({value:e,defaultValue:r="expanded",onChange:o}={}){const i=e!==void 0,[s,a]=n.useState(r),d=i?e:s,f=n.useCallback(p=>{p!==d&&(i||a(p),o==null||o(p))},[d,i,o]);return[d,f]}const In=["hidden","minimized","expanded"];function Pn(e){return e&&In.includes(e)?e:null}function an({value:e,defaultValue:r="expanded",onChange:o,persistKey:i="ll-widget",disablePersistence:s=!1}={}){const a=`${i}:display-mode`,d=n.useRef(!1),[f,p]=sn({value:e,defaultValue:r,onChange:b=>{e===void 0&&!s&&Tn(a,b),o==null||o(b)}});return n.useEffect(()=>{if(d.current||(d.current=!0,s||e!==void 0))return;const b=Pn(Mn(a));b&&b!==f&&p(b)},[]),[f,p]}const $n=640;function ln(e=$n){const[r,o]=n.useState(!1);return n.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]),r}const It="__llHistoryPatched",ht="ll:pathname";function Bn(){if(typeof window>"u"||window.history[It])return;const e=window.history.pushState,r=window.history.replaceState;window.history.pushState=function(...o){const i=e.apply(this,o);return window.dispatchEvent(new Event(ht)),i},window.history.replaceState=function(...o){const i=r.apply(this,o);return window.dispatchEvent(new Event(ht)),i},window.history[It]=!0}function Pt(){return typeof window>"u"?"/":window.location.pathname||"/"}function cn(e){const[r,o]=n.useState(()=>e??Pt());return n.useEffect(()=>{if(e!==void 0)return;Bn();const i=()=>o(Pt());return i(),window.addEventListener("popstate",i),window.addEventListener(ht,i),()=>{window.removeEventListener("popstate",i),window.removeEventListener(ht,i)}},[e]),e??r}const $t=new Map,zn=/[\\^$+?.()|{}[\]]/g;function On(e){return e.replace(zn,"\\$&")}function Un(e){const r=$t.get(e);if(r)return r;const o=e.length>1&&e.endsWith("/")?e.slice(0,-1):e,i="",s="",a=o.replace(/\*\*/g,i).replace(/\*/g,s),f=On(a).replace(new RegExp(`\\/${i}`,"g"),"(?:\\/.*)?").replace(new RegExp(i,"g"),".*").replace(new RegExp(s,"g"),"[^/]+"),p=new RegExp(`^${f}\\/?$`);return $t.set(e,p),p}function qn(e,r){const o=r.length>1&&r.endsWith("/")?r.slice(0,-1):r;return Un(e).test(o)}function un(e,r){return typeof e=="function"?e(r):e instanceof RegExp?e.test(r):qn(e,r)}function Bt(e,r){if(!e||e.length===0)return!1;for(const o of e)if(un(o,r))return!0;return!1}function dn(e,r,o){return e===void 0?!0:Bt(o,e)?!1:r&&r.length>0?Bt(r,e):!0}function fn(e,r,o){return n.useMemo(()=>dn(e,r,o),[e,r,o])}const zt=({muted:e=!1,className:r})=>e?t.jsxs("svg",{className:r,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,"aria-hidden":"true",children:[t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"}),t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M17 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2"})]}):t.jsx("svg",{className:r,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,"aria-hidden":"true",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19 11a7 7 0 01-7 7m0 0a7 7 0 01-7-7m7 7v4m0 0H8m4 0h4M12 1a3 3 0 00-3 3v4a3 3 0 006 0V4a3 3 0 00-3-3z"})}),Ot=({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"})}),Hn=({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"})}),Vn={left:180,right:0,up:-90,down:90},Ut=({direction:e="right",className:r})=>t.jsx("svg",{className:r,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,style:{transform:`rotate(${Vn[e]}deg)`},"aria-hidden":"true",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 6l6 6-6 6"})});function Wn(e){return e==="top-left"||e==="bottom-left"?"left":"right"}const pn="ll-hidden-tab-center-y",Fn=5,qt=16;function Gn(){if(typeof window>"u")return null;try{const e=window.localStorage.getItem(pn);if(!e)return null;const r=Number.parseFloat(e);return Number.isFinite(r)?r:null}catch{return null}}function Ht(e){if(!(typeof window>"u"))try{window.localStorage.setItem(pn,String(e))}catch{}}const Jn=({position:e,isMobile:r,isSpeaking:o,onExpand:i,label:s="Open widget",avatarImageUrl:a,agentName:d})=>{const f=Wn(e),p=f==="right"?"left":"right",b=r?80:72,w=!!a,[c,l]=n.useState(null),[S,L]=n.useState(!1),E=n.useRef(null),v=n.useRef(!1),_=n.useCallback(A=>{if(typeof window>"u")return A;const $=b/2,U=qt+$,Y=window.innerHeight-qt-$;return Y<U?Math.max(U,A):Math.max(U,Math.min(Y,A))},[b]);n.useEffect(()=>{const A=Gn();l(_(A??window.innerHeight/2));const $=()=>{l(U=>U===null?null:_(U))};return window.addEventListener("resize",$),()=>window.removeEventListener("resize",$)},[_]);const I=n.useCallback(A=>{if(!(A.pointerType==="mouse"&&A.button!==0)&&c!==null){try{A.currentTarget.setPointerCapture(A.pointerId)}catch{}E.current={startClientY:A.clientY,startCenterY:c,moved:!1}}},[c]),D=n.useCallback(A=>{const $=E.current;if(!$)return;const U=A.clientY-$.startClientY;!$.moved&&Math.abs(U)>Fn&&($.moved=!0,L(!0)),$.moved&&l(_($.startCenterY+U))},[_]),P=n.useCallback(A=>{const $=E.current;if($){try{A.currentTarget.releasePointerCapture(A.pointerId)}catch{}E.current=null,$.moved&&(L(!1),v.current=!0,l(U=>(U!==null&&Ht(U),U)))}},[]),g=n.useCallback(()=>{if(v.current){v.current=!1;return}i()},[i]),R=n.useCallback(A=>{if(A.key==="ArrowUp"||A.key==="ArrowDown"){A.preventDefault();const $=A.key==="ArrowUp"?-8:8;l(U=>{if(U===null)return U;const Y=_(U+$);return Ht(Y),Y})}},[_]),z=["ll-hidden",`ll-hidden--${f}`,r?"ll-hidden--mobile":"ll-hidden--desktop",o?"ll-hidden--speaking":null,S?"is-dragging":null,w?"ll-hidden--with-avatar":null].filter(Boolean).join(" "),M=c===null?void 0:{top:`${c-b/2}px`,transform:"none"};return t.jsx("button",{type:"button",className:z,onPointerDown:I,onPointerMove:D,onPointerUp:P,onPointerCancel:P,onClick:g,onKeyDown:R,"aria-label":s,"data-position":e,style:M,children:w?t.jsxs(t.Fragment,{children:[t.jsx(Ut,{direction:p,className:"ll-hidden__chevron ll-hidden__chevron--mini"}),t.jsx("img",{src:a,alt:d?`${d} avatar`:"Agent avatar",className:"ll-hidden__avatar",draggable:!1})]}):t.jsx(Ut,{direction:p,className:"ll-hidden__chevron"})})},Yn=({audioLevel:e,bars:r=20,maxHeight:o=20,minHeight:i=4,className:s,barClassName:a})=>{const d=n.useRef(null),f=n.useRef([]),p=n.useMemo(()=>{const w=(Math.sqrt(5)-1)/2;return Array.from({length:r},(c,l)=>.5+l*w%1*.5)},[r]);n.useEffect(()=>e.subscribe(c=>{for(let l=0;l<r;l++){const S=f.current[l];if(!S)continue;const L=Math.max(i,c*o*p[l]);S.style.height=`${L}px`}}),[e,r,o,i,p]);const b=["ll-waveform",s].filter(Boolean).join(" ");return t.jsx("div",{ref:d,className:b,"aria-hidden":"true",children:Array.from({length:r},(w,c)=>t.jsx("div",{ref:l=>{f.current[c]=l},className:["ll-waveform__bar",a].filter(Boolean).join(" "),style:{height:`${i}px`}},c))})},Kn=({position:e,isMobile:r,agentName:o,avatarImageUrl:i,agentState:s,isMuted:a,audioLevel:d,onExpand:f,onToggleMute:p,onClose:b})=>r?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:f,"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(Yn,{audioLevel:d,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:w=>{w.stopPropagation(),p()},onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&(w.stopPropagation(),w.preventDefault(),p())},"aria-label":a?"Unmute microphone":"Mute microphone",children:t.jsx(zt,{muted:a,className:"ll-minimized__icon"})}),t.jsx(Ot,{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(zt,{muted:a,className:"ll-minimized__icon"})}),t.jsx("button",{type:"button",className:"ll-minimized__btn",onClick:f,"aria-label":`Expand ${o} widget`,children:t.jsx(Ot,{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(Hn,{className:"ll-minimized__icon"})})]})]})}),Xn=({src:e,alt:r,preCannedPlaying:o=!1,className:i,style:s})=>{const[a,d]=n.useState(!1),f=n.useRef(e);if(n.useEffect(()=>{f.current!==e&&(f.current=e,d(!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:r,className:i,style:p,loading:"eager",fetchPriority:"high",onLoad:()=>d(!0)})},Qn=({position:e,isMobile:r,agentName:o,avatarImageUrl:i,idleLoopUrl:s,greeting:a,branding:d,teamMembers:f,currentTeamMemberId:p,isSwitchingTeamMember:b,teamSwitcherOpen:w,onToggleTeamSwitcher:c,onSelectTeamMember:l,languageMenuOpen:S,onToggleLanguageMenu:L,connectionState:E,agentState:v,transcript:_,canResume:I,needsUserGesture:D,error:P,isMuted:g,micError:R,micDevices:z,isCameraEnabled:M,cameraPreviewEl:A,cameraDevices:$,activeCameraId:U,isScreenShareEnabled:Y,screenPreviewEl:ne,isSpeakerMuted:ve,allowCamera:et,allowScreenShare:tt,allowTyping:nt,avatarVideoContainerRef:rt,agentVideoEl:te,micGateOpen:ce,onConnect:we,onDisconnect:Ce,onRetry:Le,onResumeAudio:je,onToggleMute:Ne,onToggleCamera:Re,onSwitchCameraDevice:W,onToggleScreenShare:gt,onToggleSpeaker:yt,onSendMessage:ot,onMinimize:re,onClose:Ae,onClearMicError:Ue})=>{var Pe;const _e=((f==null?void 0:f.length)??0)>1,De=E==="connecting"||E==="connected",J=E==="connected",Q=E==="idle"||E==="disconnected"||E==="error",[Me,oe]=n.useState(!1);n.useEffect(()=>{if(!te){oe(!1);return}if(!te.paused&&te.readyState>=2){oe(!0);return}oe(!1);const h=()=>oe(!0);return te.addEventListener("playing",h),te.addEventListener("loadeddata",h),()=>{te.removeEventListener("playing",h),te.removeEventListener("loadeddata",h)}},[te]);const[ue,ke]=n.useState(!1);n.useEffect(()=>{if(!J){ke(!1);return}if(Me)return;const h=setTimeout(()=>ke(!0),8e3);return()=>clearTimeout(h)},[J,Me]);const qe=E==="connecting"||J&&!!i&&!Me&&!ue,Z=n.useRef(null),ie=n.useRef(null);n.useEffect(()=>{const h=Z.current;h&&(h.innerHTML="",A&&(A.style.width="100%",A.style.height="100%",A.style.objectFit="cover",A.style.transform="scaleX(-1)",h.appendChild(A)))},[A]),n.useEffect(()=>{const h=ie.current;h&&(h.innerHTML="",ne&&(ne.style.width="100%",ne.style.height="100%",ne.style.objectFit="contain",h.appendChild(ne)))},[ne]);const[se,de]=n.useState(!1),[Te,fe]=n.useState(!1);n.useEffect(()=>{if(!se&&!Te&&!S&&!w)return;const h=()=>{de(!1),fe(!1),S&&L(),w&&c()};return document.addEventListener("click",h),()=>document.removeEventListener("click",h)},[se,Te,S,w,L,c]);const[pe,He]=n.useState(""),Ve=n.useCallback(h=>{h.preventDefault();const F=pe.trim();F&&(ot(F),He(""))},[pe,ot]),We=d.productName||"Live Layer";let he=null,me=null;for(let h=_.length-1;h>=0;h--){const F=_[h];if(!he&&F.role==="agent"?he=F:!me&&F.role==="user"&&(me=F),he&&me)break}const Ie=J?(he==null?void 0:he.text)||null:a||null,it=J&&(me==null?void 0:me.text)||null,Fe=["ll-expanded",r?"ll-expanded--mobile":"ll-expanded--desktop"].join(" ");return t.jsxs("div",{className:Fe,"data-position":e,"data-state":J?"connected":De?"connecting":"idle",role:"dialog","aria-label":`${o} widget`,children:[t.jsxs("div",{className:"ll-expanded__bg",children:[i?t.jsx(Xn,{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:((Pe=o==null?void 0:o.charAt(0))==null?void 0:Pe.toUpperCase())||"A"})}),s&&!J&&t.jsx("video",{className:"ll-expanded__bg-idle",src:s,autoPlay:!0,loop:!0,muted:!0,playsInline:!0})]}),t.jsx("div",{ref:rt,className:"ll-expanded__video"}),qe&&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..."})]}),D&&J&&t.jsxs("button",{type:"button",className:"ll-expanded__overlay ll-expanded__overlay--gesture",onClick:je,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"})]}),De?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=>{_e&&(h.stopPropagation(),c())},"aria-haspopup":_e?"listbox":void 0,"aria-expanded":_e?w:void 0,children:[t.jsx("span",{className:"ll-hpill__label",children:o}),_e&&t.jsx(dt,{})]}),_e&&w&&t.jsx("div",{className:"ll-hmenu",onClick:h=>h.stopPropagation(),role:"listbox",children:f==null?void 0:f.map(h=>t.jsxs("button",{type:"button",className:`ll-hmenu__item ${h.id===p?"is-active":""}`,onClick:()=>l(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(),L()},"aria-haspopup":"listbox","aria-expanded":S,"aria-label":"Language: English",title:"Language: English",children:[t.jsx("span",{className:"ll-hpill__label",children:"EN"}),t.jsx(dt,{})]}),S&&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--${v}`,children:v})]}),t.jsxs("div",{className:"ll-expanded__header-actions",children:[t.jsx("button",{type:"button",className:"ll-hbtn",onClick:re,"aria-label":"Minimize widget",title:"Minimize",children:t.jsx(Wt,{})}),t.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--danger",onClick:Ae,"aria-label":"End call",title:"End call",children:t.jsx(Vt,{})})]})]}):t.jsxs("div",{className:"ll-expanded__header ll-expanded__header--idle",children:[t.jsx("span",{className:"ll-expanded__brand",children:We}),t.jsxs("div",{className:"ll-expanded__header-actions",children:[t.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--ghost",onClick:re,"aria-label":"Minimize widget",children:t.jsx(Wt,{})}),t.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--danger",onClick:Ae,"aria-label":"Close widget",children:t.jsx(Vt,{})})]})]}),Q&&(()=>{const h=I?"Restart paused session":E==="disconnected"?"Reconnect to agent":"Start video call",F=I?"Pick up where you left off":null,st=E==="idle"&&!I&&!P;return t.jsxs(t.Fragment,{children:[st&&t.jsxs("button",{type:"button",className:"ll-expanded__play",onClick:we,"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})}),F&&t.jsx("p",{className:"ll-expanded__cta-sublabel",children:F}),t.jsx("button",{type:"button",className:"ll-expanded__cta",onClick:we,"aria-label":h,children:h})]})]})})(),t.jsxs("div",{className:`ll-expanded__pip ${De&&(M||Y)?"is-visible":""}`,children:[t.jsx("div",{ref:ie,className:Y?"ll-expanded__pip-host":"ll-expanded__pip-host is-hidden"}),t.jsx("div",{ref:Z,className:!Y&&M?"ll-expanded__pip-host":"ll-expanded__pip-host is-hidden"})]}),De?t.jsxs("div",{className:"ll-expanded__bottom",children:[Ie&&t.jsx("div",{className:"ll-expanded__transcript ll-expanded__transcript--agent","data-role":"agent",children:t.jsx("p",{className:"ll-expanded__transcript-text",children:Ie})}),it&&t.jsx("div",{className:"ll-expanded__transcript ll-expanded__transcript--user","data-role":"user",children:t.jsx("p",{className:"ll-expanded__transcript-text",children:it})}),t.jsxs("div",{className:"ll-toolbar",onClick:h=>h.stopPropagation(),children:[tt&&t.jsx("button",{type:"button",className:`ll-tool ${Y?"is-on":""}`,onClick:gt,"aria-label":Y?"Stop sharing screen":"Share screen",title:Y?"Stop sharing":"Share screen",children:t.jsx(Zn,{})}),et&&t.jsxs("div",{className:"ll-tool-split",children:[t.jsx("button",{type:"button",className:`ll-tool ll-tool--left ${M?"is-on":""}`,onClick:Re,"aria-label":M?"Turn off camera":"Turn on camera",title:M?"Stop camera":"Start camera",children:t.jsx(er,{})}),t.jsx("button",{type:"button",className:`ll-tool ll-tool--right ${M?"is-on":""}`,onClick:h=>{h.stopPropagation(),fe(F=>!F),de(!1)},"aria-label":"Camera devices","aria-haspopup":"listbox","aria-expanded":Te,children:t.jsx(dt,{})}),Te&&$.length>0&&t.jsx(Ft,{label:"Camera",devices:$,activeId:U,onPick:h=>{fe(!1),W(h)}})]}),t.jsxs("div",{className:`ll-tool-split${!ce&&J?" ll-tool-split--gated":""}`,children:[t.jsx("button",{type:"button",className:`ll-tool ll-tool--left ${g?"is-muted":""}`,onClick:Ne,disabled:!ce&&J,"aria-label":!ce&&J?"Microphone enables once the agent finishes its greeting":g?"Unmute microphone":"Mute microphone",title:!ce&&J?"Mic enables after greeting":g?"Unmute":"Mute",children:t.jsx(tr,{muted:g})}),t.jsx("button",{type:"button",className:`ll-tool ll-tool--right ${g?"is-muted":""}`,onClick:h=>{h.stopPropagation(),de(F=>!F),fe(!1)},"aria-label":"Microphone devices","aria-haspopup":"listbox","aria-expanded":se,children:t.jsx(dt,{})}),se&&z.length>0&&t.jsx(Ft,{label:"Microphone",devices:z,activeId:"",onPick:()=>de(!1)})]}),t.jsx("button",{type:"button",className:`ll-tool ${ve?"is-muted":""}`,onClick:yt,"aria-label":ve?"Unmute speaker":"Mute speaker",title:ve?"Unmute speaker":"Mute speaker",children:t.jsx(nr,{muted:ve})}),t.jsx("button",{type:"button",className:"ll-tool ll-tool--danger",onClick:Ce,"aria-label":"End conversation",title:"End conversation",children:t.jsx(or,{})})]}),nt&&t.jsxs("form",{className:"ll-message-input",onSubmit:Ve,children:[t.jsx("input",{type:"text",className:"ll-message-input__field",placeholder:"Message...",value:pe,onChange:h=>He(h.target.value),"aria-label":"Message the agent"}),pe.trim()&&t.jsx("button",{type:"submit",className:"ll-message-input__send","aria-label":"Send message",children:t.jsx(rr,{})})]})]}):null,(()=>{if(R&&E!=="error")return t.jsxs("div",{className:"ll-expanded__banner",role:"alert",children:[t.jsx("span",{children:R}),t.jsx("button",{type:"button",className:"ll-expanded__banner-x",onClick:Ue,"aria-label":"Dismiss",children:"×"})]});if(!P||E!=="error")return null;let h="Failed to connect",F="Try again";return P==="MIC_PERMISSION_DENIED"?h="Microphone blocked. Allow access to talk.":P==="MIC_NOT_FOUND"?h="No microphone found. Plug one in + retry.":P==="MIC_UNAVAILABLE"?h="Mic unavailable. Check other apps using it.":P==="AGENT_TIMEOUT"?h="Agent didn't pick up. Try again.":P==="CONNECT_FAILED"?h="Connection failed. Check your network.":P.length<80&&(h=P),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:Le,children:F})]})})()]})};function dt(){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 Vt(){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 Wt(){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 Zn(){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 er(){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 tr({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 nr({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 rr(){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 or(){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 Ft=({label:e,devices:r,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}),r.map((s,a)=>{const d=o===s.deviceId;return t.jsxs("button",{type:"button",className:`ll-device-menu__item ${d?"is-active":""}`,onClick:()=>i(s.deviceId),role:"option","aria-selected":d,children:[d&&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)})]}),ir=['[data-ll-private="true"]',".ll-widget"];function kt(e){let r=e;for(;r;){for(const o of ir)if(r.matches(o))return!0;r=r.parentElement}return!1}function mt(e){if(kt(e))return!1;if(e instanceof HTMLInputElement){if(e.type==="password")return!1;const r=(e.getAttribute("autocomplete")||"").toLowerCase();if(r==="off"||r.startsWith("cc-"))return!1}return!0}const ft=4096,sr=20,ar=20,lr=10,cr=10,ur=30,Gt=500,dr=['[data-ll-private="true"]',".ll-widget","script","style","noscript","iframe"];function Xe(e){if(e.getAttribute("aria-hidden")==="true"||e.hasAttribute("hidden"))return!0;let r=e;for(;r;){for(const o of dr)if(r.matches(o))return!0;r=r.parentElement}return!1}function Qe(e){if(typeof window>"u")return!0;const r=e.getBoundingClientRect();if(r.width<=0||r.height<=0)return!1;const o=window.innerHeight||document.documentElement.clientHeight,i=window.innerWidth||document.documentElement.clientWidth;return r.bottom>0&&r.right>0&&r.top<o&&r.left<i}function Jt(e){const r=e.getAttribute("id");if(r){const a=document.querySelector(`label[for="${CSS.escape(r)}"]`);if(a!=null&&a.textContent)return a.textContent.trim()}const 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 Ee(e,r){return e.length<=r?e:e.slice(0,r-1)+"…"}function $e(e){return e.length}function hn(e,r={}){const o=r.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||"",d=Array.from(o.querySelectorAll("[data-ll-region]")),f=[];for(const g of d){if(f.length>=lr)break;if(Xe(g)||!Qe(g))continue;const R=g.getAttribute("data-ll-region")??"",z=g.getAttribute("data-ll-intent")??void 0,M=Ee((g.innerText||g.textContent||"").trim(),Gt*2);!R||!M||f.push({id:R,intent:z,text:M})}const p=[],b=["H1","H2","H3","H4","H5","H6"],w=Array.from(o.querySelectorAll("h1, h2, h3, h4, h5, h6"));for(const g of w){if(Xe(g)||!Qe(g))continue;const R=(g.textContent||"").trim();R&&p.push(`${g.tagName}: ${Ee(R,200)}`)}const c=Array.from(o.querySelectorAll("p, li"));for(const g of c){if(Xe(g)||!Qe(g)||b.includes(g.tagName))continue;const R=(g.textContent||"").trim();R.length>10&&p.push(Ee(R,Gt))}const l=p.join(`
|
|
1
|
+
"use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("react/jsx-runtime"),n=require("react"),An=require("@livelayer/sdk"),pt=require("livekit-client");class Xt extends n.Component{constructor(){super(...arguments),this.state={hasError:!1,error:null},this.reset=()=>{this.setState({hasError:!1,error:null})}}static getDerivedStateFromError(r){return{hasError:!0,error:r}}componentDidCatch(r,o){var i,s;(s=(i=this.props).onError)==null||s.call(i,r,o)}render(){var r;return this.state.hasError?this.props.fallback?this.props.fallback:t.jsxs("div",{className:"ll-error-boundary",role:"alert",children:[t.jsx("p",{className:"ll-error-boundary__title",children:"Widget crashed"}),t.jsx("p",{className:"ll-error-boundary__message",children:((r=this.state.error)==null?void 0:r.message)||"Something went wrong."}),t.jsx("button",{type:"button",className:"ll-error-boundary__retry",onClick:this.reset,children:"Reload widget"})]}):this.props.children}}function Qt(e){const[r,o]=n.useState("idle"),[i,s]=n.useState("idle"),[a,d]=n.useState([]),[f,p]=n.useState(null),[b,w]=n.useState(null),[c,l]=n.useState(null),[S,L]=n.useState(!1),[E,v]=n.useState(null),_=n.useRef(null),I=n.useRef(e.onDataMessage);I.current=e.onDataMessage,n.useEffect(()=>{const R={onConnectionStateChange:M=>{o(M),M==="connected"&&v(null)},onAgentStateChange:s,onTranscript:M=>d([...M]),onAgentConfig:p,onAudioTrack:M=>l(M),onVideoTrack:M=>w(M),onVideoTrackRemoved:()=>w(null),onError:M=>v(M),onDataMessage:M=>{var A;(A=I.current)==null||A.call(I,M)},onResumabilityChange:L},z=new An.LiveKitSession({agentId:e.agentId,baseUrl:e.baseUrl,apiKey:e.apiKey,sessionEndpoint:e.sessionEndpoint,sessionBody:e.sessionBody,manageMic:!1},R);return _.current=z,o("idle"),s("idle"),d([]),p(null),w(null),l(null),L(!1),v(null),()=>{var M;(M=z.destroy)==null||M.call(z),_.current=null}},[e.agentId,e.baseUrl,e.apiKey,e.sessionEndpoint,JSON.stringify(e.sessionBody??{})]);const D=n.useCallback(async()=>{const R=_.current;if(R)try{await R.connect()}catch(z){throw v(z instanceof Error?z.message:String(z)),z}},[]),P=n.useCallback(()=>{const R=_.current;R&&R.disconnect()},[]),g=n.useCallback(()=>{var R;return((R=_.current)==null?void 0:R.getRoom())??null},[]);return{connectionState:r,agentState:i,transcript:a,agentConfig:f,videoElement:b,audioElement:c,canResume:S,error:E,connect:D,disconnect:P,getRoom:g,session:_.current}}function Zt(){const e=n.useRef(null),r=n.useRef(null),o=n.useRef(null),i=n.useRef(null),s=n.useRef(new Set),a=n.useRef(null),d=n.useCallback(()=>{const c=r.current;if(!c){i.current=null;return}(!a.current||a.current.length!==c.frequencyBinCount)&&(a.current=new Uint8Array(new ArrayBuffer(c.frequencyBinCount)));const l=a.current;c.getByteFrequencyData(l);let S=0;for(let E=0;E<l.length;E++)S+=l[E];const L=S/l.length/255;for(const E of s.current)try{E(L)}catch(v){console.error("[useAudioLevel] subscriber threw:",v)}i.current=requestAnimationFrame(d)},[]),f=n.useCallback(()=>{if(e.current||typeof window>"u"||typeof AudioContext>"u")return;const c=new AudioContext,l=c.createAnalyser();l.fftSize=64,l.connect(c.destination),e.current=c,r.current=l},[]),p=n.useCallback(c=>{if(f(),!(!e.current||!r.current)){if(o.current){try{o.current.disconnect()}catch{}o.current=null}try{const l=e.current.createMediaElementSource(c);l.connect(r.current),o.current=l}catch(l){console.warn("[useAudioLevel] createMediaElementSource failed:",l);return}i.current===null&&(i.current=requestAnimationFrame(d))}},[f,d]),b=n.useCallback(()=>{if(i.current!==null&&(cancelAnimationFrame(i.current),i.current=null),o.current){try{o.current.disconnect()}catch{}o.current=null}},[]),w=n.useCallback(c=>(s.current.add(c),()=>{s.current.delete(c)}),[]);return n.useEffect(()=>()=>{if(b(),r.current){try{r.current.disconnect()}catch{}r.current=null}if(e.current){try{e.current.close()}catch{}e.current=null}s.current.clear(),a.current=null},[b]),{attach:p,detach:b,subscribe:w}}function en(){const[e,r]=n.useState(!1),[o,i]=n.useState(null),s=n.useRef(null),a=n.useRef(null),d=n.useCallback(async(c,l)=>{if(s.current&&a.current){try{await a.current.localParticipant.unpublishTrack(s.current)}catch{}s.current.stop(),s.current=null}a.current=c,i(null);try{const S=await pt.createLocalAudioTrack({echoCancellation:!0,noiseSuppression:!0});l!=null&&l.startMuted&&await S.mute(),await c.localParticipant.publishTrack(S),s.current=S,r(S.isMuted)}catch(S){const L=S instanceof Error&&S.name==="NotAllowedError"?"Enable your microphone to talk with the agent.":"Microphone unavailable. Check browser permissions and try again.";throw i(L),S}},[]),f=n.useCallback(()=>{const c=s.current;c&&(c.isMuted?(c.unmute(),r(!1)):(c.mute(),r(!0)))},[]),p=n.useCallback(c=>{const l=s.current;l&&(c&&!l.isMuted?(l.mute(),r(!0)):!c&&l.isMuted&&(l.unmute(),r(!1)))},[]),b=n.useCallback(()=>{const c=s.current,l=a.current;if(c&&l){try{l.localParticipant.unpublishTrack(c)}catch{}c.stop()}s.current=null,a.current=null,r(!1)},[]),w=n.useCallback(()=>i(null),[]);return{isMuted:e,micError:o,toggleMute:f,setMuted:p,setupMic:d,teardownMic:b,clearError:w}}const Dn={resolution:{width:640,height:480,frameRate:24}};function tn(){const[e,r]=n.useState(!1),[o,i]=n.useState(null),[s,a]=n.useState(null),[d,f]=n.useState(""),p=n.useRef(null),b=n.useRef(null),w=n.useCallback(_=>{p.current=_},[]),c=n.useCallback(()=>{const _=p.current,I=b.current;if(I&&_){const D=_.localParticipant.getTrackPublication(pt.Track.Source.Camera);if(D!=null&&D.track){try{_.localParticipant.unpublishTrack(D.track)}catch{}D.track.stop()}else I.stop()}b.current=null,a(null),r(!1)},[]),l=n.useCallback(async _=>{const I=p.current;if(I){i(null);try{const D={...Dn};_&&(D.deviceId=_);const P=await pt.createLocalVideoTrack(D);await I.localParticipant.publishTrack(P),b.current=P;const g=P.attach();a(g),r(!0),_&&f(_);try{I.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({type:"user_camera_on"})),{reliable:!0})}catch{}}catch(D){const P=D instanceof Error&&D.name==="NotAllowedError"?"Enable your camera in the browser to share video.":"Camera unavailable. Check permissions and try again.";i(P)}}},[]),S=n.useCallback(async()=>{e?c():await l(d||void 0)},[e,d,c,l]),L=n.useCallback(async _=>{c(),await l(_)},[c,l]),E=n.useCallback(()=>{c(),p.current=null,i(null),f("")},[c]),v=n.useCallback(()=>i(null),[]);return n.useEffect(()=>()=>{b.current&&b.current.stop()},[]),{isEnabled:e,error:o,previewEl:s,activeDeviceId:d,toggle:S,switchDevice:L,attachRoom:w,teardown:E,clearError:v}}function nn(){const[e,r]=n.useState(!1),[o,i]=n.useState(null),[s,a]=n.useState(null),d=n.useRef(null),f=n.useCallback(l=>{d.current=l},[]),p=n.useCallback(()=>a(null),[]),b=n.useCallback(async()=>{const l=d.current;if(l){if(e){try{await l.localParticipant.setScreenShareEnabled(!1)}catch{}p(),r(!1);return}i(null);try{await l.localParticipant.setScreenShareEnabled(!0);let S=0;const L=()=>{const E=l.localParticipant.getTrackPublication(pt.Track.Source.ScreenShare);if(E!=null&&E.track){const v=E.track.attach();a(v),r(!0);try{l.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({type:"user_screen_share_on"})),{reliable:!0})}catch{}return}S++<10?setTimeout(L,100):r(!0)};L()}catch(S){const L=S instanceof Error?S.name:"";L!=="NotAllowedError"&&L!=="AbortError"&&i("Screen share unavailable. Try again."),r(!1)}}},[e,p]),w=n.useCallback(()=>{const l=d.current;if(l&&e)try{l.localParticipant.setScreenShareEnabled(!1)}catch{}p(),r(!1),i(null),d.current=null},[e,p]),c=n.useCallback(()=>i(null),[]);return{isEnabled:e,error:o,previewEl:s,toggle:b,attachRoom:f,teardown:w,clearError:c}}function rn(){const[e,r]=n.useState([]),[o,i]=n.useState([]),s=n.useCallback(async()=>{if(!(typeof navigator>"u"||!navigator.mediaDevices))try{const a=await navigator.mediaDevices.enumerateDevices();r(a.filter(d=>d.kind==="audioinput")),i(a.filter(d=>d.kind==="videoinput"))}catch{}},[]);return n.useEffect(()=>{if(s(),typeof navigator>"u"||!navigator.mediaDevices)return;const a=()=>void s();return navigator.mediaDevices.addEventListener("devicechange",a),()=>navigator.mediaDevices.removeEventListener("devicechange",a)},[s]),{mics:e,cameras:o,refresh:s}}function on(e,r,o=!1){const[i,s]=n.useState(null),[a,d]=n.useState(null),[f,p]=n.useState(!o&&!!e);return n.useEffect(()=>{if(o||!e){p(!1);return}const b=new AbortController,w=r||"https://app.livelayer.studio";return p(!0),d(null),fetch(`${w}/api/widget/agent/${encodeURIComponent(e)}`,{signal:b.signal}).then(async c=>{if(!c.ok){const l=await c.json().catch(()=>({}));throw new Error(l.error||`HTTP ${c.status}`)}return c.json()}).then(c=>{b.signal.aborted||(s(c),p(!1))}).catch(c=>{b.signal.aborted||(d(c instanceof Error?c.message:"Agent lookup failed"),p(!1))}),()=>b.abort()},[e,r,o]),{info:i,error:a,loading:f}}function Mn(e){if(typeof window>"u")return null;try{return window.localStorage.getItem(e)}catch{return null}}function Tn(e,r){if(!(typeof window>"u"))try{window.localStorage.setItem(e,r)}catch{}}function sn({value:e,defaultValue:r="expanded",onChange:o}={}){const i=e!==void 0,[s,a]=n.useState(r),d=i?e:s,f=n.useCallback(p=>{p!==d&&(i||a(p),o==null||o(p))},[d,i,o]);return[d,f]}const In=["hidden","minimized","expanded"];function Pn(e){return e&&In.includes(e)?e:null}function an({value:e,defaultValue:r="expanded",onChange:o,persistKey:i="ll-widget",disablePersistence:s=!1}={}){const a=`${i}:display-mode`,d=n.useRef(!1),[f,p]=sn({value:e,defaultValue:r,onChange:b=>{e===void 0&&!s&&Tn(a,b),o==null||o(b)}});return n.useEffect(()=>{if(d.current||(d.current=!0,s||e!==void 0))return;const b=Pn(Mn(a));b&&b!==f&&p(b)},[]),[f,p]}const $n=640;function ln(e=$n){const[r,o]=n.useState(!1);return n.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]),r}const It="__llHistoryPatched",ht="ll:pathname";function Bn(){if(typeof window>"u"||window.history[It])return;const e=window.history.pushState,r=window.history.replaceState;window.history.pushState=function(...o){const i=e.apply(this,o);return window.dispatchEvent(new Event(ht)),i},window.history.replaceState=function(...o){const i=r.apply(this,o);return window.dispatchEvent(new Event(ht)),i},window.history[It]=!0}function Pt(){return typeof window>"u"?"/":window.location.pathname||"/"}function cn(e){const[r,o]=n.useState(()=>e??Pt());return n.useEffect(()=>{if(e!==void 0)return;Bn();const i=()=>o(Pt());return i(),window.addEventListener("popstate",i),window.addEventListener(ht,i),()=>{window.removeEventListener("popstate",i),window.removeEventListener(ht,i)}},[e]),e??r}const $t=new Map,zn=/[\\^$+?.()|{}[\]]/g;function On(e){return e.replace(zn,"\\$&")}function Un(e){const r=$t.get(e);if(r)return r;const o=e.length>1&&e.endsWith("/")?e.slice(0,-1):e,i="",s="",a=o.replace(/\*\*/g,i).replace(/\*/g,s),f=On(a).replace(new RegExp(`\\/${i}`,"g"),"(?:\\/.*)?").replace(new RegExp(i,"g"),".*").replace(new RegExp(s,"g"),"[^/]+"),p=new RegExp(`^${f}\\/?$`);return $t.set(e,p),p}function qn(e,r){const o=r.length>1&&r.endsWith("/")?r.slice(0,-1):r;return Un(e).test(o)}function un(e,r){return typeof e=="function"?e(r):e instanceof RegExp?e.test(r):qn(e,r)}function Bt(e,r){if(!e||e.length===0)return!1;for(const o of e)if(un(o,r))return!0;return!1}function dn(e,r,o){return e===void 0?!0:Bt(o,e)?!1:r&&r.length>0?Bt(r,e):!0}function fn(e,r,o){return n.useMemo(()=>dn(e,r,o),[e,r,o])}const zt=({muted:e=!1,className:r})=>e?t.jsxs("svg",{className:r,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,"aria-hidden":"true",children:[t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"}),t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M17 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2"})]}):t.jsx("svg",{className:r,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,"aria-hidden":"true",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19 11a7 7 0 01-7 7m0 0a7 7 0 01-7-7m7 7v4m0 0H8m4 0h4M12 1a3 3 0 00-3 3v4a3 3 0 006 0V4a3 3 0 00-3-3z"})}),Ot=({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"})}),Hn=({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"})}),Vn={left:180,right:0,up:-90,down:90},Ut=({direction:e="right",className:r})=>t.jsx("svg",{className:r,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,style:{transform:`rotate(${Vn[e]}deg)`},"aria-hidden":"true",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 6l6 6-6 6"})});function Wn(e){return e==="top-left"||e==="bottom-left"?"left":"right"}const pn="ll-hidden-tab-center-y",Fn=5,qt=16;function Gn(){if(typeof window>"u")return null;try{const e=window.localStorage.getItem(pn);if(!e)return null;const r=Number.parseFloat(e);return Number.isFinite(r)?r:null}catch{return null}}function Ht(e){if(!(typeof window>"u"))try{window.localStorage.setItem(pn,String(e))}catch{}}const Jn=({position:e,isMobile:r,isSpeaking:o,onExpand:i,label:s="Open widget",avatarImageUrl:a,agentName:d})=>{const f=Wn(e),p=f==="right"?"left":"right",b=r?80:72,w=!!a,[c,l]=n.useState(null),[S,L]=n.useState(!1),E=n.useRef(null),v=n.useRef(!1),_=n.useCallback(A=>{if(typeof window>"u")return A;const $=b/2,U=qt+$,Y=window.innerHeight-qt-$;return Y<U?Math.max(U,A):Math.max(U,Math.min(Y,A))},[b]);n.useEffect(()=>{const A=Gn();l(_(A??window.innerHeight/2));const $=()=>{l(U=>U===null?null:_(U))};return window.addEventListener("resize",$),()=>window.removeEventListener("resize",$)},[_]);const I=n.useCallback(A=>{if(!(A.pointerType==="mouse"&&A.button!==0)&&c!==null){try{A.currentTarget.setPointerCapture(A.pointerId)}catch{}E.current={startClientY:A.clientY,startCenterY:c,moved:!1}}},[c]),D=n.useCallback(A=>{const $=E.current;if(!$)return;const U=A.clientY-$.startClientY;!$.moved&&Math.abs(U)>Fn&&($.moved=!0,L(!0)),$.moved&&l(_($.startCenterY+U))},[_]),P=n.useCallback(A=>{const $=E.current;if($){try{A.currentTarget.releasePointerCapture(A.pointerId)}catch{}E.current=null,$.moved&&(L(!1),v.current=!0,l(U=>(U!==null&&Ht(U),U)))}},[]),g=n.useCallback(()=>{if(v.current){v.current=!1;return}i()},[i]),R=n.useCallback(A=>{if(A.key==="ArrowUp"||A.key==="ArrowDown"){A.preventDefault();const $=A.key==="ArrowUp"?-8:8;l(U=>{if(U===null)return U;const Y=_(U+$);return Ht(Y),Y})}},[_]),z=["ll-hidden",`ll-hidden--${f}`,r?"ll-hidden--mobile":"ll-hidden--desktop",o?"ll-hidden--speaking":null,S?"is-dragging":null,w?"ll-hidden--with-avatar":null].filter(Boolean).join(" "),M=c===null?void 0:{top:`${c-b/2}px`,transform:"none"};return t.jsx("button",{type:"button",className:z,onPointerDown:I,onPointerMove:D,onPointerUp:P,onPointerCancel:P,onClick:g,onKeyDown:R,"aria-label":s,"data-position":e,style:M,children:w?t.jsxs(t.Fragment,{children:[t.jsx(Ut,{direction:p,className:"ll-hidden__chevron ll-hidden__chevron--mini"}),t.jsx("img",{src:a,alt:d?`${d} avatar`:"Agent avatar",className:"ll-hidden__avatar",draggable:!1})]}):t.jsx(Ut,{direction:p,className:"ll-hidden__chevron"})})},Yn=({audioLevel:e,bars:r=20,maxHeight:o=20,minHeight:i=4,className:s,barClassName:a})=>{const d=n.useRef(null),f=n.useRef([]),p=n.useMemo(()=>{const w=(Math.sqrt(5)-1)/2;return Array.from({length:r},(c,l)=>.5+l*w%1*.5)},[r]);n.useEffect(()=>e.subscribe(c=>{for(let l=0;l<r;l++){const S=f.current[l];if(!S)continue;const L=Math.max(i,c*o*p[l]);S.style.height=`${L}px`}}),[e,r,o,i,p]);const b=["ll-waveform",s].filter(Boolean).join(" ");return t.jsx("div",{ref:d,className:b,"aria-hidden":"true",children:Array.from({length:r},(w,c)=>t.jsx("div",{ref:l=>{f.current[c]=l},className:["ll-waveform__bar",a].filter(Boolean).join(" "),style:{height:`${i}px`}},c))})},Kn=({position:e,isMobile:r,agentName:o,avatarImageUrl:i,agentState:s,isMuted:a,audioLevel:d,onExpand:f,onToggleMute:p,onClose:b})=>r?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:f,"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(Yn,{audioLevel:d,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:w=>{w.stopPropagation(),p()},onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&(w.stopPropagation(),w.preventDefault(),p())},"aria-label":a?"Unmute microphone":"Mute microphone",children:t.jsx(zt,{muted:a,className:"ll-minimized__icon"})}),t.jsx(Ot,{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(zt,{muted:a,className:"ll-minimized__icon"})}),t.jsx("button",{type:"button",className:"ll-minimized__btn",onClick:f,"aria-label":`Expand ${o} widget`,children:t.jsx(Ot,{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(Hn,{className:"ll-minimized__icon"})})]})]})}),Xn=({src:e,alt:r,preCannedPlaying:o=!1,className:i,style:s})=>{const[a,d]=n.useState(!1),f=n.useRef(e);if(n.useEffect(()=>{f.current!==e&&(f.current=e,d(!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:r,className:i,style:p,loading:"eager",fetchPriority:"high",onLoad:()=>d(!0)})},Qn=({position:e,isMobile:r,agentName:o,avatarImageUrl:i,idleLoopUrl:s,greeting:a,branding:d,teamMembers:f,currentTeamMemberId:p,isSwitchingTeamMember:b,teamSwitcherOpen:w,onToggleTeamSwitcher:c,onSelectTeamMember:l,languageMenuOpen:S,onToggleLanguageMenu:L,connectionState:E,agentState:v,transcript:_,canResume:I,needsUserGesture:D,error:P,isMuted:g,micError:R,micDevices:z,isCameraEnabled:M,cameraPreviewEl:A,cameraDevices:$,activeCameraId:U,isScreenShareEnabled:Y,screenPreviewEl:ne,isSpeakerMuted:ve,allowCamera:et,allowScreenShare:tt,allowTyping:nt,avatarVideoContainerRef:rt,agentVideoEl:te,micGateOpen:ce,onConnect:we,onDisconnect:Ce,onRetry:Le,onResumeAudio:je,onToggleMute:Ne,onToggleCamera:Re,onSwitchCameraDevice:W,onToggleScreenShare:gt,onToggleSpeaker:yt,onSendMessage:ot,onMinimize:re,onClose:Ae,onClearMicError:Ue})=>{var Pe;const _e=((f==null?void 0:f.length)??0)>1,De=E==="connecting"||E==="connected",J=E==="connected",Q=E==="idle"||E==="disconnected"||E==="error",[Me,oe]=n.useState(!1);n.useEffect(()=>{if(!te){oe(!1);return}if(!te.paused&&te.readyState>=2){oe(!0);return}oe(!1);const h=()=>oe(!0);return te.addEventListener("playing",h),te.addEventListener("loadeddata",h),()=>{te.removeEventListener("playing",h),te.removeEventListener("loadeddata",h)}},[te]);const[ue,ke]=n.useState(!1);n.useEffect(()=>{if(!J){ke(!1);return}if(Me)return;const h=setTimeout(()=>ke(!0),8e3);return()=>clearTimeout(h)},[J,Me]);const qe=E==="connecting"||J&&!!i&&!Me&&!ue,Z=n.useRef(null),ie=n.useRef(null);n.useEffect(()=>{const h=Z.current;h&&(h.innerHTML="",A&&(A.style.width="100%",A.style.height="100%",A.style.objectFit="cover",A.style.transform="scaleX(-1)",h.appendChild(A)))},[A]),n.useEffect(()=>{const h=ie.current;h&&(h.innerHTML="",ne&&(ne.style.width="100%",ne.style.height="100%",ne.style.objectFit="contain",h.appendChild(ne)))},[ne]);const[se,de]=n.useState(!1),[Te,fe]=n.useState(!1);n.useEffect(()=>{if(!se&&!Te&&!S&&!w)return;const h=()=>{de(!1),fe(!1),S&&L(),w&&c()};return document.addEventListener("click",h),()=>document.removeEventListener("click",h)},[se,Te,S,w,L,c]);const[pe,He]=n.useState(""),Ve=n.useCallback(h=>{h.preventDefault();const F=pe.trim();F&&(ot(F),He(""))},[pe,ot]),We=d.productName||"Live Layer";let he=null,me=null;for(let h=_.length-1;h>=0;h--){const F=_[h];if(!he&&F.role==="agent"?he=F:!me&&F.role==="user"&&(me=F),he&&me)break}const Ie=J?(he==null?void 0:he.text)||null:a||null,it=J&&(me==null?void 0:me.text)||null,Fe=["ll-expanded",r?"ll-expanded--mobile":"ll-expanded--desktop"].join(" ");return t.jsxs("div",{className:Fe,"data-position":e,"data-state":J?"connected":De?"connecting":"idle",role:"dialog","aria-label":`${o} widget`,children:[t.jsxs("div",{className:"ll-expanded__bg",children:[i?t.jsx(Xn,{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:((Pe=o==null?void 0:o.charAt(0))==null?void 0:Pe.toUpperCase())||"A"})}),s&&!J&&t.jsx("video",{className:"ll-expanded__bg-idle",src:s,autoPlay:!0,loop:!0,muted:!0,playsInline:!0})]}),t.jsx("div",{ref:rt,className:"ll-expanded__video"}),qe&&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..."})]}),D&&J&&t.jsxs("button",{type:"button",className:"ll-expanded__overlay ll-expanded__overlay--gesture",onClick:je,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"})]}),De?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=>{_e&&(h.stopPropagation(),c())},"aria-haspopup":_e?"listbox":void 0,"aria-expanded":_e?w:void 0,children:[t.jsx("span",{className:"ll-hpill__label",children:o}),_e&&t.jsx(dt,{})]}),_e&&w&&t.jsx("div",{className:"ll-hmenu",onClick:h=>h.stopPropagation(),role:"listbox",children:f==null?void 0:f.map(h=>t.jsxs("button",{type:"button",className:`ll-hmenu__item ${h.id===p?"is-active":""}`,onClick:()=>l(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(),L()},"aria-haspopup":"listbox","aria-expanded":S,"aria-label":"Language: English",title:"Language: English",children:[t.jsx("span",{className:"ll-hpill__label",children:"EN"}),t.jsx(dt,{})]}),S&&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--${v}`,children:v})]}),t.jsxs("div",{className:"ll-expanded__header-actions",children:[t.jsx("button",{type:"button",className:"ll-hbtn",onClick:re,"aria-label":"Minimize widget",title:"Minimize",children:t.jsx(Wt,{})}),t.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--danger",onClick:Ae,"aria-label":"End call",title:"End call",children:t.jsx(Vt,{})})]})]}):t.jsxs("div",{className:"ll-expanded__header ll-expanded__header--idle",children:[t.jsx("span",{className:"ll-expanded__brand",children:We}),t.jsxs("div",{className:"ll-expanded__header-actions",children:[t.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--ghost",onClick:re,"aria-label":"Minimize widget",children:t.jsx(Wt,{})}),t.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--danger",onClick:Ae,"aria-label":"Close widget",children:t.jsx(Vt,{})})]})]}),Q&&(()=>{const h=I?"Restart paused session":E==="disconnected"?"Reconnect to agent":"Start video call",F=I?"Pick up where you left off":null,st=E==="idle"&&!I&&!P;return t.jsxs(t.Fragment,{children:[st&&t.jsxs("button",{type:"button",className:"ll-expanded__play",onClick:we,"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})}),F&&t.jsx("p",{className:"ll-expanded__cta-sublabel",children:F}),t.jsx("button",{type:"button",className:"ll-expanded__cta",onClick:we,"aria-label":h,children:h})]})]})})(),t.jsxs("div",{className:`ll-expanded__pip ${De&&(M||Y)?"is-visible":""}`,children:[t.jsx("div",{ref:ie,className:Y?"ll-expanded__pip-host":"ll-expanded__pip-host is-hidden"}),t.jsx("div",{ref:Z,className:!Y&&M?"ll-expanded__pip-host":"ll-expanded__pip-host is-hidden"})]}),De?t.jsxs("div",{className:"ll-expanded__bottom",children:[Ie&&t.jsx("div",{className:"ll-expanded__transcript ll-expanded__transcript--agent","data-role":"agent",children:t.jsx("p",{className:"ll-expanded__transcript-text",children:Ie})}),it&&t.jsx("div",{className:"ll-expanded__transcript ll-expanded__transcript--user","data-role":"user",children:t.jsx("p",{className:"ll-expanded__transcript-text",children:it})}),t.jsxs("div",{className:"ll-toolbar",onClick:h=>h.stopPropagation(),children:[tt&&t.jsx("button",{type:"button",className:`ll-tool ${Y?"is-on":""}`,onClick:gt,"aria-label":Y?"Stop sharing screen":"Share screen",title:Y?"Stop sharing":"Share screen",children:t.jsx(Zn,{})}),et&&t.jsxs("div",{className:"ll-tool-split",children:[t.jsx("button",{type:"button",className:`ll-tool ll-tool--left ${M?"is-on":""}`,onClick:Re,"aria-label":M?"Turn off camera":"Turn on camera",title:M?"Stop camera":"Start camera",children:t.jsx(er,{})}),t.jsx("button",{type:"button",className:`ll-tool ll-tool--right ${M?"is-on":""}`,onClick:h=>{h.stopPropagation(),fe(F=>!F),de(!1)},"aria-label":"Camera devices","aria-haspopup":"listbox","aria-expanded":Te,children:t.jsx(dt,{})}),Te&&$.length>0&&t.jsx(Ft,{label:"Camera",devices:$,activeId:U,onPick:h=>{fe(!1),W(h)}})]}),t.jsxs("div",{className:`ll-tool-split${!ce&&J?" ll-tool-split--gated":""}`,children:[t.jsx("button",{type:"button",className:`ll-tool ll-tool--left ${g?"is-muted":""}`,onClick:Ne,disabled:!ce&&J,"aria-label":!ce&&J?"Microphone enables once the agent finishes its greeting":g?"Unmute microphone":"Mute microphone",title:!ce&&J?"Mic enables after greeting":g?"Unmute":"Mute",children:t.jsx(tr,{muted:g})}),t.jsx("button",{type:"button",className:`ll-tool ll-tool--right ${g?"is-muted":""}`,onClick:h=>{h.stopPropagation(),de(F=>!F),fe(!1)},"aria-label":"Microphone devices","aria-haspopup":"listbox","aria-expanded":se,children:t.jsx(dt,{})}),se&&z.length>0&&t.jsx(Ft,{label:"Microphone",devices:z,activeId:"",onPick:()=>de(!1)})]}),t.jsx("button",{type:"button",className:`ll-tool ${ve?"is-muted":""}`,onClick:yt,"aria-label":ve?"Unmute speaker":"Mute speaker",title:ve?"Unmute speaker":"Mute speaker",children:t.jsx(nr,{muted:ve})}),t.jsx("button",{type:"button",className:"ll-tool ll-tool--danger",onClick:Ce,"aria-label":"End conversation",title:"End conversation",children:t.jsx(or,{})})]}),nt&&t.jsxs("form",{className:"ll-message-input",onSubmit:Ve,children:[t.jsx("input",{type:"text",className:"ll-message-input__field",placeholder:"Message...",value:pe,onChange:h=>He(h.target.value),"aria-label":"Message the agent"}),pe.trim()&&t.jsx("button",{type:"submit",className:"ll-message-input__send","aria-label":"Send message",children:t.jsx(rr,{})})]})]}):null,(()=>{if(R&&E!=="error")return t.jsxs("div",{className:"ll-expanded__banner",role:"alert",children:[t.jsx("span",{children:R}),t.jsx("button",{type:"button",className:"ll-expanded__banner-x",onClick:Ue,"aria-label":"Dismiss",children:"×"})]});if(!P||E!=="error")return null;let h="Failed to connect",F="Try again";return P==="MIC_PERMISSION_DENIED"?h="Microphone blocked. Allow access to talk.":P==="MIC_NOT_FOUND"?h="No microphone found. Plug one in + retry.":P==="MIC_UNAVAILABLE"?h="Mic unavailable. Check other apps using it.":P==="AGENT_TIMEOUT"?h="Agent didn't pick up. Try again.":P==="CONNECT_FAILED"?h="Connection failed. Check your network.":P.length<80&&(h=P),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:Le,children:F})]})})()]})};function dt(){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 Vt(){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 Wt(){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 Zn(){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 er(){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 tr({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 nr({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 rr(){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 or(){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 Ft=({label:e,devices:r,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}),r.map((s,a)=>{const d=o===s.deviceId;return t.jsxs("button",{type:"button",className:`ll-device-menu__item ${d?"is-active":""}`,onClick:()=>i(s.deviceId),role:"option","aria-selected":d,children:[d&&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)})]}),ir=['[data-ll-private="true"]',".ll-widget"];function kt(e){let r=e;for(;r;){for(const o of ir)if(r.matches(o))return!0;r=r.parentElement}return!1}function mt(e){if(kt(e))return!1;if(e instanceof HTMLInputElement){if(e.type==="password")return!1;const r=(e.getAttribute("autocomplete")||"").toLowerCase();if(r==="off"||r.startsWith("cc-"))return!1}return!0}const ft=4096,sr=20,ar=20,lr=10,cr=10,ur=30,Gt=500,dr=['[data-ll-private="true"]',".ll-widget","script","style","noscript","iframe"];function Xe(e){if(e.getAttribute("aria-hidden")==="true"||e.hasAttribute("hidden"))return!0;let r=e;for(;r;){for(const o of dr)if(r.matches(o))return!0;r=r.parentElement}return!1}function Qe(e){if(typeof window>"u")return!0;const r=e.getBoundingClientRect();if(r.width<=0||r.height<=0)return!1;const o=window.innerHeight||document.documentElement.clientHeight,i=window.innerWidth||document.documentElement.clientWidth;return r.bottom>0&&r.right>0&&r.top<o&&r.left<i}function Jt(e){const r=e.getAttribute("id");if(r){const a=document.querySelector(`label[for="${CSS.escape(r)}"]`);if(a!=null&&a.textContent)return a.textContent.trim()}const 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 Ee(e,r){return e.length<=r?e:e.slice(0,r-1)+"…"}function $e(e){return e.length}function hn(e,r={}){const o=r.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||"",d=Array.from(o.querySelectorAll("[data-ll-region]")),f=[];for(const g of d){if(f.length>=lr)break;if(Xe(g)||!Qe(g))continue;const R=g.getAttribute("data-ll-region")??"",z=g.getAttribute("data-ll-intent")??void 0,M=Ee((g.innerText||g.textContent||"").trim(),Gt*2);!R||!M||f.push({id:R,intent:z,text:M})}const p=[],b=["H1","H2","H3","H4","H5","H6"],w=Array.from(o.querySelectorAll("h1, h2, h3, h4, h5, h6"));for(const g of w){if(Xe(g)||!Qe(g))continue;const R=(g.textContent||"").trim();R&&p.push(`${g.tagName}: ${Ee(R,200)}`)}const c=Array.from(o.querySelectorAll("p, li"));for(const g of c){if(Xe(g)||!Qe(g)||b.includes(g.tagName))continue;const R=(g.textContent||"").trim();R.length>10&&p.push(Ee(R,Gt))}const l=p.join(`
|
|
2
2
|
`),S=[],L=Array.from(o.querySelectorAll("a[href]"));for(const g of L){if(S.length>=sr)break;if(Xe(g)||!Qe(g))continue;const R=g.getAttribute("href")||"",z=(g.textContent||"").trim();!R||!z||S.push({href:R,text:Ee(z,100)})}const E=[],v=Array.from(o.querySelectorAll("input, textarea, select"));for(const g of v){if(E.length>=ar)break;if(Xe(g)||!mt(g)||!Qe(g))continue;const R=Jt(g),z=g instanceof HTMLInputElement?g.type:g.tagName.toLowerCase();R&&E.push({label:Ee(R,100),type:z})}const _=Array.from(o.querySelectorAll("[data-ll-form]")),I=[];for(const g of _){if(I.length>=cr)break;if(kt(g))continue;const R=g.getAttribute("data-ll-form")||"";if(!R)continue;const z=g.getAttribute("data-ll-intent")||void 0,M=Array.from(g.querySelectorAll("[data-ll-field]")),A=[];for(const $ of M){if(A.length>=ur)break;if(!mt($))continue;const U=$.getAttribute("data-ll-field")||"";if(!U)continue;const Y=Jt($)||U,ne=$ instanceof HTMLInputElement?$.type:$.tagName.toLowerCase();A.push({name:U,label:Ee(Y,100),type:ne})}I.push({id:R,intent:z,fields:A})}const D={url:i,title:a,pathname:s,regions:f,visibleText:l,visibleLinks:S,visibleFields:E,forms:I,extras:e};let P=$e(JSON.stringify(D.regions))+$e(D.visibleText)+$e(JSON.stringify(D.visibleLinks))+$e(JSON.stringify(D.visibleFields));for(;P>ft&&D.visibleFields.length>0;)D.visibleFields.pop(),P=$e(JSON.stringify(D.visibleFields));for(;P>ft&&D.visibleLinks.length>0;)D.visibleLinks.pop(),P-=80;return $e(D.visibleText)>ft&&(D.visibleText=Ee(D.visibleText,ft-100)),D}let Be=null;function Ze(e,r={}){const o=Date.now(),s=`${typeof window<"u"&&window.location.pathname||"/"}::${typeof window<"u"?window.scrollY:0}`;if(Be&&Be.key===s&&o-Be.at<1e3)return Be.ctx;const a=hn(e,r);return Be={key:s,at:o,ctx:a},a}function mn(){Be=null}const fr=200;function gn(e){const r=String(e.href||"");return{href:r,text:String(e.text??e.title??r),internal:e.internal??!0,title:e.title,description:e.description}}function pr(e){return!(!e||e.startsWith("#")||e.startsWith("javascript:")||e.startsWith("mailto:")||e.startsWith("tel:"))}function yn(e){const r=e??(typeof document<"u"?document:null);if(!r)return[];const o=typeof window<"u"&&window.location.origin||"",i=new Set,s=[],a=Array.from(r.querySelectorAll("a[href]"));for(const d of a){if(s.length>=fr)break;if(kt(d))continue;const f=d.getAttribute("href")||"";if(!pr(f))continue;let p=f,b=!0;try{if(typeof window<"u"){const c=new URL(f,o);b=c.origin===o,b&&f.startsWith("http")&&(p=c.pathname+c.search+c.hash)}}catch{continue}if(i.has(p))continue;i.add(p);const w=(d.textContent||"").trim().slice(0,120);s.push({href:p,text:w,internal:b})}return s}let ze=null;const hr=5e3;function Oe(){const e=Date.now(),r=typeof window<"u"&&window.location.pathname||"/";if(ze&&ze.pathname===r&&e-ze.at<hr)return ze.routes;const o=yn();return ze={at:e,pathname:r,routes:o},o}function bn(){ze=null}function mr(e,r){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,r):e.value=r}function gr(e,r,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"),d=a==null?void 0:a.set,f=r==="true"||r==="1"||r==="on";d?d.call(e,f):e.checked=f,i&&e.dispatchEvent(new Event("input",{bubbles:!0})),s&&e.dispatchEvent(new Event("change",{bubbles:!0}));return}mr(e,r),i&&e.dispatchEvent(new Event("input",{bubbles:!0})),s&&e.dispatchEvent(new Event("change",{bubbles:!0}))}function yr(){if(typeof window>"u"||typeof document>"u")return!1;const e=document.scrollingElement||document.documentElement;if(!e||e.scrollHeight<=e.clientHeight+2)return!1;const r=window.getComputedStyle(e);return!(r.overflowY==="hidden"||r.overflowY==="clip")}function br(e){if(!(e instanceof HTMLElement))return!1;const o=window.getComputedStyle(e).overflowY;return!(o!=="auto"&&o!=="scroll"||e.scrollHeight<=e.clientHeight+2)}function xr(){if(typeof document>"u")return null;const e=Array.from(document.querySelectorAll("body, body *"));let r=null,o=0;for(const i of e){if(!br(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,r=i)}return r}function vr(){if(typeof window>"u")return null;if(yr())return window;const e=xr();return e||window}function Yt(e){return e instanceof Window?e.innerHeight||0:e.clientHeight||0}function wr(e){var r,o;return e instanceof Window?typeof document>"u"?0:Math.max(((r=document.body)==null?void 0:r.scrollHeight)??0,((o=document.documentElement)==null?void 0:o.scrollHeight)??0):e.scrollHeight-e.clientHeight}const _r=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","request_initial_sync"]);function kr(e){var jt,Nt,Rt,At,Dt,Mt,Tt;const{agentId:r,apiKey:o,baseUrl:i="https://app.livelayer.studio",sessionEndpoint:s,sessionBody:a,autoConnect:d=!1,displayMode:f,defaultDisplayMode:p="expanded",onDisplayModeChange:b,position:w="bottom-right",mobileBreakpoint:c=640,persistKey:l="ll-widget",disablePersistence:S=!1,teamMembers:L,currentTeamMemberId:E,onTeamMemberChange:v,idleLoopUrl:_,greeting:I,avatarImageUrl:D,agentName:P,branding:g={},allowCamera:R=!0,allowScreenShare:z=!0,allowTyping:M=!0,showOn:A,hideOn:$,pathname:U,onNavigate:Y,onScrollToSelector:ne,getPageContext:ve,pageContextExtras:et,getRoutes:tt,onScrollPage:nt,onClick:rt,capabilities:te,onConnect:ce,onDisconnect:we,onTranscript:Ce,onAgentState:Le,onConnectionStateChange:je,onAgentEvent:Ne,onAgentCommand:Re,controlledSession:W,className:gt,style:yt,zIndex:ot=2147483647}=e,re=cn(U),Ae=fn(re,A,$);n.useEffect(()=>{mn(),bn()},[re]);const Ue=E!==void 0,[_e,De]=n.useState(()=>{var m;return E??((m=L==null?void 0:L[0])==null?void 0:m.id)}),J=Ue?E:_e,Q=n.useMemo(()=>(L==null?void 0:L.find(m=>m.id===J))??null,[L,J]),Me=(Q==null?void 0:Q.agentId)??r,[oe,ue]=an({value:f,defaultValue:p,onChange:b,persistKey:l,disablePersistence:S}),ke=ln(c),qe=Zt(),Z=en(),ie=tn(),se=nn(),de=rn(),[Te,fe]=n.useState(!1),[pe,He]=n.useState(!1),[Ve,We]=n.useState(!1),[he,me]=n.useState(!1),[Ie,it]=n.useState(!1),Fe=n.useRef(Y),Pe=n.useRef(ne),h=n.useRef(nt),F=n.useRef(rt),st=n.useRef(ve),at=n.useRef(et),lt=n.useRef(tt),bt=n.useRef(te),ee=n.useRef(null),ct=n.useRef(null),St=n.useRef(void 0);St.current=re,Fe.current=Y,Pe.current=ne,h.current=nt,F.current=rt,st.current=ve,at.current=et,lt.current=tt,bt.current=te;function ge(m){const u=bt.current;return u?u.includes(m):!0}function ye(m,u){console.warn(`[LiveLayer] Agent command "${m}" blocked — capability "${u}" not in allowlist. See https://livelayer.studio/docs/react/capabilities`)}const Ge=n.useCallback(m=>{var V,ae,X,be,xe,G;const u=m;if(!(!u.type||typeof u.type!="string")){if(Ne==null||Ne({eventName:u.type,data:m}),u.type==="bot_ready"||u.type==="request_initial_sync"){console.log(`[NAV-DEBUG][widget] received ${u.type} → triggering pushSnapshot`);try{(V=ct.current)==null||V.call(ct)}catch(x){console.warn("[NAV-DEBUG][widget] pushSnapshot threw:",x)}}if(u.type==="navigate"){if(!ge("navigate")){ye("navigate","navigate");return}const x=typeof u.href=="string"?u.href:null;if(!x){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(Fe.current){try{Fe.current(x)}catch(k){console.warn(`[LiveLayer] onNavigate threw for "${x}". Falling back. Error:`,k)}return}if(typeof document<"u"){const k=document.querySelector(`a[href="${x.replace(/"/g,'\\"')}"]`);if(k){k.click();return}}if(typeof window<"u"&&typeof history<"u")try{history.pushState({},"",x),window.dispatchEvent(new PopStateEvent("popstate"))}catch(k){console.warn(`[LiveLayer] history.pushState fallback failed for "${x}". Pass an onNavigate prop to use your router directly. See https://livelayer.studio/docs/react/navigation`,k)}return}if(u.type==="scroll_to"){if(!ge("scroll")){ye("scroll_to","scroll");return}const x=typeof u.selector=="string"?u.selector:null;if(!x)return;const k=u.behavior==="instant"?"instant":"smooth";if(Pe.current){try{Pe.current(x,k)}catch(j){console.warn("[LiveLayer] onScrollToSelector threw.",j)}return}if(typeof document<"u"){let j=null;try{j=document.querySelector(x)}catch{console.warn(`[LiveLayer] scroll_to: invalid selector "${x}".`);return}if(!j){console.warn(`[LiveLayer] scroll_to: no element matched "${x}". The user may be on a different page. See https://livelayer.studio/docs/errors/scroll-no-match`);return}j.scrollIntoView({behavior:k,block:"start"})}return}if(u.type==="request_page_context"){if(!ge("read_page")){ye("request_page_context","read_page");return}const x=typeof u.requestId=="string"?u.requestId:void 0,k=(ae=ee.current)==null?void 0:ae.call(ee),j=H=>{const N=k,q=N==null?void 0:N.localParticipant;if(q!=null&&q.publishData)try{const T=x?{...H,requestId:x}:H,K=new TextEncoder().encode(JSON.stringify(T));q.publishData(K,{reliable:!0})}catch(T){console.warn("[LiveLayer] publishData failed.",T)}},C=at.current,O=st.current;try{if(O){const H=O(C);if(H instanceof Promise){j({type:"page_context_pending"}),H.then(N=>j({type:"page_context",context:N})).catch(N=>{console.warn("[LiveLayer] getPageContext rejected; falling back to default walker.",N),j({type:"page_context",context:Ze(C)})});return}j({type:"page_context",context:H});return}j({type:"page_context",context:Ze(C)})}catch(H){console.warn("[LiveLayer] page-context extraction threw. Sending empty context.",H),j({type:"page_context",context:{url:"",title:"",pathname:"/",regions:[],visibleText:"",visibleLinks:[],visibleFields:[],forms:[],extras:C}})}return}if(u.type==="scroll_page"){if(!ge("scroll")){ye("scroll_page","scroll");return}const x=u.direction;if(x!=="up"&&x!=="down"&&x!=="top"&&x!=="bottom"){console.warn(`[LiveLayer] scroll_page: invalid direction "${String(x)}". Expected up | down | top | bottom.`);return}const k=u.behavior==="instant"?"instant":"smooth";if(h.current){try{h.current(x,k)}catch(N){console.warn("[LiveLayer] onScrollPage threw.",N)}return}if(typeof window>"u")return;const j={behavior:k},C=vr(),O=N=>{C instanceof Window?C.scrollBy({top:N,...j}):C.scrollBy({top:N,...j})},H=N=>{C instanceof Window?C.scrollTo({top:N,...j}):C.scrollTo({top:N,...j})};x==="up"?O(-Yt(C)):x==="down"?O(Yt(C)):H(x==="top"?0:wr(C));return}if(u.type==="click"){if(!ge("click")){ye("click","click");return}const x=typeof u.selector=="string"?u.selector:null;if(!x){console.warn("[LiveLayer] click: missing selector.");return}if(F.current){try{F.current(x)}catch(j){console.warn("[LiveLayer] onClick threw.",j)}return}if(typeof document>"u")return;let k=null;try{k=document.querySelector(x)}catch{console.warn(`[LiveLayer] click: invalid selector "${x}".`);return}if(!k){console.warn(`[LiveLayer] click: no element matched "${x}". See https://livelayer.studio/docs/errors/click-no-match`);return}if(k.closest('[data-ll-private="true"], .ll-widget')){console.warn("[LiveLayer] click: refusing to click element inside a private subtree.");return}(X=k.click)==null||X.call(k);return}if(u.type==="fill_form"||u.type==="focus_field"){if(!ge("fill_forms")){ye(u.type,"fill_forms");return}if(typeof document>"u")return;const x=typeof u.requestId=="string"?u.requestId:void 0,k=(be=ee.current)==null?void 0:be.call(ee),j=T=>{if(u.type!=="fill_form")return;const K=k,le=K==null?void 0:K.localParticipant;if(le!=null&&le.publishData)try{const Se=x?{...T,requestId:x}:T,Rn=new TextEncoder().encode(JSON.stringify(Se));le.publishData(Rn,{reliable:!0})}catch(Se){console.warn("[LiveLayer] publishData failed.",Se)}},C=typeof u.formId=="string"?u.formId:null;if(!C){console.warn(`[LiveLayer] ${u.type}: missing formId.`),j({type:"fill_form_result",ok:!1,reason:"missing formId"});return}const O=document.querySelector(`[data-ll-form="${C.replace(/"/g,'\\"')}"]`);if(!O){console.warn(`[LiveLayer] ${u.type}: no form with data-ll-form="${C}". Tag your form with <LiveLayerForm id> or data-ll-form. See https://livelayer.studio/docs/react/forms`),j({type:"fill_form_result",ok:!1,reason:`no form with data-ll-form="${C}" on this page`,formId:C});return}if(O.closest('[data-ll-private="true"], .ll-widget')){console.warn(`[LiveLayer] ${u.type}: refusing to touch a form in a private subtree.`),j({type:"fill_form_result",ok:!1,reason:"form is in a private subtree (data-ll-private)",formId:C});return}if(u.type==="focus_field"){const T=typeof u.fieldName=="string"?u.fieldName:null;if(!T){console.warn("[LiveLayer] focus_field: missing fieldName.");return}const K=O.querySelector(`[data-ll-field="${T.replace(/"/g,'\\"')}"]`);if(!K){console.warn(`[LiveLayer] focus_field: no field "${T}" in form "${C}".`);return}if(!mt(K)){console.warn(`[LiveLayer] focus_field: field "${T}" is privacy-protected and not focusable.`);return}K.focus();return}const H=u.values&&typeof u.values=="object"?u.values:null;if(!H){console.warn("[LiveLayer] fill_form: missing or invalid values."),j({type:"fill_form_result",ok:!1,reason:"missing or invalid values",formId:C});return}const N=[],q=[];for(const[T,K]of Object.entries(H)){if(typeof K!="string")continue;const le=O.querySelector(`[data-ll-field="${T.replace(/"/g,'\\"')}"]`);if(!le){console.warn(`[LiveLayer] fill_form: no field "${T}" in form "${C}". Skipping.`),q.push(T);continue}if(!mt(le)){console.warn(`[LiveLayer] fill_form: field "${T}" is privacy-protected (password / cc-* / private). Skipping.`),q.push(T);continue}try{gr(le,K),N.push(T)}catch(Se){console.warn(`[LiveLayer] fill_form: failed to set "${T}".`,Se),q.push(T)}}j({type:"fill_form_result",ok:N.length>0,formId:C,filled:N,skipped:q,reason:N.length===0?`none of the requested fields exist on this form (skipped: ${q.join(", ")})`:void 0});return}if(u.type==="submit_form"){if(!ge("submit_forms")){ye("submit_form","submit_forms");return}if(typeof document>"u")return;const x=typeof u.formId=="string"?u.formId:null;if(!x){console.warn("[LiveLayer] submit_form: missing formId.");return}const k=document.querySelector(`[data-ll-form="${x.replace(/"/g,'\\"')}"]`);if(!k){console.warn(`[LiveLayer] submit_form: no form with data-ll-form="${x}".`);return}if(k.closest('[data-ll-private="true"], .ll-widget')){console.warn("[LiveLayer] submit_form: refusing to submit a form in a private subtree.");return}const j=typeof u.requestId=="string"?u.requestId:void 0,C=(xe=ee.current)==null?void 0:xe.call(ee),O=q=>{const T=C,K=T==null?void 0:T.localParticipant;if(K!=null&&K.publishData)try{const le=j?{...q,requestId:j}:q,Se=new TextEncoder().encode(JSON.stringify(le));K.publishData(Se,{reliable:!0})}catch{}};let H=!1;const N=()=>{H=!0,O({type:"form_submitted",formId:x})};k.addEventListener("submit",N,{once:!0});try{typeof k.requestSubmit=="function"?k.requestSubmit():k.submit()}catch(q){console.warn("[LiveLayer] submit_form: requestSubmit threw.",q),k.removeEventListener("submit",N),O({type:"form_submit_blocked",formId:x,reason:"exception"});return}setTimeout(()=>{H||(k.removeEventListener("submit",N),O({type:"form_submit_blocked",formId:x,reason:"validation"}))},500);return}if(u.type==="request_routes"){if(!ge("read_page")){ye("request_routes","read_page");return}const x=typeof u.requestId=="string"?u.requestId:void 0,j=(G=ee.current)==null?void 0:G.call(ee),C=j==null?void 0:j.localParticipant;if(!(C!=null&&C.publishData))return;const O=N=>{try{const q=x?{type:"routes",routes:N,requestId:x}:{type:"routes",routes:N},T=new TextEncoder().encode(JSON.stringify(q));C.publishData(T,{reliable:!0})}catch(q){console.warn("[LiveLayer] request_routes: publishData failed.",q)}},H=lt.current;if(H){try{const N=H(),q=T=>{if(!Array.isArray(T)){O([]);return}O(T.map(gn).slice(0,200))};N instanceof Promise?N.then(q).catch(T=>{console.warn("[LiveLayer] getRoutes rejected; falling back to DOM walker.",T),O(Oe())}):q(N)}catch(N){console.warn("[LiveLayer] getRoutes threw; falling back to DOM walker.",N),O(Oe())}return}try{O(Oe())}catch(N){console.warn("[LiveLayer] request_routes: extractRoutes threw.",N)}return}_r.has(u.type)||Re==null||Re(u)}},[Re,Ne]),B=Qt({agentId:W?"__controlled__":Me,baseUrl:i,apiKey:o,sessionEndpoint:s,sessionBody:a,onDataMessage:W?void 0:Ge});n.useEffect(()=>{if(W!=null&&W.subscribeToDataMessages)return W.subscribeToDataMessages(Ge)},[W,Ge]),ee.current=()=>{var m;return(m=B.getRoom)==null?void 0:m.call(B)},ct.current=()=>{var ae,X,be,xe;const m=St.current;if(!m){console.log("[NAV-DEBUG][widget] pushSnapshot bailed: no pathname");return}const u=(ae=B.getRoom)==null?void 0:ae.call(B),V=u==null?void 0:u.localParticipant;if(!(V!=null&&V.publishData)){console.log("[NAV-DEBUG][widget] pushSnapshot bailed: no publishData (not connected)");return}try{V.publishData(new TextEncoder().encode(JSON.stringify({type:"pathname",pathname:m})),{reliable:!0})}catch(G){console.warn("[NAV-DEBUG][widget] pushSnapshot pathname threw:",G)}try{const G=Ze(at.current);V.publishData(new TextEncoder().encode(JSON.stringify({type:"page_context_push",pathname:m,context:G})),{reliable:!0}),console.log(`[NAV-DEBUG][widget] pushSnapshot page_context_push sent (regions=${((X=G.regions)==null?void 0:X.length)??0} forms=${((be=G.forms)==null?void 0:be.length)??0} links=${((xe=G.visibleLinks)==null?void 0:xe.length)??0})`)}catch(G){console.warn("[NAV-DEBUG][widget] pushSnapshot page_context threw:",G)}(async()=>{try{const G=lt.current;let x=[];if(G){const k=G(),j=k instanceof Promise?await k:k;x=Array.isArray(j)?j.slice(0,200):[]}else x=Oe();V.publishData(new TextEncoder().encode(JSON.stringify({type:"routes_push",routes:x})),{reliable:!0}),console.log(`[NAV-DEBUG][widget] pushSnapshot routes_push sent (${x.length} routes)`)}catch(G){console.warn("[NAV-DEBUG][widget] pushSnapshot routes threw:",G)}})()},n.useEffect(()=>{var ae;if(console.log(`[NAV-DEBUG][widget] pathname-effect fired pathname=${re} connState=${B.connectionState} t=${Date.now()}`),!re){console.log("[NAV-DEBUG][widget] effect bailed: no pathname");return}const m=(ae=B.getRoom)==null?void 0:ae.call(B),u=m==null?void 0:m.localParticipant;if(console.log(`[NAV-DEBUG][widget] immediate-push state: room=${!!m} lp=${!!u} publishData=${!!(u!=null&&u.publishData)}`),!(u!=null&&u.publishData)){console.log("[NAV-DEBUG][widget] effect bailed: no publishData (not connected yet)");return}try{const X=new TextEncoder().encode(JSON.stringify({type:"pathname",pathname:re}));u.publishData(X,{reliable:!0}),console.log(`[NAV-DEBUG][widget] pathname push sent (${X.byteLength} bytes)`)}catch(X){console.warn("[NAV-DEBUG][widget] pathname push threw:",X)}const V=setTimeout(async()=>{var X,be,xe,G;console.log("[NAV-DEBUG][widget] settle timer fired (250ms after pathname-effect)");try{const x=(X=B.getRoom)==null?void 0:X.call(B),k=x==null?void 0:x.localParticipant;if(console.log(`[NAV-DEBUG][widget] settle-time state: room=${!!x} lp=${!!k} publishData=${!!(k!=null&&k.publishData)}`),!(k!=null&&k.publishData)){console.log("[NAV-DEBUG][widget] settle bailed: no publishData");return}const j=Ze(at.current);console.log(`[NAV-DEBUG][widget] page_context built: regions=${((be=j.regions)==null?void 0:be.length)??0} forms=${((xe=j.forms)==null?void 0:xe.length)??0} links=${((G=j.visibleLinks)==null?void 0:G.length)??0}`);try{const C=new TextEncoder().encode(JSON.stringify({type:"page_context_push",pathname:re,context:j}));k.publishData(C,{reliable:!0}),console.log(`[NAV-DEBUG][widget] page_context_push SENT (${C.byteLength} bytes)`)}catch(C){console.warn("[NAV-DEBUG][widget] page_context_push threw:",C)}try{const C=lt.current;let O=[];if(C){console.log("[NAV-DEBUG][widget] routes: calling custom getRoutes()");const N=C(),q=N instanceof Promise?await N:N;O=Array.isArray(q)?q.slice(0,200):[],console.log(`[NAV-DEBUG][widget] routes: custom returned ${O.length}`)}else console.log("[NAV-DEBUG][widget] routes: walking DOM (no custom getRoutes)"),O=Oe(),console.log(`[NAV-DEBUG][widget] routes: DOM walk returned ${O.length}`);const H=new TextEncoder().encode(JSON.stringify({type:"routes_push",routes:O}));k.publishData(H,{reliable:!0}),console.log(`[NAV-DEBUG][widget] routes_push SENT (${H.byteLength} bytes, ${O.length} routes)`)}catch(C){console.warn("[NAV-DEBUG][widget] routes_push threw:",C)}}catch(x){console.warn("[NAV-DEBUG][widget] settle outer threw:",x)}},250);return()=>{clearTimeout(V)}},[re,B,B.connectionState]),n.useEffect(()=>{var V;if(typeof window>"u")return;const m=((V=window.location)==null?void 0:V.hostname)||"";if(m==="localhost"||m==="127.0.0.1"||m==="0.0.0.0"||m.endsWith(".local")||m.endsWith(".test"))return window.__livelayerSimulateCommand=ae=>{try{Ge(ae)}catch(X){console.warn("[LiveLayer] simulate-command threw:",X)}},()=>{delete window.__livelayerSimulateCommand}},[Ge]);const y=n.useMemo(()=>W?{connectionState:W.connectionState,agentState:W.agentState,transcript:W.transcript,videoElement:W.videoElement,audioElement:W.audioElement,canResume:W.canResume,error:W.error,agentConfig:null,connect:async()=>{await W.onConnect()},disconnect:()=>W.onDisconnect(),getRoom:B.getRoom,isControlled:!0}:{connectionState:B.connectionState,agentState:B.agentState,transcript:B.transcript,videoElement:B.videoElement,audioElement:B.audioElement,canResume:B.canResume,error:B.error,agentConfig:B.agentConfig,connect:B.connect,disconnect:B.disconnect,getRoom:B.getRoom,isControlled:!1},[W,B]),Et=n.useRef(null);n.useEffect(()=>{const m=y.videoElement,u=Et.current;if(!(!m||!u))return u.appendChild(m),()=>{m.parentNode===u&&u.removeChild(m)}},[y.videoElement]),n.useEffect(()=>{const m=y.audioElement;if(!m)return;qe.attach(m);const u=m.play();return u&&typeof u.catch=="function"&&u.catch(V=>{(V==null?void 0:V.name)==="NotAllowedError"&&fe(!0)}),()=>{qe.detach()}},[y.audioElement]),n.useEffect(()=>{if(y.isControlled||y.connectionState!=="connected")return;const m=y.getRoom();if(m)return Z.setupMic(m,{startMuted:!0}).catch(()=>{}),ie.attachRoom(m),se.attachRoom(m),de.refresh(),()=>{Z.teardownMic(),ie.teardown(),se.teardown()}},[y.isControlled,y.connectionState]);const[Je,xt]=n.useState(!1),vt=n.useRef("idle");n.useEffect(()=>{if(y.connectionState==="idle"||y.connectionState==="disconnected"){xt(!1),vt.current="idle";return}!Je&&vt.current==="speaking"&&y.agentState!=="speaking"&&(xt(!0),Z.setMuted(!1)),vt.current=y.agentState},[y.agentState,y.connectionState,Je]),n.useEffect(()=>{if(y.connectionState!=="connected"||Je)return;const m=setTimeout(()=>{xt(!0),Z.setMuted(!1)},4e3);return()=>clearTimeout(m)},[y.connectionState,Je]),n.useEffect(()=>{const m=y.audioElement;m&&(m.muted=Ie)},[y.audioElement,Ie]);const xn=n.useCallback(m=>{const u=y.getRoom();if(u)try{const V=new TextEncoder().encode(JSON.stringify({type:"user_message",text:m}));u.localParticipant.publishData(V,{reliable:!0})}catch{}},[y]),vn=n.useCallback(()=>{it(m=>!m)},[]);n.useEffect(()=>{je==null||je(y.connectionState),y.connectionState==="connected"?ce==null||ce():y.connectionState==="disconnected"&&(we==null||we())},[y.connectionState,ce,we,je]),n.useEffect(()=>{Ce==null||Ce(y.transcript)},[y.transcript,Ce]),n.useEffect(()=>{Le==null||Le(y.agentState)},[y.agentState,Le]);const Ct=n.useRef(!1);n.useEffect(()=>{y.isControlled||!d||Ct.current||Ae&&y.connectionState==="idle"&&(Ct.current=!0,y.connect())},[d,y.connectionState,y,Ae]);const wn=n.useCallback(m=>{const u=L==null?void 0:L.find(V=>V.id===m);u&&(We(!1),m!==J&&(He(!0),y.disconnect(),Ue||De(m),v==null||v(u)))},[L,J,y,Ue,v]);n.useEffect(()=>{pe&&y.connectionState==="connected"&&He(!1)},[y.connectionState,pe]),n.useEffect(()=>{if(!Ve)return;const m=u=>{u.key==="Escape"&&We(!1)};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[Ve]);const _n=!!D||!!(Q!=null&&Q.avatarImageUrl)||y.isControlled,Ye=on(Me,i,_n);te===void 0&&((jt=Ye.info)!=null&&jt.capabilities)&&(bt.current=Ye.info.capabilities);const ut=(Q==null?void 0:Q.name)??P??((Nt=y.agentConfig)==null?void 0:Nt.name)??((Rt=Ye.info)==null?void 0:Rt.name)??"Live Layer",wt=(Q==null?void 0:Q.avatarImageUrl)??D??((At=y.agentConfig)==null?void 0:At.avatarImageUrl)??((Dt=Ye.info)==null?void 0:Dt.avatarImageUrl)??null,kn=_??((Mt=y.agentConfig)==null?void 0:Mt.idleLoopUrl)??((Tt=Ye.info)==null?void 0:Tt.idleLoopUrl)??null,Sn=I??null,En=n.useCallback(()=>ue("expanded"),[ue]),Cn=n.useCallback(()=>ue("minimized"),[ue]),Lt=n.useCallback(()=>{y.disconnect(),ue("hidden")},[y,ue]),Ln=n.useCallback(()=>{const m=y.audioElement;m&&m.play().then(()=>fe(!1)).catch(()=>{})},[y.audioElement]),jn=n.useCallback(()=>{fe(!1),y.connect()},[y]),Ke={...yt,zIndex:ot};g.primaryColor&&(Ke["--ll-color-primary"]=g.primaryColor),g.accentColor&&(Ke["--ll-color-accent"]=g.accentColor),g.backgroundColor&&(Ke["--ll-color-bg"]=g.backgroundColor),g.textColor&&(Ke["--ll-color-fg"]=g.textColor);const Nn=["ll-widget",`ll-widget--${oe}`,`ll-widget--${ke?"mobile":"desktop"}`,gt].filter(Boolean).join(" ");return Ae?t.jsxs("div",{className:Nn,style:Ke,"data-display-mode":oe,"data-position":w,children:[oe==="hidden"&&t.jsx(Jn,{position:w,isMobile:ke,isSpeaking:y.agentState==="speaking",onExpand:()=>ue("expanded"),label:`Open ${ut} widget`,avatarImageUrl:wt,agentName:ut}),oe==="minimized"&&t.jsx(Kn,{position:w,isMobile:ke,agentName:ut,avatarImageUrl:wt,agentState:y.agentState,isMuted:Z.isMuted,audioLevel:qe,onExpand:En,onToggleMute:Z.toggleMute,onClose:Lt}),oe==="expanded"&&t.jsx(Qn,{position:w,isMobile:ke,agentName:ut,avatarImageUrl:wt,idleLoopUrl:kn,greeting:Sn,branding:g,teamMembers:L,currentTeamMemberId:J,isSwitchingTeamMember:pe,teamSwitcherOpen:Ve,onToggleTeamSwitcher:()=>We(m=>!m),onSelectTeamMember:wn,connectionState:y.connectionState,agentState:y.agentState,transcript:y.transcript,isMuted:Z.isMuted,micDevices:de.mics,isCameraEnabled:ie.isEnabled,cameraPreviewEl:ie.previewEl,cameraDevices:de.cameras,activeCameraId:ie.activeDeviceId,isScreenShareEnabled:se.isEnabled,screenPreviewEl:se.previewEl,isSpeakerMuted:Ie,allowCamera:R,allowScreenShare:z,allowTyping:M,languageMenuOpen:he,onToggleLanguageMenu:()=>me(m=>!m),needsUserGesture:Te,canResume:y.canResume,micError:Z.micError,error:y.error,avatarVideoContainerRef:Et,agentVideoEl:y.videoElement,micGateOpen:y.isControlled?!0:Je,onConnect:()=>void y.connect(),onDisconnect:()=>y.disconnect(),onRetry:jn,onResumeAudio:Ln,onToggleMute:Z.toggleMute,onToggleCamera:()=>void ie.toggle(),onSwitchCameraDevice:m=>void ie.switchDevice(m),onToggleScreenShare:()=>void se.toggle(),onToggleSpeaker:vn,onSendMessage:xn,onMinimize:Cn,onClose:Lt,onClearMicError:Z.clearError})]}):null}function Sr(e){return t.jsx(Xt,{children:t.jsx(kr,{...e})})}const Er=({agentId:e,baseUrl:r,apiKey:o,mode:i,onAgentEvent:s,className:a,style:d})=>{const f=n.useRef(null),p=n.useRef(null),b=n.useRef(s);b.current=s;const w=n.useCallback(c=>{var S;const l=c.detail;(S=b.current)==null||S.call(b,l)},[]);return n.useEffect(()=>{const c=f.current;if(!c)return;const l=document.createElement("livelayer-widget");return l.setAttribute("agent-id",e),r&&l.setAttribute("base-url",r),o&&l.setAttribute("api-key",o),i&&l.setAttribute("mode",i),l.addEventListener("agent-event",w),c.appendChild(l),p.current=l,()=>{l.removeEventListener("agent-event",w),c.removeChild(l),p.current=null}},[e]),n.useEffect(()=>{p.current&&(i?p.current.setAttribute("mode",i):p.current.removeAttribute("mode"))},[i]),t.jsx("div",{ref:f,className:a,style:d})},Cr=n.forwardRef(function({id:r,intent:o,as:i="div",className:s,style:a,children:d},f){return n.createElement(i,{ref:f,"data-ll-region":r,"data-ll-intent":o,className:s,style:a},d)}),Lr=n.forwardRef(function({id:r,intent:o,children:i,...s},a){return t.jsx("form",{ref:a,"data-ll-form":r,"data-ll-intent":o,...s,children:i})}),jr=n.forwardRef(function(r,o){const{name:i,label:s,labelClassName:a}=r,d={name:i,"data-ll-field":i};let f;if("as"in r&&r.as==="textarea"){const{name:p,label:b,labelClassName:w,as:c,...l}=r;f=t.jsx("textarea",{ref:o,...d,...l})}else if("as"in r&&r.as==="select"){const{name:p,label:b,labelClassName:w,as:c,children:l,...S}=r;f=t.jsx("select",{ref:o,...d,...S,children:l})}else{const{name:p,label:b,labelClassName:w,as:c,...l}=r;f=t.jsx("input",{ref:o,...d,...l})}return s===void 0?f:t.jsxs("label",{className:a,children:[s,f]})});let Kt=1;function Nr({onMount:e,defaultOpen:r=!1,storageKey:o="ll-debug-open"}){const[i,s]=n.useState(r),[a,d]=n.useState([]),[f,p]=n.useState(""),[b,w]=n.useState(!1),c=n.useRef(new Set),l=n.useRef([]),S=n.useRef(b);S.current=b,n.useEffect(()=>{try{const v=localStorage.getItem(o);v==="1"&&s(!0),v==="0"&&s(!1)}catch{}},[o]),n.useEffect(()=>{try{localStorage.setItem(o,i?"1":"0")}catch{}},[i,o]),n.useEffect(()=>{const v=_=>{(_.metaKey||_.ctrlKey)&&_.shiftKey&&_.key.toLowerCase()==="l"&&(_.preventDefault(),s(I=>!I))};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[]),n.useEffect(()=>{const v=setInterval(()=>{if(l.current.length===0||S.current)return;const _=l.current.splice(0,l.current.length);d(I=>[..._.reverse(),...I].slice(0,200))},100);return()=>clearInterval(v)},[]);const L=n.useRef(!1);if(n.useEffect(()=>{!e||L.current||(L.current=!0,e(v=>{l.current.push({id:Kt++,ts:Date.now(),kind:"event",type:v.eventName,data:v.data})}))},[e]),n.useEffect(()=>{const v=console.warn,_=console.log,I=(D,P)=>function(...g){try{const R=typeof g[0]=="string"?g[0]:"";R.startsWith("[LiveLayer]")&&l.current.push({id:Kt++,ts:Date.now(),kind:D,type:R.slice(0,120),data:{args:g.slice(1).map(z=>Ar(z))}})}catch{}return P.apply(this,g)};return console.warn=I("warn",v),console.log=I("log",_),()=>{console.warn=v,console.log=_}},[]),!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 E=a.filter(v=>{if(!f)return!0;const _=f.toLowerCase();return v.type.toLowerCase().includes(_)||JSON.stringify(v.data||{}).toLowerCase().includes(_)});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:()=>w(v=>!v),style:_t(b?"#f59e0b":"transparent"),title:"Pause / resume capture",children:b?"▶ resume":"⏸ pause"}),t.jsx("button",{type:"button",onClick:()=>{d([]),l.current=[]},style:_t("transparent"),title:"Clear buffer",children:"clear"}),t.jsx("button",{type:"button",onClick:()=>s(!1),style:_t("transparent"),"aria-label":"Close",title:"Close (Cmd/Ctrl + Shift + L)",children:"✕"})]}),t.jsx("input",{type:"text",value:f,onChange:v=>p(v.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:E.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"
|
package/dist/index.mjs
CHANGED
|
@@ -58,7 +58,14 @@ function Ln(e) {
|
|
|
58
58
|
baseUrl: e.baseUrl,
|
|
59
59
|
apiKey: e.apiKey,
|
|
60
60
|
sessionEndpoint: e.sessionEndpoint,
|
|
61
|
-
sessionBody: e.sessionBody
|
|
61
|
+
sessionBody: e.sessionBody,
|
|
62
|
+
// useMicrophoneState owns the mic track. If we let the SDK
|
|
63
|
+
// also publish, livekit-client logs "publishing a second track
|
|
64
|
+
// with the same source: microphone" and renegotiates the
|
|
65
|
+
// publisher PC, which closes the data channel — every later
|
|
66
|
+
// publishData throws "PC manager is closed". That breaks the
|
|
67
|
+
// pathname / page_context / routes pushes the agent depends on.
|
|
68
|
+
manageMic: !1
|
|
62
69
|
},
|
|
63
70
|
I
|
|
64
71
|
);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@livelayer/react",
|
|
3
|
-
"version": "0.5.24-debug.
|
|
3
|
+
"version": "0.5.24-debug.2",
|
|
4
4
|
"description": "LiveLayer agent widget for React — avatar video, team switching, responsive layouts, full-fidelity embed",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"module": "dist/index.mjs",
|
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
},
|
|
23
23
|
"dependencies": {
|
|
24
24
|
"livekit-client": "^2.17.3",
|
|
25
|
-
"@livelayer/sdk": "0.3.
|
|
25
|
+
"@livelayer/sdk": "0.3.7"
|
|
26
26
|
},
|
|
27
27
|
"devDependencies": {
|
|
28
28
|
"@testing-library/dom": "^10.4.1",
|