@characterxyz/widget 0.7.3 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- var ei=Object.defineProperty;var ti=(t,e,n)=>e in t?ei(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var V=(t,e,n)=>ti(t,typeof e!="symbol"?e+"":e,n);var ni=Object.defineProperty,ii=(t,e,n)=>e in t?ni(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,v=(t,e,n)=>ii(t,typeof e!="symbol"?e+"":e,n),pe=null;function Dt(){return(!pe||pe.state==="closed")&&(pe=new AudioContext({latencyHint:"interactive"})),pe.state==="suspended"&&pe.resume().catch(()=>{}),pe}var ai=class{constructor(t={}){v(this,"opts",t),v(this,"ctx"),v(this,"gain"),v(this,"analyser"),v(this,"data"),v(this,"nextAt",0),v(this,"started",!1),v(this,"ended",!1),v(this,"finishing",!1),v(this,"sources",new Set),v(this,"startedAt",0),v(this,"sampleRate"),this.ctx=Dt(),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?.())}},ri=`
1
+ var ei=Object.defineProperty;var ti=(t,e,n)=>e in t?ei(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var j=(t,e,n)=>ti(t,typeof e!="symbol"?e+"":e,n);var ni=Object.defineProperty,ii=(t,e,n)=>e in t?ni(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,y=(t,e,n)=>ii(t,typeof e!="symbol"?e+"":e,n),ue=null;function zt(){return(!ue||ue.state==="closed")&&(ue=new AudioContext({latencyHint:"interactive"})),ue.state==="suspended"&&ue.resume().catch(()=>{}),ue}var ai=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=zt(),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?.())}},ri=`
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 si(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 oi(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,si(d))},o,l;try{let d=URL.createObjectURL(new Blob([ri],{type:"application/javascript"}));try{await n.audioWorklet.addModule(d)}finally{URL.revokeObjectURL(d)}let f=new AudioWorkletNode(n,"cxyz-mic");f.port.onmessage=m=>s(m.data),o=f,l=()=>{f.port.onmessage=null}}catch{let d=n.createScriptProcessor(4096,1,1),f=n.sampleRate/16e3,m=0,c=new Int16Array(480),g=0;d.onaudioprocess=x=>{let b=x.inputBuffer.getChannelData(0);for(let _=0;_<b.length;_++)if(m+=1,m>=f){m-=f;let k=Math.max(-1,Math.min(1,b[_]));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 ct=class{constructor(){v(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),v(this,"code"),v(this,"status"),v(this,"fields"),this.name="CxError",this.code=t,this.status=n,this.fields=i}};function li(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 ci(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(li(t.status),e||`Request failed (${t.status})`,t.status,n)}async function xe(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 ci(a);return a}async function G(t,e,n={}){return(await(await xe(t,e,n)).json()).data}async function zt(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=It(o,e)}o+=s.decode(),It(o+`
33
+ `;function si(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 oi(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,si(d))},o,l;try{let d=URL.createObjectURL(new Blob([ri],{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 pt=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={}}},z=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 li(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 ci(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 z(li(t.status),e||`Request failed (${t.status})`,t.status,n)}async function be(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 z("network","Could not reach Character XYZ. Check your connection.")}if(!a.ok)throw await ci(a);return a}async function X(t,e,n={}){return(await(await be(t,e,n)).json()).data}async function Rt(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=Lt(o,e)}o+=s.decode(),Lt(o+`
34
34
 
35
- `,e)}finally{n?.removeEventListener("abort",l)}}function It(t,e){let n=t.replace(/\r\n/g,`
35
+ `,e)}finally{n?.removeEventListener("abort",l)}}function Lt(t,e){let n=t.replace(/\r\n/g,`
36
36
  `),i;for(;(i=n.indexOf(`
37
37
 
38
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(":"),m=f===-1?d:d.slice(0,f),c=f===-1?"":d.slice(f+1).replace(/^ /,"");m==="event"?s=c:m==="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 di(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 pi=.09,ui=350,hi=25e3,fi=()=>({phase:"idle",callId:null,position:null,etaSeconds:null,holdSeconds:null,maxSeconds:null,startedAt:null,endReason:null,muted:!1,speaking:!1,agentState:"idle",error:null}),gi=class extends ct{constructor(t,e,n,i={}){super(),v(this,"apiUrl",t),v(this,"session",e),v(this,"agentId",n),v(this,"opts",i),v(this,"s",fi()),v(this,"ticket",null),v(this,"eventsAbort",null),v(this,"ws",null),v(this,"mic",null),v(this,"players",new Map),v(this,"sampleRates",new Map),v(this,"cancelled",new Set),v(this,"speakingCorr",null),v(this,"heartbeat",null),v(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"}),Dt();try{this.mic=await oi({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 G(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 xe(this.apiUrl,`/sdk/v1/calls/${encodeURIComponent(this.s.callId)}/events`,{token:e,signal:this.eventsAbort.signal});t=0,await zt(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"}),hi),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>pi){if(this.loudSince??(this.loudSince=i),i-this.loudSince>=ui){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=di(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 ai({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 xe(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})}},mi=0,Lt=t=>`${t}_${Date.now().toString(36)}_${(mi++).toString(36)}`,_i=class extends ct{constructor(t,e){super(),v(this,"apiUrl",t),v(this,"session",e),v(this,"list",[]),v(this,"loaded",!1),v(this,"busy",!1),v(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 G(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:Lt("local"),role:"visitor",text:e,createdAt:new Date().toISOString()},i={id:Lt("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 xe(this.apiUrl,"/sdk/v1/chat/messages",{method:"POST",body:{text:e},token:a,signal:this.abort.signal}),o=null,l=null;if(await zt(s,({event:d,data:f})=>{let m=f;if(d==="delta"&&typeof m?.text=="string")i.text+=m.text,this.publish();else if(d==="done"){let c=Array.isArray(m.suggestions)?m.suggestions.filter(g=>typeof g=="string"&&g.trim()!==""):[];o={id:String(m.id),role:"agent",text:String(m.text??i.text),createdAt:String(m.createdAt??i.createdAt),...c.length?{suggestions:c}:{},...m.askDetails&&typeof m.askDetails=="object"?{askDetails:m.askDetails}:{},...m.detailsForm&&typeof m.detailsForm=="object"?{detailsForm:m.detailsForm}:{}}}else d==="error"&&(l=typeof m?.message=="string"?m.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 xe(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)}},xi=()=>{let t=new Map;return{get:e=>t.get(e)??null,set:(e,n)=>{t.set(e,n)}}},bi=()=>({get(t){try{return globalThis.localStorage?.getItem(t)??null}catch{return null}},set(t,e){try{globalThis.localStorage?.setItem(t,e)}catch{}}}),vi=60,yi=class{constructor(t){if(v(this,"src",t),v(this,"current",null),v(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-vi>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 G(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 G(this.src.apiUrl,"/sdk/v1/session",{token:t}),token:t}}},ki="https://api.character.xyz",dt=class Rt extends ct{constructor(e,n,i){super(),v(this,"apiUrl",e),v(this,"session",n),v(this,"info",i),v(this,"chat"),v(this,"currentCall",null),v(this,"destroyed",!1),v(this,"openingP",null),v(this,"actionHandlers",new Map),this.chat=new _i(e,n)}static async init(e){let n=(e.apiUrl??ki).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"?xi():e.storage&&typeof e.storage=="object"?e.storage:bi(),a=new yi({apiUrl:n,agentId:e.agentId,publishableKey:e.publishableKey,getSessionToken:e.getSessionToken,store:i}),s=await a.refresh();return new Rt(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 G(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 G(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 G(this.apiUrl,"/sdk/v1/lead",{token:n,body:{...e,consent:!0,...i?{page:i}:{}}})}async declineDetails(){let e=await this.session.token();await G(this.apiUrl,"/sdk/v1/lead/decline",{token:e,method:"POST",body:{}})}async identify(e){let n=await this.session.token();await G(this.apiUrl,"/sdk/v1/context",{token:n,method:"POST",body:{visitor:e}})}async setContext(e){let n=await this.session.token();await G(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??wi(),o=await G(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 G(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 gi(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 wi(){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 $e,E,Nt,Ci,se,Pt,Bt,Ht,pt,De,be,Wt,ft,ut,ht,Si,Pe={},Ue=[],Ti=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Ne=Array.isArray;function ie(t,e){for(var n in e)t[n]=e[n];return t}function gt(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function Ai(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?$e.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 ze(t,o,i,a,null)}function ze(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??++Nt,__i:-1,__u:0};return a==null&&E.vnode!=null&&E.vnode(s),s}function F(t){return t.children}function Re(t,e){this.props=t,this.context=e}function le(t,e){if(e==null)return t.__?le(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"?le(t):null}function Mi(t){if(t.__P&&t.__d){var e=t.__v,n=e.__e,i=[],a=[],s=ie({},e);s.__v=e.__v+1,E.vnode&&E.vnode(s),mt(t.__P,s,e,t.__n,t.__P.namespaceURI,32&e.__u?[n]:null,i,n??le(e),!!(32&e.__u),a),s.__v=e.__v,s.__.__k[s.__i]=s,Kt(i,s,a),e.__e=e.__=null,s.__e!=n&&Yt(s)}}function Yt(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}),Yt(t)}function Ut(t){(!t.__d&&(t.__d=!0)&&se.push(t)&&!Oe.__r++||Pt!=E.debounceRendering)&&((Pt=E.debounceRendering)||Bt)(Oe)}function Oe(){try{for(var t,e=1;se.length;)se.length>e&&se.sort(Ht),t=se.shift(),e=se.length,Mi(t)}finally{se.length=Oe.__r=0}}function jt(t,e,n,i,a,s,o,l,p,d,f){var m,c,g,x,b,_,k=i&&i.__k||Ue,w=e.length;for(p=Ei(n,e,k,p,w),m=0;m<w;m++)(g=n.__k[m])!=null&&(c=g.__i!=-1&&k[g.__i]||Pe,g.__i=m,_=mt(t,g,c,a,s,o,l,p,d,f),x=g.__e,g.ref&&c.ref!=g.ref&&(c.ref&&_t(c.ref,null,g),f.push(g.ref,g.__c||x,g)),b==null&&x!=null&&(b=x),4&g.__u?(p=qt(g,p,t),c.__e&&(c.__e=null)):typeof g.type=="function"&&_!==void 0?p=_:x&&(p=x.nextSibling),g.__u&=-7);return n.__e=b,p}function Ei(t,e,n,i,a){var s,o,l,p,d,f=n.length,m=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]=ze(null,o,null,null,null):Ne(o)?o=t.__k[s]=ze(F,{children:o},null,null,null):o.constructor===void 0&&o.__b>0?o=t.__k[s]=ze(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=Fi(o,n,p,m))!=-1&&(m--,(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(m)for(s=0;s<f;s++)(l=n[s])!=null&&(2&l.__u)==0&&(l.__e==i&&(i=le(l)),Zt(l,l));return i}function qt(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=qt(i[a],e,n));return e}t.__e!=e&&(e&&t.type&&!e.parentNode&&(e=le(t)),e=n.insertBefore(t.__e,e||null));do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function Fi(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 Ot(t,e,n){e[0]=="-"?t.setProperty(e,n??""):t[e]=n==null?"":typeof n!="number"||Ti.test(e)?n:n+"px"}function Le(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||Ot(t.style,e,"");if(n)for(e in n)i&&n[e]==i[e]||Ot(t.style,e,n[e])}else if(e[0]=="o"&&e[1]=="n")s=e!=(e=e.replace(Wt,"$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[be]=i[be]:(n[be]=ft,t.addEventListener(e,s?ht:ut,s)):t.removeEventListener(e,s?ht:ut,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 $t(t){return function(e){if(this.l){var n=this.l[e.type+t];if(e[De]==null)e[De]=ft++;else if(e[De]<n[be])return;return n(E.event?E.event(e):e)}}}function mt(t,e,n,i,a,s,o,l,p,d){var f,m,c,g,x,b,_,k,w,$,R,N,j,H,O,X,y=e.type;if(e.constructor!==void 0)return null;128&n.__u&&(p=!!(32&n.__u),s=[l=e.__e=n.__e]),(f=E.__b)&&f(e);e:if(typeof y=="function"){m=o.length;try{if(w=e.props,$=y.prototype&&y.prototype.render,R=(f=y.contextType)&&i[f.__c],N=f?R?R.props.value:f.__:i,n.__c?k=(c=e.__c=n.__c).__=c.__E:($?e.__c=c=new y(w,N):(e.__c=c=new Re(w,N),c.constructor=y,c.render=Li),R&&R.sub(c),c.state||(c.state={}),c.__n=i,g=c.__d=!0,c.__h=[],c._sb=[]),$&&c.__s==null&&(c.__s=c.state),$&&y.getDerivedStateFromProps!=null&&(c.__s==c.state&&(c.__s=ie({},c.__s)),ie(c.__s,y.getDerivedStateFromProps(w,c.__s))),x=c.props,b=c.state,c.__v=e,g)$&&y.getDerivedStateFromProps==null&&c.componentWillMount!=null&&c.componentWillMount(),$&&c.componentDidMount!=null&&c.__h.push(c.componentDidMount);else{if($&&y.getDerivedStateFromProps==null&&w!==x&&c.componentWillReceiveProps!=null&&c.componentWillReceiveProps(w,N),e.__v==n.__v||!c.__e&&c.shouldComponentUpdate!=null&&c.shouldComponentUpdate(w,c.__s,N)===!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(B){B&&(B.__=e)}),Ue.push.apply(c.__h,c._sb),c._sb=[],c.__h.length&&o.push(c),l=le(n);break e}c.componentWillUpdate!=null&&c.componentWillUpdate(w,c.__s,N),$&&c.componentDidUpdate!=null&&c.__h.push(function(){c.componentDidUpdate(x,b,_)})}if(c.context=N,c.props=w,c.__P=t,c.__e=!1,j=E.__r,H=0,$)c.state=c.__s,c.__d=!1,j&&j(e),f=c.render(c.props,c.state,c.context),Ue.push.apply(c.__h,c._sb),c._sb=[];else do c.__d=!1,j&&j(e),f=c.render(c.props,c.state,c.context),c.state=c.__s;while(c.__d&&++H<25);c.state=c.__s,c.getChildContext!=null&&(i=ie(ie({},i),c.getChildContext())),$&&!g&&c.getSnapshotBeforeUpdate!=null&&(_=c.getSnapshotBeforeUpdate(x,b)),O=f!=null&&f.type===F&&f.key==null?Xt(f.props.children):f,l=jt(t,Ne(O)?O:[O],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(B){if(o.length=m,e.__v=null,p||s!=null){if(B.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(X=s.length;X--;)gt(s[X])}else e.__e=n.__e;e.__k==null&&(e.__k=n.__k||[]),B.then||Vt(e),E.__e(B,e,n)}}else s==null&&e.__v==n.__v?(e.__k=n.__k,e.__e=n.__e):l=e.__e=Ii(n.__e,e,n,i,a,s,o,p,d);return(f=E.diffed)&&f(e),128&e.__u?void 0:l}function Vt(t){t&&(t.__c&&(t.__c.__e=!0),t.__k&&t.__k.some(Vt))}function Kt(t,e,n){for(var i=0;i<n.length;i++)_t(n[i],n[++i],n[++i]);E.__c&&E.__c(e,t),t.some(function(a){try{t=a.__h,a.__h=[],t.some(function(s){s.call(a)})}catch(s){E.__e(s,a.__v)}})}function Xt(t){return typeof t!="object"||t==null||t.__b>0?t:Ne(t)?t.map(Xt):t.constructor!==void 0?null:ie({},t)}function Ii(t,e,n,i,a,s,o,l,p){var d,f,m,c,g,x,b,_=n.props||Pe,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&&(E.__m&&E.__m(e,s),l=!1),s=null}if(w==null)_===k||l&&t.data==k||(t.data=k);else{if(s=w=="textarea"&&k.defaultValue!=null?null:s&&$e.call(t.childNodes),!l&&s!=null)for(_={},d=0;d<t.attributes.length;d++)_[(g=t.attributes[d]).name]=g.value;for(d in _)g=_[d],d=="dangerouslySetInnerHTML"?m=g:d=="children"||d in k||d=="value"&&"defaultValue"in k||d=="checked"&&"defaultChecked"in k||Le(t,d,null,g,a);for(d in k)g=k[d],d=="children"?c=g:d=="dangerouslySetInnerHTML"?f=g:d=="value"?x=g:d=="checked"?b=g:l&&typeof g!="function"||_[d]===g||Le(t,d,g,_[d],a);if(f)l||m&&(f.__html==m.__html||f.__html==t.innerHTML)||(t.innerHTML=f.__html),e.__k=[];else if(m&&(t.innerHTML=""),jt(e.type=="template"?t.content:t,Ne(c)?c:[c],e,n,i,w=="foreignObject"?"http://www.w3.org/1999/xhtml":a,s,o,s?s[0]:n.__k&&le(n,0),l,p),s!=null)for(d=s.length;d--;)gt(s[d]);l&&w!="textarea"||(d="value",w=="progress"&&x==null?t.removeAttribute("value"):x!=null&&(x!==t[d]||w=="progress"&&!x||w=="option"&&x!=_[d])&&Le(t,d,x,_[d],a),d="checked",b!=null&&b!=t[d]&&Le(t,d,b,_[d],a))}return t}function _t(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){E.__e(a,n)}}function Zt(t,e,n){var i,a;if(E.unmount&&E.unmount(t),(i=t.ref)&&(i.current&&i.current!=t.__e||_t(i,null,e)),(i=t.__c)!=null){if(i.componentWillUnmount)try{i.componentWillUnmount()}catch(s){E.__e(s,e)}i.base=i.__P=i.__n=null}if(i=t.__k)for(a=0;a<i.length;a++)i[a]&&Zt(i[a],e,n||typeof t.type!="function");n||gt(t.__e),t.__c=t.__=t.__e=void 0}function Li(t,e,n){return this.constructor(t,n)}function xt(t,e,n){var i,a,s,o;e==document&&(e=document.documentElement),E.__&&E.__(t,e),a=(i=typeof n=="function")?null:n&&n.__k||e.__k,s=[],o=[],mt(e,t=(!i&&n||e).__k=Ai(F,null,[t]),a||Pe,Pe,e.namespaceURI,!i&&n?[n]:a?null:e.firstChild?$e.call(e.childNodes):null,s,!i&&n?n:a?a.__e:e.firstChild,i,o),Kt(s,t,o),t.props.children=null}$e=Ue.slice,E={__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}},Nt=0,Ci=function(t){return t!=null&&t.constructor===void 0},Re.prototype.setState=function(t,e){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=ie({},this.state),typeof t=="function"&&(t=t(ie({},n),this.props)),t&&ie(n,t),t!=null&&this.__v&&(e&&this._sb.push(e),Ut(this))},Re.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),Ut(this))},Re.prototype.render=F,se=[],Bt=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Ht=function(t,e){return t.__v.__b-e.__v.__b},Oe.__r=0,pt=Math.random().toString(8),De="__d"+pt,be="__a"+pt,Wt=/(PointerCapture)$|Capture$/i,ft=0,ut=$t(!1),ht=$t(!0),Si=0;var ue,z,bt,Jt,ve=0,sn=[],U=E,Gt=U.__b,Qt=U.__r,en=U.diffed,tn=U.__c,nn=U.unmount,an=U.__;function He(t,e){U.__h&&U.__h(z,t,ve||e),ve=0;var n=z.__H||(z.__H={__:[],__h:[]});return t>=n.__.length&&n.__.push({}),n.__[t]}function C(t){return ve=1,Di(ln,t)}function Di(t,e,n){var i=He(ue++,2);if(i.t=t,!i.__c&&(i.__=[n?n(e):ln(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=z,!z.__f)){var a=function(l,p,d){if(!i.__c.__H)return!0;var f=!1,m=i.__c.props!==l;if(i.__c.__H.__.some(function(g){if(g.__N){f=!0;var x=g.__[0];g.__=g.__N,g.__N=void 0,x!==g.__[0]&&(m=!0)}}),s){var c=s.call(this,l,p,d);return f?c||m:c}return!f||m};z.__f=!0;var s=z.shouldComponentUpdate,o=z.componentWillUpdate;z.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)},z.shouldComponentUpdate=a}return i.__N||i.__}function I(t,e){var n=He(ue++,3);!U.__s&&yt(n.__H,e)&&(n.__=t,n.u=e,z.__H.__h.push(n))}function We(t,e){var n=He(ue++,4);!U.__s&&yt(n.__H,e)&&(n.__=t,n.u=e,z.__h.push(n))}function K(t){return ve=5,on(function(){return{current:t}},[])}function on(t,e){var n=He(ue++,7);return yt(n.__H,e)&&(n.__=t(),n.__H=e,n.__h=t),n.__}function ye(t,e){return ve=8,on(function(){return t},e)}function zi(){for(var t;t=sn.shift();){var e=t.__H;if(t.__P&&e)try{e.__h.some(Be),e.__h.some(vt),e.__h=[]}catch(n){e.__h=[],U.__e(n,t.__v)}}}U.__b=function(t){z=null,Gt&&Gt(t)},U.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),an&&an(t,e)},U.__r=function(t){Qt&&Qt(t),ue=0;var e=(z=t.__c).__H;e&&(bt===z?(e.__h=[],z.__h=[],e.__.some(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(e.__h.some(Be),e.__h.some(vt),e.__h=[],ue=0)),bt=z},U.diffed=function(t){en&&en(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(sn.push(e)!==1&&Jt===U.requestAnimationFrame||((Jt=U.requestAnimationFrame)||Ri)(zi)),e.__H.__.some(function(n){n.u&&(n.__H=n.u,n.u=void 0)})),bt=z=null},U.__c=function(t,e){e.some(function(n){try{n.__h.some(Be),n.__h=n.__h.filter(function(i){return!i.__||vt(i)})}catch(i){e.some(function(a){a.__h&&(a.__h=[])}),e=[],U.__e(i,n.__v)}}),tn&&tn(t,e)},U.unmount=function(t){nn&&nn(t);var e,n=t.__c;n&&n.__H&&(n.__H.__.some(function(i){try{Be(i)}catch(a){e=a}}),n.__H=void 0,e&&U.__e(e,n.__v))};var rn=typeof requestAnimationFrame=="function";function Ri(t){var e,n=function(){clearTimeout(i),rn&&cancelAnimationFrame(e),setTimeout(t)},i=setTimeout(n,35);rn&&(e=requestAnimationFrame(n))}function Be(t){var e=z,n=t.__c;typeof n=="function"&&(t.__c=void 0,n()),z=e}function vt(t){var e=z;t.__c=t.__(),z=e}function yt(t,e){return!t||t.length!==e.length||e.some(function(n,i){return n!==t[i]})}function ln(t,e){return typeof e=="function"?e(t):e}var Ce={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},kt=(t,e=200)=>typeof t=="string"?t.slice(0,e):void 0;function Pi(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 Ui(t){if(typeof t!="string")return;let e=t.trim();return/^[\w\s,"'-]{1,120}$/.test(e)?e:void 0}function Se(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=Pi(e.accent)??n.accent,n.radius=ke(e.radius,0,40)??n.radius,n.font=Ui(e.font)??n.font,e.subtitle===null?n.subtitle=null:n.subtitle=kt(e.subtitle,80)??n.subtitle,n.greeting=kt(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=kt(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 cn(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}function pn(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 Ye(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 dn(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 un(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=>dn(a.replace(/^\s*[-*•]\s+/,"")))}):e.push({t:"p",parts:dn(n)})}return e}var Oi={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."},hn={},fn=!0;function gn(t){hn=t??{},fn=!t||!Object.keys(t).length}function h(t,e){let n=hn[t]??Oi[t];if(e)for(let i in e)n=n.split(`{${i}}`).join(String(e[i]));return n}function oe(t){return fn?pn(t):String(t)}function je(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 mn(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 _n={cx:.5,cy:.12,span:.06};function bn(t,e,n){let i=t?.face?.eyes,a=t?.face?.chin;if(!i||!a||!e||!n)return _n;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}:_n}var qe={faceFraction:.26,at:{x:.5,y:.5}},vn={faceFraction:.14,at:{x:.5,y:.34},keepCrown:!0},yn={faceFraction:.16,at:{x:.5,y:.22},keepCrown:!0},kn={fit:"height"},$i=1.8,xn=.04;function wn(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*$i)*s;return a.keepCrown&&p<i*xn&&(l+=i*xn-p),{width:o,height:s,left:n*a.at.x-t.cx*o,top:l}}var Cn=/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/,Ni=/\+?\d[\d\s().-]{5,}\d/g,Bi=/\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,Hi=new Set(["interested","looking","from","with","here","trying","not","a","an","the","just","also","happy","keen","curious","calling","sure","fine","good","okay","ok"]);function Sn(t){let e={},n=t.match(Cn)?.[0];n&&(e.email=n.replace(/[.,;:]+$/,""));for(let a of t.replace(Cn," ").matchAll(Ni)){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(Bi)?.[1];if(i){let a=i.split(/\s+/).filter(o=>!Hi.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 Wi=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:--Wi,__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 E.vnode&&E.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}),Te=({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"})),he=({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"})),Tn=({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"})),An=({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"})]})),Mn=({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"})]})),Ve=({size:t=18})=>ee(t,r("path",{d:"M6 6l12 12M18 6L6 18"})),En=({size:t=18})=>ee(t,r("path",{d:"M12 19V5M5.5 11.5L12 5l6.5 6.5"})),Fn=({size:t=18})=>ee(t,r("path",{d:"M15 5l-7 7 7 7"}));var In=({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"})),Ln=({size:t=14})=>ee(t,r("path",{d:"M5 12.5l4.2 4.2L19 7"})),Dn=({size:t=14})=>ee(t,r("path",{d:"M4 12a8 8 0 1 0 2.3-5.6M4 4v4h4"}));var wt={current:null};function Yi(t){return t?t.speaking?"speaking":t.agentState==="thinking"?"reasoning":t.agentState==="listening"||t.phase==="live"?"listening":"idle":"idle"}function zn({client:t,call:e,state:n,src:i,onStatus:a}){let s=K(null),[o,l]=C(!1),p=K(!1),d=(()=>{try{return new URL(i).origin}catch{return null}})(),f=(c,g)=>{let x=s.current?.contentWindow;x&&d&&x.postMessage({cx:"face",...c},d,g??[])};I(()=>{if(!d){a("unavailable");return}let c=!1,g=b=>{if(b.source!==s.current?.contentWindow||b.origin!==d)return;let _=b.data;_?.cx==="face"&&(_.type==="loaded"?(p.current=!0,l(!0),t.videoAvatar().then(k=>{c||(k?f({type:"init",avatar:k}):a("unavailable"))}).catch(()=>!c&&a("unavailable"))):_.type==="ready"?(wt.current=typeof _.faceEmotion=="string"?_.faceEmotion:null,a("ready")):_.type==="unavailable"&&a("unavailable"))};window.addEventListener("message",g);let x=setTimeout(()=>!c&&!p.current&&a("unavailable"),15e3);return()=>{c=!0,clearTimeout(x),window.removeEventListener("message",g)}},[t,d]);let m=Yi(n);return I(()=>{o&&f({type:"state",state:m})},[m,o]),I(()=>{if(!e||!o)return;let c=[e.on("face",({corr:b,payload:_})=>f({type:"batch",corr:b,payload:_},[_.buffer])),e.on("line",({corr:b,event:_})=>{f(_==="audible"?{type:"audible",corr:b,ms:e.audible()?.ms??0}:{type:"end",corr:b})})],g=0,x=()=>{let b=e.audible();b&&f({type:"clock",corr:b.corr,ms:b.ms}),g=requestAnimationFrame(x)};return g=requestAnimationFrame(x),()=>{c.forEach(b=>b()),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 ji(){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 qi=()=>typeof matchMedia<"u"&&matchMedia("(prefers-reduced-motion: reduce)").matches;function Ae({agent:t,shot:e,talking:n=!1,still:i=!1,full:a=!1,class:s}){let o=K(null),[l,p]=C({w:0,h:0}),[d,f]=C(null),[m,c]=C({}),[g,x]=C({}),b=t.video,_=(L,D,ne)=>!a&&L&&!g[ne]?L:D,k=b?.anchor?.alphaUrl??b?.anchor?.url??null,w=_(b?.anchor?.smallUrl,k,"anchor"),$=w!==k,R=!i&&!qi()&&ji(),N=b?.clips.idle,j=b?.clips.talking??N,H=_(N?.smallUrl,N?.alphaUrl??null,"idle"),O=_(j?.smallUrl,j?.alphaUrl??null,"talk")??H,[X,y]=C(a);if(I(()=>{n&&y(!0)},[n]),We(()=>{let L=o.current;if(!L)return;let D=()=>p({w:L.clientWidth,h:L.clientHeight});if(D(),typeof ResizeObserver>"u")return;let ne=new ResizeObserver(D);return ne.observe(L),()=>ne.disconnect()},[]),!b||!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 Z=(b.anchor?.width&&b.anchor?.height?{w:b.anchor.width,h:b.anchor.height}:null)??(d&&!$?d:null),ae=bn(b,Z?.w??0,Z?.h??0),Y=l.w&&l.h&&Z?wn(ae,Z.w/Z.h,l.w,l.h,e):null,re=Y?{width:`${Y.width}px`,height:`${Y.height}px`,left:`${Y.left}px`,top:`${Y.top}px`}:{},S=!!Y&&R&&!!H&&!!m.idle,W=!!Y&&R&&!!O&&O!==H&&!!m.talk&&n,J=!!Y&&(!!d||S);return r("div",{ref:o,class:`portrait ${s??""}`,"aria-hidden":"true",children:[r("img",{class:"portrait__media",src:w,alt:"",draggable:!1,style:{...re,opacity:Y&&d&&!S?1:0},onLoad:L=>{let D=L.currentTarget;f({w:D.naturalWidth,h:D.naturalHeight})},onError:()=>$&&x(L=>({...L,anchor:!0}))}),R&&H?r(Rn,{src:H,style:re,visible:S&&!W,onReady:()=>c(L=>({...L,idle:!0})),onFail:()=>x(L=>({...L,idle:!0}))}):null,R&&X&&O&&O!==H?r(Rn,{src:O,style:re,visible:W,onReady:()=>c(L=>({...L,talk:!0})),onFail:()=>x(L=>({...L,talk:!0}))}):null,r("span",{class:`portrait__sparkle${J?" is-done":""}`,children:[r("i",{}),r("i",{}),r("i",{})]})]})}function Rn({src:t,style:e,visible:n,onReady:i,onFail:a}){let s=K(null);return I(()=>{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 Ct="cxyz:greeted",Pn="cxyz:introduced";function Me(t,e){try{return e!==void 0&&localStorage.setItem(t,e),localStorage.getItem(t)}catch{return null}}function Vi(){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 Ki(t){let[e,n]=C(t.chat.messages),[i,a]=C(t.chat.isBusy);return I(()=>{let s=t.chat.on("messages",n),o=t.chat.on("busy",a);return()=>{s(),o()}},[t]),{messages:e,busy:i}}function Xi(t){let[e,n]=C(t.call),[i,a]=C(t.call?.state??null),[s,o]=C([]);return I(()=>t.on("call",l=>l&&n(l)),[t]),I(()=>{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 Zi(t,e){let[n,i]=C(Date.now());return I(()=>{if(!e)return;let a=setInterval(()=>i(Date.now()),1e3);return()=>clearInterval(a)},[e]),t?Math.max(0,(n-t)/1e3):0}function Ji(t,e,n){I(()=>{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 Un({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 Gi={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 Qi(){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 ea({form:t,title:e,note:n,onSend:i,onSkip:a,skipLabel:s,initial:o,hasHistory:l}){let[p,d]=C(()=>({...o??{}})),f=t.reasonOptions??[],m=t.fields.includes("reason"),c=m&&!l?Qi():"",g=t.reasonDefault||c||"",[x,b]=C(g),[_,k]=C(t.reasonDefault?t.reasonSource??"conversation":c?"cta":""),[w,$]=C(m&&!g),[R,N]=C(!1),[j,H]=C(""),[O,X]=C({}),[y,B]=C(null),[Z,ae]=C(!1),Y=K(null),re=K(null);return I(()=>{setTimeout(()=>Y.current?.focus({preventScroll:!0}),80)},[]),We(()=>{let S=re.current?.closest(".log");if(!S)return;let W=S.style.scrollBehavior;S.style.scrollBehavior="auto",S.scrollTop=S.scrollHeight,S.style.scrollBehavior=W},[w,R]),r("form",{class:"card",part:"details",ref:re,onSubmit:async S=>{S.preventDefault(),ae(!0),X({}),B(null);try{let W=(R?j:x).trim();await i({name:p.name??"",email:p.email??"",...p.phone?{phone:p.phone}:{},...p.company?{company:p.company}:{},...m&&W?{reason:W}:{}})}catch(W){let J=W.fields??{};Object.keys(J).length?X(J):B(W.message||h("sendFailed"))}finally{ae(!1)}},children:[r("div",{class:"card__title",children:e}),n?r("div",{class:"card__note",children:n}):null,t.fields.map((S,W)=>{if(S==="reason")return r("div",{class:"card__field card__field--reason",children:[!w&&x?null:r("span",{class:"card__reason-label",children:t.reasonLabel||h("reasonField")}),!w&&x?r(F,{children:[r("div",{class:"card__reason-line",children:[r("span",{class:"card__reason-said",children:h("reasonInferred")}),r("strong",{children:x}),r("button",{type:"button",class:"card__change",onClick:()=>$(!0),children:h("change")})]}),_?r("span",{class:"card__reason-src",children:_==="cta"?h("reasonFromPage"):_==="conversation"?h("reasonFromConversation"):null}):null]}):r("div",{class:"card__reason-edit",children:[f.length?r("div",{class:"card__chips",role:"group","aria-label":t.reasonLabel||h("reasonField"),children:[f.map(D=>r("button",{type:"button",class:"card__chip","aria-pressed":!R&&x===D,onClick:()=>{b(D),N(!1),k("user"),$(!1)},children:D},D)),r("button",{type:"button",class:"card__chip","aria-pressed":R,onClick:()=>{N(!0),b("")},children:h("reasonOther")})]}):null,R||!f.length?r("input",{type:"text",maxLength:500,placeholder:h("reasonPlaceholder"),value:j,onInput:D=>H(D.currentTarget.value)}):null]}),O.reason?r("em",{children:O.reason}):null]},S);let J=Gi[S],L=h(J.label);return r("label",{class:"card__field",children:[r("span",{children:[L,S==="phone"||S==="company"?r("i",{children:[" \xB7 ",h("optional")]}):null]}),r("input",{ref:W===0?Y:void 0,type:J.type,autocomplete:J.auto,required:S==="name"||S==="email",maxLength:S==="email"?254:120,value:p[S]??"","aria-invalid":O[S]?"true":void 0,onInput:D=>d(ne=>({...ne,[S]:D.currentTarget.value}))}),O[S]?r("em",{children:O[S]}):null]},S)}),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]}),y?r("div",{class:"card__failed",children:y}):null,r("div",{class:"card__actions",children:[r("button",{type:"submit",class:"btn btn--accent btn--sm",disabled:Z,children:Z?h("sending"):h("send")}),r("button",{type:"button",class:"btn btn--ghost btn--sm",onClick:a,disabled:Z,children:s})]})]})}function St({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 On({text:t}){return r(F,{children:un(t).map((e,n)=>e.t==="ul"?r("ul",{children:e.items.map((i,a)=>r("li",{children:r(Un,{parts:i})},a))},n):r("p",{children:r(Un,{parts:e.parts})},n))})}function $n({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,m]=C(!1),[c,g]=C(!1),{messages:x,busy:b}=Ki(t),{call:_,state:k,captions:w,reset:$}=Xi(t),[R,N]=C(""),j=K(null),H=K(null),O=K(null),X=e.subtitle??a.tagline,y=a.name||h("assistant"),[B,Z]=C(null);I(()=>{if(!o)return;let u=!0;return t.opening().then(T=>{u&&(gn(T?.strings),Z(T))}),()=>{u=!1}},[t,o]);let ae=e.greeting||B?.teaser||"",Y=e.suggestions.length?e.suggestions:B?.suggestions??[],re=B?.greeting||h("greetingDefault",{name:y}),[S,W]=C("loading"),[J,L]=C(!1),[D,ne]=C(null),[Tt,Wn]=C(""),[Je,Ge]=C(null),[Qe,et]=C(null),te=ye(u=>{d(u),i(u)},[i]),ce=ye(()=>{m(!0),setTimeout(()=>{m(!1),te("closed")},200)},[te]),fe=ye(async()=>{try{let u=await t.chat.load();W(T=>T==="loading"?u.length?u.length:"empty":T)}catch{W(u=>u==="loading"?"empty":u)}},[t]),Q=ye((u=o?"chat":"call")=>{g(!1),Me(Ct,"1"),te(u),u==="chat"&&fe()},[o,te,fe]);I(()=>n({open:Q,close:ce}),[n,Q,ce]),I(()=>t.on("siteEvent",u=>{u.openChat&&Q("chat")}),[t,Q]),I(()=>{e.open&&o&&fe()},[fe,e.open,o]),I(()=>{if(!ae||Me(Ct))return;let u=setTimeout(()=>g(!0),e.greetingDelay*1e3);return()=>clearTimeout(u)},[ae,e.greetingDelay]),I(()=>{if(p!=="chat"||J||S==="loading")return;let u=setTimeout(()=>L(!0),700);return()=>clearTimeout(u)},[p,J,S]);let[tt,Yn]=C(()=>!Me(Pn));I(()=>{if(!tt)return;let u=setTimeout(()=>{Yn(!1),Me(Pn,"1")},5e3);return()=>clearTimeout(u)},[tt]),I(()=>{if(p==="closed")return;let u=T=>{T.key==="Escape"&&ce()};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[p,ce]),I(()=>{let u=j.current;u&&(u.scrollTop=u.scrollHeight)},[x,p,k?.phase]),I(()=>{p==="chat"&&setTimeout(()=>H.current?.focus({preventScroll:!0}),60)},[p]);let ge=e.face&&!!a.video,[Ee,jn]=C("loading"),A=k?.phase??"idle";I(()=>{if(!(A!=="ready"||!_)){if(Vi(),p==="call"){if(!ge||Ee!=="loading"){_.accept();return}let u=setTimeout(()=>_.accept(),3e3);return()=>clearTimeout(u)}if(typeof document<"u"&&document.hidden){let u=document.title;document.title=`\u25CF ${y} is ready for you`;let T=()=>{document.title=u,document.removeEventListener("visibilitychange",T)};document.addEventListener("visibilitychange",T)}}},[A,_,p,y,ge,Ee]);let At=A==="live"||A==="connecting";Ji(_,O,At&&p==="call");let Fe=Zi(k?.startedAt??null,A==="live"),nt=ta(_,k?.position??1),it=()=>{let u=B?.details;if(u&&!D&&o){Ge(u),te("chat"),fe();return}at()},Mt=(u,T="")=>{ne(u),Wn(T),et(null);let de=!!Je;Ge(null),de&&at()},qn=async u=>{await t.sendDetails(u),Mt("sent",u.name.trim().split(/\s+/)[0]??"")},Vn=()=>{t.declineDetails().catch(()=>{}),Mt("skipped")},Kn=async()=>{try{await t.chat.reset()}catch{return}W("empty"),L(!1),ne(null),Ge(null),et(null),N(""),Z(await t.opening(!0))},at=async()=>{te("call");try{await t.startCall({autoAccept:!1,...ge?{face:{emotion:()=>wt.current}}:{}})}catch{}},rt=[...x].reverse().find(u=>u.detailsForm||u.askDetails)?.detailsForm??[...x].reverse().find(u=>u.askDetails)?.askDetails??B?.details??null,me=async u=>{let T=u.trim();if(!T||b)return;let de=rt&&D!=="sent"?Sn(T):null;de&&rt&&et({form:rt,values:de}),N(""),H.current&&(H.current.style.height="");try{await t.chat.send(T)}catch{}},Ie=x[x.length-1],Et=Ie?.role==="agent"&&!Ie.streaming?Ie.askDetails:void 0,q=Je?{form:Je,kind:"call"}:Qe&&D!=="sent"&&!b?{form:Qe.form,kind:"typed",initial:Qe.values}:Et&&!D?{form:Et,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:[ae,r("button",{class:"greeting__close","aria-label":h("dismiss"),onClick:T=>{T.stopPropagation(),g(!1),Me(Ct,"1")},children:r(Ve,{size:14})})]}):null,r("button",{class:`presence presence--${e.display} ${u?"presence--live":""}`,part:"presence","aria-label":u?A==="queued"?h("inLineToCall",{position:oe(k?.position??1),name:y}):h("backToCallWith",{name:y}):o?h("chatWith",{name:y}):h("callName",{name:y}),onClick:()=>Q(u||!o?"call":"chat"),children:[e.display==="bubble"?r("span",{class:"presence__ring"}):null,r("span",{class:"presence__face",children:r(Ae,{agent:a,shot:e.display==="full"?kn:e.display==="half"?yn:qe})}),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:oe(k?.position??1)}):h("backToCall"):o?h("chatWith",{name:y}):h("callName",{name:y})}):null]}),e.launcher==="bubble"?null:r("div",{class:`acts ${tt?"acts--labelled":""}`,part:"actions",children:[o?r("button",{class:"act","aria-label":h("chatWith",{name:y}),onClick:()=>Q("chat"),children:[r(Te,{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:oe(k?.position??1)}):h("backToCall"):h("callName",{name:y}),onClick:()=>u?Q("call"):it(),children:[r(he,{size:20}),r("span",{class:"act__label","aria-hidden":"true",children:u?A==="queued"?h("inLine",{position:oe(k?.position??1)}):h("onCall"):h("call")}),A==="queued"?r("span",{class:"act__badge","aria-hidden":"true",children:k?.position??1}):null]}):null]})]})}let Xn=r("div",{class:"head",part:"header",children:[r("div",{class:"head__face",children:r(Ae,{agent:a,shot:qe})}),r("div",{class:"head__who",children:[r("div",{class:"head__name",children:y}),r("div",{class:"head__sub",children:[r("i",{}),b?h("typing"):X||h("online")]})]}),p==="chat"&&x.length>0&&!b?r("button",{class:"icon-btn","aria-label":h("newConversation"),title:h("newConversation"),onClick:()=>{Kn()},children:r(In,{})}):null,l&&p==="chat"?r("button",{class:"icon-btn icon-btn--accent","aria-label":h("callName",{name:y}),title:h("callName",{name:y}),onClick:()=>_&&A!=="ended"?te("call"):it(),children:r(he,{size:18})}):null,r("button",{class:"icon-btn","aria-label":h("close"),onClick:ce,children:r(Ve,{})})]});if(p==="chat")return r("div",{class:`panel ${f?"is-closing":""}`,part:"panel",role:"dialog","aria-label":h("chatWith",{name:y}),children:[Xn,_&&(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:oe(k?.position??1),eta:je(k?.etaSeconds??null)})}):r(F,{children:[r("b",{children:h("readyForYou",{name:y})})," \xB7 ",h("secondsToJoin",{seconds:k?.holdSeconds??30})]})}),A==="ready"?r("button",{class:"btn btn--accent btn--glow",onClick:()=>{_.accept(),te("call")},children:h("join")}):r("button",{class:"btn",onClick:()=>te("call"),children:h("view")})]}):null,r("div",{class:"log",ref:j,role:"log","aria-live":"polite","aria-relevant":"additions",children:[x.length===0?r(F,{children:[r("div",{class:"empty",children:[r("div",{class:"empty__face",children:r(Ae,{agent:a,shot:qe})}),r("div",{class:"empty__title",children:y}),X?r("div",{class:"empty__body",children:X}):null]}),S==="loading"?null:J?r(F,{children:[r("div",{class:"msg msg--agent",part:"message message-agent",children:r(On,{text:re})}),q?null:r(St,{items:Y,onPick:u=>{me(u)},children:l?r("button",{class:"chip chip--call",onClick:()=>_&&A!=="ended"?te("call"):it(),children:[r(he,{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,x.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:y}),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(On,{text:u.text}):u.text}),u===x[x.length-1]&&u.role==="agent"&&!u.streaming&&!b&&!q&&u.suggestions?.length?r(St,{items:u.suggestions,onPick:T=>{me(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(Dn,{})," ",h("notSent")]}):null]},u.id)),typeof S=="number"&&x.length===S&&B?.welcomeBack?r(F,{children:[r("div",{class:"msg msg--agent",part:"message message-agent",children:B.welcomeBack}),q?null:r(St,{items:Y,onPick:u=>{me(u)}})]}):null,q?r(ea,{form:q.form,initial:q.initial,title:q.kind==="call"?h("beforeYouCall",{name:y}):q.kind==="typed"?h("confirmDetails"):h("leaveDetails"),note:q.kind==="call"?h("detailsWhy"):q.kind==="typed"?h("detailsTyped"):null,onSend:qn,onSkip:Vn,skipLabel:q.kind==="call"?h("skipAndCall"):h("notNow"),hasHistory:x.length>0},q.kind==="invited"?Ie?.id:q.kind):D==="sent"?r("div",{class:"notice",role:"status",children:[r(Ln,{})," ",Tt?h("thanksName",{name:Tt}):h("thanks")]}):null]}),r("form",{class:"compose",part:"composer",onSubmit:u=>{u.preventDefault(),me(R)},children:r("div",{class:"compose__box",children:[r("textarea",{ref:H,rows:1,value:R,maxLength:2e3,placeholder:e.placeholder===Ce.placeholder?h("message"):e.placeholder,"aria-label":h("message"),onInput:u=>{let T=u.currentTarget;N(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(),me(R))}}),r("button",{class:"send",type:"submit","aria-label":h("send"),disabled:!R.trim()||b,children:r(En,{})})]})}),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 M=k,st=M?.position??1,Zn=nt>1?(nt-st)/(nt-1):0,ot=74,Ft=2*Math.PI*ot,_e=M?.maxSeconds?M.maxSeconds-Fe:null,Jn=M?.agentState??"idle",Gn=M?.speaking?h("speaking"):Jn==="thinking"?h("thinking"):h("listening"),Qn=!M||A==="ended"||A==="idle",lt=mn(M?.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 ${ge&&Ee==="ready"?"stage--face":""}`,ref:O,children:[r("div",{class:"stage__figure",style:{opacity:A==="queued"?.35:1,transition:"opacity .6s"},children:[r(Ae,{agent:a,shot:vn,talking:!!M?.speaking,full:!0}),ge?r("div",{class:`stage__face ${Ee==="ready"?"is-ready":""}`,children:r(zn,{client:t,call:_,state:M,src:e.faceUrl,onStatus:jn})}):null]}),At?r("div",{class:"voice"}):null,r("div",{class:"stage__veil"}),r("div",{class:"stage__top",children:[A==="live"?r("span",{class:`badge ${_e!=null&&_e<=60?"badge--warn":""}`,role:"timer","aria-label":h("callTime"),children:[r("i",{}),_e!=null&&_e<=60?h("timeLeft",{time:Ye(_e)}):Ye(Fe)]}):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(Te,{size:18})}):null,r("button",{class:"icon-btn","aria-label":h("minimise"),onClick:ce,children:r(Ve,{})})]})]}),r("div",{class:"stage__bottom","aria-live":"polite",children:[A==="joining"||A==="connecting"?r(F,{children:[r("div",{class:"stage__name",children:y}),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:oe(st),eta:je(M?.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:ot,fill:"none","stroke-width":"7"}),r("circle",{class:"line__fill",cx:"84",cy:"84",r:ot,fill:"none","stroke-width":"7","stroke-linecap":"round","stroke-dasharray":Ft,"stroke-dashoffset":Ft*(1-Math.max(.06,Zn))})]}),r("div",{children:[r("div",{class:"line__num",children:oe(st)}),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:je(M?.etaSeconds??null)})}),r("div",{class:"btn-row",children:[o?r("button",{class:"btn btn--accent",onClick:()=>Q("chat"),children:[r(Te,{size:18})," ",h("keepChatting")]}):null,r("button",{class:"btn",onClick:()=>{_?.hangUp()},children:h("leaveLine")})]})]}):null,A==="ready"?r(F,{children:[r("div",{class:"title",children:h("readyForYou",{name:y})}),r("div",{class:"note",children:h("joinWithin",{seconds:M?.holdSeconds??30})}),r("button",{class:"btn btn--accent btn--glow",onClick:()=>_?.accept(),children:[r(he,{size:18})," ",h("joinCall")]})]}):null,A==="live"?r(F,{children:[r("div",{class:"stage__name",children:y}),r("div",{class:"stage__status",children:[M?.speaking?r("span",{class:"wave","aria-hidden":"true",children:[.6,1,.75,1,.55].map((u,T)=>r("i",{style:{"--k":u}},T))}):null,M?.muted?h("muted"):Gn]}),r("div",{class:"captions",children:w.slice(-2).map((u,T,de)=>r("div",{class:`captions__line ${T===de.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 ${M?.muted?"round--on":""}`,"aria-pressed":M?.muted,"aria-label":M?.muted?h("unmute"):h("mute"),onClick:()=>_?.setMuted(!M?.muted),children:M?.muted?r(Mn,{size:22}):r(An,{size:22})}),r("span",{class:"round__label",children:M?.muted?h("unmute"):h("mute")})]}),r("div",{class:"ctl",children:[r("button",{class:"round round--end","aria-label":h("endCall"),onClick:()=>{_?.hangUp()},children:r(Tn,{size:26})}),r("span",{class:"round__label",children:h("end")})]}),M?.speaking?r("div",{class:"ctl",children:[r("button",{class:"round","aria-label":h("interruptName",{name:y}),onClick:()=>_?.interrupt(),children:r(Fn,{size:22})}),r("span",{class:"round__label",children:h("interrupt")})]}):null]})]}):null,Qn?r(F,{children:[r("div",{class:"title",children:M?lt.title:h("callName",{name:y})}),r("div",{class:"note",children:M?M.endReason==="hangup"&&Fe?`${Ye(Fe)} \xB7 ${lt.body}`:M.error??lt.body:h("talkWith",{name:y})}),r("div",{class:"btn-row",children:[l&&M?.endReason!=="credits"&&M?.endReason!=="unavailable"&&M?.endReason!=="daily_limit"?r("button",{class:"btn btn--accent",onClick:()=>{$(),at()},children:[r(he,{size:18})," ",M?h("callAgain"):h("startCall")]}):null,o?r("button",{class:"btn",onClick:()=>Q("chat"),children:[r(Te,{size:18})," ",h("chat")]}):null]})]}):null]})]})})}function ta(t,e){let n=K({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 Nn=`
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 di(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 pi=.09,ui=350,hi=25e3,fi=()=>({phase:"idle",callId:null,position:null,etaSeconds:null,holdSeconds:null,maxSeconds:null,startedAt:null,endReason:null,muted:!1,speaking:!1,agentState:"idle",error:null}),gi=class extends pt{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",fi()),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"}),zt();try{this.mic=await oi({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 z?t:new z("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 be(this.apiUrl,`/sdk/v1/calls/${encodeURIComponent(this.s.callId)}/events`,{token:e,signal:this.eventsAbort.signal});t=0,await Rt(n,i=>this.onServerEvent(i.event,i.data),this.eventsAbort.signal)}catch(e){if(e?.name==="AbortError")return;if(e instanceof z&&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"}),hi),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>pi){if(this.loudSince??(this.loudSince=i),i-this.loudSince>=ui){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=di(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 ai({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 be(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})}},mi=0,Dt=t=>`${t}_${Date.now().toString(36)}_${(mi++).toString(36)}`,_i=class extends pt{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 z("invalid","Say something first.");if(this.busy)throw new z("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 be(this.apiUrl,"/sdk/v1/chat/messages",{method:"POST",body:{text:e},token:a,signal:this.abort.signal}),o=null,l=null;if(await Rt(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 z("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 z?a:new z("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 be(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 z("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)}},xi=()=>{let t=new Map;return{get:e=>t.get(e)??null,set:(e,n)=>{t.set(e,n)}}},bi=()=>({get(t){try{return globalThis.localStorage?.getItem(t)??null}catch{return null}},set(t,e){try{globalThis.localStorage?.setItem(t,e)}catch{}}}),vi=60,yi=class{constructor(t){if(y(this,"src",t),y(this,"current",null),y(this,"inflight",null),!t.publishableKey&&!t.getSessionToken)throw new z("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-vi>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}}},ki="https://api.character.xyz",ut=class Pt extends pt{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 _i(e,n)}static async init(e){let n=(e.apiUrl??ki).replace(/\/+$/,"");if(e.publishableKey&&/^cxyz_sk_/.test(e.publishableKey))throw new z("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"?xi():e.storage&&typeof e.storage=="object"?e.storage:bi(),a=new yi({apiUrl:n,agentId:e.agentId,publishableKey:e.publishableKey,getSessionToken:e.getSessionToken,store:i}),s=await a.refresh();return new Pt(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??wi(),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 z("invalid","This client was destroyed.");if(!this.features.call)throw new z("forbidden","Calls are not available on this site.");if(this.call)return this.call;let n=new gi(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 wi(){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 Ne,F,Bt,Ci,oe,Ut,Ht,Wt,ht,ze,ve,Yt,mt,ft,gt,Si,Ue={},Oe=[],Ti=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Be=Array.isArray;function ae(t,e){for(var n in e)t[n]=e[n];return t}function _t(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function Ai(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?Ne.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 Re(t,o,i,a,null)}function Re(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??++Bt,__i:-1,__u:0};return a==null&&F.vnode!=null&&F.vnode(s),s}function I(t){return t.children}function Pe(t,e){this.props=t,this.context=e}function ce(t,e){if(e==null)return t.__?ce(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"?ce(t):null}function Mi(t){if(t.__P&&t.__d){var e=t.__v,n=e.__e,i=[],a=[],s=ae({},e);s.__v=e.__v+1,F.vnode&&F.vnode(s),xt(t.__P,s,e,t.__n,t.__P.namespaceURI,32&e.__u?[n]:null,i,n??ce(e),!!(32&e.__u),a),s.__v=e.__v,s.__.__k[s.__i]=s,Xt(i,s,a),e.__e=e.__=null,s.__e!=n&&qt(s)}}function qt(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}),qt(t)}function Ot(t){(!t.__d&&(t.__d=!0)&&oe.push(t)&&!$e.__r++||Ut!=F.debounceRendering)&&((Ut=F.debounceRendering)||Ht)($e)}function $e(){try{for(var t,e=1;oe.length;)oe.length>e&&oe.sort(Wt),t=oe.shift(),e=oe.length,Mi(t)}finally{oe.length=$e.__r=0}}function jt(t,e,n,i,a,s,o,l,p,d,f){var _,c,g,b,x,m,k=i&&i.__k||Oe,w=e.length;for(p=Ei(n,e,k,p,w),_=0;_<w;_++)(g=n.__k[_])!=null&&(c=g.__i!=-1&&k[g.__i]||Ue,g.__i=_,m=xt(t,g,c,a,s,o,l,p,d,f),b=g.__e,g.ref&&c.ref!=g.ref&&(c.ref&&bt(c.ref,null,g),f.push(g.ref,g.__c||b,g)),x==null&&b!=null&&(x=b),4&g.__u?(p=Vt(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 Ei(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]=Re(null,o,null,null,null):Be(o)?o=t.__k[s]=Re(I,{children:o},null,null,null):o.constructor===void 0&&o.__b>0?o=t.__k[s]=Re(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=Fi(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=ce(l)),Jt(l,l));return i}function Vt(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=Vt(i[a],e,n));return e}t.__e!=e&&(e&&t.type&&!e.parentNode&&(e=ce(t)),e=n.insertBefore(t.__e,e||null));do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function Fi(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 $t(t,e,n){e[0]=="-"?t.setProperty(e,n??""):t[e]=n==null?"":typeof n!="number"||Ti.test(e)?n:n+"px"}function De(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||$t(t.style,e,"");if(n)for(e in n)i&&n[e]==i[e]||$t(t.style,e,n[e])}else if(e[0]=="o"&&e[1]=="n")s=e!=(e=e.replace(Yt,"$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[ve]=i[ve]:(n[ve]=mt,t.addEventListener(e,s?gt:ft,s)):t.removeEventListener(e,s?gt:ft,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 Nt(t){return function(e){if(this.l){var n=this.l[e.type+t];if(e[ze]==null)e[ze]=mt++;else if(e[ze]<n[ve])return;return n(F.event?F.event(e):e)}}}function xt(t,e,n,i,a,s,o,l,p,d){var f,_,c,g,b,x,m,k,w,N,U,O,B,H,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=F.__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 Pe(w,O),c.constructor=v,c.render=Li),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)}),Oe.push.apply(c.__h,c._sb),c._sb=[],c.__h.length&&o.push(c),l=ce(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,B=F.__r,H=0,N)c.state=c.__s,c.__d=!1,B&&B(e),f=c.render(c.props,c.state,c.context),Oe.push.apply(c.__h,c._sb),c._sb=[];else do c.__d=!1,B&&B(e),f=c.render(c.props,c.state,c.context),c.state=c.__s;while(c.__d&&++H<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===I&&f.key==null?Zt(f.props.children):f,l=jt(t,Be(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--;)_t(s[Z])}else e.__e=n.__e;e.__k==null&&(e.__k=n.__k||[]),$.then||Kt(e),F.__e($,e,n)}}else s==null&&e.__v==n.__v?(e.__k=n.__k,e.__e=n.__e):l=e.__e=Ii(n.__e,e,n,i,a,s,o,p,d);return(f=F.diffed)&&f(e),128&e.__u?void 0:l}function Kt(t){t&&(t.__c&&(t.__c.__e=!0),t.__k&&t.__k.some(Kt))}function Xt(t,e,n){for(var i=0;i<n.length;i++)bt(n[i],n[++i],n[++i]);F.__c&&F.__c(e,t),t.some(function(a){try{t=a.__h,a.__h=[],t.some(function(s){s.call(a)})}catch(s){F.__e(s,a.__v)}})}function Zt(t){return typeof t!="object"||t==null||t.__b>0?t:Be(t)?t.map(Zt):t.constructor!==void 0?null:ae({},t)}function Ii(t,e,n,i,a,s,o,l,p){var d,f,_,c,g,b,x,m=n.props||Ue,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&&(F.__m&&F.__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&&Ne.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||De(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||De(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=""),jt(e.type=="template"?t.content:t,Be(c)?c:[c],e,n,i,w=="foreignObject"?"http://www.w3.org/1999/xhtml":a,s,o,s?s[0]:n.__k&&ce(n,0),l,p),s!=null)for(d=s.length;d--;)_t(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])&&De(t,d,b,m[d],a),d="checked",x!=null&&x!=t[d]&&De(t,d,x,m[d],a))}return t}function bt(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){F.__e(a,n)}}function Jt(t,e,n){var i,a;if(F.unmount&&F.unmount(t),(i=t.ref)&&(i.current&&i.current!=t.__e||bt(i,null,e)),(i=t.__c)!=null){if(i.componentWillUnmount)try{i.componentWillUnmount()}catch(s){F.__e(s,e)}i.base=i.__P=i.__n=null}if(i=t.__k)for(a=0;a<i.length;a++)i[a]&&Jt(i[a],e,n||typeof t.type!="function");n||_t(t.__e),t.__c=t.__=t.__e=void 0}function Li(t,e,n){return this.constructor(t,n)}function vt(t,e,n){var i,a,s,o;e==document&&(e=document.documentElement),F.__&&F.__(t,e),a=(i=typeof n=="function")?null:n&&n.__k||e.__k,s=[],o=[],xt(e,t=(!i&&n||e).__k=Ai(I,null,[t]),a||Ue,Ue,e.namespaceURI,!i&&n?[n]:a?null:e.firstChild?Ne.call(e.childNodes):null,s,!i&&n?n:a?a.__e:e.firstChild,i,o),Xt(s,t,o),t.props.children=null}Ne=Oe.slice,F={__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}},Bt=0,Ci=function(t){return t!=null&&t.constructor===void 0},Pe.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),Ot(this))},Pe.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),Ot(this))},Pe.prototype.render=I,oe=[],Ht=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Wt=function(t,e){return t.__v.__b-e.__v.__b},$e.__r=0,ht=Math.random().toString(8),ze="__d"+ht,ve="__a"+ht,Yt=/(PointerCapture)$|Capture$/i,mt=0,ft=Nt(!1),gt=Nt(!0),Si=0;var he,D,yt,Gt,ye=0,on=[],R=F,Qt=R.__b,en=R.__r,tn=R.diffed,nn=R.__c,an=R.unmount,rn=R.__;function We(t,e){R.__h&&R.__h(D,t,ye||e),ye=0;var n=D.__H||(D.__H={__:[],__h:[]});return t>=n.__.length&&n.__.push({}),n.__[t]}function C(t){return ye=1,Di(cn,t)}function Di(t,e,n){var i=We(he++,2);if(i.t=t,!i.__c&&(i.__=[n?n(e):cn(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=D,!D.__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||_};D.__f=!0;var s=D.shouldComponentUpdate,o=D.componentWillUpdate;D.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)},D.shouldComponentUpdate=a}return i.__N||i.__}function L(t,e){var n=We(he++,3);!R.__s&&wt(n.__H,e)&&(n.__=t,n.u=e,D.__H.__h.push(n))}function Ye(t,e){var n=We(he++,4);!R.__s&&wt(n.__H,e)&&(n.__=t,n.u=e,D.__h.push(n))}function V(t){return ye=5,ln(function(){return{current:t}},[])}function ln(t,e){var n=We(he++,7);return wt(n.__H,e)&&(n.__=t(),n.__H=e,n.__h=t),n.__}function ke(t,e){return ye=8,ln(function(){return t},e)}function zi(){for(var t;t=on.shift();){var e=t.__H;if(t.__P&&e)try{e.__h.some(He),e.__h.some(kt),e.__h=[]}catch(n){e.__h=[],R.__e(n,t.__v)}}}R.__b=function(t){D=null,Qt&&Qt(t)},R.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),rn&&rn(t,e)},R.__r=function(t){en&&en(t),he=0;var e=(D=t.__c).__H;e&&(yt===D?(e.__h=[],D.__h=[],e.__.some(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(e.__h.some(He),e.__h.some(kt),e.__h=[],he=0)),yt=D},R.diffed=function(t){tn&&tn(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(on.push(e)!==1&&Gt===R.requestAnimationFrame||((Gt=R.requestAnimationFrame)||Ri)(zi)),e.__H.__.some(function(n){n.u&&(n.__H=n.u,n.u=void 0)})),yt=D=null},R.__c=function(t,e){e.some(function(n){try{n.__h.some(He),n.__h=n.__h.filter(function(i){return!i.__||kt(i)})}catch(i){e.some(function(a){a.__h&&(a.__h=[])}),e=[],R.__e(i,n.__v)}}),nn&&nn(t,e)},R.unmount=function(t){an&&an(t);var e,n=t.__c;n&&n.__H&&(n.__H.__.some(function(i){try{He(i)}catch(a){e=a}}),n.__H=void 0,e&&R.__e(e,n.__v))};var sn=typeof requestAnimationFrame=="function";function Ri(t){var e,n=function(){clearTimeout(i),sn&&cancelAnimationFrame(e),setTimeout(t)},i=setTimeout(n,35);sn&&(e=requestAnimationFrame(n))}function He(t){var e=D,n=t.__c;typeof n=="function"&&(t.__c=void 0,n()),D=e}function kt(t){var e=D;t.__c=t.__(),D=e}function wt(t,e){return!t||t.length!==e.length||e.some(function(n,i){return n!==t[i]})}function cn(t,e){return typeof e=="function"?e(t):e}var Se={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"},we=(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},Ce=t=>{if(typeof t=="boolean")return t;if(t==="true"||t===""||t==="1")return!0;if(t==="false"||t==="0")return!1},Ct=(t,e=200)=>typeof t=="string"?t.slice(0,e):void 0;function Pi(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 Ui(t){if(typeof t!="string")return;let e=t.trim();return/^[\w\s,"'-]{1,120}$/.test(e)?e:void 0}function Te(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=Pi(e.accent)??n.accent,n.radius=we(e.radius,0,40)??n.radius,n.font=Ui(e.font)??n.font,e.subtitle===null?n.subtitle=null:n.subtitle=Ct(e.subtitle,80)??n.subtitle,n.greeting=Ct(e.greeting,160)??n.greeting,n.greetingDelay=we(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=Ct(e.placeholder,60)??n.placeholder,n.showChat=Ce(e.showChat)??n.showChat,n.showCall=Ce(e.showCall)??n.showCall,n.branding=Ce(e.branding)??n.branding,n.offsetX=we(e.offsetX,0,200)??n.offsetX,n.offsetY=we(e.offsetY,0,200)??n.offsetY,n.zIndex=we(e.zIndex,0,2147483647)??n.zIndex,n.open=Ce(e.open)??n.open,n.face=Ce(e.face)??n.face,typeof e.faceUrl=="string"&&/^https?:\/\/[^\s"'<>]+$/.test(e.faceUrl.trim())&&(n.faceUrl=e.faceUrl.trim()),n}function dn(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}function un(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 qe(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 pn(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 hn(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=>pn(a.replace(/^\s*[-*•]\s+/,"")))}):e.push({t:"p",parts:pn(n)})}return e}var Oi={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."},fn={},gn=!0;function mn(t){fn=t??{},gn=!t||!Object.keys(t).length}function h(t,e){let n=fn[t]??Oi[t];if(e)for(let i in e)n=n.split(`{${i}}`).join(String(e[i]));return n}function le(t){return gn?un(t):String(t)}function je(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 _n(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 xn={cx:.5,cy:.12,span:.06};function vn(t,e,n){let i=t?.face?.eyes,a=t?.face?.chin;if(!i||!a||!e||!n)return xn;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}:xn}var Ve={faceFraction:.26,at:{x:.5,y:.5}},yn={faceFraction:.14,at:{x:.5,y:.34},keepCrown:!0},kn={faceFraction:.16,at:{x:.5,y:.22},keepCrown:!0},wn={fit:"height"},$i=1.8,bn=.04;function Cn(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*$i)*s;return a.keepCrown&&p<i*bn&&(l+=i*bn-p),{width:o,height:s,left:n*a.at.x-t.cx*o,top:l}}var Sn=/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/,Ni=/\+?\d[\d\s().-]{5,}\d/g,Bi=/\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,Hi=new Set(["interested","looking","from","with","here","trying","not","a","an","the","just","also","happy","keen","curious","calling","sure","fine","good","okay","ok"]);function Tn(t){let e={},n=t.match(Sn)?.[0];n&&(e.email=n.replace(/[.,;:]+$/,""));for(let a of t.replace(Sn," ").matchAll(Ni)){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(Bi)?.[1];if(i){let a=i.split(/\s+/).filter(o=>!Hi.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 Wi=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:--Wi,__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 F.vnode&&F.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}),Ae=({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"})),fe=({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"})),An=({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"})),Mn=({size:t=20})=>ee(t,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"})]})),En=({size:t=20})=>ee(t,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"})]})),Ke=({size:t=18})=>ee(t,r("path",{d:"M6 6l12 12M18 6L6 18"})),Fn=({size:t=18})=>ee(t,r("path",{d:"M12 19V5M5.5 11.5L12 5l6.5 6.5"})),In=({size:t=18})=>ee(t,r("path",{d:"M15 5l-7 7 7 7"}));var Ln=({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"})),zn=({size:t=14})=>ee(t,r("path",{d:"M4 12a8 8 0 1 0 2.3-5.6M4 4v4h4"}));var St={current:null};function Yi(t){return t?t.speaking?"speaking":t.agentState==="thinking"?"reasoning":t.agentState==="listening"||t.phase==="live"?"listening":"idle":"idle"}function Rn({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 _=Yi(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 ji=()=>typeof matchMedia<"u"&&matchMedia("(prefers-reduced-motion: reduce)").matches;function Me({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,P,ie)=>!a&&S&&!g[ie]?S:P,k=x?.anchor?.alphaUrl??x?.anchor?.url??null,w=m(x?.anchor?.smallUrl,k,"anchor"),N=w!==k,U=!i&&!ji()&&qi(),O=x?.clips.idle,B=x?.clips.talking??O,H=m(O?.smallUrl,O?.alphaUrl??null,"idle"),W=m(B?.smallUrl,B?.alphaUrl??null,"talk")??H,[Z,v]=C(a);if(L(()=>{n&&v(!0)},[n]),Ye(()=>{let S=o.current;if(!S)return;let P=()=>p({w:S.clientWidth,h:S.clientHeight});if(P(),typeof ResizeObserver>"u")return;let ie=new ResizeObserver(P);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),re=vn(x,J?.w??0,J?.h??0),Y=l.w&&l.h&&J?Cn(re,J.w/J.h,l.w,l.h,e):null,se=Y?{width:`${Y.width}px`,height:`${Y.height}px`,left:`${Y.left}px`,top:`${Y.top}px`}:{},K=!!Y&&U&&!!H&&!!_.idle,ne=!!Y&&U&&!!W&&W!==H&&!!_.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:{...se,opacity:Y&&d&&!K?1:0},onLoad:S=>{let P=S.currentTarget;f({w:P.naturalWidth,h:P.naturalHeight})},onError:()=>N&&b(S=>({...S,anchor:!0}))}),U&&H?r(Pn,{src:H,style:se,visible:K&&!ne,onReady:()=>c(S=>({...S,idle:!0})),onFail:()=>b(S=>({...S,idle:!0}))}):null,U&&Z&&W&&W!==H?r(Pn,{src:W,style:se,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 Pn({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",Un="cxyz:introduced";function Ee(t,e){try{return e!==void 0&&localStorage.setItem(t,e),localStorage.getItem(t)}catch{return null}}function Vi(){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 Ki(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 Xi(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 Zi(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 Ji(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 On({parts:t}){return r(I,{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(I,{children:[i,a<s.length-1?r("br",{}):null]},`${n}.${a}`)))})}var Gi={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 Qi(){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 ea({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?Qi():"",x=t.reasonDefault||b||"",[m,k]=C(x),[w,N]=C(t.reasonDefault?t.reasonSource??"conversation":b?"cta":""),[U,O]=C(g&&!x),[B,H]=C(!1),[W,Z]=C(""),[v,$]=C({}),[J,re]=C(null),[Y,se]=C(!1),K=V(null),ne=V(null);return L(()=>{setTimeout(()=>K.current?.focus({preventScroll:!0}),80)},[]),Ye(()=>{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,B]),r("form",{class:"card",part:"details",ref:ne,onSubmit:async M=>{M.preventDefault(),se(!0),$({}),re(null);try{let S=(B?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 P=S.fields??{};Object.keys(P).length?$(P):re(S.message||h("sendFailed"))}finally{se(!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(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:()=>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":!B&&m===G,onClick:()=>{k(G),H(!1),N("user"),O(!1)},children:G},G)),r("button",{type:"button",class:"card__chip","aria-pressed":B,onClick:()=>{H(!0),k("")},children:h("reasonOther")})]}):null,B||!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 P=Gi[M],ie=h(P.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:P.type,autocomplete:P.auto,required:_(M),maxLength:M==="email"?254:120,value:p[M]??"","aria-invalid":v[M]?"true":void 0,onInput:G=>d(Ge=>({...Ge,[M]:G.currentTarget.value}))}),v[M]?r("em",{children:v[M]}):null]},M)}),r("div",{class:"card__consent",children:[t.consent,t.privacyUrl?r(I,{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 $n({text:t}){return r(I,{children:hn(t).map((e,n)=>e.t==="ul"?r("ul",{children:e.items.map((i,a)=>r("li",{children:r(On,{parts:i})},a))},n):r("p",{children:r(On,{parts:e.parts})},n))})}function Nn({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}=Ki(t),{call:m,state:k,captions:w,reset:N}=Xi(t),[U,O]=C(""),B=V(null),H=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&&(mn(T?.strings),J(T))}),()=>{u=!1}},[t,o]);let re=e.greeting||$?.teaser||"",Y=e.suggestions.length?e.suggestions:$?.suggestions??[],se=$?.greeting||h("greetingDefault",{name:v}),[K,ne]=C("loading"),[M,S]=C(!1),[P,ie]=C(null),[G,Ge]=C(""),[Qe,et]=C(null),[tt,nt]=C(null),te=ke(u=>{d(u),i(u)},[i]),de=ke(()=>{_(!0),setTimeout(()=>{_(!1),te("closed")},200)},[te]),ge=ke(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=ke((u=o?"chat":"call")=>{g(!1),Ee(Tt,"1"),te(u),u==="chat"&&ge()},[o,te,ge]);L(()=>n({open:Q,close:de}),[n,Q,de]),L(()=>t.on("siteEvent",u=>{u.openChat&&Q("chat")}),[t,Q]),L(()=>{e.open&&o&&ge()},[ge,e.open,o]),L(()=>{if(!re||Ee(Tt))return;let u=setTimeout(()=>g(!0),e.greetingDelay*1e3);return()=>clearTimeout(u)},[re,e.greetingDelay]),L(()=>{if(p!=="chat"||M||K==="loading")return;let u=setTimeout(()=>S(!0),700);return()=>clearTimeout(u)},[p,M,K]);let[it,Yn]=C(()=>!Ee(Un));L(()=>{if(!it)return;let u=setTimeout(()=>{Yn(!1),Ee(Un,"1")},5e3);return()=>clearTimeout(u)},[it]),L(()=>{if(p==="closed")return;let u=T=>{T.key==="Escape"&&de()};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[p,de]),L(()=>{let u=B.current;u&&(u.scrollTop=u.scrollHeight)},[b,p,k?.phase]),L(()=>{p==="chat"&&setTimeout(()=>H.current?.focus({preventScroll:!0}),60)},[p]);let me=e.face&&!!a.video,[Fe,qn]=C("loading"),A=k?.phase??"idle";L(()=>{if(!(A!=="ready"||!m)){if(Vi(),p==="call"){if(!me||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,me,Fe]);let Mt=A==="live"||A==="connecting";Ji(m,W,Mt&&p==="call");let Ie=Zi(k?.startedAt??null,A==="live"),at=ta(m,k?.position??1),rt=()=>{let u=$?.details;if(u&&!P&&o){et(u),te("chat"),ge();return}st()},Et=(u,T="")=>{ie(u),Ge(T),nt(null);let pe=!!Qe;et(null),pe&&st()},jn=async u=>{await t.sendDetails(u),Et("sent",u.name.trim().split(/\s+/)[0]??"")},Vn=()=>{t.declineDetails().catch(()=>{}),Et("skipped")},Kn=async()=>{try{await t.chat.reset()}catch{return}ne("empty"),S(!1),ie(null),et(null),nt(null),O(""),J(await t.opening(!0))},st=async()=>{te("call");try{await t.startCall({autoAccept:!1,...me?{face:{emotion:()=>St.current}}:{}})}catch{}},ot=[...b].reverse().find(u=>u.detailsForm||u.askDetails)?.detailsForm??[...b].reverse().find(u=>u.askDetails)?.askDetails??$?.details??null,_e=async u=>{let T=u.trim();if(!T||x)return;let pe=ot&&P!=="sent"?Tn(T):null;pe&&ot&&nt({form:ot,values:pe}),O(""),H.current&&(H.current.style.height="");try{await t.chat.send(T)}catch{}},Le=b[b.length-1],Ft=Le?.role==="agent"&&!Le.streaming?Le.askDetails:void 0,q=Qe?{form:Qe,kind:"call"}:tt&&P!=="sent"&&!x?{form:tt.form,kind:"typed",initial:tt.values}:Ft&&!P?{form:Ft,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:[re,r("button",{class:"greeting__close","aria-label":h("dismiss"),onClick:T=>{T.stopPropagation(),g(!1),Ee(Tt,"1")},children:r(Ke,{size:14})})]}):null,r("button",{class:`presence presence--${e.display} ${u?"presence--live":""}`,part:"presence","aria-label":u?A==="queued"?h("inLineToCall",{position:le(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(Me,{agent:a,shot:e.display==="full"?wn:e.display==="half"?kn:Ve})}),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:le(k?.position??1)}):h("backToCall"):o?h("chatWith",{name:v}):h("callName",{name:v})}):null]}),e.launcher==="bubble"?null:r("div",{class:`acts ${it?"acts--labelled":""}`,part:"actions",children:[o?r("button",{class:"act","aria-label":h("chatWith",{name:v}),onClick:()=>Q("chat"),children:[r(Ae,{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:le(k?.position??1)}):h("backToCall"):h("callName",{name:v}),onClick:()=>u?Q("call"):rt(),children:[r(fe,{size:20}),r("span",{class:"act__label","aria-hidden":"true",children:u?A==="queued"?h("inLine",{position:le(k?.position??1)}):h("onCall"):h("call")}),A==="queued"?r("span",{class:"act__badge","aria-hidden":"true",children:k?.position??1}):null]}):null]})]})}let Xn=r("div",{class:"head",part:"header",children:[r("div",{class:"head__face",children:r(Me,{agent:a,shot:Ve})}),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:()=>{Kn()},children:r(Ln,{})}):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"):rt(),children:r(fe,{size:18})}):null,r("button",{class:"icon-btn","aria-label":h("close"),onClick:de,children:r(Ke,{})})]});if(p==="chat")return r("div",{class:`panel ${f?"is-closing":""}`,part:"panel",role:"dialog","aria-label":h("chatWith",{name:v}),children:[Xn,m&&(A==="queued"||A==="ready")?r("div",{class:"banner",part:"banner",role:"status",children:[r("div",{class:"banner__text",children:A==="queued"?r(I,{children:h("inLineFor",{position:le(k?.position??1),eta:je(k?.etaSeconds??null)})}):r(I,{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:B,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(Me,{agent:a,shot:Ve})}),r("div",{class:"empty__title",children:v}),Z?r("div",{class:"empty__body",children:Z}):null]}),K==="loading"?null:M?r(I,{children:[r("div",{class:"msg msg--agent",part:"message message-agent",children:r($n,{text:se})}),q?null:r(At,{items:Y,onPick:u=>{_e(u)},children:l?r("button",{class:"chip chip--call",onClick:()=>m&&A!=="ended"?te("call"):rt(),children:[r(fe,{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(I,{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($n,{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=>{_e(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(zn,{})," ",h("notSent")]}):null]},u.id)),typeof K=="number"&&b.length===K&&$?.welcomeBack?r(I,{children:[r("div",{class:"msg msg--agent",part:"message message-agent",children:$.welcomeBack}),q?null:r(At,{items:Y,onPick:u=>{_e(u)}})]}):null,q?r(ea,{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:jn,onSkip:Vn,skipLabel:q.kind==="call"?h("skipAndCall"):h("notNow"),hasHistory:b.length>0},q.kind==="invited"?Le?.id:q.kind):P==="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(),_e(U)},children:r("div",{class:"compose__box",children:[r("textarea",{ref:H,rows:1,value:U,maxLength:2e3,placeholder:e.placeholder===Se.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(),_e(U))}}),r("button",{class:"send",type:"submit","aria-label":h("send"),disabled:!U.trim()||x,children:r(Fn,{})})]})}),e.branding?r("div",{class:"foot",children:h("poweredBy").split("{brand}").map((u,T)=>r(I,{children:[T?r("a",{href:"https://character.xyz",target:"_blank",rel:"noopener noreferrer",children:"Character XYZ"}):null,u]},T))}):null]});let E=k,lt=E?.position??1,Zn=at>1?(at-lt)/(at-1):0,ct=74,It=2*Math.PI*ct,xe=E?.maxSeconds?E.maxSeconds-Ie:null,Jn=E?.agentState??"idle",Gn=E?.speaking?h("speaking"):Jn==="thinking"?h("thinking"):h("listening"),Qn=!E||A==="ended"||A==="idle",dt=_n(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 ${me&&Fe==="ready"?"stage--face":""}`,ref:W,children:[r("div",{class:"stage__figure",style:{opacity:A==="queued"?.35:1,transition:"opacity .6s"},children:[r(Me,{agent:a,shot:yn,talking:!!E?.speaking,full:!0}),me?r("div",{class:`stage__face ${Fe==="ready"?"is-ready":""}`,children:r(Rn,{client:t,call:m,state:E,src:e.faceUrl,onStatus:qn})}):null]}),Mt?r("div",{class:"voice"}):null,r("div",{class:"stage__veil"}),r("div",{class:"stage__top",children:[A==="live"?r("span",{class:`badge ${xe!=null&&xe<=60?"badge--warn":""}`,role:"timer","aria-label":h("callTime"),children:[r("i",{}),xe!=null&&xe<=60?h("timeLeft",{time:qe(xe)}):qe(Ie)]}):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(Ae,{size:18})}):null,r("button",{class:"icon-btn","aria-label":h("minimise"),onClick:de,children:r(Ke,{})})]})]}),r("div",{class:"stage__bottom","aria-live":"polite",children:[A==="joining"||A==="connecting"?r(I,{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(I,{children:[r("div",{class:"line",role:"status","aria-label":h("inLineEta",{position:le(lt),eta:je(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:ct,fill:"none","stroke-width":"7"}),r("circle",{class:"line__fill",cx:"84",cy:"84",r:ct,fill:"none","stroke-width":"7","stroke-linecap":"round","stroke-dasharray":It,"stroke-dashoffset":It*(1-Math.max(.06,Zn))})]}),r("div",{children:[r("div",{class:"line__num",children:le(lt)}),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:je(E?.etaSeconds??null)})}),r("div",{class:"btn-row",children:[o?r("button",{class:"btn btn--accent",onClick:()=>Q("chat"),children:[r(Ae,{size:18})," ",h("keepChatting")]}):null,r("button",{class:"btn",onClick:()=>{m?.hangUp()},children:h("leaveLine")})]})]}):null,A==="ready"?r(I,{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(fe,{size:18})," ",h("joinCall")]})]}):null,A==="live"?r(I,{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"):Gn]}),r("div",{class:"captions",children:w.slice(-2).map((u,T,pe)=>r("div",{class:`captions__line ${T===pe.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(En,{size:22}):r(Mn,{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(An,{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(In,{size:22})}),r("span",{class:"round__label",children:h("interrupt")})]}):null]})]}):null,Qn?r(I,{children:[r("div",{class:"title",children:E?dt.title:h("callName",{name:v})}),r("div",{class:"note",children:E?E.endReason==="hangup"&&Ie?`${qe(Ie)} \xB7 ${dt.body}`:E.error??dt.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(),st()},children:[r(fe,{size:18})," ",E?h("callAgain"):h("startCall")]}):null,o?r("button",{class:"btn",onClick:()=>Q("chat"),children:[r(Ae,{size:18})," ",h("chat")]}):null]})]}):null]})]})})}function ta(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 Bn=`
43
43
  :host {
44
44
  --cx-accent: #7c5cff;
45
45
  --cx-accent-ink: #fff;
@@ -401,5 +401,5 @@ button:focus-visible, textarea:focus-visible, a:focus-visible { outline: 2px sol
401
401
  *, *::before, *::after { animation-duration: .01ms !important; animation-iteration-count: 1 !important; transition-duration: .01ms !important; }
402
402
  .presence__ring { animation: none; }
403
403
  }
404
- `;var Ke="character-xyz";function Hn(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 na(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 Bn(t){for(let e of[document.body,document.documentElement]){if(!e)continue;let n=na(getComputedStyle(e).backgroundColor);if(n!==null)return n<.22}return!!t?.matches}var ia=["publishable-key","agent","api-url","position","mode","accent","greeting","open"],Xe=class extends HTMLElement{constructor(){super(...arguments);V(this,"options",null);V(this,"client",null);V(this,"api",null);V(this,"pendingOpen",null);V(this,"booted",!1);V(this,"mq",null);V(this,"stage",null);V(this,"waiters",[]);V(this,"queuedActions",new Map);V(this,"bootFailed",!1);V(this,"onSchemeChange",()=>requestAnimationFrame(this.onScheme));V(this,"onScheme",()=>{this.dataset.mode==="auto"&&(this.dataset.theme=Bn(this.mq)?"dark":"light")})}static get observedAttributes(){return ia}connectedCallback(){if(this.booted)return;this.booted=!0;let n=this.shadowRoot??this.attachShadow({mode:"open"}),i=document.createElement("style");i.textContent=Nn,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&&xt(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=cn(Array.from(this.attributes)),a=n.publishableKey??i.publishableKey;try{this.client=await dt.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=Se(Ce,s.appearance);if(o=Se(o,i),o=Se(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="",xt(r($n,{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=Bn(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",Hn(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 Ze(){typeof customElements<"u"&&!customElements.get(Ke)&&customElements.define(Ke,Xe)}function aa(t){Ze();let e=document.createElement(Ke);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()}}Ze();export{dt as CharacterXYZ,Xe as CharacterXYZElement,P as CxError,Ce as DEFAULTS,Ke as TAG,Se as applyLayer,Ze as define,Hn as inkFor,aa as mount};
404
+ `;var Xe="character-xyz";function Wn(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 na(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 Hn(t){for(let e of[document.body,document.documentElement]){if(!e)continue;let n=na(getComputedStyle(e).backgroundColor);if(n!==null)return n<.22}return!!t?.matches}var ia=["publishable-key","agent","api-url","position","mode","accent","greeting","open"],Ze=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=Hn(this.mq)?"dark":"light")})}static get observedAttributes(){return ia}connectedCallback(){if(this.booted)return;this.booted=!0;let n=this.shadowRoot??this.attachShadow({mode:"open"}),i=document.createElement("style");i.textContent=Bn,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&&vt(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 z("unknown","The widget could not start.")):new Promise((n,i)=>{this.waiters.push(a=>a?n(a):i(new z("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=dn(Array.from(this.attributes)),a=n.publishableKey??i.publishableKey;try{this.client=await ut.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 z?l:new z("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=Te(Se,s.appearance);if(o=Te(o,i),o=Te(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="",vt(r(Nn,{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=Hn(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",Wn(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 Je(){typeof customElements<"u"&&!customElements.get(Xe)&&customElements.define(Xe,Ze)}function aa(t){Je();let e=document.createElement(Xe);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()}}Je();export{ut as CharacterXYZ,Ze as CharacterXYZElement,z as CxError,Se as DEFAULTS,Xe as TAG,Te as applyLayer,Je as define,Wn as inkFor,aa as mount};
405
405
  //# sourceMappingURL=index.js.map