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