@customer-agent/sdk 0.7.1-test.7bc1d0145e2e → 0.8.0-test.9c55f78ce2b3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/chunks/{App-CbauHu6i.js → App-4aMv2rvR.js} +2 -2
- package/chunks/{InterviewChatScreen-Dx7IiTbY.js → InterviewChatScreen-BjKUe3ZV.js} +1 -1
- package/chunks/Panel-CDuB9D7s.js +7 -0
- package/chunks/{WidgetComposer-C_Y7bwhP.js → WidgetComposer-ysA2-sTG.js} +1 -1
- package/chunks/{constants-DpT1T6rb.js → constants-Ce5kEnIK.js} +1 -1
- package/chunks/{controller-BsoOhWVN.js → controller-CbWyMVSt.js} +1 -1
- package/chunks/routes-YeWhHObb.js +1 -0
- package/index.js +1 -1
- package/package.json +1 -1
- package/react.js +1 -1
- package/runtime.es.js +1 -1
- package/sdk.js +1 -1
- package/types/sdk/controller.d.ts +2 -2
- package/types/sdk/public-types.d.ts +7 -4
- package/types/types.d.ts +10 -0
- package/chunks/Panel-S4xOfPIe.js +0 -7
- package/chunks/routes-Dh46ka4-.js +0 -1
package/sdk.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
(function(){var e=`0.
|
|
1
|
+
(function(){var e=`0.8.0-test.9c55f78ce2b3`;function t(){typeof window>`u`||(window.__customerAgentVersion=e)}var n=`__customerAgentRuntime`,r=`__customerAgentScript`,i=typeof document<`u`&&document.currentScript instanceof HTMLScriptElement?document.currentScript:null,a=[];t();var o=`idle`,s=null,c=null;function l(e){return typeof e==`object`&&!!e}function u(e){return Array.prototype.slice.call(e)}function d(){let e=i?.src??new URL(`sdk.js`,window.location.href).toString();return new URL(`runtime.es.js`,e).toString()}function f(e){let t=e.CustomerAgent??e.default;if(typeof t!=`function`)throw Error(`CustomerAgent widget runtime module did not export CustomerAgent.`);return Object.assign(t,{[n]:!0})}function p(){if(!s)return;let e=a.splice(0);for(let t of e)t(s)}async function m(){return o===`ready`&&s?s:o===`loading`&&c?await c:(o=`loading`,c=import(d()).then(e=>(s=f(e),window.CustomerAgent=s,o=`ready`,p(),s)).catch(e=>{throw o=`failed`,c=null,console.error(`CustomerAgent widget runtime failed to load.`,e),e}),await c)}function h(e){if(s){e(s);return}a.push(e),m().catch(()=>{})}function g(e,t){h(n=>{let r=n[e];typeof r==`function`&&r(...t)})}function _(e){return h(t=>{t(`boot`,e)}),R}async function v(){return await(await m()).ensureInvitation()}async function y(e){return await(await m()).startInvitation(e)}async function b(){return await(await m()).startInterview()}async function x(e,t){await(await m()).chooseInvitation(e,t)}async function S(e){await(await m()).sendInterviewMessage(e)}async function C(e){return await(await m()).loadInterviewReward(e)}function w(e){g(`update`,[e])}function T(e){g(`show`,[e])}function E(){g(`hide`,[])}function D(e){g(`toggle`,[e])}function O(e){g(`openEntry`,[e])}function k(){g(`shutdown`,[])}function A(e){g(`identify`,[e])}function j(e,t){g(`setContext`,[e,t])}async function M(){return await(await m()).getSession()}function N(){return s?.getSupportState()??null}function P(){return s?.getInterviewState()??null}function F(){return s?.getInterviewSession()??null}function I(){return s?.getState()??null}function L(e,t){let n=!0,r=()=>{};return h(i=>{n&&(r=i.on(e,t))}),()=>{n=!1,r()}}var R={chooseInvitation:x,async ensureInvitation(){let e=await v();if(!e)throw Error(`CustomerAgent widget is not initialized.`);return e},getInterviewState(){let e=P();if(!e)throw Error(`CustomerAgent widget is not initialized.`);return e},getInterviewSession(){return F()},async getSession(){let e=await M();if(!e)throw Error(`CustomerAgent widget is not initialized.`);return e},getState(){let e=I();if(!e)throw Error(`CustomerAgent widget is not initialized.`);return e},getSupportState(){let e=N();if(!e)throw Error(`CustomerAgent widget is not initialized.`);return e},hide:E,identify:A,on:L,openEntry:O,loadInterviewReward:C,sendInterviewMessage:S,setContext:j,show:T,shutdown:k,async startInterview(){let e=await b();if(!e)throw Error(`CustomerAgent widget is not initialized.`);return e},async startInvitation(e){let t=await y(e);if(!t)throw Error(`CustomerAgent widget is not initialized.`);return t},toggle:D,update:w};function z(e,...t){switch(e){case`boot`:return _(t[0]);case`chooseInvitation`:return x(t[0],t[1]);case`ensureInvitation`:return v();case`getSession`:return M();case`getState`:return I();case`getSupportState`:return N();case`getInterviewState`:return P();case`getInterviewSession`:return F();case`hide`:return E();case`identify`:return A(t[0]);case`on`:return L(t[0],t[1]);case`openEntry`:return O(t[0]);case`loadInterviewReward`:return C(t[0]);case`sendInterviewMessage`:return S(t[0]);case`setContext`:return j(t[0],t[1]);case`show`:return T(t[0]);case`shutdown`:return k();case`startInvitation`:return y(t[0]);case`startInterview`:return b();case`toggle`:return D(t[0]);case`update`:return w(t[0]);default:throw Error(`CustomerAgent received an unknown command: ${String(e)}.`)}}var B=Object.assign(z,{[r]:!0,boot:_,chooseInvitation:x,ensureInvitation:v,getInterviewState:P,getInterviewSession:F,getSession:M,getState:I,getSupportState:N,hide:E,identify:A,on:L,openEntry:O,loadInterviewReward:C,sendInterviewMessage:S,setContext:j,show:T,shutdown:k,startInterview:b,startInvitation:y,toggle:D,update:w});function V(e){if(!l(e))return!1;let t=e.q;if(!Array.isArray(t)||t.length===0)return!1;for(let e of t)z(...u(e));return!0}function H(){if(!i)return;let e=i.dataset.appId;e&&B(`boot`,{app_id:e,open_on_init:i.dataset.open===`true`,position:i.dataset.position===`bottom-left`?`bottom-left`:`bottom-right`})}if(typeof window<`u`){let e=window.CustomerAgent;window.CustomerAgent=B,V(e)||H()}})();
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { WidgetContextJson, WidgetUser } from '../types';
|
|
2
2
|
import { CustomerAgentEventMap, CustomerAgentEventName } from './events';
|
|
3
|
-
import { CustomerAgentGlobal, CustomerAgentInterviewInvitationChoice, CustomerAgentOptions, CustomerAgentTarget, CustomerAgentWidget, SetContextOptions } from './public-types';
|
|
3
|
+
import { CustomerAgentGlobal, CustomerAgentInterviewInvitationChoice, CustomerAgentOptions, CustomerAgentTarget, CustomerAgentUpdateOptions, CustomerAgentWidget, SetContextOptions } from './public-types';
|
|
4
4
|
declare function boot(options: CustomerAgentOptions): CustomerAgentWidget;
|
|
5
5
|
declare function ensureInvitation(): Promise<{
|
|
6
6
|
invitationId: string;
|
|
@@ -16,7 +16,7 @@ declare function startInterview(): Promise<{
|
|
|
16
16
|
declare function chooseInvitation(invitationId: string, choice: CustomerAgentInterviewInvitationChoice): Promise<void>;
|
|
17
17
|
declare function sendInterviewMessage(content: string): Promise<void>;
|
|
18
18
|
declare function loadInterviewReward(sessionId?: string): Promise<unknown>;
|
|
19
|
-
declare function update(options:
|
|
19
|
+
declare function update(options: CustomerAgentUpdateOptions): void;
|
|
20
20
|
declare function show(target?: CustomerAgentTarget): void;
|
|
21
21
|
declare function hide(): void;
|
|
22
22
|
declare function toggle(target?: CustomerAgentTarget): void;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { CustomerAgentInterviewState, InterviewInvitationChoice, InterviewSessionResponse } from '../runtime/interview/interviewTypes';
|
|
2
2
|
import { CustomerAgentSupportState } from '../runtime/support/supportTypes';
|
|
3
|
-
import { WidgetContextJson, WidgetHeaderOptions, WidgetLauncherOptions, WidgetLauncherTarget, WidgetLocaleMessages, WidgetMobileOptions, WidgetTheme, WidgetUser } from '../types';
|
|
3
|
+
import { WidgetContextJson, WidgetExperimentalOptions, WidgetHeaderOptions, WidgetLauncherOptions, WidgetLauncherTarget, WidgetLocaleMessages, WidgetMobileOptions, WidgetPageOptions, WidgetTheme, WidgetUser } from '../types';
|
|
4
4
|
import { CustomerAgentEventMap, CustomerAgentEventName } from './events';
|
|
5
5
|
export type { CustomerAgentInterviewState } from '../runtime/interview/interviewTypes';
|
|
6
6
|
export type { InterviewInvitationAction as CustomerAgentInterviewInvitationAction, InterviewInvitationChoice as CustomerAgentInterviewInvitationChoice } from '../runtime/interview/interviewTypes';
|
|
@@ -14,6 +14,7 @@ export type CustomerAgentOptions = {
|
|
|
14
14
|
};
|
|
15
15
|
context?: WidgetContextJson;
|
|
16
16
|
context_ready?: boolean;
|
|
17
|
+
experimental?: WidgetExperimentalOptions;
|
|
17
18
|
header?: WidgetHeaderOptions;
|
|
18
19
|
launcher?: WidgetLauncherOptions & {
|
|
19
20
|
target?: WidgetLauncherTarget;
|
|
@@ -23,10 +24,12 @@ export type CustomerAgentOptions = {
|
|
|
23
24
|
mobile?: WidgetMobileOptions;
|
|
24
25
|
mount?: HTMLElement | string;
|
|
25
26
|
open_on_init?: boolean;
|
|
27
|
+
page?: WidgetPageOptions;
|
|
26
28
|
position?: "bottom-right" | "bottom-left";
|
|
27
29
|
theme?: WidgetTheme;
|
|
28
30
|
user?: WidgetUser;
|
|
29
31
|
};
|
|
32
|
+
export type CustomerAgentUpdateOptions = Partial<Omit<CustomerAgentOptions, "experimental">>;
|
|
30
33
|
export type SetContextOptions = {
|
|
31
34
|
merge?: boolean;
|
|
32
35
|
ready?: boolean;
|
|
@@ -87,7 +90,7 @@ export type CustomerAgentWidget = {
|
|
|
87
90
|
sessionId: string;
|
|
88
91
|
}>;
|
|
89
92
|
toggle(target?: CustomerAgentTarget): void;
|
|
90
|
-
update(options:
|
|
93
|
+
update(options: CustomerAgentUpdateOptions): void;
|
|
91
94
|
};
|
|
92
95
|
export type CustomerAgentGlobal = {
|
|
93
96
|
(command: "boot", options: CustomerAgentOptions): CustomerAgentWidget;
|
|
@@ -117,7 +120,7 @@ export type CustomerAgentGlobal = {
|
|
|
117
120
|
<TEventName extends CustomerAgentEventName>(command: "on", eventName: TEventName, handler: (event: CustomerAgentEventMap[TEventName]) => void): () => void;
|
|
118
121
|
(command: "setContext", context: WidgetContextJson, options?: SetContextOptions): void;
|
|
119
122
|
(command: "show" | "toggle", target?: CustomerAgentTarget): void;
|
|
120
|
-
(command: "update", options:
|
|
123
|
+
(command: "update", options: CustomerAgentUpdateOptions): void;
|
|
121
124
|
(command: "hide" | "shutdown"): void;
|
|
122
125
|
boot(options: CustomerAgentOptions): CustomerAgentWidget;
|
|
123
126
|
chooseInvitation(invitationId: string, choice: InterviewInvitationChoice): Promise<void>;
|
|
@@ -149,5 +152,5 @@ export type CustomerAgentGlobal = {
|
|
|
149
152
|
sessionId: string;
|
|
150
153
|
} | null>;
|
|
151
154
|
toggle(target?: CustomerAgentTarget): void;
|
|
152
|
-
update(options:
|
|
155
|
+
update(options: CustomerAgentUpdateOptions): void;
|
|
153
156
|
};
|
package/types/types.d.ts
CHANGED
|
@@ -11,6 +11,11 @@ export type WidgetMobileOptions = {
|
|
|
11
11
|
mode?: "auto" | "fullscreen" | "bottom-sheet";
|
|
12
12
|
};
|
|
13
13
|
export type WidgetMobilePresentation = "desktop" | "fullscreen" | "bottom-sheet";
|
|
14
|
+
export type WidgetPageOptions = {
|
|
15
|
+
customerOrigin?: string;
|
|
16
|
+
pagePath?: string;
|
|
17
|
+
pageUrl?: string;
|
|
18
|
+
};
|
|
14
19
|
export type WidgetLauncherPlacement = "bottom" | "left" | "right" | "top";
|
|
15
20
|
export type WidgetLauncherStyle = Record<string, number | string | undefined>;
|
|
16
21
|
export type WidgetLauncherVariableName = "bg-color" | "border-color" | "border-radius" | "border-style" | "border-width" | "box-shadow" | "color" | "hover-bg-color" | "hover-border-color" | "hover-border-radius" | "hover-border-style" | "hover-border-width" | "hover-box-shadow" | "hover-color";
|
|
@@ -38,6 +43,9 @@ export type WidgetHeaderOptions = {
|
|
|
38
43
|
close?: boolean;
|
|
39
44
|
menu?: boolean;
|
|
40
45
|
};
|
|
46
|
+
export type WidgetExperimentalOptions = {
|
|
47
|
+
stablePanelIframeInit?: boolean;
|
|
48
|
+
};
|
|
41
49
|
export type WidgetViewport = {
|
|
42
50
|
height: number;
|
|
43
51
|
isMobile: boolean;
|
|
@@ -58,12 +66,14 @@ export type WidgetOptions = {
|
|
|
58
66
|
};
|
|
59
67
|
context?: WidgetContextJson;
|
|
60
68
|
context_ready?: boolean;
|
|
69
|
+
experimental?: WidgetExperimentalOptions;
|
|
61
70
|
header?: WidgetHeaderOptions;
|
|
62
71
|
locale?: string;
|
|
63
72
|
launcher?: WidgetLauncherOptions;
|
|
64
73
|
messages?: WidgetLocaleMessages;
|
|
65
74
|
mobile?: WidgetMobileOptions;
|
|
66
75
|
open_on_init?: boolean;
|
|
76
|
+
page?: WidgetPageOptions;
|
|
67
77
|
theme?: WidgetTheme;
|
|
68
78
|
user?: WidgetUser;
|
|
69
79
|
};
|
package/chunks/Panel-S4xOfPIe.js
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import{t as e}from"./constants-DpT1T6rb.js";import{n as t,t as n}from"./interviewTypes-Ch2NsXKB.js";import{a as r,b as i,c as a,d as o,f as s,i as c,l,m as u,n as d,o as f,r as ee,s as p,t as m,v as h,y as g}from"./routes-Dh46ka4-.js";import{d as _,l as te,s as ne,t as v}from"./navigationState-LdqG_Osx.js";import{t as y}from"./i18n-Q8u2wtW4.js";import{r as b}from"../runtime.es.js";import{t as x}from"./react-CKmEJ8Ba.js";import{A as re,C as ie,D as ae,E as oe,O as se,S as ce,T as S,_ as C,a as w,b as T,c as le,d as E,f as D,g as ue,h as de,i as fe,j as pe,k as O,l as me,m as k,n as he,o as ge,r as _e,s as ve,t as ye,u as be,v as A,w as xe,x as Se,y as Ce}from"./WidgetComposer-C_Y7bwhP.js";import{n as we,t as j}from"./WidgetGlobalLoading-B_z-6_yk.js";import{t as M}from"./DockNavigation-CI9i1n3W.js";import{t as N}from"./conversationRegistry-Y5Ouo35n.js";import{t as P}from"./jsx-runtime-S2ZBQkZm.js";import{t as F}from"./classNames-3q0x02_x.js";import{N as Te}from"./useSmooth-CYGvfMVe.js";import{S as I,_ as Ee,b as De,c as Oe,d as ke,f as Ae,g as je,h as Me,l as Ne,m as L,p as Pe,s as R,u as Fe,v as Ie,w as Le}from"./dist-dzGCY2H5.js";var z=b(x(),1),B=P(),Re=`Dialog`,[ze,Be]=Ee(Re),[Ve,V]=ze(Re),He=e=>{let{__scopeDialog:t,children:n,open:r,defaultOpen:i,onOpenChange:a,modal:o=!0}=e,s=z.useRef(null),c=z.useRef(null),[l,u]=Me({prop:r,defaultProp:i??!1,onChange:a,caller:Re});return(0,B.jsx)(Ve,{scope:t,triggerRef:s,contentRef:c,contentId:Pe(),titleId:Pe(),descriptionId:Pe(),open:l,onOpenChange:u,onOpenToggle:z.useCallback(()=>u(e=>!e),[u]),modal:o,children:n})};He.displayName=Re;var Ue=`DialogTrigger`,We=z.forwardRef((e,t)=>{let{__scopeDialog:n,...r}=e,i=V(Ue,n),a=Le(t,i.triggerRef);return(0,B.jsx)(Ie.button,{type:`button`,"aria-haspopup":`dialog`,"aria-expanded":i.open,"aria-controls":i.contentId,"data-state":it(i.open),...r,ref:a,onClick:I(e.onClick,i.onOpenToggle)})});We.displayName=Ue;var H=`DialogPortal`,[U,Ge]=ze(H,{forceMount:void 0}),Ke=e=>{let{__scopeDialog:t,forceMount:n,children:r,container:i}=e,a=V(H,t);return(0,B.jsx)(U,{scope:t,forceMount:n,children:z.Children.map(r,e=>(0,B.jsx)(L,{present:n||a.open,children:(0,B.jsx)(Fe,{asChild:!0,container:i,children:e})}))})};Ke.displayName=H;var qe=`DialogOverlay`,Je=z.forwardRef((e,t)=>{let n=Ge(qe,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,a=V(qe,e.__scopeDialog);return a.modal?(0,B.jsx)(L,{present:r||a.open,children:(0,B.jsx)(W,{...i,ref:t})}):null});Je.displayName=qe;var Ye=De(`DialogOverlay.RemoveScroll`),W=z.forwardRef((e,t)=>{let{__scopeDialog:n,...r}=e,i=V(qe,n);return(0,B.jsx)(Oe,{as:Ye,allowPinchZoom:!0,shards:[i.contentRef],children:(0,B.jsx)(Ie.div,{"data-state":it(i.open),...r,ref:t,style:{pointerEvents:`auto`,...r.style}})})}),G=`DialogContent`,Xe=z.forwardRef((e,t)=>{let n=Ge(G,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,a=V(G,e.__scopeDialog);return(0,B.jsx)(L,{present:r||a.open,children:a.modal?(0,B.jsx)(Ze,{...i,ref:t}):(0,B.jsx)(Qe,{...i,ref:t})})});Xe.displayName=G;var Ze=z.forwardRef((e,t)=>{let n=V(G,e.__scopeDialog),r=z.useRef(null),i=Le(t,n.contentRef,r);return z.useEffect(()=>{let e=r.current;if(e)return R(e)},[]),(0,B.jsx)($e,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:I(e.onCloseAutoFocus,e=>{e.preventDefault(),n.triggerRef.current?.focus()}),onPointerDownOutside:I(e.onPointerDownOutside,e=>{let t=e.detail.originalEvent,n=t.button===0&&t.ctrlKey===!0;(t.button===2||n)&&e.preventDefault()}),onFocusOutside:I(e.onFocusOutside,e=>e.preventDefault())})}),Qe=z.forwardRef((e,t)=>{let n=V(G,e.__scopeDialog),r=z.useRef(!1),i=z.useRef(!1);return(0,B.jsx)($e,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:t=>{e.onCloseAutoFocus?.(t),t.defaultPrevented||(r.current||n.triggerRef.current?.focus(),t.preventDefault()),r.current=!1,i.current=!1},onInteractOutside:t=>{e.onInteractOutside?.(t),t.defaultPrevented||(r.current=!0,t.detail.originalEvent.type===`pointerdown`&&(i.current=!0));let a=t.target;n.triggerRef.current?.contains(a)&&t.preventDefault(),t.detail.originalEvent.type===`focusin`&&i.current&&t.preventDefault()}})}),$e=z.forwardRef((e,t)=>{let{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:i,onCloseAutoFocus:a,...o}=e,s=V(G,n),c=z.useRef(null),l=Le(t,c);return Ne(),(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(ke,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:i,onUnmountAutoFocus:a,children:(0,B.jsx)(Ae,{role:`dialog`,id:s.contentId,"aria-describedby":s.descriptionId,"aria-labelledby":s.titleId,"data-state":it(s.open),...o,ref:l,onDismiss:()=>s.onOpenChange(!1)})}),(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(ct,{titleId:s.titleId}),(0,B.jsx)(ut,{contentRef:c,descriptionId:s.descriptionId})]})]})}),et=`DialogTitle`,K=z.forwardRef((e,t)=>{let{__scopeDialog:n,...r}=e,i=V(et,n);return(0,B.jsx)(Ie.h2,{id:i.titleId,...r,ref:t})});K.displayName=et;var tt=`DialogDescription`,nt=z.forwardRef((e,t)=>{let{__scopeDialog:n,...r}=e,i=V(tt,n);return(0,B.jsx)(Ie.p,{id:i.descriptionId,...r,ref:t})});nt.displayName=tt;var q=`DialogClose`,rt=z.forwardRef((e,t)=>{let{__scopeDialog:n,...r}=e,i=V(q,n);return(0,B.jsx)(Ie.button,{type:`button`,...r,ref:t,onClick:I(e.onClick,()=>i.onOpenChange(!1))})});rt.displayName=q;function it(e){return e?`open`:`closed`}var at=`DialogTitleWarning`,[ot,st]=je(at,{contentName:G,titleName:et,docsSlug:`dialog`}),ct=({titleId:e})=>{let t=st(at),n=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users.
|
|
2
|
-
|
|
3
|
-
If you want to hide the \`${t.titleName}\`, you can wrap it with our VisuallyHidden component.
|
|
4
|
-
|
|
5
|
-
For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return z.useEffect(()=>{e&&(document.getElementById(e)||console.error(n))},[n,e]),null},lt=`DialogDescriptionWarning`,ut=({contentRef:e,descriptionId:t})=>{let n=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${st(lt).contentName}}.`;return z.useEffect(()=>{let r=e.current?.getAttribute(`aria-describedby`);t&&r&&(document.getElementById(t)||console.warn(n))},[n,e,t]),null},dt=He,ft=Je,J=Xe,pt=K,mt=nt,ht=365.2425,gt=6048e5,_t=864e5,vt=3600*24;vt*7,vt*ht/12*3;var yt=Symbol.for(`constructDateFrom`);function Y(e,t){return typeof e==`function`?e(t):e&&typeof e==`object`&&yt in e?e[yt](t):e instanceof Date?new e.constructor(t):new Date(t)}function X(e,t){return Y(t||e,e)}var bt={};function xt(){return bt}function St(e,t){let n=xt(),r=t?.weekStartsOn??t?.locale?.options?.weekStartsOn??n.weekStartsOn??n.locale?.options?.weekStartsOn??0,i=X(e,t?.in),a=i.getDay(),o=(a<r?7:0)+a-r;return i.setDate(i.getDate()-o),i.setHours(0,0,0,0),i}function Ct(e,t){return St(e,{...t,weekStartsOn:1})}function wt(e,t){let n=X(e,t?.in),r=n.getFullYear(),i=Y(n,0);i.setFullYear(r+1,0,4),i.setHours(0,0,0,0);let a=Ct(i),o=Y(n,0);o.setFullYear(r,0,4),o.setHours(0,0,0,0);let s=Ct(o);return n.getTime()>=a.getTime()?r+1:n.getTime()>=s.getTime()?r:r-1}function Tt(e){let t=X(e),n=new Date(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()));return n.setUTCFullYear(t.getFullYear()),e-+n}function Et(e,...t){let n=Y.bind(null,e||t.find(e=>typeof e==`object`));return t.map(n)}function Dt(e,t){let n=X(e,t?.in);return n.setHours(0,0,0,0),n}function Ot(e,t,n){let[r,i]=Et(n?.in,e,t),a=Dt(r),o=Dt(i),s=+a-Tt(a),c=+o-Tt(o);return Math.round((s-c)/_t)}function kt(e,t){let n=wt(e,t),r=Y(t?.in||e,0);return r.setFullYear(n,0,4),r.setHours(0,0,0,0),Ct(r)}function At(e,t,n){let[r,i]=Et(n?.in,e,t);return+Dt(r)==+Dt(i)}function jt(e){return e instanceof Date||typeof e==`object`&&Object.prototype.toString.call(e)===`[object Date]`}function Mt(e){return!(!jt(e)&&typeof e!=`number`||isNaN(+X(e)))}function Nt(e,t){let n=X(e,t?.in);return n.setFullYear(n.getFullYear(),0,1),n.setHours(0,0,0,0),n}var Pt={lessThanXSeconds:{one:`less than a second`,other:`less than {{count}} seconds`},xSeconds:{one:`1 second`,other:`{{count}} seconds`},halfAMinute:`half a minute`,lessThanXMinutes:{one:`less than a minute`,other:`less than {{count}} minutes`},xMinutes:{one:`1 minute`,other:`{{count}} minutes`},aboutXHours:{one:`about 1 hour`,other:`about {{count}} hours`},xHours:{one:`1 hour`,other:`{{count}} hours`},xDays:{one:`1 day`,other:`{{count}} days`},aboutXWeeks:{one:`about 1 week`,other:`about {{count}} weeks`},xWeeks:{one:`1 week`,other:`{{count}} weeks`},aboutXMonths:{one:`about 1 month`,other:`about {{count}} months`},xMonths:{one:`1 month`,other:`{{count}} months`},aboutXYears:{one:`about 1 year`,other:`about {{count}} years`},xYears:{one:`1 year`,other:`{{count}} years`},overXYears:{one:`over 1 year`,other:`over {{count}} years`},almostXYears:{one:`almost 1 year`,other:`almost {{count}} years`}},Ft=(e,t,n)=>{let r,i=Pt[e];return r=typeof i==`string`?i:t===1?i.one:i.other.replace(`{{count}}`,t.toString()),n?.addSuffix?n.comparison&&n.comparison>0?`in `+r:r+` ago`:r};function It(e){return(t={})=>{let n=t.width?String(t.width):e.defaultWidth;return e.formats[n]||e.formats[e.defaultWidth]}}var Lt={date:It({formats:{full:`EEEE, MMMM do, y`,long:`MMMM do, y`,medium:`MMM d, y`,short:`MM/dd/yyyy`},defaultWidth:`full`}),time:It({formats:{full:`h:mm:ss a zzzz`,long:`h:mm:ss a z`,medium:`h:mm:ss a`,short:`h:mm a`},defaultWidth:`full`}),dateTime:It({formats:{full:`{{date}} 'at' {{time}}`,long:`{{date}} 'at' {{time}}`,medium:`{{date}}, {{time}}`,short:`{{date}}, {{time}}`},defaultWidth:`full`})},Rt={lastWeek:`'last' eeee 'at' p`,yesterday:`'yesterday at' p`,today:`'today at' p`,tomorrow:`'tomorrow at' p`,nextWeek:`eeee 'at' p`,other:`P`},zt=(e,t,n,r)=>Rt[e];function Bt(e){return(t,n)=>{let r=n?.context?String(n.context):`standalone`,i;if(r===`formatting`&&e.formattingValues){let t=e.defaultFormattingWidth||e.defaultWidth,r=n?.width?String(n.width):t;i=e.formattingValues[r]||e.formattingValues[t]}else{let t=e.defaultWidth,r=n?.width?String(n.width):e.defaultWidth;i=e.values[r]||e.values[t]}let a=e.argumentCallback?e.argumentCallback(t):t;return i[a]}}var Vt={ordinalNumber:(e,t)=>{let n=Number(e),r=n%100;if(r>20||r<10)switch(r%10){case 1:return n+`st`;case 2:return n+`nd`;case 3:return n+`rd`}return n+`th`},era:Bt({values:{narrow:[`B`,`A`],abbreviated:[`BC`,`AD`],wide:[`Before Christ`,`Anno Domini`]},defaultWidth:`wide`}),quarter:Bt({values:{narrow:[`1`,`2`,`3`,`4`],abbreviated:[`Q1`,`Q2`,`Q3`,`Q4`],wide:[`1st quarter`,`2nd quarter`,`3rd quarter`,`4th quarter`]},defaultWidth:`wide`,argumentCallback:e=>e-1}),month:Bt({values:{narrow:[`J`,`F`,`M`,`A`,`M`,`J`,`J`,`A`,`S`,`O`,`N`,`D`],abbreviated:[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],wide:[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`]},defaultWidth:`wide`}),day:Bt({values:{narrow:[`S`,`M`,`T`,`W`,`T`,`F`,`S`],short:[`Su`,`Mo`,`Tu`,`We`,`Th`,`Fr`,`Sa`],abbreviated:[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`],wide:[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`]},defaultWidth:`wide`}),dayPeriod:Bt({values:{narrow:{am:`a`,pm:`p`,midnight:`mi`,noon:`n`,morning:`morning`,afternoon:`afternoon`,evening:`evening`,night:`night`},abbreviated:{am:`AM`,pm:`PM`,midnight:`midnight`,noon:`noon`,morning:`morning`,afternoon:`afternoon`,evening:`evening`,night:`night`},wide:{am:`a.m.`,pm:`p.m.`,midnight:`midnight`,noon:`noon`,morning:`morning`,afternoon:`afternoon`,evening:`evening`,night:`night`}},defaultWidth:`wide`,formattingValues:{narrow:{am:`a`,pm:`p`,midnight:`mi`,noon:`n`,morning:`in the morning`,afternoon:`in the afternoon`,evening:`in the evening`,night:`at night`},abbreviated:{am:`AM`,pm:`PM`,midnight:`midnight`,noon:`noon`,morning:`in the morning`,afternoon:`in the afternoon`,evening:`in the evening`,night:`at night`},wide:{am:`a.m.`,pm:`p.m.`,midnight:`midnight`,noon:`noon`,morning:`in the morning`,afternoon:`in the afternoon`,evening:`in the evening`,night:`at night`}},defaultFormattingWidth:`wide`})};function Ht(e){return(t,n={})=>{let r=n.width,i=r&&e.matchPatterns[r]||e.matchPatterns[e.defaultMatchWidth],a=t.match(i);if(!a)return null;let o=a[0],s=r&&e.parsePatterns[r]||e.parsePatterns[e.defaultParseWidth],c=Array.isArray(s)?Wt(s,e=>e.test(o)):Ut(s,e=>e.test(o)),l;l=e.valueCallback?e.valueCallback(c):c,l=n.valueCallback?n.valueCallback(l):l;let u=t.slice(o.length);return{value:l,rest:u}}}function Ut(e,t){for(let n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&t(e[n]))return n}function Wt(e,t){for(let n=0;n<e.length;n++)if(t(e[n]))return n}function Gt(e){return(t,n={})=>{let r=t.match(e.matchPattern);if(!r)return null;let i=r[0],a=t.match(e.parsePattern);if(!a)return null;let o=e.valueCallback?e.valueCallback(a[0]):a[0];o=n.valueCallback?n.valueCallback(o):o;let s=t.slice(i.length);return{value:o,rest:s}}}var Kt={code:`en-US`,formatDistance:Ft,formatLong:Lt,formatRelative:zt,localize:Vt,match:{ordinalNumber:Gt({matchPattern:/^(\d+)(th|st|nd|rd)?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)}),era:Ht({matchPatterns:{narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},defaultMatchWidth:`wide`,parsePatterns:{any:[/^b/i,/^(a|c)/i]},defaultParseWidth:`any`}),quarter:Ht({matchPatterns:{narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},defaultMatchWidth:`wide`,parsePatterns:{any:[/1/i,/2/i,/3/i,/4/i]},defaultParseWidth:`any`,valueCallback:e=>e+1}),month:Ht({matchPatterns:{narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},defaultMatchWidth:`wide`,parsePatterns:{narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},defaultParseWidth:`any`}),day:Ht({matchPatterns:{narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},defaultMatchWidth:`wide`,parsePatterns:{narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},defaultParseWidth:`any`}),dayPeriod:Ht({matchPatterns:{narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},defaultMatchWidth:`any`,parsePatterns:{any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},defaultParseWidth:`any`})},options:{weekStartsOn:0,firstWeekContainsDate:1}};function qt(e,t){let n=X(e,t?.in);return Ot(n,Nt(n))+1}function Jt(e,t){let n=X(e,t?.in),r=Ct(n)-+kt(n);return Math.round(r/gt)+1}function Yt(e,t){let n=X(e,t?.in),r=n.getFullYear(),i=xt(),a=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??i.firstWeekContainsDate??i.locale?.options?.firstWeekContainsDate??1,o=Y(t?.in||e,0);o.setFullYear(r+1,0,a),o.setHours(0,0,0,0);let s=St(o,t),c=Y(t?.in||e,0);c.setFullYear(r,0,a),c.setHours(0,0,0,0);let l=St(c,t);return+n>=+s?r+1:+n>=+l?r:r-1}function Xt(e,t){let n=xt(),r=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??n.firstWeekContainsDate??n.locale?.options?.firstWeekContainsDate??1,i=Yt(e,t),a=Y(t?.in||e,0);return a.setFullYear(i,0,r),a.setHours(0,0,0,0),St(a,t)}function Zt(e,t){let n=X(e,t?.in),r=St(n,t)-+Xt(n,t);return Math.round(r/gt)+1}function Z(e,t){return(e<0?`-`:``)+Math.abs(e).toString().padStart(t,`0`)}var Qt={y(e,t){let n=e.getFullYear(),r=n>0?n:1-n;return Z(t===`yy`?r%100:r,t.length)},M(e,t){let n=e.getMonth();return t===`M`?String(n+1):Z(n+1,2)},d(e,t){return Z(e.getDate(),t.length)},a(e,t){let n=e.getHours()/12>=1?`pm`:`am`;switch(t){case`a`:case`aa`:return n.toUpperCase();case`aaa`:return n;case`aaaaa`:return n[0];default:return n===`am`?`a.m.`:`p.m.`}},h(e,t){return Z(e.getHours()%12||12,t.length)},H(e,t){return Z(e.getHours(),t.length)},m(e,t){return Z(e.getMinutes(),t.length)},s(e,t){return Z(e.getSeconds(),t.length)},S(e,t){let n=t.length,r=e.getMilliseconds();return Z(Math.trunc(r*10**(n-3)),t.length)}},$t={am:`am`,pm:`pm`,midnight:`midnight`,noon:`noon`,morning:`morning`,afternoon:`afternoon`,evening:`evening`,night:`night`},en={G:function(e,t,n){let r=+(e.getFullYear()>0);switch(t){case`G`:case`GG`:case`GGG`:return n.era(r,{width:`abbreviated`});case`GGGGG`:return n.era(r,{width:`narrow`});default:return n.era(r,{width:`wide`})}},y:function(e,t,n){if(t===`yo`){let t=e.getFullYear(),r=t>0?t:1-t;return n.ordinalNumber(r,{unit:`year`})}return Qt.y(e,t)},Y:function(e,t,n,r){let i=Yt(e,r),a=i>0?i:1-i;return t===`YY`?Z(a%100,2):t===`Yo`?n.ordinalNumber(a,{unit:`year`}):Z(a,t.length)},R:function(e,t){return Z(wt(e),t.length)},u:function(e,t){return Z(e.getFullYear(),t.length)},Q:function(e,t,n){let r=Math.ceil((e.getMonth()+1)/3);switch(t){case`Q`:return String(r);case`QQ`:return Z(r,2);case`Qo`:return n.ordinalNumber(r,{unit:`quarter`});case`QQQ`:return n.quarter(r,{width:`abbreviated`,context:`formatting`});case`QQQQQ`:return n.quarter(r,{width:`narrow`,context:`formatting`});default:return n.quarter(r,{width:`wide`,context:`formatting`})}},q:function(e,t,n){let r=Math.ceil((e.getMonth()+1)/3);switch(t){case`q`:return String(r);case`qq`:return Z(r,2);case`qo`:return n.ordinalNumber(r,{unit:`quarter`});case`qqq`:return n.quarter(r,{width:`abbreviated`,context:`standalone`});case`qqqqq`:return n.quarter(r,{width:`narrow`,context:`standalone`});default:return n.quarter(r,{width:`wide`,context:`standalone`})}},M:function(e,t,n){let r=e.getMonth();switch(t){case`M`:case`MM`:return Qt.M(e,t);case`Mo`:return n.ordinalNumber(r+1,{unit:`month`});case`MMM`:return n.month(r,{width:`abbreviated`,context:`formatting`});case`MMMMM`:return n.month(r,{width:`narrow`,context:`formatting`});default:return n.month(r,{width:`wide`,context:`formatting`})}},L:function(e,t,n){let r=e.getMonth();switch(t){case`L`:return String(r+1);case`LL`:return Z(r+1,2);case`Lo`:return n.ordinalNumber(r+1,{unit:`month`});case`LLL`:return n.month(r,{width:`abbreviated`,context:`standalone`});case`LLLLL`:return n.month(r,{width:`narrow`,context:`standalone`});default:return n.month(r,{width:`wide`,context:`standalone`})}},w:function(e,t,n,r){let i=Zt(e,r);return t===`wo`?n.ordinalNumber(i,{unit:`week`}):Z(i,t.length)},I:function(e,t,n){let r=Jt(e);return t===`Io`?n.ordinalNumber(r,{unit:`week`}):Z(r,t.length)},d:function(e,t,n){return t===`do`?n.ordinalNumber(e.getDate(),{unit:`date`}):Qt.d(e,t)},D:function(e,t,n){let r=qt(e);return t===`Do`?n.ordinalNumber(r,{unit:`dayOfYear`}):Z(r,t.length)},E:function(e,t,n){let r=e.getDay();switch(t){case`E`:case`EE`:case`EEE`:return n.day(r,{width:`abbreviated`,context:`formatting`});case`EEEEE`:return n.day(r,{width:`narrow`,context:`formatting`});case`EEEEEE`:return n.day(r,{width:`short`,context:`formatting`});default:return n.day(r,{width:`wide`,context:`formatting`})}},e:function(e,t,n,r){let i=e.getDay(),a=(i-r.weekStartsOn+8)%7||7;switch(t){case`e`:return String(a);case`ee`:return Z(a,2);case`eo`:return n.ordinalNumber(a,{unit:`day`});case`eee`:return n.day(i,{width:`abbreviated`,context:`formatting`});case`eeeee`:return n.day(i,{width:`narrow`,context:`formatting`});case`eeeeee`:return n.day(i,{width:`short`,context:`formatting`});default:return n.day(i,{width:`wide`,context:`formatting`})}},c:function(e,t,n,r){let i=e.getDay(),a=(i-r.weekStartsOn+8)%7||7;switch(t){case`c`:return String(a);case`cc`:return Z(a,t.length);case`co`:return n.ordinalNumber(a,{unit:`day`});case`ccc`:return n.day(i,{width:`abbreviated`,context:`standalone`});case`ccccc`:return n.day(i,{width:`narrow`,context:`standalone`});case`cccccc`:return n.day(i,{width:`short`,context:`standalone`});default:return n.day(i,{width:`wide`,context:`standalone`})}},i:function(e,t,n){let r=e.getDay(),i=r===0?7:r;switch(t){case`i`:return String(i);case`ii`:return Z(i,t.length);case`io`:return n.ordinalNumber(i,{unit:`day`});case`iii`:return n.day(r,{width:`abbreviated`,context:`formatting`});case`iiiii`:return n.day(r,{width:`narrow`,context:`formatting`});case`iiiiii`:return n.day(r,{width:`short`,context:`formatting`});default:return n.day(r,{width:`wide`,context:`formatting`})}},a:function(e,t,n){let r=e.getHours()/12>=1?`pm`:`am`;switch(t){case`a`:case`aa`:return n.dayPeriod(r,{width:`abbreviated`,context:`formatting`});case`aaa`:return n.dayPeriod(r,{width:`abbreviated`,context:`formatting`}).toLowerCase();case`aaaaa`:return n.dayPeriod(r,{width:`narrow`,context:`formatting`});default:return n.dayPeriod(r,{width:`wide`,context:`formatting`})}},b:function(e,t,n){let r=e.getHours(),i;switch(i=r===12?$t.noon:r===0?$t.midnight:r/12>=1?`pm`:`am`,t){case`b`:case`bb`:return n.dayPeriod(i,{width:`abbreviated`,context:`formatting`});case`bbb`:return n.dayPeriod(i,{width:`abbreviated`,context:`formatting`}).toLowerCase();case`bbbbb`:return n.dayPeriod(i,{width:`narrow`,context:`formatting`});default:return n.dayPeriod(i,{width:`wide`,context:`formatting`})}},B:function(e,t,n){let r=e.getHours(),i;switch(i=r>=17?$t.evening:r>=12?$t.afternoon:r>=4?$t.morning:$t.night,t){case`B`:case`BB`:case`BBB`:return n.dayPeriod(i,{width:`abbreviated`,context:`formatting`});case`BBBBB`:return n.dayPeriod(i,{width:`narrow`,context:`formatting`});default:return n.dayPeriod(i,{width:`wide`,context:`formatting`})}},h:function(e,t,n){if(t===`ho`){let t=e.getHours()%12;return t===0&&(t=12),n.ordinalNumber(t,{unit:`hour`})}return Qt.h(e,t)},H:function(e,t,n){return t===`Ho`?n.ordinalNumber(e.getHours(),{unit:`hour`}):Qt.H(e,t)},K:function(e,t,n){let r=e.getHours()%12;return t===`Ko`?n.ordinalNumber(r,{unit:`hour`}):Z(r,t.length)},k:function(e,t,n){let r=e.getHours();return r===0&&(r=24),t===`ko`?n.ordinalNumber(r,{unit:`hour`}):Z(r,t.length)},m:function(e,t,n){return t===`mo`?n.ordinalNumber(e.getMinutes(),{unit:`minute`}):Qt.m(e,t)},s:function(e,t,n){return t===`so`?n.ordinalNumber(e.getSeconds(),{unit:`second`}):Qt.s(e,t)},S:function(e,t){return Qt.S(e,t)},X:function(e,t,n){let r=e.getTimezoneOffset();if(r===0)return`Z`;switch(t){case`X`:return nn(r);case`XXXX`:case`XX`:return rn(r);default:return rn(r,`:`)}},x:function(e,t,n){let r=e.getTimezoneOffset();switch(t){case`x`:return nn(r);case`xxxx`:case`xx`:return rn(r);default:return rn(r,`:`)}},O:function(e,t,n){let r=e.getTimezoneOffset();switch(t){case`O`:case`OO`:case`OOO`:return`GMT`+tn(r,`:`);default:return`GMT`+rn(r,`:`)}},z:function(e,t,n){let r=e.getTimezoneOffset();switch(t){case`z`:case`zz`:case`zzz`:return`GMT`+tn(r,`:`);default:return`GMT`+rn(r,`:`)}},t:function(e,t,n){return Z(Math.trunc(e/1e3),t.length)},T:function(e,t,n){return Z(+e,t.length)}};function tn(e,t=``){let n=e>0?`-`:`+`,r=Math.abs(e),i=Math.trunc(r/60),a=r%60;return a===0?n+String(i):n+String(i)+t+Z(a,2)}function nn(e,t){return e%60==0?(e>0?`-`:`+`)+Z(Math.abs(e)/60,2):rn(e,t)}function rn(e,t=``){let n=e>0?`-`:`+`,r=Math.abs(e),i=Z(Math.trunc(r/60),2),a=Z(r%60,2);return n+i+t+a}var an=(e,t)=>{switch(e){case`P`:return t.date({width:`short`});case`PP`:return t.date({width:`medium`});case`PPP`:return t.date({width:`long`});default:return t.date({width:`full`})}},on=(e,t)=>{switch(e){case`p`:return t.time({width:`short`});case`pp`:return t.time({width:`medium`});case`ppp`:return t.time({width:`long`});default:return t.time({width:`full`})}},sn={p:on,P:(e,t)=>{let n=e.match(/(P+)(p+)?/)||[],r=n[1],i=n[2];if(!i)return an(e,t);let a;switch(r){case`P`:a=t.dateTime({width:`short`});break;case`PP`:a=t.dateTime({width:`medium`});break;case`PPP`:a=t.dateTime({width:`long`});break;default:a=t.dateTime({width:`full`});break}return a.replace(`{{date}}`,an(r,t)).replace(`{{time}}`,on(i,t))}},cn=/^D+$/,ln=/^Y+$/,un=[`D`,`DD`,`YY`,`YYYY`];function dn(e){return cn.test(e)}function fn(e){return ln.test(e)}function pn(e,t,n){let r=mn(e,t,n);if(console.warn(r),un.includes(e))throw RangeError(r)}function mn(e,t,n){let r=e[0]===`Y`?`years`:`days of the month`;return`Use \`${e.toLowerCase()}\` instead of \`${e}\` (in \`${t}\`) for formatting ${r} to the input \`${n}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}var hn=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,gn=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,_n=/^'([^]*?)'?$/,vn=/''/g,yn=/[a-zA-Z]/;function bn(e,t,n){let r=xt(),i=n?.locale??r.locale??Kt,a=n?.firstWeekContainsDate??n?.locale?.options?.firstWeekContainsDate??r.firstWeekContainsDate??r.locale?.options?.firstWeekContainsDate??1,o=n?.weekStartsOn??n?.locale?.options?.weekStartsOn??r.weekStartsOn??r.locale?.options?.weekStartsOn??0,s=X(e,n?.in);if(!Mt(s))throw RangeError(`Invalid time value`);let c=t.match(gn).map(e=>{let t=e[0];if(t===`p`||t===`P`){let n=sn[t];return n(e,i.formatLong)}return e}).join(``).match(hn).map(e=>{if(e===`''`)return{isToken:!1,value:`'`};let t=e[0];if(t===`'`)return{isToken:!1,value:xn(e)};if(en[t])return{isToken:!0,value:e};if(t.match(yn))throw RangeError("Format string contains an unescaped latin alphabet character `"+t+"`");return{isToken:!1,value:e}});i.localize.preprocessor&&(c=i.localize.preprocessor(s,c));let l={firstWeekContainsDate:a,weekStartsOn:o,locale:i};return c.map(r=>{if(!r.isToken)return r.value;let a=r.value;(!n?.useAdditionalWeekYearTokens&&fn(a)||!n?.useAdditionalDayOfYearTokens&&dn(a))&&pn(a,t,String(e));let o=en[a[0]];return o(s,a,i.localize,l)}).join(``)}function xn(e){let t=e.match(_n);return t?t[1].replace(vn,`'`):e}function Sn(){return{handledInviteChoices:{},entries:[],invitePrompt:null,isMobileDockOpen:!1}}function Cn(e,n,r,i={}){if(!n?.prompt||n.status!==N.INVITABLE)return e;let a=e.entries.find(e=>e.id===n.id),o=e.handledInviteChoices[n.prompt.invitationId];if(o===t.CLOSE)return{...e,invitePrompt:null,isMobileDockOpen:!1};let s=(i.canShowPrompt??!0)&&o!==t.LATER&&a?.unread!==!1;return{...e,entries:[...e.entries.filter(e=>e.id!==n.id),{...n,unread:a?.unread??!0}],invitePrompt:s?n.prompt:null,isMobileDockOpen:s&&r===`mobile`}}function wn(e,t){return!t||t.kind!==`interview`||t.status!==N.ACTIVE?e:{...e,entries:[...e.entries.filter(e=>e.id!==t.id&&!(e.kind===`interview`&&e.status===N.INVITABLE)),{...t,unread:!1}],invitePrompt:null,isMobileDockOpen:!1}}function Tn(e,t){return{...e,entries:e.entries.map(e=>e.id===t?{...e,unread:!1}:e)}}function En(e,n,r){return{...e,handledInviteChoices:{...e.handledInviteChoices,[n]:r},entries:r===t.CLOSE?e.entries.filter(e=>e.prompt?.invitationId!==n):e.entries,invitePrompt:null,isMobileDockOpen:!1}}function Dn(e,{invitationId:t,sessionId:n,subtitle:r,title:i}){let a=e.entries.find(e=>e.prompt?.invitationId===t),o={id:`interview/session/${n}`,kind:`interview`,priority:a?.priority??20,status:N.ACTIVE,subtitle:r,title:i},s={...e.handledInviteChoices};return delete s[t],{...e,handledInviteChoices:s,entries:[...e.entries.filter(e=>e.prompt?.invitationId!==t),o],invitePrompt:null,isMobileDockOpen:!1}}function On({children:e,scope:t,transitionKey:n}){let r=(0,z.useRef)(1),i=(0,z.useRef)({content:e,id:0,isPresent:!0,shouldAnimate:!1,transitionKey:n}),[a,o]=(0,z.useState)(()=>[i.current]);(0,z.useLayoutEffect)(()=>{o(t=>{let a=i.current;if(a.transitionKey===n){let n={...a,content:e};return i.current=n,t.map(e=>e.id===n.id?n:e)}let o={...a,isPresent:!1,shouldAnimate:!0},s={content:e,id:r.current++,isPresent:!0,shouldAnimate:!0,transitionKey:n};return i.current=s,[...t.filter(e=>e.id!==a.id&&e.isPresent),o,s]})},[e,n]);function s(e){o(t=>t.filter(t=>t.id!==e))}function c(e,t){t.isPresent||e.target!==e.currentTarget||e.animationName!==`customer-agent-chat-route-out`||s(t.id)}let l=t===`shell`?`customer-agent-shell-route-layer absolute inset-0 flex min-h-0 flex-1`:`customer-agent-chat-route-layer absolute inset-0 flex min-h-0 flex-1`,u=t===`shell`?`customer-agent-shell-route-content flex min-h-0 flex-1 flex-row`:`customer-agent-chat-route-content flex min-h-0 flex-1 flex-col`;return(0,B.jsx)(`div`,{className:`customer-agent-${t}-route-stack relative flex min-w-0 flex-1 overflow-hidden`,"data-customer-agent-route-stack":t,children:a.map(e=>(0,B.jsx)(L,{present:e.isPresent,children:(0,B.jsx)(`div`,{className:l,"aria-hidden":!e.isPresent,"data-route-state":e.isPresent?`open`:`closed`,"data-route-transition-key":e.transitionKey,"data-route-motion":e.shouldAnimate?`animate`:`idle`,"data-testid":`customer-agent-${t}-route-layer`,onAnimationEnd:t=>c(t,e),children:(0,B.jsx)(`div`,{className:u,"data-route-content":``,children:e.content})})},e.id))})}var kn=null,An=(0,z.lazy)(async()=>({default:(await jn()).MobileDockDrawer}));function jn(){return kn??=import(`./MobileDockDrawer-ZIdezZML.js`).catch(e=>{throw kn=null,e}),kn}function Mn({activeEntryId:e,ariaLabel:t,children:n,entries:r,invitePrompt:i=null,interviewChat:o,isChatLoading:s=!1,isExpanded:c,isMobileDockOpen:l,isOpen:u,route:d,routeTransitionKey:f=0,style:ee,viewportMode:m,onEntrySelect:h,onInviteClose:g,onInviteLater:_,onInviteStart:te,onMobileDockOpenChange:ne}){let[v,y]=(0,z.useState)(null),b=i?.invitationId??null,x=!!(b&&r.some(e=>e.prompt?.invitationId===b)),re=!!(b&&x&&v===b)&&(m===`desktop`||l),ie=d.name,ae=d.name===a.AGENTS_CONVERSATIONS?[f,d.child.name,d.child.entryId,s&&d.child.name===p.CHAT?`loading`:`ready`].join(`:`):f;(0,z.useEffect)(()=>{m===`mobile`&&jn()},[m]),(0,z.useEffect)(()=>{if(!b||!x)return;let e=window.setTimeout(()=>{y(b)},280);return()=>window.clearTimeout(e)},[x,b]);let oe=d.name===a.GLOBAL_LOADING?(0,B.jsx)(j,{label:`Loading conversations`}):(0,B.jsxs)(B.Fragment,{children:[m===`desktop`?(0,B.jsx)(M,{activeEntryId:e,entries:r,invitePrompt:i,isInvitePromptOpen:re,onEntrySelect:h,onInviteClose:g,onInviteLater:_,onInviteStart:te}):(0,B.jsx)(Pn,{isOpen:l,onOpenChange:ne,children:(0,B.jsx)(z.Suspense,{fallback:(0,B.jsx)(Fn,{}),children:(0,B.jsx)(An,{activeEntryId:e,entries:r,invitePrompt:i,isInvitePromptOpen:re,onEntrySelect:h,onInviteClose:g,onInviteLater:_,onInviteStart:te,onOpenChange:ne})})}),(0,B.jsx)(`div`,{className:`relative flex min-w-0 flex-1 flex-col overflow-hidden rounded-l-[28px] border-l border-border-divider bg-bg-canvas shadow-[-6px_0_18px_rgba(9,14,21,0.035)] data-[viewport-mode=mobile]:rounded-none data-[viewport-mode=mobile]:border-l-0 data-[viewport-mode=mobile]:shadow-none`,"data-customer-agent-chat-outlet":``,"data-viewport-mode":m,children:(0,B.jsx)(On,{scope:`chat`,transitionKey:ae,children:(0,B.jsx)(Nn,{inviteMask:re?(0,B.jsx)(`div`,{className:`absolute inset-0 z-10 animate-[customer-agent-invite-mask-in_140ms_ease-out_both] bg-black/20 motion-reduce:animate-none`,"data-state":`open`,"data-testid":`interview-invite-mask`}):null,interviewChat:o,isChatLoading:s,route:d,children:n})})})]});return(0,B.jsx)(`section`,{className:`customer-agent-panel flex h-full w-full overflow-hidden rounded-messenger bg-bg-canvas text-text-primary outline-none data-[expanded=true]:[--messenger-conversation-part-max-width:520px] data-[viewport-mode=mobile]:h-[var(--customer-agent-visual-height)] data-[viewport-mode=mobile]:rounded-none`,"aria-hidden":!u,"aria-label":t,"data-expanded":c?`true`:`false`,"data-route":d.name,"data-state":u?`open`:`closed`,"data-viewport-mode":m,style:ee,children:(0,B.jsx)(On,{scope:`shell`,transitionKey:ie,children:oe})})}function Nn({children:e,inviteMask:t,interviewChat:n,isChatLoading:r,route:i}){return i.name===a.AGENTS_CONVERSATIONS?i.child.name===p.INTERVIEW_STARTING?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(j,{label:`Starting interview`}),t]}):i.child.name===p.CHAT&&r&&f(i.child.entryId)?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(j,{label:`Loading chat`}),t]}):i.child.entryId.startsWith(`interview/`)?(0,B.jsxs)(B.Fragment,{children:[n??(0,B.jsx)(j,{label:`Loading interview`}),t]}):(0,B.jsxs)(B.Fragment,{children:[e,t]}):null}function Pn({children:e,isOpen:t,onOpenChange:n}){return(0,B.jsxs)(dt,{modal:!0,open:t,onOpenChange:n,children:[(0,B.jsx)(ft,{className:`absolute inset-0 z-20 bg-black/20 data-[state=open]:animate-[customer-agent-mobile-dock-overlay-in_160ms_ease-out_both] motion-reduce:animate-none`,"data-customer-agent-mobile-dock-mask":``}),(0,B.jsxs)(J,{className:`absolute inset-y-0 left-0 z-30 w-[min(360px,100%)] bg-transparent outline-none data-[state=open]:animate-[customer-agent-mobile-dock-in_180ms_var(--ease-emphasis)_both] motion-reduce:animate-none`,"aria-label":`Conversations`,"aria-describedby":void 0,"data-customer-agent-mobile-dock":``,onPointerDown:e=>{e.target===e.currentTarget&&n(!1)},children:[(0,B.jsx)(pt,{className:`sr-only`,children:`Conversations`}),(0,B.jsx)(mt,{className:`sr-only`,children:`Select a conversation.`}),e]})]})}function Fn(){return(0,B.jsx)(`div`,{className:`pointer-events-auto h-full w-16 bg-bg-canvas shadow-card`,"aria-label":`Loading conversations`,"data-customer-agent-mobile-dock-rail":``,"data-customer-agent-mobile-dock-skeleton":``,role:`status`,children:(0,B.jsxs)(`div`,{className:`flex w-16 shrink-0 flex-col items-center gap-3 px-2 py-4`,children:[(0,B.jsx)(In,{className:`h-10 w-10 rounded-lg`}),(0,B.jsx)(In,{className:`h-10 w-10 rounded-lg`})]})})}function In({className:e}){return(0,B.jsx)(`div`,{className:F(`animate-pulse rounded bg-gray-3`,e),"data-customer-agent-skeleton":``})}function Ln(){return{name:a.GLOBAL_LOADING}}function Rn(){let e={name:a.GLOBAL_LOADING};return{action:`reset`,current:e,stack:[e],transitionKey:0}}function zn(e,t){return{...t,transitionKey:e.transitionKey+1}}function Bn(e,t){if(!e||!t)return!1;switch(e.name){case a.GLOBAL_LOADING:return t.name===a.GLOBAL_LOADING?Vn(e.target,t.target):!1;case a.GLOBAL_ERROR:return t.name===a.GLOBAL_ERROR?Vn(e.retryTo,t.retryTo):!1;case a.AGENTS_CONVERSATIONS:return t.name!==a.AGENTS_CONVERSATIONS||e.child.name!==t.child.name?!1:e.child.name===p.INTERVIEW_STARTING?t.child.name===p.INTERVIEW_STARTING&&e.child.entryId===t.child.entryId&&e.child.invitationId===t.child.invitationId:t.child.name===p.CHAT&&e.child.entryId===t.child.entryId}}function Vn(e,t){return e||t?Bn(e,t):!0}function Hn(e,t){switch(t.type){case`push`:return Bn(e.current,t.route)?e:zn(e,{action:`push`,current:t.route,previous:e.current,stack:[...e.stack,t.route]});case`replace`:return Bn(e.current,t.route)?e:zn(e,{action:`replace`,current:t.route,previous:e.current,stack:[...e.stack.slice(0,-1),t.route]});case`reset`:return Bn(e.current,t.route)?e:zn(e,{action:`reset`,current:t.route,previous:e.current,stack:[t.route]});case`back`:{let n=e.stack.slice(0,-1),r=n[n.length-1]??t.fallback??e.current;return zn(e,{action:`back`,current:r,previous:e.current,stack:n.length>0?n:[r]})}}}var Un=`customer_agent:widget_route`;function Wn(e){return typeof e==`string`&&e.trim()?e.trim():null}function Gn(e){let t=Wn(e.user?.id),n=Wn(e.anonymous_id),r=t?`user:${t}`:n?`anonymous:${n}`:`anonymous`;return encodeURIComponent(r)}function Kn(e){return`${Un}:${e.app_id}:${Gn(e)}`}function qn(e){return e.name===a.AGENTS_CONVERSATIONS?e.child.name===p.CHAT&&Xn(e.child.entryId):!1}function Jn(e){return!!e&&typeof e==`object`}function Yn(e){if(!Jn(e)||e.name!==a.AGENTS_CONVERSATIONS)return!1;let t=e.child;return!Jn(t)||typeof t.entryId!=`string`?!1:!!(t.name===p.CHAT&&Xn(t.entryId))}function Xn(e){return e.startsWith(`support/`)?f(e):e.startsWith(`interview/session/`)?c(e):!0}function Zn(e){if(!e)return null;let t=JSON.parse(e);return Yn(t)&&qn(t)?t:null}function Qn(e){try{let t=Kn(e);return Zn(window.localStorage.getItem(t))}catch{return null}}function $n(e,t){if(qn(t))try{window.localStorage.setItem(Kn(e),JSON.stringify(t))}catch{}}function er(e){return e.type===`support`||e.type===`home`?Ln():e.type===`entry`?ne(e.entryId)?{child:{entryId:e.entryId,name:p.CHAT},name:a.AGENTS_CONVERSATIONS}:Ln():e.sessionId?{child:{entryId:`interview/session/${e.sessionId}`,name:p.CHAT},name:a.AGENTS_CONVERSATIONS}:e.campaignId?{child:{entryId:`interview/invite/${e.campaignId}`,name:p.CHAT},name:a.AGENTS_CONVERSATIONS}:Ln()}function tr(e){return e.status===n.AVAILABLE?{id:`interview/invite/${e.campaignId}`,kind:`interview`,priority:20,prompt:{anchor:`dock`,body:e.body,campaignId:e.campaignId,closeLabel:`No`,invitationId:`runtime:${e.campaignId}`,kind:`interview-invite`,laterLabel:e.laterCta,startLabel:e.startCta},status:N.INVITABLE,title:e.title}:e.status===n.ACTIVE?{id:e.entryId,kind:`interview`,priority:20,status:N.ACTIVE,title:e.title??``}:null}function nr(){let e=i(h());return{async checkEligibility(t){let{data:n}=await e.request(`/interviews/eligibility`,{body:t,method:`POST`});return n},async chooseInvitation(t,n){await e.request(`/interviews/invitations/${t}/choice`,{body:n,method:`PATCH`})},async createInvitation(t){let{data:n}=await e.request(`/interviews/invitations`,{body:t,method:`POST`});return n},async getReward(t){let{data:n}=await e.request(`/interviews/sessions/${t}/reward`);return n},async getSession(t){let{data:n}=await e.request(`/interviews/sessions/${t}`);return n},async sendMessage(t,n){let{data:r}=await e.request(`/interviews/sessions/${t}/messages`,{body:n,method:`POST`});return r},async startInvitation(t,n){let{data:r}=await e.request(`/interviews/invitations/${t}/start`,{body:n,method:`POST`});return r}}}var Q=Object.freeze({ERROR:`error`,IDLE:`idle`,LOADING:`loading`,READY:`ready`}),rr=`image/*,application/pdf,video/mp4,.jpg,.jpeg,.png,.gif,.pdf,.mp4`,ir=Object.freeze({MAX_FILE_SIZE_BYTES:50*1024*1024}),ar=`customer-agent-attachment`,or=(0,z.lazy)(async()=>({default:(await import(`./MarkdownText-CXKW_2Ol.js`)).MarkdownText})),sr=null,cr=(0,z.lazy)(async()=>({default:(await ur()).InterviewChatScreen})),lr=new Set([n.CHECKING,n.IDLE]);function ur(){return sr??=import(`./InterviewChatScreen-Dx7IiTbY.js`).catch(e=>{throw sr=null,e}),sr}function dr(e,t){return r(e)&&e.child.entryId===t.id?e:m(t.id)}function fr(){return typeof crypto<`u`&&`randomUUID`in crypto?crypto.randomUUID():`msg_${Date.now()}_${Math.random().toString(36).slice(2)}`}function pr(e){return e?.brand?.name??`Customer Agent`}function mr(e,t){return t===`Customer Agent`&&e||t}function hr(e){return e.content.map(e=>e.type===`text`?e.text:``).filter(Boolean).join(`
|
|
6
|
-
`)}function gr(e){return e===`user`?`user`:`assistant`}function _r(e){let t=e.metadata?.custom?.assistantAuthor;return t===`human`||t===`llm`?t:null}function vr(e,t){return e===`human`?t.messages.assistant_author_human:t.messages.assistant_author_ai}function yr(e){let t=e?.find(e=>e.type===`image`&&typeof e.image==`string`||e.type===`file`&&typeof e.data==`string`);return t?.image??t?.data??``}function br(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.id==`string`&&typeof t.filename==`string`&&typeof t.mimeType==`string`&&typeof t.sizeBytes==`number`&&typeof t.url==`string`}function xr(e){let t=Or(e.content);if(t)return{...t,file:e.file};let n=yr(e.content);return!n&&!e.file?null:{expiresAt:void 0,file:e.file,filename:e.name,id:e.id,mimeType:e.contentType??e.file?.type??`application/octet-stream`,sizeBytes:e.file?.size??0,url:n}}function Sr(e){let t=[],n=new Set;for(let r of e.attachments??[]){let e=xr(r);e&&!n.has(e.id)&&(t.push(e),n.add(e.id))}let r=e.metadata?.custom?.attachments;if(Array.isArray(r))for(let e of r)br(e)&&!n.has(e.id)&&(t.push(e),n.add(e.id));return t}function Cr(e){return!!(e.content.trim()||(e.attachments?.length??0)>0)}function wr(e){return e.filter(Cr).map(e=>e.id)}function Tr(e){return(e.attachments??[]).map(e=>({id:e.id}))}function Er(e,t){return[...e].sort((e,n)=>{let r=Or(e.content),i=Or(n.content),a=r?t.get(r.id):void 0,o=i?t.get(i.id):void 0;return a!==void 0&&o!==void 0?a-o:a===void 0?o===void 0?0:1:-1})}function Dr(e){return(e.attachments??[]).map(e=>Or(e.content)).filter(e=>!!e)}function Or(e){let t=e?.find(e=>e.type===`data`&&e.name===ar)?.data;if(!t||typeof t!=`object`)return null;let n=t;return typeof n.id==`string`&&typeof n.filename==`string`&&typeof n.mimeType==`string`&&typeof n.sizeBytes==`number`&&typeof n.url==`string`?{expiresAt:typeof n.expiresAt==`string`?n.expiresAt:void 0,filename:n.filename,id:n.id,mimeType:n.mimeType,sizeBytes:n.sizeBytes,url:n.url}:null}function kr(e){return e instanceof Date&&!Number.isNaN(e.getTime())}function Ar(e){let t=e.createdAt;return kr(t)?t:new Date}function jr(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function Mr(e,t){return At(e,t)}function Nr(e,t){let n=new Date,r=Ot(n,e);return r<=0?t.messages.relative_time_today:r===1?t.messages.relative_time_yesterday:r<7?y(t.messages.relative_time_day,{count:String(r)}):bn(e,e.getFullYear()===n.getFullYear()?`MM-dd`:`yyyy-MM-dd`)}function Pr(e,t){let n=Math.max(0,Date.now()-e.getTime()),r=6e4,i=60*r,a=24*i;return n<r?t.messages.relative_time_now:n<i?y(t.messages.relative_time_minute,{count:String(Math.floor(n/r))}):n<a?y(t.messages.relative_time_hour,{count:String(Math.floor(n/i))}):y(t.messages.relative_time_day,{count:String(Math.floor(n/a))})}function Fr(e,t){let n=e[t],r=e[t-1],i=e[t+1],a=r?.role===n.role&&Mr(r.createdAt,n.createdAt),o=i?.role===n.role&&Mr(i.createdAt,n.createdAt);return a&&o?`middle`:a?`bottom`:o?`top`:`standalone`}function Ir(e,t){let n=`var(--messenger-conversation-part-radius)`,r=`var(--messenger-conversation-part-adjacent-radius)`,i=t===`middle`||t===`bottom`,a=t===`middle`||t===`top`;return e===`user`?{borderTopLeftRadius:n,borderTopRightRadius:i?r:n,borderBottomRightRadius:a?r:n,borderBottomLeftRadius:n}:{borderTopLeftRadius:i?r:n,borderTopRightRadius:n,borderBottomRightRadius:n,borderBottomLeftRadius:a?r:n}}function Lr(e){return(e??`Customer Agent`).trim().replace(/[^a-z0-9\u4e00-\u9fa5]+/gi,`_`).replace(/^_+|_+$/g,``)}function Rr(e,t,n,r){let i=n.getFullYear(),a=String(n.getMonth()+1).padStart(2,`0`),o=String(n.getDate()).padStart(2,`0`);return`${Lr(e)||`Customer_Agent`}_${t}_${i}_${a}_${o}_${r}.txt`}function zr(e){return(e??[]).map(e=>({id:e.id,role:e.author===`visitor`?`user`:`assistant`,content:e.text,status:e.author===`assistant`?{type:`complete`,reason:`stop`}:void 0}))}function Br(t,n,r,i){let a=new Map;return{accept:rr,async*add({file:o}){let c=fr(),l={id:c,type:o.type.startsWith(`image/`)?`image`:`file`,name:o.name,contentType:o.type,file:o,content:[]};if(o.size>ir.MAX_FILE_SIZE_BYTES){yield{...l,status:{reason:`error`,type:`incomplete`}};return}yield{...l,status:{progress:0,reason:`uploading`,type:`running`}};let u=t.current;if(!u)throw Error(`The support chat is missing widget configuration.`);await i.current?.ensureSession();let d=await s.uploadAttachment(u,o,{onConversationCreated(t){n.current?.emit(e.CONVERSATION_CREATED,{...Ur(t)})}});if(a.set(c,d),r.current.set(d.id,r.current.size),d.mimeType.startsWith(`image/`)&&d.url){let e=new Image;e.src=d.url,await e.decode().catch(()=>void 0)}yield{...l,status:{reason:`composer-send`,type:`requires-action`}}},async remove(e){a.delete(e.id)},async send(e){let t=a.get(e.id);if(!t)throw Error(`The attachment is not ready to send yet.`);a.delete(e.id);let n=t.mimeType.startsWith(`image/`)?[{type:`image`,image:t.url,filename:t.filename}]:[{type:`file`,data:t.url,filename:t.filename,mimeType:t.mimeType}];return{id:t.id,type:e.type,name:e.name,contentType:e.contentType,file:e.file,content:[...n,{type:`data`,name:ar,data:t}],status:{type:`complete`}}}}}function $(e){return!e?.app_id||!e.widgetId?null:{...e,context:e.context??{}}}function Vr(e){return e?.messages?.welcome_message?.trim()??``}function Hr(e){return e instanceof g?e.message:`I couldn't reach support right now. Please try again in a moment.`}function Ur(e){return{conversationId:e,conversationType:`support`,entryId:d(e),supportConversationId:e}}function Wr(e){let t=$(e);return t?_(t):null}function Gr({hasCachedInterviewSession:e,hasInterviewIdentity:t,interview:i,storedRoute:a}){return i.status===n.ACTIVE?!1:t&&(e||r(a))&&lr.has(i.status)}function Kr({interview:e,storedRoute:t,supportEntryId:n,supportRoute:i}){return r(t)?t.child.entryId===e.entryId?t:m(e.entryId):Qr({storedRoute:t,supportEntryId:n})??i}function qr({storedRoute:e,supportEntryId:t,supportRoute:n}){return Qr({storedRoute:e,supportEntryId:t})??n}function Jr(e){return!e||e.type===v.SUPPORT?null:m(e.entryId)}function Yr(e){return e.name===a.AGENTS_CONVERSATIONS&&e.child.name===p.CHAT?{entryId:e.child.entryId,type:v.CHAT}:null}function Xr(e){return e.startsWith(`interview/`)}function Zr(e){return e?.name===a.AGENTS_CONVERSATIONS&&e.child.name===p.CHAT&&f(e.child.entryId)}function Qr({storedRoute:e,supportEntryId:t}){return!e||e.name!==a.AGENTS_CONVERSATIONS||r(e)?null:Zr(e)&&t?e.child.entryId===t?e:m(t):e}function $r(e){return e?m(e):Ln()}function ei(e){return e?e.type===`interview`?!0:e.type===`entry`&&Xr(e.entryId):!1}function ti({activeTarget:e,supportHydrationKey:t,supportStatus:n}){return!!t&&!ei(e)&&n!==te.READY}function ni(e,t){if(!ei(e))return null;if(e?.type===`interview`&&e.sessionId)return m(`interview/session/${e.sessionId}`);if(t?.status===n.ACTIVE)return m(t.entryId);let r=e?.type===`interview`?e.campaignId:void 0;return r?{child:{entryId:`interview/invite/${r}`,invitationId:`runtime:${r}`,name:p.INTERVIEW_STARTING},name:a.AGENTS_CONVERSATIONS}:e?.type===`entry`?er(e):null}function ri(e){return`session`in e}function ii(e){return e.content.map(e=>e.type===`text`?e.text:``).filter(Boolean).join(`
|
|
7
|
-
`).trim()}function ai(e){return e.id?.startsWith(`local-`)??!1}function oi(e,t){return{...e,metadata:{...e.metadata,custom:{...e.metadata?.custom,supportConversationId:t}}}}function si(e,t){let n=oi(e,t);return{...n,metadata:{...n.metadata,custom:{...n.metadata?.custom,supportAckConversationId:t,supportSendStatus:`acked`}}}}function ci(e,t){let n=e.metadata?.custom;return n?.supportConversationId===t||n?.supportAckConversationId===t}function li(e,t){return o(e).map(e=>oi(e,t))}function ui(e,t){let n=new Map(e.map(e=>[e.id,e]));for(let e of t)n.set(e.id,e);return[...n.values()]}function di(e,t){if(e.length===0)return t;let n=new Set(e.map(e=>e.id)),r=t.filter(e=>ai(e)&&!n.has(e.id));return[...e,...r]}function fi(e,t,n){if(e.length===0)return t;let r=e.map(e=>oi(e,n)),i=new Set(r.map(e=>e.id)),a=t.filter(e=>!i.has(e.id)&&(ai(e)||ci(e,n)));return[...r,...a]}function pi({activeTarget:t,bootOptions:n,eventBus:r,interviewRuntime:i,isExpanded:a,isOpen:c,locale:u,memoryRoute:d,messages:f,onMemoryRouteChange:ee,onExpandedChange:p,onOpenChange:m,runtimeState:h,supportRuntime:g,viewport:ne}){let v=(0,z.useRef)(null),y=(0,z.useRef)(!1),b=(0,z.useRef)(!1),x=(0,z.useRef)(null),[re,ae]=(0,z.useState)(!1),[oe,se]=(0,z.useState)(null),[ce,C]=(0,z.useState)(Q.IDLE),[w,T]=(0,z.useState)(null),[le,E]=(0,z.useState)(()=>zr(f)),D=$(n),ue=(0,z.useRef)(D),de=(0,z.useRef)(r),fe=(0,z.useRef)(g),pe=(0,z.useRef)(null),O=(0,z.useRef)(null),me=(0,z.useRef)(new Map),k=(0,z.useMemo)(()=>Wr(n),[n]);ue.current=D,de.current=r,fe.current=g,(!pe.current||O.current!==k)&&(me.current=new Map,pe.current=Br(ue,de,me,fe),O.current=k);let he=pe.current,ge=D?k&&oe===k?v.current===k?Q.READY:ce===Q.ERROR?Q.ERROR:Q.LOADING:Q.IDLE:Q.READY,_e=ge===Q.READY&&w?.key===k&&w.messageIds.length>0&&!w.messageIds.every(e=>le.some(t=>t.id===e)),ve=le.some(e=>e.role===`assistant`&&e.status?.type===`running`),ye=re||ge!==Q.READY||_e||ve,be=S({adapters:(0,z.useMemo)(()=>({attachments:he}),[he]),convertMessage:(0,z.useCallback)(e=>e,[]),isRunning:re,isSendDisabled:ye,messages:le,onNew:(0,z.useCallback)(async t=>{let n=ii(t),i=Er(t.attachments??[],me.current),a=Tr({...t,attachments:i});if(!D){E(e=>ui(e,[{id:`local-error-${fr()}`,role:`assistant`,content:`The support chat is missing widget configuration.`,createdAt:new Date,status:{type:`complete`,reason:`stop`}}]));return}if(!n&&a.length===0)return;let c=`local-user-${fr()}`,l;b.current=!0,ae(!0),r?.emit(e.MESSAGE_SENT,{...w?Ur(w.conversationId):{conversationType:`support`},messageId:c,role:`user`}),E(e=>ui(e,[{id:c,role:`user`,content:n||[],attachments:i,createdAt:new Date,metadata:{custom:{attachments:Dr({...t,attachments:i})}}}]));let u=new AbortController;try{if(!g)throw Error(`The support chat is missing runtime session orchestration.`);let t=await g.ensureSession();l=t.conversationId,r?.emit(e.MESSAGE_STARTED,{...Ur(l),role:`assistant`});let i=await s.sendMessage(D,n,a,u.signal,{onConversationCreated(t){r?.emit(e.CONVERSATION_CREATED,{...Ur(t)})},onSessionInvalidated(){g.invalidateSession?.()}});i.conversationId!==t.conversationId&&g.ensureSession().catch(e=>{console.error(`CustomerAgent session recovery failed.`,e)}),l=i.conversationId;let d=o([i.userMessage,i.assistantMessage]).map(e=>si(e,i.conversationId));T({conversationId:i.conversationId,key:_(D),messageIds:[]}),E(e=>ui(e.filter(e=>e.id!==c),d)),r?.emit(e.MESSAGE_COMPLETED,{assistantAuthor:i.assistantMessage.assistantAuthor??void 0,...Ur(i.conversationId),messageId:i.assistantMessage.id,role:`assistant`}),i.handoff.needed&&r?.emit(e.HANDOFF_REQUESTED,{...Ur(i.conversationId)})}catch(t){console.error(`CustomerAgent message request failed.`,t);let n=l?Ur(l):{conversationType:`support`};r?.emit(e.MESSAGE_SEND_FAILED,{...n,messageId:c,role:`user`}),r?.emit(e.MESSAGE_FAILED,{...n,role:`assistant`}),E(e=>ui(e,[{id:`local-error-${fr()}`,role:`assistant`,content:Hr(t),createdAt:new Date,status:{type:`complete`,reason:`stop`}}]))}finally{b.current=!1,ae(!1)}},[r,D,w,g])});return(0,z.useEffect)(()=>{let e=$(n),t=Wr(n);if(!e||!t){v.current=null,x.current=null,C(Q.READY),T(null);return}if(oe!==t){v.current=null,x.current=null,E(zr(f)),C(Q.IDLE),T(null);return}if(v.current===t){C(Q.READY);return}if(!g){C(Q.ERROR),T(null);return}let r=g?.getSessionSnapshot();if(h?.support.status===te.READY&&r?.conversationId===h.support.conversationId){v.current=t,T({conversationId:r.conversationId,key:t,messageIds:wr(r.messages)}),r.messages.length>0&&E(e=>di(li(r.messages,r.conversationId),e)),C(Q.READY);return}let i=!1,a=x.current;return(!a||a.key!==t)&&(E(zr(f)),T(null),a={key:t,promise:g.ensureSession()},x.current=a),C(Q.LOADING),a.promise.then(e=>{i||(v.current=t,T({conversationId:e.conversationId,key:t,messageIds:wr(e.messages)}),e.messages.length>0&&E(t=>di(li(e.messages,e.conversationId),t)),C(Q.READY))}).catch(e=>{i||(x.current?.key===t&&(x.current=null),v.current=null,T(null),C(Q.ERROR),console.error(`CustomerAgent session bootstrap failed.`,e))}),()=>{i=!0}},[n,r,f,h,oe,g]),(0,z.useEffect)(()=>{let e=$(n);if(!e)return;let t=e,r=!1,i=null;function a(){r||document.hidden||y.current||b.current||(y.current=!0,i=new AbortController,s.refreshSession(t,i.signal).then(e=>{r||b.current||e&&(T(n=>n?.key===_(t)?{conversationId:e.conversationId,key:n.key,messageIds:[]}:n),E(t=>fi(li(e.messages,e.conversationId),t,e.conversationId)))}).catch(e=>{if(!(e instanceof DOMException&&e.name===`AbortError`)){if(e instanceof l){let e=_(t);if(!g){v.current=null,T(null),C(Q.ERROR);return}g.invalidateSession?.(),v.current=null,x.current=null,se(e),C(Q.READY),g.ensureSession().then(t=>{r||(v.current=e,T({conversationId:t.conversationId,key:e,messageIds:wr(t.messages)}),E(e=>di(li(t.messages,t.conversationId),e)),C(Q.READY))}).catch(e=>{r||(v.current=null,T(null),C(Q.ERROR),console.error(`CustomerAgent session recovery failed.`,e))});return}console.error(`CustomerAgent session refresh failed.`,e)}}).finally(()=>{y.current=!1,i=null}))}let o=window.setInterval(a,5e3);return()=>{r=!0,i?.abort(),window.clearInterval(o),y.current=!1}},[n,f,w,g]),(0,B.jsx)(ie,{runtime:be,children:(0,B.jsx)(mi,{bootOptions:n,activeTarget:t,eventBus:r,interviewRuntime:i,isExpanded:a,isOpen:c,locale:u,memoryRoute:d,onMemoryRouteChange:ee,onExpandedChange:p,onOpenChange:m,runtimeState:h,supportRuntime:g,onSupportBootstrapNeeded:se,supportHydrationSnapshot:w,supportBootstrapStatus:ge,viewport:ne})})}function mi({activeTarget:i,bootOptions:o,eventBus:s,interviewRuntime:c,isExpanded:l,isOpen:h,locale:g,memoryRoute:_,onMemoryRouteChange:ne,onExpandedChange:v,onOpenChange:b,runtimeState:x,supportRuntime:ie,onSupportBootstrapNeeded:S,supportBootstrapStatus:T,supportHydrationSnapshot:O,viewport:A}){let[Se,Ce]=(0,z.useState)(!1),[j,M]=(0,z.useReducer)(Hn,void 0,Rn),[P,I]=(0,z.useState)(Sn),[Ee,De]=(0,z.useState)({}),Oe=Te(e=>e.thread.messages),ke=ce().composer,Ae=!!o?.embedded,je=A.presentation===`fullscreen`&&!Ae,Me=A.mode===`mobile`?je?A.safeAreaBottom:Math.max(A.safeAreaBottom,A.keyboardInset):0,Ne=A.mode===`mobile`&&je?A.height:A.visualHeight,L=(0,z.useRef)(null),Pe=(0,z.useRef)(null),R=(0,z.useRef)(null),Fe=(0,z.useRef)(null),Ie=(0,z.useRef)(null),Le=(0,z.useRef)(null),Re=(0,z.useRef)(null),ze=(0,z.useRef)(null),Be=(0,z.useRef)(!1),Ve=(0,z.useRef)(!1),V=(0,z.useRef)(null),He=(0,z.useRef)(null),Ue=(0,z.useRef)(!1),We=(0,z.useRef)(!1),H=pr(o),U=o?.header?.menu!==!1,Ge=g.messages.interview_session_description,Ke=o?.theme?.primaryColor??`var(--gray-12)`,qe=y(g.messages.support_chat_label,{title:H}),Je=Vr(o),Ye={"--customer-agent-bottom-inset":`${Me}px`,"--customer-agent-primary":Ke,"--customer-agent-visual-height":`${Ne}px`},W=Oe.map(e=>{let t=e,n=hr(t).trim(),r=t.role===`assistant`&&t.status?.type===`running`&&!n;return{assistantAuthor:_r(t),attachments:Sr(t),createdAt:Ar(t),id:t.id,isPending:r,role:gr(t.role),text:n}}).filter(e=>e.text||e.isPending||e.attachments.length>0),G=W.length?jr(W[W.length-1].createdAt):null,Xe=new Set(G?[[...W].reverse().find(e=>e.role===`assistant`&&!e.isPending&&jr(e.createdAt)===G)?.id].filter(e=>!!e):[]),Ze=new Map(W.map((e,t)=>{let n=W[t-1];return[e.id,{dateLabel:!n||!Mr(n.createdAt,e.createdAt)?Nr(e.createdAt,g):void 0,groupPosition:Fr(W,t),isFirst:t===0,message:e,previousMessage:n,showsDefaultAssistantTime:Xe.has(e.id)}]})),Qe=W[W.length-1],$e=Qe?[Qe.id,Qe.text.length,Qe.isPending?`pending`:`settled`,Qe.attachments.map(e=>`${e.id}:${e.url}:${e.mimeType}`).join(`|`)].join(`:`):null,et=O?.conversationId??(x?.support.status===te.READY?x.support.conversationId:null),K=et?d(et):null,tt=Zr(j.current)?j.current.child.entryId:null,nt=K??tt,q=j.current.name===a.AGENTS_CONVERSATIONS?j.current.child.entryId:nt??``,rt=j.current.name!==a.GLOBAL_LOADING,it=nt?{id:nt,kind:`support`,priority:0,status:N.AVAILABLE,title:H}:null,at=[...it?[it]:[],...P.entries.map(e=>e.kind===`interview`&&e.status===N.ACTIVE?{...e,subtitle:Ge,title:mr(e.title,H)}:e)],ot=at.find(e=>e.id===q),st=ot?.kind===`interview`?ot.title:H,ct=new Set(W.map(e=>e.id)),lt=ee(q),ut=!!lt&&T===Q.READY&&O?.key===Wr(o)&&O.conversationId===lt&&O.messageIds.length>0&&!O.messageIds.every(e=>ct.has(e)),dt=f(q)&&(T!==Q.READY||ut),ft=P.entries.some(e=>e.kind===`interview`&&e.status===N.ACTIVE),J=!!P.invitePrompt,pt=be({composerRuntime:ke,inputRef:L,shouldSuppressComposerFocus:J});(0,z.useEffect)(()=>{let t=P.invitePrompt;!s||!t||Ie.current===t.invitationId||(Ie.current=t.invitationId,s.emit(e.INTERVIEW_INVITATION_SHOWN,{campaignId:t.campaignId,entryId:P.entries.find(e=>e.prompt?.invitationId===t.invitationId)?.id??`interview/invite/${t.campaignId}`,invitationId:t.invitationId}))},[P.entries,P.invitePrompt,s]),(0,z.useEffect)(()=>{if(!x)return;let e=tr(x.interview);if(!e){R.current=null,I(e=>({...e,entries:e.entries.filter(e=>e.kind!==`interview`),invitePrompt:null,isMobileDockOpen:!1}));return}if(x.interview.status===n.ACTIVE){let t=c?.getActiveSession(),n=R.current?.getState();if(t&&(!R.current||n?.sessionId!==t.sessionId)){let e=$(o);if(e){let n=k({client:nr(),options:e});n.hydrateSession(t),R.current=n}}I(t=>wn(t,e));return}I(t=>{let n=Cn(t,e,A.mode,{canShowPrompt:rt});return ei(i)?{...Tn(n,e.id),invitePrompt:null,isMobileDockOpen:!1}:n})},[i,o,rt,c,x,A.mode]);function mt(){let e=L.current;if(!e||A.mode===`mobile`||J)return!1;let t=e.value.length;return e.focus(),e.setSelectionRange(t,t),!0}function ht(){Be.current||=mt()}function gt(e){L.current=e,!(!e||!h||A.mode===`mobile`||J)&&window.requestAnimationFrame(ht)}(0,z.useEffect)(()=>{let e=L.current;!J||document.activeElement!==e||e?.blur()},[J]);function _t(){let t=new Date,n=t.getTime(),r=W.map(e=>({createdAt:e.createdAt,role:e.role,text:e.text})),i=E({conversationName:H,exportedAt:t,locale:g.locale,messages:r,userSpeaker:D(o)}),a=new Blob([i],{type:`text/plain;charset=utf-8`}),c=URL.createObjectURL(a),l=document.createElement(`a`);l.href=c,l.download=Rr(H,`support`,t,n),l.click(),window.setTimeout(()=>URL.revokeObjectURL(c),0);let u=ie?.getSessionSnapshot();s?.emit(e.TRANSCRIPT_DOWNLOADED,{...u?Ur(u.conversationId):O?Ur(O.conversationId):{conversationType:`support`},messageCount:r.length})}function vt(){let e=He.current;e&&(e.scrollTop=e.scrollHeight)}(0,z.useLayoutEffect)(()=>{let e=h&&!We.current;We.current=h,h||(Be.current=!1),e&&(Ue.current=!1,A.mode!==`mobile`&&!J&&window.requestAnimationFrame(()=>{if(Be.current)return;let e=L.current;if(!e||J)return;let t=e.value.length;e.focus(),e.setSelectionRange(t,t),Be.current=!0})),!(!h||!$e)&&(Ue.current||(vt(),window.requestAnimationFrame(vt)))},[h,$e,J,A.mode]),(0,z.useLayoutEffect)(()=>{let e=V.current;if(V.current=q,e!==null&&e!==q&&(Ve.current=f(q)),Ve.current){if(!f(q)||!h||A.mode===`mobile`||J){Ve.current=!1;return}dt||window.requestAnimationFrame(()=>{Ve.current=!mt()})}},[q,h,dt,J,A.mode]);function yt(){!h||Ue.current||(vt(),window.requestAnimationFrame(vt))}function Y(e){let t=e.currentTarget;Ue.current=t.scrollHeight-t.clientHeight-t.scrollTop>=120}(0,z.useLayoutEffect)(()=>{U||Ce(!1)},[U]),(0,z.useEffect)(()=>{if(!U)return;function e(){Ce(!1)}return window.addEventListener(`blur`,e),()=>window.removeEventListener(`blur`,e)},[U]),(0,z.useEffect)(()=>{if(!U||!Se)return;function e(e){let t=e.target;t instanceof Node&&(Pe.current?.contains(t)||Ce(!1))}return document.addEventListener(`pointerdown`,e,!0),()=>document.removeEventListener(`pointerdown`,e,!0)},[U,Se]),(0,z.useEffect)(()=>{let e=$(o),t=Wr(o),s=$r(K);if(x){let r=e?u(e):null,o=Jr(_)??(e?Qn(e):null),c=e&&r?!!de(e):!1,l=ti({activeTarget:i,supportHydrationKey:t,supportStatus:x.support.status});if(t&&l&&S(t),j.current.name!==a.GLOBAL_LOADING)return;let d=ni(i,x.interview);if(d){ze.current=x.interview.status===n.ACTIVE?x.interview.entryId:null,M({route:d,type:`replace`});return}if(ei(i))return;if(x.interview.status===n.ACTIVE)ze.current=x.interview.entryId,M({route:Kr({interview:x.interview,storedRoute:o,supportEntryId:K,supportRoute:s}),type:`replace`});else if(Gr({hasCachedInterviewSession:c,hasInterviewIdentity:!!r,interview:x.interview,storedRoute:o}))return;else ze.current=null,M({route:qr({storedRoute:o,supportEntryId:K,supportRoute:s}),type:`replace`});return}if(!e||!t){M({route:s,type:`replace`});return}let c=!1,l=u(e),d=Le.current;if(!l)return M({route:qr({storedRoute:Qn(e),supportEntryId:K,supportRoute:s}),type:`replace`}),S(t),()=>{c=!0};if(!d||d.key!==l){let t=Qn(e),n=!!de(e),i=k({client:nr(),options:e});d={key:l,promise:(async()=>{if(n||r(t)){let e=await i.restoreCachedSession();if(e&&r(t))return{controller:i,entry:e,kind:`interview`,route:dr(t,e)};if(e)return{controller:i,entry:e,kind:`support`,route:qr({storedRoute:t,supportEntryId:K,supportRoute:s})}}return{kind:`support`,route:qr({storedRoute:t,supportEntryId:K,supportRoute:s})}})()},Le.current=d}return d.promise.then(e=>{if(!(c||Re.current===l)){if(Re.current=l,e.kind===`interview`){R.current=e.controller,I(t=>wn(t,e.entry)),M({route:e.route,type:`replace`}),ei(i)||S(t);return}`entry`in e&&(R.current=e.controller,I(t=>wn(t,e.entry))),M({route:e.route,type:`replace`}),S(t)}}),()=>{c=!0}},[o,i,S,_,j.current,x,K]),(0,z.useEffect)(()=>{if(!K||j.current.name===a.GLOBAL_LOADING&&x&&(ei(i)||x.interview.status===n.ACTIVE))return;if(j.current.name===a.GLOBAL_LOADING&&x){let e=$(o),t=e?u(e):null,n=Jr(_)??(e?Qn(e):null);if(Gr({hasCachedInterviewSession:e&&t?!!de(e):!1,hasInterviewIdentity:!!t,interview:x.interview,storedRoute:n}))return}let e=m(K);(j.current.name===a.GLOBAL_LOADING||Zr(j.current)&&j.current.child.entryId!==K)&&M({route:e,type:`replace`})},[i,o,_,j.current,x,K]),(0,z.useEffect)(()=>{let e=Yr(j.current);if(x&&e){ne?.(e);return}let t=$(o);t&&$n(t,j.current)},[o,ne,j,x]),(0,z.useEffect)(()=>{if(!i)return;if(i.type===`support`||i.type===`home`){let e=Wr(o);if(e&&S(e),T!==Q.READY||!K)return;M({route:m(K),type:`push`});return}let e=ni(i,x?.interview);if(e){M({route:e,type:`push`});return}ei(i)&&(!x||x.interview.status!==n.ACTIVE)||T===Q.READY&&M({route:er(i),type:`push`})},[i,o,S,x,T,K]),(0,z.useEffect)(()=>{j.current.name===a.AGENTS_CONVERSATIONS&&j.current.child.name===p.CHAT&&j.current.child.entryId.startsWith(`interview/session/`)&&ur()},[j.current]);let X=(0,z.useRef)(!1);(0,z.useEffect)(()=>{if(!h){X.current=!1;return}X.current||r(j.current)&&(X.current=!0,l||v(!0))},[h,l,v,j.current]),(0,z.useEffect)(()=>{let e=Wr(o);!e||T!==Q.IDLE||j.current.name!==a.AGENTS_CONVERSATIONS||j.current.child.name!==p.CHAT||!f(j.current.child.entryId)||S(e)},[o,S,j,T]),(0,z.useEffect)(()=>{let e=$(o);if(x||!e||T!==Q.READY||ft)return;let t=!1,n=u(e),r=Fe.current;if(!n){Fe.current=null,R.current=null;return}if(!r||r.key!==n){let t=k({client:nr(),options:e});r={controller:t,key:n,promise:t.restoreCachedSession().then(e=>e??t.discoverInvitation()).catch(e=>(Fe.current?.key===n&&(Fe.current=null),console.error(`CustomerAgent interview eligibility request failed.`,e),null))},Fe.current=r}return R.current=r.controller,r.promise.then(e=>{t||I(t=>e?.status===N.ACTIVE?wn(t,e):Cn(t,e,A.mode,{canShowPrompt:rt}))}),()=>{t=!0}},[o,s,rt,ft,x,T,A.mode]);function bt(e){if(e===q)return;let t=P.entries.find(t=>t.id===e);if(I(t=>Tn(t,e)),t?.prompt){xt(t.prompt.invitationId);return}M({route:{child:{entryId:e,name:p.CHAT},name:a.AGENTS_CONVERSATIONS},type:`push`})}async function xt(t){let n=P.entries.find(e=>e.prompt?.invitationId===t);if(!n?.prompt)return;I(e=>({...Tn(e,n.id),invitePrompt:null,isMobileDockOpen:!1})),M({route:{child:{entryId:n.id,invitationId:t,name:p.INTERVIEW_STARTING},name:a.AGENTS_CONVERSATIONS},type:`push`}),ur();let r=t.startsWith(`runtime:`)&&c?await c.ensureInvitation():t,i=c?await c.startInvitation(r):await R.current?.startInvitation(r);if(!i)return;if(c&&ri(i)){let e=$(o);if(e){let t=k({client:nr(),options:e});t.hydrateSession(i.session),R.current=t}}I(e=>Dn(e,{invitationId:t,sessionId:i.sessionId,subtitle:Ge,title:H}));let l={conversationId:`interview/session/${i.sessionId}`,conversationType:`interview`,entryId:i.entryId,interviewSessionId:i.sessionId};c||(s?.emit(e.CONVERSATION_CREATED,l),s?.emit(e.INTERVIEW_SESSION_STARTED,l)),M({route:{child:{entryId:i.entryId,name:p.CHAT},name:a.AGENTS_CONVERSATIONS},type:`replace`})}function St(n,r){let i=P.entries.find(e=>e.prompt?.invitationId===n);i?.prompt&&s?.emit(r===t.LATER?e.INTERVIEW_INVITATION_LATER:e.INTERVIEW_INVITATION_CLOSED,{campaignId:i.prompt.campaignId,entryId:i.id,invitationId:n}),I(e=>En(e,n,r)),c?n.startsWith(`runtime:`)||c.chooseInvitation(n,r).catch(e=>{console.error(`CustomerAgent interview invitation choice request failed.`,e)}):R.current?.chooseInvitation(n,r).catch(e=>{console.error(`CustomerAgent interview invitation choice request failed.`,e)})}return(0,B.jsxs)(Mn,{activeEntryId:q,ariaLabel:qe,entries:at,invitePrompt:P.invitePrompt,interviewChat:R.current?(0,B.jsx)(z.Suspense,{fallback:(0,B.jsx)(Si,{label:`Loading interview`}),children:(0,B.jsx)(xi,{children:(0,B.jsx)(cr,{controller:R.current,description:Ge,eventBus:s,isHeaderMenuEnabled:U,isExpanded:l,isOpen:h,locale:g,onToggleExpanded:()=>v(!l),title:st,transcriptAppName:st,visitorName:D(o),viewportMode:A.mode,onOpenMobileDock:()=>I(e=>({...e,isMobileDockOpen:!0}))})})}):void 0,isChatLoading:dt,isExpanded:l,isMobileDockOpen:P.isMobileDockOpen,isOpen:h,route:j.current,routeTransitionKey:j.transitionKey,style:Ye,viewportMode:A.mode,onEntrySelect:bt,onInviteClose:e=>void St(e,t.CLOSE),onInviteLater:e=>void St(e,t.LATER),onInviteStart:e=>void xt(e),onMobileDockOpenChange:e=>I(t=>({...t,isMobileDockOpen:e})),children:[(0,B.jsxs)(`header`,{className:F(`grid shrink-0 items-center gap-[var(--messenger-header-gap)] border-b border-border-divider bg-bg-canvas px-[var(--messenger-header-padding-x)] py-[var(--messenger-header-padding-y)]`,A.mode===`mobile`?`grid-cols-[auto_auto_1fr_auto] pl-1`:`grid-cols-[auto_1fr_auto]`),"data-customer-agent-panel-header":``,children:[A.mode===`mobile`?(0,B.jsx)(`button`,{className:`grid h-[var(--messenger-header-button-size)] w-6 cursor-pointer place-items-center rounded-md border-0 bg-transparent p-0 text-text-quaternary transition-colors hover:bg-gray-3 hover:text-text-primary focus-visible:outline-none focus-visible:shadow-none`,"aria-label":`Open conversations`,title:`Open conversations`,type:`button`,onClick:()=>I(e=>({...e,isMobileDockOpen:!0})),children:(0,B.jsx)(ae,{size:16})}):null,(0,B.jsx)(`div`,{className:`grid h-[var(--messenger-header-avatar-size)] w-[var(--messenger-header-avatar-size)] place-items-center rounded-full bg-[var(--customer-agent-primary)] text-gray-1 shadow-[0_0_0_1px_var(--border-default)]`,"aria-hidden":`true`,children:(0,B.jsx)(we,{size:16})}),(0,B.jsxs)(`div`,{className:`flex min-w-0 flex-col justify-center`,children:[(0,B.jsx)(`p`,{className:`m-0 truncate text-[length:var(--messenger-header-title-size)] font-semibold leading-[var(--messenger-header-title-line-height)]`,children:H}),(0,B.jsx)(`span`,{className:`block truncate text-[length:var(--messenger-header-subtitle-size)] leading-[var(--messenger-header-subtitle-line-height)] text-text-tertiary`,children:g.messages.status_reply_time})]}),U?(0,B.jsx)(`div`,{className:`relative flex items-center gap-[var(--messenger-header-action-gap)] pr-[var(--messenger-header-button-size)]`,children:(0,B.jsxs)(`div`,{ref:Pe,onKeyDown:e=>{e.key===`Escape`&&(e.stopPropagation(),Ce(!1))},children:[(0,B.jsx)(`button`,{className:`grid h-[var(--messenger-header-button-size)] w-[var(--messenger-header-button-size)] cursor-pointer place-items-center rounded-[var(--messenger-header-button-radius)] border-0 bg-transparent text-text-quaternary transition-colors hover:bg-gray-3 hover:text-text-primary focus-visible:outline-none focus-visible:shadow-none data-[state=open]:bg-gray-3 data-[state=open]:text-text-primary`,"aria-expanded":Se,"aria-haspopup":`menu`,"aria-label":g.messages.more_options,"data-state":Se?`open`:`closed`,title:g.messages.more_options,type:`button`,onClick:()=>Ce(e=>!e),children:(0,B.jsx)(re,{size:16})}),Se?(0,B.jsxs)(`div`,{className:`absolute top-[calc(100%+0.5rem)] right-[var(--messenger-header-button-size)] z-[var(--z-dropdown)] grid min-w-64 gap-1 rounded-lg border border-border-default bg-bg-elevated p-1 text-sm text-text-primary shadow-popover`,role:`menu`,children:[(0,B.jsxs)(`button`,{className:`flex w-full cursor-pointer items-center gap-2 rounded-md border-0 bg-transparent px-2 py-1.5 text-left text-sm text-text-secondary transition-colors hover:bg-gray-3 hover:text-text-primary focus-visible:outline-none focus-visible:shadow-[var(--shadow-focus)]`,role:`menuitem`,type:`button`,onClick:()=>{Ce(!1),v(!l)},children:[l?(0,B.jsx)(oe,{size:16}):(0,B.jsx)(se,{size:16}),(0,B.jsx)(`span`,{children:l?g.messages.collapse_window:g.messages.expand_window})]}),(0,B.jsxs)(`button`,{className:`flex w-full cursor-pointer items-center gap-2 rounded-md border-0 bg-transparent px-2 py-1.5 text-left text-sm text-text-secondary transition-colors hover:bg-gray-3 hover:text-text-primary focus-visible:outline-none focus-visible:shadow-[var(--shadow-focus)]`,role:`menuitem`,type:`button`,onClick:()=>{Ce(!1),_t()},children:[(0,B.jsx)(pe,{size:16}),(0,B.jsx)(`span`,{children:g.messages.download_transcript})]})]}):null]})}):(0,B.jsx)(`div`,{className:`h-[var(--messenger-header-button-size)] w-[var(--messenger-header-button-size)]`,"data-customer-agent-header-menu-placeholder":``,"aria-hidden":`true`})]}),(0,B.jsx)(C,{className:`relative flex min-h-0 flex-1 flex-col overflow-hidden bg-bg-canvas`,children:(0,B.jsx)(ue,{asChild:!0,"aria-live":`polite`,autoScroll:!0,role:`log`,scrollToBottomOnInitialize:!0,scrollToBottomOnRunStart:!0,scrollToBottomOnThreadSwitch:!0,children:(0,B.jsx)(`div`,{className:`customer-agent-thread-viewport min-h-0 flex-1 overflow-y-auto bg-bg-canvas [scrollbar-width:none] [&::-webkit-scrollbar]:hidden [&>[data-radix-scroll-area-content]]:flex [&>[data-radix-scroll-area-content]]:min-h-full [&>[data-radix-scroll-area-content]]:flex-col [&>[data-radix-scroll-area-content]]:self-stretch [&>[data-radix-scroll-area-content]]:bg-inherit [&>div]:flex [&>div]:min-h-full [&>div]:flex-col [&>div]:self-stretch [&>div]:bg-inherit`,"data-customer-agent-thread-viewport":``,ref:He,onScroll:Y,children:(0,B.jsxs)(`div`,{className:F(`flex min-h-full flex-col px-[var(--messenger-conversation-horizontal-padding)] pt-3`,`customer-agent-message-list`),"data-customer-agent-message-list":``,children:[Je?(0,B.jsx)(`p`,{className:`mx-auto mt-1 mb-8 max-w-[min(100%,var(--messenger-conversation-part-max-width))] whitespace-pre-wrap px-2 text-center text-base leading-6 text-text-tertiary`,children:Je}):null,(0,B.jsx)(xe,{children:({message:e})=>{let t=Ze.get(e.id);return t?(0,B.jsx)(hi,{...t,appName:H,isTimeVisible:Ee[e.id]??t.showsDefaultAssistantTime,locale:g,onAttachmentLoad:yt,onTimeVisibilityChange:t=>{De(n=>({...n,[e.id]:t}))}}):null}})]})})})}),(0,B.jsxs)(ve,{className:F(`relative z-[var(--z-composer)] shrink-0 bg-transparent px-[var(--messenger-conversation-horizontal-padding)] pt-0 pb-[max(1rem,calc(1rem+var(--customer-agent-bottom-inset)))]`,`-mt-[var(--messenger-radius)]`),onSubmit:()=>{pt.closeEmojiPicker()},children:[(0,B.jsx)(_e,{removeAttachmentLabel:g.messages.remove_attachment}),(0,B.jsx)(ge,{inputAriaLabel:g.messages.message_aria_label,inputRef:gt,placeholder:g.messages.input_placeholder}),(0,B.jsxs)(ye,{children:[(0,B.jsxs)(me,{children:[(0,B.jsx)(he,{attachmentLabel:g.messages.attachment_label}),(0,B.jsx)(w,{hostRef:pt.emojiPickerHostRef,isLoading:pt.isEmojiPickerLoading,open:pt.isEmojiPickerOpen,onOpenChange:pt.onEmojiOpenChange,children:(0,B.jsx)(fe,{emojiLabel:g.messages.add_emoji})})]}),(0,B.jsx)(le,{sendLabel:g.messages.send_message})]})]})]})}function hi({appName:e,dateLabel:t,groupPosition:n,isFirst:r,isTimeVisible:i,locale:a,message:o,onAttachmentLoad:s,onTimeVisibilityChange:c,previousMessage:l}){let u=o.role===`assistant`&&!o.isPending;function d(){u&&c(!i)}function f(e){let t=e.target;t instanceof Element&&t.closest(`a, button`)||d()}function ee(e){!u||e.key!==`Enter`&&e.key!==` `||(e.preventDefault(),d())}return(0,B.jsxs)(B.Fragment,{children:[t?(0,B.jsx)(`div`,{className:F(`self-center rounded-full px-3 py-1 text-sm leading-5 text-text-tertiary`,r?`mt-1 mb-3`:`mt-4 mb-3`),children:t}):null,(0,B.jsxs)(Ce,{className:F(`flex max-w-[var(--messenger-conversation-part-max-width)] flex-col`,!r&&!t&&(l?.role===o.role?`mt-[var(--messenger-conversation-part-group-gap)]`:`mt-[var(--messenger-conversation-part-stack-gap)]`),o.role===`user`?`self-end items-end`:`self-start items-start`),"aria-expanded":u?i:void 0,role:u?`button`:void 0,tabIndex:u?0:void 0,onClick:f,onKeyDown:ee,children:[(0,B.jsx)(`div`,{className:F(`w-fit max-w-full whitespace-pre-wrap px-[var(--messenger-conversation-part-padding-x)] py-[var(--messenger-conversation-part-padding-y)] text-base leading-5`,o.role===`user`?`bg-[var(--customer-agent-primary)] text-gray-1`:`bg-gray-3 text-text-secondary`),style:Ir(o.role,n),children:(0,B.jsxs)(`div`,{className:`grid gap-2`,children:[o.text?(0,B.jsx)(A,{children:({part:e})=>e.type===`text`?(0,B.jsx)(bi,{}):null}):null,o.isPending?(0,B.jsx)(Ci,{}):null,o.attachments.length>0?(0,B.jsx)(vi,{attachments:o.attachments,role:o.role,onAttachmentLoad:s}):null]})}),u?(0,B.jsxs)(`span`,{className:F(`overflow-hidden px-[var(--messenger-conversation-part-padding-x)] text-sm leading-5 text-text-tertiary transition-[max-height,opacity,transform,margin] duration-200 ease-out`,i?`mt-1 max-h-5 translate-y-0 opacity-100`:`mt-0 max-h-0 -translate-y-1 opacity-0`),children:[e,` · `,vr(o.assistantAuthor,a),` ·`,` `,Pr(o.createdAt,a)]}):null]})]})}function gi(e){if(!Number.isFinite(e)||e<=0)return``;let t=e/(1024*1024);return t>=1?`${t.toFixed(t>=10?0:1)} MB`:`${Math.max(1,Math.round(e/1024))} KB`}function _i(e){let t=e.filename.split(`.`).pop();return t&&t!==e.filename?t.toUpperCase():e.mimeType.split(`/`).pop()?.toUpperCase()??`FILE`}function vi({attachments:e,onAttachmentLoad:t,role:n}){return(0,B.jsx)(`div`,{className:`grid gap-2`,children:e.map(e=>e.mimeType.startsWith(`image/`)&&e.url?(0,B.jsx)(yi,{attachment:e,onLoad:t},e.id):(0,B.jsxs)(`a`,{className:F(`grid min-w-0 grid-cols-[32px_minmax(0,1fr)] items-center gap-2 rounded-lg px-2.5 py-2 no-underline`,n===`user`?`bg-gray-1/15 text-gray-1 hover:bg-gray-1/20`:`bg-bg-canvas text-text-secondary hover:bg-gray-2`),href:e.url||void 0,rel:`noreferrer`,target:`_blank`,children:[(0,B.jsx)(`span`,{className:F(`grid h-8 w-8 place-items-center rounded-md`,n===`user`?`bg-gray-1/20`:`bg-gray-12 text-gray-1`),children:(0,B.jsx)(O,{size:16})}),(0,B.jsxs)(`span`,{className:`min-w-0`,children:[(0,B.jsx)(`span`,{className:`block truncate text-sm font-semibold`,children:e.filename}),(0,B.jsx)(`span`,{className:`block truncate text-xs opacity-70`,children:[_i(e),gi(e.sizeBytes)].filter(Boolean).join(` · `)})]})]},e.id))})}function yi({attachment:e,onLoad:t}){let[n]=(0,z.useState)(()=>e.file&&e.mimeType.startsWith(`image/`)?URL.createObjectURL(e.file):null),[r,i]=(0,z.useState)(!e.url),[a,o]=(0,z.useState)(null),s=r?e.url:n??e.url,c=a!==null,l=c?Math.min(256,Math.round(192*a)):192;(0,z.useEffect)(()=>()=>{n&&URL.revokeObjectURL(n)},[n]),(0,z.useEffect)(()=>{if(!e.url)return;let n=!1,r=new Image;return r.src=e.url,r.decode().catch(()=>void 0).then(()=>{n||(r.naturalWidth>0&&r.naturalHeight>0&&o(r.naturalWidth/r.naturalHeight),i(!0),t(),window.requestAnimationFrame(t))}),()=>{n=!0}},[e.url,t]),(0,z.useEffect)(()=>{if(!n)return;let e=!1,t=new Image;return t.src=n,t.decode().catch(()=>void 0).then(()=>{e||t.naturalWidth<=0||t.naturalHeight<=0||o(t.naturalWidth/t.naturalHeight)}),()=>{e=!0}},[n]);function u(e){let n=e.currentTarget;n.naturalWidth>0&&n.naturalHeight>0&&o(n.naturalWidth/n.naturalHeight),t(),window.requestAnimationFrame(t)}return(0,B.jsxs)(`a`,{className:`relative block max-w-full overflow-hidden rounded-lg bg-gray-3`,href:e.url,rel:`noreferrer`,target:`_blank`,style:{aspectRatio:a??void 0,height:c?void 0:144,width:l},children:[c?null:(0,B.jsx)(`span`,{className:`absolute inset-0 animate-pulse bg-gray-4`,"aria-hidden":`true`}),s?(0,B.jsx)(`img`,{className:F(`absolute inset-0 h-full w-full object-contain transition-opacity`,c?`opacity-100`:`opacity-0`),alt:e.filename,src:s,onLoad:u}):null]})}function bi(){return(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(z.Suspense,{fallback:(0,B.jsx)(Se,{className:`min-w-0 break-words`}),children:(0,B.jsx)(or,{})}),(0,B.jsx)(T,{children:(0,B.jsx)(Ci,{})})]})}function xi({children:e}){return(0,B.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col animate-[customer-agent-chat-route-in_var(--duration-fast)_var(--ease-emphasis)_both] motion-reduce:animate-none`,"data-customer-agent-lazy-route-ready":``,children:e})}function Si({label:e}){return(0,B.jsx)(`div`,{className:`grid min-h-0 flex-1 place-items-center`,"aria-label":e,role:`status`,children:(0,B.jsx)(`div`,{className:`h-8 w-8 animate-spin rounded-full border-2 border-[var(--gray-4)] border-t-[var(--customer-agent-primary)]`})})}function Ci(){return(0,B.jsxs)(`span`,{className:`inline-flex h-5 items-center gap-1 align-middle text-text-quaternary`,children:[(0,B.jsx)(`span`,{className:`h-1.5 w-1.5 animate-[customer-agent-typing-dot-bounce_1.05s_ease-in-out_infinite] rounded-full bg-current`}),(0,B.jsx)(`span`,{className:`h-1.5 w-1.5 animate-[customer-agent-typing-dot-bounce_1.05s_ease-in-out_infinite] rounded-full bg-current [animation-delay:140ms]`}),(0,B.jsx)(`span`,{className:`h-1.5 w-1.5 animate-[customer-agent-typing-dot-bounce_1.05s_ease-in-out_infinite] rounded-full bg-current [animation-delay:280ms]`})]})}export{pi as WidgetPanel};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var e=class extends Error{code;requestId;status;constructor(e,t){super(e),this.name=`CustomerAgentApiError`,this.code=t.code,this.requestId=t.requestId??null,this.status=t.status}};function t(e){return e.replace(/\/+$/g,``)}function n(e){return!!e&&typeof e==`object`&&e.ok===!1&&typeof e.error?.message==`string`}function r(e){return!!e&&typeof e==`object`&&e.ok===!0}async function i(t){let n=await t.text();if(!n)return null;try{return JSON.parse(n)}catch{throw new e(`The server returned an unreadable response.`,{code:`INVALID_RESPONSE`,requestId:t.headers.get(`X-Request-Id`),status:t.status})}}function a(a){let o=t(a);async function s(t){let a=await i(t);if(n(a))throw new e(a.error.message,{code:a.error.code,requestId:a.meta?.requestId??t.headers.get(`X-Request-Id`),status:t.status});if(!t.ok)throw new e(`The server could not complete the request.`,{code:`HTTP_ERROR`,requestId:t.headers.get(`X-Request-Id`),status:t.status});if(!r(a))throw new e(`The server returned an unexpected response.`,{code:`INVALID_RESPONSE`,requestId:t.headers.get(`X-Request-Id`),status:t.status});return{data:a.data,response:t}}async function c(e,t={}){let n=new Headers;return t.method!==`GET`&&n.set(`Content-Type`,`application/json`),t.conversationId&&n.set(`X-Customer-Agent-Conversation-Id`,t.conversationId),await s(await fetch(`${o}${e}`,{body:t.body?JSON.stringify(t.body):void 0,credentials:`omit`,headers:n,method:t.method??`GET`,signal:t.signal}))}async function l(e,t,n={}){let r=new Headers;return n.conversationId&&r.set(`X-Customer-Agent-Conversation-Id`,n.conversationId),await s(await fetch(`${o}${e}`,{body:t,credentials:`omit`,headers:r,method:`POST`,signal:n.signal}))}return{request:c,upload:l}}function o(){return typeof crypto<`u`&&`randomUUID`in crypto?crypto.randomUUID():`ca_${Date.now()}_${Math.random().toString(36).slice(2)}`}function s(){return`https://api-ctmr-agent-dev.deepjoy.me/api/customer-agent`}function c(e,t){if(!e.app_id)throw Error(`CustomerAgent requires an app_id.`);let{launcher:n,mount:r,...i}=e;return{...i,context:e.context??{},embedded:!!r,launcher:n?{offset:n.offset,placement:n.placement,style:n.style,variables:n.variables}:void 0,widgetId:t}}function l(e){return typeof e==`string`&&e.trim()?e.trim():null}function u(e){let t=l(e.user?.id);return t?JSON.stringify({appId:e.app_id,userId:t}):null}function d(e){let t=u(e);return t?`customer_agent:interview_session:${encodeURIComponent(t)}`:null}function f(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.entryId==`string`&&typeof t.priority==`number`&&typeof t.sessionId==`string`&&typeof t.title==`string`}function p(e){return u(e)}function m(){return{clear(e){let t=d(e);if(t)try{window.localStorage.removeItem(t)}catch{}},read(e){let t=d(e);if(!t)return null;try{let e=window.localStorage.getItem(t);if(!e)return null;let n=JSON.parse(e);return f(n)?n:null}catch{return null}},write(e,t){let n=d(e);if(n)try{window.localStorage.setItem(n,JSON.stringify(t))}catch{}}}}var h=class extends Error{conversationId;constructor(e){super(`The support conversation session is no longer available.`),this.conversationId=e,this.name=`CustomerAgentSessionInvalidatedError`}};function g(e){return typeof e==`string`&&e.trim()?e.trim():null}function _(e){let t=g(e.user?.id),n=g(e.anonymous_id),r=t?`user:${t}`:n?`anonymous:${n}`:`anonymous`;return encodeURIComponent(r)}function v(e){return`customer_agent:conversation_id:${e.app_id}:${_(e)}`}function y(e){return`${e.app_id}::${_(e)}`}function b(e){try{return window.localStorage.getItem(v(e))}catch{return null}}function x(e,t){try{window.localStorage.setItem(v(e),t)}catch{}}function S(e){try{window.localStorage.removeItem(v(e))}catch{}}function C(){try{return window.parent?.location??window.location}catch{return window.location}}function w(){let e=C();return!e?.href||e.href===`about:blank`?{}:{customerOrigin:e.origin,pagePath:`${e.pathname}${e.search}${e.hash}`,pageUrl:e.href}}function T(){return{language:navigator.language,languages:navigator.languages,platform:navigator.platform,screen:{height:window.screen.height,width:window.screen.width},userAgent:navigator.userAgent,viewport:{height:window.innerHeight,width:window.innerWidth}}}function E(e){return Object.fromEntries(Object.entries(e).filter(e=>e[1]!==void 0))}function D(e){return Array.isArray(e)?`[${e.map(e=>D(e)).join(`,`)}]`:e&&typeof e==`object`?`{${Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${JSON.stringify(e)}:${D(t)}`).join(`,`)}}`:JSON.stringify(e)}function O(e){return e.anonymous_id??e.user?.id}function k(e){return E({...e.context,...e.user,userId:e.user?.id,visitorId:O(e)})}function A(e){let t=k(e);return{appId:e.app_id,...E({...w(),deviceInfo:T(),locale:e.locale,userContext:Object.keys(t).length?t:void 0,visitorId:O(e),widgetId:e.widgetId})}}function j(e){return{id:e.id,role:e.role,content:e.content,createdAt:new Date(e.createdAt),metadata:{custom:{assistantAuthor:e.assistantAuthor,attachments:e.attachments??[]}},status:e.role===`assistant`?{type:`complete`,reason:`stop`}:void 0}}function M(e){return e.map(j)}var N=class{apiOrigin=null;client=null;lastContextFingerprint=null;session=null;sessionPromise=null;getClient(){let e=s();return(this.apiOrigin!==e||!this.client)&&(this.apiOrigin=e,this.client=a(e),this.lastContextFingerprint=null,this.session=null,this.sessionPromise=null),this.client}clear(e){this.lastContextFingerprint=null,this.session=null,this.sessionPromise=null,S(e)}hydrateSession(e,t){this.session={cacheKey:y(e),conversationId:t.conversationId,messages:t.messages},this.sessionPromise=null,x(e,t.conversationId)}async ensureSession(e,t={}){let n=y(e);if(this.session?.conversationId&&this.session.cacheKey===n)return this.session;if(this.session?.cacheKey!==n&&(this.lastContextFingerprint=null,this.session=null,this.sessionPromise=null),this.sessionPromise)return await this.sessionPromise;let r=b(e);this.sessionPromise=this.startSession(e,r,t);try{return this.session=await this.sessionPromise,this.session}finally{this.sessionPromise=null}}async sendMessage(t,n,r,i,a={}){let o=this.getHydratedSession(t)??await this.ensureSession(t,a);try{let e=await this.postMessage(t,o.conversationId,n,r,i);return this.session?.conversationId===e.conversationId&&(this.session={...this.session,messages:P(this.session.messages,[e.userMessage,e.assistantMessage])}),e}catch(s){if(s instanceof e&&s.code===`NOT_FOUND`){this.clear(t),a.onSessionInvalidated?.(o.conversationId);let e=await this.ensureSession(t,a),s=await this.postMessage(t,e.conversationId,n,r,i);return this.session={...e,messages:P(e.messages,[s.userMessage,s.assistantMessage])},s}throw s}}async refreshSession(t,n){let r=this.getHydratedSession(t);if(!r)return null;try{let{data:e}=await this.getClient().request(`/conversation`,{conversationId:r.conversationId,method:`GET`,signal:n});return this.session={...r,conversationId:e.conversationId,messages:e.messages},x(t,e.conversationId),this.session}catch(n){if(n instanceof e&&n.code===`NOT_FOUND`){let e=r.conversationId;throw this.clear(t),new h(e)}throw n}}async updateContext(e){let t=this.getHydratedSession(e);if(!t)return null;let n=A(e),r=D(n);if(r===this.lastContextFingerprint)return null;let{data:i}=await this.getClient().request(`/context`,{body:{...n,conversationId:t.conversationId},conversationId:t.conversationId,method:`PATCH`});return this.lastContextFingerprint=r,i}async uploadAttachment(e,t,n={}){let r=this.getHydratedSession(e);if(!r)throw Error(`The support conversation session has not been initialized.`);let i=new FormData;i.set(`appId`,e.app_id),i.set(`conversationId`,r.conversationId),i.set(`file`,t);let{data:a}=await this.getClient().upload(`/attachments`,i,{conversationId:r.conversationId});return{filename:a.filename,id:a.attachmentId,mimeType:a.mimeType,sizeBytes:a.sizeBytes,url:a.url}}async startSession(t,n,r={}){let i=this.getClient(),a=A(t);try{let{data:e}=await i.request(`/session`,{body:E({...a,conversationId:n??void 0}),conversationId:n,method:`POST`}),o=e.conversationId;return x(t,o),this.lastContextFingerprint=D(a),n||r.onConversationCreated?.(o),{cacheKey:y(t),conversationId:o,messages:e.messages}}catch(i){if(n&&i instanceof e&&i.code===`NOT_FOUND`)return S(t),await this.startSession(t,null,r);throw i}}async postMessage(e,t,n,r,i){let a=A(e),{data:o}=await this.getClient().request(`/messages`,{body:{...a,attachments:r.length?r:void 0,conversationId:t,message:n},conversationId:t,method:`POST`,signal:i});return this.lastContextFingerprint=D(a),o}getHydratedSession(e){let t=y(e);return this.session?.conversationId&&this.session.cacheKey===t?this.session:null}};function P(e,t){let n=new Map(e.map(e=>[e.id,e]));for(let e of t)n.set(e.id,e);return[...n.values()]}var F=new N,I={AGENTS_CONVERSATIONS:`agents.conversations`,GLOBAL_ERROR:`global.error`,GLOBAL_LOADING:`global.loading`},L={CHAT:`chat`,INTERVIEW_STARTING:`interview.starting`},R=`interview/session/`,z=`support/session/`;function B(e,t){return e.startsWith(t)&&e.length>t.length}function V(e){return B(e,R)}function H(e){return`${z}${e}`}function U(e){return B(e,z)}function W(e){return U(e)?e.slice(16):null}function G(e){return!e||e.name!==I.AGENTS_CONVERSATIONS?!1:e.child.name===L.CHAT&&V(e.child.entryId)}function K(e){return{child:{entryId:e,name:L.CHAT},name:I.AGENTS_CONVERSATIONS}}export{c as _,G as a,a as b,I as c,M as d,F as f,o as g,u as h,V as i,h as l,p as m,H as n,U as o,m as p,W as r,L as s,K as t,A as u,s as v,e as y};
|