@characterxyz/widget 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -65,6 +65,7 @@ The defaults come from the key (set on the Embed page); anything passed here ove
65
65
  | `accent`, `mode`, `radius`, `font` | Colour, `auto` · `light` · `dark`, corner radius, font family |
66
66
  | `showChat`, `showCall`, `branding` | Turn chat, calls or the footer off |
67
67
  | `offsetX`, `offsetY`, `zIndex`, `container` | Placement |
68
+ | `movable` | Visitors can drag her anywhere along the bottom (hold first on touch); let go higher up and she falls back down. The chat then opens from where she stands. Off by default |
68
69
 
69
70
  What the agent says (persona, knowledge, greeting) is the agent's own, set in Character XYZ.
70
71
 
package/dist/cx.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var CharacterXYZWidget=(()=>{var ze=Object.defineProperty;var ii=Object.getOwnPropertyDescriptor;var ai=Object.getOwnPropertyNames;var ri=Object.prototype.hasOwnProperty;var si=(t,e,n)=>e in t?ze(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var oi=(t,e)=>{for(var n in e)ze(t,n,{get:e[n],enumerable:!0})},li=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of ai(e))!ri.call(t,a)&&a!==n&&ze(t,a,{get:()=>e[a],enumerable:!(i=ii(e,a))||i.enumerable});return t};var ci=t=>li(ze({},"__esModule",{value:!0}),t);var j=(t,e,n)=>si(t,typeof e!="symbol"?e+"":e,n);var ga={};oi(ga,{mount:()=>Ge});var de={position:"bottom-right",mode:"auto",launcher:"bubble",display:"bubble",accent:"#7c5cff",radius:24,font:"",subtitle:null,greeting:"",greetingDelay:3,suggestions:[],placeholder:"Message",showChat:!0,showCall:!0,branding:!0,offsetX:20,offsetY:20,zIndex:2147483e3,open:!1,face:!0,faceUrl:"https://www.character.xyz/embed/face"},ke=(t,e,n)=>{let i=typeof t=="number"?t:typeof t=="string"&&t.trim()!==""?Number(t):NaN;return Number.isFinite(i)?Math.min(n,Math.max(e,i)):void 0},we=t=>{if(typeof t=="boolean")return t;if(t==="true"||t===""||t==="1")return!0;if(t==="false"||t==="0")return!1},ut=(t,e=200)=>typeof t=="string"?t.slice(0,e):void 0;function di(t){if(typeof t!="string")return;let e=t.trim();if(/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(e)||/^(rgb|rgba|hsl|hsla|oklch|oklab)\([0-9.,%\s/+-]+\)$/i.test(e)||/^[a-z]{3,20}$/i.test(e))return e}function pi(t){if(typeof t!="string")return;let e=t.trim();return/^[\w\s,"'-]{1,120}$/.test(e)?e:void 0}function fe(t,e){if(!e||typeof e!="object")return t;let n={...t};return(e.position==="bottom-left"||e.position==="bottom-right")&&(n.position=e.position),(e.mode==="light"||e.mode==="dark"||e.mode==="auto")&&(n.mode=e.mode),(e.launcher==="bubble"||e.launcher==="actions")&&(n.launcher=e.launcher),(e.display==="bubble"||e.display==="half"||e.display==="full")&&(n.display=e.display),n.accent=di(e.accent)??n.accent,n.radius=ke(e.radius,0,40)??n.radius,n.font=pi(e.font)??n.font,e.subtitle===null?n.subtitle=null:n.subtitle=ut(e.subtitle,80)??n.subtitle,n.greeting=ut(e.greeting,160)??n.greeting,n.greetingDelay=ke(e.greetingDelay,0,120)??n.greetingDelay,Array.isArray(e.suggestions)?n.suggestions=e.suggestions.filter(i=>typeof i=="string"&&i.trim()!=="").map(i=>i.slice(0,80)).slice(0,4):typeof e.suggestions=="string"&&(n.suggestions=e.suggestions.split("|").map(i=>i.trim()).filter(Boolean).slice(0,4)),n.placeholder=ut(e.placeholder,60)??n.placeholder,n.showChat=we(e.showChat)??n.showChat,n.showCall=we(e.showCall)??n.showCall,n.branding=we(e.branding)??n.branding,n.offsetX=ke(e.offsetX,0,200)??n.offsetX,n.offsetY=ke(e.offsetY,0,200)??n.offsetY,n.zIndex=ke(e.zIndex,0,2147483647)??n.zIndex,n.open=we(e.open)??n.open,n.face=we(e.face)??n.face,typeof e.faceUrl=="string"&&/^https?:\/\/[^\s"'<>]+$/.test(e.faceUrl.trim())&&(n.faceUrl=e.faceUrl.trim()),n}function De(t){let e={};for(let{name:n,value:i}of t){let a=n.replace(/^data-/,"").replace(/-([a-z])/g,(s,o)=>o.toUpperCase());e[a]=i}return e}var ui=Object.defineProperty,hi=(t,e,n)=>e in t?ui(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,y=(t,e,n)=>hi(t,typeof e!="symbol"?e+"":e,n),ge=null;function Pt(){return(!ge||ge.state==="closed")&&(ge=new AudioContext({latencyHint:"interactive"})),ge.state==="suspended"&&ge.resume().catch(()=>{}),ge}var fi=class{constructor(t={}){y(this,"opts",t),y(this,"ctx"),y(this,"gain"),y(this,"analyser"),y(this,"data"),y(this,"nextAt",0),y(this,"started",!1),y(this,"ended",!1),y(this,"finishing",!1),y(this,"sources",new Set),y(this,"startedAt",0),y(this,"sampleRate"),this.ctx=Pt(),this.sampleRate=t.sampleRate??16e3,this.gain=this.ctx.createGain(),this.gain.gain.value=t.volume??1,this.analyser=this.ctx.createAnalyser(),this.analyser.fftSize=512,this.data=new Uint8Array(new ArrayBuffer(this.analyser.fftSize)),this.gain.connect(this.analyser).connect(this.ctx.destination)}enqueue(t){if(this.ended||t.byteLength<2)return;let e=Math.floor(t.byteLength/2),n=new DataView(t.buffer,t.byteOffset,e*2),i=this.ctx.createBuffer(1,e,this.sampleRate),a=i.getChannelData(0);for(let l=0;l<e;l++)a[l]=n.getInt16(l*2,!0)/32768;let s=this.ctx.createBufferSource();s.buffer=i,s.connect(this.gain);let o=this.ctx.currentTime;if(this.nextAt<o&&(this.nextAt=o+(this.started?.02:.12)),s.start(this.nextAt),!this.started){this.started=!0;let l=Math.max(0,(this.nextAt-o)*1e3);this.startedAt=performance.now()+l,setTimeout(()=>this.opts.onStart?.(),l)}this.nextAt+=i.duration,this.sources.add(s),s.onended=()=>{this.sources.delete(s),this.finishing&&this.sources.size===0&&this.finish()}}end(){this.finishing=!0,this.sources.size===0&&this.finish()}stop(){this.ended=!0;for(let t of this.sources)try{t.stop()}catch{}this.sources.clear(),this.gain.disconnect()}playedMs(){return this.started?Math.max(0,performance.now()-this.startedAt):0}level(){this.analyser.getByteTimeDomainData(this.data);let t=0;for(let e=0;e<this.data.length;e++){let n=(this.data[e]-128)/128;t+=n*n}return Math.min(1,Math.sqrt(t/this.data.length)*3)}finish(){this.ended||(this.ended=!0,this.gain.disconnect(),this.opts.onEnd?.())}},gi=`
1
+ "use strict";var CharacterXYZWidget=(()=>{var Pe=Object.defineProperty;var ci=Object.getOwnPropertyDescriptor;var di=Object.getOwnPropertyNames;var ui=Object.prototype.hasOwnProperty;var pi=(e,t,n)=>t in e?Pe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var hi=(e,t)=>{for(var n in t)Pe(e,n,{get:t[n],enumerable:!0})},fi=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of di(t))!ui.call(e,a)&&a!==n&&Pe(e,a,{get:()=>t[a],enumerable:!(i=ci(t,a))||i.enumerable});return e};var gi=e=>fi(Pe({},"__esModule",{value:!0}),e);var X=(e,t,n)=>pi(e,typeof t!="symbol"?t+"":t,n);var Ma={};hi(Ma,{mount:()=>et});var ue={position:"bottom-right",mode:"auto",launcher:"bubble",display:"bubble",accent:"#7c5cff",radius:24,font:"",subtitle:null,greeting:"",greetingDelay:3,suggestions:[],placeholder:"Message",showChat:!0,showCall:!0,branding:!0,offsetX:20,offsetY:20,zIndex:2147483e3,open:!1,face:!0,faceUrl:"https://www.character.xyz/embed/face",movable:!1},Ce=(e,t,n)=>{let i=typeof e=="number"?e:typeof e=="string"&&e.trim()!==""?Number(e):NaN;return Number.isFinite(i)?Math.min(n,Math.max(t,i)):void 0},ge=e=>{if(typeof e=="boolean")return e;if(e==="true"||e===""||e==="1")return!0;if(e==="false"||e==="0")return!1},ft=(e,t=200)=>typeof e=="string"?e.slice(0,t):void 0;function mi(e){if(typeof e!="string")return;let t=e.trim();if(/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(t)||/^(rgb|rgba|hsl|hsla|oklch|oklab)\([0-9.,%\s/+-]+\)$/i.test(t)||/^[a-z]{3,20}$/i.test(t))return t}function xi(e){if(typeof e!="string")return;let t=e.trim();return/^[\w\s,"'-]{1,120}$/.test(t)?t:void 0}function me(e,t){if(!t||typeof t!="object")return e;let n={...e};return(t.position==="bottom-left"||t.position==="bottom-right")&&(n.position=t.position),(t.mode==="light"||t.mode==="dark"||t.mode==="auto")&&(n.mode=t.mode),(t.launcher==="bubble"||t.launcher==="actions")&&(n.launcher=t.launcher),(t.display==="bubble"||t.display==="half"||t.display==="full")&&(n.display=t.display),n.accent=mi(t.accent)??n.accent,n.radius=Ce(t.radius,0,40)??n.radius,n.font=xi(t.font)??n.font,t.subtitle===null?n.subtitle=null:n.subtitle=ft(t.subtitle,80)??n.subtitle,n.greeting=ft(t.greeting,160)??n.greeting,n.greetingDelay=Ce(t.greetingDelay,0,120)??n.greetingDelay,Array.isArray(t.suggestions)?n.suggestions=t.suggestions.filter(i=>typeof i=="string"&&i.trim()!=="").map(i=>i.slice(0,80)).slice(0,4):typeof t.suggestions=="string"&&(n.suggestions=t.suggestions.split("|").map(i=>i.trim()).filter(Boolean).slice(0,4)),n.placeholder=ft(t.placeholder,60)??n.placeholder,n.showChat=ge(t.showChat)??n.showChat,n.showCall=ge(t.showCall)??n.showCall,n.branding=ge(t.branding)??n.branding,n.offsetX=Ce(t.offsetX,0,200)??n.offsetX,n.offsetY=Ce(t.offsetY,0,200)??n.offsetY,n.zIndex=Ce(t.zIndex,0,2147483647)??n.zIndex,n.open=ge(t.open)??n.open,n.face=ge(t.face)??n.face,n.movable=ge(t.movable)??n.movable,typeof t.faceUrl=="string"&&/^https?:\/\/[^\s"'<>]+$/.test(t.faceUrl.trim())&&(n.faceUrl=t.faceUrl.trim()),n}function ze(e){let t={};for(let{name:n,value:i}of e){let a=n.replace(/^data-/,"").replace(/-([a-z])/g,(s,o)=>o.toUpperCase());t[a]=i}return t}var _i=Object.defineProperty,vi=(e,t,n)=>t in e?_i(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,k=(e,t,n)=>vi(e,typeof t!="symbol"?t+"":t,n),xe=null;function Ht(){return(!xe||xe.state==="closed")&&(xe=new AudioContext({latencyHint:"interactive"})),xe.state==="suspended"&&xe.resume().catch(()=>{}),xe}var bi=class{constructor(e={}){k(this,"opts",e),k(this,"ctx"),k(this,"gain"),k(this,"analyser"),k(this,"data"),k(this,"nextAt",0),k(this,"started",!1),k(this,"ended",!1),k(this,"finishing",!1),k(this,"sources",new Set),k(this,"startedAt",0),k(this,"sampleRate"),this.ctx=Ht(),this.sampleRate=e.sampleRate??16e3,this.gain=this.ctx.createGain(),this.gain.gain.value=e.volume??1,this.analyser=this.ctx.createAnalyser(),this.analyser.fftSize=512,this.data=new Uint8Array(new ArrayBuffer(this.analyser.fftSize)),this.gain.connect(this.analyser).connect(this.ctx.destination)}enqueue(e){if(this.ended||e.byteLength<2)return;let t=Math.floor(e.byteLength/2),n=new DataView(e.buffer,e.byteOffset,t*2),i=this.ctx.createBuffer(1,t,this.sampleRate),a=i.getChannelData(0);for(let l=0;l<t;l++)a[l]=n.getInt16(l*2,!0)/32768;let s=this.ctx.createBufferSource();s.buffer=i,s.connect(this.gain);let o=this.ctx.currentTime;if(this.nextAt<o&&(this.nextAt=o+(this.started?.02:.12)),s.start(this.nextAt),!this.started){this.started=!0;let l=Math.max(0,(this.nextAt-o)*1e3);this.startedAt=performance.now()+l,setTimeout(()=>this.opts.onStart?.(),l)}this.nextAt+=i.duration,this.sources.add(s),s.onended=()=>{this.sources.delete(s),this.finishing&&this.sources.size===0&&this.finish()}}end(){this.finishing=!0,this.sources.size===0&&this.finish()}stop(){this.ended=!0;for(let e of this.sources)try{e.stop()}catch{}this.sources.clear(),this.gain.disconnect()}playedMs(){return this.started?Math.max(0,performance.now()-this.startedAt):0}level(){this.analyser.getByteTimeDomainData(this.data);let e=0;for(let t=0;t<this.data.length;t++){let n=(this.data[t]-128)/128;e+=n*n}return Math.min(1,Math.sqrt(e/this.data.length)*3)}finish(){this.ended||(this.ended=!0,this.gain.disconnect(),this.opts.onEnd?.())}},yi=`
2
2
  class CxyzMic extends AudioWorkletProcessor {
3
3
  constructor(o) {
4
4
  super();
@@ -30,16 +30,16 @@ class CxyzMic extends AudioWorkletProcessor {
30
30
  }
31
31
  }
32
32
  registerProcessor('cxyz-mic', CxyzMic);
33
- `;function mi(t){let e=new Int16Array(t);if(!e.length)return 0;let n=0;for(let i=0;i<e.length;i++){let a=e[i]/32768;n+=a*a}return Math.sqrt(n/e.length)}async function _i(t){if(!navigator.mediaDevices?.getUserMedia)throw new Error("This browser cannot use a microphone here.");let e=await navigator.mediaDevices.getUserMedia({audio:{deviceId:t.deviceId?{exact:t.deviceId}:void 0,channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}}),n=new AudioContext({latencyHint:"interactive"}),i=n.createMediaStreamSource(e),a=!1,s=d=>{if(a){t.onFrame(new ArrayBuffer(d.byteLength),0);return}t.onFrame(d,mi(d))},o,l;try{let d=URL.createObjectURL(new Blob([gi],{type:"application/javascript"}));try{await n.audioWorklet.addModule(d)}finally{URL.revokeObjectURL(d)}let f=new AudioWorkletNode(n,"cxyz-mic");f.port.onmessage=_=>s(_.data),o=f,l=()=>{f.port.onmessage=null}}catch{let d=n.createScriptProcessor(4096,1,1),f=n.sampleRate/16e3,_=0,c=new Int16Array(480),g=0;d.onaudioprocess=b=>{let x=b.inputBuffer.getChannelData(0);for(let m=0;m<x.length;m++)if(_+=1,_>=f){_-=f;let k=Math.max(-1,Math.min(1,x[m]));c[g++]=k<0?k*32768:k*32767,g===480&&(s(c.buffer),c=new Int16Array(480),g=0)}},o=d,l=()=>{d.onaudioprocess=null}}i.connect(o);let p=n.createGain();return p.gain.value=0,o.connect(p).connect(n.destination),n.state==="suspended"&&await n.resume().catch(()=>{}),{get muted(){return a},setMuted(d){a=d;for(let f of e.getAudioTracks())f.enabled=!d},stop(){l();try{i.disconnect(),o.disconnect()}catch{}for(let d of e.getTracks())d.stop();n.close().catch(()=>{})}}}var ht=class{constructor(){y(this,"handlers",{})}on(t,e){var n;return((n=this.handlers)[t]??(n[t]=new Set)).add(e),()=>this.handlers[t]?.delete(e)}emit(t,e){for(let n of this.handlers[t]??[])try{n(e)}catch(i){console.error("[characterxyz] listener threw",i)}}clear(){this.handlers={}}},P=class extends Error{constructor(t,e,n=0,i={}){super(e),y(this,"code"),y(this,"status"),y(this,"fields"),this.name="CxError",this.code=t,this.status=n,this.fields=i}};function xi(t){switch(t){case 401:return"unauthorized";case 403:return"forbidden";case 404:return"not_found";case 402:return"payment_required";case 422:return"invalid";case 429:return"rate_limited";case 503:return"unavailable";default:return"unknown"}}async function bi(t){let e="",n={};try{let i=await t.json();typeof i?.message=="string"&&(e=i.message);for(let a of Array.isArray(i?.errors)?i.errors:[])typeof a?.path=="string"&&typeof a?.message=="string"&&(n[a.path]=a.message)}catch{}return new P(xi(t.status),e||`Request failed (${t.status})`,t.status,n)}async function Ce(t,e,n={}){let i={};n.body!==void 0&&(i["Content-Type"]="application/json"),n.token&&(i.Authorization=`Bearer ${n.token}`);let a;try{a=await fetch(t+e,{method:n.method??(n.body===void 0?"GET":"POST"),headers:i,body:n.body===void 0?void 0:JSON.stringify(n.body),signal:n.signal,keepalive:n.keepalive,credentials:"omit",cache:"no-store"})}catch(s){throw s?.name==="AbortError"?s:new P("network","Could not reach Character XYZ. Check your connection.")}if(!a.ok)throw await bi(a);return a}async function X(t,e,n={}){return(await(await Ce(t,e,n)).json()).data}async function Ut(t,e,n){let i=t.body;if(!i)return;let a=i.getReader(),s=new TextDecoder,o="",l=()=>{a.cancel().catch(()=>{})};n?.addEventListener("abort",l);try{for(;;){let{value:p,done:d}=await a.read();if(d)break;o+=s.decode(p,{stream:!0}),o=zt(o,e)}o+=s.decode(),zt(o+`
33
+ `;function ki(e){let t=new Int16Array(e);if(!t.length)return 0;let n=0;for(let i=0;i<t.length;i++){let a=t[i]/32768;n+=a*a}return Math.sqrt(n/t.length)}async function wi(e){if(!navigator.mediaDevices?.getUserMedia)throw new Error("This browser cannot use a microphone here.");let t=await navigator.mediaDevices.getUserMedia({audio:{deviceId:e.deviceId?{exact:e.deviceId}:void 0,channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}}),n=new AudioContext({latencyHint:"interactive"}),i=n.createMediaStreamSource(t),a=!1,s=c=>{if(a){e.onFrame(new ArrayBuffer(c.byteLength),0);return}e.onFrame(c,ki(c))},o,l;try{let c=URL.createObjectURL(new Blob([yi],{type:"application/javascript"}));try{await n.audioWorklet.addModule(c)}finally{URL.revokeObjectURL(c)}let f=new AudioWorkletNode(n,"cxyz-mic");f.port.onmessage=x=>s(x.data),o=f,l=()=>{f.port.onmessage=null}}catch{let c=n.createScriptProcessor(4096,1,1),f=n.sampleRate/16e3,x=0,d=new Int16Array(480),g=0;c.onaudioprocess=b=>{let v=b.inputBuffer.getChannelData(0);for(let m=0;m<v.length;m++)if(x+=1,x>=f){x-=f;let _=Math.max(-1,Math.min(1,v[m]));d[g++]=_<0?_*32768:_*32767,g===480&&(s(d.buffer),d=new Int16Array(480),g=0)}},o=c,l=()=>{c.onaudioprocess=null}}i.connect(o);let u=n.createGain();return u.gain.value=0,o.connect(u).connect(n.destination),n.state==="suspended"&&await n.resume().catch(()=>{}),{get muted(){return a},setMuted(c){a=c;for(let f of t.getAudioTracks())f.enabled=!c},stop(){l();try{i.disconnect(),o.disconnect()}catch{}for(let c of t.getTracks())c.stop();n.close().catch(()=>{})}}}var gt=class{constructor(){k(this,"handlers",{})}on(e,t){var n;return((n=this.handlers)[e]??(n[e]=new Set)).add(t),()=>this.handlers[e]?.delete(t)}emit(e,t){for(let n of this.handlers[e]??[])try{n(t)}catch(i){console.error("[characterxyz] listener threw",i)}}clear(){this.handlers={}}},Y=class extends Error{constructor(e,t,n=0,i={}){super(t),k(this,"code"),k(this,"status"),k(this,"fields"),this.name="CxError",this.code=e,this.status=n,this.fields=i}};function Ci(e){switch(e){case 401:return"unauthorized";case 403:return"forbidden";case 404:return"not_found";case 402:return"payment_required";case 422:return"invalid";case 429:return"rate_limited";case 503:return"unavailable";default:return"unknown"}}async function Si(e){let t="",n={};try{let i=await e.json();typeof i?.message=="string"&&(t=i.message);for(let a of Array.isArray(i?.errors)?i.errors:[])typeof a?.path=="string"&&typeof a?.message=="string"&&(n[a.path]=a.message)}catch{}return new Y(Ci(e.status),t||`Request failed (${e.status})`,e.status,n)}async function Se(e,t,n={}){let i={};n.body!==void 0&&(i["Content-Type"]="application/json"),n.token&&(i.Authorization=`Bearer ${n.token}`);let a;try{a=await fetch(e+t,{method:n.method??(n.body===void 0?"GET":"POST"),headers:i,body:n.body===void 0?void 0:JSON.stringify(n.body),signal:n.signal,keepalive:n.keepalive,credentials:"omit",cache:"no-store"})}catch(s){throw s?.name==="AbortError"?s:new Y("network","Could not reach Character XYZ. Check your connection.")}if(!a.ok)throw await Si(a);return a}async function G(e,t,n={}){return(await(await Se(e,t,n)).json()).data}async function Wt(e,t,n){let i=e.body;if(!i)return;let a=i.getReader(),s=new TextDecoder,o="",l=()=>{a.cancel().catch(()=>{})};n?.addEventListener("abort",l);try{for(;;){let{value:u,done:c}=await a.read();if(c)break;o+=s.decode(u,{stream:!0}),o=Ut(o,t)}o+=s.decode(),Ut(o+`
34
34
 
35
- `,e)}finally{n?.removeEventListener("abort",l)}}function zt(t,e){let n=t.replace(/\r\n/g,`
35
+ `,t)}finally{n?.removeEventListener("abort",l)}}function Ut(e,t){let n=e.replace(/\r\n/g,`
36
36
  `),i;for(;(i=n.indexOf(`
37
37
 
38
- `))!==-1;){let a=n.slice(0,i);n=n.slice(i+2);let s="message",o=[];for(let d of a.split(`
39
- `)){if(!d||d.startsWith(":"))continue;let f=d.indexOf(":"),_=f===-1?d:d.slice(0,f),c=f===-1?"":d.slice(f+1).replace(/^ /,"");_==="event"?s=c:_==="data"&&o.push(c)}if(!o.length)continue;let l=o.join(`
40
- `),p=l;try{p=JSON.parse(l)}catch{}e({event:s,data:p})}return n}function vi(t){if(t.byteLength<25)return null;let e=new DataView(t);if(e.getUint8(0)!==67||e.getUint8(1)!==88||e.getUint8(2)!==89||e.getUint8(3)!==90||e.getUint8(4)!==1)return null;let n=e.getUint8(5),i=(e.getUint8(6)&1)!==0,a=7,s=e.getUint16(a,!0);if(a+=2,a+s+20>t.byteLength)return null;let o=new TextDecoder().decode(new Uint8Array(t,a,s));a+=s+4+8+4;let l=e.getUint32(a,!0);return a+=4,a+l>t.byteLength?null:{kind:n,final:i,corr:o,payload:new Uint8Array(t,a,l)}}var yi=.09,ki=350,wi=25e3,Ci=()=>({phase:"idle",callId:null,position:null,etaSeconds:null,holdSeconds:null,maxSeconds:null,startedAt:null,endReason:null,muted:!1,speaking:!1,agentState:"idle",error:null}),Si=class extends ht{constructor(t,e,n,i={}){super(),y(this,"apiUrl",t),y(this,"session",e),y(this,"agentId",n),y(this,"opts",i),y(this,"s",Ci()),y(this,"ticket",null),y(this,"eventsAbort",null),y(this,"ws",null),y(this,"mic",null),y(this,"players",new Map),y(this,"sampleRates",new Map),y(this,"cancelled",new Set),y(this,"speakingCorr",null),y(this,"heartbeat",null),y(this,"loudSince",null)}get state(){return this.s}audible(){let t=this.speakingCorr,e=t?this.players.get(t):void 0;return t&&e?{corr:t,ms:e.playedMs()}:null}voiceLevel(){let t=this.speakingCorr?this.players.get(this.speakingCorr):void 0;return t?t.level():0}set(t){this.s={...this.s,...t},this.emit("state",this.s)}async start(){if(this.s.phase==="idle"){this.set({phase:"joining"}),Pt();try{this.mic=await _i({deviceId:this.opts.deviceId,onFrame:(t,e)=>this.onMicFrame(t,e)})}catch{this.finish("mic-denied","Allow the microphone to talk, or chat instead.");return}try{let t=await this.session.token(),e=await X(this.apiUrl,"/sdk/v1/calls",{method:"POST",body:{},token:t});this.set({callId:e.callId,phase:e.state==="ready"?"joining":"queued",position:e.position??null,etaSeconds:e.etaSeconds??null}),this.follow()}catch(t){let e=t instanceof P?t:new P("unknown","Could not start the call."),n=e.code==="rate_limited"?"busy":"unavailable";this.finish(n,e.message),this.emit("error",e)}}}async follow(){let t=0;for(;this.s.callId&&this.s.phase!=="ended"&&this.s.phase!=="idle";){this.eventsAbort=new AbortController;try{let e=await this.session.token(),n=await Ce(this.apiUrl,`/sdk/v1/calls/${encodeURIComponent(this.s.callId)}/events`,{token:e,signal:this.eventsAbort.signal});t=0,await Ut(n,i=>this.onServerEvent(i.event,i.data),this.eventsAbort.signal)}catch(e){if(e?.name==="AbortError")return;if(e instanceof P&&e.code==="not_found"){this.finish("failed","The call ended.");return}if(t+=1,t>5){this.finish("failed","Lost the connection to the call.");return}}if(this.ended())return;await new Promise(e=>setTimeout(e,Math.min(4e3,500*2**t)))}}onServerEvent(t,e){switch(t){case"queued":(this.s.phase==="joining"||this.s.phase==="queued")&&this.set({phase:"queued",position:Number(e.position)||1,etaSeconds:Number(e.etaSeconds)||null});break;case"ready":{typeof e.ticket=="string"&&e.ticket&&(this.ticket=e.ticket);let n=Number(e.holdSeconds)||0;this.s.phase!=="ready"&&this.s.phase!=="connecting"&&this.s.phase!=="live"?(this.set({phase:"ready",holdSeconds:n,position:null,etaSeconds:null}),this.emit("ready",{holdSeconds:n}),this.opts.autoAccept!==!1&&this.accept()):this.s.phase==="ready"&&this.set({holdSeconds:n});break}case"live":this.set({phase:"live",maxSeconds:Number(e.maxSeconds)||null,startedAt:this.s.startedAt??Date.now()-(Number(e.elapsedSeconds)||0)*1e3});break;case"ended":this.finish(String(e.reason||"hangup")||"hangup",null);break}}ended(){return this.s.phase==="ended"}accept(){if(this.s.phase!=="ready"||!this.ticket||this.ws)return;this.set({phase:"connecting"});let t=this.apiUrl.replace(/^http/,"ws")+"/sdk/v1/calls/socket",e=new WebSocket(t,[`cxyz-ticket.${this.ticket}`]);this.ticket=null,e.binaryType="arraybuffer",this.ws=e,e.onopen=()=>{let n=this.opts.face,i=n?.emotion?.()??null;e.send(JSON.stringify({type:"agent_identity",agent_id:this.agentId,skin_index:0,blendshapes:!!n,...n?{blendshape_stream:!0}:{},...n&&i?{face_emotion:i}:{}})),e.send(JSON.stringify({type:"mic_state",silero:"off",denoise:!1})),this.heartbeat=setInterval(()=>this.sendJson({type:"heartbeat"}),wi),this.set({phase:"live",startedAt:this.s.startedAt??Date.now()})},e.onmessage=n=>this.onSocket(n.data),e.onclose=()=>{this.ws=null,setTimeout(()=>{(this.s.phase==="live"||this.s.phase==="connecting")&&this.finish("hangup",null)},1500)}}sendJson(t){this.ws?.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify(t))}onMicFrame(t,e){let n=this.ws;if(!(!n||n.readyState!==WebSocket.OPEN)){if(this.speakingCorr){let i=performance.now();if(e>yi){if(this.loudSince??(this.loudSince=i),i-this.loudSince>=ki){this.loudSince=null,this.interrupt(),n.send(t);return}}else this.loudSince=null;n.send(new ArrayBuffer(t.byteLength));return}n.send(t)}}onSocket(t){if(t instanceof ArrayBuffer){let n=vi(t);if(!n||this.cancelled.has(n.corr))return;if(n.kind===3){this.opts.face&&this.emit("face",{corr:n.corr,payload:n.payload.slice()});return}if(n.kind!==1)return;let i=this.players.get(n.corr);if(!i){for(let[s,o]of this.players)o.stop(),this.players.delete(s);let a=n.corr;i=new fi({sampleRate:this.sampleRates.get(a)??16e3,onStart:()=>{this.speakingCorr=a,this.set({speaking:!0}),this.emit("line",{corr:a,event:"audible"}),this.sendJson({type:"playback_started",correlationId:a,timestampMs:Date.now()})},onEnd:()=>{this.players.delete(a),this.speakingCorr===a&&(this.speakingCorr=null),this.set({speaking:!1}),this.emit("line",{corr:a,event:"end"}),this.sendJson({type:"playback_ended",correlationId:a,timestampMs:Date.now(),reason:"natural"}),this.sendJson({type:"speech_ended"})}}),this.players.set(a,i)}i.enqueue(n.payload),n.final&&i.end();return}if(typeof t!="string")return;let e;try{e=JSON.parse(t)}catch{return}if("AgentSpeechMeta"in e){let n=e.AgentSpeechMeta;n?.correlation_id&&n.sample_rate&&this.sampleRates.set(n.correlation_id,n.sample_rate);return}if("InteractorTranscript"in e){let n=e.InteractorTranscript;n?.text&&this.emit("caption",{id:`v:${n.correlation_id}`,role:"visitor",text:n.text});return}if("AgentReplyTranscript"in e){let n=e.AgentReplyTranscript;n?.text&&!this.cancelled.has(n.correlation_id)&&this.emit("caption",{id:`a:${n.correlation_id}`,role:"agent",text:n.text});return}if(e.type==="turn_cancelled"&&typeof e.correlationId=="string"){let n=e.correlationId;this.cancelled.add(n),this.players.get(n)?.stop(),this.players.delete(n),this.emit("line",{corr:n,event:"end"}),this.speakingCorr===n&&(this.speakingCorr=null,this.set({speaking:!1})),this.emit("captionRemoved",`a:${n}`);return}e.kind==="agent_status"&&typeof e.state=="string"&&this.set({agentState:e.state.toLowerCase()})}interrupt(){let t=this.speakingCorr;if(!t)return;let e=this.players.get(t),n=Math.round(e?.playedMs()??0);e?.stop(),this.players.delete(t),this.cancelled.add(t),this.speakingCorr=null,this.set({speaking:!1}),this.emit("line",{corr:t,event:"end"}),this.sendJson({type:"playback_ended",correlationId:t,timestampMs:Date.now(),reason:"interrupted"}),this.sendJson({type:"interrupt",correlationId:t,heardMs:n,timestampMs:Date.now()})}setMuted(t){this.mic?.setMuted(t),this.set({muted:t})}async hangUp(){let t=this.s.callId,e=this.s.phase;if(this.finish(e==="live"?"hangup":"left",null),!!t)try{let n=await this.session.token();await Ce(this.apiUrl,`/sdk/v1/calls/${encodeURIComponent(t)}`,{method:"DELETE",token:n})}catch{}}finish(t,e){if(this.s.phase==="ended")return;this.eventsAbort?.abort(),this.eventsAbort=null,this.heartbeat&&clearInterval(this.heartbeat),this.heartbeat=null;for(let i of this.players.values())i.stop();this.players.clear(),this.speakingCorr=null,this.mic?.stop(),this.mic=null;let n=this.ws;this.ws=null,n&&n.readyState<=WebSocket.OPEN&&n.close(1e3),this.ticket=null,this.set({phase:"ended",endReason:t,speaking:!1,holdSeconds:null,error:e})}},Ti=0,Dt=t=>`${t}_${Date.now().toString(36)}_${(Ti++).toString(36)}`,Ai=class extends ht{constructor(t,e){super(),y(this,"apiUrl",t),y(this,"session",e),y(this,"list",[]),y(this,"loaded",!1),y(this,"busy",!1),y(this,"abort",null)}get messages(){return this.list}get isBusy(){return this.busy}publish(){this.list=[...this.list],this.emit("messages",this.list)}applySiteEvent(t){let e=!1;t.event&&!this.list.some(n=>n.id===t.event.id)&&(this.list.push(t.event),e=!0),t.message&&!this.list.some(n=>n.id===t.message.id)&&(this.list.push({...t.message,...t.suggestions?.length?{suggestions:t.suggestions}:{},...t.askDetails?{askDetails:t.askDetails}:{}}),e=!0),e&&this.publish()}async load(){if(this.loaded)return this.list;let t=await this.session.token(),e=await X(this.apiUrl,"/sdk/v1/chat/messages?limit=50",{token:t}),n=this.list;return this.list=[...e?.messages??[],...n],this.loaded=!0,this.publish(),this.list}async send(t){let e=t.trim();if(!e)throw new P("invalid","Say something first.");if(this.busy)throw new P("rate_limited","Wait for the reply first.");this.setBusy(!0);let n={id:Dt("local"),role:"visitor",text:e,createdAt:new Date().toISOString()},i={id:Dt("reply"),role:"agent",text:"",createdAt:new Date().toISOString(),streaming:!0};this.list.push(n,i),this.publish(),this.abort=new AbortController;try{let a=await this.session.token(),s=await Ce(this.apiUrl,"/sdk/v1/chat/messages",{method:"POST",body:{text:e},token:a,signal:this.abort.signal}),o=null,l=null;if(await Ut(s,({event:d,data:f})=>{let _=f;if(d==="delta"&&typeof _?.text=="string")i.text+=_.text,this.publish();else if(d==="done"){let c=Array.isArray(_.suggestions)?_.suggestions.filter(g=>typeof g=="string"&&g.trim()!==""):[];o={id:String(_.id),role:"agent",text:String(_.text??i.text),createdAt:String(_.createdAt??i.createdAt),...c.length?{suggestions:c}:{},..._.askDetails&&typeof _.askDetails=="object"?{askDetails:_.askDetails}:{},..._.detailsForm&&typeof _.detailsForm=="object"?{detailsForm:_.detailsForm}:{}}}else d==="error"&&(l=typeof _?.message=="string"?_.message:"Something went wrong.")},this.abort.signal),l||!o)throw new P("unknown",l??"The reply was cut off. Try again.");let p=o;return this.replace(i.id,p),p}catch(a){let s=a instanceof P?a:new P("network","The reply was cut off. Try again.");this.list=this.list.filter(l=>l.id!==i.id);let o=this.list.findIndex(l=>l.id===n.id);throw o!==-1&&(this.list[o]={...n,failed:!0,...s.status===429?{error:s.message}:{}}),this.publish(),a?.name!=="AbortError"&&this.emit("error",s),s}finally{this.abort=null,this.setBusy(!1)}}async reset(){this.stop();let t=await this.session.token();await Ce(this.apiUrl,"/sdk/v1/chat/messages",{method:"DELETE",token:t}),this.list=[],this.loaded=!0,this.publish()}retry(t){let e=this.list.find(n=>n.id===t&&n.failed);if(!e)throw new P("not_found","Nothing to retry.");return this.list=this.list.filter(n=>n.id!==t),this.publish(),this.send(e.text)}stop(){this.abort?.abort()}replace(t,e){let n=this.list.findIndex(i=>i.id===t);n!==-1&&(this.list[n]=e),this.publish()}setBusy(t){this.busy=t,this.emit("busy",t)}},Mi=()=>{let t=new Map;return{get:e=>t.get(e)??null,set:(e,n)=>{t.set(e,n)}}},Ei=()=>({get(t){try{return globalThis.localStorage?.getItem(t)??null}catch{return null}},set(t,e){try{globalThis.localStorage?.setItem(t,e)}catch{}}}),Ii=60,Fi=class{constructor(t){if(y(this,"src",t),y(this,"current",null),y(this,"inflight",null),!t.publishableKey&&!t.getSessionToken)throw new P("invalid","Pass a publishableKey, or getSessionToken for sessions your server mints.")}visitorKey(){return`cxyz:visitor:${(this.src.publishableKey??"server").slice(-12)}`}get info(){return this.current}async token(){let t=Date.now()/1e3;return this.current&&this.current.expiresAt-Ii>t?this.current.token:(await this.refresh()).token}refresh(){return this.inflight??(this.inflight=this.mint().finally(()=>{this.inflight=null})),this.inflight}async mint(){let t;if(this.src.getSessionToken){let e=await this.src.getSessionToken();typeof e=="string"?t=await this.describe(e):t=e}else{let e=this.src.store.get(this.visitorKey())??void 0;t=await X(this.src.apiUrl,"/sdk/v1/sessions",{method:"POST",body:{publishableKey:this.src.publishableKey,agentId:this.src.agentId,visitorId:e}}),this.src.store.set(this.visitorKey(),t.visitorId)}return this.current=t,t}async describe(t){return{...await X(this.src.apiUrl,"/sdk/v1/session",{token:t}),token:t}}},Li="https://api.character.xyz",Ot=class $t extends ht{constructor(e,n,i){super(),y(this,"apiUrl",e),y(this,"session",n),y(this,"info",i),y(this,"chat"),y(this,"currentCall",null),y(this,"destroyed",!1),y(this,"openingP",null),y(this,"actionHandlers",new Map),this.chat=new Ai(e,n)}static async init(e){let n=(e.apiUrl??Li).replace(/\/+$/,"");if(e.publishableKey&&/^cxyz_sk_/.test(e.publishableKey))throw new P("invalid","That is a SECRET key. Never put it in a web page: use a publishable key (cxyz_pk_\u2026). Revoke the secret key now.");let i=e.storage==="memory"?Mi():e.storage&&typeof e.storage=="object"?e.storage:Ei(),a=new Fi({apiUrl:n,agentId:e.agentId,publishableKey:e.publishableKey,getSessionToken:e.getSessionToken,store:i}),s=await a.refresh();return new $t(n,a,s)}get agent(){return(this.session.info??this.info).agent}get features(){return(this.session.info??this.info).features}get appearance(){return(this.session.info??this.info).appearance??{}}get visitorId(){return(this.session.info??this.info).visitorId}get mode(){return(this.session.info??this.info).mode}get call(){return this.currentCall&&this.currentCall.state.phase!=="ended"?this.currentCall:null}async videoAvatar(){let e=await this.session.token();return X(this.apiUrl,"/sdk/v1/agent/video-avatar",{token:e})}opening(e=!1){return e&&(this.openingP=null),this.openingP??(this.openingP=this.session.token().then(n=>{let i=typeof navigator>"u"?"":navigator.language||"",a=i?`/sdk/v1/agent/opening?locale=${encodeURIComponent(i)}`:"/sdk/v1/agent/opening";return X(this.apiUrl,a,{token:n})}).catch(()=>null)),this.openingP}async sendDetails(e){let n=await this.session.token(),i=typeof location<"u"?location.href:void 0;await X(this.apiUrl,"/sdk/v1/lead",{token:n,body:{...e,consent:!0,...i?{page:i}:{}}})}async declineDetails(){let e=await this.session.token();await X(this.apiUrl,"/sdk/v1/lead/decline",{token:e,method:"POST",body:{}})}async identify(e){let n=await this.session.token();await X(this.apiUrl,"/sdk/v1/context",{token:n,method:"POST",body:{visitor:e}})}async setContext(e){let n=await this.session.token();await X(this.apiUrl,"/sdk/v1/context",{token:n,method:"POST",body:{context:e}})}async track(e,n={},i={}){let a=await this.session.token(),s=i.id??Ri(),o=await X(this.apiUrl,"/sdk/v1/track",{token:a,method:"POST",body:{name:e,data:n,id:s},keepalive:!0});this.emit("siteEvent",o),!o.accepted&&o.ignored&&o.ignored!=="duplicate"&&console.warn(`[characterxyz] event "${e}" ignored: ${o.ignored}`);for(let p of o.actions??[])this.runAction(p);let l=0;for(;o.action&&l++<4;){let p=o.action,d=await this.runAction(p);o=await X(this.apiUrl,`/sdk/v1/actions/${encodeURIComponent(p.id)}`,{token:a,method:"POST",body:d}),this.emit("siteEvent",o)}return this.chat.applySiteEvent(o),o}registerAction(e,n){return this.actionHandlers.set(e,n),()=>{this.actionHandlers.get(e)===n&&this.actionHandlers.delete(e)}}async runAction(e){let n=this.actionHandlers.get(e.name);if(!n)return{ok:!1,error:`no handler registered for "${e.name}"`};try{return{ok:!0,result:await n(e.inputs??{},e.name)??null}}catch(i){return{ok:!1,error:String(i?.message??i)}}}async startCall(e={}){if(this.destroyed)throw new P("invalid","This client was destroyed.");if(!this.features.call)throw new P("forbidden","Calls are not available on this site.");if(this.call)return this.call;let n=new Si(this.apiUrl,this.session,this.agent.id,e);return this.currentCall=n,n.on("state",i=>{i.phase==="ended"&&this.currentCall===n&&this.emit("call",null)}),n.on("error",i=>this.emit("error",i)),this.emit("call",n),await n.start(),n}destroy(){this.destroyed=!0,this.currentCall?.hangUp(),this.chat.stop(),this.chat.clear(),this.actionHandlers.clear(),this.clear()}};function Ri(){let t=typeof crypto<"u"?crypto:void 0;return t&&typeof t.randomUUID=="function"?`evt_${t.randomUUID()}`:`evt_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`}var We,I,Yt,zi,le,Nt,qt,jt,ft,Ue,Se,Vt,_t,gt,mt,Di,Ne={},He=[],Pi=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Ye=Array.isArray;function ae(t,e){for(var n in e)t[n]=e[n];return t}function xt(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function Ui(t,e,n){var i,a,s,o={};for(s in e)s=="key"?i=e[s]:s=="ref"?a=e[s]:o[s]=e[s];if(arguments.length>2&&(o.children=arguments.length>3?We.call(arguments,2):n),typeof t=="function"&&t.defaultProps!=null)for(s in t.defaultProps)o[s]===void 0&&(o[s]=t.defaultProps[s]);return Oe(t,o,i,a,null)}function Oe(t,e,n,i,a){var s={type:t,props:e,key:n,ref:i,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:a??++Yt,__i:-1,__u:0};return a==null&&I.vnode!=null&&I.vnode(s),s}function F(t){return t.children}function $e(t,e){this.props=t,this.context=e}function pe(t,e){if(e==null)return t.__?pe(t.__,t.__i+1):null;for(var n;e<t.__k.length;e++)if((n=t.__k[e])!=null&&n.__e!=null)return n.__e;return typeof t.type=="function"?pe(t):null}function Oi(t){if(t.__P&&t.__d){var e=t.__v,n=e.__e,i=[],a=[],s=ae({},e);s.__v=e.__v+1,I.vnode&&I.vnode(s),bt(t.__P,s,e,t.__n,t.__P.namespaceURI,32&e.__u?[n]:null,i,n??pe(e),!!(32&e.__u),a),s.__v=e.__v,s.__.__k[s.__i]=s,Gt(i,s,a),e.__e=e.__=null,s.__e!=n&&Kt(s)}}function Kt(t){if((t=t.__)!=null&&t.__c!=null)return t.__e=t.__c.base=null,t.__k.some(function(e){if(e!=null&&e.__e!=null)return t.__e=t.__c.base=e.__e}),Kt(t)}function Ht(t){(!t.__d&&(t.__d=!0)&&le.push(t)&&!Be.__r++||Nt!=I.debounceRendering)&&((Nt=I.debounceRendering)||qt)(Be)}function Be(){try{for(var t,e=1;le.length;)le.length>e&&le.sort(jt),t=le.shift(),e=le.length,Oi(t)}finally{le.length=Be.__r=0}}function Xt(t,e,n,i,a,s,o,l,p,d,f){var _,c,g,b,x,m,k=i&&i.__k||He,w=e.length;for(p=$i(n,e,k,p,w),_=0;_<w;_++)(g=n.__k[_])!=null&&(c=g.__i!=-1&&k[g.__i]||Ne,g.__i=_,m=bt(t,g,c,a,s,o,l,p,d,f),b=g.__e,g.ref&&c.ref!=g.ref&&(c.ref&&vt(c.ref,null,g),f.push(g.ref,g.__c||b,g)),x==null&&b!=null&&(x=b),4&g.__u?(p=Zt(g,p,t),c.__e&&(c.__e=null)):typeof g.type=="function"&&m!==void 0?p=m:b&&(p=b.nextSibling),g.__u&=-7);return n.__e=x,p}function $i(t,e,n,i,a){var s,o,l,p,d,f=n.length,_=f,c=0;for(t.__k=new Array(a),s=0;s<a;s++)(o=e[s])!=null&&typeof o!="boolean"&&typeof o!="function"?(typeof o=="string"||typeof o=="number"||typeof o=="bigint"||o.constructor==String?o=t.__k[s]=Oe(null,o,null,null,null):Ye(o)?o=t.__k[s]=Oe(F,{children:o},null,null,null):o.constructor===void 0&&o.__b>0?o=t.__k[s]=Oe(o.type,o.props,o.key,o.ref?o.ref:null,o.__v):t.__k[s]=o,p=s+c,o.__=t,o.__b=t.__b+1,l=null,(d=o.__i=Ni(o,n,p,_))!=-1&&(_--,(l=n[d])&&(l.__u|=2)),l==null||l.__v==null?(d==-1&&(a>f?c--:a<f&&c++),typeof o.type!="function"&&(o.__u|=4)):d!=p&&(d==p-1?c--:d==p+1?c++:(d>p?c--:c++,o.__u|=4))):t.__k[s]=null;if(_)for(s=0;s<f;s++)(l=n[s])!=null&&(2&l.__u)==0&&(l.__e==i&&(i=pe(l)),en(l,l));return i}function Zt(t,e,n){var i,a;if(typeof t.type=="function"){for(i=t.__k,a=0;i&&a<i.length;a++)i[a]&&(i[a].__=t,e=Zt(i[a],e,n));return e}t.__e!=e&&(e&&t.type&&!e.parentNode&&(e=pe(t)),e=n.insertBefore(t.__e,e||null));do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function Ni(t,e,n,i){var a,s,o,l=t.key,p=t.type,d=e[n],f=d!=null&&(2&d.__u)==0;if(d===null&&l==null||f&&l==d.key&&p==d.type)return n;if(i>(f?1:0)){for(a=n-1,s=n+1;a>=0||s<e.length;)if((d=e[o=a>=0?a--:s++])!=null&&(2&d.__u)==0&&l==d.key&&p==d.type)return o}return-1}function Bt(t,e,n){e[0]=="-"?t.setProperty(e,n??""):t[e]=n==null?"":typeof n!="number"||Pi.test(e)?n:n+"px"}function Pe(t,e,n,i,a){var s,o;e:if(e=="style")if(typeof n=="string")t.style.cssText=n;else{if(typeof i=="string"&&(t.style.cssText=i=""),i)for(e in i)n&&e in n||Bt(t.style,e,"");if(n)for(e in n)i&&n[e]==i[e]||Bt(t.style,e,n[e])}else if(e[0]=="o"&&e[1]=="n")s=e!=(e=e.replace(Vt,"$1")),o=e.toLowerCase(),e=o in t||e=="onFocusOut"||e=="onFocusIn"?o.slice(2):e.slice(2),t.l||(t.l={}),t.l[e+s]=n,n?i?n[Se]=i[Se]:(n[Se]=_t,t.addEventListener(e,s?mt:gt,s)):t.removeEventListener(e,s?mt:gt,s);else{if(a=="http://www.w3.org/2000/svg")e=e.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(e!="width"&&e!="height"&&e!="href"&&e!="list"&&e!="form"&&e!="tabIndex"&&e!="download"&&e!="rowSpan"&&e!="colSpan"&&e!="role"&&e!="popover"&&e in t)try{t[e]=n??"";break e}catch{}typeof n=="function"||(n==null||n===!1&&e[4]!="-"?t.removeAttribute(e):t.setAttribute(e,e=="popover"&&n==1?"":n))}}function Wt(t){return function(e){if(this.l){var n=this.l[e.type+t];if(e[Ue]==null)e[Ue]=_t++;else if(e[Ue]<n[Se])return;return n(I.event?I.event(e):e)}}}function bt(t,e,n,i,a,s,o,l,p,d){var f,_,c,g,b,x,m,k,w,N,U,O,H,B,W,Z,v=e.type;if(e.constructor!==void 0)return null;128&n.__u&&(p=!!(32&n.__u),s=[l=e.__e=n.__e]),(f=I.__b)&&f(e);e:if(typeof v=="function"){_=o.length;try{if(w=e.props,N=v.prototype&&v.prototype.render,U=(f=v.contextType)&&i[f.__c],O=f?U?U.props.value:f.__:i,n.__c?k=(c=e.__c=n.__c).__=c.__E:(N?e.__c=c=new v(w,O):(e.__c=c=new $e(w,O),c.constructor=v,c.render=Bi),U&&U.sub(c),c.state||(c.state={}),c.__n=i,g=c.__d=!0,c.__h=[],c._sb=[]),N&&c.__s==null&&(c.__s=c.state),N&&v.getDerivedStateFromProps!=null&&(c.__s==c.state&&(c.__s=ae({},c.__s)),ae(c.__s,v.getDerivedStateFromProps(w,c.__s))),b=c.props,x=c.state,c.__v=e,g)N&&v.getDerivedStateFromProps==null&&c.componentWillMount!=null&&c.componentWillMount(),N&&c.componentDidMount!=null&&c.__h.push(c.componentDidMount);else{if(N&&v.getDerivedStateFromProps==null&&w!==b&&c.componentWillReceiveProps!=null&&c.componentWillReceiveProps(w,O),e.__v==n.__v||!c.__e&&c.shouldComponentUpdate!=null&&c.shouldComponentUpdate(w,c.__s,O)===!1){e.__v!=n.__v&&(c.props=w,c.state=c.__s,c.__d=!1),e.__e=n.__e,e.__k=n.__k,e.__k.some(function($){$&&($.__=e)}),He.push.apply(c.__h,c._sb),c._sb=[],c.__h.length&&o.push(c),l=pe(n);break e}c.componentWillUpdate!=null&&c.componentWillUpdate(w,c.__s,O),N&&c.componentDidUpdate!=null&&c.__h.push(function(){c.componentDidUpdate(b,x,m)})}if(c.context=O,c.props=w,c.__P=t,c.__e=!1,H=I.__r,B=0,N)c.state=c.__s,c.__d=!1,H&&H(e),f=c.render(c.props,c.state,c.context),He.push.apply(c.__h,c._sb),c._sb=[];else do c.__d=!1,H&&H(e),f=c.render(c.props,c.state,c.context),c.state=c.__s;while(c.__d&&++B<25);c.state=c.__s,c.getChildContext!=null&&(i=ae(ae({},i),c.getChildContext())),N&&!g&&c.getSnapshotBeforeUpdate!=null&&(m=c.getSnapshotBeforeUpdate(b,x)),W=f!=null&&f.type===F&&f.key==null?Qt(f.props.children):f,l=Xt(t,Ye(W)?W:[W],e,n,i,a,s,o,l,p,d),c.base=e.__e,e.__u&=-161,c.__h.length&&o.push(c),k&&(c.__E=c.__=null)}catch($){if(o.length=_,e.__v=null,p||s!=null){if($.then){for(e.__u|=p?160:128;l&&l.nodeType==8&&l.nextSibling;)l=l.nextSibling;s!=null&&(s[s.indexOf(l)]=null),e.__e=l}else if(s!=null)for(Z=s.length;Z--;)xt(s[Z])}else e.__e=n.__e;e.__k==null&&(e.__k=n.__k||[]),$.then||Jt(e),I.__e($,e,n)}}else s==null&&e.__v==n.__v?(e.__k=n.__k,e.__e=n.__e):l=e.__e=Hi(n.__e,e,n,i,a,s,o,p,d);return(f=I.diffed)&&f(e),128&e.__u?void 0:l}function Jt(t){t&&(t.__c&&(t.__c.__e=!0),t.__k&&t.__k.some(Jt))}function Gt(t,e,n){for(var i=0;i<n.length;i++)vt(n[i],n[++i],n[++i]);I.__c&&I.__c(e,t),t.some(function(a){try{t=a.__h,a.__h=[],t.some(function(s){s.call(a)})}catch(s){I.__e(s,a.__v)}})}function Qt(t){return typeof t!="object"||t==null||t.__b>0?t:Ye(t)?t.map(Qt):t.constructor!==void 0?null:ae({},t)}function Hi(t,e,n,i,a,s,o,l,p){var d,f,_,c,g,b,x,m=n.props||Ne,k=e.props,w=e.type;if(w=="svg"?a="http://www.w3.org/2000/svg":w=="math"?a="http://www.w3.org/1998/Math/MathML":a||(a="http://www.w3.org/1999/xhtml"),s!=null){for(d=0;d<s.length;d++)if((g=s[d])&&"setAttribute"in g==!!w&&(w?g.localName==w:g.nodeType==3)){t=g,s[d]=null;break}}if(t==null){if(w==null)return document.createTextNode(k);t=document.createElementNS(a,w,k.is&&k),l&&(I.__m&&I.__m(e,s),l=!1),s=null}if(w==null)m===k||l&&t.data==k||(t.data=k);else{if(s=w=="textarea"&&k.defaultValue!=null?null:s&&We.call(t.childNodes),!l&&s!=null)for(m={},d=0;d<t.attributes.length;d++)m[(g=t.attributes[d]).name]=g.value;for(d in m)g=m[d],d=="dangerouslySetInnerHTML"?_=g:d=="children"||d in k||d=="value"&&"defaultValue"in k||d=="checked"&&"defaultChecked"in k||Pe(t,d,null,g,a);for(d in k)g=k[d],d=="children"?c=g:d=="dangerouslySetInnerHTML"?f=g:d=="value"?b=g:d=="checked"?x=g:l&&typeof g!="function"||m[d]===g||Pe(t,d,g,m[d],a);if(f)l||_&&(f.__html==_.__html||f.__html==t.innerHTML)||(t.innerHTML=f.__html),e.__k=[];else if(_&&(t.innerHTML=""),Xt(e.type=="template"?t.content:t,Ye(c)?c:[c],e,n,i,w=="foreignObject"?"http://www.w3.org/1999/xhtml":a,s,o,s?s[0]:n.__k&&pe(n,0),l,p),s!=null)for(d=s.length;d--;)xt(s[d]);l&&w!="textarea"||(d="value",w=="progress"&&b==null?t.removeAttribute("value"):b!=null&&(b!==t[d]||w=="progress"&&!b||w=="option"&&b!=m[d])&&Pe(t,d,b,m[d],a),d="checked",x!=null&&x!=t[d]&&Pe(t,d,x,m[d],a))}return t}function vt(t,e,n){try{if(typeof t=="function"){var i=typeof t.__u=="function";i&&t.__u(),i&&e==null||(t.__u=t(e))}else t.current=e}catch(a){I.__e(a,n)}}function en(t,e,n){var i,a;if(I.unmount&&I.unmount(t),(i=t.ref)&&(i.current&&i.current!=t.__e||vt(i,null,e)),(i=t.__c)!=null){if(i.componentWillUnmount)try{i.componentWillUnmount()}catch(s){I.__e(s,e)}i.base=i.__P=i.__n=null}if(i=t.__k)for(a=0;a<i.length;a++)i[a]&&en(i[a],e,n||typeof t.type!="function");n||xt(t.__e),t.__c=t.__=t.__e=void 0}function Bi(t,e,n){return this.constructor(t,n)}function yt(t,e,n){var i,a,s,o;e==document&&(e=document.documentElement),I.__&&I.__(t,e),a=(i=typeof n=="function")?null:n&&n.__k||e.__k,s=[],o=[],bt(e,t=(!i&&n||e).__k=Ui(F,null,[t]),a||Ne,Ne,e.namespaceURI,!i&&n?[n]:a?null:e.firstChild?We.call(e.childNodes):null,s,!i&&n?n:a?a.__e:e.firstChild,i,o),Gt(s,t,o),t.props.children=null}We=He.slice,I={__e:function(t,e,n,i){for(var a,s,o;e=e.__;)if((a=e.__c)&&!a.__)try{if((s=a.constructor)&&s.getDerivedStateFromError!=null&&(a.setState(s.getDerivedStateFromError(t)),o=a.__d),a.componentDidCatch!=null&&(a.componentDidCatch(t,i||{}),o=a.__d),o)return a.__E=a}catch(l){t=l}throw t}},Yt=0,zi=function(t){return t!=null&&t.constructor===void 0},$e.prototype.setState=function(t,e){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=ae({},this.state),typeof t=="function"&&(t=t(ae({},n),this.props)),t&&ae(n,t),t!=null&&this.__v&&(e&&this._sb.push(e),Ht(this))},$e.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),Ht(this))},$e.prototype.render=F,le=[],qt=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,jt=function(t,e){return t.__v.__b-e.__v.__b},Be.__r=0,ft=Math.random().toString(8),Ue="__d"+ft,Se="__a"+ft,Vt=/(PointerCapture)$|Capture$/i,_t=0,gt=Wt(!1),mt=Wt(!0),Di=0;var me,R,kt,tn,Te=0,dn=[],z=I,nn=z.__b,an=z.__r,rn=z.diffed,sn=z.__c,on=z.unmount,ln=z.__;function je(t,e){z.__h&&z.__h(R,t,Te||e),Te=0;var n=R.__H||(R.__H={__:[],__h:[]});return t>=n.__.length&&n.__.push({}),n.__[t]}function C(t){return Te=1,Wi(un,t)}function Wi(t,e,n){var i=je(me++,2);if(i.t=t,!i.__c&&(i.__=[n?n(e):un(void 0,e),function(l){var p=i.__N?i.__N[0]:i.__[0],d=i.t(p,l);p!==d&&(i.__N=[d,i.__[1]],i.__c.setState({}))}],i.__c=R,!R.__f)){var a=function(l,p,d){if(!i.__c.__H)return!0;var f=!1,_=i.__c.props!==l;if(i.__c.__H.__.some(function(g){if(g.__N){f=!0;var b=g.__[0];g.__=g.__N,g.__N=void 0,b!==g.__[0]&&(_=!0)}}),s){var c=s.call(this,l,p,d);return f?c||_:c}return!f||_};R.__f=!0;var s=R.shouldComponentUpdate,o=R.componentWillUpdate;R.componentWillUpdate=function(l,p,d){if(this.__e){var f=s;s=void 0,a(l,p,d),s=f}o&&o.call(this,l,p,d)},R.shouldComponentUpdate=a}return i.__N||i.__}function L(t,e){var n=je(me++,3);!z.__s&&Ct(n.__H,e)&&(n.__=t,n.u=e,R.__H.__h.push(n))}function Ve(t,e){var n=je(me++,4);!z.__s&&Ct(n.__H,e)&&(n.__=t,n.u=e,R.__h.push(n))}function V(t){return Te=5,pn(function(){return{current:t}},[])}function pn(t,e){var n=je(me++,7);return Ct(n.__H,e)&&(n.__=t(),n.__H=e,n.__h=t),n.__}function Ae(t,e){return Te=8,pn(function(){return t},e)}function Yi(){for(var t;t=dn.shift();){var e=t.__H;if(t.__P&&e)try{e.__h.some(qe),e.__h.some(wt),e.__h=[]}catch(n){e.__h=[],z.__e(n,t.__v)}}}z.__b=function(t){R=null,nn&&nn(t)},z.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),ln&&ln(t,e)},z.__r=function(t){an&&an(t),me=0;var e=(R=t.__c).__H;e&&(kt===R?(e.__h=[],R.__h=[],e.__.some(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(e.__h.some(qe),e.__h.some(wt),e.__h=[],me=0)),kt=R},z.diffed=function(t){rn&&rn(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(dn.push(e)!==1&&tn===z.requestAnimationFrame||((tn=z.requestAnimationFrame)||qi)(Yi)),e.__H.__.some(function(n){n.u&&(n.__H=n.u,n.u=void 0)})),kt=R=null},z.__c=function(t,e){e.some(function(n){try{n.__h.some(qe),n.__h=n.__h.filter(function(i){return!i.__||wt(i)})}catch(i){e.some(function(a){a.__h&&(a.__h=[])}),e=[],z.__e(i,n.__v)}}),sn&&sn(t,e)},z.unmount=function(t){on&&on(t);var e,n=t.__c;n&&n.__H&&(n.__H.__.some(function(i){try{qe(i)}catch(a){e=a}}),n.__H=void 0,e&&z.__e(e,n.__v))};var cn=typeof requestAnimationFrame=="function";function qi(t){var e,n=function(){clearTimeout(i),cn&&cancelAnimationFrame(e),setTimeout(t)},i=setTimeout(n,35);cn&&(e=requestAnimationFrame(n))}function qe(t){var e=R,n=t.__c;typeof n=="function"&&(t.__c=void 0,n()),R=e}function wt(t){var e=R;t.__c=t.__(),R=e}function Ct(t,e){return!t||t.length!==e.length||e.some(function(n,i){return n!==t[i]})}function un(t,e){return typeof e=="function"?e(t):e}function fn(t){let e=t%100;if(e>=11&&e<=13)return`${t}th`;switch(t%10){case 1:return`${t}st`;case 2:return`${t}nd`;case 3:return`${t}rd`;default:return`${t}th`}}function Ke(t){let e=Math.max(0,Math.floor(t)),n=Math.floor(e/3600),i=Math.floor(e%3600/60),a=String(e%60).padStart(2,"0");return n?`${n}:${String(i).padStart(2,"0")}:${a}`:`${i}:${a}`}function hn(t){let e=[],n=/(\*\*[^*]+\*\*|`[^`]+`|\[[^\]]+\]\((https?:\/\/[^)\s]+)\)|https?:\/\/[^\s<>()]+[^\s<>().,;:!?'"]|\*[^*\s][^*]*\*)/g,i=0,a;for(;a=n.exec(t);){a.index>i&&e.push({t:"text",v:t.slice(i,a.index)});let s=a[0];s.startsWith("**")?e.push({t:"b",v:s.slice(2,-2)}):s.startsWith("`")?e.push({t:"code",v:s.slice(1,-1)}):s.startsWith("[")?e.push({t:"link",v:s.slice(1,s.indexOf("]")),href:a[2]}):s.startsWith("http")?e.push({t:"link",v:s,href:s}):e.push({t:"i",v:s.slice(1,-1)}),i=a.index+s.length}return i<t.length&&e.push({t:"text",v:t.slice(i)}),e}function gn(t){let e=[];for(let n of t.split(/\n{2,}/)){let i=n.split(`
41
- `);i.length&&i.every(a=>/^\s*[-*•]\s+/.test(a))?e.push({t:"ul",items:i.map(a=>hn(a.replace(/^\s*[-*•]\s+/,"")))}):e.push({t:"p",parts:hn(n)})}return e}var ji={assistant:"Assistant",online:"Online",typing:"Typing\u2026",typingName:"{name} is typing",message:"Message",send:"Send",sending:"Sending\u2026",close:"Close",minimise:"Minimise",dismiss:"Dismiss",notNow:"Not now",newConversation:"Start a new conversation",chat:"Chat",chatWith:"Chat with {name}",call:"Call",callName:"Call {name}",callWith:"Call with {name}",startCall:"Start call",callAgain:"Call again",joinCall:"Join call",join:"Join",view:"View",onCall:"On call",backToCall:"Back to your call",backToCallWith:"Back to your call with {name}",callTime:"Call time",timeLeft:"{time} left",endCall:"End call",end:"End",mute:"Mute",unmute:"Unmute",muted:"You are muted",interrupt:"Interrupt",interruptName:"Interrupt {name}",connecting:"Connecting\u2026",joining:"Joining\u2026",speaking:"Speaking",thinking:"Thinking\u2026",listening:"Listening",you:"You: {text}",inLine:"{position} in line",lineLabel:"in line",inLineFor:"You're {position} in line for a call \xB7 {eta}",inLineToCall:"You are {position} in line to call {name}. Open",inLineOpen:"You are {position} in line. Open your call",inLineEta:"You are {position} in line, {eta}",onOtherCalls:"{name} is on other calls",yourTurn:"Your turn in {eta}. We'll chime when it's time.",yourTurnChat:"Your turn in {eta}. We'll chime when it's time, so feel free to keep chatting.",keepChatting:"Keep chatting",leaveLine:"Leave line",readyForYou:"{name} is ready for you",secondsToJoin:"{seconds}s to join",joinWithin:"Join within {seconds} seconds.",talkWith:"Talk with {name} in real time.",etaSoon:"less than a minute",etaMin:"about {n} min",etaHr:"about {n} hr",notSent:"Not sent \xB7 Retry",beforeYouCall:"Before you call {name}",leaveDetails:"Leave your details",confirmDetails:"Confirm your details",detailsWhy:"So the team can follow up, even if the line drops.",detailsTyped:"From what you typed. Check them and send.",reasonField:"Reason",reasonChoose:"Choose a reason",reasonOther:"Something else",reasonPlaceholder:"Tell us in a few words",reasonInferred:"I'll tell the team this is about",reasonFromConversation:"From your conversation",reasonFromPage:"From this page",change:"Change",skipAndCall:"Skip and call",optional:"optional",privacyPolicy:"Privacy policy",thanks:"Thanks. The team will be in touch.",thanksName:"Thanks, {name}. The team will be in touch.",sendFailed:"Could not send. Try again.",nameField:"Name",emailField:"Email",phoneField:"Phone",companyField:"Company",poweredBy:"Powered by {brand}",greetingDefault:"Hi, I'm {name}. How can I help you today?",endedTitle:"Call ended",endedBody:"Thanks for talking with {name}.",leftTitle:"You left the line",leftBody:"You can call again whenever you like.",missedTitle:"You missed your turn",missedBody:"{name} was ready, but the call wasn't joined in time.",stillBusyTitle:"Still busy",stillBusyBody:"Sorry for the wait. {name} is still on other calls. Chat is open meanwhile.",limitTitle:"Time is up",limitBody:"This call reached its time limit.",busyTitle:"All lines are busy",busyBody:"Try again in a few minutes, or keep chatting.",micTitle:"Microphone needed",micBody:"Allow the microphone in your browser to talk, or keep chatting.",silenceBody:"The line was quiet for a minute, so {name} hung up. Call again any time.",restingTitle:"Calls are resting",restingBody:"Calls are done for today. Chat is open.",unavailableTitle:"Calls are unavailable",unavailableBody:"Calls are not available right now. Chat is open.",droppedTitle:"The call dropped",droppedBody:"Something interrupted the call. Try again."},mn={},_n=!0;function xn(t){mn=t??{},_n=!t||!Object.keys(t).length}function h(t,e){let n=mn[t]??ji[t];if(e)for(let i in e)n=n.split(`{${i}}`).join(String(e[i]));return n}function ce(t){return _n?fn(t):String(t)}function Xe(t){if(t==null)return"";if(t<60)return h("etaSoon");let e=Math.round(t/60);return e<60?h("etaMin",{n:e}):h("etaHr",{n:Math.round(e/60)})}function bn(t,e){let n=(i,a)=>({title:h(i),body:h(a,{name:e})});switch(t){case"hangup":return n("endedTitle","endedBody");case"left":return n("leftTitle","leftBody");case"missed":return n("missedTitle","missedBody");case"timeout":return n("stillBusyTitle","stillBusyBody");case"limit":return n("limitTitle","limitBody");case"busy":return n("busyTitle","busyBody");case"mic-denied":return n("micTitle","micBody");case"silence":return n("endedTitle","silenceBody");case"daily_limit":return n("restingTitle","restingBody");case"credits":case"unavailable":return n("unavailableTitle","unavailableBody");default:return n("droppedTitle","droppedBody")}}var vn={cx:.5,cy:.12,span:.06};function kn(t,e,n){let i=t?.face?.eyes,a=t?.face?.chin;if(!i||!a||!e||!n)return vn;let s=(i.left.x+i.right.x)/2,o=(i.left.y+i.right.y)/2,l=(a.y-o)/n;return l>.005&&l<.5?{cx:s/e,cy:(o+a.y)/2/n,span:l}:vn}var Ze={faceFraction:.26,at:{x:.5,y:.5}},wn={faceFraction:.14,at:{x:.5,y:.34},keepCrown:!0},Cn={faceFraction:.16,at:{x:.5,y:.22},keepCrown:!0},Sn={fit:"height"},Vi=1.8,yn=.04;function Tn(t,e,n,i,a){if("fit"in a){let d=i*e;return{width:d,height:i,left:n/2-t.cx*d,top:0}}let s=i*a.faceFraction/t.span,o=s*e,l=i*a.at.y-t.cy*s,p=l+(t.cy-t.span*Vi)*s;return a.keepCrown&&p<i*yn&&(l+=i*yn-p),{width:o,height:s,left:n*a.at.x-t.cx*o,top:l}}var An=/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/,Ki=/\+?\d[\d\s().-]{5,}\d/g,Xi=/\b(?:my name is|i am|i'm|im|this is|name\s*[:-])\s+([A-Za-z][A-Za-z'’-]+(?:\s+[A-Za-z][A-Za-z'’-]+)?)/i,Zi=new Set(["interested","looking","from","with","here","trying","not","a","an","the","just","also","happy","keen","curious","calling","sure","fine","good","okay","ok"]);function Mn(t){let e={},n=t.match(An)?.[0];n&&(e.email=n.replace(/[.,;:]+$/,""));for(let a of t.replace(An," ").matchAll(Ki)){let s=a[0].replace(/\D/g,"");if(s.length>=7&&s.length<=15){e.phone=a[0].trim();break}}if(!e.email&&!e.phone)return null;let i=t.match(Xi)?.[1];if(i){let a=i.split(/\s+/).filter(o=>!Zi.has(o.toLowerCase())),s=[];for(let o of a){if(["and","here","at","from"].includes(o.toLowerCase()))break;s.push(o)}s.length&&s[0].length>1&&(e.name=s.map(o=>o[0].toUpperCase()+o.slice(1)).join(" "))}return e}var Ji=0;function r(t,e,n,i,a,s){e||(e={});var o,l,p=e;if("ref"in p)for(l in p={},e)l=="ref"?o=e[l]:p[l]=e[l];var d={type:t,props:p,key:n,ref:o,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--Ji,__i:-1,__u:0,__source:a,__self:s};if(typeof t=="function"&&(o=t.defaultProps))for(l in o)p[l]===void 0&&(p[l]=o[l]);return I.vnode&&I.vnode(d),d}var ee=(t,e)=>r("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"1.9","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",focusable:"false",children:e}),Me=({size:t=20})=>ee(t,r("path",{d:"M4 5.5A2.5 2.5 0 0 1 6.5 3h11A2.5 2.5 0 0 1 20 5.5v8a2.5 2.5 0 0 1-2.5 2.5H10l-4.2 3.6a.5.5 0 0 1-.8-.4V16h0A2.5 2.5 0 0 1 4 13.5z"})),_e=({size:t=20})=>ee(t,r("path",{d:"M5.2 3.5h3l1.6 4.2-2 1.4a12 12 0 0 0 7.1 7.1l1.4-2 4.2 1.6v3a1.7 1.7 0 0 1-1.8 1.7A16.6 16.6 0 0 1 3.5 5.3 1.7 1.7 0 0 1 5.2 3.5z"})),En=({size:t=22})=>ee(t,r("path",{d:"M3 13.6c5-4.4 13-4.4 18 0l-1.7 2.6-3.6-1.3v-2.6a11 11 0 0 0-7.4 0v2.6l-3.6 1.3z"})),In=({size:t=20})=>ee(t,r(F,{children:[r("rect",{x:"9",y:"3",width:"6",height:"11",rx:"3"}),r("path",{d:"M5.5 11a6.5 6.5 0 0 0 13 0M12 17.5V21"})]})),Fn=({size:t=20})=>ee(t,r(F,{children:[r("path",{d:"M9 9v2a3 3 0 0 0 5.1 2.1M15 9.4V6a3 3 0 0 0-5.7-1.3"}),r("path",{d:"M5.5 11a6.5 6.5 0 0 0 10.6 5M18.4 12.5a6.5 6.5 0 0 0 .1-1.5M12 17.5V21M3 3l18 18"})]})),Je=({size:t=18})=>ee(t,r("path",{d:"M6 6l12 12M18 6L6 18"})),Ln=({size:t=18})=>ee(t,r("path",{d:"M12 19V5M5.5 11.5L12 5l6.5 6.5"})),Rn=({size:t=18})=>ee(t,r("path",{d:"M15 5l-7 7 7 7"}));var zn=({size:t=18})=>ee(t,r("path",{d:"M12 4H6.5A2.5 2.5 0 0 0 4 6.5v11A2.5 2.5 0 0 0 6.5 20h11a2.5 2.5 0 0 0 2.5-2.5V12M17.5 3.5a2.1 2.1 0 0 1 3 3L13 14l-4 1 1-4z"})),Dn=({size:t=14})=>ee(t,r("path",{d:"M5 12.5l4.2 4.2L19 7"})),Pn=({size:t=14})=>ee(t,r("path",{d:"M4 12a8 8 0 1 0 2.3-5.6M4 4v4h4"}));var St={current:null};function Gi(t){return t?t.speaking?"speaking":t.agentState==="thinking"?"reasoning":t.agentState==="listening"||t.phase==="live"?"listening":"idle":"idle"}function Un({client:t,call:e,state:n,src:i,onStatus:a}){let s=V(null),[o,l]=C(!1),p=V(!1),d=(()=>{try{return new URL(i).origin}catch{return null}})(),f=(c,g)=>{let b=s.current?.contentWindow;b&&d&&b.postMessage({cx:"face",...c},d,g??[])};L(()=>{if(!d){a("unavailable");return}let c=!1,g=x=>{if(x.source!==s.current?.contentWindow||x.origin!==d)return;let m=x.data;m?.cx==="face"&&(m.type==="loaded"?(p.current=!0,l(!0),t.videoAvatar().then(k=>{c||(k?f({type:"init",avatar:k}):a("unavailable"))}).catch(()=>!c&&a("unavailable"))):m.type==="ready"?(St.current=typeof m.faceEmotion=="string"?m.faceEmotion:null,a("ready")):m.type==="unavailable"&&a("unavailable"))};window.addEventListener("message",g);let b=setTimeout(()=>!c&&!p.current&&a("unavailable"),15e3);return()=>{c=!0,clearTimeout(b),window.removeEventListener("message",g)}},[t,d]);let _=Gi(n);return L(()=>{o&&f({type:"state",state:_})},[_,o]),L(()=>{if(!e||!o)return;let c=[e.on("face",({corr:x,payload:m})=>f({type:"batch",corr:x,payload:m},[m.buffer])),e.on("line",({corr:x,event:m})=>{f(m==="audible"?{type:"audible",corr:x,ms:e.audible()?.ms??0}:{type:"end",corr:x})})],g=0,b=()=>{let x=e.audible();x&&f({type:"clock",corr:x.corr,ms:x.ms}),g=requestAnimationFrame(b)};return g=requestAnimationFrame(b),()=>{c.forEach(x=>x()),cancelAnimationFrame(g)}},[e,o]),d?r("iframe",{ref:s,class:"face-frame",src:i,title:"","aria-hidden":"true",tabIndex:-1,allow:"autoplay",sandbox:"allow-scripts allow-same-origin",referrerpolicy:"strict-origin"}):null}function Qi(){if(typeof document>"u")return!1;let t=navigator.userAgent;return/Safari\//.test(t)&&!/(Chrome|Chromium|Edg|OPR|Firefox)\//.test(t)?!1:document.createElement("video").canPlayType('video/webm; codecs="vp9"')!==""}var ea=()=>typeof matchMedia<"u"&&matchMedia("(prefers-reduced-motion: reduce)").matches;function Ee({agent:t,shot:e,talking:n=!1,still:i=!1,full:a=!1,class:s}){let o=V(null),[l,p]=C({w:0,h:0}),[d,f]=C(null),[_,c]=C({}),[g,b]=C({}),x=t.video,m=(S,D,ie)=>!a&&S&&!g[ie]?S:D,k=x?.anchor?.alphaUrl??x?.anchor?.url??null,w=m(x?.anchor?.smallUrl,k,"anchor"),N=w!==k,U=!i&&!ea()&&Qi(),O=x?.clips.idle,H=x?.clips.talking??O,B=m(O?.smallUrl,O?.alphaUrl??null,"idle"),W=m(H?.smallUrl,H?.alphaUrl??null,"talk")??B,[Z,v]=C(a);if(L(()=>{n&&v(!0)},[n]),Ve(()=>{let S=o.current;if(!S)return;let D=()=>p({w:S.clientWidth,h:S.clientHeight});if(D(),typeof ResizeObserver>"u")return;let ie=new ResizeObserver(D);return ie.observe(S),()=>ie.disconnect()},[]),!x||!w)return r("div",{ref:o,class:`portrait portrait--initial ${s??""}`,"aria-hidden":"true",children:r("span",{children:(t.name||"?").slice(0,1).toUpperCase()})});let J=(x.anchor?.width&&x.anchor?.height?{w:x.anchor.width,h:x.anchor.height}:null)??(d&&!N?d:null),se=kn(x,J?.w??0,J?.h??0),Y=l.w&&l.h&&J?Tn(se,J.w/J.h,l.w,l.h,e):null,oe=Y?{width:`${Y.width}px`,height:`${Y.height}px`,left:`${Y.left}px`,top:`${Y.top}px`}:{},K=!!Y&&U&&!!B&&!!_.idle,ne=!!Y&&U&&!!W&&W!==B&&!!_.talk&&n,M=!!Y&&(!!d||K);return r("div",{ref:o,class:`portrait ${s??""}`,"aria-hidden":"true",children:[r("img",{class:"portrait__media",src:w,alt:"",draggable:!1,style:{...oe,opacity:Y&&d&&!K?1:0},onLoad:S=>{let D=S.currentTarget;f({w:D.naturalWidth,h:D.naturalHeight})},onError:()=>N&&b(S=>({...S,anchor:!0}))}),U&&B?r(On,{src:B,style:oe,visible:K&&!ne,onReady:()=>c(S=>({...S,idle:!0})),onFail:()=>b(S=>({...S,idle:!0}))}):null,U&&Z&&W&&W!==B?r(On,{src:W,style:oe,visible:ne,onReady:()=>c(S=>({...S,talk:!0})),onFail:()=>b(S=>({...S,talk:!0}))}):null,r("span",{class:`portrait__sparkle${M?" is-done":""}`,children:[r("i",{}),r("i",{}),r("i",{})]})]})}function On({src:t,style:e,visible:n,onReady:i,onFail:a}){let s=V(null);return L(()=>{let o=s.current;o&&(n?o.play().catch(()=>{}):o.pause())},[n]),r("video",{ref:s,class:"portrait__media portrait__clip",src:t,muted:!0,loop:!0,playsInline:!0,preload:"auto",style:{...e,opacity:n?1:0},onLoadedData:i,onError:a})}var Tt="cxyz:greeted",$n="cxyz:introduced";function Ie(t,e){try{return e!==void 0&&localStorage.setItem(t,e),localStorage.getItem(t)}catch{return null}}function ta(){try{let t=window.AudioContext??window.webkitAudioContext,e=new t,n=e.currentTime;[660,880].forEach((i,a)=>{let s=e.createOscillator(),o=e.createGain();s.type="sine",s.frequency.value=i,o.gain.setValueAtTime(0,n+a*.16),o.gain.linearRampToValueAtTime(.18,n+a*.16+.02),o.gain.exponentialRampToValueAtTime(1e-4,n+a*.16+.5),s.connect(o).connect(e.destination),s.start(n+a*.16),s.stop(n+a*.16+.55)}),setTimeout(()=>{e.close()},1200)}catch{}}function na(t){let[e,n]=C(t.chat.messages),[i,a]=C(t.chat.isBusy);return L(()=>{let s=t.chat.on("messages",n),o=t.chat.on("busy",a);return()=>{s(),o()}},[t]),{messages:e,busy:i}}function ia(t){let[e,n]=C(t.call),[i,a]=C(t.call?.state??null),[s,o]=C([]);return L(()=>t.on("call",l=>l&&n(l)),[t]),L(()=>{if(!e)return;a(e.state),o([]);let l=[e.on("state",a),e.on("caption",p=>o(d=>[...d.filter(f=>f.id!==p.id),p].slice(-4))),e.on("captionRemoved",p=>o(d=>d.filter(f=>f.id!==p)))];return()=>l.forEach(p=>p())},[e]),{call:e,state:i,captions:s,reset:()=>n(null)}}function aa(t,e){let[n,i]=C(Date.now());return L(()=>{if(!e)return;let a=setInterval(()=>i(Date.now()),1e3);return()=>clearInterval(a)},[e]),t?Math.max(0,(n-t)/1e3):0}function ra(t,e,n){L(()=>{if(!t||!n)return;let i=0,a=0,s=()=>{let o=t.voiceLevel();a=a*.7+o*.3,e.current?.style.setProperty("--cx-lvl",a.toFixed(3)),i=requestAnimationFrame(s)};return i=requestAnimationFrame(s),()=>cancelAnimationFrame(i)},[t,n,e])}function Nn({parts:t}){return r(F,{children:t.map((e,n)=>e.t==="b"?r("strong",{children:e.v},n):e.t==="i"?r("em",{children:e.v},n):e.t==="code"?r("code",{children:e.v},n):e.t==="link"?r("a",{href:e.href,target:"_blank",rel:"noopener noreferrer nofollow",children:e.v},n):e.v.split(`
42
- `).map((i,a,s)=>r(F,{children:[i,a<s.length-1?r("br",{}):null]},`${n}.${a}`)))})}var sa={name:{label:"nameField",type:"text",auto:"name"},email:{label:"emailField",type:"email",auto:"email"},phone:{label:"phoneField",type:"tel",auto:"tel"},company:{label:"companyField",type:"text",auto:"organization"},reason:{label:"reasonField",type:"text",auto:"off"}};function oa(){try{let t=new URLSearchParams(location.search).get("reason")??new URLSearchParams(location.search).get("intent");return t&&t.trim()?t.trim().slice(0,120):(document.querySelector("character-xyz")?.getAttribute("data-reason")??"").trim().slice(0,120)}catch{return""}}function la({form:t,title:e,note:n,onSend:i,onSkip:a,skipLabel:s,initial:o,hasHistory:l}){let[p,d]=C(()=>({...o??{}})),f=t.required??["name","email"],_=M=>f.includes(M),c=t.reasonOptions??[],g=t.fields.includes("reason"),b=g&&!l?oa():"",x=t.reasonDefault||b||"",[m,k]=C(x),[w,N]=C(t.reasonDefault?t.reasonSource??"conversation":b?"cta":""),[U,O]=C(g&&!x),[H,B]=C(!1),[W,Z]=C(""),[v,$]=C({}),[J,se]=C(null),[Y,oe]=C(!1),K=V(null),ne=V(null);return L(()=>{setTimeout(()=>K.current?.focus({preventScroll:!0}),80)},[]),Ve(()=>{let M=ne.current?.closest(".log");if(!M)return;let S=M.style.scrollBehavior;M.style.scrollBehavior="auto",M.scrollTop=M.scrollHeight,M.style.scrollBehavior=S},[U,H]),r("form",{class:"card",part:"details",ref:ne,onSubmit:async M=>{M.preventDefault(),oe(!0),$({}),se(null);try{let S=(H?W:m).trim();await i({name:p.name??"",email:p.email??"",...p.phone?{phone:p.phone}:{},...p.company?{company:p.company}:{},...g&&S?{reason:S}:{}})}catch(S){let D=S.fields??{};Object.keys(D).length?$(D):se(S.message||h("sendFailed"))}finally{oe(!1)}},children:[r("div",{class:"card__title",children:e}),n?r("div",{class:"card__note",children:n}):null,t.fields.map((M,S)=>{if(M==="reason")return r("div",{class:"card__field card__field--reason",children:[!U&&m?null:r("span",{class:"card__reason-label",children:t.reasonLabel||h("reasonField")}),!U&&m?r(F,{children:[r("div",{class:"card__reason-line",children:[r("span",{class:"card__reason-said",children:h("reasonInferred")}),r("strong",{children:m}),r("button",{type:"button",class:"card__change",onClick:()=>O(!0),children:h("change")})]}),w?r("span",{class:"card__reason-src",children:w==="cta"?h("reasonFromPage"):w==="conversation"?h("reasonFromConversation"):null}):null]}):r("div",{class:"card__reason-edit",children:[c.length?r("div",{class:"card__chips",role:"group","aria-label":t.reasonLabel||h("reasonField"),children:[c.map(G=>r("button",{type:"button",class:"card__chip","aria-pressed":!H&&m===G,onClick:()=>{k(G),B(!1),N("user"),O(!1)},children:G},G)),r("button",{type:"button",class:"card__chip","aria-pressed":H,onClick:()=>{B(!0),k("")},children:h("reasonOther")})]}):null,H||!c.length?r("input",{type:"text",maxLength:500,placeholder:h("reasonPlaceholder"),value:W,onInput:G=>Z(G.currentTarget.value)}):null]}),v.reason?r("em",{children:v.reason}):null]},M);let D=sa[M],ie=h(D.label);return r("label",{class:"card__field",children:[r("span",{children:[ie,_(M)?null:r("i",{children:[" \xB7 ",h("optional")]})]}),r("input",{ref:S===0?K:void 0,type:D.type,autocomplete:D.auto,required:_(M),maxLength:M==="email"?254:120,value:p[M]??"","aria-invalid":v[M]?"true":void 0,onInput:G=>d(Qe=>({...Qe,[M]:G.currentTarget.value}))}),v[M]?r("em",{children:v[M]}):null]},M)}),r("div",{class:"card__consent",children:[t.consent,t.privacyUrl?r(F,{children:[" ",r("a",{href:t.privacyUrl,target:"_blank",rel:"noopener noreferrer",children:h("privacyPolicy")})]}):null]}),J?r("div",{class:"card__failed",children:J}):null,r("div",{class:"card__actions",children:[r("button",{type:"submit",class:"btn btn--accent btn--sm",disabled:Y,children:Y?h("sending"):h("send")}),r("button",{type:"button",class:"btn btn--ghost btn--sm",onClick:a,disabled:Y,children:s})]})]})}function At({items:t,onPick:e,children:n}){return!t.length&&!n?null:r("div",{class:"chips chips--start",part:"suggestions",children:[t.map(i=>r("button",{class:"chip",onClick:()=>e(i),children:i},i)),n]})}function Hn({text:t}){return r(F,{children:gn(t).map((e,n)=>e.t==="ul"?r("ul",{children:e.items.map((i,a)=>r("li",{children:r(Nn,{parts:i})},a))},n):r("p",{children:r(Nn,{parts:e.parts})},n))})}function Bn({client:t,config:e,bind:n,onView:i}){let a=t.agent,s=t.features,o=e.showChat&&s.chat,l=e.showCall&&s.call,[p,d]=C(e.open?o?"chat":"call":"closed"),[f,_]=C(!1),[c,g]=C(!1),{messages:b,busy:x}=na(t),{call:m,state:k,captions:w,reset:N}=ia(t),[U,O]=C(""),H=V(null),B=V(null),W=V(null),Z=e.subtitle??a.tagline,v=a.name||h("assistant"),[$,J]=C(null);L(()=>{if(!o)return;let u=!0;return t.opening().then(T=>{u&&(xn(T?.strings),J(T))}),()=>{u=!1}},[t,o]);let se=e.greeting||$?.teaser||"",Y=e.suggestions.length?e.suggestions:$?.suggestions??[],oe=$?.greeting||h("greetingDefault",{name:v}),[K,ne]=C("loading"),[M,S]=C(!1),[D,ie]=C(null),[G,Qe]=C(""),[et,tt]=C(null),[nt,it]=C(null),te=Ae(u=>{d(u),i(u)},[i]),ue=Ae(()=>{_(!0),setTimeout(()=>{_(!1),te("closed")},200)},[te]),xe=Ae(async()=>{try{let u=await t.chat.load();ne(T=>T==="loading"?u.length?u.length:"empty":T)}catch{ne(u=>u==="loading"?"empty":u)}},[t]),Q=Ae((u=o?"chat":"call")=>{g(!1),Ie(Tt,"1"),te(u),u==="chat"&&xe()},[o,te,xe]);L(()=>n({open:Q,close:ue}),[n,Q,ue]),L(()=>t.on("siteEvent",u=>{u.openChat&&Q("chat")}),[t,Q]),L(()=>{e.open&&o&&xe()},[xe,e.open,o]),L(()=>{if(!se||Ie(Tt))return;let u=setTimeout(()=>g(!0),e.greetingDelay*1e3);return()=>clearTimeout(u)},[se,e.greetingDelay]),L(()=>{if(p!=="chat"||M||K==="loading")return;let u=setTimeout(()=>S(!0),700);return()=>clearTimeout(u)},[p,M,K]);let[at,Vn]=C(()=>!Ie($n));L(()=>{if(!at)return;let u=setTimeout(()=>{Vn(!1),Ie($n,"1")},5e3);return()=>clearTimeout(u)},[at]),L(()=>{if(p==="closed")return;let u=T=>{T.key==="Escape"&&ue()};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[p,ue]),L(()=>{let u=H.current;u&&(u.scrollTop=u.scrollHeight)},[b,p,k?.phase]),L(()=>{p==="chat"&&setTimeout(()=>B.current?.focus({preventScroll:!0}),60)},[p]);let be=e.face&&!!a.video,[Fe,Kn]=C("loading"),A=k?.phase??"idle";L(()=>{if(!(A!=="ready"||!m)){if(ta(),p==="call"){if(!be||Fe!=="loading"){m.accept();return}let u=setTimeout(()=>m.accept(),3e3);return()=>clearTimeout(u)}if(typeof document<"u"&&document.hidden){let u=document.title;document.title=`\u25CF ${v} is ready for you`;let T=()=>{document.title=u,document.removeEventListener("visibilitychange",T)};document.addEventListener("visibilitychange",T)}}},[A,m,p,v,be,Fe]);let It=A==="live"||A==="connecting";ra(m,W,It&&p==="call");let Le=aa(k?.startedAt??null,A==="live"),rt=ca(m,k?.position??1),st=()=>{let u=$?.details;if(u&&!D&&o){tt(u),te("chat"),xe();return}ot()},Ft=(u,T="")=>{ie(u),Qe(T),it(null);let he=!!et;tt(null),he&&ot()},Xn=async u=>{await t.sendDetails(u),Ft("sent",u.name.trim().split(/\s+/)[0]??"")},Zn=()=>{t.declineDetails().catch(()=>{}),Ft("skipped")},Jn=async()=>{try{await t.chat.reset()}catch{return}ne("empty"),S(!1),ie(null),tt(null),it(null),O(""),J(await t.opening(!0))},ot=async()=>{te("call");try{await t.startCall({autoAccept:!1,...be?{face:{emotion:()=>St.current}}:{}})}catch{}},lt=[...b].reverse().find(u=>u.detailsForm||u.askDetails)?.detailsForm??[...b].reverse().find(u=>u.askDetails)?.askDetails??$?.details??null,ve=async u=>{let T=u.trim();if(!T||x)return;let he=lt&&D!=="sent"?Mn(T):null;he&&lt&&it({form:lt,values:he}),O(""),B.current&&(B.current.style.height="");try{await t.chat.send(T)}catch{}},Re=b[b.length-1],Lt=Re?.role==="agent"&&!Re.streaming?Re.askDetails:void 0,q=et?{form:et,kind:"call"}:nt&&D!=="sent"&&!x?{form:nt.form,kind:"typed",initial:nt.values}:Lt&&!D?{form:Lt,kind:"invited"}:null;if(p==="closed"){let u=A==="queued"||A==="ready"||A==="live"||A==="connecting";return r("div",{class:`dock dock--${e.display}`,part:"launcher",children:[c?r("div",{class:"greeting",part:"greeting",role:"status",onClick:()=>Q(),children:[se,r("button",{class:"greeting__close","aria-label":h("dismiss"),onClick:T=>{T.stopPropagation(),g(!1),Ie(Tt,"1")},children:r(Je,{size:14})})]}):null,r("button",{class:`presence presence--${e.display} ${u?"presence--live":""}`,part:"presence","aria-label":u?A==="queued"?h("inLineToCall",{position:ce(k?.position??1),name:v}):h("backToCallWith",{name:v}):o?h("chatWith",{name:v}):h("callName",{name:v}),onClick:()=>Q(u||!o?"call":"chat"),children:[e.display==="bubble"?r("span",{class:"presence__ring"}):null,r("span",{class:"presence__face",children:r(Ee,{agent:a,shot:e.display==="full"?Sn:e.display==="half"?Cn:Ze})}),r("span",{class:"presence__dot"}),t.mode==="test"?r("span",{class:"testmode",title:"Test mode: this key only works on development sites",children:"TEST"}):null,A==="queued"?r("span",{class:"presence__badge","aria-hidden":"true",children:k?.position??1}):null,e.launcher==="bubble"&&!c?r("span",{class:"presence__label","aria-hidden":"true",children:u?A==="queued"?h("inLine",{position:ce(k?.position??1)}):h("backToCall"):o?h("chatWith",{name:v}):h("callName",{name:v})}):null]}),e.launcher==="bubble"?null:r("div",{class:`acts ${at?"acts--labelled":""}`,part:"actions",children:[o?r("button",{class:"act","aria-label":h("chatWith",{name:v}),onClick:()=>Q("chat"),children:[r(Me,{size:20}),r("span",{class:"act__label","aria-hidden":"true",children:h("chat")})]}):null,l?r("button",{class:`act act--call ${u?"act--live":""}`,"aria-label":u?A==="queued"?h("inLineOpen",{position:ce(k?.position??1)}):h("backToCall"):h("callName",{name:v}),onClick:()=>u?Q("call"):st(),children:[r(_e,{size:20}),r("span",{class:"act__label","aria-hidden":"true",children:u?A==="queued"?h("inLine",{position:ce(k?.position??1)}):h("onCall"):h("call")}),A==="queued"?r("span",{class:"act__badge","aria-hidden":"true",children:k?.position??1}):null]}):null]})]})}let Gn=r("div",{class:"head",part:"header",children:[r("div",{class:"head__face",children:r(Ee,{agent:a,shot:Ze})}),r("div",{class:"head__who",children:[r("div",{class:"head__name",children:v}),r("div",{class:"head__sub",children:[r("i",{}),x?h("typing"):Z||h("online")]})]}),p==="chat"&&b.length>0&&!x?r("button",{class:"icon-btn","aria-label":h("newConversation"),title:h("newConversation"),onClick:()=>{Jn()},children:r(zn,{})}):null,l&&p==="chat"?r("button",{class:"icon-btn icon-btn--accent","aria-label":h("callName",{name:v}),title:h("callName",{name:v}),onClick:()=>m&&A!=="ended"?te("call"):st(),children:r(_e,{size:18})}):null,r("button",{class:"icon-btn","aria-label":h("close"),onClick:ue,children:r(Je,{})})]});if(p==="chat")return r("div",{class:`panel ${f?"is-closing":""}`,part:"panel",role:"dialog","aria-label":h("chatWith",{name:v}),children:[Gn,m&&(A==="queued"||A==="ready")?r("div",{class:"banner",part:"banner",role:"status",children:[r("div",{class:"banner__text",children:A==="queued"?r(F,{children:h("inLineFor",{position:ce(k?.position??1),eta:Xe(k?.etaSeconds??null)})}):r(F,{children:[r("b",{children:h("readyForYou",{name:v})})," \xB7 ",h("secondsToJoin",{seconds:k?.holdSeconds??30})]})}),A==="ready"?r("button",{class:"btn btn--accent btn--glow",onClick:()=>{m.accept(),te("call")},children:h("join")}):r("button",{class:"btn",onClick:()=>te("call"),children:h("view")})]}):null,r("div",{class:"log",ref:H,role:"log","aria-live":"polite","aria-relevant":"additions",children:[b.length===0?r(F,{children:[r("div",{class:"empty",children:[r("div",{class:"empty__face",children:r(Ee,{agent:a,shot:Ze})}),r("div",{class:"empty__title",children:v}),Z?r("div",{class:"empty__body",children:Z}):null]}),K==="loading"?null:M?r(F,{children:[r("div",{class:"msg msg--agent",part:"message message-agent",children:r(Hn,{text:oe})}),q?null:r(At,{items:Y,onPick:u=>{ve(u)},children:l?r("button",{class:"chip chip--call",onClick:()=>m&&A!=="ended"?te("call"):st(),children:[r(_e,{size:14})," ",h("callName",{name:v})]}):null})]}):r("div",{class:"msg msg--agent typing","aria-label":h("typingName",{name:v}),children:[r("i",{}),r("i",{}),r("i",{})]})]}):null,b.map(u=>u.role==="event"?r("div",{class:"event",part:"event message message-event",children:[r("span",{class:"event__dot","aria-hidden":"true"}),u.text]},u.id):u.role==="agent"&&u.streaming&&!u.text?r("div",{class:"msg msg--agent typing","aria-label":h("typingName",{name:v}),children:[r("i",{}),r("i",{}),r("i",{})]},u.id):r(F,{children:[r("div",{class:`msg msg--${u.role} ${u.failed?"msg--failed":""} ${u.streaming?"caret":""}`,part:`message message-${u.role}`,children:u.role==="agent"?r(Hn,{text:u.text}):u.text}),u===b[b.length-1]&&u.role==="agent"&&!u.streaming&&!x&&!q&&u.suggestions?.length?r(At,{items:u.suggestions,onPick:T=>{ve(T)}}):null,u.failed&&u.error?r("div",{class:"msg__why",role:"status",children:u.error}):u.failed?r("button",{class:"msg__retry",onClick:()=>{t.chat.retry(u.id).catch(()=>{})},children:[r(Pn,{})," ",h("notSent")]}):null]},u.id)),typeof K=="number"&&b.length===K&&$?.welcomeBack?r(F,{children:[r("div",{class:"msg msg--agent",part:"message message-agent",children:$.welcomeBack}),q?null:r(At,{items:Y,onPick:u=>{ve(u)}})]}):null,q?r(la,{form:q.form,initial:q.initial,title:q.kind==="call"?h("beforeYouCall",{name:v}):q.kind==="typed"?h("confirmDetails"):h("leaveDetails"),note:q.kind==="call"?h("detailsWhy"):q.kind==="typed"?h("detailsTyped"):null,onSend:Xn,onSkip:Zn,skipLabel:q.kind==="call"?h("skipAndCall"):h("notNow"),hasHistory:b.length>0},q.kind==="invited"?Re?.id:q.kind):D==="sent"?r("div",{class:"notice",role:"status",children:[r(Dn,{})," ",G?h("thanksName",{name:G}):h("thanks")]}):null]}),r("form",{class:"compose",part:"composer",onSubmit:u=>{u.preventDefault(),ve(U)},children:r("div",{class:"compose__box",children:[r("textarea",{ref:B,rows:1,value:U,maxLength:2e3,placeholder:e.placeholder===de.placeholder?h("message"):e.placeholder,"aria-label":h("message"),onInput:u=>{let T=u.currentTarget;O(T.value),T.style.height="auto",T.style.height=`${Math.min(120,T.scrollHeight)}px`},onKeyDown:u=>{u.key==="Enter"&&!u.shiftKey&&!u.isComposing&&(u.preventDefault(),ve(U))}}),r("button",{class:"send",type:"submit","aria-label":h("send"),disabled:!U.trim()||x,children:r(Ln,{})})]})}),e.branding?r("div",{class:"foot",children:h("poweredBy").split("{brand}").map((u,T)=>r(F,{children:[T?r("a",{href:"https://character.xyz",target:"_blank",rel:"noopener noreferrer",children:"Character XYZ"}):null,u]},T))}):null]});let E=k,ct=E?.position??1,Qn=rt>1?(rt-ct)/(rt-1):0,dt=74,Rt=2*Math.PI*dt,ye=E?.maxSeconds?E.maxSeconds-Le:null,ei=E?.agentState??"idle",ti=E?.speaking?h("speaking"):ei==="thinking"?h("thinking"):h("listening"),ni=!E||A==="ended"||A==="idle",pt=bn(E?.endReason??null,v);return r("div",{class:`panel ${f?"is-closing":""}`,part:"panel",role:"dialog","aria-label":h("callWith",{name:v}),children:r("div",{class:`stage ${be&&Fe==="ready"?"stage--face":""}`,ref:W,children:[r("div",{class:"stage__figure",style:{opacity:A==="queued"?.35:1,transition:"opacity .6s"},children:[r(Ee,{agent:a,shot:wn,talking:!!E?.speaking,full:!0}),be?r("div",{class:`stage__face ${Fe==="ready"?"is-ready":""}`,children:r(Un,{client:t,call:m,state:E,src:e.faceUrl,onStatus:Kn})}):null]}),It?r("div",{class:"voice"}):null,r("div",{class:"stage__veil"}),r("div",{class:"stage__top",children:[A==="live"?r("span",{class:`badge ${ye!=null&&ye<=60?"badge--warn":""}`,role:"timer","aria-label":h("callTime"),children:[r("i",{}),ye!=null&&ye<=60?h("timeLeft",{time:Ke(ye)}):Ke(Le)]}):r("span",{}),r("div",{style:{display:"flex",gap:"6px"},children:[o?r("button",{class:"icon-btn","aria-label":h("chat"),title:h("chat"),onClick:()=>Q("chat"),children:r(Me,{size:18})}):null,r("button",{class:"icon-btn","aria-label":h("minimise"),onClick:ue,children:r(Je,{})})]})]}),r("div",{class:"stage__bottom","aria-live":"polite",children:[A==="joining"||A==="connecting"?r(F,{children:[r("div",{class:"stage__name",children:v}),r("div",{class:"stage__status",children:[r("span",{class:"spinner"})," ",A==="joining"?h("connecting"):h("joining")]})]}):null,A==="queued"?r(F,{children:[r("div",{class:"line",role:"status","aria-label":h("inLineEta",{position:ce(ct),eta:Xe(E?.etaSeconds??null)}),children:[r("svg",{width:"168",height:"168",viewBox:"0 0 168 168",children:[r("circle",{class:"line__track",cx:"84",cy:"84",r:dt,fill:"none","stroke-width":"7"}),r("circle",{class:"line__fill",cx:"84",cy:"84",r:dt,fill:"none","stroke-width":"7","stroke-linecap":"round","stroke-dasharray":Rt,"stroke-dashoffset":Rt*(1-Math.max(.06,Qn))})]}),r("div",{children:[r("div",{class:"line__num",children:ce(ct)}),r("div",{class:"line__lbl",children:h("lineLabel")})]})]}),r("div",{class:"title",children:h("onOtherCalls",{name:v})}),r("div",{class:"note",children:h(o?"yourTurnChat":"yourTurn",{eta:Xe(E?.etaSeconds??null)})}),r("div",{class:"btn-row",children:[o?r("button",{class:"btn btn--accent",onClick:()=>Q("chat"),children:[r(Me,{size:18})," ",h("keepChatting")]}):null,r("button",{class:"btn",onClick:()=>{m?.hangUp()},children:h("leaveLine")})]})]}):null,A==="ready"?r(F,{children:[r("div",{class:"title",children:h("readyForYou",{name:v})}),r("div",{class:"note",children:h("joinWithin",{seconds:E?.holdSeconds??30})}),r("button",{class:"btn btn--accent btn--glow",onClick:()=>m?.accept(),children:[r(_e,{size:18})," ",h("joinCall")]})]}):null,A==="live"?r(F,{children:[r("div",{class:"stage__name",children:v}),r("div",{class:"stage__status",children:[E?.speaking?r("span",{class:"wave","aria-hidden":"true",children:[.6,1,.75,1,.55].map((u,T)=>r("i",{style:{"--k":u}},T))}):null,E?.muted?h("muted"):ti]}),r("div",{class:"captions",children:w.slice(-2).map((u,T,he)=>r("div",{class:`captions__line ${T===he.length-1?"captions__line--now":""}`,children:u.role==="visitor"?h("you",{text:u.text}):u.text},u.id))}),r("div",{class:"controls",children:[r("div",{class:"ctl",children:[r("button",{class:`round ${E?.muted?"round--on":""}`,"aria-pressed":E?.muted,"aria-label":E?.muted?h("unmute"):h("mute"),onClick:()=>m?.setMuted(!E?.muted),children:E?.muted?r(Fn,{size:22}):r(In,{size:22})}),r("span",{class:"round__label",children:E?.muted?h("unmute"):h("mute")})]}),r("div",{class:"ctl",children:[r("button",{class:"round round--end","aria-label":h("endCall"),onClick:()=>{m?.hangUp()},children:r(En,{size:26})}),r("span",{class:"round__label",children:h("end")})]}),E?.speaking?r("div",{class:"ctl",children:[r("button",{class:"round","aria-label":h("interruptName",{name:v}),onClick:()=>m?.interrupt(),children:r(Rn,{size:22})}),r("span",{class:"round__label",children:h("interrupt")})]}):null]})]}):null,ni?r(F,{children:[r("div",{class:"title",children:E?pt.title:h("callName",{name:v})}),r("div",{class:"note",children:E?E.endReason==="hangup"&&Le?`${Ke(Le)} \xB7 ${pt.body}`:E.error??pt.body:h("talkWith",{name:v})}),r("div",{class:"btn-row",children:[l&&E?.endReason!=="credits"&&E?.endReason!=="unavailable"&&E?.endReason!=="daily_limit"?r("button",{class:"btn btn--accent",onClick:()=>{N(),ot()},children:[r(_e,{size:18})," ",E?h("callAgain"):h("startCall")]}):null,o?r("button",{class:"btn",onClick:()=>Q("chat"),children:[r(Me,{size:18})," ",h("chat")]}):null]})]}):null]})]})})}function ca(t,e){let n=V({call:null,start:e});return n.current.call!==t&&(n.current={call:t,start:e}),e>n.current.start&&(n.current.start=e),n.current.start}var Wn=`
38
+ `))!==-1;){let a=n.slice(0,i);n=n.slice(i+2);let s="message",o=[];for(let c of a.split(`
39
+ `)){if(!c||c.startsWith(":"))continue;let f=c.indexOf(":"),x=f===-1?c:c.slice(0,f),d=f===-1?"":c.slice(f+1).replace(/^ /,"");x==="event"?s=d:x==="data"&&o.push(d)}if(!o.length)continue;let l=o.join(`
40
+ `),u=l;try{u=JSON.parse(l)}catch{}t({event:s,data:u})}return n}function Ti(e){if(e.byteLength<25)return null;let t=new DataView(e);if(t.getUint8(0)!==67||t.getUint8(1)!==88||t.getUint8(2)!==89||t.getUint8(3)!==90||t.getUint8(4)!==1)return null;let n=t.getUint8(5),i=(t.getUint8(6)&1)!==0,a=7,s=t.getUint16(a,!0);if(a+=2,a+s+20>e.byteLength)return null;let o=new TextDecoder().decode(new Uint8Array(e,a,s));a+=s+4+8+4;let l=t.getUint32(a,!0);return a+=4,a+l>e.byteLength?null:{kind:n,final:i,corr:o,payload:new Uint8Array(e,a,l)}}var Ai=.09,Mi=350,Ei=25e3,Li=()=>({phase:"idle",callId:null,position:null,etaSeconds:null,holdSeconds:null,maxSeconds:null,startedAt:null,endReason:null,muted:!1,speaking:!1,agentState:"idle",error:null}),Fi=class extends gt{constructor(e,t,n,i={}){super(),k(this,"apiUrl",e),k(this,"session",t),k(this,"agentId",n),k(this,"opts",i),k(this,"s",Li()),k(this,"ticket",null),k(this,"eventsAbort",null),k(this,"ws",null),k(this,"mic",null),k(this,"players",new Map),k(this,"sampleRates",new Map),k(this,"cancelled",new Set),k(this,"speakingCorr",null),k(this,"heartbeat",null),k(this,"loudSince",null)}get state(){return this.s}audible(){let e=this.speakingCorr,t=e?this.players.get(e):void 0;return e&&t?{corr:e,ms:t.playedMs()}:null}voiceLevel(){let e=this.speakingCorr?this.players.get(this.speakingCorr):void 0;return e?e.level():0}set(e){this.s={...this.s,...e},this.emit("state",this.s)}async start(){if(this.s.phase==="idle"){this.set({phase:"joining"}),Ht();try{this.mic=await wi({deviceId:this.opts.deviceId,onFrame:(e,t)=>this.onMicFrame(e,t)})}catch{this.finish("mic-denied","Allow the microphone to talk, or chat instead.");return}try{let e=await this.session.token(),t=await G(this.apiUrl,"/sdk/v1/calls",{method:"POST",body:{},token:e});this.set({callId:t.callId,phase:t.state==="ready"?"joining":"queued",position:t.position??null,etaSeconds:t.etaSeconds??null}),this.follow()}catch(e){let t=e instanceof Y?e:new Y("unknown","Could not start the call."),n=t.code==="rate_limited"?"busy":"unavailable";this.finish(n,t.message),this.emit("error",t)}}}async follow(){let e=0;for(;this.s.callId&&this.s.phase!=="ended"&&this.s.phase!=="idle";){this.eventsAbort=new AbortController;try{let t=await this.session.token(),n=await Se(this.apiUrl,`/sdk/v1/calls/${encodeURIComponent(this.s.callId)}/events`,{token:t,signal:this.eventsAbort.signal});e=0,await Wt(n,i=>this.onServerEvent(i.event,i.data),this.eventsAbort.signal)}catch(t){if(t?.name==="AbortError")return;if(t instanceof Y&&t.code==="not_found"){this.finish("failed","The call ended.");return}if(e+=1,e>5){this.finish("failed","Lost the connection to the call.");return}}if(this.ended())return;await new Promise(t=>setTimeout(t,Math.min(4e3,500*2**e)))}}onServerEvent(e,t){switch(e){case"queued":(this.s.phase==="joining"||this.s.phase==="queued")&&this.set({phase:"queued",position:Number(t.position)||1,etaSeconds:Number(t.etaSeconds)||null});break;case"ready":{typeof t.ticket=="string"&&t.ticket&&(this.ticket=t.ticket);let n=Number(t.holdSeconds)||0;this.s.phase!=="ready"&&this.s.phase!=="connecting"&&this.s.phase!=="live"?(this.set({phase:"ready",holdSeconds:n,position:null,etaSeconds:null}),this.emit("ready",{holdSeconds:n}),this.opts.autoAccept!==!1&&this.accept()):this.s.phase==="ready"&&this.set({holdSeconds:n});break}case"live":this.set({phase:"live",maxSeconds:Number(t.maxSeconds)||null,startedAt:this.s.startedAt??Date.now()-(Number(t.elapsedSeconds)||0)*1e3});break;case"ended":this.finish(String(t.reason||"hangup")||"hangup",null);break}}ended(){return this.s.phase==="ended"}accept(){if(this.s.phase!=="ready"||!this.ticket||this.ws)return;this.set({phase:"connecting"});let e=this.apiUrl.replace(/^http/,"ws")+"/sdk/v1/calls/socket",t=new WebSocket(e,[`cxyz-ticket.${this.ticket}`]);this.ticket=null,t.binaryType="arraybuffer",this.ws=t,t.onopen=()=>{let n=this.opts.face,i=n?.emotion?.()??null;t.send(JSON.stringify({type:"agent_identity",agent_id:this.agentId,skin_index:0,blendshapes:!!n,...n?{blendshape_stream:!0}:{},...n&&i?{face_emotion:i}:{}})),t.send(JSON.stringify({type:"mic_state",silero:"off",denoise:!1})),this.heartbeat=setInterval(()=>this.sendJson({type:"heartbeat"}),Ei),this.set({phase:"live",startedAt:this.s.startedAt??Date.now()})},t.onmessage=n=>this.onSocket(n.data),t.onclose=()=>{this.ws=null,setTimeout(()=>{(this.s.phase==="live"||this.s.phase==="connecting")&&this.finish("hangup",null)},1500)}}sendJson(e){this.ws?.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify(e))}onMicFrame(e,t){let n=this.ws;if(!(!n||n.readyState!==WebSocket.OPEN)){if(this.speakingCorr){let i=performance.now();if(t>Ai){if(this.loudSince??(this.loudSince=i),i-this.loudSince>=Mi){this.loudSince=null,this.interrupt(),n.send(e);return}}else this.loudSince=null;n.send(new ArrayBuffer(e.byteLength));return}n.send(e)}}onSocket(e){if(e instanceof ArrayBuffer){let n=Ti(e);if(!n||this.cancelled.has(n.corr))return;if(n.kind===3){this.opts.face&&this.emit("face",{corr:n.corr,payload:n.payload.slice()});return}if(n.kind!==1)return;let i=this.players.get(n.corr);if(!i){for(let[s,o]of this.players)o.stop(),this.players.delete(s);let a=n.corr;i=new bi({sampleRate:this.sampleRates.get(a)??16e3,onStart:()=>{this.speakingCorr=a,this.set({speaking:!0}),this.emit("line",{corr:a,event:"audible"}),this.sendJson({type:"playback_started",correlationId:a,timestampMs:Date.now()})},onEnd:()=>{this.players.delete(a),this.speakingCorr===a&&(this.speakingCorr=null),this.set({speaking:!1}),this.emit("line",{corr:a,event:"end"}),this.sendJson({type:"playback_ended",correlationId:a,timestampMs:Date.now(),reason:"natural"}),this.sendJson({type:"speech_ended"})}}),this.players.set(a,i)}i.enqueue(n.payload),n.final&&i.end();return}if(typeof e!="string")return;let t;try{t=JSON.parse(e)}catch{return}if("AgentSpeechMeta"in t){let n=t.AgentSpeechMeta;n?.correlation_id&&n.sample_rate&&this.sampleRates.set(n.correlation_id,n.sample_rate);return}if("InteractorTranscript"in t){let n=t.InteractorTranscript;n?.text&&this.emit("caption",{id:`v:${n.correlation_id}`,role:"visitor",text:n.text});return}if("AgentReplyTranscript"in t){let n=t.AgentReplyTranscript;n?.text&&!this.cancelled.has(n.correlation_id)&&this.emit("caption",{id:`a:${n.correlation_id}`,role:"agent",text:n.text});return}if(t.type==="turn_cancelled"&&typeof t.correlationId=="string"){let n=t.correlationId;this.cancelled.add(n),this.players.get(n)?.stop(),this.players.delete(n),this.emit("line",{corr:n,event:"end"}),this.speakingCorr===n&&(this.speakingCorr=null,this.set({speaking:!1})),this.emit("captionRemoved",`a:${n}`);return}t.kind==="agent_status"&&typeof t.state=="string"&&this.set({agentState:t.state.toLowerCase()})}interrupt(){let e=this.speakingCorr;if(!e)return;let t=this.players.get(e),n=Math.round(t?.playedMs()??0);t?.stop(),this.players.delete(e),this.cancelled.add(e),this.speakingCorr=null,this.set({speaking:!1}),this.emit("line",{corr:e,event:"end"}),this.sendJson({type:"playback_ended",correlationId:e,timestampMs:Date.now(),reason:"interrupted"}),this.sendJson({type:"interrupt",correlationId:e,heardMs:n,timestampMs:Date.now()})}setMuted(e){this.mic?.setMuted(e),this.set({muted:e})}async hangUp(){let e=this.s.callId,t=this.s.phase;if(this.finish(t==="live"?"hangup":"left",null),!!e)try{let n=await this.session.token();await Se(this.apiUrl,`/sdk/v1/calls/${encodeURIComponent(e)}`,{method:"DELETE",token:n})}catch{}}finish(e,t){if(this.s.phase==="ended")return;this.eventsAbort?.abort(),this.eventsAbort=null,this.heartbeat&&clearInterval(this.heartbeat),this.heartbeat=null;for(let i of this.players.values())i.stop();this.players.clear(),this.speakingCorr=null,this.mic?.stop(),this.mic=null;let n=this.ws;this.ws=null,n&&n.readyState<=WebSocket.OPEN&&n.close(1e3),this.ticket=null,this.set({phase:"ended",endReason:e,speaking:!1,holdSeconds:null,error:t})}},Ii=0,Ot=e=>`${e}_${Date.now().toString(36)}_${(Ii++).toString(36)}`,Ri=class extends gt{constructor(e,t){super(),k(this,"apiUrl",e),k(this,"session",t),k(this,"list",[]),k(this,"loaded",!1),k(this,"busy",!1),k(this,"abort",null)}get messages(){return this.list}get isBusy(){return this.busy}publish(){this.list=[...this.list],this.emit("messages",this.list)}applySiteEvent(e){let t=!1;e.event&&!this.list.some(n=>n.id===e.event.id)&&(this.list.push(e.event),t=!0),e.message&&!this.list.some(n=>n.id===e.message.id)&&(this.list.push({...e.message,...e.suggestions?.length?{suggestions:e.suggestions}:{},...e.askDetails?{askDetails:e.askDetails}:{}}),t=!0),t&&this.publish()}async load(){if(this.loaded)return this.list;let e=await this.session.token(),t=await G(this.apiUrl,"/sdk/v1/chat/messages?limit=50",{token:e}),n=this.list;return this.list=[...t?.messages??[],...n],this.loaded=!0,this.publish(),this.list}async send(e){let t=e.trim();if(!t)throw new Y("invalid","Say something first.");if(this.busy)throw new Y("rate_limited","Wait for the reply first.");this.setBusy(!0);let n={id:Ot("local"),role:"visitor",text:t,createdAt:new Date().toISOString()},i={id:Ot("reply"),role:"agent",text:"",createdAt:new Date().toISOString(),streaming:!0};this.list.push(n,i),this.publish(),this.abort=new AbortController;try{let a=await this.session.token(),s=await Se(this.apiUrl,"/sdk/v1/chat/messages",{method:"POST",body:{text:t},token:a,signal:this.abort.signal}),o=null,l=null;if(await Wt(s,({event:c,data:f})=>{let x=f;if(c==="delta"&&typeof x?.text=="string")i.text+=x.text,this.publish();else if(c==="done"){let d=Array.isArray(x.suggestions)?x.suggestions.filter(g=>typeof g=="string"&&g.trim()!==""):[];o={id:String(x.id),role:"agent",text:String(x.text??i.text),createdAt:String(x.createdAt??i.createdAt),...d.length?{suggestions:d}:{},...x.askDetails&&typeof x.askDetails=="object"?{askDetails:x.askDetails}:{},...x.detailsForm&&typeof x.detailsForm=="object"?{detailsForm:x.detailsForm}:{}}}else c==="error"&&(l=typeof x?.message=="string"?x.message:"Something went wrong.")},this.abort.signal),l||!o)throw new Y("unknown",l??"The reply was cut off. Try again.");let u=o;return this.replace(i.id,u),u}catch(a){let s=a instanceof Y?a:new Y("network","The reply was cut off. Try again.");this.list=this.list.filter(l=>l.id!==i.id);let o=this.list.findIndex(l=>l.id===n.id);throw o!==-1&&(this.list[o]={...n,failed:!0,...s.status===429?{error:s.message}:{}}),this.publish(),a?.name!=="AbortError"&&this.emit("error",s),s}finally{this.abort=null,this.setBusy(!1)}}async reset(){this.stop();let e=await this.session.token();await Se(this.apiUrl,"/sdk/v1/chat/messages",{method:"DELETE",token:e}),this.list=[],this.loaded=!0,this.publish()}retry(e){let t=this.list.find(n=>n.id===e&&n.failed);if(!t)throw new Y("not_found","Nothing to retry.");return this.list=this.list.filter(n=>n.id!==e),this.publish(),this.send(t.text)}stop(){this.abort?.abort()}replace(e,t){let n=this.list.findIndex(i=>i.id===e);n!==-1&&(this.list[n]=t),this.publish()}setBusy(e){this.busy=e,this.emit("busy",e)}},Di=()=>{let e=new Map;return{get:t=>e.get(t)??null,set:(t,n)=>{e.set(t,n)}}},Pi=()=>({get(e){try{return globalThis.localStorage?.getItem(e)??null}catch{return null}},set(e,t){try{globalThis.localStorage?.setItem(e,t)}catch{}}}),zi=60,Ui=class{constructor(e){if(k(this,"src",e),k(this,"current",null),k(this,"inflight",null),!e.publishableKey&&!e.getSessionToken)throw new Y("invalid","Pass a publishableKey, or getSessionToken for sessions your server mints.")}visitorKey(){return`cxyz:visitor:${(this.src.publishableKey??"server").slice(-12)}`}get info(){return this.current}async token(){let e=Date.now()/1e3;return this.current&&this.current.expiresAt-zi>e?this.current.token:(await this.refresh()).token}refresh(){return this.inflight??(this.inflight=this.mint().finally(()=>{this.inflight=null})),this.inflight}async mint(){let e;if(this.src.getSessionToken){let t=await this.src.getSessionToken();typeof t=="string"?e=await this.describe(t):e=t}else{let t=this.src.store.get(this.visitorKey())??void 0;e=await G(this.src.apiUrl,"/sdk/v1/sessions",{method:"POST",body:{publishableKey:this.src.publishableKey,agentId:this.src.agentId,visitorId:t}}),this.src.store.set(this.visitorKey(),e.visitorId)}return this.current=e,e}async describe(e){return{...await G(this.src.apiUrl,"/sdk/v1/session",{token:e}),token:e}}},Oi="https://api.character.xyz",$t=class Nt extends gt{constructor(t,n,i){super(),k(this,"apiUrl",t),k(this,"session",n),k(this,"info",i),k(this,"chat"),k(this,"currentCall",null),k(this,"destroyed",!1),k(this,"openingP",null),k(this,"actionHandlers",new Map),this.chat=new Ri(t,n)}static async init(t){let n=(t.apiUrl??Oi).replace(/\/+$/,"");if(t.publishableKey&&/^cxyz_sk_/.test(t.publishableKey))throw new Y("invalid","That is a SECRET key. Never put it in a web page: use a publishable key (cxyz_pk_\u2026). Revoke the secret key now.");let i=t.storage==="memory"?Di():t.storage&&typeof t.storage=="object"?t.storage:Pi(),a=new Ui({apiUrl:n,agentId:t.agentId,publishableKey:t.publishableKey,getSessionToken:t.getSessionToken,store:i}),s=await a.refresh();return new Nt(n,a,s)}get agent(){return(this.session.info??this.info).agent}get features(){return(this.session.info??this.info).features}get appearance(){return(this.session.info??this.info).appearance??{}}get visitorId(){return(this.session.info??this.info).visitorId}get mode(){return(this.session.info??this.info).mode}get call(){return this.currentCall&&this.currentCall.state.phase!=="ended"?this.currentCall:null}async videoAvatar(){let t=await this.session.token();return G(this.apiUrl,"/sdk/v1/agent/video-avatar",{token:t})}opening(t=!1){return t&&(this.openingP=null),this.openingP??(this.openingP=this.session.token().then(n=>{let i=typeof navigator>"u"?"":navigator.language||"",a=i?`/sdk/v1/agent/opening?locale=${encodeURIComponent(i)}`:"/sdk/v1/agent/opening";return G(this.apiUrl,a,{token:n})}).catch(()=>null)),this.openingP}async sendDetails(t){let n=await this.session.token(),i=typeof location<"u"?location.href:void 0;await G(this.apiUrl,"/sdk/v1/lead",{token:n,body:{...t,consent:!0,...i?{page:i}:{}}})}async declineDetails(){let t=await this.session.token();await G(this.apiUrl,"/sdk/v1/lead/decline",{token:t,method:"POST",body:{}})}async identify(t){let n=await this.session.token();await G(this.apiUrl,"/sdk/v1/context",{token:n,method:"POST",body:{visitor:t}})}async setContext(t){let n=await this.session.token();await G(this.apiUrl,"/sdk/v1/context",{token:n,method:"POST",body:{context:t}})}async track(t,n={},i={}){let a=await this.session.token(),s=i.id??Hi(),o=await G(this.apiUrl,"/sdk/v1/track",{token:a,method:"POST",body:{name:t,data:n,id:s},keepalive:!0});this.emit("siteEvent",o),!o.accepted&&o.ignored&&o.ignored!=="duplicate"&&console.warn(`[characterxyz] event "${t}" ignored: ${o.ignored}`);for(let u of o.actions??[])this.runAction(u);let l=0;for(;o.action&&l++<4;){let u=o.action,c=await this.runAction(u);o=await G(this.apiUrl,`/sdk/v1/actions/${encodeURIComponent(u.id)}`,{token:a,method:"POST",body:c}),this.emit("siteEvent",o)}return this.chat.applySiteEvent(o),o}registerAction(t,n){return this.actionHandlers.set(t,n),()=>{this.actionHandlers.get(t)===n&&this.actionHandlers.delete(t)}}async runAction(t){let n=this.actionHandlers.get(t.name);if(!n)return{ok:!1,error:`no handler registered for "${t.name}"`};try{return{ok:!0,result:await n(t.inputs??{},t.name)??null}}catch(i){return{ok:!1,error:String(i?.message??i)}}}async startCall(t={}){if(this.destroyed)throw new Y("invalid","This client was destroyed.");if(!this.features.call)throw new Y("forbidden","Calls are not available on this site.");if(this.call)return this.call;let n=new Fi(this.apiUrl,this.session,this.agent.id,t);return this.currentCall=n,n.on("state",i=>{i.phase==="ended"&&this.currentCall===n&&this.emit("call",null)}),n.on("error",i=>this.emit("error",i)),this.emit("call",n),await n.start(),n}destroy(){this.destroyed=!0,this.currentCall?.hangUp(),this.chat.stop(),this.chat.clear(),this.actionHandlers.clear(),this.clear()}};function Hi(){let e=typeof crypto<"u"?crypto:void 0;return e&&typeof e.randomUUID=="function"?`evt_${e.randomUUID()}`:`evt_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`}var Ye,F,Vt,Wi,ce,Bt,Xt,Kt,mt,Oe,Te,Zt,vt,xt,_t,$i,$e={},Ne=[],Ni=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,qe=Array.isArray;function re(e,t){for(var n in t)e[n]=t[n];return e}function bt(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function Bi(e,t,n){var i,a,s,o={};for(s in t)s=="key"?i=t[s]:s=="ref"?a=t[s]:o[s]=t[s];if(arguments.length>2&&(o.children=arguments.length>3?Ye.call(arguments,2):n),typeof e=="function"&&e.defaultProps!=null)for(s in e.defaultProps)o[s]===void 0&&(o[s]=e.defaultProps[s]);return He(e,o,i,a,null)}function He(e,t,n,i,a){var s={type:e,props:t,key:n,ref:i,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:a??++Vt,__i:-1,__u:0};return a==null&&F.vnode!=null&&F.vnode(s),s}function I(e){return e.children}function We(e,t){this.props=e,this.context=t}function pe(e,t){if(t==null)return e.__?pe(e.__,e.__i+1):null;for(var n;t<e.__k.length;t++)if((n=e.__k[t])!=null&&n.__e!=null)return n.__e;return typeof e.type=="function"?pe(e):null}function Yi(e){if(e.__P&&e.__d){var t=e.__v,n=t.__e,i=[],a=[],s=re({},t);s.__v=t.__v+1,F.vnode&&F.vnode(s),yt(e.__P,s,t,e.__n,e.__P.namespaceURI,32&t.__u?[n]:null,i,n??pe(t),!!(32&t.__u),a),s.__v=t.__v,s.__.__k[s.__i]=s,tn(i,s,a),t.__e=t.__=null,s.__e!=n&&Jt(s)}}function Jt(e){if((e=e.__)!=null&&e.__c!=null)return e.__e=e.__c.base=null,e.__k.some(function(t){if(t!=null&&t.__e!=null)return e.__e=e.__c.base=t.__e}),Jt(e)}function Yt(e){(!e.__d&&(e.__d=!0)&&ce.push(e)&&!Be.__r++||Bt!=F.debounceRendering)&&((Bt=F.debounceRendering)||Xt)(Be)}function Be(){try{for(var e,t=1;ce.length;)ce.length>t&&ce.sort(Kt),e=ce.shift(),t=ce.length,Yi(e)}finally{ce.length=Be.__r=0}}function Gt(e,t,n,i,a,s,o,l,u,c,f){var x,d,g,b,v,m,_=i&&i.__k||Ne,w=t.length;for(u=qi(n,t,_,u,w),x=0;x<w;x++)(g=n.__k[x])!=null&&(d=g.__i!=-1&&_[g.__i]||$e,g.__i=x,m=yt(e,g,d,a,s,o,l,u,c,f),b=g.__e,g.ref&&d.ref!=g.ref&&(d.ref&&kt(d.ref,null,g),f.push(g.ref,g.__c||b,g)),v==null&&b!=null&&(v=b),4&g.__u?(u=Qt(g,u,e),d.__e&&(d.__e=null)):typeof g.type=="function"&&m!==void 0?u=m:b&&(u=b.nextSibling),g.__u&=-7);return n.__e=v,u}function qi(e,t,n,i,a){var s,o,l,u,c,f=n.length,x=f,d=0;for(e.__k=new Array(a),s=0;s<a;s++)(o=t[s])!=null&&typeof o!="boolean"&&typeof o!="function"?(typeof o=="string"||typeof o=="number"||typeof o=="bigint"||o.constructor==String?o=e.__k[s]=He(null,o,null,null,null):qe(o)?o=e.__k[s]=He(I,{children:o},null,null,null):o.constructor===void 0&&o.__b>0?o=e.__k[s]=He(o.type,o.props,o.key,o.ref?o.ref:null,o.__v):e.__k[s]=o,u=s+d,o.__=e,o.__b=e.__b+1,l=null,(c=o.__i=ji(o,n,u,x))!=-1&&(x--,(l=n[c])&&(l.__u|=2)),l==null||l.__v==null?(c==-1&&(a>f?d--:a<f&&d++),typeof o.type!="function"&&(o.__u|=4)):c!=u&&(c==u-1?d--:c==u+1?d++:(c>u?d--:d++,o.__u|=4))):e.__k[s]=null;if(x)for(s=0;s<f;s++)(l=n[s])!=null&&(2&l.__u)==0&&(l.__e==i&&(i=pe(l)),an(l,l));return i}function Qt(e,t,n){var i,a;if(typeof e.type=="function"){for(i=e.__k,a=0;i&&a<i.length;a++)i[a]&&(i[a].__=e,t=Qt(i[a],t,n));return t}e.__e!=t&&(t&&e.type&&!t.parentNode&&(t=pe(e)),t=n.insertBefore(e.__e,t||null));do t=t&&t.nextSibling;while(t!=null&&t.nodeType==8);return t}function ji(e,t,n,i){var a,s,o,l=e.key,u=e.type,c=t[n],f=c!=null&&(2&c.__u)==0;if(c===null&&l==null||f&&l==c.key&&u==c.type)return n;if(i>(f?1:0)){for(a=n-1,s=n+1;a>=0||s<t.length;)if((c=t[o=a>=0?a--:s++])!=null&&(2&c.__u)==0&&l==c.key&&u==c.type)return o}return-1}function qt(e,t,n){t[0]=="-"?e.setProperty(t,n??""):e[t]=n==null?"":typeof n!="number"||Ni.test(t)?n:n+"px"}function Ue(e,t,n,i,a){var s,o;e:if(t=="style")if(typeof n=="string")e.style.cssText=n;else{if(typeof i=="string"&&(e.style.cssText=i=""),i)for(t in i)n&&t in n||qt(e.style,t,"");if(n)for(t in n)i&&n[t]==i[t]||qt(e.style,t,n[t])}else if(t[0]=="o"&&t[1]=="n")s=t!=(t=t.replace(Zt,"$1")),o=t.toLowerCase(),t=o in e||t=="onFocusOut"||t=="onFocusIn"?o.slice(2):t.slice(2),e.l||(e.l={}),e.l[t+s]=n,n?i?n[Te]=i[Te]:(n[Te]=vt,e.addEventListener(t,s?_t:xt,s)):e.removeEventListener(t,s?_t:xt,s);else{if(a=="http://www.w3.org/2000/svg")t=t.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(t!="width"&&t!="height"&&t!="href"&&t!="list"&&t!="form"&&t!="tabIndex"&&t!="download"&&t!="rowSpan"&&t!="colSpan"&&t!="role"&&t!="popover"&&t in e)try{e[t]=n??"";break e}catch{}typeof n=="function"||(n==null||n===!1&&t[4]!="-"?e.removeAttribute(t):e.setAttribute(t,t=="popover"&&n==1?"":n))}}function jt(e){return function(t){if(this.l){var n=this.l[t.type+e];if(t[Oe]==null)t[Oe]=vt++;else if(t[Oe]<n[Te])return;return n(F.event?F.event(t):t)}}}function yt(e,t,n,i,a,s,o,l,u,c){var f,x,d,g,b,v,m,_,w,O,z,H,$,P,q,V,y=t.type;if(t.constructor!==void 0)return null;128&n.__u&&(u=!!(32&n.__u),s=[l=t.__e=n.__e]),(f=F.__b)&&f(t);e:if(typeof y=="function"){x=o.length;try{if(w=t.props,O=y.prototype&&y.prototype.render,z=(f=y.contextType)&&i[f.__c],H=f?z?z.props.value:f.__:i,n.__c?_=(d=t.__c=n.__c).__=d.__E:(O?t.__c=d=new y(w,H):(t.__c=d=new We(w,H),d.constructor=y,d.render=Xi),z&&z.sub(d),d.state||(d.state={}),d.__n=i,g=d.__d=!0,d.__h=[],d._sb=[]),O&&d.__s==null&&(d.__s=d.state),O&&y.getDerivedStateFromProps!=null&&(d.__s==d.state&&(d.__s=re({},d.__s)),re(d.__s,y.getDerivedStateFromProps(w,d.__s))),b=d.props,v=d.state,d.__v=t,g)O&&y.getDerivedStateFromProps==null&&d.componentWillMount!=null&&d.componentWillMount(),O&&d.componentDidMount!=null&&d.__h.push(d.componentDidMount);else{if(O&&y.getDerivedStateFromProps==null&&w!==b&&d.componentWillReceiveProps!=null&&d.componentWillReceiveProps(w,H),t.__v==n.__v||!d.__e&&d.shouldComponentUpdate!=null&&d.shouldComponentUpdate(w,d.__s,H)===!1){t.__v!=n.__v&&(d.props=w,d.state=d.__s,d.__d=!1),t.__e=n.__e,t.__k=n.__k,t.__k.some(function(C){C&&(C.__=t)}),Ne.push.apply(d.__h,d._sb),d._sb=[],d.__h.length&&o.push(d),l=pe(n);break e}d.componentWillUpdate!=null&&d.componentWillUpdate(w,d.__s,H),O&&d.componentDidUpdate!=null&&d.__h.push(function(){d.componentDidUpdate(b,v,m)})}if(d.context=H,d.props=w,d.__P=e,d.__e=!1,$=F.__r,P=0,O)d.state=d.__s,d.__d=!1,$&&$(t),f=d.render(d.props,d.state,d.context),Ne.push.apply(d.__h,d._sb),d._sb=[];else do d.__d=!1,$&&$(t),f=d.render(d.props,d.state,d.context),d.state=d.__s;while(d.__d&&++P<25);d.state=d.__s,d.getChildContext!=null&&(i=re(re({},i),d.getChildContext())),O&&!g&&d.getSnapshotBeforeUpdate!=null&&(m=d.getSnapshotBeforeUpdate(b,v)),q=f!=null&&f.type===I&&f.key==null?nn(f.props.children):f,l=Gt(e,qe(q)?q:[q],t,n,i,a,s,o,l,u,c),d.base=t.__e,t.__u&=-161,d.__h.length&&o.push(d),_&&(d.__E=d.__=null)}catch(C){if(o.length=x,t.__v=null,u||s!=null){if(C.then){for(t.__u|=u?160:128;l&&l.nodeType==8&&l.nextSibling;)l=l.nextSibling;s!=null&&(s[s.indexOf(l)]=null),t.__e=l}else if(s!=null)for(V=s.length;V--;)bt(s[V])}else t.__e=n.__e;t.__k==null&&(t.__k=n.__k||[]),C.then||en(t),F.__e(C,t,n)}}else s==null&&t.__v==n.__v?(t.__k=n.__k,t.__e=n.__e):l=t.__e=Vi(n.__e,t,n,i,a,s,o,u,c);return(f=F.diffed)&&f(t),128&t.__u?void 0:l}function en(e){e&&(e.__c&&(e.__c.__e=!0),e.__k&&e.__k.some(en))}function tn(e,t,n){for(var i=0;i<n.length;i++)kt(n[i],n[++i],n[++i]);F.__c&&F.__c(t,e),e.some(function(a){try{e=a.__h,a.__h=[],e.some(function(s){s.call(a)})}catch(s){F.__e(s,a.__v)}})}function nn(e){return typeof e!="object"||e==null||e.__b>0?e:qe(e)?e.map(nn):e.constructor!==void 0?null:re({},e)}function Vi(e,t,n,i,a,s,o,l,u){var c,f,x,d,g,b,v,m=n.props||$e,_=t.props,w=t.type;if(w=="svg"?a="http://www.w3.org/2000/svg":w=="math"?a="http://www.w3.org/1998/Math/MathML":a||(a="http://www.w3.org/1999/xhtml"),s!=null){for(c=0;c<s.length;c++)if((g=s[c])&&"setAttribute"in g==!!w&&(w?g.localName==w:g.nodeType==3)){e=g,s[c]=null;break}}if(e==null){if(w==null)return document.createTextNode(_);e=document.createElementNS(a,w,_.is&&_),l&&(F.__m&&F.__m(t,s),l=!1),s=null}if(w==null)m===_||l&&e.data==_||(e.data=_);else{if(s=w=="textarea"&&_.defaultValue!=null?null:s&&Ye.call(e.childNodes),!l&&s!=null)for(m={},c=0;c<e.attributes.length;c++)m[(g=e.attributes[c]).name]=g.value;for(c in m)g=m[c],c=="dangerouslySetInnerHTML"?x=g:c=="children"||c in _||c=="value"&&"defaultValue"in _||c=="checked"&&"defaultChecked"in _||Ue(e,c,null,g,a);for(c in _)g=_[c],c=="children"?d=g:c=="dangerouslySetInnerHTML"?f=g:c=="value"?b=g:c=="checked"?v=g:l&&typeof g!="function"||m[c]===g||Ue(e,c,g,m[c],a);if(f)l||x&&(f.__html==x.__html||f.__html==e.innerHTML)||(e.innerHTML=f.__html),t.__k=[];else if(x&&(e.innerHTML=""),Gt(t.type=="template"?e.content:e,qe(d)?d:[d],t,n,i,w=="foreignObject"?"http://www.w3.org/1999/xhtml":a,s,o,s?s[0]:n.__k&&pe(n,0),l,u),s!=null)for(c=s.length;c--;)bt(s[c]);l&&w!="textarea"||(c="value",w=="progress"&&b==null?e.removeAttribute("value"):b!=null&&(b!==e[c]||w=="progress"&&!b||w=="option"&&b!=m[c])&&Ue(e,c,b,m[c],a),c="checked",v!=null&&v!=e[c]&&Ue(e,c,v,m[c],a))}return e}function kt(e,t,n){try{if(typeof e=="function"){var i=typeof e.__u=="function";i&&e.__u(),i&&t==null||(e.__u=e(t))}else e.current=t}catch(a){F.__e(a,n)}}function an(e,t,n){var i,a;if(F.unmount&&F.unmount(e),(i=e.ref)&&(i.current&&i.current!=e.__e||kt(i,null,t)),(i=e.__c)!=null){if(i.componentWillUnmount)try{i.componentWillUnmount()}catch(s){F.__e(s,t)}i.base=i.__P=i.__n=null}if(i=e.__k)for(a=0;a<i.length;a++)i[a]&&an(i[a],t,n||typeof e.type!="function");n||bt(e.__e),e.__c=e.__=e.__e=void 0}function Xi(e,t,n){return this.constructor(e,n)}function wt(e,t,n){var i,a,s,o;t==document&&(t=document.documentElement),F.__&&F.__(e,t),a=(i=typeof n=="function")?null:n&&n.__k||t.__k,s=[],o=[],yt(t,e=(!i&&n||t).__k=Bi(I,null,[e]),a||$e,$e,t.namespaceURI,!i&&n?[n]:a?null:t.firstChild?Ye.call(t.childNodes):null,s,!i&&n?n:a?a.__e:t.firstChild,i,o),tn(s,e,o),e.props.children=null}Ye=Ne.slice,F={__e:function(e,t,n,i){for(var a,s,o;t=t.__;)if((a=t.__c)&&!a.__)try{if((s=a.constructor)&&s.getDerivedStateFromError!=null&&(a.setState(s.getDerivedStateFromError(e)),o=a.__d),a.componentDidCatch!=null&&(a.componentDidCatch(e,i||{}),o=a.__d),o)return a.__E=a}catch(l){e=l}throw e}},Vt=0,Wi=function(e){return e!=null&&e.constructor===void 0},We.prototype.setState=function(e,t){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=re({},this.state),typeof e=="function"&&(e=e(re({},n),this.props)),e&&re(n,e),e!=null&&this.__v&&(t&&this._sb.push(t),Yt(this))},We.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),Yt(this))},We.prototype.render=I,ce=[],Xt=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Kt=function(e,t){return e.__v.__b-t.__v.__b},Be.__r=0,mt=Math.random().toString(8),Oe="__d"+mt,Te="__a"+mt,Zt=/(PointerCapture)$|Capture$/i,vt=0,xt=jt(!1),_t=jt(!0),$i=0;var _e,U,Ct,rn,Ae=0,hn=[],W=F,sn=W.__b,on=W.__r,ln=W.diffed,cn=W.__c,dn=W.unmount,un=W.__;function Ve(e,t){W.__h&&W.__h(U,e,Ae||t),Ae=0;var n=U.__H||(U.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function S(e){return Ae=1,Ki(gn,e)}function Ki(e,t,n){var i=Ve(_e++,2);if(i.t=e,!i.__c&&(i.__=[n?n(t):gn(void 0,t),function(l){var u=i.__N?i.__N[0]:i.__[0],c=i.t(u,l);u!==c&&(i.__N=[c,i.__[1]],i.__c.setState({}))}],i.__c=U,!U.__f)){var a=function(l,u,c){if(!i.__c.__H)return!0;var f=!1,x=i.__c.props!==l;if(i.__c.__H.__.some(function(g){if(g.__N){f=!0;var b=g.__[0];g.__=g.__N,g.__N=void 0,b!==g.__[0]&&(x=!0)}}),s){var d=s.call(this,l,u,c);return f?d||x:d}return!f||x};U.__f=!0;var s=U.shouldComponentUpdate,o=U.componentWillUpdate;U.componentWillUpdate=function(l,u,c){if(this.__e){var f=s;s=void 0,a(l,u,c),s=f}o&&o.call(this,l,u,c)},U.shouldComponentUpdate=a}return i.__N||i.__}function R(e,t){var n=Ve(_e++,3);!W.__s&&Tt(n.__H,t)&&(n.__=e,n.u=t,U.__H.__h.push(n))}function Xe(e,t){var n=Ve(_e++,4);!W.__s&&Tt(n.__H,t)&&(n.__=e,n.u=t,U.__h.push(n))}function Z(e){return Ae=5,fn(function(){return{current:e}},[])}function fn(e,t){var n=Ve(_e++,7);return Tt(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}function Me(e,t){return Ae=8,fn(function(){return e},t)}function Zi(){for(var e;e=hn.shift();){var t=e.__H;if(e.__P&&t)try{t.__h.some(je),t.__h.some(St),t.__h=[]}catch(n){t.__h=[],W.__e(n,e.__v)}}}W.__b=function(e){U=null,sn&&sn(e)},W.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),un&&un(e,t)},W.__r=function(e){on&&on(e),_e=0;var t=(U=e.__c).__H;t&&(Ct===U?(t.__h=[],U.__h=[],t.__.some(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(t.__h.some(je),t.__h.some(St),t.__h=[],_e=0)),Ct=U},W.diffed=function(e){ln&&ln(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(hn.push(t)!==1&&rn===W.requestAnimationFrame||((rn=W.requestAnimationFrame)||Ji)(Zi)),t.__H.__.some(function(n){n.u&&(n.__H=n.u,n.u=void 0)})),Ct=U=null},W.__c=function(e,t){t.some(function(n){try{n.__h.some(je),n.__h=n.__h.filter(function(i){return!i.__||St(i)})}catch(i){t.some(function(a){a.__h&&(a.__h=[])}),t=[],W.__e(i,n.__v)}}),cn&&cn(e,t)},W.unmount=function(e){dn&&dn(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.some(function(i){try{je(i)}catch(a){t=a}}),n.__H=void 0,t&&W.__e(t,n.__v))};var pn=typeof requestAnimationFrame=="function";function Ji(e){var t,n=function(){clearTimeout(i),pn&&cancelAnimationFrame(t),setTimeout(e)},i=setTimeout(n,35);pn&&(t=requestAnimationFrame(n))}function je(e){var t=U,n=e.__c;typeof n=="function"&&(e.__c=void 0,n()),U=t}function St(e){var t=U;e.__c=e.__(),U=t}function Tt(e,t){return!e||e.length!==t.length||t.some(function(n,i){return n!==e[i]})}function gn(e,t){return typeof t=="function"?t(e):t}function xn(e){let t=e%100;if(t>=11&&t<=13)return`${e}th`;switch(e%10){case 1:return`${e}st`;case 2:return`${e}nd`;case 3:return`${e}rd`;default:return`${e}th`}}function Ke(e){let t=Math.max(0,Math.floor(e)),n=Math.floor(t/3600),i=Math.floor(t%3600/60),a=String(t%60).padStart(2,"0");return n?`${n}:${String(i).padStart(2,"0")}:${a}`:`${i}:${a}`}function mn(e){let t=[],n=/(\*\*[^*]+\*\*|`[^`]+`|\[[^\]]+\]\((https?:\/\/[^)\s]+)\)|https?:\/\/[^\s<>()]+[^\s<>().,;:!?'"]|\*[^*\s][^*]*\*)/g,i=0,a;for(;a=n.exec(e);){a.index>i&&t.push({t:"text",v:e.slice(i,a.index)});let s=a[0];s.startsWith("**")?t.push({t:"b",v:s.slice(2,-2)}):s.startsWith("`")?t.push({t:"code",v:s.slice(1,-1)}):s.startsWith("[")?t.push({t:"link",v:s.slice(1,s.indexOf("]")),href:a[2]}):s.startsWith("http")?t.push({t:"link",v:s,href:s}):t.push({t:"i",v:s.slice(1,-1)}),i=a.index+s.length}return i<e.length&&t.push({t:"text",v:e.slice(i)}),t}function _n(e){let t=[];for(let n of e.split(/\n{2,}/)){let i=n.split(`
41
+ `);i.length&&i.every(a=>/^\s*[-*•]\s+/.test(a))?t.push({t:"ul",items:i.map(a=>mn(a.replace(/^\s*[-*•]\s+/,"")))}):t.push({t:"p",parts:mn(n)})}return t}var Gi={assistant:"Assistant",online:"Online",typing:"Typing\u2026",typingName:"{name} is typing",message:"Message",send:"Send",sending:"Sending\u2026",close:"Close",minimise:"Minimise",dismiss:"Dismiss",notNow:"Not now",newConversation:"Start a new conversation",chat:"Chat",chatWith:"Chat with {name}",call:"Call",callName:"Call {name}",callWith:"Call with {name}",startCall:"Start call",callAgain:"Call again",joinCall:"Join call",join:"Join",view:"View",onCall:"On call",backToCall:"Back to your call",backToCallWith:"Back to your call with {name}",callTime:"Call time",timeLeft:"{time} left",endCall:"End call",end:"End",mute:"Mute",unmute:"Unmute",muted:"You are muted",interrupt:"Interrupt",interruptName:"Interrupt {name}",connecting:"Connecting\u2026",joining:"Joining\u2026",speaking:"Speaking",thinking:"Thinking\u2026",listening:"Listening",you:"You: {text}",inLine:"{position} in line",lineLabel:"in line",inLineFor:"You're {position} in line for a call \xB7 {eta}",inLineToCall:"You are {position} in line to call {name}. Open",inLineOpen:"You are {position} in line. Open your call",inLineEta:"You are {position} in line, {eta}",onOtherCalls:"{name} is on other calls",yourTurn:"Your turn in {eta}. We'll chime when it's time.",yourTurnChat:"Your turn in {eta}. We'll chime when it's time, so feel free to keep chatting.",keepChatting:"Keep chatting",leaveLine:"Leave line",readyForYou:"{name} is ready for you",secondsToJoin:"{seconds}s to join",joinWithin:"Join within {seconds} seconds.",talkWith:"Talk with {name} in real time.",etaSoon:"less than a minute",etaMin:"about {n} min",etaHr:"about {n} hr",notSent:"Not sent \xB7 Retry",beforeYouCall:"Before you call {name}",leaveDetails:"Leave your details",confirmDetails:"Confirm your details",detailsWhy:"So the team can follow up, even if the line drops.",detailsTyped:"From what you typed. Check them and send.",reasonField:"Reason",reasonChoose:"Choose a reason",reasonOther:"Something else",reasonPlaceholder:"Tell us in a few words",reasonInferred:"I'll tell the team this is about",reasonFromConversation:"From your conversation",reasonFromPage:"From this page",change:"Change",skipAndCall:"Skip and call",optional:"optional",privacyPolicy:"Privacy policy",thanks:"Thanks. The team will be in touch.",thanksName:"Thanks, {name}. The team will be in touch.",sendFailed:"Could not send. Try again.",nameField:"Name",emailField:"Email",phoneField:"Phone",companyField:"Company",poweredBy:"Powered by {brand}",greetingDefault:"Hi, I'm {name}. How can I help you today?",endedTitle:"Call ended",endedBody:"Thanks for talking with {name}.",leftTitle:"You left the line",leftBody:"You can call again whenever you like.",missedTitle:"You missed your turn",missedBody:"{name} was ready, but the call wasn't joined in time.",stillBusyTitle:"Still busy",stillBusyBody:"Sorry for the wait. {name} is still on other calls. Chat is open meanwhile.",limitTitle:"Time is up",limitBody:"This call reached its time limit.",busyTitle:"All lines are busy",busyBody:"Try again in a few minutes, or keep chatting.",micTitle:"Microphone needed",micBody:"Allow the microphone in your browser to talk, or keep chatting.",silenceBody:"The line was quiet for a minute, so {name} hung up. Call again any time.",restingTitle:"Calls are resting",restingBody:"Calls are done for today. Chat is open.",unavailableTitle:"Calls are unavailable",unavailableBody:"Calls are not available right now. Chat is open.",droppedTitle:"The call dropped",droppedBody:"Something interrupted the call. Try again."},vn={},bn=!0;function yn(e){vn=e??{},bn=!e||!Object.keys(e).length}function h(e,t){let n=vn[e]??Gi[e];if(t)for(let i in t)n=n.split(`{${i}}`).join(String(t[i]));return n}function de(e){return bn?xn(e):String(e)}function Ze(e){if(e==null)return"";if(e<60)return h("etaSoon");let t=Math.round(e/60);return t<60?h("etaMin",{n:t}):h("etaHr",{n:Math.round(t/60)})}function kn(e,t){let n=(i,a)=>({title:h(i),body:h(a,{name:t})});switch(e){case"hangup":return n("endedTitle","endedBody");case"left":return n("leftTitle","leftBody");case"missed":return n("missedTitle","missedBody");case"timeout":return n("stillBusyTitle","stillBusyBody");case"limit":return n("limitTitle","limitBody");case"busy":return n("busyTitle","busyBody");case"mic-denied":return n("micTitle","micBody");case"silence":return n("endedTitle","silenceBody");case"daily_limit":return n("restingTitle","restingBody");case"credits":case"unavailable":return n("unavailableTitle","unavailableBody");default:return n("droppedTitle","droppedBody")}}var wn={cx:.5,cy:.12,span:.06};function Sn(e,t,n){let i=e?.face?.eyes,a=e?.face?.chin;if(!i||!a||!t||!n)return wn;let s=(i.left.x+i.right.x)/2,o=(i.left.y+i.right.y)/2,l=(a.y-o)/n;return l>.005&&l<.5?{cx:s/t,cy:(o+a.y)/2/n,span:l}:wn}var Je={faceFraction:.26,at:{x:.5,y:.5}},Tn={faceFraction:.14,at:{x:.5,y:.34},keepCrown:!0},An={faceFraction:.16,at:{x:.5,y:.22},keepCrown:!0},Mn={fit:"height"},Qi=1.8,Cn=.04;function En(e,t,n,i,a){if("fit"in a){let c=i*t;return{width:c,height:i,left:n/2-e.cx*c,top:0}}let s=i*a.faceFraction/e.span,o=s*t,l=i*a.at.y-e.cy*s,u=l+(e.cy-e.span*Qi)*s;return a.keepCrown&&u<i*Cn&&(l+=i*Cn-u),{width:o,height:s,left:n*a.at.x-e.cx*o,top:l}}var Ln=/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/,ea=/\+?\d[\d\s().-]{5,}\d/g,ta=/\b(?:my name is|i am|i'm|im|this is|name\s*[:-])\s+([A-Za-z][A-Za-z'’-]+(?:\s+[A-Za-z][A-Za-z'’-]+)?)/i,na=new Set(["interested","looking","from","with","here","trying","not","a","an","the","just","also","happy","keen","curious","calling","sure","fine","good","okay","ok"]);function Fn(e){let t={},n=e.match(Ln)?.[0];n&&(t.email=n.replace(/[.,;:]+$/,""));for(let a of e.replace(Ln," ").matchAll(ea)){let s=a[0].replace(/\D/g,"");if(s.length>=7&&s.length<=15){t.phone=a[0].trim();break}}if(!t.email&&!t.phone)return null;let i=e.match(ta)?.[1];if(i){let a=i.split(/\s+/).filter(o=>!na.has(o.toLowerCase())),s=[];for(let o of a){if(["and","here","at","from"].includes(o.toLowerCase()))break;s.push(o)}s.length&&s[0].length>1&&(t.name=s.map(o=>o[0].toUpperCase()+o.slice(1)).join(" "))}return t}var ia=0;function r(e,t,n,i,a,s){t||(t={});var o,l,u=t;if("ref"in u)for(l in u={},t)l=="ref"?o=t[l]:u[l]=t[l];var c={type:e,props:u,key:n,ref:o,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--ia,__i:-1,__u:0,__source:a,__self:s};if(typeof e=="function"&&(o=e.defaultProps))for(l in o)u[l]===void 0&&(u[l]=o[l]);return F.vnode&&F.vnode(c),c}var te=(e,t)=>r("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"1.9","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",focusable:"false",children:t}),Ee=({size:e=20})=>te(e,r("path",{d:"M4 5.5A2.5 2.5 0 0 1 6.5 3h11A2.5 2.5 0 0 1 20 5.5v8a2.5 2.5 0 0 1-2.5 2.5H10l-4.2 3.6a.5.5 0 0 1-.8-.4V16h0A2.5 2.5 0 0 1 4 13.5z"})),ve=({size:e=20})=>te(e,r("path",{d:"M5.2 3.5h3l1.6 4.2-2 1.4a12 12 0 0 0 7.1 7.1l1.4-2 4.2 1.6v3a1.7 1.7 0 0 1-1.8 1.7A16.6 16.6 0 0 1 3.5 5.3 1.7 1.7 0 0 1 5.2 3.5z"})),In=({size:e=22})=>te(e,r("path",{d:"M3 13.6c5-4.4 13-4.4 18 0l-1.7 2.6-3.6-1.3v-2.6a11 11 0 0 0-7.4 0v2.6l-3.6 1.3z"})),Rn=({size:e=20})=>te(e,r(I,{children:[r("rect",{x:"9",y:"3",width:"6",height:"11",rx:"3"}),r("path",{d:"M5.5 11a6.5 6.5 0 0 0 13 0M12 17.5V21"})]})),Dn=({size:e=20})=>te(e,r(I,{children:[r("path",{d:"M9 9v2a3 3 0 0 0 5.1 2.1M15 9.4V6a3 3 0 0 0-5.7-1.3"}),r("path",{d:"M5.5 11a6.5 6.5 0 0 0 10.6 5M18.4 12.5a6.5 6.5 0 0 0 .1-1.5M12 17.5V21M3 3l18 18"})]})),Ge=({size:e=18})=>te(e,r("path",{d:"M6 6l12 12M18 6L6 18"})),Pn=({size:e=18})=>te(e,r("path",{d:"M12 19V5M5.5 11.5L12 5l6.5 6.5"})),zn=({size:e=18})=>te(e,r("path",{d:"M15 5l-7 7 7 7"}));var Un=({size:e=18})=>te(e,r("path",{d:"M12 4H6.5A2.5 2.5 0 0 0 4 6.5v11A2.5 2.5 0 0 0 6.5 20h11a2.5 2.5 0 0 0 2.5-2.5V12M17.5 3.5a2.1 2.1 0 0 1 3 3L13 14l-4 1 1-4z"})),On=({size:e=14})=>te(e,r("path",{d:"M5 12.5l4.2 4.2L19 7"})),Hn=({size:e=14})=>te(e,r("path",{d:"M4 12a8 8 0 1 0 2.3-5.6M4 4v4h4"}));var At={current:null};function aa(e){return e?e.speaking?"speaking":e.agentState==="thinking"?"reasoning":e.agentState==="listening"||e.phase==="live"?"listening":"idle":"idle"}function Wn({client:e,call:t,state:n,src:i,onStatus:a}){let s=Z(null),[o,l]=S(!1),u=Z(!1),c=(()=>{try{return new URL(i).origin}catch{return null}})(),f=(d,g)=>{let b=s.current?.contentWindow;b&&c&&b.postMessage({cx:"face",...d},c,g??[])};R(()=>{if(!c){a("unavailable");return}let d=!1,g=v=>{if(v.source!==s.current?.contentWindow||v.origin!==c)return;let m=v.data;m?.cx==="face"&&(m.type==="loaded"?(u.current=!0,l(!0),e.videoAvatar().then(_=>{d||(_?f({type:"init",avatar:_}):a("unavailable"))}).catch(()=>!d&&a("unavailable"))):m.type==="ready"?(At.current=typeof m.faceEmotion=="string"?m.faceEmotion:null,a("ready")):m.type==="unavailable"&&a("unavailable"))};window.addEventListener("message",g);let b=setTimeout(()=>!d&&!u.current&&a("unavailable"),15e3);return()=>{d=!0,clearTimeout(b),window.removeEventListener("message",g)}},[e,c]);let x=aa(n);return R(()=>{o&&f({type:"state",state:x})},[x,o]),R(()=>{if(!t||!o)return;let d=[t.on("face",({corr:v,payload:m})=>f({type:"batch",corr:v,payload:m},[m.buffer])),t.on("line",({corr:v,event:m})=>{f(m==="audible"?{type:"audible",corr:v,ms:t.audible()?.ms??0}:{type:"end",corr:v})})],g=0,b=()=>{let v=t.audible();v&&f({type:"clock",corr:v.corr,ms:v.ms}),g=requestAnimationFrame(b)};return g=requestAnimationFrame(b),()=>{d.forEach(v=>v()),cancelAnimationFrame(g)}},[t,o]),c?r("iframe",{ref:s,class:"face-frame",src:i,title:"","aria-hidden":"true",tabIndex:-1,allow:"autoplay",sandbox:"allow-scripts allow-same-origin",referrerpolicy:"strict-origin"}):null}function ra(){if(typeof document>"u")return!1;let e=navigator.userAgent;return/Safari\//.test(e)&&!/(Chrome|Chromium|Edg|OPR|Firefox)\//.test(e)?!1:document.createElement("video").canPlayType('video/webm; codecs="vp9"')!==""}var sa=()=>typeof matchMedia<"u"&&matchMedia("(prefers-reduced-motion: reduce)").matches;function Le({agent:e,shot:t,talking:n=!1,still:i=!1,full:a=!1,class:s}){let o=Z(null),[l,u]=S({w:0,h:0}),[c,f]=S(null),[x,d]=S({}),[g,b]=S({}),v=e.video,m=(T,B,ae)=>!a&&T&&!g[ae]?T:B,_=v?.anchor?.alphaUrl??v?.anchor?.url??null,w=m(v?.anchor?.smallUrl,_,"anchor"),O=w!==_,z=!i&&!sa()&&ra(),H=v?.clips.idle,$=v?.clips.talking??H,P=m(H?.smallUrl,H?.alphaUrl??null,"idle"),q=m($?.smallUrl,$?.alphaUrl??null,"talk")??P,[V,y]=S(a);if(R(()=>{n&&y(!0)},[n]),Xe(()=>{let T=o.current;if(!T)return;let B=()=>u({w:T.clientWidth,h:T.clientHeight});if(B(),typeof ResizeObserver>"u")return;let ae=new ResizeObserver(B);return ae.observe(T),()=>ae.disconnect()},[]),!v||!w)return r("div",{ref:o,class:`portrait portrait--initial ${s??""}`,"aria-hidden":"true",children:r("span",{children:(e.name||"?").slice(0,1).toUpperCase()})});let N=(v.anchor?.width&&v.anchor?.height?{w:v.anchor.width,h:v.anchor.height}:null)??(c&&!O?c:null),D=Sn(v,N?.w??0,N?.h??0),j=l.w&&l.h&&N?En(D,N.w/N.h,l.w,l.h,t):null,le=j?{width:`${j.width}px`,height:`${j.height}px`,left:`${j.left}px`,top:`${j.top}px`}:{},J=!!j&&z&&!!P&&!!x.idle,ie=!!j&&z&&!!q&&q!==P&&!!x.talk&&n,E=!!j&&(!!c||J);return r("div",{ref:o,class:`portrait ${s??""}`,"aria-hidden":"true",children:[r("img",{class:"portrait__media",src:w,alt:"",draggable:!1,style:{...le,opacity:j&&c&&!J?1:0},onLoad:T=>{let B=T.currentTarget;f({w:B.naturalWidth,h:B.naturalHeight})},onError:()=>O&&b(T=>({...T,anchor:!0}))}),z&&P?r($n,{src:P,style:le,visible:J&&!ie,onReady:()=>d(T=>({...T,idle:!0})),onFail:()=>b(T=>({...T,idle:!0}))}):null,z&&V&&q&&q!==P?r($n,{src:q,style:le,visible:ie,onReady:()=>d(T=>({...T,talk:!0})),onFail:()=>b(T=>({...T,talk:!0}))}):null,r("span",{class:`portrait__sparkle${E?" is-done":""}`,children:[r("i",{}),r("i",{}),r("i",{})]})]})}function $n({src:e,style:t,visible:n,onReady:i,onFail:a}){let s=Z(null);return R(()=>{let o=s.current;o&&(n?o.play().catch(()=>{}):o.pause())},[n]),r("video",{ref:s,class:"portrait__media portrait__clip",src:e,muted:!0,loop:!0,playsInline:!0,preload:"auto",style:{...t,opacity:n?1:0},onLoadedData:i,onError:a})}var Mt="cxyz:greeted",Nn="cxyz:introduced";function Fe(e,t){try{return t!==void 0&&localStorage.setItem(e,t),localStorage.getItem(e)}catch{return null}}function oa(){try{let e=window.AudioContext??window.webkitAudioContext,t=new e,n=t.currentTime;[660,880].forEach((i,a)=>{let s=t.createOscillator(),o=t.createGain();s.type="sine",s.frequency.value=i,o.gain.setValueAtTime(0,n+a*.16),o.gain.linearRampToValueAtTime(.18,n+a*.16+.02),o.gain.exponentialRampToValueAtTime(1e-4,n+a*.16+.5),s.connect(o).connect(t.destination),s.start(n+a*.16),s.stop(n+a*.16+.55)}),setTimeout(()=>{t.close()},1200)}catch{}}function la(e){let[t,n]=S(e.chat.messages),[i,a]=S(e.chat.isBusy);return R(()=>{let s=e.chat.on("messages",n),o=e.chat.on("busy",a);return()=>{s(),o()}},[e]),{messages:t,busy:i}}function ca(e){let[t,n]=S(e.call),[i,a]=S(e.call?.state??null),[s,o]=S([]);return R(()=>e.on("call",l=>l&&n(l)),[e]),R(()=>{if(!t)return;a(t.state),o([]);let l=[t.on("state",a),t.on("caption",u=>o(c=>[...c.filter(f=>f.id!==u.id),u].slice(-4))),t.on("captionRemoved",u=>o(c=>c.filter(f=>f.id!==u)))];return()=>l.forEach(u=>u())},[t]),{call:t,state:i,captions:s,reset:()=>n(null)}}function da(e,t){let[n,i]=S(Date.now());return R(()=>{if(!t)return;let a=setInterval(()=>i(Date.now()),1e3);return()=>clearInterval(a)},[t]),e?Math.max(0,(n-e)/1e3):0}function ua(e,t,n){R(()=>{if(!e||!n)return;let i=0,a=0,s=()=>{let o=e.voiceLevel();a=a*.7+o*.3,t.current?.style.setProperty("--cx-lvl",a.toFixed(3)),i=requestAnimationFrame(s)};return i=requestAnimationFrame(s),()=>cancelAnimationFrame(i)},[e,n,t])}function Bn({parts:e}){return r(I,{children:e.map((t,n)=>t.t==="b"?r("strong",{children:t.v},n):t.t==="i"?r("em",{children:t.v},n):t.t==="code"?r("code",{children:t.v},n):t.t==="link"?r("a",{href:t.href,target:"_blank",rel:"noopener noreferrer nofollow",children:t.v},n):t.v.split(`
42
+ `).map((i,a,s)=>r(I,{children:[i,a<s.length-1?r("br",{}):null]},`${n}.${a}`)))})}var pa={name:{label:"nameField",type:"text",auto:"name"},email:{label:"emailField",type:"email",auto:"email"},phone:{label:"phoneField",type:"tel",auto:"tel"},company:{label:"companyField",type:"text",auto:"organization"},reason:{label:"reasonField",type:"text",auto:"off"}};function ha(){try{let e=new URLSearchParams(location.search).get("reason")??new URLSearchParams(location.search).get("intent");return e&&e.trim()?e.trim().slice(0,120):(document.querySelector("character-xyz")?.getAttribute("data-reason")??"").trim().slice(0,120)}catch{return""}}function fa({form:e,title:t,note:n,onSend:i,onSkip:a,skipLabel:s,initial:o,hasHistory:l}){let[u,c]=S(()=>({...o??{}})),f=e.required??["name","email"],x=E=>f.includes(E),d=e.reasonOptions??[],g=e.fields.includes("reason"),b=g&&!l?ha():"",v=e.reasonDefault||b||"",[m,_]=S(v),[w,O]=S(e.reasonDefault?e.reasonSource??"conversation":b?"cta":""),[z,H]=S(g&&!v),[$,P]=S(!1),[q,V]=S(""),[y,C]=S({}),[N,D]=S(null),[j,le]=S(!1),J=Z(null),ie=Z(null);return R(()=>{setTimeout(()=>J.current?.focus({preventScroll:!0}),80)},[]),Xe(()=>{let E=ie.current?.closest(".log");if(!E)return;let T=E.style.scrollBehavior;E.style.scrollBehavior="auto",E.scrollTop=E.scrollHeight,E.style.scrollBehavior=T},[z,$]),r("form",{class:"card",part:"details",ref:ie,onSubmit:async E=>{E.preventDefault(),le(!0),C({}),D(null);try{let T=($?q:m).trim();await i({name:u.name??"",email:u.email??"",...u.phone?{phone:u.phone}:{},...u.company?{company:u.company}:{},...g&&T?{reason:T}:{}})}catch(T){let B=T.fields??{};Object.keys(B).length?C(B):D(T.message||h("sendFailed"))}finally{le(!1)}},children:[r("div",{class:"card__title",children:t}),n?r("div",{class:"card__note",children:n}):null,e.fields.map((E,T)=>{if(E==="reason")return r("div",{class:"card__field card__field--reason",children:[!z&&m?null:r("span",{class:"card__reason-label",children:e.reasonLabel||h("reasonField")}),!z&&m?r(I,{children:[r("div",{class:"card__reason-line",children:[r("span",{class:"card__reason-said",children:h("reasonInferred")}),r("strong",{children:m}),r("button",{type:"button",class:"card__change",onClick:()=>H(!0),children:h("change")})]}),w?r("span",{class:"card__reason-src",children:w==="cta"?h("reasonFromPage"):w==="conversation"?h("reasonFromConversation"):null}):null]}):r("div",{class:"card__reason-edit",children:[d.length?r("div",{class:"card__chips",role:"group","aria-label":e.reasonLabel||h("reasonField"),children:[d.map(Q=>r("button",{type:"button",class:"card__chip","aria-pressed":!$&&m===Q,onClick:()=>{_(Q),P(!1),O("user"),H(!1)},children:Q},Q)),r("button",{type:"button",class:"card__chip","aria-pressed":$,onClick:()=>{P(!0),_("")},children:h("reasonOther")})]}):null,$||!d.length?r("input",{type:"text",maxLength:500,placeholder:h("reasonPlaceholder"),value:q,onInput:Q=>V(Q.currentTarget.value)}):null]}),y.reason?r("em",{children:y.reason}):null]},E);let B=pa[E],ae=h(B.label);return r("label",{class:"card__field",children:[r("span",{children:[ae,x(E)?null:r("i",{children:[" \xB7 ",h("optional")]})]}),r("input",{ref:T===0?J:void 0,type:B.type,autocomplete:B.auto,required:x(E),maxLength:E==="email"?254:120,value:u[E]??"","aria-invalid":y[E]?"true":void 0,onInput:Q=>c(tt=>({...tt,[E]:Q.currentTarget.value}))}),y[E]?r("em",{children:y[E]}):null]},E)}),r("div",{class:"card__consent",children:[e.consent,e.privacyUrl?r(I,{children:[" ",r("a",{href:e.privacyUrl,target:"_blank",rel:"noopener noreferrer",children:h("privacyPolicy")})]}):null]}),N?r("div",{class:"card__failed",children:N}):null,r("div",{class:"card__actions",children:[r("button",{type:"submit",class:"btn btn--accent btn--sm",disabled:j,children:j?h("sending"):h("send")}),r("button",{type:"button",class:"btn btn--ghost btn--sm",onClick:a,disabled:j,children:s})]})]})}function Et({items:e,onPick:t,children:n}){return!e.length&&!n?null:r("div",{class:"chips chips--start",part:"suggestions",children:[e.map(i=>r("button",{class:"chip",onClick:()=>t(i),children:i},i)),n]})}function Yn({text:e}){return r(I,{children:_n(e).map((t,n)=>t.t==="ul"?r("ul",{children:t.items.map((i,a)=>r("li",{children:r(Bn,{parts:i})},a))},n):r("p",{children:r(Bn,{parts:t.parts})},n))})}function qn({client:e,config:t,bind:n,onView:i}){let a=e.agent,s=e.features,o=t.showChat&&s.chat,l=t.showCall&&s.call,[u,c]=S(t.open?o?"chat":"call":"closed"),[f,x]=S(!1),[d,g]=S(!1),{messages:b,busy:v}=la(e),{call:m,state:_,captions:w,reset:O}=ca(e),[z,H]=S(""),$=Z(null),P=Z(null),q=Z(null),V=t.subtitle??a.tagline,y=a.name||h("assistant"),[C,N]=S(null);R(()=>{if(!o)return;let p=!0;return e.opening().then(A=>{p&&(yn(A?.strings),N(A))}),()=>{p=!1}},[e,o]);let D=t.greeting||C?.teaser||"",j=t.suggestions.length?t.suggestions:C?.suggestions??[],le=C?.greeting||h("greetingDefault",{name:y}),[J,ie]=S("loading"),[E,T]=S(!1),[B,ae]=S(null),[Q,tt]=S(""),[nt,it]=S(null),[at,rt]=S(null),ne=Me(p=>{c(p),i(p)},[i]),he=Me(()=>{x(!0),setTimeout(()=>{x(!1),ne("closed")},200)},[ne]),be=Me(async()=>{try{let p=await e.chat.load();ie(A=>A==="loading"?p.length?p.length:"empty":A)}catch{ie(p=>p==="loading"?"empty":p)}},[e]),ee=Me((p=o?"chat":"call")=>{g(!1),Fe(Mt,"1"),ne(p),p==="chat"&&be()},[o,ne,be]);R(()=>n({open:ee,close:he}),[n,ee,he]),R(()=>e.on("siteEvent",p=>{p.openChat&&ee("chat")}),[e,ee]),R(()=>{t.open&&o&&be()},[be,t.open,o]),R(()=>{if(!D||Fe(Mt))return;let p=setTimeout(()=>g(!0),t.greetingDelay*1e3);return()=>clearTimeout(p)},[D,t.greetingDelay]),R(()=>{if(u!=="chat"||E||J==="loading")return;let p=setTimeout(()=>T(!0),700);return()=>clearTimeout(p)},[u,E,J]);let[st,Qn]=S(()=>!Fe(Nn));R(()=>{if(!st)return;let p=setTimeout(()=>{Qn(!1),Fe(Nn,"1")},5e3);return()=>clearTimeout(p)},[st]),R(()=>{if(u==="closed")return;let p=A=>{A.key==="Escape"&&he()};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[u,he]),R(()=>{let p=$.current;p&&(p.scrollTop=p.scrollHeight)},[b,u,_?.phase]),R(()=>{u==="chat"&&setTimeout(()=>P.current?.focus({preventScroll:!0}),60)},[u]);let ye=t.face&&!!a.video,[Ie,ei]=S("loading"),M=_?.phase??"idle";R(()=>{if(!(M!=="ready"||!m)){if(oa(),u==="call"){if(!ye||Ie!=="loading"){m.accept();return}let p=setTimeout(()=>m.accept(),3e3);return()=>clearTimeout(p)}if(typeof document<"u"&&document.hidden){let p=document.title;document.title=`\u25CF ${y} is ready for you`;let A=()=>{document.title=p,document.removeEventListener("visibilitychange",A)};document.addEventListener("visibilitychange",A)}}},[M,m,u,y,ye,Ie]);let Rt=M==="live"||M==="connecting";ua(m,q,Rt&&u==="call");let Re=da(_?.startedAt??null,M==="live"),ot=ga(m,_?.position??1),lt=()=>{let p=C?.details;if(p&&!B&&o){it(p),ne("chat"),be();return}ct()},Dt=(p,A="")=>{ae(p),tt(A),rt(null);let fe=!!nt;it(null),fe&&ct()},ti=async p=>{await e.sendDetails(p),Dt("sent",p.name.trim().split(/\s+/)[0]??"")},ni=()=>{e.declineDetails().catch(()=>{}),Dt("skipped")},ii=async()=>{try{await e.chat.reset()}catch{return}ie("empty"),T(!1),ae(null),it(null),rt(null),H(""),N(await e.opening(!0))},ct=async()=>{ne("call");try{await e.startCall({autoAccept:!1,...ye?{face:{emotion:()=>At.current}}:{}})}catch{}},dt=[...b].reverse().find(p=>p.detailsForm||p.askDetails)?.detailsForm??[...b].reverse().find(p=>p.askDetails)?.askDetails??C?.details??null,ke=async p=>{let A=p.trim();if(!A||v)return;let fe=dt&&B!=="sent"?Fn(A):null;fe&&dt&&rt({form:dt,values:fe}),H(""),P.current&&(P.current.style.height="");try{await e.chat.send(A)}catch{}},De=b[b.length-1],Pt=De?.role==="agent"&&!De.streaming?De.askDetails:void 0,K=nt?{form:nt,kind:"call"}:at&&B!=="sent"&&!v?{form:at.form,kind:"typed",initial:at.values}:Pt&&!B?{form:Pt,kind:"invited"}:null;if(u==="closed"){let p=M==="queued"||M==="ready"||M==="live"||M==="connecting";return r("div",{class:`dock dock--${t.display}`,part:"launcher",children:[d?r("div",{class:"greeting",part:"greeting",role:"status",onClick:()=>ee(),children:[D,r("button",{class:"greeting__close","aria-label":h("dismiss"),onClick:A=>{A.stopPropagation(),g(!1),Fe(Mt,"1")},children:r(Ge,{size:14})})]}):null,r("button",{class:`presence presence--${t.display} ${p?"presence--live":""}`,part:"presence","aria-label":p?M==="queued"?h("inLineToCall",{position:de(_?.position??1),name:y}):h("backToCallWith",{name:y}):o?h("chatWith",{name:y}):h("callName",{name:y}),onClick:()=>ee(p||!o?"call":"chat"),children:[t.display==="bubble"?r("span",{class:"presence__ring"}):null,r("span",{class:"presence__face",children:r(Le,{agent:a,shot:t.display==="full"?Mn:t.display==="half"?An:Je})}),r("span",{class:"presence__dot"}),e.mode==="test"?r("span",{class:"testmode",title:"Test mode: this key only works on development sites",children:"TEST"}):null,M==="queued"?r("span",{class:"presence__badge","aria-hidden":"true",children:_?.position??1}):null,t.launcher==="bubble"&&!d?r("span",{class:"presence__label","aria-hidden":"true",children:p?M==="queued"?h("inLine",{position:de(_?.position??1)}):h("backToCall"):o?h("chatWith",{name:y}):h("callName",{name:y})}):null]}),t.launcher==="bubble"?null:r("div",{class:`acts ${st?"acts--labelled":""}`,part:"actions",children:[o?r("button",{class:"act","aria-label":h("chatWith",{name:y}),onClick:()=>ee("chat"),children:[r(Ee,{size:20}),r("span",{class:"act__label","aria-hidden":"true",children:h("chat")})]}):null,l?r("button",{class:`act act--call ${p?"act--live":""}`,"aria-label":p?M==="queued"?h("inLineOpen",{position:de(_?.position??1)}):h("backToCall"):h("callName",{name:y}),onClick:()=>p?ee("call"):lt(),children:[r(ve,{size:20}),r("span",{class:"act__label","aria-hidden":"true",children:p?M==="queued"?h("inLine",{position:de(_?.position??1)}):h("onCall"):h("call")}),M==="queued"?r("span",{class:"act__badge","aria-hidden":"true",children:_?.position??1}):null]}):null]})]})}let ai=r("div",{class:"head",part:"header",children:[r("div",{class:"head__face",children:r(Le,{agent:a,shot:Je})}),r("div",{class:"head__who",children:[r("div",{class:"head__name",children:y}),r("div",{class:"head__sub",children:[r("i",{}),v?h("typing"):V||h("online")]})]}),u==="chat"&&b.length>0&&!v?r("button",{class:"icon-btn","aria-label":h("newConversation"),title:h("newConversation"),onClick:()=>{ii()},children:r(Un,{})}):null,l&&u==="chat"?r("button",{class:"icon-btn icon-btn--accent","aria-label":h("callName",{name:y}),title:h("callName",{name:y}),onClick:()=>m&&M!=="ended"?ne("call"):lt(),children:r(ve,{size:18})}):null,r("button",{class:"icon-btn","aria-label":h("close"),onClick:he,children:r(Ge,{})})]});if(u==="chat")return r("div",{class:`panel ${f?"is-closing":""}`,part:"panel",role:"dialog","aria-label":h("chatWith",{name:y}),children:[ai,m&&(M==="queued"||M==="ready")?r("div",{class:"banner",part:"banner",role:"status",children:[r("div",{class:"banner__text",children:M==="queued"?r(I,{children:h("inLineFor",{position:de(_?.position??1),eta:Ze(_?.etaSeconds??null)})}):r(I,{children:[r("b",{children:h("readyForYou",{name:y})})," \xB7 ",h("secondsToJoin",{seconds:_?.holdSeconds??30})]})}),M==="ready"?r("button",{class:"btn btn--accent btn--glow",onClick:()=>{m.accept(),ne("call")},children:h("join")}):r("button",{class:"btn",onClick:()=>ne("call"),children:h("view")})]}):null,r("div",{class:"log",ref:$,role:"log","aria-live":"polite","aria-relevant":"additions",children:[b.length===0?r(I,{children:[r("div",{class:"empty",children:[r("div",{class:"empty__face",children:r(Le,{agent:a,shot:Je})}),r("div",{class:"empty__title",children:y}),V?r("div",{class:"empty__body",children:V}):null]}),J==="loading"?null:E?r(I,{children:[r("div",{class:"msg msg--agent",part:"message message-agent",children:r(Yn,{text:le})}),K?null:r(Et,{items:j,onPick:p=>{ke(p)},children:l?r("button",{class:"chip chip--call",onClick:()=>m&&M!=="ended"?ne("call"):lt(),children:[r(ve,{size:14})," ",h("callName",{name:y})]}):null})]}):r("div",{class:"msg msg--agent typing","aria-label":h("typingName",{name:y}),children:[r("i",{}),r("i",{}),r("i",{})]})]}):null,b.map(p=>p.role==="event"?r("div",{class:"event",part:"event message message-event",children:[r("span",{class:"event__dot","aria-hidden":"true"}),p.text]},p.id):p.role==="agent"&&p.streaming&&!p.text?r("div",{class:"msg msg--agent typing","aria-label":h("typingName",{name:y}),children:[r("i",{}),r("i",{}),r("i",{})]},p.id):r(I,{children:[r("div",{class:`msg msg--${p.role} ${p.failed?"msg--failed":""} ${p.streaming?"caret":""}`,part:`message message-${p.role}`,children:p.role==="agent"?r(Yn,{text:p.text}):p.text}),p===b[b.length-1]&&p.role==="agent"&&!p.streaming&&!v&&!K&&p.suggestions?.length?r(Et,{items:p.suggestions,onPick:A=>{ke(A)}}):null,p.failed&&p.error?r("div",{class:"msg__why",role:"status",children:p.error}):p.failed?r("button",{class:"msg__retry",onClick:()=>{e.chat.retry(p.id).catch(()=>{})},children:[r(Hn,{})," ",h("notSent")]}):null]},p.id)),typeof J=="number"&&b.length===J&&C?.welcomeBack?r(I,{children:[r("div",{class:"msg msg--agent",part:"message message-agent",children:C.welcomeBack}),K?null:r(Et,{items:j,onPick:p=>{ke(p)}})]}):null,K?r(fa,{form:K.form,initial:K.initial,title:K.kind==="call"?h("beforeYouCall",{name:y}):K.kind==="typed"?h("confirmDetails"):h("leaveDetails"),note:K.kind==="call"?h("detailsWhy"):K.kind==="typed"?h("detailsTyped"):null,onSend:ti,onSkip:ni,skipLabel:K.kind==="call"?h("skipAndCall"):h("notNow"),hasHistory:b.length>0},K.kind==="invited"?De?.id:K.kind):B==="sent"?r("div",{class:"notice",role:"status",children:[r(On,{})," ",Q?h("thanksName",{name:Q}):h("thanks")]}):null]}),r("form",{class:"compose",part:"composer",onSubmit:p=>{p.preventDefault(),ke(z)},children:r("div",{class:"compose__box",children:[r("textarea",{ref:P,rows:1,value:z,maxLength:2e3,placeholder:t.placeholder===ue.placeholder?h("message"):t.placeholder,"aria-label":h("message"),onInput:p=>{let A=p.currentTarget;H(A.value),A.style.height="auto",A.style.height=`${Math.min(120,A.scrollHeight)}px`},onKeyDown:p=>{p.key==="Enter"&&!p.shiftKey&&!p.isComposing&&(p.preventDefault(),ke(z))}}),r("button",{class:"send",type:"submit","aria-label":h("send"),disabled:!z.trim()||v,children:r(Pn,{})})]})}),t.branding?r("div",{class:"foot",children:h("poweredBy").split("{brand}").map((p,A)=>r(I,{children:[A?r("a",{href:"https://character.xyz",target:"_blank",rel:"noopener noreferrer",children:"Character XYZ"}):null,p]},A))}):null]});let L=_,ut=L?.position??1,ri=ot>1?(ot-ut)/(ot-1):0,pt=74,zt=2*Math.PI*pt,we=L?.maxSeconds?L.maxSeconds-Re:null,si=L?.agentState??"idle",oi=L?.speaking?h("speaking"):si==="thinking"?h("thinking"):h("listening"),li=!L||M==="ended"||M==="idle",ht=kn(L?.endReason??null,y);return r("div",{class:`panel ${f?"is-closing":""}`,part:"panel",role:"dialog","aria-label":h("callWith",{name:y}),children:r("div",{class:`stage ${ye&&Ie==="ready"?"stage--face":""}`,ref:q,children:[r("div",{class:"stage__figure",style:{opacity:M==="queued"?.35:1,transition:"opacity .6s"},children:[r(Le,{agent:a,shot:Tn,talking:!!L?.speaking,full:!0}),ye?r("div",{class:`stage__face ${Ie==="ready"?"is-ready":""}`,children:r(Wn,{client:e,call:m,state:L,src:t.faceUrl,onStatus:ei})}):null]}),Rt?r("div",{class:"voice"}):null,r("div",{class:"stage__veil"}),r("div",{class:"stage__top",children:[M==="live"?r("span",{class:`badge ${we!=null&&we<=60?"badge--warn":""}`,role:"timer","aria-label":h("callTime"),children:[r("i",{}),we!=null&&we<=60?h("timeLeft",{time:Ke(we)}):Ke(Re)]}):r("span",{}),r("div",{style:{display:"flex",gap:"6px"},children:[o?r("button",{class:"icon-btn","aria-label":h("chat"),title:h("chat"),onClick:()=>ee("chat"),children:r(Ee,{size:18})}):null,r("button",{class:"icon-btn","aria-label":h("minimise"),onClick:he,children:r(Ge,{})})]})]}),r("div",{class:"stage__bottom","aria-live":"polite",children:[M==="joining"||M==="connecting"?r(I,{children:[r("div",{class:"stage__name",children:y}),r("div",{class:"stage__status",children:[r("span",{class:"spinner"})," ",M==="joining"?h("connecting"):h("joining")]})]}):null,M==="queued"?r(I,{children:[r("div",{class:"line",role:"status","aria-label":h("inLineEta",{position:de(ut),eta:Ze(L?.etaSeconds??null)}),children:[r("svg",{width:"168",height:"168",viewBox:"0 0 168 168",children:[r("circle",{class:"line__track",cx:"84",cy:"84",r:pt,fill:"none","stroke-width":"7"}),r("circle",{class:"line__fill",cx:"84",cy:"84",r:pt,fill:"none","stroke-width":"7","stroke-linecap":"round","stroke-dasharray":zt,"stroke-dashoffset":zt*(1-Math.max(.06,ri))})]}),r("div",{children:[r("div",{class:"line__num",children:de(ut)}),r("div",{class:"line__lbl",children:h("lineLabel")})]})]}),r("div",{class:"title",children:h("onOtherCalls",{name:y})}),r("div",{class:"note",children:h(o?"yourTurnChat":"yourTurn",{eta:Ze(L?.etaSeconds??null)})}),r("div",{class:"btn-row",children:[o?r("button",{class:"btn btn--accent",onClick:()=>ee("chat"),children:[r(Ee,{size:18})," ",h("keepChatting")]}):null,r("button",{class:"btn",onClick:()=>{m?.hangUp()},children:h("leaveLine")})]})]}):null,M==="ready"?r(I,{children:[r("div",{class:"title",children:h("readyForYou",{name:y})}),r("div",{class:"note",children:h("joinWithin",{seconds:L?.holdSeconds??30})}),r("button",{class:"btn btn--accent btn--glow",onClick:()=>m?.accept(),children:[r(ve,{size:18})," ",h("joinCall")]})]}):null,M==="live"?r(I,{children:[r("div",{class:"stage__name",children:y}),r("div",{class:"stage__status",children:[L?.speaking?r("span",{class:"wave","aria-hidden":"true",children:[.6,1,.75,1,.55].map((p,A)=>r("i",{style:{"--k":p}},A))}):null,L?.muted?h("muted"):oi]}),r("div",{class:"captions",children:w.slice(-2).map((p,A,fe)=>r("div",{class:`captions__line ${A===fe.length-1?"captions__line--now":""}`,children:p.role==="visitor"?h("you",{text:p.text}):p.text},p.id))}),r("div",{class:"controls",children:[r("div",{class:"ctl",children:[r("button",{class:`round ${L?.muted?"round--on":""}`,"aria-pressed":L?.muted,"aria-label":L?.muted?h("unmute"):h("mute"),onClick:()=>m?.setMuted(!L?.muted),children:L?.muted?r(Dn,{size:22}):r(Rn,{size:22})}),r("span",{class:"round__label",children:L?.muted?h("unmute"):h("mute")})]}),r("div",{class:"ctl",children:[r("button",{class:"round round--end","aria-label":h("endCall"),onClick:()=>{m?.hangUp()},children:r(In,{size:26})}),r("span",{class:"round__label",children:h("end")})]}),L?.speaking?r("div",{class:"ctl",children:[r("button",{class:"round","aria-label":h("interruptName",{name:y}),onClick:()=>m?.interrupt(),children:r(zn,{size:22})}),r("span",{class:"round__label",children:h("interrupt")})]}):null]})]}):null,li?r(I,{children:[r("div",{class:"title",children:L?ht.title:h("callName",{name:y})}),r("div",{class:"note",children:L?L.endReason==="hangup"&&Re?`${Ke(Re)} \xB7 ${ht.body}`:L.error??ht.body:h("talkWith",{name:y})}),r("div",{class:"btn-row",children:[l&&L?.endReason!=="credits"&&L?.endReason!=="unavailable"&&L?.endReason!=="daily_limit"?r("button",{class:"btn btn--accent",onClick:()=>{O(),ct()},children:[r(ve,{size:18})," ",L?h("callAgain"):h("startCall")]}):null,o?r("button",{class:"btn",onClick:()=>ee("chat"),children:[r(Ee,{size:18})," ",h("chat")]}):null]})]}):null]})]})})}function ga(e,t){let n=Z({call:null,start:t});return n.current.call!==e&&(n.current={call:e,start:t}),t>n.current.start&&(n.current.start=t),n.current.start}var ma=(e=0)=>({x:e,y:0,vx:0,vy:0,held:!1,tx:e,ty:0,rot:0,rv:0,sx:1,sxv:0,sy:1,syv:0});var se=(e,t,n)=>Math.min(n,Math.max(t,e));function Lt(e,t,n,i,a,s){return t+=(i*(n-e)-a*t)*s,[e+t*s,t]}function jn(e){e.held=!1,e.vx=se(e.vx*.6,-1500,1500),e.vy=se(e.vy*.6,-1500,1500)}function xa(e,t,n,i=!1){for(let o=Math.min(t,1/20);o>1e-6;o-=1/120){let l=Math.min(o,.008333333333333333);if(e.held){let c=1-Math.exp(-14*l),f=e.x+(e.tx-e.x)*c,x=e.y+(e.ty-e.y)*c;e.vx=(f-e.x)/l,e.vy=(x-e.y)/l,e.x=f,e.y=x}else if(i)e.vx=e.vy=0,e.y+=(0-e.y)*(1-Math.exp(-12*l)),e.y>-.5&&(e.y=0);else{if(e.vy+=1900*l,e.x+=e.vx*l,e.y+=e.vy*l,e.vx*=Math.exp(-(e.y<0?1:8)*l),(e.x<n.minX||e.x>n.maxX)&&(e.x=se(e.x,n.minX,n.maxX),e.vx=-e.vx*.12),e.y<n.minY&&e.vy<0&&(e.y=n.minY,e.vy=-e.vy*.2),e.y>=0&&e.vy>=0){let c=Math.min(1,e.vy/1400);e.vy=e.vy>180?-e.vy*.28:0,c>.05&&(e.syv-=1.8*c,e.sxv+=1.3*c),e.y=0}e.y===0&&e.vy===0&&Math.abs(e.vx)<6&&(e.vx=0)}let u=e.held?1.04:1;[e.rot,e.rv]=Lt(e.rot,e.rv,i||!e.held?0:se(e.vx*.01,-9,9),90,8,l),[e.sx,e.sxv]=Lt(e.sx,e.sxv,u,260,13,l),[e.sy,e.syv]=Lt(e.sy,e.syv,u,260,13,l)}let a=!e.held&&e.y===0&&e.vy===0&&e.vx===0,s=Math.abs(e.rot)+Math.abs(e.rv)+Math.abs(e.sx-1)+Math.abs(e.sy-1)+Math.abs(e.sxv)+Math.abs(e.syv)<.01;return!(a&&s)}function _a(e,t,n,i,a){let s=(e.left+e.right)/2>i/2?"left":"right",o=a,l=Math.max(a,i-a-n),u=se(s==="left"?e.right-n:e.left,o,l);return{x:(s==="left"?u+n:u)-t,grow:s}}var va=350,ba=6,Qe=8,ya=16,ka=520,Vn="cx:spot";function Xn(e){let t=ma(),n={minX:0,maxX:0,minY:0},i={left:0,right:0},a=0,s=0,o=()=>e.hasAttribute("data-open"),l=()=>typeof matchMedia<"u"&&matchMedia("(prefers-reduced-motion: reduce)").matches,u=()=>document.documentElement.clientWidth||innerWidth,c=e.style,f=()=>{let{translate:C,rotate:N}=c;c.translate=c.rotate="";let D=e.getBoundingClientRect();return c.translate=C,c.rotate=N,D.width?(i={left:D.left,right:D.right},n={minX:Qe-D.left,maxX:Math.max(Qe-D.left,u()-Qe-D.right),minY:Qe-D.top},t.x=t.tx=se(t.x,n.minX,n.maxX),t.y=se(t.y,n.minY,0),!0):!1},x=()=>{e.dataset.grow=(i.left+i.right)/2+t.x>u()/2?"left":"right"},d=()=>{if(o()){if(c.rotate="",c.removeProperty("--cx-sq"),u()<=ka){c.translate="";return}let C=e.dataset.side==="left"?i.left:i.right,N=e.shadowRoot?.querySelector(".panel")?.offsetWidth||392,D=_a({left:i.left+t.x,right:i.right+t.x},C,N,u(),ya);e.dataset.grow=D.grow,c.translate=`${D.x.toFixed(1)}px 0px`;return}c.translate=`${t.x.toFixed(1)}px ${t.y.toFixed(1)}px`,c.rotate=`${t.rot.toFixed(2)}deg`,c.setProperty("--cx-sq",`${t.sx.toFixed(3)} ${t.sy.toFixed(3)}`)},g=()=>{try{sessionStorage.setItem(Vn,String(Math.round(t.x)))}catch{}},b=C=>{let N=s?(C-s)/1e3:.016666666666666666;s=C;let D=xa(t,N,n,l());d(),D?a=requestAnimationFrame(b):(a=0,x(),g())},v=()=>{a||o()||(s=0,a=requestAnimationFrame(b))};try{t.x=t.tx=Number(sessionStorage.getItem(Vn))||0}catch{}c.transformOrigin="50% 0";let m=()=>{c.touchAction=o()?"":"none",!o()&&f()&&x(),d()};requestAnimationFrame(m);let _=null,w=!1,O,z=()=>{!_||!f()||(t.held=!0,t.tx=t.x,t.ty=t.y,c.cursor="grabbing",_.touch&&navigator.vibrate?.(12),v())},H=C=>{o()||C.pointerType==="mouse"&&C.button!==0||(_={px:C.clientX,py:C.clientY,x:t.x,y:t.y,id:C.pointerId,touch:C.pointerType!=="mouse"},w=!1,_.touch&&(O=setTimeout(z,va)))},$=C=>{if(!_||C.pointerId!==_.id)return;let N=C.clientX-_.px,D=C.clientY-_.py;if(!t.held){if(Math.hypot(N,D)<ba)return;if(_.touch)return P();if(z(),!t.held)return}C.preventDefault(),t.tx=se(_.x+N,n.minX,n.maxX),t.ty=se(_.y+D,n.minY,0)},P=()=>{clearTimeout(O),t.held&&(w=!0,c.cursor="",jn(t),v()),_=null},q=C=>{w&&(w=!1,C.preventDefault(),C.stopPropagation())},V=C=>{(t.held||_?.touch)&&C.preventDefault()},y=new MutationObserver(()=>{o()&&(cancelAnimationFrame(a),a=0,t.held&&jn(t),t.y=0,t.vx=t.vy=0,g()),m()});return y.observe(e,{attributes:!0,attributeFilter:["data-open"]}),e.addEventListener("pointerdown",H),addEventListener("pointermove",$,{passive:!1}),addEventListener("pointerup",P),addEventListener("pointercancel",P),e.addEventListener("click",q,!0),e.addEventListener("contextmenu",V),addEventListener("resize",m),addEventListener("pagehide",g),()=>{clearTimeout(O),cancelAnimationFrame(a),y.disconnect(),e.removeEventListener("pointerdown",H),removeEventListener("pointermove",$),removeEventListener("pointerup",P),removeEventListener("pointercancel",P),e.removeEventListener("click",q,!0),e.removeEventListener("contextmenu",V),removeEventListener("resize",m),removeEventListener("pagehide",g)}}var Kn=`
43
43
  :host {
44
44
  --cx-accent: #7c5cff;
45
45
  --cx-accent-ink: #fff;
@@ -86,7 +86,7 @@ button:focus-visible, textarea:focus-visible, a:focus-visible { outline: 2px sol
86
86
  .sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
87
87
 
88
88
  /* ------------------------------------------------------------ launcher */
89
- .dock { display: flex; align-items: flex-end; gap: 10px; }
89
+ .dock { display: flex; align-items: flex-end; gap: 10px; scale: var(--cx-sq, 1); transform-origin: 50% 100%; }
90
90
  /* She sits in the corner and never moves; the buttons grow away from her. */
91
91
  :host([data-side="right"]) .dock { flex-direction: row-reverse; }
92
92
  .presence {
@@ -121,8 +121,8 @@ button:focus-visible, textarea:focus-visible, a:focus-visible { outline: 2px sol
121
121
  color: var(--cx-ink); background: var(--cx-solid); border: 1px solid var(--cx-line); box-shadow: var(--cx-shadow);
122
122
  transition: opacity .2s, transform .3s var(--cx-ease);
123
123
  }
124
- :host([data-side="right"]) .presence__label { right: calc(100% + 10px); }
125
- :host([data-side="left"]) .presence__label { left: calc(100% + 10px); transform: translate(-6px, -50%); }
124
+ :host([data-grow="left"]) .presence__label { right: calc(100% + 10px); }
125
+ :host([data-grow="right"]) .presence__label { left: calc(100% + 10px); transform: translate(-6px, -50%); }
126
126
  .presence:hover .presence__label, .presence:focus-visible .presence__label { opacity: 1; transform: translate(0, -50%); }
127
127
  /* Waiting in line: the place, on her. */
128
128
  .presence__badge {
@@ -184,8 +184,8 @@ button:focus-visible, textarea:focus-visible, a:focus-visible { outline: 2px sol
184
184
  background: var(--cx-solid); box-shadow: var(--cx-shadow); border: 1px solid var(--cx-line);
185
185
  font-size: 14px; color: var(--cx-ink); animation: cx-pop .55s var(--cx-spring) both; cursor: pointer;
186
186
  }
187
- :host([data-side="right"]) .greeting { right: 0; border-bottom-right-radius: 6px; }
188
- :host([data-side="left"]) .greeting { left: 0; border-bottom-left-radius: 6px; }
187
+ :host([data-grow="left"]) .greeting { right: 0; border-bottom-right-radius: 6px; }
188
+ :host([data-grow="right"]) .greeting { left: 0; border-bottom-left-radius: 6px; }
189
189
  .greeting__close { position: absolute; top: 6px; right: 6px; width: 24px; height: 24px; border-radius: 50%; display: grid; place-items: center; color: var(--cx-ink-3); }
190
190
  .greeting__close:hover { background: var(--cx-bubble); color: var(--cx-ink); }
191
191
 
@@ -199,8 +199,9 @@ button:focus-visible, textarea:focus-visible, a:focus-visible { outline: 2px sol
199
199
  transform-origin: bottom right;
200
200
  animation: cx-open .5s var(--cx-ease) both;
201
201
  }
202
- :host([data-side="right"]) .panel { right: 0; }
203
- :host([data-side="left"]) .panel { left: 0; transform-origin: bottom left; }
202
+ /* data-grow: which way she opens \u2014 away from her corner, or (movable) towards the middle. */
203
+ :host([data-grow="left"]) .panel { right: 0; }
204
+ :host([data-grow="right"]) .panel { left: 0; transform-origin: bottom left; }
204
205
  .panel.is-closing { animation: cx-close .22s ease-in both; }
205
206
 
206
207
  .head { display: flex; align-items: center; gap: 12px; padding: 14px 14px 12px 16px; border-bottom: 1px solid var(--cx-line); }
@@ -401,5 +402,5 @@ button:focus-visible, textarea:focus-visible, a:focus-visible { outline: 2px sol
401
402
  *, *::before, *::after { animation-duration: .01ms !important; animation-iteration-count: 1 !important; transition-duration: .01ms !important; }
402
403
  .presence__ring { animation: none; }
403
404
  }
404
- `;var Mt="character-xyz";function da(t){let e=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(t.trim());if(!e)return"#ffffff";let n=e[1].length===3?e[1].replace(/./g,l=>l+l):e[1],[i,a,s]=[0,2,4].map(l=>parseInt(n.slice(l,l+2),16)/255).map(l=>l<=.03928?l/12.92:((l+.055)/1.055)**2.4);return .2126*i+.7152*a+.0722*s>.45?"#14121a":"#ffffff"}function pa(t){let e=/rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)(?:[,\s/]+([\d.]+%?))?\s*\)/.exec(t);if(!e||(e[4]===void 0?1:e[4].endsWith("%")?parseFloat(e[4])/100:parseFloat(e[4]))<.5)return null;let[i,a,s]=[e[1],e[2],e[3]].map(o=>Number(o)/255).map(o=>o<=.03928?o/12.92:((o+.055)/1.055)**2.4);return .2126*i+.7152*a+.0722*s}function Yn(t){for(let e of[document.body,document.documentElement]){if(!e)continue;let n=pa(getComputedStyle(e).backgroundColor);if(n!==null)return n<.22}return!!t?.matches}var ua=["publishable-key","agent","api-url","position","mode","accent","greeting","open"],Et=class extends HTMLElement{constructor(){super(...arguments);j(this,"options",null);j(this,"client",null);j(this,"api",null);j(this,"pendingOpen",null);j(this,"booted",!1);j(this,"mq",null);j(this,"stage",null);j(this,"waiters",[]);j(this,"queuedActions",new Map);j(this,"bootFailed",!1);j(this,"onSchemeChange",()=>requestAnimationFrame(this.onScheme));j(this,"onScheme",()=>{this.dataset.mode==="auto"&&(this.dataset.theme=Yn(this.mq)?"dark":"light")})}static get observedAttributes(){return ua}connectedCallback(){if(this.booted)return;this.booted=!0;let n=this.shadowRoot??this.attachShadow({mode:"open"}),i=document.createElement("style");i.textContent=Wn,this.stage=document.createElement("div"),n.replaceChildren(i,this.stage),this.style.display="none";let a=window.requestIdleCallback;a?a(()=>{this.boot()},{timeout:2e3}):setTimeout(()=>{this.boot()},200)}disconnectedCallback(){this.stage&&yt(null,this.stage),this.settleWaiters(!1),this.client?.destroy(),this.client=null,this.mq?.removeEventListener("change",this.onSchemeChange),this.booted=!1}open(n="chat"){this.api?this.api.open(n):this.pendingOpen=n}close(){this.api?.close()}track(n,i={},a={}){return this.untilClient().then(s=>s.track(n,i,a))}identify(n){return this.untilClient().then(i=>i.identify(n))}setContext(n){return this.untilClient().then(i=>i.setContext(n))}registerAction(n,i){return this.queuedActions.set(n,i),this.client?.registerAction(n,i),()=>{this.queuedActions.delete(n),this.client?.registerAction(n,i)()}}untilClient(){return this.client?Promise.resolve(this.client):this.bootFailed?Promise.reject(new P("unknown","The widget could not start.")):new Promise((n,i)=>{this.waiters.push(a=>a?n(a):i(new P("unknown","The widget could not start.")))})}settleWaiters(n){let i=this.waiters;this.waiters=[];for(let a of i)a(n?this.client:null)}fire(n,i){this.dispatchEvent(new CustomEvent(n,{detail:i,bubbles:!0,composed:!0}))}async boot(){let n={...this.options??{}},i=De(Array.from(this.attributes)),a=n.publishableKey??i.publishableKey;try{this.client=await Ot.init({publishableKey:a,getSessionToken:n.getSessionToken,agentId:n.agentId??i.agent,apiUrl:n.apiUrl??i.apiUrl,storage:n.storage})}catch(l){let p=l instanceof P?l:new P("unknown",String(l?.message??l));console.warn(`[characterxyz] widget not shown: ${p.message}`),this.fire("cx-error",{code:p.code,message:p.message}),this.bootFailed=!0,this.settleWaiters(!1);return}if(!this.isConnected){this.client.destroy();return}let s=this.client;for(let[l,p]of this.queuedActions)s.registerAction(l,p);let o=fe(de,s.appearance);if(o=fe(o,i),o=fe(o,n),!(o.showChat&&s.features.chat)&&!(o.showCall&&s.features.call)){console.warn("[characterxyz] widget not shown: neither chat nor calls are enabled for this site");return}this.applyTokens(o),s.on("call",l=>{l&&l.on("state",p=>this.fire("cx-call",{phase:p.phase,position:p.position,endReason:p.endReason}))}),s.on("error",l=>this.fire("cx-error",{code:l.code,message:l.message})),this.style.display="",yt(r(Bn,{client:s,config:o,bind:l=>{this.api=l,this.pendingOpen&&this.pendingOpen!=="closed"&&(l.open(this.pendingOpen),this.pendingOpen=null)},onView:l=>{l==="closed"?(this.removeAttribute("data-open"),this.fire("cx-close")):(this.setAttribute("data-open",""),this.fire("cx-open",{view:l}))}}),this.stage),o.open&&this.setAttribute("data-open",""),this.fire("cx-ready",{agent:{id:s.agent.id,name:s.agent.name},features:s.features}),this.settleWaiters(!0)}applyTokens(n){this.dataset.side=n.position==="bottom-left"?"left":"right",this.dataset.mode=n.mode,n.mode==="auto"?(this.mq=matchMedia("(prefers-color-scheme: dark)"),this.mq.addEventListener("change",this.onSchemeChange),this.dataset.theme=Yn(this.mq)?"dark":"light"):this.dataset.theme=n.mode;let i=(a,s)=>this.style.setProperty(a,s);i("--cx-accent",n.accent),i("--cx-accent-ink",da(n.accent)),i("--cx-radius",`${n.radius}px`),n.font&&i("--cx-font",n.font),i("--cx-ox",`${n.offsetX}px`),i("--cx-oy",`${n.offsetY}px`),i("--cx-z",String(n.zIndex))}};function ha(){typeof customElements<"u"&&!customElements.get(Mt)&&customElements.define(Mt,Et)}function Ge(t){ha();let e=document.createElement(Mt);return e.options=t,(t.container??document.body).appendChild(e),{element:e,open:n=>e.open(n),close:()=>e.close(),track:(n,i,a)=>e.track(n,i,a),identify:n=>e.identify(n),setContext:n=>e.setContext(n),registerAction:(n,i)=>e.registerAction(n,i),destroy:()=>e.remove()}}var qn=document.currentScript,re=null;function jn(){if(!qn)return;let t=De(Array.from(qn.attributes).filter(o=>o.name.startsWith("data-"))),e=o=>typeof o=="string"&&o.trim()?o.trim():void 0,n=e(t.key)??e(t.publishableKey);if(!n)return;let i=fe(de,t),s={...Object.fromEntries(Object.entries(i).filter(([o,l])=>o in t&&l!==de[o])),publishableKey:n,agentId:e(t.agent),apiUrl:e(t.apiUrl)};re=Ge(s)}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",jn,{once:!0}):jn();var fa={mount:t=>re=Ge(t),open:t=>re?.open(t),close:()=>re?.close(),track:(t,e,n)=>re?.track(t,e,n),identify:t=>re?.identify(t),setContext:t=>re?.setContext(t),registerAction:(t,e)=>re?.registerAction(t,e),get widget(){return re}};window.CharacterXYZ=fa;return ci(ga);})();
405
+ `;var Ft="character-xyz";function wa(e){let t=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(e.trim());if(!t)return"#ffffff";let n=t[1].length===3?t[1].replace(/./g,l=>l+l):t[1],[i,a,s]=[0,2,4].map(l=>parseInt(n.slice(l,l+2),16)/255).map(l=>l<=.03928?l/12.92:((l+.055)/1.055)**2.4);return .2126*i+.7152*a+.0722*s>.45?"#14121a":"#ffffff"}function Ca(e){let t=/rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)(?:[,\s/]+([\d.]+%?))?\s*\)/.exec(e);if(!t||(t[4]===void 0?1:t[4].endsWith("%")?parseFloat(t[4])/100:parseFloat(t[4]))<.5)return null;let[i,a,s]=[t[1],t[2],t[3]].map(o=>Number(o)/255).map(o=>o<=.03928?o/12.92:((o+.055)/1.055)**2.4);return .2126*i+.7152*a+.0722*s}function Zn(e){for(let t of[document.body,document.documentElement]){if(!t)continue;let n=Ca(getComputedStyle(t).backgroundColor);if(n!==null)return n<.22}return!!e?.matches}var Sa=["publishable-key","agent","api-url","position","mode","accent","greeting","open"],It=class extends HTMLElement{constructor(){super(...arguments);X(this,"options",null);X(this,"client",null);X(this,"api",null);X(this,"pendingOpen",null);X(this,"booted",!1);X(this,"mq",null);X(this,"stage",null);X(this,"waiters",[]);X(this,"queuedActions",new Map);X(this,"bootFailed",!1);X(this,"detachMover",null);X(this,"onSchemeChange",()=>requestAnimationFrame(this.onScheme));X(this,"onScheme",()=>{this.dataset.mode==="auto"&&(this.dataset.theme=Zn(this.mq)?"dark":"light")})}static get observedAttributes(){return Sa}connectedCallback(){if(this.booted)return;this.booted=!0;let n=this.shadowRoot??this.attachShadow({mode:"open"}),i=document.createElement("style");i.textContent=Kn,this.stage=document.createElement("div"),n.replaceChildren(i,this.stage),this.style.display="none";let a=window.requestIdleCallback;a?a(()=>{this.boot()},{timeout:2e3}):setTimeout(()=>{this.boot()},200)}disconnectedCallback(){this.stage&&wt(null,this.stage),this.detachMover?.(),this.detachMover=null,this.settleWaiters(!1),this.client?.destroy(),this.client=null,this.mq?.removeEventListener("change",this.onSchemeChange),this.booted=!1}open(n="chat"){this.api?this.api.open(n):this.pendingOpen=n}close(){this.api?.close()}track(n,i={},a={}){return this.untilClient().then(s=>s.track(n,i,a))}identify(n){return this.untilClient().then(i=>i.identify(n))}setContext(n){return this.untilClient().then(i=>i.setContext(n))}registerAction(n,i){return this.queuedActions.set(n,i),this.client?.registerAction(n,i),()=>{this.queuedActions.delete(n),this.client?.registerAction(n,i)()}}untilClient(){return this.client?Promise.resolve(this.client):this.bootFailed?Promise.reject(new Y("unknown","The widget could not start.")):new Promise((n,i)=>{this.waiters.push(a=>a?n(a):i(new Y("unknown","The widget could not start.")))})}settleWaiters(n){let i=this.waiters;this.waiters=[];for(let a of i)a(n?this.client:null)}fire(n,i){this.dispatchEvent(new CustomEvent(n,{detail:i,bubbles:!0,composed:!0}))}async boot(){let n={...this.options??{}},i=ze(Array.from(this.attributes)),a=n.publishableKey??i.publishableKey;try{this.client=await $t.init({publishableKey:a,getSessionToken:n.getSessionToken,agentId:n.agentId??i.agent,apiUrl:n.apiUrl??i.apiUrl,storage:n.storage})}catch(l){let u=l instanceof Y?l:new Y("unknown",String(l?.message??l));console.warn(`[characterxyz] widget not shown: ${u.message}`),this.fire("cx-error",{code:u.code,message:u.message}),this.bootFailed=!0,this.settleWaiters(!1);return}if(!this.isConnected){this.client.destroy();return}let s=this.client;for(let[l,u]of this.queuedActions)s.registerAction(l,u);let o=me(ue,s.appearance);if(o=me(o,i),o=me(o,n),!(o.showChat&&s.features.chat)&&!(o.showCall&&s.features.call)){console.warn("[characterxyz] widget not shown: neither chat nor calls are enabled for this site");return}this.applyTokens(o),s.on("call",l=>{l&&l.on("state",u=>this.fire("cx-call",{phase:u.phase,position:u.position,endReason:u.endReason}))}),s.on("error",l=>this.fire("cx-error",{code:l.code,message:l.message})),this.style.display="",wt(r(qn,{client:s,config:o,bind:l=>{this.api=l,this.pendingOpen&&this.pendingOpen!=="closed"&&(l.open(this.pendingOpen),this.pendingOpen=null)},onView:l=>{l==="closed"?(this.removeAttribute("data-open"),this.fire("cx-close")):(this.setAttribute("data-open",""),this.fire("cx-open",{view:l}))}}),this.stage),o.open&&this.setAttribute("data-open",""),o.movable&&(this.detachMover=Xn(this)),this.fire("cx-ready",{agent:{id:s.agent.id,name:s.agent.name},features:s.features}),this.settleWaiters(!0)}applyTokens(n){this.dataset.side=n.position==="bottom-left"?"left":"right",this.dataset.grow=n.position==="bottom-left"?"right":"left",this.dataset.mode=n.mode,n.mode==="auto"?(this.mq=matchMedia("(prefers-color-scheme: dark)"),this.mq.addEventListener("change",this.onSchemeChange),this.dataset.theme=Zn(this.mq)?"dark":"light"):this.dataset.theme=n.mode;let i=(a,s)=>this.style.setProperty(a,s);i("--cx-accent",n.accent),i("--cx-accent-ink",wa(n.accent)),i("--cx-radius",`${n.radius}px`),n.font&&i("--cx-font",n.font),i("--cx-ox",`${n.offsetX}px`),i("--cx-oy",`${n.offsetY}px`),i("--cx-z",String(n.zIndex))}};function Ta(){typeof customElements<"u"&&!customElements.get(Ft)&&customElements.define(Ft,It)}function et(e){Ta();let t=document.createElement(Ft);return t.options=e,(e.container??document.body).appendChild(t),{element:t,open:n=>t.open(n),close:()=>t.close(),track:(n,i,a)=>t.track(n,i,a),identify:n=>t.identify(n),setContext:n=>t.setContext(n),registerAction:(n,i)=>t.registerAction(n,i),destroy:()=>t.remove()}}var Jn=document.currentScript,oe=null;function Gn(){if(!Jn)return;let e=ze(Array.from(Jn.attributes).filter(o=>o.name.startsWith("data-"))),t=o=>typeof o=="string"&&o.trim()?o.trim():void 0,n=t(e.key)??t(e.publishableKey);if(!n)return;let i=me(ue,e),s={...Object.fromEntries(Object.entries(i).filter(([o,l])=>o in e&&l!==ue[o])),publishableKey:n,agentId:t(e.agent),apiUrl:t(e.apiUrl)};oe=et(s)}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",Gn,{once:!0}):Gn();var Aa={mount:e=>oe=et(e),open:e=>oe?.open(e),close:()=>oe?.close(),track:(e,t,n)=>oe?.track(e,t,n),identify:e=>oe?.identify(e),setContext:e=>oe?.setContext(e),registerAction:(e,t)=>oe?.registerAction(e,t),get widget(){return oe}};window.CharacterXYZ=Aa;return gi(Ma);})();
405
406
  //# sourceMappingURL=cx.js.map