@webority/chat-core 0.168.0 → 0.170.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.
@@ -0,0 +1 @@
1
+ var e=[`disclaimer`,`privacy`,`assurance`,`captcha`];function t(e,t){if(!t||t.length===0)return[...e];let n=/* @__PURE__ */ new Set,r=[];for(let i of t){if(n.has(i))continue;n.add(i);let t=e.find(e=>e.name===i);t&&r.push(t)}return[...r,...e.filter(e=>!n.has(e.name))]}export{e as CHAT_FOOTER_PARTS,t as orderFooterParts};
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,isSafePrivacyUrl as F}from"./links.js";import{CHAT_RECENT_ROWS_MAX as I,defaultChatLook as L,mergeLook as R}from"./look.js";import{pacingDelayMs as z}from"./pacing.js";import{CHAT_FEATURES as B,LOADER_STYLES as V,emptyFeatures as H,featureRecord as U,loaderView as W,resolveFeatures as G,resolveNudge as K,resolveStart as q,showsCaptchaNote as J}from"./profile.js";import{provideRuntimeCrypto as Y}from"./runtime.js";import{createChatSession as X,createTurnApi as Z,handoffSettledIds as Q}from"./session.js";import{CHAT_SPEECH_TOKEN_MARGIN_MS as $,ChatSpeechError as ee,createSpeechTokenSource as te}from"./speech.js";import{humanizeService as ne,selectStarters as re}from"./starters.js";import{createSseParser as ie,createStreamReader as ae}from"./stream.js";import{buildTranscript as oe,transcriptToText as se}from"./transcript.js";import{formatClipTime as ce,voiceClipBars as le}from"./voiceClip.js";export{c as CHAT_CONTRACT_VERSION,B as CHAT_FEATURES,l as CHAT_HANDOFF_REQUEST_ID,I as CHAT_RECENT_ROWS_MAX,$ as CHAT_SPEECH_TOKEN_MARGIN_MS,t as ChatApiError,i as ChatDecodeError,ee 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,V as LOADER_STYLES,oe as buildTranscript,n as createChatClient,X as createChatSession,u as createConversationList,m as createDictation,g as createExplain,b as createFixtureClient,te as createSpeechTokenSource,ie as createSseParser,ae as createStreamReader,Z as createTurnApi,o as decodeChatConversationView,x as decodeChatFixture,s as decodeChatMessageView,a as decodeChatPart,d as decodeChatProfileView,h as decodeChatStreamEvent,L as defaultChatLook,H as emptyFeatures,U as featureRecord,S as formatChatDate,C as formatChatDateTime,w as formatChatDay,T as formatChatValue,ce as formatClipTime,_ as formatFigure,E as formatFileSize,Q as handoffSettledIds,ne as humanizeService,O as isHandoffTarget,N as isSafeActionHref,P as isSafeLinkUrl,F as isSafePrivacyUrl,W as loaderView,M as mergeLabels,R as mergeLook,D as messagePlainText,r as newIdempotencyKey,z as pacingDelayMs,Y as provideRuntimeCrypto,G as resolveFeatures,K as resolveNudge,q as resolveStart,re as selectStarters,J as showsCaptchaNote,e as sniffAudioType,v as toFigureRuns,y as toFigureText,se as transcriptToText,le 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{CHAT_FOOTER_PARTS as S,orderFooterParts as C}from"./footerOrder.js";import{formatChatDate as w,formatChatDateTime as T,formatChatDay as E,formatChatValue as D,formatFileSize as O,messagePlainText as k}from"./format.js";import{isHandoffTarget as A}from"./handoff.js";import{IDLE_CHAT_SESSION as j,IDLE_CHAT_STATE as M}from"./idleSession.js";import{DEFAULT_CHAT_LABELS as N,mergeLabels as P}from"./labels.js";import{isSafeActionHref as F,isSafeLinkUrl as I,isSafePrivacyUrl as L}from"./links.js";import{CHAT_RECENT_ROWS_CEILING as R,CHAT_RECENT_ROWS_MAX as z,defaultChatLook as B,mergeLook as V,unknownLookNames as H}from"./look.js";import{pacingDelayMs as U}from"./pacing.js";import{CHAT_FEATURES as W,LOADER_STYLES as G,emptyFeatures as K,featureRecord as q,loaderView as J,resolveFeatures as Y,resolveNudge as X,resolveStart as Z,showsCaptchaNote as Q}from"./profile.js";import{provideRuntimeCrypto as $}from"./runtime.js";import{createChatSession as ee,createTurnApi as te,handoffSettledIds as ne}from"./session.js";import{CHAT_SPEECH_TOKEN_MARGIN_MS as re,ChatSpeechError as ie,createSpeechTokenSource as ae}from"./speech.js";import{humanizeService as oe,selectStarters as se}from"./starters.js";import{createSseParser as ce,createStreamReader as le}from"./stream.js";import{buildTranscript as ue,transcriptToText as de}from"./transcript.js";import{formatClipTime as fe,voiceClipBars as pe}from"./voiceClip.js";export{c as CHAT_CONTRACT_VERSION,W as CHAT_FEATURES,S as CHAT_FOOTER_PARTS,l as CHAT_HANDOFF_REQUEST_ID,R as CHAT_RECENT_ROWS_CEILING,z as CHAT_RECENT_ROWS_MAX,re as CHAT_SPEECH_TOKEN_MARGIN_MS,t as ChatApiError,i as ChatDecodeError,ie as ChatSpeechError,N as DEFAULT_CHAT_LABELS,f as DICTATION_NO_SPEECH_MS,p as DICTATION_SILENCE_MS,j as IDLE_CHAT_SESSION,M as IDLE_CHAT_STATE,G as LOADER_STYLES,ue as buildTranscript,n as createChatClient,ee as createChatSession,u as createConversationList,m as createDictation,g as createExplain,b as createFixtureClient,ae as createSpeechTokenSource,ce as createSseParser,le as createStreamReader,te as createTurnApi,o as decodeChatConversationView,x as decodeChatFixture,s as decodeChatMessageView,a as decodeChatPart,d as decodeChatProfileView,h as decodeChatStreamEvent,B as defaultChatLook,K as emptyFeatures,q as featureRecord,w as formatChatDate,T as formatChatDateTime,E as formatChatDay,D as formatChatValue,fe as formatClipTime,_ as formatFigure,O as formatFileSize,ne as handoffSettledIds,oe as humanizeService,A as isHandoffTarget,F as isSafeActionHref,I as isSafeLinkUrl,L as isSafePrivacyUrl,J as loaderView,P as mergeLabels,V as mergeLook,k as messagePlainText,r as newIdempotencyKey,C as orderFooterParts,U as pacingDelayMs,$ as provideRuntimeCrypto,Y as resolveFeatures,X as resolveNudge,Z as resolveStart,se as selectStarters,Q as showsCaptchaNote,e as sniffAudioType,v as toFigureRuns,y as toFigureText,de as transcriptToText,H as unknownLookNames,pe as voiceClipBars};
package/dist/look.js CHANGED
@@ -1 +1 @@
1
- var e=5,t={launcher:{style:`Round`,entrance:`Rise`,idle:`None`,labelReveal:`Bubble`,compact:!1,mark:`Icon`,glass:`Light`},panel:{motion:`Spring`,widthPx:420,maxHeightPx:650,bottomGapPx:24,height:`Fixed`,placement:`Floating`,replyAvatars:`First`,greetingLoaderMs:0,emptyMinHeightPx:null},phone:{maxWidthPx:768,mode:`FullScreen`,sheetHeightDvh:85,sheetMaxHeightPx:640,hideLauncher:!1,launcherLabel:!1,entrance:`Fade`,offsetXPx:null,offsetYPx:null},input:{ring:!0,sendReveal:`OnText`,sendIcon:`arrow-up`,mark:`None`,edge:`None`,placeholder:`Plain`,busyEdge:`Off`,markInsetPx:null,sendInsetPx:null,rowHeightPx:null,markAlign:`Centre`},starters:{style:`Chips`,recentRows:0,heading:!1,gapPx:null},footer:{layout:`Stacked`,disclaimer:`Show`},quickReplies:{style:`Plain`},avoid:{liftAboveBanner:!0,liftGapPx:20,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},quickReplies:{...t.quickReplies,...n.quickReplies},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};
1
+ var e=5,t=20,n={launcher:{style:`Round`,entrance:`Rise`,idle:`None`,labelReveal:`Bubble`,compact:!1,mark:`Icon`,glass:`Light`},panel:{motion:`Spring`,widthPx:420,maxHeightPx:650,bottomGapPx:24,height:`Fixed`,placement:`Floating`,replyAvatars:`First`,greetingLoaderMs:0,emptyMinHeightPx:null},phone:{maxWidthPx:768,mode:`FullScreen`,sheetHeightDvh:85,sheetMaxHeightPx:640,hideLauncher:!1,launcherLabel:!1,entrance:`Fade`,offsetXPx:null,offsetYPx:null},input:{ring:!0,sendReveal:`OnText`,sendIcon:`arrow-up`,mark:`None`,edge:`None`,placeholder:`Plain`,busyEdge:`Off`,emphasis:`Always`,markInsetPx:null,sendInsetPx:null,rowHeightPx:null,markAlign:`Centre`},starters:{style:`Chips`,recentRows:0,recentRowsMax:5,heading:!1,gapPx:null,greetingHeading:`Show`,greetingStyle:`Welcome`},footer:{layout:`Stacked`,disclaimer:`Show`,order:null,noticeBreak:`None`},quickReplies:{style:`Plain`},replies:{ratingRow:`Hover`},avoid:{liftAboveBanner:!0,liftGapPx:20,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},r=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function i(e){let t={...n},i=[];for(let[n,a]of Object.entries(e??{})){if(!(n in t)){i.push(n);continue}let e=t[n];if(r(e)&&r(a))for(let t of Object.keys(a))t in e||i.push(`${n}.${t}`)}return i}function a(e){let t=e??{};return{launcher:{...n.launcher,...t.launcher},panel:{...n.panel,...t.panel},phone:{...n.phone,...t.phone},input:{...n.input,...t.input},starters:{...n.starters,...t.starters},footer:{...n.footer,...t.footer},quickReplies:{...n.quickReplies,...t.quickReplies},replies:{...n.replies,...t.replies},avoid:{...n.avoid,...t.avoid},motion:t.motion??n.motion,avatar:t.avatar??n.avatar,avatarMotion:t.avatarMotion??n.avatarMotion,expressive:t.expressive??n.expressive}}export{t as CHAT_RECENT_ROWS_CEILING,e as CHAT_RECENT_ROWS_MAX,n as defaultChatLook,a as mergeLook,i as unknownLookNames};
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"./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(`
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 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(`
2
2
 
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};
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,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}),be=(e,t)=>{let n=Math.min(Math.max(Number.isFinite(e)?Math.floor(e):0,0),20);return n!==e&&t?.(/* @__PURE__ */ RangeError(`recentConversations must be a whole number from 0 to 20; using ${n} instead of ${e}.`)),n},p=(s,f)=>{let p=i(f.labels),m=f.schedule??ae,h=f.prefs,xe=be(f.recentConversations??0,f.onError),g=/* @__PURE__ */ new Set,_=ye(h),v=0,y=null,b=null,Se=0,Ce=0,we=null,x=null,S=/* @__PURE__ */ new Map,Te=/* @__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,Ee=!0,N=!1,P=/* @__PURE__ */ new Set,F=/* @__PURE__ */ new Map,I=Promise.resolve(),L=0,De=()=>f.pathname?.()??u.location?.pathname??`/`,Oe=()=>f.reducedMotion?.()===!0||_.profile?.experience.motion===!1,R=()=>_.streaming||_.thinking,ke=e=>{if(!e.profile)return{...e,greeting:null,starters:[]};let t=De(),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)},Ae=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()},je=e=>{for(let t of Ae(e))D.add(t.actionId)},Me=()=>{for(let e of Ae(_.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}))},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`?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}))},Pe=()=>!N&&Ee&&_.features.HumanHandoff&&_.conversationId!==null&&(_.conversationState===`WaitingForAgent`||_.conversationState===`WithAgent`),U=()=>{if(!Pe()){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),_=ke(t);for(let e of g)e();e.messages!==void 0&&Me(),U()},Fe=(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},Ie=(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()})},Le=()=>{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()},Re=e=>{let t=C.get(e);if(!t)throw Error(`No uploaded file for composer attachment ${e}.`);return t},ze=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&&Fe(e,{progress:t})}})}catch{T.get(e)===n&&(T.delete(e),Fe(e,{status:`Failed`,progress:null,error:p.attachmentFailed}));return}T.get(e)===n?(T.delete(e),C.set(e,r),w.add(e),Fe(e,{status:`Ready`,progress:null})):s.deleteAttachment(r.publicId).catch(q)},Be=e=>{let t={...n(f.pageContext?.()),path:De(),behaviour:f.behaviour?.()??null};return e&&(t.attribution=f.attribution?.()??null),t},Ve=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},He=(e,t,n)=>{let r=se(_.messages,oe(e,!1));W(n?{messages:r,messagesLeftToday:t??_.messagesLeftToday,steps:[],thinking:!1}:{messages:r})},Ue=e=>{let n=_.profile?.experience.pacing;return!n||Te.has(e.publicId)||e.author.kind!==`Assistant`&&e.author.kind!==`Script`?0:o(t(e.parts),n,Oe())},We=(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()&&He(e,t,i),L===0&&W({pending:null})})},Ge=(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),Ke=()=>{z(),_.agentTyping!==null&&W({agentTyping:null})},qe=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`)Te.add(e.data.messageId),Ie(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`&&Ke(),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:Ge(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:Ge(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`&&Ke();let a=Ue(t);a>0||L>0?We(t,i,a,n,r):He(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`&&qe(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;Se+=1;let c={id:`local-${Se}`,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 Ve();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:Be(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!==we&&(we=l,f.onEvent?.(`chatStarted`,{conversationId:l}))},Je=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)}))}),Ye=async()=>{try{W({openTickets:await s.listOpenTickets()})}catch(e){q(e)}},Xe=async()=>{try{let e=await s.listConversations({page:1,pageSize:Math.max(1,xe)});W({lastConversation:e.items[0]??null,recentConversations:e.items.slice(0,xe)})}catch(e){q(e)}},Ze=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&&Ye(),t.History&&(t.ResumeLast||xe>0)&&Xe(),f.conversationId&&await pt(f.conversationId)},Qe=()=>(x||=Ze(),x),$e=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=>Re(e.key));await $({wireText:t===``?null:t,displayText:t,quickReplyId:null,replacesMessageId:i,repliesToMessageId:null,attachments:a},r,!0)},et=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}},tt=async e=>{if(e.action!==`Send`||R())return;if(e.id===`handoff.request`&&_.features.HumanHandoff&&_.conversationId!==null&&!_.handoffPending){await wt();return}let t=et(e);await $({wireText:null,displayText:e.label,quickReplyId:e.id,replacesMessageId:null,repliesToMessageId:t?.stored&&_.conversationId!==null?t.id:null,attachments:[]},_.messages,!1)},nt=async(e,t)=>{let n=await Ve();await s.sendOtp(e,{...t,captchaToken:n})},rt=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,Ne(t,n);let c=t===_.handoffContactRequestId;W({streaming:!0,thinking:!0});try{let e=await Ve();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 wt().catch(q))),{ok:!0}},it=async e=>{let t=await s.confirmAction(e);Je(t),f.onEvent?.(`chatActionConfirmed`,{actionId:t.actionId,kind:t.actionKind}),await Q()},at=async(e,t)=>{Je(await s.rejectAction(e,t)),await Q()},ot=()=>{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})},st=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)},ct=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)},lt=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:[]}))},ut=()=>{_.editing&&(J(),W({editing:null,attachments:[]}))},dt=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);Ce+=1;let o=`file-${Ce}`,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})=>ze(e,t)))},ft=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 pt(e){Le();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(),je(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 mt=async()=>{let e=_.lastConversation;e&&await pt(e.publicId)},ht=()=>{J(),Le(),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&&Ye()},gt=(e,t,n)=>{W({messages:Y(e,e=>({...e,rating:t,ratingNote:n}))})},_t=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;gt(e,t,a);try{await s.rateMessage(e,{rating:t,note:a})}catch(t){throw gt(e,i.rating,i.ratingNote),t}f.onEvent?.(`rated`,{messageId:e,rating:t})},vt=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})},yt=e=>{_.open&&(h?.set(`wchat:dismissed`,`1`),W({open:!1}),f.onEvent?.(`chatClosed`,{layout:f.layout??null,reason:e}))},bt=e=>{h?.set(`wchat:muted`,e?`1`:`0`),W({muted:e}),f.onEvent?.(`chatSoundToggled`,{muted:e})},xt=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))},St=async()=>{R()||(f.onEvent?.(`chatLeadCancelled`,{}),await $({wireText:null,displayText:p.cancel,quickReplyId:`lead.cancel`,replacesMessageId:null,repliesToMessageId:null,attachments:[]},_.messages,!1))},Ct=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)},wt=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`})},Tt=()=>{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)]))},Et=e=>{Ee=e,U()},Dt=()=>{_.live===`Lost`&&Pe()&&(H(null),U())},Ot=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},kt=()=>{B(),_.handoffPause&&W({handoffPause:!1})};return{client:s,getState:()=>_,subscribe:e=>(g.add(e),x||Qe(),()=>{g.delete(e)}),load:Qe,submit:$e,chooseQuickReply:tt,answerInput:rt,sendOtp:nt,confirmAction:it,rejectAction:at,stop:ot,retry:st,regenerate:ct,startEdit:lt,cancelEdit:ut,attach:dt,removeAttachment:ft,openConversation:pt,resumeLast:mt,newConversation:ht,rate:_t,open:vt,close:yt,setMuted:bt,skipField:xt,cancelLead:St,editLeadField:Ct,requestHandoff:wt,notifyTyping:Tt,setLiveActive:Et,resumeLive:Dt,beginHandoff:(e,t)=>{_.handoffPause||(W({handoffPause:!0}),f.onEvent?.(`chatHandoff`,{destination:e.id}),A=u.setTimeout(()=>{A=null;try{t()}catch(e){kt(),q(e)}},Ot(e)))},endHandoffPause:kt,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(),Le(),x=null,I=Promise.resolve(),L=0,Te.clear(),we=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};
@@ -0,0 +1,5 @@
1
+ import type { ChatFooterPart } from "./look";
2
+ export declare const CHAT_FOOTER_PARTS: readonly ChatFooterPart[];
3
+ export declare function orderFooterParts<T extends {
4
+ name: ChatFooterPart;
5
+ }>(parts: readonly T[], order: readonly ChatFooterPart[] | null): T[];
@@ -7,6 +7,7 @@ export * from "./dictation";
7
7
  export * from "./explain";
8
8
  export * from "./figures";
9
9
  export * from "./fixtureClient";
10
+ export * from "./footerOrder";
10
11
  export * from "./format";
11
12
  export * from "./handoff";
12
13
  export * from "./idleSession";
@@ -23,12 +23,17 @@ export type ChatAvatarMotion = "Still" | "Drift";
23
23
  export type ChatFooterLayout = "Stacked" | "Inline";
24
24
  /** Hide drops the footer disclaimer line; the privacy link, assurance text and reCAPTCHA notice still show. */
25
25
  export type ChatFooterDisclaimer = "Show" | "Hide";
26
+ /** BeforeLinks breaks the reCAPTCHA notice after "the Google", so its two links keep their own line; None lets the notice wrap freely. */
27
+ export type ChatFooterNoticeBreak = "None" | "BeforeLinks";
28
+ export type ChatFooterPart = "disclaimer" | "privacy" | "assurance" | "captcha";
26
29
  /** What draws the ask box edge: the plain border, or the chat gradient. */
27
30
  export type ChatInputEdge = "None" | "Gradient";
28
31
  /** How the ask box placeholder is drawn: plain muted text, or filled with the chat gradient. */
29
32
  export type ChatInputPlaceholder = "Plain" | "Gradient";
30
33
  /** Whether the ask box edge moves while a reply is thinking or streaming: Sweep slides the chat gradient along the edge; Conic turns a conic brand-colour border around it. */
31
34
  export type ChatInputBusyEdge = "Off" | "Sweep" | "Conic";
35
+ /** Whether the ask box ring, halo and edge show at rest: Always keeps them on; Active shows them only while the visitor types or focuses in the box, or while a reply loads, and draws the box at its built-in height until then. */
36
+ export type ChatInputEmphasis = "Always" | "Active";
32
37
  /** How the quick-reply chips are drawn: Plain, or Outlined with a resting border and an accent tint on hover. */
33
38
  export type ChatQuickReplyStyle = "Plain" | "Outlined";
34
39
  /** The launcher glass: Light follows the page and dark mode; Dark draws darker glass with a white label for a launcher over a dark page band. */
@@ -39,8 +44,16 @@ export type ChatPhoneEntrance = "Fade" | "Match";
39
44
  export type ChatInputMarkAlign = "Centre" | "Bottom";
40
45
  /** How the starter questions are laid out: wrapping chips, or full-width rows with an icon. */
41
46
  export type ChatStartersStyle = "Chips" | "Rows";
42
- /** The most recent chats a welcome screen can list. */
47
+ /** Whether the empty screen draws the greeting heading: Show draws it; Hide leaves it out and keeps the assistant mark and intro. */
48
+ export type ChatGreetingHeading = "Show" | "Hide";
49
+ /** Welcome draws the greeting and the intro as two lines; Message joins them into one greeting line. */
50
+ export type ChatGreetingStyle = "Welcome" | "Message";
51
+ /** When the rating row under an assistant reply shows: Hover (default) on hover or focus, always on a touch screen; Always under every reply. */
52
+ export type ChatRatingRow = "Hover" | "Always";
53
+ /** The default for how many of the most recent chats a welcome screen can list; `look.starters.recentRowsMax` raises it. */
43
54
  export declare const CHAT_RECENT_ROWS_MAX = 5;
55
+ /** The most `look.starters.recentRowsMax` can be set to. */
56
+ export declare const CHAT_RECENT_ROWS_CEILING = 20;
44
57
  export interface ChatLook {
45
58
  launcher: {
46
59
  style: ChatLauncherStyle;
@@ -92,28 +105,39 @@ export interface ChatLook {
92
105
  edge: ChatInputEdge;
93
106
  placeholder: ChatInputPlaceholder;
94
107
  busyEdge: ChatInputBusyEdge;
108
+ emphasis: ChatInputEmphasis;
95
109
  markInsetPx: number | null;
96
110
  sendInsetPx: number | null;
97
111
  rowHeightPx: number | null;
98
112
  markAlign: ChatInputMarkAlign;
99
113
  };
100
114
  /** The starter questions on the empty welcome screen, on the web surfaces; the phone ignores it. */
101
- /** recentRows lists that many of the visitor's recent chats under the starters, 0 to 5; 0 lists none. */
102
- /** heading draws the starters' label as a visible heading; gapPx sets the space between the last starter and the ask box, null keeps the built-in layout. */
115
+ /** recentRows lists that many of the visitor's recent chats under the starters, 0 up to recentRowsMax; 0 lists none. recentRowsMax is that cap, 5 by default and at most 20. */
116
+ /** heading draws the starters' label as a visible heading; gapPx sets the space between the last starter and the ask box, null keeps the built-in layout. greetingHeading Hide leaves the greeting heading off the empty screen. */
103
117
  starters: {
104
118
  style: ChatStartersStyle;
105
119
  recentRows: number;
120
+ recentRowsMax: number;
106
121
  heading: boolean;
107
122
  gapPx: number | null;
123
+ greetingHeading: ChatGreetingHeading;
124
+ greetingStyle: ChatGreetingStyle;
108
125
  };
109
126
  /** The lines under the composer on the web surfaces (the elements and React); the phone footer ignores it. */
127
+ /** The order the web footer draws its parts in; null keeps disclaimer, privacy, assurance, captcha. Names not listed follow the listed ones; unknown names are ignored; the phone footer ignores it. */
110
128
  footer: {
111
129
  layout: ChatFooterLayout;
112
130
  disclaimer: ChatFooterDisclaimer;
131
+ order: ChatFooterPart[] | null;
132
+ noticeBreak: ChatFooterNoticeBreak;
113
133
  };
114
134
  quickReplies: {
115
135
  style: ChatQuickReplyStyle;
116
136
  };
137
+ /** The assistant replies on the web surfaces; the phone ignores it. */
138
+ replies: {
139
+ ratingRow: ChatRatingRow;
140
+ };
117
141
  avoid: {
118
142
  /** Whether the launcher lifts over an open banner; the profile's own setting also has to allow it. */
119
143
  liftAboveBanner: boolean;
@@ -137,5 +161,7 @@ export declare const defaultChatLook: ChatLook;
137
161
  export type ChatLookInput = {
138
162
  [K in keyof ChatLook]?: ChatLook[K] extends object ? Partial<ChatLook[K]> : ChatLook[K];
139
163
  };
164
+ /** The names in a given look that the chat does not know, as `key` or `group.member`; the look is never changed. */
165
+ export declare function unknownLookNames(input?: ChatLookInput | null): string[];
140
166
  /** The defaults with each given group merged member by member. */
141
167
  export declare function mergeLook(input?: ChatLookInput | null): ChatLook;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webority/chat-core",
3
- "version": "0.168.0",
3
+ "version": "0.170.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",