@webority/chat-core 0.151.1 → 0.152.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{featureRecord as e}from"../profile.js";import{ChatCaptchaModeValues as t,ChatFieldTypeValues as n,ChatQuickReplyVariantValues as r}from"./enums.js";import{array as i,boolean as a,field as o,nullable as s,number as c,oneOf as l,record as u,string as d}from"./primitives.js";var f=l(r),p=l(t),m=l(n),h=(e,t)=>{let n=u(e,t);return{name:o(n,`name`,d,t),tagline:o(n,`tagline`,s(d),t),intro:o(n,`intro`,s(d),t)}},g=(e,t)=>{let n=u(e,t);return{privacyText:o(n,`privacyText`,s(d),t),privacyUrl:o(n,`privacyUrl`,s(d),t),assuranceText:o(n,`assuranceText`,s(d),t),disclaimer:o(n,`disclaimer`,s(d),t)}},_=(e,t)=>{let n=u(e,t);return{mode:o(n,`mode`,p,t),siteKey:o(n,`siteKey`,s(d),t),action:o(n,`action`,d,t)}},v=(e,t)=>{let n=u(e,t);return{maxMessageLength:o(n,`maxMessageLength`,c,t),maxAttachments:o(n,`maxAttachments`,c,t),maxFileBytes:o(n,`maxFileBytes`,c,t),contentTypes:o(n,`contentTypes`,i(d),t),maxRepliesPerConversation:o(n,`maxRepliesPerConversation`,s(c),t)}},y=(e,t)=>{let n=u(e,t);return{id:o(n,`id`,d,t),label:o(n,`label`,d,t),message:o(n,`message`,d,t),icon:o(n,`icon`,s(d),t),variant:o(n,`variant`,s(f),t)}},b=(e,t)=>{let n=u(e,t);return{pathPrefix:o(n,`pathPrefix`,d,t),greeting:o(n,`greeting`,s(d),t),starters:o(n,`starters`,s(i(y)),t)}},x=(e,t)=>{let n=u(e,t);return{kind:o(n,`kind`,d,t),text:o(n,`text`,d,t),delaySeconds:o(n,`delaySeconds`,c,t),scrollPercent:o(n,`scrollPercent`,s(c),t),pagesViewed:o(n,`pagesViewed`,s(c),t)}},S=(e,t)=>{let n=u(e,t);return{id:o(n,`id`,d,t),minTimeOnSiteSeconds:o(n,`minTimeOnSiteSeconds`,s(c),t),minScrollPercent:o(n,`minScrollPercent`,s(c),t),minPagesViewed:o(n,`minPagesViewed`,s(c),t),minServicesViewed:o(n,`minServicesViewed`,s(c),t),starters:o(n,`starters`,i(y),t),keepPageStarters:o(n,`keepPageStarters`,c,t)}},C=(e,t)=>{let n=u(e,t);return{servicePathPrefixes:o(n,`servicePathPrefixes`,i(d),t),maxStarters:o(n,`maxStarters`,c,t),recentServiceStarter:o(n,`recentServiceStarter`,s(d),t)}},w=(e,t)=>{let n=u(e,t);return{greeting:o(n,`greeting`,d,t),starters:o(n,`starters`,i(y),t),pageRules:o(n,`pageRules`,i(b),t),returningGreeting:o(n,`returningGreeting`,s(d),t),returningStarters:o(n,`returningStarters`,s(i(y)),t),nudge:o(n,`nudge`,s(x),t),rules:o(n,`rules`,s(i(S)),t),behaviour:o(n,`behaviour`,s(C),t)}},T=(e,t)=>{let n=u(e,t);return{open:o(n,`open`,a,t),sent:o(n,`sent`,a,t),reply:o(n,`reply`,a,t),vibrate:o(n,`vibrate`,a,t),vibrateMs:o(n,`vibrateMs`,c,t),volume:o(n,`volume`,c,t),muteControl:o(n,`muteControl`,a,t)}},E=(e,t)=>{let n=u(e,t);return{typingPause:o(n,`typingPause`,a,t),pauseBaseMs:o(n,`pauseBaseMs`,c,t),pausePerCharMs:o(n,`pausePerCharMs`,c,t),pauseMaxMs:o(n,`pauseMaxMs`,c,t),handoffPauseMs:o(n,`handoffPauseMs`,c,t),thinkingPhrases:o(n,`thinkingPhrases`,i(d),t),phraseIntervalMs:o(n,`phraseIntervalMs`,c,t)}},D=(e,t)=>{let n=u(e,t);return{peek:o(n,`peek`,a,t),peekSeconds:o(n,`peekSeconds`,c,t),hoverLabel:o(n,`hoverLabel`,s(d),t),hideWhileOpen:o(n,`hideWhileOpen`,a,t),liftAboveBanner:o(n,`liftAboveBanner`,a,t),liftAboveFooter:o(n,`liftAboveFooter`,a,t),stepAsideForMenus:o(n,`stepAsideForMenus`,a,t),switchOnDark:o(n,`switchOnDark`,a,t)}},O=(e,t)=>{let n=u(e,t);return{delaySeconds:o(n,`delaySeconds`,c,t),oncePerSession:o(n,`oncePerSession`,a,t),rememberDismissal:o(n,`rememberDismissal`,a,t),skipBelowWidthPx:o(n,`skipBelowWidthPx`,c,t),skipWhenFormTouched:o(n,`skipWhenFormTouched`,a,t),skipWhenCoversControl:o(n,`skipWhenCoversControl`,a,t),busyRetrySeconds:o(n,`busyRetrySeconds`,c,t),skipPathPrefixes:o(n,`skipPathPrefixes`,i(d),t)}},k=(e,t)=>{let n=u(e,t);return{motion:o(n,`motion`,a,t),sound:o(n,`sound`,T,t),pacing:o(n,`pacing`,E,t),launcher:o(n,`launcher`,D,t),autoOpen:o(n,`autoOpen`,O,t)}},A=(t,n)=>{let r=u(t,n),l=u(r.features,`${n}.features`);return{contractVersion:o(r,`contractVersion`,c,n),surface:o(r,`surface`,d,n),screen:o(r,`screen`,s(d),n),assistant:o(r,`assistant`,h,n),start:o(r,`start`,w,n),features:e(e=>o(l,e,a,`${n}.features`)),limits:o(r,`limits`,v,n),messagesLeftToday:o(r,`messagesLeftToday`,s(c),n),inputFieldTypes:o(r,`inputFieldTypes`,i(m),n),footer:o(r,`footer`,g,n),captcha:o(r,`captcha`,_,n),experience:o(r,`experience`,k,n),speechAvailable:o(r,`speechAvailable`,a,n)}};export{h as decodeChatAssistantCopy,O as decodeChatAutoOpenSettings,C as decodeChatBehaviourSettings,p as decodeChatCaptchaMode,_ as decodeChatCaptchaSettings,k as decodeChatExperienceSettings,m as decodeChatFieldType,g as decodeChatFooterCopy,D as decodeChatLauncherSettings,v as decodeChatLimits,x as decodeChatNudge,E as decodeChatPacingSettings,b as decodeChatPageRule,A as decodeChatProfileView,f as decodeChatQuickReplyVariant,T as decodeChatSoundSettings,w as decodeChatStartSettings,y as decodeChatStarter,S as decodeChatStarterRule};
1
+ import{featureRecord as e}from"../profile.js";import{ChatCaptchaModeValues as t,ChatFieldTypeValues as n,ChatQuickReplyVariantValues as r}from"./enums.js";import{array as i,boolean as a,field as o,nullable as s,number as c,oneOf as l,record as u,string as d}from"./primitives.js";var f=l(r),p=l(t),m=l(n),h=(e,t)=>{let n=u(e,t);return{name:o(n,`name`,d,t),tagline:o(n,`tagline`,s(d),t),intro:o(n,`intro`,s(d),t)}},g=(e,t)=>{let n=u(e,t);return{privacyText:o(n,`privacyText`,s(d),t),privacyUrl:o(n,`privacyUrl`,s(d),t),assuranceText:o(n,`assuranceText`,s(d),t),disclaimer:o(n,`disclaimer`,s(d),t)}},_=(e,t)=>{let n=u(e,t);return{mode:o(n,`mode`,p,t),siteKey:o(n,`siteKey`,s(d),t),action:o(n,`action`,d,t),testToken:o(n,`testToken`,s(d),t)}},v=(e,t)=>{let n=u(e,t);return{maxMessageLength:o(n,`maxMessageLength`,c,t),maxAttachments:o(n,`maxAttachments`,c,t),maxFileBytes:o(n,`maxFileBytes`,c,t),contentTypes:o(n,`contentTypes`,i(d),t),maxRepliesPerConversation:o(n,`maxRepliesPerConversation`,s(c),t)}},y=(e,t)=>{let n=u(e,t);return{id:o(n,`id`,d,t),label:o(n,`label`,d,t),message:o(n,`message`,d,t),icon:o(n,`icon`,s(d),t),variant:o(n,`variant`,s(f),t)}},b=(e,t)=>{let n=u(e,t);return{pathPrefix:o(n,`pathPrefix`,d,t),greeting:o(n,`greeting`,s(d),t),starters:o(n,`starters`,s(i(y)),t)}},x=(e,t)=>{let n=u(e,t);return{kind:o(n,`kind`,d,t),text:o(n,`text`,d,t),delaySeconds:o(n,`delaySeconds`,c,t),scrollPercent:o(n,`scrollPercent`,s(c),t),pagesViewed:o(n,`pagesViewed`,s(c),t)}},S=(e,t)=>{let n=u(e,t);return{id:o(n,`id`,d,t),minTimeOnSiteSeconds:o(n,`minTimeOnSiteSeconds`,s(c),t),minScrollPercent:o(n,`minScrollPercent`,s(c),t),minPagesViewed:o(n,`minPagesViewed`,s(c),t),minServicesViewed:o(n,`minServicesViewed`,s(c),t),starters:o(n,`starters`,i(y),t),keepPageStarters:o(n,`keepPageStarters`,c,t)}},C=(e,t)=>{let n=u(e,t);return{servicePathPrefixes:o(n,`servicePathPrefixes`,i(d),t),maxStarters:o(n,`maxStarters`,c,t),recentServiceStarter:o(n,`recentServiceStarter`,s(d),t)}},w=(e,t)=>{let n=u(e,t);return{greeting:o(n,`greeting`,d,t),starters:o(n,`starters`,i(y),t),pageRules:o(n,`pageRules`,i(b),t),returningGreeting:o(n,`returningGreeting`,s(d),t),returningStarters:o(n,`returningStarters`,s(i(y)),t),nudge:o(n,`nudge`,s(x),t),rules:o(n,`rules`,s(i(S)),t),behaviour:o(n,`behaviour`,s(C),t)}},T=(e,t)=>{let n=u(e,t);return{open:o(n,`open`,a,t),sent:o(n,`sent`,a,t),reply:o(n,`reply`,a,t),vibrate:o(n,`vibrate`,a,t),vibrateMs:o(n,`vibrateMs`,c,t),volume:o(n,`volume`,c,t),muteControl:o(n,`muteControl`,a,t)}},E=(e,t)=>{let n=u(e,t);return{typingPause:o(n,`typingPause`,a,t),pauseBaseMs:o(n,`pauseBaseMs`,c,t),pausePerCharMs:o(n,`pausePerCharMs`,c,t),pauseMaxMs:o(n,`pauseMaxMs`,c,t),handoffPauseMs:o(n,`handoffPauseMs`,c,t),thinkingPhrases:o(n,`thinkingPhrases`,i(d),t),phraseIntervalMs:o(n,`phraseIntervalMs`,c,t)}},D=(e,t)=>{let n=u(e,t);return{peek:o(n,`peek`,a,t),peekSeconds:o(n,`peekSeconds`,c,t),hoverLabel:o(n,`hoverLabel`,s(d),t),hideWhileOpen:o(n,`hideWhileOpen`,a,t),liftAboveBanner:o(n,`liftAboveBanner`,a,t),liftAboveFooter:o(n,`liftAboveFooter`,a,t),stepAsideForMenus:o(n,`stepAsideForMenus`,a,t),switchOnDark:o(n,`switchOnDark`,a,t)}},O=(e,t)=>{let n=u(e,t);return{delaySeconds:o(n,`delaySeconds`,c,t),oncePerSession:o(n,`oncePerSession`,a,t),rememberDismissal:o(n,`rememberDismissal`,a,t),skipBelowWidthPx:o(n,`skipBelowWidthPx`,c,t),skipWhenFormTouched:o(n,`skipWhenFormTouched`,a,t),skipWhenCoversControl:o(n,`skipWhenCoversControl`,a,t),busyRetrySeconds:o(n,`busyRetrySeconds`,c,t),skipPathPrefixes:o(n,`skipPathPrefixes`,i(d),t)}},k=(e,t)=>{let n=u(e,t);return{motion:o(n,`motion`,a,t),sound:o(n,`sound`,T,t),pacing:o(n,`pacing`,E,t),launcher:o(n,`launcher`,D,t),autoOpen:o(n,`autoOpen`,O,t)}},A=(t,n)=>{let r=u(t,n),l=u(r.features,`${n}.features`);return{contractVersion:o(r,`contractVersion`,c,n),surface:o(r,`surface`,d,n),screen:o(r,`screen`,s(d),n),assistant:o(r,`assistant`,h,n),start:o(r,`start`,w,n),features:e(e=>o(l,e,a,`${n}.features`)),limits:o(r,`limits`,v,n),messagesLeftToday:o(r,`messagesLeftToday`,s(c),n),inputFieldTypes:o(r,`inputFieldTypes`,i(m),n),footer:o(r,`footer`,g,n),captcha:o(r,`captcha`,_,n),experience:o(r,`experience`,k,n),speechAvailable:o(r,`speechAvailable`,a,n)}};export{h as decodeChatAssistantCopy,O as decodeChatAutoOpenSettings,C as decodeChatBehaviourSettings,p as decodeChatCaptchaMode,_ as decodeChatCaptchaSettings,k as decodeChatExperienceSettings,m as decodeChatFieldType,g as decodeChatFooterCopy,D as decodeChatLauncherSettings,v as decodeChatLimits,x as decodeChatNudge,E as decodeChatPacingSettings,b as decodeChatPageRule,A as decodeChatProfileView,f as decodeChatQuickReplyVariant,T as decodeChatSoundSettings,w as decodeChatStartSettings,y as decodeChatStarter,S as decodeChatStarterRule};
package/dist/figures.js CHANGED
@@ -1 +1 @@
1
- var e=`×`,t=`[-+\\u2212]?\\d{1,3}`,n=/* @__PURE__ */ new Map([[`times`,e],[`cdot`,`·`],[`sum`,`∑`],[`leq`,`≤`],[`le`,`≤`],[`geq`,`≥`],[`ge`,`≥`],[`neq`,`≠`],[`approx`,`≈`],[`pm`,`±`],[`rightarrow`,`→`],[`to`,`→`],[`alpha`,`α`],[`beta`,`β`],[`gamma`,`γ`],[`delta`,`δ`],[`lambda`,`λ`],[`mu`,`μ`],[`pi`,`π`],[`rho`,`ρ`],[`sigma`,`σ`],[`tau`,`τ`],[`Delta`,`Δ`],[`Omega`,`Ω`]]),r=/\\\((.*?)\\\)|\\\[(.*?)\\\]|\$\$(.*?)\$\$/gs,i=/`[^`]+`/g,a=/([_^])(\{[^}]*\}|[A-Za-z0-9])/g,o=e=>`(?<${e}>\\{\\s*${t}\\s*\\}|\\(\\s*${t}\\s*\\)|${t})`,s=`(?<tensMantissa>\\d+(?:\\.\\d+)?) *[xX*] *10 ?\\^ ?${o(`tensExp`)}`,c=`\\b10 ?\\^ ?${o(`powExp`)}`,l=`(?<![A-Za-z0-9_.#-])(?<etoken>\\d+(?:\\.\\d+)?[eE]${t})(?![A-Za-z0-9_.-])`,u=RegExp(`${s}|${c}|${l}|(?<![A-Za-z0-9_])(?<symLetter>[A-Za-z])_(?<symSub>[A-Za-z0-9]+)(?<symPrime>')?(?![A-Za-z0-9_])`,`g`),d=e=>e.replace(/\\(?:left|right)\b/g,``).replace(/\\(?:text|mathrm|mathbf|mathit|operatorname)\{([^{}]*)\}/g,`$1`).replace(/\\frac\{([^{}]*)\}\{([^{}]*)\}/g,`($1)/($2)`).replace(/\\sqrt\{([^{}]*)\}/g,`√($1)`).replace(/\\[,;:! ]/g,` `).replace(/\\([A-Za-z]+)/g,(e,t)=>n.get(t)??t),f=e=>{let t=e.replace(/^[{(]\s*/,``).replace(/\s*[})]$/,``).trim().replace(/\u2212/g,`-`),n=``;return t.startsWith(`-`)?(n=`-`,t=t.slice(1)):t.startsWith(`+`)&&(t=t.slice(1)),t=t.replace(/^0+(?=\d)/,``),t===`0`?`0`:n+t},p=t=>{if(!Number.isFinite(t))return[{kind:`text`,text:String(t)}];if(t===0)return[{kind:`text`,text:`0`}];if(t<0)return[{kind:`text`,text:`-`},...p(-t)];let n=Math.floor(Math.log10(t)),r=t/10**n;Number(r.toFixed(2))>=10&&(r/=10,n+=1);let i=Math.abs(r-Math.round(r))<1e-9?String(Math.round(r)):String(Number(r.toFixed(2)));return n===0?[{kind:`text`,text:i}]:[{kind:`text`,text:`${i} ${e} 10`},{kind:`sup`,text:String(n)}]},m=(e,t)=>{let n=t.replace(/[{}]/g,``);n!==``&&e.push({kind:`text`,text:n})},h=e=>{let t=[],n=0;for(let r of e.matchAll(a)){let{index:i}=r,[,a,o]=r;if(i===void 0||a===void 0||o===void 0)throw Error(`figure script match is incomplete in "${e}"`);m(t,e.slice(n,i));let s=o.startsWith(`{`)?o.slice(1,-1):o;t.push({kind:a===`_`?`sub`:`sup`,text:s}),n=i+r[0].length}return m(t,e.slice(n)),t},g=t=>{let n=[],r=0;for(let i of t.matchAll(u)){let a=i.index??0;a>r&&n.push({kind:`text`,text:t.slice(r,a)});let o=i.groups??{};o.tensMantissa===void 0?o.powExp===void 0?o.etoken===void 0?(n.push({kind:`text`,text:o.symLetter??``}),n.push({kind:`sub`,text:o.symSub??``}),o.symPrime!==void 0&&n.push({kind:`text`,text:`'`})):n.push(...p(Number(o.etoken.replace(/\u2212/g,`-`)))):(n.push({kind:`text`,text:`10`}),n.push({kind:`sup`,text:f(o.powExp)})):(n.push({kind:`text`,text:`${o.tensMantissa} ${e} 10`}),n.push({kind:`sup`,text:f(o.tensExp??``)})),r=a+i[0].length}return r<t.length&&n.push({kind:`text`,text:t.slice(r)}),n},_=e=>{let t=[],n=0;for(let r of e.matchAll(i)){let i=r.index??0;t.push(...g(e.slice(n,i))),t.push({kind:`text`,text:r[0]}),n=i+r[0].length}return t.push(...g(e.slice(n))),t},v=e=>{let t=[];for(let n of e){if(n.text===``)continue;let e=t.at(-1);n.kind===`text`&&e?.kind===`text`?t[t.length-1]={kind:`text`,text:e.text+n.text}:t.push(n)}return t};function y(e){if(typeof e!=`string`||e===``)return[];let t=[],n=0;for(let i of e.matchAll(r)){let r=i.index??0;t.push(..._(e.slice(n,r)));let a=i[1]??i[2]??i[3]??``;t.push(...h(d(a))),n=r+i[0].length}return t.push(..._(e.slice(n))),v(t)}function b(e){return y(e).map(e=>e.kind===`sup`?`^${e.text}`:e.text).join(``)}function x(e){return Number.isFinite(e)&&e!==0&&Math.abs(e)<.001?p(e):Number.isFinite(e)?[{kind:`text`,text:new Intl.NumberFormat(`en-IN`,{maximumFractionDigits:10}).format(e)}]:[{kind:`text`,text:String(e)}]}export{x as formatFigure,y as toFigureRuns,b as toFigureText};
1
+ var e=`×`,t=`[-+\\u2212]?\\d{1,3}`,n=/* @__PURE__ */ new Map([[`times`,e],[`cdot`,`·`],[`sum`,`∑`],[`leq`,`≤`],[`le`,`≤`],[`geq`,`≥`],[`ge`,`≥`],[`neq`,`≠`],[`approx`,`≈`],[`pm`,`±`],[`rightarrow`,`→`],[`to`,`→`],[`alpha`,`α`],[`beta`,`β`],[`gamma`,`γ`],[`delta`,`δ`],[`lambda`,`λ`],[`mu`,`μ`],[`pi`,`π`],[`rho`,`ρ`],[`sigma`,`σ`],[`tau`,`τ`],[`Delta`,`Δ`],[`Omega`,`Ω`]]),r=/\\\((.*?)\\\)|\\\[(.*?)\\\]|\$\$(.*?)\$\$/gs,i=/`[^`]+`/g,a=/([_^])(\{[^}]*\}|[A-Za-z0-9])/g,o=e=>`(?<${e}>\\{\\s*${t}\\s*\\}|\\(\\s*${t}\\s*\\)|${t})`,s=`(?<tensMantissa>\\d+(?:\\.\\d+)?) *[xX*] *10 ?\\^ ?${o(`tensExp`)}`,c=`\\b10 ?\\^ ?${o(`powExp`)}`,l=`(?<![A-Za-z0-9_.#-])(?<etoken>\\d+(?:\\.\\d+)?[eE]${t})(?![A-Za-z0-9_.-])`,u=RegExp(`${s}|${c}|${l}|(?<![A-Za-z0-9_])(?<symLetter>[A-Za-z])_(?<symSub>[A-Za-z0-9]+)(?<symPrime>')?(?![A-Za-z0-9_])`,`g`),d=e=>e.replace(/\\(?:left|right)\b/g,``).replace(/\\(?:text|mathrm|mathbf|mathit|operatorname)\{([^{}]*)\}/g,`$1`).replace(/\\frac\{([^{}]*)\}\{([^{}]*)\}/g,`($1)/($2)`).replace(/\\sqrt\{([^{}]*)\}/g,`√($1)`).replace(/\\[,;:! ]/g,` `).replace(/\\([A-Za-z]+)/g,(e,t)=>n.get(t)??t),f=e=>{let t=e.replace(/^[{(]\s*/,``).replace(/\s*[})]$/,``).trim().replace(/\u2212/g,`-`),n=``;return t.startsWith(`-`)?(n=`-`,t=t.slice(1)):t.startsWith(`+`)&&(t=t.slice(1)),t=t.replace(/^0+(?=\d)/,``),t===`0`?`0`:n+t},p=t=>{if(!Number.isFinite(t))return[{kind:`text`,text:String(t)}];if(t===0)return[{kind:`text`,text:`0`}];if(t<0)return[{kind:`text`,text:`-`},...p(-t)];let n=Math.floor(Math.log10(t)),r=t/10**n;Number(r.toFixed(2))>=10&&(r/=10,n+=1);let i=Math.abs(r-Math.round(r))<1e-9?String(Math.round(r)):String(Number(r.toFixed(2)));return n===0?[{kind:`text`,text:i}]:[{kind:`text`,text:`${i} ${e} 10`},{kind:`sup`,text:String(n)}]},m=(e,t)=>{let n=t.replace(/[{}]/g,``);n!==``&&e.push({kind:`text`,text:n})},h=e=>{let t=[],n=0;for(let r of e.matchAll(a)){let{index:i}=r,[,a,o]=r;if(i===void 0||a===void 0||o===void 0)throw Error(`figure script match is incomplete in "${e}"`);m(t,e.slice(n,i));let s=o.startsWith(`{`)?o.slice(1,-1):o;t.push({kind:a===`_`?`sub`:`sup`,text:s}),n=i+r[0].length}return m(t,e.slice(n)),t},g=t=>{let n=[],r=0;for(let i of t.matchAll(u)){let a=i.index??0;a>r&&n.push({kind:`text`,text:t.slice(r,a)});let o=i.groups??{};o.tensMantissa===void 0?o.powExp===void 0?o.etoken===void 0?(n.push({kind:`text`,text:o.symLetter??``}),n.push({kind:`sub`,text:o.symSub??``}),o.symPrime!==void 0&&n.push({kind:`text`,text:`'`})):n.push(...p(Number(o.etoken.replace(/\u2212/g,`-`)))):(n.push({kind:`text`,text:`10`}),n.push({kind:`sup`,text:f(o.powExp)})):(n.push({kind:`text`,text:`${o.tensMantissa} ${e} 10`}),n.push({kind:`sup`,text:f(o.tensExp??``)})),r=a+i[0].length}return r<t.length&&n.push({kind:`text`,text:t.slice(r)}),n},_=e=>{let t=[],n=0;for(let r of e.matchAll(i)){let i=r.index??0;t.push(...g(e.slice(n,i))),t.push({kind:`text`,text:r[0]}),n=i+r[0].length}return t.push(...g(e.slice(n))),t},v=e=>{let t=[];for(let n of e){if(n.text===``)continue;let e=t[t.length-1];n.kind===`text`&&e?.kind===`text`?t[t.length-1]={kind:`text`,text:e.text+n.text}:t.push(n)}return t};function y(e){if(typeof e!=`string`||e===``)return[];let t=[],n=0;for(let i of e.matchAll(r)){let r=i.index??0;t.push(..._(e.slice(n,r)));let a=i[1]??i[2]??i[3]??``;t.push(...h(d(a))),n=r+i[0].length}return t.push(..._(e.slice(n))),v(t)}function b(e){return y(e).map(e=>e.kind===`sup`?`^${e.text}`:e.text).join(``)}function x(e){return Number.isFinite(e)&&e!==0&&Math.abs(e)<.001?p(e):Number.isFinite(e)?[{kind:`text`,text:new Intl.NumberFormat(`en-IN`,{maximumFractionDigits:10}).format(e)}]:[{kind:`text`,text:String(e)}]}export{x as formatFigure,y as toFigureRuns,b as toFigureText};
package/dist/session.js CHANGED
@@ -1,3 +1,3 @@
1
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 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}},d=(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
- `),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,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),be=f.schedule??oe,m=f.prefs,h=/* @__PURE__ */ new Set,g=ye(m),_=0,v=null,y=null,xe=0,Se=0,Ce=null,b=null,x=/* @__PURE__ */ new Map,S=/* @__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,Te=!1,N=/* @__PURE__ */ new Set,P=/* @__PURE__ */ new Map,F=Promise.resolve(),I=0,Ee=()=>f.pathname?.()??l.location?.pathname??`/`,De=()=>f.reducedMotion?.()===!0||g.profile?.experience.motion===!1,L=()=>g.streaming||g.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:f.behaviour?.()??null,behaviourStarters:e.features.BehaviourStarters});return{...e,greeting:r,starters:de(e.starters,i)?e.starters:i}},R=()=>{O!==null&&(l.clearTimeout(O),O=null)},ke=()=>{A!==null&&(l.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)}]:[])),je=()=>{E.name=null,E.email=null,E.phone=null,D.clear()},Me=e=>{for(let t of Ae(e))D.add(t.actionId)},Ne=()=>{for(let e of Ae(g.messages))D.has(e.actionId)||(D.add(e.actionId),f.onEvent?.(`leadSubmitted`,{conversationId:g.conversationId,fields:{name:E.name,email:E.email,phone:E.phone},leadType:e.leadType}))},Pe=(e,t)=>{let n=g.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()))}},z=e=>{let t=M;t!==null&&(M=null,t.handle?.stop(),e!==null&&V({live:e}))},Fe=()=>!Te&&we&&g.features.HumanHandoff&&g.conversationId!==null&&(g.conversationState===`WaitingForAgent`||g.conversationState===`WithAgent`),B=()=>{if(!Fe()){M!==null&&z(`Off`);return}let e=g.conversationId;if(e===null||M!==null&&M.conversationId===e)return;z(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 g.messages)t.sequence!==null&&(e===null||t.sequence>e)&&(e=t.sequence);return e},onStatus:e=>{M===t&&g.live!==e&&V({live:e})},onError:e=>K(e)});t.handle=n,M!==t&&n.stop()},V=e=>{let t={...g,...e};g.conversationState===`WithAgent`&&t.conversationState!==`WithAgent`&&t.agentTyping!==null&&(R(),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),g=Oe(t);for(let e of h)e();e.messages!==void 0&&Ne(),B()},H=(e,t)=>V({attachments:g.attachments.map(n=>n.key===e?{...n,...t}:n)}),U=()=>{if(x.size===0)return;let e=[...x.values()];x.clear(),V({messages:g.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}})})},W=()=>{x.clear(),y?.(),y=null},Ie=(e,t,n)=>{let r=`${e}#${t}`,i=x.get(r);x.set(r,{messageId:e,index:t,text:(i?.text??``)+n}),y||=be(()=>{y=null,U()})},G=()=>{U(),_+=1,v?.abort(),v=null},K=e=>{if(f.onError)f.onError(e);else throw e},q=()=>{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(K)}w.clear(),C.clear()},Le=e=>{let t=C.get(e);if(!t)throw Error(`No uploaded file for composer attachment ${e}.`);return t},Re=async(e,t)=>{let n=new l.AbortController;T.set(e,n);let r;try{r=await s.uploadAttachment(t,{signal:n.signal,onProgress:t=>{T.get(e)===n&&H(e,{progress:t})}})}catch{T.get(e)===n&&(T.delete(e),H(e,{status:`Failed`,progress:null,error:p.attachmentFailed}));return}T.get(e)===n?(T.delete(e),C.set(e,r),w.add(e),H(e,{status:`Ready`,progress:null})):s.deleteAttachment(r.publicId).catch(K)},ze=e=>{let t={...n(f.pageContext?.()),path:Ee(),behaviour:f.behaviour?.()??null};return e&&(t.attribution=f.attribution?.()??null),t},J=async()=>{let t=g.profile?.captcha;if(!t||!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`,p.captchaUnavailable)}if(!n)throw new e(`captcha_unavailable`,p.captchaUnavailable);return n},Be=(e,t,n)=>{let r=se(g.messages,d(e,!1));V(n?{messages:r,messagesLeftToday:t??g.messagesLeftToday,steps:[],thinking:!1}:{messages:r})},Ve=e=>{let n=g.profile?.experience.pacing;return!n||S.has(e.publicId)||e.author.kind!==`Assistant`&&e.author.kind!==`Script`?0:o(t(e.parts),n,De())},He=(e,t,n,r,i)=>{I+=1,V({pending:{typing:!0,authorKind:e.author.kind}}),F=F.then(()=>new Promise(e=>l.setTimeout(e,n))).then(()=>{--I,r()&&Be(e,t,i),I===0&&V({pending:null})})},Ue=(e,t,n)=>{let r=[...e];return r[t]=n,r},Y=(e,t)=>g.messages.map(n=>n.id===e?t(n):n),X=e=>g.messages.some(t=>t.id===e),We=()=>{R(),g.agentTyping!==null&&V({agentTyping:null})},Ge=e=>{R(),O=l.setTimeout(()=>{O=null,V({agentTyping:null})},ne),V({agentTyping:{displayName:e}})},Z=(e,t,n)=>{if(!n())return;let r=t===`turn`;if(e.name===`partDelta`)S.add(e.data.messageId),Ie(e.data.messageId,e.data.index,e.data.text);else switch(U(),e.name){case`messageStarted`:{let t=e.data.message;if(t.author.kind===`Agent`&&We(),X(t.publicId))break;V({messages:[...g.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;V({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;V({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[...x.keys()])x.get(e)?.messageId===t&&x.delete(e);V({messages:Y(t,e=>({...e,parts:[]})),...r?{thinking:!0,steps:[]}:{}});break}case`step`:{if(!r)break;let t=e.data.label;g.steps[g.steps.length-1]!==t&&V({steps:[...g.steps,t]});break}case`messageCompleted`:{let{message:t,messagesLeftToday:i}=e.data;t.author.kind===`Agent`&&We();let a=Ve(t);a>0||I>0?He(t,i,a,n,r):Be(t,i,r);break}case`conversationUpdated`:{let t=e.data;V({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=g.conversationId;if(e===null)return;let t=_;try{let n=await s.getConversation(e);if(t!==_)return;let r=new Set(g.messages.filter(e=>e.restored).map(e=>e.id));V({messages:n.messages.map(e=>d(e,r.has(e.publicId))),title:n.title,conversationState:n.state,continuesConversationId:n.continuesConversationId})}catch(e){K(e)}},$=async(e,t,n)=>{let r=_,i=new l.AbortController,a=()=>r===_&&!i.signal.aborted;v=i;let o=g.conversationId===null;xe+=1;let ee={id:`local-${xe}`,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()),V({messages:[...t,ee],thinking:!0,streaming:!0,steps:[],turnError:null,stopped:!1,...n?{editing:null,attachments:[]}:{}});try{let t=await J();await s.send({conversationId:g.conversationId,text:e.wireText,quickReplyId:e.quickReplyId,attachmentIds:e.attachments.map(e=>e.publicId),replacesMessageId:e.replacesMessageId,pageContext:ze(o),captchaToken:t},{signal:i.signal,onEvent:e=>Z(e,`turn`,a)})}catch(e){if(U(),!a())return;let t=u(e);V({messages:g.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{v===i&&(v=null)}if(await F,!a())return;U(),V({thinking:!1,streaming:!1}),await Q();let c=g.conversationId;o&&c!==null&&c!==Ce&&(Ce=c,f.onEvent?.(`chatStarted`,{conversationId:c}))},Ke=e=>V({messages:g.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{V({openTickets:await s.listOpenTickets()})}catch(e){K(e)}},Je=async()=>{try{let e=await s.listConversations({page:1,pageSize:1});V({lastConversation:e.items[0]??null})}catch(e){K(e)}},Ye=async()=>{let e;try{e=await s.getProfile(f.screen)}catch(e){V({profileError:u(e)});return}let t=ee(e,f.narrow);V({profile:e,profileError:null,features:t,messagesLeftToday:e.messagesLeftToday}),t.OpenTickets&&qe(),t.ResumeLast&&t.History&&Je(),f.conversationId&&await ut(f.conversationId)},Xe=()=>(b||=Ye(),b),Ze=async e=>{let t=typeof e==`string`?e.trim():``,n=g.attachments.filter(e=>e.status===`Ready`);if(t===``&&n.length===0||g.streaming||g.attachments.some(e=>e.status===`Uploading`))return;let r=g.messages,i=null;if(g.editing){let e=g.messages.findIndex(e=>e.id===g.editing?.messageId),t=g.messages[e];if(!t?.stored)return;i=t.id,r=g.messages.slice(0,e)}let a=n.map(e=>Le(e.key));await $({wireText:t===``?null:t,displayText:t,quickReplyId:null,replacesMessageId:i,attachments:a},r,!0)},Qe=async e=>{e.action!==`Send`||L()||(e.id===`handoff.request`&&g.features.HumanHandoff&&g.conversationId!==null&&!g.handoffPending?await xt():await $({wireText:null,displayText:e.label,quickReplyId:e.id,replacesMessageId:null,attachments:[]},g.messages,!1))},$e=async(e,t)=>{let n=await J();await s.sendOtp(e,{...t,captchaToken:n})},et=async(t,n,r=null)=>{if(g.streaming)return{ok:!1,errors:{},message:p.errorGeneric};let i=_,a=new l.AbortController,o=()=>i===_&&!a.signal.aborted;v=a,Pe(t,n);let ee=t===g.handoffContactRequestId;V({streaming:!0,thinking:!0});try{let e=await J();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 U(),V({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:u(t).message}}finally{v===a&&(v=null)}return await F,o()&&(U(),V({thinking:!1,streaming:!1}),f.onEvent?.(`inputSubmitted`,{requestId:t}),await Q(),ee&&(V({handoffContactRequestId:null}),await xt().catch(K))),{ok:!0}},tt=async e=>{let t=await s.confirmAction(e);Ke(t),f.onEvent?.(`chatActionConfirmed`,{actionId:t.actionId,kind:t.actionKind}),await Q()},nt=async(e,t)=>{Ke(await s.rejectAction(e,t)),await Q()},rt=()=>{if(!g.streaming)return;W();let e=v;v=null,e?.abort(),V({messages:g.messages.filter(e=>!e.streaming),thinking:!1,streaming:!1,stopped:!0,steps:[],pending:null})},it=async()=>{if(g.streaming||g.turnError===null&&!g.stopped)return;let e=ce(g.messages,e=>e.author.kind===`Visitor`),t=g.messages[e];t!==void 0&&await $(ve(t),g.messages.slice(0,e),!1)},at=async()=>{if(L())return;let e=ce(g.messages,e=>e.author.kind===`Visitor`&&e.stored),t=g.messages[e];t!==void 0&&await $({...ve(t),replacesMessageId:t.id},g.messages.slice(0,e),!1)},ot=e=>{let t=g.messages.find(t=>t.id===e);t?.stored&&t.author.kind===`Visitor`&&(q(),V({editing:{messageId:e,text:le(t.parts)},attachments:[]}))},st=()=>{g.editing&&(q(),V({editing:null,attachments:[]}))},ct=async e=>{let t=g.profile;if(!t||!g.features.Attachments)return;let n=t.limits,r=n.maxAttachments-g.attachments.filter(e=>e.status!==`Failed`).length,i=[],a=[];for(let t of e){let e=ue(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: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}))}V({attachments:[...g.attachments,...i]}),await Promise.all(a.map(({key:e,file:t})=>Re(e,t)))},lt=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),V({attachments:g.attachments.filter(t=>t.key!==e)})};async function ut(e){G();let t=_;V({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!==_)return;let r=n.messages.map(e=>d(e,!0));je(),Me(r),V({messages:r,conversationId:n.publicId,title:n.title,conversationState:n.state,continuesConversationId:n.continuesConversationId})}catch(e){if(t!==_)return;V({loadError:u(e)})}finally{t===_&&V({loading:!1})}}let dt=async()=>{let e=g.lastConversation;e&&await ut(e.publicId)},ft=()=>{q(),G(),W(),je(),V({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}),g.features.OpenTickets&&qe()},pt=(e,t,n)=>{V({messages:Y(e,e=>({...e,rating:t,ratingNote:n}))})},mt=async(e,t,n)=>{let r=g.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;pt(e,t,a);try{await s.rateMessage(e,{rating:t,note:a})}catch(t){throw pt(e,i.rating,i.ratingNote),t}f.onEvent?.(`rated`,{messageId:e,rating:t})},ht=e=>{let t=g.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`),V(i),t||f.onEvent?.(`chatOpened`,{layout:f.layout??null,trigger:n})},gt=e=>{g.open&&(m?.set(`wchat:dismissed`,`1`),V({open:!1}),f.onEvent?.(`chatClosed`,{layout:f.layout??null,reason:e}))},_t=e=>{m?.set(`wchat:muted`,e?`1`:`0`),V({muted:e}),f.onEvent?.(`chatSoundToggled`,{muted:e})},vt=async e=>{L()||(e===g.handoffContactRequestId&&V({handoffContactRequestId:null}),f.onEvent?.(`chatLeadSkipped`,{requestId:e}),await $({wireText:null,displayText:p.skip,quickReplyId:`lead.skip`,replacesMessageId:null,attachments:[]},g.messages,!1))},yt=async()=>{L()||(f.onEvent?.(`chatLeadCancelled`,{}),await $({wireText:null,displayText:p.cancel,quickReplyId:`lead.cancel`,replacesMessageId:null,attachments:[]},g.messages,!1))},bt=async(e,t)=>{L()||g.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,attachments:[]},g.messages,!1)},xt=async t=>{if(!g.features.HumanHandoff)throw new e(`chat_feature_off`,r.errorGeneric,403);let n=g.conversationId;if(n===null)throw new e(`conversation_required`,r.errorGeneric);if(g.streaming||g.handoffPending)throw new e(`busy`,r.errorGeneric);let i=new l.AbortController;j=i,V({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 V({messages:g.messages.filter(e=>!e.streaming),handoffPending:!1}),e}finally{j===i&&(j=null)}V({handoffPending:!1,handoffContactRequestId:a}),await Q(),f.onEvent?.(`chatHandoff`,{destination:`person`})},St=()=>{let e=g.conversationId;if(!g.features.HumanHandoff||e===null||g.conversationState!==`WithAgent`)return;let t=Date.now();k!==null&&t-k<re||(k=t,Promise.allSettled([s.sendTyping(e)]))},Ct=e=>{we=e,B()},wt=()=>{g.live===`Lost`&&Fe()&&(z(null),B())},Tt=e=>{if(f.reducedMotion?.()===!0)return ie;let t=e.navigateAfterMs;if(typeof t==`number`&&Number.isFinite(t)&&t>=0)return t;let n=g.profile?.experience.pacing.handoffPauseMs;return typeof n==`number`&&Number.isFinite(n)?n:ae},Et=()=>{ke(),g.handoffPause&&V({handoffPause:!1})};return{client:s,getState:()=>g,subscribe:e=>(h.add(e),b||Xe(),()=>{h.delete(e)}),load:Xe,submit:Ze,chooseQuickReply:Qe,answerInput:et,sendOtp:$e,confirmAction:tt,rejectAction:nt,stop:rt,retry:it,regenerate:at,startEdit:ot,cancelEdit:st,attach:ct,removeAttachment:lt,openConversation:ut,resumeLast:dt,newConversation:ft,rate:mt,open:ht,close:gt,setMuted:_t,skipField:vt,cancelLead:yt,editLeadField:bt,requestHandoff:xt,notifyTyping:St,setLiveActive:Ct,resumeLive:wt,beginHandoff:(e,t)=>{g.handoffPause||(V({handoffPause:!0}),f.onEvent?.(`chatHandoff`,{destination:e.id}),A=l.setTimeout(()=>{A=null;try{t()}catch(e){Et(),K(e)}},Tt(e)))},endHandoffPause:Et,consumeDraft:()=>{g.draft!==null&&V({draft:null})},loadAttachmentUrl:t=>{let n=P.get(t);if(n!==void 0)return n;let r=(async()=>{let n=l.createObjectUrl;if(!n)throw new e(`unsupported`,p.errorGeneric);let r=await s.getAttachment(t);if(Te)throw new e(`aborted`,p.errorGeneric);let i=n(r);return N.add(i),i})();return P.set(t,r),r.catch(()=>{P.get(t)===r&&P.delete(t)}),r},reset:()=>{q(),W(),G(),b=null,F=Promise.resolve(),I=0,S.clear(),Ce=null,je(),R(),ke(),V(ye(m))},dispose:()=>{h.clear(),Te=!0,_+=1;let e=v;v=null,e?.abort(),j?.abort(),j=null,ke(),R(),z(null),q(),W();let t=l.revokeObjectUrl;for(let e of N)t?.(e);N.clear(),P.clear(),V({attachments:[],editing:null,agentTyping:null})}}},be=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 be(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,m as createTurnApi,be 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,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),be=f.schedule??oe,m=f.prefs,h=/* @__PURE__ */ new Set,g=ye(m),_=0,v=null,y=null,xe=0,Se=0,Ce=null,b=null,x=/* @__PURE__ */ new Map,S=/* @__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,Te=!1,N=/* @__PURE__ */ new Set,P=/* @__PURE__ */ new Map,F=Promise.resolve(),I=0,Ee=()=>f.pathname?.()??l.location?.pathname??`/`,De=()=>f.reducedMotion?.()===!0||g.profile?.experience.motion===!1,L=()=>g.streaming||g.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:f.behaviour?.()??null,behaviourStarters:e.features.BehaviourStarters});return{...e,greeting:r,starters:de(e.starters,i)?e.starters:i}},R=()=>{O!==null&&(l.clearTimeout(O),O=null)},ke=()=>{A!==null&&(l.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)}]:[])),je=()=>{E.name=null,E.email=null,E.phone=null,D.clear()},Me=e=>{for(let t of Ae(e))D.add(t.actionId)},Ne=()=>{for(let e of Ae(g.messages))D.has(e.actionId)||(D.add(e.actionId),f.onEvent?.(`leadSubmitted`,{conversationId:g.conversationId,fields:{name:E.name,email:E.email,phone:E.phone},leadType:e.leadType}))},Pe=(e,t)=>{let n=g.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()))}},z=e=>{let t=M;t!==null&&(M=null,t.handle?.stop(),e!==null&&V({live:e}))},Fe=()=>!Te&&we&&g.features.HumanHandoff&&g.conversationId!==null&&(g.conversationState===`WaitingForAgent`||g.conversationState===`WithAgent`),B=()=>{if(!Fe()){M!==null&&z(`Off`);return}let e=g.conversationId;if(e===null||M!==null&&M.conversationId===e)return;z(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 g.messages)t.sequence!==null&&(e===null||t.sequence>e)&&(e=t.sequence);return e},onStatus:e=>{M===t&&g.live!==e&&V({live:e})},onError:e=>K(e)});t.handle=n,M!==t&&n.stop()},V=e=>{let t={...g,...e};g.conversationState===`WithAgent`&&t.conversationState!==`WithAgent`&&t.agentTyping!==null&&(R(),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),g=Oe(t);for(let e of h)e();e.messages!==void 0&&Ne(),B()},H=(e,t)=>V({attachments:g.attachments.map(n=>n.key===e?{...n,...t}:n)}),U=()=>{if(x.size===0)return;let e=[...x.values()];x.clear(),V({messages:g.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}})})},W=()=>{x.clear(),y?.(),y=null},Ie=(e,t,n)=>{let r=`${e}#${t}`,i=x.get(r);x.set(r,{messageId:e,index:t,text:(i?.text??``)+n}),y||=be(()=>{y=null,U()})},G=()=>{U(),_+=1,v?.abort(),v=null},K=e=>{if(f.onError)f.onError(e);else throw e},q=()=>{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(K)}w.clear(),C.clear()},Le=e=>{let t=C.get(e);if(!t)throw Error(`No uploaded file for composer attachment ${e}.`);return t},Re=async(e,t)=>{let n=new l.AbortController;T.set(e,n);let r;try{r=await s.uploadAttachment(t,{signal:n.signal,onProgress:t=>{T.get(e)===n&&H(e,{progress:t})}})}catch{T.get(e)===n&&(T.delete(e),H(e,{status:`Failed`,progress:null,error:p.attachmentFailed}));return}T.get(e)===n?(T.delete(e),C.set(e,r),w.add(e),H(e,{status:`Ready`,progress:null})):s.deleteAttachment(r.publicId).catch(K)},ze=e=>{let t={...n(f.pageContext?.()),path:Ee(),behaviour:f.behaviour?.()??null};return e&&(t.attribution=f.attribution?.()??null),t},J=async()=>{let t=g.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`,p.captchaUnavailable)}if(!n)throw new e(`captcha_unavailable`,p.captchaUnavailable);return n},Be=(e,t,n)=>{let r=se(g.messages,d(e,!1));V(n?{messages:r,messagesLeftToday:t??g.messagesLeftToday,steps:[],thinking:!1}:{messages:r})},Ve=e=>{let n=g.profile?.experience.pacing;return!n||S.has(e.publicId)||e.author.kind!==`Assistant`&&e.author.kind!==`Script`?0:o(t(e.parts),n,De())},He=(e,t,n,r,i)=>{I+=1,V({pending:{typing:!0,authorKind:e.author.kind}}),F=F.then(()=>new Promise(e=>l.setTimeout(e,n))).then(()=>{--I,r()&&Be(e,t,i),I===0&&V({pending:null})})},Ue=(e,t,n)=>{let r=[...e];return r[t]=n,r},Y=(e,t)=>g.messages.map(n=>n.id===e?t(n):n),X=e=>g.messages.some(t=>t.id===e),We=()=>{R(),g.agentTyping!==null&&V({agentTyping:null})},Ge=e=>{R(),O=l.setTimeout(()=>{O=null,V({agentTyping:null})},ne),V({agentTyping:{displayName:e}})},Z=(e,t,n)=>{if(!n())return;let r=t===`turn`;if(e.name===`partDelta`)S.add(e.data.messageId),Ie(e.data.messageId,e.data.index,e.data.text);else switch(U(),e.name){case`messageStarted`:{let t=e.data.message;if(t.author.kind===`Agent`&&We(),X(t.publicId))break;V({messages:[...g.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;V({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;V({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[...x.keys()])x.get(e)?.messageId===t&&x.delete(e);V({messages:Y(t,e=>({...e,parts:[]})),...r?{thinking:!0,steps:[]}:{}});break}case`step`:{if(!r)break;let t=e.data.label;g.steps[g.steps.length-1]!==t&&V({steps:[...g.steps,t]});break}case`messageCompleted`:{let{message:t,messagesLeftToday:i}=e.data;t.author.kind===`Agent`&&We();let a=Ve(t);a>0||I>0?He(t,i,a,n,r):Be(t,i,r);break}case`conversationUpdated`:{let t=e.data;V({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=g.conversationId;if(e===null)return;let t=_;try{let n=await s.getConversation(e);if(t!==_)return;let r=new Set(g.messages.filter(e=>e.restored).map(e=>e.id));V({messages:n.messages.map(e=>d(e,r.has(e.publicId))),title:n.title,conversationState:n.state,continuesConversationId:n.continuesConversationId})}catch(e){K(e)}},$=async(e,t,n)=>{let r=_,i=new l.AbortController,a=()=>r===_&&!i.signal.aborted;v=i;let o=g.conversationId===null;xe+=1;let ee={id:`local-${xe}`,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()),V({messages:[...t,ee],thinking:!0,streaming:!0,steps:[],turnError:null,stopped:!1,...n?{editing:null,attachments:[]}:{}});try{let t=await J();await s.send({conversationId:g.conversationId,text:e.wireText,quickReplyId:e.quickReplyId,attachmentIds:e.attachments.map(e=>e.publicId),replacesMessageId:e.replacesMessageId,pageContext:ze(o),captchaToken:t},{signal:i.signal,onEvent:e=>Z(e,`turn`,a)})}catch(e){if(U(),!a())return;let t=u(e);V({messages:g.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{v===i&&(v=null)}if(await F,!a())return;U(),V({thinking:!1,streaming:!1}),await Q();let c=g.conversationId;o&&c!==null&&c!==Ce&&(Ce=c,f.onEvent?.(`chatStarted`,{conversationId:c}))},Ke=e=>V({messages:g.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{V({openTickets:await s.listOpenTickets()})}catch(e){K(e)}},Je=async()=>{try{let e=await s.listConversations({page:1,pageSize:1});V({lastConversation:e.items[0]??null})}catch(e){K(e)}},Ye=async()=>{let e;try{e=await s.getProfile(f.screen)}catch(e){V({profileError:u(e)});return}let t=ee(e,f.narrow);V({profile:e,profileError:null,features:t,messagesLeftToday:e.messagesLeftToday}),t.OpenTickets&&qe(),t.ResumeLast&&t.History&&Je(),f.conversationId&&await ut(f.conversationId)},Xe=()=>(b||=Ye(),b),Ze=async e=>{let t=typeof e==`string`?e.trim():``,n=g.attachments.filter(e=>e.status===`Ready`);if(t===``&&n.length===0||g.streaming||g.attachments.some(e=>e.status===`Uploading`))return;let r=g.messages,i=null;if(g.editing){let e=g.messages.findIndex(e=>e.id===g.editing?.messageId),t=g.messages[e];if(!t?.stored)return;i=t.id,r=g.messages.slice(0,e)}let a=n.map(e=>Le(e.key));await $({wireText:t===``?null:t,displayText:t,quickReplyId:null,replacesMessageId:i,attachments:a},r,!0)},Qe=async e=>{e.action!==`Send`||L()||(e.id===`handoff.request`&&g.features.HumanHandoff&&g.conversationId!==null&&!g.handoffPending?await xt():await $({wireText:null,displayText:e.label,quickReplyId:e.id,replacesMessageId:null,attachments:[]},g.messages,!1))},$e=async(e,t)=>{let n=await J();await s.sendOtp(e,{...t,captchaToken:n})},et=async(t,n,r=null)=>{if(g.streaming)return{ok:!1,errors:{},message:p.errorGeneric};let i=_,a=new l.AbortController,o=()=>i===_&&!a.signal.aborted;v=a,Pe(t,n);let ee=t===g.handoffContactRequestId;V({streaming:!0,thinking:!0});try{let e=await J();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 U(),V({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:u(t).message}}finally{v===a&&(v=null)}return await F,o()&&(U(),V({thinking:!1,streaming:!1}),f.onEvent?.(`inputSubmitted`,{requestId:t}),await Q(),ee&&(V({handoffContactRequestId:null}),await xt().catch(K))),{ok:!0}},tt=async e=>{let t=await s.confirmAction(e);Ke(t),f.onEvent?.(`chatActionConfirmed`,{actionId:t.actionId,kind:t.actionKind}),await Q()},nt=async(e,t)=>{Ke(await s.rejectAction(e,t)),await Q()},rt=()=>{if(!g.streaming)return;W();let e=v;v=null,e?.abort(),V({messages:g.messages.filter(e=>!e.streaming),thinking:!1,streaming:!1,stopped:!0,steps:[],pending:null})},it=async()=>{if(g.streaming||g.turnError===null&&!g.stopped)return;let e=ce(g.messages,e=>e.author.kind===`Visitor`),t=g.messages[e];t!==void 0&&await $(ve(t),g.messages.slice(0,e),!1)},at=async()=>{if(L())return;let e=ce(g.messages,e=>e.author.kind===`Visitor`&&e.stored),t=g.messages[e];t!==void 0&&await $({...ve(t),replacesMessageId:t.id},g.messages.slice(0,e),!1)},ot=e=>{let t=g.messages.find(t=>t.id===e);t?.stored&&t.author.kind===`Visitor`&&(q(),V({editing:{messageId:e,text:le(t.parts)},attachments:[]}))},st=()=>{g.editing&&(q(),V({editing:null,attachments:[]}))},ct=async e=>{let t=g.profile;if(!t||!g.features.Attachments)return;let n=t.limits,r=n.maxAttachments-g.attachments.filter(e=>e.status!==`Failed`).length,i=[],a=[];for(let t of e){let e=ue(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: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}))}V({attachments:[...g.attachments,...i]}),await Promise.all(a.map(({key:e,file:t})=>Re(e,t)))},lt=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),V({attachments:g.attachments.filter(t=>t.key!==e)})};async function ut(e){G();let t=_;V({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!==_)return;let r=n.messages.map(e=>d(e,!0));je(),Me(r),V({messages:r,conversationId:n.publicId,title:n.title,conversationState:n.state,continuesConversationId:n.continuesConversationId})}catch(e){if(t!==_)return;V({loadError:u(e)})}finally{t===_&&V({loading:!1})}}let dt=async()=>{let e=g.lastConversation;e&&await ut(e.publicId)},ft=()=>{q(),G(),W(),je(),V({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}),g.features.OpenTickets&&qe()},pt=(e,t,n)=>{V({messages:Y(e,e=>({...e,rating:t,ratingNote:n}))})},mt=async(e,t,n)=>{let r=g.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;pt(e,t,a);try{await s.rateMessage(e,{rating:t,note:a})}catch(t){throw pt(e,i.rating,i.ratingNote),t}f.onEvent?.(`rated`,{messageId:e,rating:t})},ht=e=>{let t=g.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`),V(i),t||f.onEvent?.(`chatOpened`,{layout:f.layout??null,trigger:n})},gt=e=>{g.open&&(m?.set(`wchat:dismissed`,`1`),V({open:!1}),f.onEvent?.(`chatClosed`,{layout:f.layout??null,reason:e}))},_t=e=>{m?.set(`wchat:muted`,e?`1`:`0`),V({muted:e}),f.onEvent?.(`chatSoundToggled`,{muted:e})},vt=async e=>{L()||(e===g.handoffContactRequestId&&V({handoffContactRequestId:null}),f.onEvent?.(`chatLeadSkipped`,{requestId:e}),await $({wireText:null,displayText:p.skip,quickReplyId:`lead.skip`,replacesMessageId:null,attachments:[]},g.messages,!1))},yt=async()=>{L()||(f.onEvent?.(`chatLeadCancelled`,{}),await $({wireText:null,displayText:p.cancel,quickReplyId:`lead.cancel`,replacesMessageId:null,attachments:[]},g.messages,!1))},bt=async(e,t)=>{L()||g.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,attachments:[]},g.messages,!1)},xt=async t=>{if(!g.features.HumanHandoff)throw new e(`chat_feature_off`,r.errorGeneric,403);let n=g.conversationId;if(n===null)throw new e(`conversation_required`,r.errorGeneric);if(g.streaming||g.handoffPending)throw new e(`busy`,r.errorGeneric);let i=new l.AbortController;j=i,V({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 V({messages:g.messages.filter(e=>!e.streaming),handoffPending:!1}),e}finally{j===i&&(j=null)}V({handoffPending:!1,handoffContactRequestId:a}),await Q(),f.onEvent?.(`chatHandoff`,{destination:`person`})},St=()=>{let e=g.conversationId;if(!g.features.HumanHandoff||e===null||g.conversationState!==`WithAgent`)return;let t=Date.now();k!==null&&t-k<re||(k=t,Promise.allSettled([s.sendTyping(e)]))},Ct=e=>{we=e,B()},wt=()=>{g.live===`Lost`&&Fe()&&(z(null),B())},Tt=e=>{if(f.reducedMotion?.()===!0)return ie;let t=e.navigateAfterMs;if(typeof t==`number`&&Number.isFinite(t)&&t>=0)return t;let n=g.profile?.experience.pacing.handoffPauseMs;return typeof n==`number`&&Number.isFinite(n)?n:ae},Et=()=>{ke(),g.handoffPause&&V({handoffPause:!1})};return{client:s,getState:()=>g,subscribe:e=>(h.add(e),b||Xe(),()=>{h.delete(e)}),load:Xe,submit:Ze,chooseQuickReply:Qe,answerInput:et,sendOtp:$e,confirmAction:tt,rejectAction:nt,stop:rt,retry:it,regenerate:at,startEdit:ot,cancelEdit:st,attach:ct,removeAttachment:lt,openConversation:ut,resumeLast:dt,newConversation:ft,rate:mt,open:ht,close:gt,setMuted:_t,skipField:vt,cancelLead:yt,editLeadField:bt,requestHandoff:xt,notifyTyping:St,setLiveActive:Ct,resumeLive:wt,beginHandoff:(e,t)=>{g.handoffPause||(V({handoffPause:!0}),f.onEvent?.(`chatHandoff`,{destination:e.id}),A=l.setTimeout(()=>{A=null;try{t()}catch(e){Et(),K(e)}},Tt(e)))},endHandoffPause:Et,consumeDraft:()=>{g.draft!==null&&V({draft:null})},loadAttachmentUrl:t=>{let n=P.get(t);if(n!==void 0)return n;let r=(async()=>{let n=l.createObjectUrl;if(!n)throw new e(`unsupported`,p.errorGeneric);let r=await s.getAttachment(t);if(Te)throw new e(`aborted`,p.errorGeneric);let i=n(r);return N.add(i),i})();return P.set(t,r),r.catch(()=>{P.get(t)===r&&P.delete(t)}),r},reset:()=>{q(),W(),G(),b=null,F=Promise.resolve(),I=0,S.clear(),Ce=null,je(),R(),ke(),V(ye(m))},dispose:()=>{h.clear(),Te=!0,_+=1;let e=v;v=null,e?.abort(),j?.abort(),j=null,ke(),R(),z(null),q(),W();let t=l.revokeObjectUrl;for(let e of N)t?.(e);N.clear(),P.clear(),V({attachments:[],editing:null,agentTyping:null})}}},be=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 be(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,m as createTurnApi,be as handoffSettledIds};
@@ -367,6 +367,7 @@ export interface ChatCaptchaSettings {
367
367
  mode: ChatCaptchaMode;
368
368
  siteKey: string | null;
369
369
  action: string;
370
+ testToken: string | null;
370
371
  }
371
372
  export interface ChatLimits {
372
373
  maxMessageLength: number;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webority/chat-core",
3
- "version": "0.151.1",
3
+ "version": "0.152.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.173.0"
29
+ "@webority/markdown-core": "^0.174.0"
30
30
  },
31
31
  "devDependencies": {
32
- "@webority/markdown-core": "0.173.1",
32
+ "@webority/markdown-core": "0.174.1",
33
33
  "typescript": "^7.0.2",
34
34
  "vite": "^8.1.6",
35
35
  "vitest": "5.1.0"