@webority/chat-core 0.161.0 → 0.162.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- import{emptyFeatures as e}from"./profile.js";var t=()=>()=>void 0,n=Object.freeze({profile:null,profileError:null,features:Object.freeze(e()),conversationId:null,conversationState:`Open`,title:null,continuesConversationId:null,messages:[],thinking:!1,steps:[],streaming:!1,loading:!1,loadError:null,turnError:null,stopped:!1,messagesLeftToday:null,editing:null,attachments:[],lastConversation:null,open:!1,muted:!1,greeting:null,starters:[],pending:null,agent:null,agentTyping:null,live:`Off`,handoffPending:!1,handoffPause:!1,handoffContactRequestId:null,openTickets:[],draft:null}),r=()=>void 0,i=()=>Promise.resolve(),a=()=>/* @__PURE__ */ Error(`The chat session has not started.`),o=()=>Promise.reject(a()),s={client:Object.freeze({getProfile:o,send:o,answerInput:o,confirmAction:o,rejectAction:o,listConversations:o,getConversation:o,renameConversation:o,deleteConversation:o,rateMessage:o,uploadAttachment:o,deleteAttachment:o,getAttachment:o,sendOtp:o,requestHandoff:o,watchConversation:o,sendTyping:o,listOpenTickets:o,getSpeechToken:o}),getState:()=>n,subscribe:t,load:i,submit:i,chooseQuickReply:i,answerInput:o,sendOtp:i,confirmAction:i,rejectAction:i,stop:r,retry:i,regenerate:i,startEdit:r,cancelEdit:r,attach:i,removeAttachment:i,openConversation:i,resumeLast:i,newConversation:r,rate:i,open:r,close:r,setMuted:r,skipField:i,cancelLead:i,editLeadField:i,requestHandoff:i,notifyTyping:r,setLiveActive:r,resumeLive:r,beginHandoff:r,endHandoffPause:r,consumeDraft:r,loadAttachmentUrl:o,reset:r,dispose:r};export{s as IDLE_CHAT_SESSION,n as IDLE_CHAT_STATE};
1
+ import{emptyFeatures as e}from"./profile.js";var t=()=>()=>void 0,n=Object.freeze({profile:null,profileError:null,features:Object.freeze(e()),conversationId:null,conversationState:`Open`,title:null,continuesConversationId:null,messages:[],thinking:!1,steps:[],streaming:!1,loading:!1,loadError:null,turnError:null,stopped:!1,messagesLeftToday:null,editing:null,attachments:[],lastConversation:null,recentConversations:[],open:!1,muted:!1,greeting:null,starters:[],pending:null,agent:null,agentTyping:null,live:`Off`,handoffPending:!1,handoffPause:!1,handoffContactRequestId:null,openTickets:[],draft:null}),r=()=>void 0,i=()=>Promise.resolve(),a=()=>/* @__PURE__ */ Error(`The chat session has not started.`),o=()=>Promise.reject(a()),s={client:Object.freeze({getProfile:o,send:o,answerInput:o,confirmAction:o,rejectAction:o,listConversations:o,getConversation:o,renameConversation:o,deleteConversation:o,rateMessage:o,uploadAttachment:o,deleteAttachment:o,getAttachment:o,sendOtp:o,requestHandoff:o,watchConversation:o,sendTyping:o,listOpenTickets:o,getSpeechToken:o}),getState:()=>n,subscribe:t,load:i,submit:i,chooseQuickReply:i,answerInput:o,sendOtp:i,confirmAction:i,rejectAction:i,stop:r,retry:i,regenerate:i,startEdit:r,cancelEdit:r,attach:i,removeAttachment:i,openConversation:i,resumeLast:i,newConversation:r,rate:i,open:r,close:r,setMuted:r,skipField:i,cancelLead:i,editLeadField:i,requestHandoff:i,notifyTyping:r,setLiveActive:r,resumeLive:r,beginHandoff:r,endHandoffPause:r,consumeDraft:r,loadAttachmentUrl:o,reset:r,dispose:r};export{s as IDLE_CHAT_SESSION,n as IDLE_CHAT_STATE};
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{sniffAudioType as e}from"./audioType.js";import{ChatApiError as t,createChatClient as n,newIdempotencyKey as r}from"./client.js";import{ChatDecodeError as i}from"./decode/primitives.js";import{decodeChatPart as a}from"./decode/parts.js";import{decodeChatConversationView as o,decodeChatMessageView as s}from"./decode/messages.js";import{CHAT_CONTRACT_VERSION as c,CHAT_HANDOFF_REQUEST_ID as l}from"./contract.js";import{createConversationList as u}from"./conversationList.js";import{decodeChatProfileView as d}from"./decode/profile.js";import{DICTATION_NO_SPEECH_MS as f,DICTATION_SILENCE_MS as p,createDictation as m}from"./dictation.js";import{decodeChatStreamEvent as h}from"./decode/events.js";import{createExplain as g}from"./explain.js";import{formatFigure as _,toFigureRuns as v,toFigureText as y}from"./figures.js";import{createFixtureClient as b}from"./fixtureClient.js";import{decodeChatFixture as x}from"./decode/fixture.js";import{formatChatDate as S,formatChatDateTime as C,formatChatDay as w,formatChatValue as T,formatFileSize as E,messagePlainText as D}from"./format.js";import{isHandoffTarget as O}from"./handoff.js";import{IDLE_CHAT_SESSION as k,IDLE_CHAT_STATE as A}from"./idleSession.js";import{DEFAULT_CHAT_LABELS as j,mergeLabels as M}from"./labels.js";import{isSafeActionHref as N,isSafeLinkUrl as P}from"./links.js";import{defaultChatLook as F,mergeLook as I}from"./look.js";import{pacingDelayMs as L}from"./pacing.js";import{CHAT_FEATURES as R,LOADER_STYLES as z,emptyFeatures as B,featureRecord as V,loaderView as H,resolveFeatures as U,resolveNudge as W,resolveStart as G,showsCaptchaNote as K}from"./profile.js";import{provideRuntimeCrypto as q}from"./runtime.js";import{createChatSession as J,createTurnApi as Y,handoffSettledIds as X}from"./session.js";import{CHAT_SPEECH_TOKEN_MARGIN_MS as Z,ChatSpeechError as Q,createSpeechTokenSource as $}from"./speech.js";import{humanizeService as ee,selectStarters as te}from"./starters.js";import{createSseParser as ne,createStreamReader as re}from"./stream.js";import{buildTranscript as ie,transcriptToText as ae}from"./transcript.js";import{formatClipTime as oe,voiceClipBars as se}from"./voiceClip.js";export{c as CHAT_CONTRACT_VERSION,R as CHAT_FEATURES,l as CHAT_HANDOFF_REQUEST_ID,Z as CHAT_SPEECH_TOKEN_MARGIN_MS,t as ChatApiError,i as ChatDecodeError,Q as ChatSpeechError,j as DEFAULT_CHAT_LABELS,f as DICTATION_NO_SPEECH_MS,p as DICTATION_SILENCE_MS,k as IDLE_CHAT_SESSION,A as IDLE_CHAT_STATE,z as LOADER_STYLES,ie as buildTranscript,n as createChatClient,J as createChatSession,u as createConversationList,m as createDictation,g as createExplain,b as createFixtureClient,$ as createSpeechTokenSource,ne as createSseParser,re as createStreamReader,Y as createTurnApi,o as decodeChatConversationView,x as decodeChatFixture,s as decodeChatMessageView,a as decodeChatPart,d as decodeChatProfileView,h as decodeChatStreamEvent,F as defaultChatLook,B as emptyFeatures,V as featureRecord,S as formatChatDate,C as formatChatDateTime,w as formatChatDay,T as formatChatValue,oe as formatClipTime,_ as formatFigure,E as formatFileSize,X as handoffSettledIds,ee as humanizeService,O as isHandoffTarget,N as isSafeActionHref,P as isSafeLinkUrl,H as loaderView,M as mergeLabels,I as mergeLook,D as messagePlainText,r as newIdempotencyKey,L as pacingDelayMs,q as provideRuntimeCrypto,U as resolveFeatures,W as resolveNudge,G as resolveStart,te as selectStarters,K as showsCaptchaNote,e as sniffAudioType,v as toFigureRuns,y as toFigureText,ae as transcriptToText,se as voiceClipBars};
1
+ import{sniffAudioType as e}from"./audioType.js";import{ChatApiError as t,createChatClient as n,newIdempotencyKey as r}from"./client.js";import{ChatDecodeError as i}from"./decode/primitives.js";import{decodeChatPart as a}from"./decode/parts.js";import{decodeChatConversationView as o,decodeChatMessageView as s}from"./decode/messages.js";import{CHAT_CONTRACT_VERSION as c,CHAT_HANDOFF_REQUEST_ID as l}from"./contract.js";import{createConversationList as u}from"./conversationList.js";import{decodeChatProfileView as d}from"./decode/profile.js";import{DICTATION_NO_SPEECH_MS as f,DICTATION_SILENCE_MS as p,createDictation as m}from"./dictation.js";import{decodeChatStreamEvent as h}from"./decode/events.js";import{createExplain as g}from"./explain.js";import{formatFigure as _,toFigureRuns as v,toFigureText as y}from"./figures.js";import{createFixtureClient as b}from"./fixtureClient.js";import{decodeChatFixture as x}from"./decode/fixture.js";import{formatChatDate as S,formatChatDateTime as C,formatChatDay as w,formatChatValue as T,formatFileSize as E,messagePlainText as D}from"./format.js";import{isHandoffTarget as O}from"./handoff.js";import{IDLE_CHAT_SESSION as k,IDLE_CHAT_STATE as A}from"./idleSession.js";import{DEFAULT_CHAT_LABELS as j,mergeLabels as M}from"./labels.js";import{isSafeActionHref as N,isSafeLinkUrl as P}from"./links.js";import{CHAT_RECENT_ROWS_MAX as F,defaultChatLook as I,mergeLook as L}from"./look.js";import{pacingDelayMs as R}from"./pacing.js";import{CHAT_FEATURES as z,LOADER_STYLES as B,emptyFeatures as V,featureRecord as H,loaderView as U,resolveFeatures as W,resolveNudge as G,resolveStart as K,showsCaptchaNote as q}from"./profile.js";import{provideRuntimeCrypto as J}from"./runtime.js";import{createChatSession as Y,createTurnApi as X,handoffSettledIds as Z}from"./session.js";import{CHAT_SPEECH_TOKEN_MARGIN_MS as Q,ChatSpeechError as $,createSpeechTokenSource as ee}from"./speech.js";import{humanizeService as te,selectStarters as ne}from"./starters.js";import{createSseParser as re,createStreamReader as ie}from"./stream.js";import{buildTranscript as ae,transcriptToText as oe}from"./transcript.js";import{formatClipTime as se,voiceClipBars as ce}from"./voiceClip.js";export{c as CHAT_CONTRACT_VERSION,z as CHAT_FEATURES,l as CHAT_HANDOFF_REQUEST_ID,F as CHAT_RECENT_ROWS_MAX,Q as CHAT_SPEECH_TOKEN_MARGIN_MS,t as ChatApiError,i as ChatDecodeError,$ as ChatSpeechError,j as DEFAULT_CHAT_LABELS,f as DICTATION_NO_SPEECH_MS,p as DICTATION_SILENCE_MS,k as IDLE_CHAT_SESSION,A as IDLE_CHAT_STATE,B as LOADER_STYLES,ae as buildTranscript,n as createChatClient,Y as createChatSession,u as createConversationList,m as createDictation,g as createExplain,b as createFixtureClient,ee as createSpeechTokenSource,re as createSseParser,ie as createStreamReader,X as createTurnApi,o as decodeChatConversationView,x as decodeChatFixture,s as decodeChatMessageView,a as decodeChatPart,d as decodeChatProfileView,h as decodeChatStreamEvent,I as defaultChatLook,V as emptyFeatures,H as featureRecord,S as formatChatDate,C as formatChatDateTime,w as formatChatDay,T as formatChatValue,se as formatClipTime,_ as formatFigure,E as formatFileSize,Z as handoffSettledIds,te as humanizeService,O as isHandoffTarget,N as isSafeActionHref,P as isSafeLinkUrl,U as loaderView,M as mergeLabels,L as mergeLook,D as messagePlainText,r as newIdempotencyKey,R as pacingDelayMs,J as provideRuntimeCrypto,W as resolveFeatures,G as resolveNudge,K as resolveStart,ne as selectStarters,q as showsCaptchaNote,e as sniffAudioType,v as toFigureRuns,y as toFigureText,oe as transcriptToText,ce as voiceClipBars};
package/dist/labels.js CHANGED
@@ -1 +1 @@
1
- var e={Open:`Open`,InProgress:`In progress`,WaitingOnCustomer:`Waiting on you`,Resolved:`Resolved`,Closed:`Closed`,Cancelled:`Cancelled`},t={Positive:`Good`,Caution:`Watch`,Negative:`Poor`,Neutral:``},n=Object.freeze({launcher:`Open chat`,launcherClose:`Close chat`,panelTitle:`Assistant`,headerStatus:`Usually replies instantly`,newChat:`New chat`,close:`Close`,history:`Past chats`,historyEmptyTitle:`No past chats`,historyEmptyText:`Your conversations show here.`,untitled:`Untitled chat`,rename:`Rename chat`,renameSave:`Save`,conversationTitle:`Chat name`,renameFailed:`We could not rename this chat. Please try again.`,deleteChat:`Delete chat`,deleteConfirmTitle:`Delete this chat?`,deleteConfirmMessage:`The conversation is removed for good.`,deleteConfirm:`Delete`,deleteFailed:`We could not delete this chat. Please try again.`,cancel:`Cancel`,loadMore:`Show more`,loadFailed:`We could not load your chats. Please try again.`,backToChat:`Back to the chat`,thread:`Conversation`,you:`You`,assistant:`Assistant`,agent:`Team`,thinking:`Working on it`,loadingConversation:`Loading the conversation`,emptyTitle:`How can I help?`,starters:`Suggested questions`,resumeLast:`Continue your last chat`,nudgeDismiss:`Dismiss suggestion`,composer:`Your message`,placeholder:`Ask anything`,send:`Send`,stop:`Stop`,composerHint:`Press Enter to send, Shift and Enter for a new line.`,counter:(e,t)=>`${e.toLocaleString(`en-GB`)} of ${t.toLocaleString(`en-GB`)}`,allowance:e=>e===0?`You have no messages left today.`:e===1?`You have 1 message left today.`:`You have ${e} messages left today.`,attach:`Attach a file`,attachHint:`Pictures or PDFs.`,removeAttachment:e=>`Remove ${e}`,attachmentUploading:`Uploading`,attachmentFailed:`That file did not upload. Please try again.`,attachmentLimit:e=>`You can attach up to ${e} files.`,editing:`Editing your message`,footerPrivacyFallback:`Privacy policy`,captchaNoticeBefore:`This site is protected by reCAPTCHA and the Google `,captchaPrivacyPolicy:`Privacy Policy`,captchaNoticeAnd:` and `,captchaTerms:`Terms of Service`,captchaNoticeAfter:` apply.`,captchaUnavailable:`We could not check this message. Please try again in a moment.`,newMessages:`New messages`,disclaimer:`The assistant can make mistakes, so check important details.`,copy:`Copy`,copied:`Copied`,share:`Share`,print:`Print`,retry:`Try again`,stopped:`Stopped.`,regenerate:`New answer`,edit:`Edit`,rateUp:`Helpful`,rateDown:`Not helpful`,rating:`Rate this answer`,rated:`Thanks for the feedback.`,ratingFailed:`Your rating did not save. Please try again.`,sources:`Sources`,openSource:e=>`Open ${e}`,quickReplies:`Suggested replies`,inputSubmitting:`Sending`,inputRequired:`This field is required.`,inputConsentRequired:`Please accept to continue.`,inputAnswered:`Details sent.`,inputExpired:`This form has expired.`,inputSkipped:`Skipped.`,inputOptional:`Optional`,inputChooseFile:`Choose a file`,inputSendCode:`Send code`,inputEnterCode:`Enter the code`,inputCodeSent:`We sent a code. Enter it below.`,inputCodeFailed:`The code could not be sent. Try again.`,inputRemoveFile:e=>`Remove ${e}`,actionConfirm:`Confirm`,actionDismiss:`Not now`,actionWorking:`Working on it`,actionConfirmed:`Confirmed.`,actionRejected:`Not sent.`,actionExpired:`This request expired and was not sent.`,actionDone:`Done.`,actionFailed:`We could not do this. Please try again.`,actionRepeat:e=>`Already done on ${e}. Nothing was sent again.`,fileOpen:e=>`Open ${e}`,errorGeneric:`Something went wrong. Please try again.`,assistantOutdated:`The assistant needs an update before it can answer. Please try again later.`,typeAnswer:`or type your answer below`,skip:`Skip`,editSomething:`Edit something`,muteSounds:`Mute sounds`,unmuteSounds:`Unmute sounds`,preparingAnswer:e=>`${e} is preparing an answer`,explainTrigger:`Why?`,explainTriggerLabel:e=>`Why? Explain ${e}`,explainAskMore:`Ask more`,explainSlow:`Still working on this.`,explainOffline:`You are offline. Explanations need a connection.`,explainError:`This could not be explained just now. Try again.`,explainRetry:`Try again`,explainEmpty:`This could not be explained in words.`,explainCapacity:e=>`The limit for explanations has been reached. They come back at ${e}.`,explainCapacityNoDate:`You have reached today's limit. Try again later.`,explainNotCounted:`Explanations do not use your daily messages. A question you type does.`,openFullScreen:`Open full screen`,openSidePanel:`Open as side panel`,earlierChat:`Earlier chat`,justNow:`Just now`,today:`Today`,yesterday:`Yesterday`,dailyLimitRefresh:e=>`They refresh on ${e}.`,talkToPerson:`Talk to a person`,handoffRequested:`Connecting you to our team.`,handoffWaiting:`Waiting for the next available person.`,handoffQueued:e=>`You are number ${e} in line.`,handoffQueuedText:`We will bring you in as soon as someone is free.`,handoffJoined:e=>`${e} joined the chat.`,handoffJoinedText:e=>`The conversation so far has been shared with ${e}, so you will not need to repeat anything.`,handoffLeft:e=>`${e} left the chat.`,handoffLeftText:`Another member of the team may join, or you can start a new chat.`,handoffEnded:`This chat with our team has ended.`,handoffEndedText:`Thank you for talking to us. Start a new chat if you need anything else.`,handoffAgentFallback:`A member of our team`,handoffMoment:`One moment`,liveLost:`We lost the connection to support.`,agentTyping:e=>`${e} is typing`,agentSays:e=>`${e} says`,statusWaitingForAgent:`Waiting for a person`,statusWithAgent:e=>`${e} from our team`,openTickets:`Your open tickets`,ticketAria:e=>`Ticket ${e}`,ticketView:`View ticket`,ticketStatus:t=>e[t]??``,table:`Table`,tableShowAll:e=>`Show all ${e} rows`,tableEmpty:`No rows to show.`,chart:`Chart`,chartEmpty:`No data to show.`,chartShowTable:`Show as table`,chartShowChart:`Show as chart`,chartLoadFailed:`This chart could not be drawn.`,chartLow:e=>`Low ${e}`,chartHigh:e=>`High ${e}`,figures:`Key figures`,figureStatus:e=>t[e]??``,recordOpen:`Open`,recordOpenFor:e=>`Open ${e}`,imageLoading:`Loading image`,imageFailed:`This image could not be loaded.`,imageViewer:`Image viewer`,imageOpen:e=>`View image: ${e}`,dictate:`Dictate`,dictateStop:`Stop dictating`,dictateListening:`Listening`,dictateTranscribing:`Turning your voice into text`,dictationBlocked:`The microphone is blocked. Allow it in your settings to dictate.`,dictationNoMicrophone:`No microphone was found. Connect one and try again.`,dictationNotHeard:`Nothing was heard. Check your microphone and try again.`,dictationFailed:`Dictation stopped working. Try again.`,dictationUnavailable:`Dictation is not available here.`,dictateOpenSettings:`Open Settings`,readAloud:`Read aloud`,readAloudStop:`Stop reading`,readAloudFailed:`This could not be read aloud.`,voiceClip:`Voice message`,voiceClipPlay:`Play voice message`,voiceClipPause:`Pause voice message`,voiceClipFailed:`This voice message could not be played.`,voiceClipShowTranscript:`Show transcript`,voiceClipHideTranscript:`Hide transcript`,voiceClipTime:(e,t)=>`${e} of ${t}`,shareConversation:`Share this conversation`,printConversation:`Print this conversation`,shareFailed:`Could not share. Try again.`,printFailed:`Could not open the print view. Try again.`,printedOn:e=>`Printed on ${e}`}),r=e=>e?{...n,...e}:n;export{n as DEFAULT_CHAT_LABELS,r as mergeLabels};
1
+ var e={Open:`Open`,InProgress:`In progress`,WaitingOnCustomer:`Waiting on you`,Resolved:`Resolved`,Closed:`Closed`,Cancelled:`Cancelled`},t={Positive:`Good`,Caution:`Watch`,Negative:`Poor`,Neutral:``},n=Object.freeze({launcher:`Open chat`,launcherClose:`Close chat`,panelTitle:`Assistant`,headerStatus:`Usually replies instantly`,newChat:`New chat`,close:`Close`,history:`Past chats`,historyEmptyTitle:`No past chats`,historyEmptyText:`Your conversations show here.`,untitled:`Untitled chat`,rename:`Rename chat`,renameSave:`Save`,conversationTitle:`Chat name`,renameFailed:`We could not rename this chat. Please try again.`,deleteChat:`Delete chat`,deleteConfirmTitle:`Delete this chat?`,deleteConfirmMessage:`The conversation is removed for good.`,deleteConfirm:`Delete`,deleteFailed:`We could not delete this chat. Please try again.`,cancel:`Cancel`,loadMore:`Show more`,loadFailed:`We could not load your chats. Please try again.`,backToChat:`Back to the chat`,thread:`Conversation`,you:`You`,assistant:`Assistant`,agent:`Team`,thinking:`Working on it`,loadingConversation:`Loading the conversation`,emptyTitle:`How can I help?`,starters:`Suggested questions`,resumeLast:`Continue your last chat`,recentChats:`Recent chats`,nudgeDismiss:`Dismiss suggestion`,composer:`Your message`,placeholder:`Ask anything`,send:`Send`,stop:`Stop`,composerHint:`Press Enter to send, Shift and Enter for a new line.`,counter:(e,t)=>`${e.toLocaleString(`en-GB`)} of ${t.toLocaleString(`en-GB`)}`,allowance:e=>e===0?`You have no messages left today.`:e===1?`You have 1 message left today.`:`You have ${e} messages left today.`,attach:`Attach a file`,attachHint:`Pictures or PDFs.`,removeAttachment:e=>`Remove ${e}`,attachmentUploading:`Uploading`,attachmentFailed:`That file did not upload. Please try again.`,attachmentLimit:e=>`You can attach up to ${e} files.`,editing:`Editing your message`,footerPrivacyFallback:`Privacy policy`,captchaNoticeBefore:`This site is protected by reCAPTCHA and the Google `,captchaPrivacyPolicy:`Privacy Policy`,captchaNoticeAnd:` and `,captchaTerms:`Terms of Service`,captchaNoticeAfter:` apply.`,captchaUnavailable:`We could not check this message. Please try again in a moment.`,newMessages:`New messages`,disclaimer:`The assistant can make mistakes, so check important details.`,copy:`Copy`,copied:`Copied`,share:`Share`,print:`Print`,retry:`Try again`,stopped:`Stopped.`,regenerate:`New answer`,edit:`Edit`,rateUp:`Helpful`,rateDown:`Not helpful`,rating:`Rate this answer`,rated:`Thanks for the feedback.`,ratingFailed:`Your rating did not save. Please try again.`,sources:`Sources`,openSource:e=>`Open ${e}`,quickReplies:`Suggested replies`,inputSubmitting:`Sending`,inputRequired:`This field is required.`,inputConsentRequired:`Please accept to continue.`,inputAnswered:`Details sent.`,inputExpired:`This form has expired.`,inputSkipped:`Skipped.`,inputOptional:`Optional`,inputChooseFile:`Choose a file`,inputSendCode:`Send code`,inputEnterCode:`Enter the code`,inputCodeSent:`We sent a code. Enter it below.`,inputCodeFailed:`The code could not be sent. Try again.`,inputRemoveFile:e=>`Remove ${e}`,actionConfirm:`Confirm`,actionDismiss:`Not now`,actionWorking:`Working on it`,actionConfirmed:`Confirmed.`,actionRejected:`Not sent.`,actionExpired:`This request expired and was not sent.`,actionDone:`Done.`,actionFailed:`We could not do this. Please try again.`,actionRepeat:e=>`Already done on ${e}. Nothing was sent again.`,fileOpen:e=>`Open ${e}`,errorGeneric:`Something went wrong. Please try again.`,assistantOutdated:`The assistant needs an update before it can answer. Please try again later.`,typeAnswer:`or type your answer below`,skip:`Skip`,editSomething:`Edit something`,muteSounds:`Mute sounds`,unmuteSounds:`Unmute sounds`,preparingAnswer:e=>`${e} is preparing an answer`,explainTrigger:`Why?`,explainTriggerLabel:e=>`Why? Explain ${e}`,explainAskMore:`Ask more`,explainSlow:`Still working on this.`,explainOffline:`You are offline. Explanations need a connection.`,explainError:`This could not be explained just now. Try again.`,explainRetry:`Try again`,explainEmpty:`This could not be explained in words.`,explainCapacity:e=>`The limit for explanations has been reached. They come back at ${e}.`,explainCapacityNoDate:`You have reached today's limit. Try again later.`,explainNotCounted:`Explanations do not use your daily messages. A question you type does.`,openFullScreen:`Open full screen`,openSidePanel:`Open as side panel`,earlierChat:`Earlier chat`,justNow:`Just now`,today:`Today`,yesterday:`Yesterday`,dailyLimitRefresh:e=>`They refresh on ${e}.`,talkToPerson:`Talk to a person`,handoffRequested:`Connecting you to our team.`,handoffWaiting:`Waiting for the next available person.`,handoffQueued:e=>`You are number ${e} in line.`,handoffQueuedText:`We will bring you in as soon as someone is free.`,handoffJoined:e=>`${e} joined the chat.`,handoffJoinedText:e=>`The conversation so far has been shared with ${e}, so you will not need to repeat anything.`,handoffLeft:e=>`${e} left the chat.`,handoffLeftText:`Another member of the team may join, or you can start a new chat.`,handoffEnded:`This chat with our team has ended.`,handoffEndedText:`Thank you for talking to us. Start a new chat if you need anything else.`,handoffAgentFallback:`A member of our team`,handoffMoment:`One moment`,liveLost:`We lost the connection to support.`,agentTyping:e=>`${e} is typing`,agentSays:e=>`${e} says`,statusWaitingForAgent:`Waiting for a person`,statusWithAgent:e=>`${e} from our team`,openTickets:`Your open tickets`,ticketAria:e=>`Ticket ${e}`,ticketView:`View ticket`,ticketStatus:t=>e[t]??``,table:`Table`,tableShowAll:e=>`Show all ${e} rows`,tableEmpty:`No rows to show.`,chart:`Chart`,chartEmpty:`No data to show.`,chartShowTable:`Show as table`,chartShowChart:`Show as chart`,chartLoadFailed:`This chart could not be drawn.`,chartLow:e=>`Low ${e}`,chartHigh:e=>`High ${e}`,figures:`Key figures`,figureStatus:e=>t[e]??``,recordOpen:`Open`,recordOpenFor:e=>`Open ${e}`,imageLoading:`Loading image`,imageFailed:`This image could not be loaded.`,imageViewer:`Image viewer`,imageOpen:e=>`View image: ${e}`,dictate:`Dictate`,dictateStop:`Stop dictating`,dictateListening:`Listening`,dictateTranscribing:`Turning your voice into text`,dictationBlocked:`The microphone is blocked. Allow it in your settings to dictate.`,dictationNoMicrophone:`No microphone was found. Connect one and try again.`,dictationNotHeard:`Nothing was heard. Check your microphone and try again.`,dictationFailed:`Dictation stopped working. Try again.`,dictationUnavailable:`Dictation is not available here.`,dictateOpenSettings:`Open Settings`,readAloud:`Read aloud`,readAloudStop:`Stop reading`,readAloudFailed:`This could not be read aloud.`,voiceClip:`Voice message`,voiceClipPlay:`Play voice message`,voiceClipPause:`Pause voice message`,voiceClipFailed:`This voice message could not be played.`,voiceClipShowTranscript:`Show transcript`,voiceClipHideTranscript:`Hide transcript`,voiceClipTime:(e,t)=>`${e} of ${t}`,shareConversation:`Share this conversation`,printConversation:`Print this conversation`,shareFailed:`Could not share. Try again.`,printFailed:`Could not open the print view. Try again.`,printedOn:e=>`Printed on ${e}`}),r=[`captchaNoticeBefore`,`captchaPrivacyPolicy`,`captchaNoticeAnd`,`captchaTerms`,`captchaNoticeAfter`],i=e=>{if(e){for(let t of r){let n=e[t];if(typeof n==`string`&&n.trim()===``)throw RangeError(`Chat label ${t} must not be empty: the reCAPTCHA notice needs its full wording.`)}return{...n,...e}}return n};export{n as DEFAULT_CHAT_LABELS,i as mergeLabels};
package/dist/look.js CHANGED
@@ -1 +1 @@
1
- var e={launcher:{style:`Round`,entrance:`Rise`,idle:`None`,labelReveal:`Bubble`,compact:!1,mark:`Icon`},panel:{motion:`Spring`,widthPx:420,maxHeightPx:650,bottomGapPx:24,height:`Fixed`,placement:`Floating`,replyAvatars:`First`,greetingLoaderMs:0},phone:{maxWidthPx:768,mode:`FullScreen`,sheetHeightDvh:85,sheetMaxHeightPx:640,hideLauncher:!1},input:{ring:!0,sendReveal:`OnText`,sendIcon:`arrow-up`,mark:`None`},avoid:{liftSelectors:[`footer`,`.form-actions-sticky`,`.wui-tabbar`],menuSelectors:[`.offcanvas.show`,`wui-drawer[open]`,`[data-menu-open]`],darkSelectors:[`[data-theme='dark']`,`[data-bs-theme='dark']`],autoOpenOptOutSelector:`[data-chat-no-autoopen]`,autoOpenBusySelectors:[`[data-chat-busy]`]},motion:`On`,avatar:null,avatarMotion:`Still`,expressive:!1};function t(t){let n=t??{};return{launcher:{...e.launcher,...n.launcher},panel:{...e.panel,...n.panel},phone:{...e.phone,...n.phone},input:{...e.input,...n.input},avoid:{...e.avoid,...n.avoid},motion:n.motion??e.motion,avatar:n.avatar??e.avatar,avatarMotion:n.avatarMotion??e.avatarMotion,expressive:n.expressive??e.expressive}}export{e as defaultChatLook,t as mergeLook};
1
+ var e=5,t={launcher:{style:`Round`,entrance:`Rise`,idle:`None`,labelReveal:`Bubble`,compact:!1,mark:`Icon`},panel:{motion:`Spring`,widthPx:420,maxHeightPx:650,bottomGapPx:24,height:`Fixed`,placement:`Floating`,replyAvatars:`First`,greetingLoaderMs:0},phone:{maxWidthPx:768,mode:`FullScreen`,sheetHeightDvh:85,sheetMaxHeightPx:640,hideLauncher:!1},input:{ring:!0,sendReveal:`OnText`,sendIcon:`arrow-up`,mark:`None`,edge:`None`,placeholder:`Plain`,busyEdge:`Off`},starters:{style:`Chips`,recentRows:0},footer:{layout:`Stacked`,disclaimer:`Show`},avoid:{liftSelectors:[`footer`,`.form-actions-sticky`,`.wui-tabbar`],menuSelectors:[`.offcanvas.show`,`wui-drawer[open]`,`[data-menu-open]`],darkSelectors:[`[data-theme='dark']`,`[data-bs-theme='dark']`],autoOpenOptOutSelector:`[data-chat-no-autoopen]`,autoOpenBusySelectors:[`[data-chat-busy]`]},motion:`On`,avatar:null,avatarMotion:`Still`,expressive:!1};function n(e){let n=e??{};return{launcher:{...t.launcher,...n.launcher},panel:{...t.panel,...n.panel},phone:{...t.phone,...n.phone},input:{...t.input,...n.input},starters:{...t.starters,...n.starters},footer:{...t.footer,...n.footer},avoid:{...t.avoid,...n.avoid},motion:n.motion??t.motion,avatar:n.avatar??t.avatar,avatarMotion:n.avatarMotion??t.avatarMotion,expressive:n.expressive??t.expressive}}export{e as CHAT_RECENT_ROWS_MAX,t as defaultChatLook,n as mergeLook};
package/dist/profile.js CHANGED
@@ -1 +1 @@
1
- import{allMembers as e}from"./decode/primitives.js";import{DEFAULT_CHAT_LABELS as t}from"./labels.js";var n=Object.freeze(e()(/* @__PURE__ */ `VisitorChat.Starters.Nudges.ResumeLast.OpenTickets.History.Rename.Delete.SuggestedReplies.Stop.Retry.Edit.Regenerate.Sources.Rating.Copy.Share.Print.Attachments.RichAnswers.InputRequests.LeadCapture.Booking.Scripts.AiAnswers.HumanHandoff.Dictation.ReadAloud.VoiceClips.Sounds.AutoOpen.BehaviourStarters.LeadShortcuts.LeadRecap.FigureText.LinkHandoff.Explain.PanelSwitch`.split(`.`))),r=e=>({VisitorChat:e(`VisitorChat`),Starters:e(`Starters`),Nudges:e(`Nudges`),ResumeLast:e(`ResumeLast`),OpenTickets:e(`OpenTickets`),History:e(`History`),Rename:e(`Rename`),Delete:e(`Delete`),SuggestedReplies:e(`SuggestedReplies`),Stop:e(`Stop`),Retry:e(`Retry`),Edit:e(`Edit`),Regenerate:e(`Regenerate`),Sources:e(`Sources`),Rating:e(`Rating`),Copy:e(`Copy`),Share:e(`Share`),Print:e(`Print`),Attachments:e(`Attachments`),RichAnswers:e(`RichAnswers`),InputRequests:e(`InputRequests`),LeadCapture:e(`LeadCapture`),Booking:e(`Booking`),Scripts:e(`Scripts`),AiAnswers:e(`AiAnswers`),HumanHandoff:e(`HumanHandoff`),Dictation:e(`Dictation`),ReadAloud:e(`ReadAloud`),VoiceClips:e(`VoiceClips`),Sounds:e(`Sounds`),AutoOpen:e(`AutoOpen`),BehaviourStarters:e(`BehaviourStarters`),LeadShortcuts:e(`LeadShortcuts`),LeadRecap:e(`LeadRecap`),FigureText:e(`FigureText`),LinkHandoff:e(`LinkHandoff`),Explain:e(`Explain`),PanelSwitch:e(`PanelSwitch`)}),i=()=>r(()=>!1),a=(e,t)=>Object.freeze(r(n=>e.features[n]===!0&&t?.[n]!==!1)),o=(e,t)=>e===`/`||t===e||t.startsWith(`${e}/`),s=(e,{pathname:t,returning:n})=>{let r=e.start,i=r.greeting,a=r.starters;n&&(i=r.returningGreeting??i,a=r.returningStarters??a);let s=null;for(let e of r.pageRules)o(e.pathPrefix,t)&&(s===null||e.pathPrefix.length>s.pathPrefix.length)&&(s=e);return s&&(i=s.greeting??i,a=s.starters??a),{greeting:i,starters:a}},c=(e,t)=>t.Nudges&&e.start.nudge?e.start.nudge:null,l=e=>e.captcha.mode!==`Off`&&typeof e.captcha.siteKey==`string`&&e.captcha.siteKey!==``,u=[`Steps`,`Phrases`,`Orb`,`Skeleton`],d=(e,n,r,i)=>{let a=r.length>0?r:[t.thinking],o=a[(i%a.length+a.length)%a.length];if(o===void 0)throw Error(`loader phrase index out of range for rotation ${i}`);let s=n.length>0?n[n.length-1]:void 0;return e===`Phrases`?{label:o,steps:[],activeIndex:-1}:e===`Steps`?{label:s??o,steps:n.length>0?[...n]:[o],activeIndex:n.length>0?n.length-1:0}:{label:s??o,steps:[],activeIndex:-1}};export{n as CHAT_FEATURES,u as LOADER_STYLES,i as emptyFeatures,r as featureRecord,d as loaderView,a as resolveFeatures,c as resolveNudge,s as resolveStart,l as showsCaptchaNote};
1
+ import{allMembers as e}from"./decode/primitives.js";import{DEFAULT_CHAT_LABELS as t}from"./labels.js";var n=Object.freeze(e()(/* @__PURE__ */ `VisitorChat.Starters.Nudges.ResumeLast.OpenTickets.History.Rename.Delete.SuggestedReplies.Stop.Retry.Edit.Regenerate.Sources.Rating.Copy.Share.Print.Attachments.RichAnswers.InputRequests.LeadCapture.Booking.Scripts.AiAnswers.HumanHandoff.Dictation.ReadAloud.VoiceClips.Sounds.AutoOpen.BehaviourStarters.LeadShortcuts.LeadRecap.FigureText.LinkHandoff.Explain.PanelSwitch`.split(`.`))),r=e=>({VisitorChat:e(`VisitorChat`),Starters:e(`Starters`),Nudges:e(`Nudges`),ResumeLast:e(`ResumeLast`),OpenTickets:e(`OpenTickets`),History:e(`History`),Rename:e(`Rename`),Delete:e(`Delete`),SuggestedReplies:e(`SuggestedReplies`),Stop:e(`Stop`),Retry:e(`Retry`),Edit:e(`Edit`),Regenerate:e(`Regenerate`),Sources:e(`Sources`),Rating:e(`Rating`),Copy:e(`Copy`),Share:e(`Share`),Print:e(`Print`),Attachments:e(`Attachments`),RichAnswers:e(`RichAnswers`),InputRequests:e(`InputRequests`),LeadCapture:e(`LeadCapture`),Booking:e(`Booking`),Scripts:e(`Scripts`),AiAnswers:e(`AiAnswers`),HumanHandoff:e(`HumanHandoff`),Dictation:e(`Dictation`),ReadAloud:e(`ReadAloud`),VoiceClips:e(`VoiceClips`),Sounds:e(`Sounds`),AutoOpen:e(`AutoOpen`),BehaviourStarters:e(`BehaviourStarters`),LeadShortcuts:e(`LeadShortcuts`),LeadRecap:e(`LeadRecap`),FigureText:e(`FigureText`),LinkHandoff:e(`LinkHandoff`),Explain:e(`Explain`),PanelSwitch:e(`PanelSwitch`)}),i=()=>r(()=>!1),a=(e,t)=>Object.freeze(r(n=>e.features[n]===!0&&t?.[n]!==!1)),o=(e,t)=>e===`/`||t===e||t.startsWith(`${e}/`),s=(e,{pathname:t,returning:n})=>{let r=e.start,i=r.greeting,a=r.starters;n&&(i=r.returningGreeting??i,a=r.returningStarters??a);let s=null;for(let e of r.pageRules)o(e.pathPrefix,t)&&(s===null||e.pathPrefix.length>s.pathPrefix.length)&&(s=e);return s&&(i=s.greeting??i,a=s.starters??a),{greeting:i,starters:a}},c=(e,t)=>t.Nudges&&e.start.nudge?e.start.nudge:null,l=e=>e.captcha.mode!==`Off`&&typeof e.captcha.siteKey==`string`&&e.captcha.siteKey!==``,u=[`Steps`,`Phrases`,`Orb`,`Skeleton`,`PulseAndDots`],d=(e,n,r,i)=>{let a=r.length>0?r:[t.thinking],o=a[(i%a.length+a.length)%a.length];if(o===void 0)throw Error(`loader phrase index out of range for rotation ${i}`);let s=n.length>0?n[n.length-1]:void 0;return e===`Phrases`?{label:o,steps:[],activeIndex:-1}:e===`Steps`?{label:s??o,steps:n.length>0?[...n]:[o],activeIndex:n.length>0?n.length-1:0}:{label:s??o,steps:[],activeIndex:-1}};export{n as CHAT_FEATURES,u as LOADER_STYLES,i as emptyFeatures,r as featureRecord,d as loaderView,a as resolveFeatures,c as resolveNudge,s as resolveStart,l as showsCaptchaNote};
package/dist/session.js CHANGED
@@ -1,3 +1,3 @@
1
- import{ChatApiError as e}from"./client.js";import"./contract.js";import{messagePlainText as t}from"./format.js";import{asRecord as n}from"./guards.js";import{DEFAULT_CHAT_LABELS as r,mergeLabels as i}from"./labels.js";import{startLiveConnection as a}from"./live.js";import{pacingDelayMs as o}from"./pacing.js";import{emptyFeatures as s,resolveFeatures as c,resolveStart as l}from"./profile.js";import{runtime as u}from"./runtime.js";import{selectStarters as ee}from"./starters.js";var te=5e3,ne=3e3,re=300,ie=1200,ae=e=>{if(u.requestAnimationFrame&&u.cancelAnimationFrame){let t=u.requestAnimationFrame(()=>e());return()=>u.cancelAnimationFrame?.(t)}let t=u.setTimeout(e,16);return()=>u.clearTimeout(t)},d=e=>{let t=n(e);return{code:typeof t.code==`string`&&t.code?t.code:`unknown`,message:typeof t.message==`string`&&t.message?t.message:r.errorGeneric,resetsDateTimeUtc:typeof t.resetsDateTimeUtc==`string`?t.resetsDateTimeUtc:null}},oe=(e,t)=>({id:e.publicId,author:e.author,createdDateTimeUtc:e.createdDateTimeUtc,parts:e.parts,sequence:e.sequence,rating:e.rating,ratingNote:e.ratingNote,streaming:!1,stored:!0,restored:t}),se=(e,t)=>{let n=e.findIndex(e=>e.id===t.id);return n<0?[...e,t]:e.map((e,r)=>r===n?t:e)},ce=(e,t)=>{for(let n=e.length-1;n>=0;--n){let r=e[n];if(r!==void 0&&t(r))return n}return-1},le=e=>e.flatMap(e=>e.kind===`Text`?[e.text]:[]).join(`
1
+ import{ChatApiError as e}from"./client.js";import"./contract.js";import{messagePlainText as t}from"./format.js";import{asRecord as n}from"./guards.js";import{DEFAULT_CHAT_LABELS as r,mergeLabels as i}from"./labels.js";import{startLiveConnection as a}from"./live.js";import"./look.js";import{pacingDelayMs as o}from"./pacing.js";import{emptyFeatures as s,resolveFeatures as ee,resolveStart as c}from"./profile.js";import{runtime as l}from"./runtime.js";import{selectStarters as te}from"./starters.js";var ne=5e3,re=3e3,ie=300,ae=1200,oe=e=>{if(l.requestAnimationFrame&&l.cancelAnimationFrame){let t=l.requestAnimationFrame(()=>e());return()=>l.cancelAnimationFrame?.(t)}let t=l.setTimeout(e,16);return()=>l.clearTimeout(t)},u=e=>{let t=n(e);return{code:typeof t.code==`string`&&t.code?t.code:`unknown`,message:typeof t.message==`string`&&t.message?t.message:r.errorGeneric,resetsDateTimeUtc:typeof t.resetsDateTimeUtc==`string`?t.resetsDateTimeUtc:null}},se=(e,t)=>({id:e.publicId,author:e.author,createdDateTimeUtc:e.createdDateTimeUtc,parts:e.parts,sequence:e.sequence,rating:e.rating,ratingNote:e.ratingNote,streaming:!1,stored:!0,restored:t}),ce=(e,t)=>{let n=e.findIndex(e=>e.id===t.id);return n<0?[...e,t]:e.map((e,r)=>r===n?t:e)},le=(e,t)=>{for(let n=e.length-1;n>=0;--n){let r=e[n];if(r!==void 0&&t(r))return n}return-1},ue=e=>e.flatMap(e=>e.kind===`Text`?[e.text]:[]).join(`
2
2
 
3
- `),f=e=>e.flatMap(e=>e.kind===`File`?[{publicId:e.attachmentId,fileName:e.fileName,contentType:e.contentType,length:e.length}]:[]),ue=e=>{let t=n(e);return{fileName:typeof t.name==`string`?t.name:``,contentType:typeof t.type==`string`?t.type:``,length:typeof t.size==`number`?t.size:null}},de=(e,t)=>e.length===t.length&&e.every((e,n)=>{let r=t[n];return r!==void 0&&e.id===r.id&&e.label===r.label&&e.message===r.message}),fe=e=>{for(let t of e){if(!t.startsWith(`Enquiry type:`))continue;let e=t.slice(13).trim();return e===``?null:e}return null},pe=e=>e.some(e=>e.kind===`Handoff`)?null:e.find(e=>e.kind===`InputRequest`)?.requestId??null,me=(e,t)=>e.some(e=>e.parts.some(e=>e.kind===`InputRequest`&&e.requestId===t&&(e.state===`Skipped`||e.state===`Expired`))),he=(e,t)=>{if(t!==`WithAgent`)return null;for(let t=e.length-1;t>=0;--t){let n=e[t];if(n!==void 0){for(let e=n.parts.length-1;e>=0;--e){let t=n.parts[e];if(t?.kind===`Handoff`){if(t.state===`Left`||t.state===`Ended`)return null;if(t.state===`Joined`&&t.agent)return t.agent}}if(n.author.kind===`Agent`)return{displayName:n.author.displayName??``,avatarUrl:n.author.avatarUrl}}}return null},ge=(e,t)=>{(e.cursor===null||t>e.cursor)&&(e.cursor=t)},_e=(e,t)=>{let n=[];e!==``&&n.push({kind:`Text`,text:e});for(let e of t)n.push({kind:`File`,attachmentId:e.publicId,fileName:e.fileName,contentType:e.contentType,length:e.length});return n},ve=e=>{let t=le(e.parts);return{wireText:t===``?null:t,displayText:t,quickReplyId:null,replacesMessageId:null,repliesToMessageId:null,attachments:f(e.parts)}},ye=e=>({profile:null,profileError:null,features:s(),conversationId:null,conversationState:`Open`,title:null,continuesConversationId:null,messages:[],thinking:!1,steps:[],streaming:!1,loading:!1,loadError:null,turnError:null,stopped:!1,messagesLeftToday:null,editing:null,attachments:[],lastConversation:null,open:!1,muted:e?.get(`wchat:muted`)===`1`,greeting:null,starters:[],pending:null,agent:null,agentTyping:null,live:`Off`,handoffPending:!1,handoffContactRequestId:null,handoffPause:!1,openTickets:[],draft:null}),p=(s,f)=>{let p=i(f.labels),m=f.schedule??ae,h=f.prefs,g=/* @__PURE__ */ new Set,_=ye(h),v=0,y=null,b=null,be=0,xe=0,Se=null,x=null,S=/* @__PURE__ */ new Map,Ce=/* @__PURE__ */ new Set,C=/* @__PURE__ */ new Map,w=/* @__PURE__ */ new Set,T=/* @__PURE__ */ new Map,E={name:null,email:null,phone:null},D=/* @__PURE__ */ new Set,O=null,k=null,A=null,j=null,M=null,we=!0,N=!1,P=/* @__PURE__ */ new Set,F=/* @__PURE__ */ new Map,I=Promise.resolve(),L=0,Te=()=>f.pathname?.()??u.location?.pathname??`/`,Ee=()=>f.reducedMotion?.()===!0||_.profile?.experience.motion===!1,R=()=>_.streaming||_.thinking,De=e=>{if(!e.profile)return{...e,greeting:null,starters:[]};let t=Te(),n=e.lastConversation!==null,r=l(e.profile,{pathname:t,returning:n}).greeting,i=ee(e.profile.start,{pathname:t,returning:n,behaviour:f.behaviour?.()??null,behaviourStarters:e.features.BehaviourStarters});return{...e,greeting:r,starters:de(e.starters,i)?e.starters:i}},z=()=>{O!==null&&(u.clearTimeout(O),O=null)},B=()=>{A!==null&&(u.clearTimeout(A),A=null)},Oe=e=>e.flatMap(e=>e.parts.flatMap(e=>e.kind===`Action`&&e.actionKind===`ChatLeadCapture`&&e.state===`Done`?[{actionId:e.actionId,leadType:fe(e.lines)}]:[])),V=()=>{E.name=null,E.email=null,E.phone=null,D.clear()},ke=e=>{for(let t of Oe(e))D.add(t.actionId)},Ae=()=>{for(let e of Oe(_.messages))D.has(e.actionId)||(D.add(e.actionId),f.onEvent?.(`leadSubmitted`,{conversationId:_.conversationId,fields:{name:E.name,email:E.email,phone:E.phone},leadType:e.leadType}))},je=(e,t)=>{let n=_.messages.flatMap(e=>e.parts).find(t=>t.kind===`InputRequest`&&t.requestId===e);if(n)for(let e of n.fields){let n=t[e.key];typeof n==`string`&&n.trim()!==``&&(e.type===`Email`?E.email=n.trim():e.type===`Phone`?E.phone=n.trim():(e.type===`Name`||e.key.toLowerCase()===`name`)&&(E.name=n.trim()))}},H=e=>{let t=M;t!==null&&(M=null,t.handle?.stop(),e!==null&&W({live:e}))},Me=()=>!N&&we&&_.features.HumanHandoff&&_.conversationId!==null&&(_.conversationState===`WaitingForAgent`||_.conversationState===`WithAgent`),U=()=>{if(!Me()){M!==null&&H(`Off`);return}let e=_.conversationId;if(e===null||M!==null&&M.conversationId===e)return;H(null);let t={conversationId:e,cursor:null,handle:null};M=t;let n=a({watch:(n,r,i)=>s.watchConversation(e,{afterSequence:n,signal:r,onCursor:e=>ge(t,e),onEvent:e=>{i(),M===t&&(e.name===`messageCompleted`&&ge(t,e.data.message.sequence),Z(e,`live`,()=>M===t))}}),beforeReconnect:()=>Q(),getCursor:()=>{let e=t.cursor;for(let t of _.messages)t.sequence!==null&&(e===null||t.sequence>e)&&(e=t.sequence);return e},onStatus:e=>{M===t&&_.live!==e&&W({live:e})},onError:e=>q(e)});t.handle=n,M!==t&&n.stop()},W=e=>{let t={..._,...e};_.conversationState===`WithAgent`&&t.conversationState!==`WithAgent`&&t.agentTyping!==null&&(z(),t.agentTyping=null),(e.messages!==void 0||e.conversationState!==void 0)&&(t.agent=he(t.messages,t.conversationState)),e.messages!==void 0&&t.handoffContactRequestId!==null&&me(t.messages,t.handoffContactRequestId)&&(t.handoffContactRequestId=null),_=De(t);for(let e of g)e();e.messages!==void 0&&Ae(),U()},Ne=(e,t)=>W({attachments:_.attachments.map(n=>n.key===e?{...n,...t}:n)}),G=()=>{if(S.size===0)return;let e=[...S.values()];S.clear(),W({messages:_.messages.map(t=>{let n=e.filter(e=>e.messageId===t.id);if(n.length===0)return t;let r=t.parts.map((e,t)=>{let r=n.filter(e=>e.index===t).map(e=>e.text).join(``);return e.kind===`Text`&&r!==``?{...e,text:e.text+r}:e});return{...t,parts:r}})})},K=()=>{S.clear(),b?.(),b=null},Pe=(e,t,n)=>{let r=`${e}#${t}`,i=S.get(r);S.set(r,{messageId:e,index:t,text:(i?.text??``)+n}),b||=m(()=>{b=null,G()})},Fe=()=>{G(),v+=1,y?.abort(),y=null},q=e=>{if(f.onError)f.onError(e);else throw e},J=()=>{for(let e of T.values())e.abort();T.clear();for(let e of w){let t=C.get(e);t&&s.deleteAttachment(t.publicId).catch(q)}w.clear(),C.clear()},Ie=e=>{let t=C.get(e);if(!t)throw Error(`No uploaded file for composer attachment ${e}.`);return t},Le=async(e,t)=>{let n=new u.AbortController;T.set(e,n);let r;try{r=await s.uploadAttachment(t,{signal:n.signal,onProgress:t=>{T.get(e)===n&&Ne(e,{progress:t})}})}catch{T.get(e)===n&&(T.delete(e),Ne(e,{status:`Failed`,progress:null,error:p.attachmentFailed}));return}T.get(e)===n?(T.delete(e),C.set(e,r),w.add(e),Ne(e,{status:`Ready`,progress:null})):s.deleteAttachment(r.publicId).catch(q)},Re=e=>{let t={...n(f.pageContext?.()),path:Te(),behaviour:f.behaviour?.()??null};return e&&(t.attribution=f.attribution?.()??null),t},ze=async()=>{let t=_.profile?.captcha;if(!t)return null;if(t.testToken)return t.testToken;if(!f.getCaptchaToken||t.mode===`Off`&&!t.siteKey)return null;let n;try{n=await f.getCaptchaToken(t.action)}catch(t){throw f.onError?.(t),new e(`captcha_unavailable`,{message:p.captchaUnavailable,cause:t})}if(!n)throw new e(`captcha_unavailable`,{message:p.captchaUnavailable});return n},Be=(e,t,n)=>{let r=se(_.messages,oe(e,!1));W(n?{messages:r,messagesLeftToday:t??_.messagesLeftToday,steps:[],thinking:!1}:{messages:r})},Ve=e=>{let n=_.profile?.experience.pacing;return!n||Ce.has(e.publicId)||e.author.kind!==`Assistant`&&e.author.kind!==`Script`?0:o(t(e.parts),n,Ee())},He=(e,t,n,r,i)=>{L+=1,W({pending:{typing:!0,authorKind:e.author.kind}}),I=I.then(()=>new Promise(e=>u.setTimeout(e,n))).then(()=>{--L,r()&&Be(e,t,i),L===0&&W({pending:null})})},Ue=(e,t,n)=>{let r=[...e];return r[t]=n,r},Y=(e,t)=>_.messages.map(n=>n.id===e?t(n):n),X=e=>_.messages.some(t=>t.id===e),We=()=>{z(),_.agentTyping!==null&&W({agentTyping:null})},Ge=e=>{z(),O=u.setTimeout(()=>{O=null,W({agentTyping:null})},te),W({agentTyping:{displayName:e}})},Z=(e,t,n)=>{if(!n())return;let r=t===`turn`;if(e.name===`partDelta`)Ce.add(e.data.messageId),Pe(e.data.messageId,e.data.index,e.data.text);else switch(G(),e.name){case`messageStarted`:{let t=e.data.message;if(t.author.kind===`Agent`&&We(),X(t.publicId))break;W({messages:[..._.messages,{id:t.publicId,author:t.author,createdDateTimeUtc:t.createdDateTimeUtc,parts:[...t.parts],sequence:t.sequence,rating:t.rating,ratingNote:t.ratingNote,streaming:!0,stored:!1,restored:!1}]});break}case`partStarted`:{let{messageId:t,index:n,part:i}=e.data;if(!X(t))break;W({messages:Y(t,e=>({...e,parts:Ue(e.parts,n,i)})),...r?{thinking:!1}:{}});break}case`partCompleted`:{let{messageId:t,index:n,part:r}=e.data;if(!X(t))break;W({messages:Y(t,e=>({...e,parts:Ue(e.parts,n,r)}))});break}case`messageReset`:{let{messageId:t}=e.data;if(!X(t))break;for(let e of[...S.keys()])S.get(e)?.messageId===t&&S.delete(e);W({messages:Y(t,e=>({...e,parts:[]})),...r?{thinking:!0,steps:[]}:{}});break}case`step`:{if(!r)break;let t=e.data.label;_.steps[_.steps.length-1]!==t&&W({steps:[..._.steps,t]});break}case`messageCompleted`:{let{message:t,messagesLeftToday:i}=e.data;t.author.kind===`Agent`&&We();let a=Ve(t);a>0||L>0?He(t,i,a,n,r):Be(t,i,r);break}case`conversationUpdated`:{let t=e.data;W({conversationId:t.conversationId,conversationState:t.state,title:t.title,continuesConversationId:t.continuesConversationId});break}case`typing`:e.data.authorKind===`Agent`&&Ge(e.data.displayName)}},Q=async()=>{let e=_.conversationId;if(e===null)return;let t=v;try{let n=await s.getConversation(e);if(t!==v)return;let r=new Set(_.messages.filter(e=>e.restored).map(e=>e.id));W({messages:n.messages.map(e=>oe(e,r.has(e.publicId))),title:n.title,conversationState:n.state,continuesConversationId:n.continuesConversationId})}catch(e){q(e)}},$=async(e,t,n)=>{let r=v,i=new u.AbortController,a=()=>r===v&&!i.signal.aborted;y=i;let o=_.conversationId===null;be+=1;let c={id:`local-${be}`,author:{kind:`Visitor`,displayName:null,avatarUrl:null},createdDateTimeUtc:(/* @__PURE__ */ new Date()).toISOString(),parts:_e(e.displayText,e.attachments),sequence:null,rating:null,ratingNote:null,streaming:!1,stored:!1,restored:!1};n&&(w.clear(),C.clear()),W({messages:[...t,c],thinking:!0,streaming:!0,steps:[],turnError:null,stopped:!1,...n?{editing:null,attachments:[]}:{}});try{let t=await ze();await s.send({conversationId:_.conversationId,text:e.wireText,quickReplyId:e.quickReplyId,attachmentIds:e.attachments.map(e=>e.publicId),replacesMessageId:e.replacesMessageId,repliesToMessageId:e.repliesToMessageId,pageContext:Re(o),captchaToken:t},{signal:i.signal,onEvent:e=>Z(e,`turn`,a)})}catch(e){if(G(),!a())return;let t=d(e);W({messages:_.messages.filter(e=>!e.streaming),thinking:!1,streaming:!1,turnError:t,...t.code===`daily_limit`?{messagesLeftToday:0}:{},...t.code===`conversation_not_found`?{conversationId:null}:{}});return}finally{y===i&&(y=null)}if(await I,!a())return;G(),W({thinking:!1,streaming:!1}),await Q();let l=_.conversationId;o&&l!==null&&l!==Se&&(Se=l,f.onEvent?.(`chatStarted`,{conversationId:l}))},Ke=e=>W({messages:_.messages.map(t=>({...t,parts:t.parts.map(t=>t.kind===`Action`&&t.actionId===e.actionId?{...t,state:e.state,decidedDateTimeUtc:e.decidedDateTimeUtc,note:e.note}:t)}))}),qe=async()=>{try{W({openTickets:await s.listOpenTickets()})}catch(e){q(e)}},Je=async()=>{try{let e=await s.listConversations({page:1,pageSize:1});W({lastConversation:e.items[0]??null})}catch(e){q(e)}},Ye=async()=>{let e;try{e=await s.getProfile(f.screen)}catch(e){W({profileError:d(e)});return}let t=c(e,f.narrow);W({profile:e,profileError:null,features:t,messagesLeftToday:e.messagesLeftToday}),t.OpenTickets&&qe(),t.ResumeLast&&t.History&&Je(),f.conversationId&&await dt(f.conversationId)},Xe=()=>(x||=Ye(),x),Ze=async e=>{let t=typeof e==`string`?e.trim():``,n=_.attachments.filter(e=>e.status===`Ready`);if(t===``&&n.length===0||_.streaming||_.attachments.some(e=>e.status===`Uploading`))return;let r=_.messages,i=null;if(_.editing){let e=_.messages.findIndex(e=>e.id===_.editing?.messageId),t=_.messages[e];if(!t?.stored)return;i=t.id,r=_.messages.slice(0,e)}let a=n.map(e=>Ie(e.key));await $({wireText:t===``?null:t,displayText:t,quickReplyId:null,replacesMessageId:i,repliesToMessageId:null,attachments:a},r,!0)},Qe=e=>{for(let t=_.messages.length-1;t>=0;t--){let n=_.messages[t];if(n?.parts.some(t=>t.kind===`QuickReplies`&&t.replies.includes(e)))return n}},$e=async e=>{if(e.action!==`Send`||R())return;if(e.id===`handoff.request`&&_.features.HumanHandoff&&_.conversationId!==null&&!_.handoffPending){await St();return}let t=Qe(e);await $({wireText:null,displayText:e.label,quickReplyId:e.id,replacesMessageId:null,repliesToMessageId:t?.stored&&_.conversationId!==null?t.id:null,attachments:[]},_.messages,!1)},et=async(e,t)=>{let n=await ze();await s.sendOtp(e,{...t,captchaToken:n})},tt=async(t,n,r=null)=>{if(_.streaming)return{ok:!1,errors:{},message:p.errorGeneric};let i=v,a=new u.AbortController,o=()=>i===v&&!a.signal.aborted;y=a,je(t,n);let c=t===_.handoffContactRequestId;W({streaming:!0,thinking:!0});try{let e=await ze();await s.answerInput(t,{values:n,codes:r,captchaToken:e,attribution:f.attribution?.()??null},{signal:a.signal,onEvent:e=>Z(e,`turn`,o)})}catch(t){return G(),W({thinking:!1,streaming:!1}),a.signal.aborted?{ok:!1,errors:{},message:p.errorGeneric}:t instanceof e&&t.code===`validation_failed`?{ok:!1,errors:t.errors??{},message:t.message}:t instanceof e&&t.code===`input_request_closed`?(await Q(),{ok:!1,errors:{},message:t.message}):{ok:!1,errors:{},message:d(t).message}}finally{y===a&&(y=null)}return await I,o()&&(G(),W({thinking:!1,streaming:!1}),f.onEvent?.(`inputSubmitted`,{requestId:t}),await Q(),c&&(W({handoffContactRequestId:null}),await St().catch(q))),{ok:!0}},nt=async e=>{let t=await s.confirmAction(e);Ke(t),f.onEvent?.(`chatActionConfirmed`,{actionId:t.actionId,kind:t.actionKind}),await Q()},rt=async(e,t)=>{Ke(await s.rejectAction(e,t)),await Q()},it=()=>{if(!_.streaming)return;K();let e=y;y=null,e?.abort(),W({messages:_.messages.filter(e=>!e.streaming),thinking:!1,streaming:!1,stopped:!0,steps:[],pending:null})},at=async()=>{if(_.streaming||_.turnError===null&&!_.stopped)return;let e=ce(_.messages,e=>e.author.kind===`Visitor`),t=_.messages[e];t!==void 0&&await $(ve(t),_.messages.slice(0,e),!1)},ot=async()=>{if(R())return;let e=ce(_.messages,e=>e.author.kind===`Visitor`&&e.stored),t=_.messages[e];t!==void 0&&await $({...ve(t),replacesMessageId:t.id},_.messages.slice(0,e),!1)},st=e=>{let t=_.messages.find(t=>t.id===e);t?.stored&&t.author.kind===`Visitor`&&(J(),W({editing:{messageId:e,text:le(t.parts)},attachments:[]}))},ct=()=>{_.editing&&(J(),W({editing:null,attachments:[]}))},lt=async e=>{let t=_.profile;if(!t||!_.features.Attachments)return;let n=t.limits,r=n.maxAttachments-_.attachments.filter(e=>e.status!==`Failed`).length,i=[],a=[];for(let t of e){let e=ue(t);xe+=1;let o=`file-${xe}`,s={key:o,fileName:e.fileName,contentType:e.contentType,length:e.length??0};r<=0?i.push({...s,status:`Failed`,progress:null,error:p.attachmentLimit(n.maxAttachments)}):e.length!==null&&e.length>n.maxFileBytes||!n.contentTypes.includes(e.contentType)?i.push({...s,status:`Failed`,progress:null,error:p.attachmentFailed}):(--r,i.push({...s,status:`Uploading`,progress:0,error:null}),a.push({key:o,file:t}))}W({attachments:[..._.attachments,...i]}),await Promise.all(a.map(({key:e,file:t})=>Le(e,t)))},ut=async e=>{let t=T.get(e);t&&(T.delete(e),t.abort());let n=w.has(e)?C.get(e):void 0;n&&await s.deleteAttachment(n.publicId),w.delete(e),C.delete(e),W({attachments:_.attachments.filter(t=>t.key!==e)})};async function dt(e){Fe();let t=v;W({messages:[],conversationId:null,loadError:null,loading:!0,editing:null,thinking:!1,streaming:!1,steps:[],turnError:null,stopped:!1});try{let n=await s.getConversation(e);if(t!==v)return;let r=n.messages.map(e=>oe(e,!0));V(),ke(r),W({messages:r,conversationId:n.publicId,title:n.title,conversationState:n.state,continuesConversationId:n.continuesConversationId})}catch(e){if(t!==v)return;W({loadError:d(e)})}finally{t===v&&W({loading:!1})}}let ft=async()=>{let e=_.lastConversation;e&&await dt(e.publicId)},pt=()=>{J(),Fe(),K(),V(),W({messages:[],conversationId:null,title:null,conversationState:`Open`,continuesConversationId:null,loadError:null,loading:!1,editing:null,attachments:[],thinking:!1,streaming:!1,steps:[],turnError:null,stopped:!1,pending:null}),_.features.OpenTickets&&qe()},mt=(e,t,n)=>{W({messages:Y(e,e=>({...e,rating:t,ratingNote:n}))})},ht=async(e,t,n)=>{let r=_.messages.find(t=>t.id===e);if(!r?.stored)throw Error(`Only a stored reply can be rated.`);let i={rating:r.rating,ratingNote:r.ratingNote},a=typeof n==`string`&&n.trim()?n.trim():null;mt(e,t,a);try{await s.rateMessage(e,{rating:t,note:a})}catch(t){throw mt(e,i.rating,i.ratingNote),t}f.onEvent?.(`rated`,{messageId:e,rating:t})},gt=e=>{let t=_.open,n=e?.trigger??`manual`,r=e?.draft,i={open:!0};typeof r==`string`&&r.trim()!==``&&(i.draft=r),!t&&n===`auto`&&h?.set(`wchat:auto-opened`,`1`),W(i),t||f.onEvent?.(`chatOpened`,{layout:f.layout??null,trigger:n})},_t=e=>{_.open&&(h?.set(`wchat:dismissed`,`1`),W({open:!1}),f.onEvent?.(`chatClosed`,{layout:f.layout??null,reason:e}))},vt=e=>{h?.set(`wchat:muted`,e?`1`:`0`),W({muted:e}),f.onEvent?.(`chatSoundToggled`,{muted:e})},yt=async e=>{R()||(e===_.handoffContactRequestId&&W({handoffContactRequestId:null}),f.onEvent?.(`chatLeadSkipped`,{requestId:e}),await $({wireText:null,displayText:p.skip,quickReplyId:`lead.skip`,replacesMessageId:null,repliesToMessageId:null,attachments:[]},_.messages,!1))},bt=async()=>{R()||(f.onEvent?.(`chatLeadCancelled`,{}),await $({wireText:null,displayText:p.cancel,quickReplyId:`lead.cancel`,replacesMessageId:null,repliesToMessageId:null,attachments:[]},_.messages,!1))},xt=async(e,t)=>{R()||_.messages.some(t=>t.parts.some(t=>t.kind===`Action`&&t.actionId===e))&&await $({wireText:null,displayText:p.editSomething,quickReplyId:`lead.edit:${t}`,replacesMessageId:null,repliesToMessageId:null,attachments:[]},_.messages,!1)},St=async t=>{if(!_.features.HumanHandoff)throw new e(`chat_feature_off`,{message:r.errorGeneric,status:403});let n=_.conversationId;if(n===null)throw new e(`conversation_required`,{message:r.errorGeneric});if(_.streaming||_.handoffPending)throw new e(`busy`,{message:r.errorGeneric});let i=new u.AbortController;j=i,W({handoffPending:!0}),f.onEvent?.(`chatHandoffRequested`,{conversationId:n});let a=null;try{a=pe((await s.requestHandoff({conversationId:n,reason:t??null},{signal:i.signal,onEvent:e=>Z(e,`handoff`,()=>!i.signal.aborted)})).parts)}catch(e){throw W({messages:_.messages.filter(e=>!e.streaming),handoffPending:!1}),e}finally{j===i&&(j=null)}W({handoffPending:!1,handoffContactRequestId:a}),await Q(),f.onEvent?.(`chatHandoff`,{destination:`person`})},Ct=()=>{let e=_.conversationId;if(!_.features.HumanHandoff||e===null||_.conversationState!==`WithAgent`)return;let t=Date.now();k!==null&&t-k<ne||(k=t,Promise.allSettled([s.sendTyping(e)]))},wt=e=>{we=e,U()},Tt=()=>{_.live===`Lost`&&Me()&&(H(null),U())},Et=e=>{if(f.reducedMotion?.()===!0)return re;let t=e.navigateAfterMs;if(typeof t==`number`&&Number.isFinite(t)&&t>=0)return t;let n=_.profile?.experience.pacing.handoffPauseMs;return typeof n==`number`&&Number.isFinite(n)?n:ie},Dt=()=>{B(),_.handoffPause&&W({handoffPause:!1})};return{client:s,getState:()=>_,subscribe:e=>(g.add(e),x||Xe(),()=>{g.delete(e)}),load:Xe,submit:Ze,chooseQuickReply:$e,answerInput:tt,sendOtp:et,confirmAction:nt,rejectAction:rt,stop:it,retry:at,regenerate:ot,startEdit:st,cancelEdit:ct,attach:lt,removeAttachment:ut,openConversation:dt,resumeLast:ft,newConversation:pt,rate:ht,open:gt,close:_t,setMuted:vt,skipField:yt,cancelLead:bt,editLeadField:xt,requestHandoff:St,notifyTyping:Ct,setLiveActive:wt,resumeLive:Tt,beginHandoff:(e,t)=>{_.handoffPause||(W({handoffPause:!0}),f.onEvent?.(`chatHandoff`,{destination:e.id}),A=u.setTimeout(()=>{A=null;try{t()}catch(e){Dt(),q(e)}},Et(e)))},endHandoffPause:Dt,consumeDraft:()=>{_.draft!==null&&W({draft:null})},loadAttachmentUrl:t=>{let n=F.get(t);if(n!==void 0)return n;let r=(async()=>{let n=u.createObjectUrl;if(!n)throw new e(`unsupported`,{message:p.errorGeneric});let r=await s.getAttachment(t);if(N)throw new e(`aborted`,{message:p.errorGeneric});let i=n(r);return P.add(i),i})();return F.set(t,r),r.catch(()=>{F.get(t)===r&&F.delete(t)}),r},reset:()=>{J(),K(),Fe(),x=null,I=Promise.resolve(),L=0,Ce.clear(),Se=null,V(),z(),B(),W(ye(h))},dispose:()=>{g.clear(),N=!0,v+=1;let e=y;y=null,e?.abort(),j?.abort(),j=null,B(),z(),H(null),J(),K();let t=u.revokeObjectUrl;for(let e of P)t?.(e);P.clear(),F.clear(),W({attachments:[],editing:null,agentTyping:null})}}},m=e=>{let t=-1;for(let n=e.length-1;n>=0;--n)if(e[n]?.parts.some(e=>e.kind===`Handoff`)){t=n;break}let n=/* @__PURE__ */ new Set;for(let r=0;r<t;r+=1){let t=e[r]?.id;t!==void 0&&n.add(t)}return n},h=(e,t)=>({get features(){return e.getState().features},labels:t.labels,get isLast(){let n=e.getState().messages;return n[n.length-1]?.id===t.messageId},get busy(){let t=e.getState();return t.streaming||t.thinking},get handoffPause(){return e.getState().handoffPause},get handoffSettled(){return m(e.getState().messages).has(t.messageId)},chooseQuickReply(t){e.chooseQuickReply(t)},skipInput(t){e.skipField(t)},cancelLead(){e.cancelLead()},answerInput:(t,n,r)=>e.answerInput(t,n,r),uploadInputFile:async(t,n)=>(await e.client.uploadAttachment(t,n?{onProgress:n}:{})).publicId,sendOtp:(t,n)=>e.sendOtp(t,n),confirmAction:t=>e.confirmAction(t),rejectAction:(t,n)=>e.rejectAction(t,n),requestHandoff:t=>e.requestHandoff(t),beginHandoff:(t,n)=>e.beginHandoff(t,n),readAttachment:t=>e.client.getAttachment(t),loadAttachmentUrl:t=>e.loadAttachmentUrl(t),...t.openAttachment?{openAttachment:t.openAttachment}:{},...t.openRecord?{openRecord:t.openRecord}:{},...t.openTicket?{openTicket:t.openTicket}:{},...t.attachmentUrl?{attachmentUrl:t.attachmentUrl}:{},...t.handoffHosts?{handoffHosts:t.handoffHosts}:{},...t.openCitation?{openCitation:t.openCitation}:{},...t.isCitation?{isCitation:t.isCitation}:{},...t.openTarget?{openTarget:t.openTarget}:{},...t.onNavigate?{onNavigate:t.onNavigate}:{}});export{p as createChatSession,h as createTurnApi,m as handoffSettledIds};
3
+ `),d=e=>e.flatMap(e=>e.kind===`File`?[{publicId:e.attachmentId,fileName:e.fileName,contentType:e.contentType,length:e.length}]:[]),de=e=>{let t=n(e);return{fileName:typeof t.name==`string`?t.name:``,contentType:typeof t.type==`string`?t.type:``,length:typeof t.size==`number`?t.size:null}},fe=(e,t)=>e.length===t.length&&e.every((e,n)=>{let r=t[n];return r!==void 0&&e.id===r.id&&e.label===r.label&&e.message===r.message}),pe=e=>{for(let t of e){if(!t.startsWith(`Enquiry type:`))continue;let e=t.slice(13).trim();return e===``?null:e}return null},me=e=>e.some(e=>e.kind===`Handoff`)?null:e.find(e=>e.kind===`InputRequest`)?.requestId??null,he=(e,t)=>e.some(e=>e.parts.some(e=>e.kind===`InputRequest`&&e.requestId===t&&(e.state===`Skipped`||e.state===`Expired`))),ge=(e,t)=>{if(t!==`WithAgent`)return null;for(let t=e.length-1;t>=0;--t){let n=e[t];if(n!==void 0){for(let e=n.parts.length-1;e>=0;--e){let t=n.parts[e];if(t?.kind===`Handoff`){if(t.state===`Left`||t.state===`Ended`)return null;if(t.state===`Joined`&&t.agent)return t.agent}}if(n.author.kind===`Agent`)return{displayName:n.author.displayName??``,avatarUrl:n.author.avatarUrl}}}return null},_e=(e,t)=>{(e.cursor===null||t>e.cursor)&&(e.cursor=t)},ve=(e,t)=>{let n=[];e!==``&&n.push({kind:`Text`,text:e});for(let e of t)n.push({kind:`File`,attachmentId:e.publicId,fileName:e.fileName,contentType:e.contentType,length:e.length});return n},ye=e=>{let t=ue(e.parts);return{wireText:t===``?null:t,displayText:t,quickReplyId:null,replacesMessageId:null,repliesToMessageId:null,attachments:d(e.parts)}},be=e=>({profile:null,profileError:null,features:s(),conversationId:null,conversationState:`Open`,title:null,continuesConversationId:null,messages:[],thinking:!1,steps:[],streaming:!1,loading:!1,loadError:null,turnError:null,stopped:!1,messagesLeftToday:null,editing:null,attachments:[],lastConversation:null,recentConversations:[],open:!1,muted:e?.get(`wchat:muted`)===`1`,greeting:null,starters:[],pending:null,agent:null,agentTyping:null,live:`Off`,handoffPending:!1,handoffContactRequestId:null,handoffPause:!1,openTickets:[],draft:null}),f=(s,d)=>{let f=i(d.labels),p=d.schedule??oe,m=d.prefs,h=d.recentConversations??0;if(!Number.isInteger(h)||h<0||h>5)throw RangeError(`recentConversations must be a whole number from 0 to 5; got ${h}.`);let g=/* @__PURE__ */ new Set,_=be(m),v=0,y=null,b=null,xe=0,Se=0,Ce=null,x=null,S=/* @__PURE__ */ new Map,C=/* @__PURE__ */ new Set,w=/* @__PURE__ */ new Map,T=/* @__PURE__ */ new Set,E=/* @__PURE__ */ new Map,D={name:null,email:null,phone:null},O=/* @__PURE__ */ new Set,k=null,A=null,j=null,M=null,N=null,we=!0,Te=!1,P=/* @__PURE__ */ new Set,F=/* @__PURE__ */ new Map,I=Promise.resolve(),L=0,Ee=()=>d.pathname?.()??l.location?.pathname??`/`,De=()=>d.reducedMotion?.()===!0||_.profile?.experience.motion===!1,R=()=>_.streaming||_.thinking,Oe=e=>{if(!e.profile)return{...e,greeting:null,starters:[]};let t=Ee(),n=e.lastConversation!==null,r=c(e.profile,{pathname:t,returning:n}).greeting,i=te(e.profile.start,{pathname:t,returning:n,behaviour:d.behaviour?.()??null,behaviourStarters:e.features.BehaviourStarters});return{...e,greeting:r,starters:fe(e.starters,i)?e.starters:i}},z=()=>{k!==null&&(l.clearTimeout(k),k=null)},ke=()=>{j!==null&&(l.clearTimeout(j),j=null)},Ae=e=>e.flatMap(e=>e.parts.flatMap(e=>e.kind===`Action`&&e.actionKind===`ChatLeadCapture`&&e.state===`Done`?[{actionId:e.actionId,leadType:pe(e.lines)}]:[])),B=()=>{D.name=null,D.email=null,D.phone=null,O.clear()},je=e=>{for(let t of Ae(e))O.add(t.actionId)},Me=()=>{for(let e of Ae(_.messages))O.has(e.actionId)||(O.add(e.actionId),d.onEvent?.(`leadSubmitted`,{conversationId:_.conversationId,fields:{name:D.name,email:D.email,phone:D.phone},leadType:e.leadType}))},Ne=(e,t)=>{let n=_.messages.flatMap(e=>e.parts).find(t=>t.kind===`InputRequest`&&t.requestId===e);if(n)for(let e of n.fields){let n=t[e.key];typeof n==`string`&&n.trim()!==``&&(e.type===`Email`?D.email=n.trim():e.type===`Phone`?D.phone=n.trim():(e.type===`Name`||e.key.toLowerCase()===`name`)&&(D.name=n.trim()))}},V=e=>{let t=N;t!==null&&(N=null,t.handle?.stop(),e!==null&&H({live:e}))},Pe=()=>!Te&&we&&_.features.HumanHandoff&&_.conversationId!==null&&(_.conversationState===`WaitingForAgent`||_.conversationState===`WithAgent`),Fe=()=>{if(!Pe()){N!==null&&V(`Off`);return}let e=_.conversationId;if(e===null||N!==null&&N.conversationId===e)return;V(null);let t={conversationId:e,cursor:null,handle:null};N=t;let n=a({watch:(n,r,i)=>s.watchConversation(e,{afterSequence:n,signal:r,onCursor:e=>_e(t,e),onEvent:e=>{i(),N===t&&(e.name===`messageCompleted`&&_e(t,e.data.message.sequence),Z(e,`live`,()=>N===t))}}),beforeReconnect:()=>Q(),getCursor:()=>{let e=t.cursor;for(let t of _.messages)t.sequence!==null&&(e===null||t.sequence>e)&&(e=t.sequence);return e},onStatus:e=>{N===t&&_.live!==e&&H({live:e})},onError:e=>q(e)});t.handle=n,N!==t&&n.stop()},H=e=>{let t={..._,...e};_.conversationState===`WithAgent`&&t.conversationState!==`WithAgent`&&t.agentTyping!==null&&(z(),t.agentTyping=null),(e.messages!==void 0||e.conversationState!==void 0)&&(t.agent=ge(t.messages,t.conversationState)),e.messages!==void 0&&t.handoffContactRequestId!==null&&he(t.messages,t.handoffContactRequestId)&&(t.handoffContactRequestId=null),_=Oe(t);for(let e of g)e();e.messages!==void 0&&Me(),Fe()},U=(e,t)=>H({attachments:_.attachments.map(n=>n.key===e?{...n,...t}:n)}),W=()=>{if(S.size===0)return;let e=[...S.values()];S.clear(),H({messages:_.messages.map(t=>{let n=e.filter(e=>e.messageId===t.id);if(n.length===0)return t;let r=t.parts.map((e,t)=>{let r=n.filter(e=>e.index===t).map(e=>e.text).join(``);return e.kind===`Text`&&r!==``?{...e,text:e.text+r}:e});return{...t,parts:r}})})},G=()=>{S.clear(),b?.(),b=null},Ie=(e,t,n)=>{let r=`${e}#${t}`,i=S.get(r);S.set(r,{messageId:e,index:t,text:(i?.text??``)+n}),b||=p(()=>{b=null,W()})},K=()=>{W(),v+=1,y?.abort(),y=null},q=e=>{if(d.onError)d.onError(e);else throw e},J=()=>{for(let e of E.values())e.abort();E.clear();for(let e of T){let t=w.get(e);t&&s.deleteAttachment(t.publicId).catch(q)}T.clear(),w.clear()},Le=e=>{let t=w.get(e);if(!t)throw Error(`No uploaded file for composer attachment ${e}.`);return t},Re=async(e,t)=>{let n=new l.AbortController;E.set(e,n);let r;try{r=await s.uploadAttachment(t,{signal:n.signal,onProgress:t=>{E.get(e)===n&&U(e,{progress:t})}})}catch{E.get(e)===n&&(E.delete(e),U(e,{status:`Failed`,progress:null,error:f.attachmentFailed}));return}E.get(e)===n?(E.delete(e),w.set(e,r),T.add(e),U(e,{status:`Ready`,progress:null})):s.deleteAttachment(r.publicId).catch(q)},ze=e=>{let t={...n(d.pageContext?.()),path:Ee(),behaviour:d.behaviour?.()??null};return e&&(t.attribution=d.attribution?.()??null),t},Be=async()=>{let t=_.profile?.captcha;if(!t)return null;if(t.testToken)return t.testToken;if(!d.getCaptchaToken||t.mode===`Off`&&!t.siteKey)return null;let n;try{n=await d.getCaptchaToken(t.action)}catch(t){throw d.onError?.(t),new e(`captcha_unavailable`,{message:f.captchaUnavailable,cause:t})}if(!n)throw new e(`captcha_unavailable`,{message:f.captchaUnavailable});return n},Ve=(e,t,n)=>{let r=ce(_.messages,se(e,!1));H(n?{messages:r,messagesLeftToday:t??_.messagesLeftToday,steps:[],thinking:!1}:{messages:r})},He=e=>{let n=_.profile?.experience.pacing;return!n||C.has(e.publicId)||e.author.kind!==`Assistant`&&e.author.kind!==`Script`?0:o(t(e.parts),n,De())},Ue=(e,t,n,r,i)=>{L+=1,H({pending:{typing:!0,authorKind:e.author.kind}}),I=I.then(()=>new Promise(e=>l.setTimeout(e,n))).then(()=>{--L,r()&&Ve(e,t,i),L===0&&H({pending:null})})},We=(e,t,n)=>{let r=[...e];return r[t]=n,r},Y=(e,t)=>_.messages.map(n=>n.id===e?t(n):n),X=e=>_.messages.some(t=>t.id===e),Ge=()=>{z(),_.agentTyping!==null&&H({agentTyping:null})},Ke=e=>{z(),k=l.setTimeout(()=>{k=null,H({agentTyping:null})},ne),H({agentTyping:{displayName:e}})},Z=(e,t,n)=>{if(!n())return;let r=t===`turn`;if(e.name===`partDelta`)C.add(e.data.messageId),Ie(e.data.messageId,e.data.index,e.data.text);else switch(W(),e.name){case`messageStarted`:{let t=e.data.message;if(t.author.kind===`Agent`&&Ge(),X(t.publicId))break;H({messages:[..._.messages,{id:t.publicId,author:t.author,createdDateTimeUtc:t.createdDateTimeUtc,parts:[...t.parts],sequence:t.sequence,rating:t.rating,ratingNote:t.ratingNote,streaming:!0,stored:!1,restored:!1}]});break}case`partStarted`:{let{messageId:t,index:n,part:i}=e.data;if(!X(t))break;H({messages:Y(t,e=>({...e,parts:We(e.parts,n,i)})),...r?{thinking:!1}:{}});break}case`partCompleted`:{let{messageId:t,index:n,part:r}=e.data;if(!X(t))break;H({messages:Y(t,e=>({...e,parts:We(e.parts,n,r)}))});break}case`messageReset`:{let{messageId:t}=e.data;if(!X(t))break;for(let e of[...S.keys()])S.get(e)?.messageId===t&&S.delete(e);H({messages:Y(t,e=>({...e,parts:[]})),...r?{thinking:!0,steps:[]}:{}});break}case`step`:{if(!r)break;let t=e.data.label;_.steps[_.steps.length-1]!==t&&H({steps:[..._.steps,t]});break}case`messageCompleted`:{let{message:t,messagesLeftToday:i}=e.data;t.author.kind===`Agent`&&Ge();let a=He(t);a>0||L>0?Ue(t,i,a,n,r):Ve(t,i,r);break}case`conversationUpdated`:{let t=e.data;H({conversationId:t.conversationId,conversationState:t.state,title:t.title,continuesConversationId:t.continuesConversationId});break}case`typing`:e.data.authorKind===`Agent`&&Ke(e.data.displayName)}},Q=async()=>{let e=_.conversationId;if(e===null)return;let t=v;try{let n=await s.getConversation(e);if(t!==v)return;let r=new Set(_.messages.filter(e=>e.restored).map(e=>e.id));H({messages:n.messages.map(e=>se(e,r.has(e.publicId))),title:n.title,conversationState:n.state,continuesConversationId:n.continuesConversationId})}catch(e){q(e)}},$=async(e,t,n)=>{let r=v,i=new l.AbortController,a=()=>r===v&&!i.signal.aborted;y=i;let o=_.conversationId===null;xe+=1;let ee={id:`local-${xe}`,author:{kind:`Visitor`,displayName:null,avatarUrl:null},createdDateTimeUtc:(/* @__PURE__ */ new Date()).toISOString(),parts:ve(e.displayText,e.attachments),sequence:null,rating:null,ratingNote:null,streaming:!1,stored:!1,restored:!1};n&&(T.clear(),w.clear()),H({messages:[...t,ee],thinking:!0,streaming:!0,steps:[],turnError:null,stopped:!1,...n?{editing:null,attachments:[]}:{}});try{let t=await Be();await s.send({conversationId:_.conversationId,text:e.wireText,quickReplyId:e.quickReplyId,attachmentIds:e.attachments.map(e=>e.publicId),replacesMessageId:e.replacesMessageId,repliesToMessageId:e.repliesToMessageId,pageContext:ze(o),captchaToken:t},{signal:i.signal,onEvent:e=>Z(e,`turn`,a)})}catch(e){if(W(),!a())return;let t=u(e);H({messages:_.messages.filter(e=>!e.streaming),thinking:!1,streaming:!1,turnError:t,...t.code===`daily_limit`?{messagesLeftToday:0}:{},...t.code===`conversation_not_found`?{conversationId:null}:{}});return}finally{y===i&&(y=null)}if(await I,!a())return;W(),H({thinking:!1,streaming:!1}),await Q();let c=_.conversationId;o&&c!==null&&c!==Ce&&(Ce=c,d.onEvent?.(`chatStarted`,{conversationId:c}))},qe=e=>H({messages:_.messages.map(t=>({...t,parts:t.parts.map(t=>t.kind===`Action`&&t.actionId===e.actionId?{...t,state:e.state,decidedDateTimeUtc:e.decidedDateTimeUtc,note:e.note}:t)}))}),Je=async()=>{try{H({openTickets:await s.listOpenTickets()})}catch(e){q(e)}},Ye=async()=>{try{let e=await s.listConversations({page:1,pageSize:Math.max(1,h)});H({lastConversation:e.items[0]??null,recentConversations:e.items.slice(0,h)})}catch(e){q(e)}},Xe=async()=>{let e;try{e=await s.getProfile(d.screen)}catch(e){H({profileError:u(e)});return}let t=ee(e,d.narrow);H({profile:e,profileError:null,features:t,messagesLeftToday:e.messagesLeftToday}),t.OpenTickets&&Je(),t.History&&(t.ResumeLast||h>0)&&Ye(),d.conversationId&&await ft(d.conversationId)},Ze=()=>(x||=Xe(),x),Qe=async e=>{let t=typeof e==`string`?e.trim():``,n=_.attachments.filter(e=>e.status===`Ready`);if(t===``&&n.length===0||_.streaming||_.attachments.some(e=>e.status===`Uploading`))return;let r=_.messages,i=null;if(_.editing){let e=_.messages.findIndex(e=>e.id===_.editing?.messageId),t=_.messages[e];if(!t?.stored)return;i=t.id,r=_.messages.slice(0,e)}let a=n.map(e=>Le(e.key));await $({wireText:t===``?null:t,displayText:t,quickReplyId:null,replacesMessageId:i,repliesToMessageId:null,attachments:a},r,!0)},$e=e=>{for(let t=_.messages.length-1;t>=0;t--){let n=_.messages[t];if(n?.parts.some(t=>t.kind===`QuickReplies`&&t.replies.includes(e)))return n}},et=async e=>{if(e.action!==`Send`||R())return;if(e.id===`handoff.request`&&_.features.HumanHandoff&&_.conversationId!==null&&!_.handoffPending){await Ct();return}let t=$e(e);await $({wireText:null,displayText:e.label,quickReplyId:e.id,replacesMessageId:null,repliesToMessageId:t?.stored&&_.conversationId!==null?t.id:null,attachments:[]},_.messages,!1)},tt=async(e,t)=>{let n=await Be();await s.sendOtp(e,{...t,captchaToken:n})},nt=async(t,n,r=null)=>{if(_.streaming)return{ok:!1,errors:{},message:f.errorGeneric};let i=v,a=new l.AbortController,o=()=>i===v&&!a.signal.aborted;y=a,Ne(t,n);let ee=t===_.handoffContactRequestId;H({streaming:!0,thinking:!0});try{let e=await Be();await s.answerInput(t,{values:n,codes:r,captchaToken:e,attribution:d.attribution?.()??null},{signal:a.signal,onEvent:e=>Z(e,`turn`,o)})}catch(t){return W(),H({thinking:!1,streaming:!1}),a.signal.aborted?{ok:!1,errors:{},message:f.errorGeneric}:t instanceof e&&t.code===`validation_failed`?{ok:!1,errors:t.errors??{},message:t.message}:t instanceof e&&t.code===`input_request_closed`?(await Q(),{ok:!1,errors:{},message:t.message}):{ok:!1,errors:{},message:u(t).message}}finally{y===a&&(y=null)}return await I,o()&&(W(),H({thinking:!1,streaming:!1}),d.onEvent?.(`inputSubmitted`,{requestId:t}),await Q(),ee&&(H({handoffContactRequestId:null}),await Ct().catch(q))),{ok:!0}},rt=async e=>{let t=await s.confirmAction(e);qe(t),d.onEvent?.(`chatActionConfirmed`,{actionId:t.actionId,kind:t.actionKind}),await Q()},it=async(e,t)=>{qe(await s.rejectAction(e,t)),await Q()},at=()=>{if(!_.streaming)return;G();let e=y;y=null,e?.abort(),H({messages:_.messages.filter(e=>!e.streaming),thinking:!1,streaming:!1,stopped:!0,steps:[],pending:null})},ot=async()=>{if(_.streaming||_.turnError===null&&!_.stopped)return;let e=le(_.messages,e=>e.author.kind===`Visitor`),t=_.messages[e];t!==void 0&&await $(ye(t),_.messages.slice(0,e),!1)},st=async()=>{if(R())return;let e=le(_.messages,e=>e.author.kind===`Visitor`&&e.stored),t=_.messages[e];t!==void 0&&await $({...ye(t),replacesMessageId:t.id},_.messages.slice(0,e),!1)},ct=e=>{let t=_.messages.find(t=>t.id===e);t?.stored&&t.author.kind===`Visitor`&&(J(),H({editing:{messageId:e,text:ue(t.parts)},attachments:[]}))},lt=()=>{_.editing&&(J(),H({editing:null,attachments:[]}))},ut=async e=>{let t=_.profile;if(!t||!_.features.Attachments)return;let n=t.limits,r=n.maxAttachments-_.attachments.filter(e=>e.status!==`Failed`).length,i=[],a=[];for(let t of e){let e=de(t);Se+=1;let o=`file-${Se}`,s={key:o,fileName:e.fileName,contentType:e.contentType,length:e.length??0};r<=0?i.push({...s,status:`Failed`,progress:null,error:f.attachmentLimit(n.maxAttachments)}):e.length!==null&&e.length>n.maxFileBytes||!n.contentTypes.includes(e.contentType)?i.push({...s,status:`Failed`,progress:null,error:f.attachmentFailed}):(--r,i.push({...s,status:`Uploading`,progress:0,error:null}),a.push({key:o,file:t}))}H({attachments:[..._.attachments,...i]}),await Promise.all(a.map(({key:e,file:t})=>Re(e,t)))},dt=async e=>{let t=E.get(e);t&&(E.delete(e),t.abort());let n=T.has(e)?w.get(e):void 0;n&&await s.deleteAttachment(n.publicId),T.delete(e),w.delete(e),H({attachments:_.attachments.filter(t=>t.key!==e)})};async function ft(e){K();let t=v;H({messages:[],conversationId:null,loadError:null,loading:!0,editing:null,thinking:!1,streaming:!1,steps:[],turnError:null,stopped:!1});try{let n=await s.getConversation(e);if(t!==v)return;let r=n.messages.map(e=>se(e,!0));B(),je(r),H({messages:r,conversationId:n.publicId,title:n.title,conversationState:n.state,continuesConversationId:n.continuesConversationId})}catch(e){if(t!==v)return;H({loadError:u(e)})}finally{t===v&&H({loading:!1})}}let pt=async()=>{let e=_.lastConversation;e&&await ft(e.publicId)},mt=()=>{J(),K(),G(),B(),H({messages:[],conversationId:null,title:null,conversationState:`Open`,continuesConversationId:null,loadError:null,loading:!1,editing:null,attachments:[],thinking:!1,streaming:!1,steps:[],turnError:null,stopped:!1,pending:null}),_.features.OpenTickets&&Je()},ht=(e,t,n)=>{H({messages:Y(e,e=>({...e,rating:t,ratingNote:n}))})},gt=async(e,t,n)=>{let r=_.messages.find(t=>t.id===e);if(!r?.stored)throw Error(`Only a stored reply can be rated.`);let i={rating:r.rating,ratingNote:r.ratingNote},a=typeof n==`string`&&n.trim()?n.trim():null;ht(e,t,a);try{await s.rateMessage(e,{rating:t,note:a})}catch(t){throw ht(e,i.rating,i.ratingNote),t}d.onEvent?.(`rated`,{messageId:e,rating:t})},_t=e=>{let t=_.open,n=e?.trigger??`manual`,r=e?.draft,i={open:!0};typeof r==`string`&&r.trim()!==``&&(i.draft=r),!t&&n===`auto`&&m?.set(`wchat:auto-opened`,`1`),H(i),t||d.onEvent?.(`chatOpened`,{layout:d.layout??null,trigger:n})},vt=e=>{_.open&&(m?.set(`wchat:dismissed`,`1`),H({open:!1}),d.onEvent?.(`chatClosed`,{layout:d.layout??null,reason:e}))},yt=e=>{m?.set(`wchat:muted`,e?`1`:`0`),H({muted:e}),d.onEvent?.(`chatSoundToggled`,{muted:e})},bt=async e=>{R()||(e===_.handoffContactRequestId&&H({handoffContactRequestId:null}),d.onEvent?.(`chatLeadSkipped`,{requestId:e}),await $({wireText:null,displayText:f.skip,quickReplyId:`lead.skip`,replacesMessageId:null,repliesToMessageId:null,attachments:[]},_.messages,!1))},xt=async()=>{R()||(d.onEvent?.(`chatLeadCancelled`,{}),await $({wireText:null,displayText:f.cancel,quickReplyId:`lead.cancel`,replacesMessageId:null,repliesToMessageId:null,attachments:[]},_.messages,!1))},St=async(e,t)=>{R()||_.messages.some(t=>t.parts.some(t=>t.kind===`Action`&&t.actionId===e))&&await $({wireText:null,displayText:f.editSomething,quickReplyId:`lead.edit:${t}`,replacesMessageId:null,repliesToMessageId:null,attachments:[]},_.messages,!1)},Ct=async t=>{if(!_.features.HumanHandoff)throw new e(`chat_feature_off`,{message:r.errorGeneric,status:403});let n=_.conversationId;if(n===null)throw new e(`conversation_required`,{message:r.errorGeneric});if(_.streaming||_.handoffPending)throw new e(`busy`,{message:r.errorGeneric});let i=new l.AbortController;M=i,H({handoffPending:!0}),d.onEvent?.(`chatHandoffRequested`,{conversationId:n});let a=null;try{a=me((await s.requestHandoff({conversationId:n,reason:t??null},{signal:i.signal,onEvent:e=>Z(e,`handoff`,()=>!i.signal.aborted)})).parts)}catch(e){throw H({messages:_.messages.filter(e=>!e.streaming),handoffPending:!1}),e}finally{M===i&&(M=null)}H({handoffPending:!1,handoffContactRequestId:a}),await Q(),d.onEvent?.(`chatHandoff`,{destination:`person`})},wt=()=>{let e=_.conversationId;if(!_.features.HumanHandoff||e===null||_.conversationState!==`WithAgent`)return;let t=Date.now();A!==null&&t-A<re||(A=t,Promise.allSettled([s.sendTyping(e)]))},Tt=e=>{we=e,Fe()},Et=()=>{_.live===`Lost`&&Pe()&&(V(null),Fe())},Dt=e=>{if(d.reducedMotion?.()===!0)return ie;let t=e.navigateAfterMs;if(typeof t==`number`&&Number.isFinite(t)&&t>=0)return t;let n=_.profile?.experience.pacing.handoffPauseMs;return typeof n==`number`&&Number.isFinite(n)?n:ae},Ot=()=>{ke(),_.handoffPause&&H({handoffPause:!1})};return{client:s,getState:()=>_,subscribe:e=>(g.add(e),x||Ze(),()=>{g.delete(e)}),load:Ze,submit:Qe,chooseQuickReply:et,answerInput:nt,sendOtp:tt,confirmAction:rt,rejectAction:it,stop:at,retry:ot,regenerate:st,startEdit:ct,cancelEdit:lt,attach:ut,removeAttachment:dt,openConversation:ft,resumeLast:pt,newConversation:mt,rate:gt,open:_t,close:vt,setMuted:yt,skipField:bt,cancelLead:xt,editLeadField:St,requestHandoff:Ct,notifyTyping:wt,setLiveActive:Tt,resumeLive:Et,beginHandoff:(e,t)=>{_.handoffPause||(H({handoffPause:!0}),d.onEvent?.(`chatHandoff`,{destination:e.id}),j=l.setTimeout(()=>{j=null;try{t()}catch(e){Ot(),q(e)}},Dt(e)))},endHandoffPause:Ot,consumeDraft:()=>{_.draft!==null&&H({draft:null})},loadAttachmentUrl:t=>{let n=F.get(t);if(n!==void 0)return n;let r=(async()=>{let n=l.createObjectUrl;if(!n)throw new e(`unsupported`,{message:f.errorGeneric});let r=await s.getAttachment(t);if(Te)throw new e(`aborted`,{message:f.errorGeneric});let i=n(r);return P.add(i),i})();return F.set(t,r),r.catch(()=>{F.get(t)===r&&F.delete(t)}),r},reset:()=>{J(),G(),K(),x=null,I=Promise.resolve(),L=0,C.clear(),Ce=null,B(),z(),ke(),H(be(m))},dispose:()=>{g.clear(),Te=!0,v+=1;let e=y;y=null,e?.abort(),M?.abort(),M=null,ke(),z(),V(null),J(),G();let t=l.revokeObjectUrl;for(let e of P)t?.(e);P.clear(),F.clear(),H({attachments:[],editing:null,agentTyping:null})}}},p=e=>{let t=-1;for(let n=e.length-1;n>=0;--n)if(e[n]?.parts.some(e=>e.kind===`Handoff`)){t=n;break}let n=/* @__PURE__ */ new Set;for(let r=0;r<t;r+=1){let t=e[r]?.id;t!==void 0&&n.add(t)}return n},m=(e,t)=>({get features(){return e.getState().features},labels:t.labels,get isLast(){let n=e.getState().messages;return n[n.length-1]?.id===t.messageId},get busy(){let t=e.getState();return t.streaming||t.thinking},get handoffPause(){return e.getState().handoffPause},get handoffSettled(){return p(e.getState().messages).has(t.messageId)},chooseQuickReply(t){e.chooseQuickReply(t)},skipInput(t){e.skipField(t)},cancelLead(){e.cancelLead()},answerInput:(t,n,r)=>e.answerInput(t,n,r),uploadInputFile:async(t,n)=>(await e.client.uploadAttachment(t,n?{onProgress:n}:{})).publicId,sendOtp:(t,n)=>e.sendOtp(t,n),confirmAction:t=>e.confirmAction(t),rejectAction:(t,n)=>e.rejectAction(t,n),requestHandoff:t=>e.requestHandoff(t),beginHandoff:(t,n)=>e.beginHandoff(t,n),readAttachment:t=>e.client.getAttachment(t),loadAttachmentUrl:t=>e.loadAttachmentUrl(t),...t.openAttachment?{openAttachment:t.openAttachment}:{},...t.openRecord?{openRecord:t.openRecord}:{},...t.openTicket?{openTicket:t.openTicket}:{},...t.attachmentUrl?{attachmentUrl:t.attachmentUrl}:{},...t.handoffHosts?{handoffHosts:t.handoffHosts}:{},...t.openCitation?{openCitation:t.openCitation}:{},...t.isCitation?{isCitation:t.isCitation}:{},...t.openTarget?{openTarget:t.openTarget}:{},...t.onNavigate?{onNavigate:t.onNavigate}:{}});export{f as createChatSession,m as createTurnApi,p as handoffSettledIds};
@@ -31,6 +31,7 @@ export interface ChatLabels {
31
31
  emptyTitle: string;
32
32
  starters: string;
33
33
  resumeLast: string;
34
+ recentChats: string;
34
35
  nudgeDismiss: string;
35
36
  composer: string;
36
37
  placeholder: string;
@@ -19,6 +19,20 @@ export type ChatInputMark = "None" | "Avatar";
19
19
  export type ChatReplyAvatars = "None" | "First" | "Every";
20
20
  /** Drift slowly turns the gradient of the header, greeting and reply orbs; it applies only while no avatar picture is set. */
21
21
  export type ChatAvatarMotion = "Still" | "Drift";
22
+ /** Stacked puts each footer part on its own line; Inline runs them together as one centred paragraph. */
23
+ export type ChatFooterLayout = "Stacked" | "Inline";
24
+ /** Hide drops the footer disclaimer line; the privacy link, assurance text and reCAPTCHA notice still show. */
25
+ export type ChatFooterDisclaimer = "Show" | "Hide";
26
+ /** What draws the ask box edge: the plain border, or the chat gradient. */
27
+ export type ChatInputEdge = "None" | "Gradient";
28
+ /** How the ask box placeholder is drawn: plain muted text, or filled with the chat gradient. */
29
+ export type ChatInputPlaceholder = "Plain" | "Gradient";
30
+ /** Whether the ask box edge sweeps while a reply is thinking or streaming. */
31
+ export type ChatInputBusyEdge = "Off" | "Sweep";
32
+ /** How the starter questions are laid out: wrapping chips, or full-width rows with an icon. */
33
+ export type ChatStartersStyle = "Chips" | "Rows";
34
+ /** The most recent chats a welcome screen can list. */
35
+ export declare const CHAT_RECENT_ROWS_MAX = 5;
22
36
  export interface ChatLook {
23
37
  launcher: {
24
38
  style: ChatLauncherStyle;
@@ -54,6 +68,20 @@ export interface ChatLook {
54
68
  sendReveal: ChatSendReveal;
55
69
  sendIcon: string;
56
70
  mark: ChatInputMark;
71
+ edge: ChatInputEdge;
72
+ placeholder: ChatInputPlaceholder;
73
+ busyEdge: ChatInputBusyEdge;
74
+ };
75
+ /** The starter questions on the empty welcome screen, on the web surfaces; the phone ignores it. */
76
+ /** recentRows lists that many of the visitor's recent chats under the starters, 0 to 5; 0 lists none. */
77
+ starters: {
78
+ style: ChatStartersStyle;
79
+ recentRows: number;
80
+ };
81
+ /** The lines under the composer on the web surfaces (the elements and React); the phone footer ignores it. */
82
+ footer: {
83
+ layout: ChatFooterLayout;
84
+ disclaimer: ChatFooterDisclaimer;
57
85
  };
58
86
  avoid: {
59
87
  liftSelectors: string[];
@@ -13,7 +13,7 @@ export declare const resolveStart: (profile: ChatProfileView, { pathname, return
13
13
  };
14
14
  export declare const resolveNudge: (profile: ChatProfileView, features: Readonly<Record<ChatFeature, boolean>>) => ChatNudge | null;
15
15
  export declare const showsCaptchaNote: (profile: ChatProfileView) => boolean;
16
- export declare const LOADER_STYLES: readonly ["Steps", "Phrases", "Orb", "Skeleton"];
16
+ export declare const LOADER_STYLES: readonly ["Steps", "Phrases", "Orb", "Skeleton", "PulseAndDots"];
17
17
  export type ChatLoaderStyle = (typeof LOADER_STYLES)[number];
18
18
  export interface ChatLoaderView {
19
19
  label: string;
@@ -59,6 +59,8 @@ export interface ChatSessionState {
59
59
  editing: ChatEditing | null;
60
60
  attachments: ComposerAttachment[];
61
61
  lastConversation: ChatConversationSummary | null;
62
+ /** The newest conversations, up to the recentConversations option; empty when that option is 0. */
63
+ recentConversations: ChatConversationSummary[];
62
64
  open: boolean;
63
65
  muted: boolean;
64
66
  greeting: string | null;
@@ -97,6 +99,8 @@ export interface ChatSessionOptions {
97
99
  onEvent?: (name: string, data: Record<string, unknown>) => void;
98
100
  onError?: (error: unknown) => void;
99
101
  labels?: Partial<ChatLabels>;
102
+ /** How many recent conversations the welcome screen lists, 0 to 5; 0, the default, reads only the last one. */
103
+ recentConversations?: number;
100
104
  }
101
105
  export interface ChatSession {
102
106
  readonly client: ChatClient;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webority/chat-core",
3
- "version": "0.161.0",
3
+ "version": "0.162.0",
4
4
  "description": "The headless Webority Chat engine: the client over the chat routes, the session state machine over message parts, the stream reader, profile resolution with screen narrowing, the default English labels and a fixture client for sandboxes and tests. No DOM and no UI.",
5
5
  "license": "SEE LICENSE IN LICENSE.txt",
6
6
  "type": "module",
@@ -26,10 +26,10 @@
26
26
  },
27
27
  "sideEffects": false,
28
28
  "peerDependencies": {
29
- "@webority/markdown-core": "^0.191.0"
29
+ "@webority/markdown-core": "^0.191.3"
30
30
  },
31
31
  "devDependencies": {
32
- "@webority/markdown-core": "0.191.0",
32
+ "@webority/markdown-core": "0.191.3",
33
33
  "typescript": "^7.0.2",
34
34
  "vite": "^8.1.6",
35
35
  "vitest": "5.1.0"