@deepdesk/deepdesk-sdk 19.1.2-beta.2 → 19.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs.js CHANGED
@@ -7,6 +7,6 @@ Try polyfilling it using "@formatjs/intl-pluralrules"
7
7
  c6.8-6.8,15.4-10.2,24.7-10.2h11.9v-70c0-44.4,16.2-82.8,47.8-115.2S212.1,0,256.4,0s82.8,16.2,115.2,47.8
8
8
  c32.4,32.4,47.8,70,47.8,115.2v70h11.9c9.4,0,17.9,3.4,24.7,10.2C462.1,250,465.5,257.7,465.5,267.9z`})})});var Hi=require("react/jsx-runtime"),xf={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},Pc=({className:t,color:e})=>(0,Hi.jsx)("svg",{className:t,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:(0,Hi.jsx)("path",{d:"M172.03 0.0199966H0V86.03C47.5 86.03 86 124.54 86 172.04C86 124.54 124.51 86.03 172.01 86.03C219.51 86.03 258.03 124.54 258.03 172.04C258.03 219.54 219.52 258.05 172.01 258.05C124.5 258.05 86 219.54 86 172.04C86 219.54 47.5 258.05 0 258.05V344.06H172.03C267.04 344.06 344.06 267.04 344.06 172.03C344.06 77.02 267.04 0 172.03 0V0.0199966Z",fill:xf[e||"pink"]})});var Ic={root:"dd-LbeUM",text:"dd-Dpfn1",isLoggedIn:"dd-XvHAn",isLoggedOut:"dd-21y-z",icon:"dd-8rLqS",logo:"dd-slXhD",lock:"dd-ByzlR"};var Bi={};Y(Bi,{enUS:()=>Sf,nlNL:()=>bf});var Sf={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},bf={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};var Mc=require("react-redux"),an=require("react/jsx-runtime"),Nc=({onLogIn:t})=>{let e=R(Bi),n=k("floatingMenu"),o=k("productName"),r=(0,Mc.useDispatch)(),s=(0,Ac.useSelector)(ne),i=S("FloatingMenu",Ic);if(s===null||n===!1)return null;let a=()=>{s===!0?r(Oe(!0)):t()};return(0,an.jsxs)("button",{type:"button",className:(0,Lc.default)(i.root,{[i.isLoggedIn]:s,[i.isLoggedOut]:!s}),onClick:a,children:[(0,an.jsx)("div",{className:i.text,children:e(s?"search":"signin",{productName:o})}),(0,an.jsxs)("div",{className:i.icon,children:[(0,an.jsx)(Pc,{className:i.logo,color:"pink"}),s===!1&&(0,an.jsx)(Rc,{className:i.lock})]})]})};var ps=require("react"),ct=require("react-redux");function qe(t){let{showMidSentenceSuggestions:e,showSuggestionsBeforePattern:n,showSuggestionsAfterPattern:o}=t.settings,{text:r,selection:s}=t.input;return s.start!==s.end?!1:s.end>=r.length?!0:e?n&&new RegExp(n).test(r.substring(s.end))||o&&new RegExp(o).test(r.substring(0,s.end))?!0:n===!1&&o===!1:!1}var Oc=require("@reduxjs/toolkit"),Cf={showTabHint:!1,inputHasFocus:!1,overlayCollapsed:!1,openOverlayWhenTyping:!1,overlayCollapsedUserOverwrite:!1},ds=({ui:t})=>t.overlayCollapsed,Dc=(0,Oc.createSlice)({name:"ui",initialState:Cf,reducers:{setShowTabHint(t,e){t.showTabHint=e.payload},setInputFocus(t,e){t.overlayCollapsedUserOverwrite!==!0&&(e.payload===!0&&(t.overlayCollapsed=!1),t.inputHasFocus=e.payload)},setOverlayCollapsed(t,e){e.payload.collapse===!1&&(t.openOverlayWhenTyping=!1),!(e.payload.skipWhenInputFocus&&t.inputHasFocus)&&(t.overlayCollapsed=e.payload.collapse)},setOpenOverlayWhenTyping(t,e){t.openOverlayWhenTyping=e.payload},setOverlayCollapsedUserOverwrite(t,e){t.overlayCollapsedUserOverwrite=e.payload,t.overlayCollapsed=e.payload}}}),{setShowTabHint:No,setInputFocus:cs,setOverlayCollapsed:Lt,setOpenOverlayWhenTyping:_c,setOverlayCollapsedUserOverwrite:Fc}=Dc.actions,Hc=Dc.reducer;var Vc=require("react");var Ki=require("interweave"),At=require("react"),Do=require("react-redux");var Bc=require("react");function Uc(t,e,n){(0,Bc.useEffect)(()=>{let o=t.current;return o?(o.addEventListener(e,n),()=>{o.removeEventListener(e,n)}):()=>{}},[t,e,n])}var Kc={root:"dd-1MBCO",actions:"dd--x4cy",closeIconContainer:"dd-1z5NR",closeIcon:"dd-8qMF-",badge:"dd-4Fpkz",formattedText:"dd-EzvTB",assistantContainer:"dd-j6o8F",formattedTextTruncated:"dd-fv169",assistantBadge:"dd-VD57E"};var Oo=require("react/jsx-runtime"),zc=({title:t})=>(0,Oo.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"18px",height:"18px",viewBox:"0 0 24 24","aria-labelledby":"closeTitle",children:[(0,Oo.jsx)("title",{id:"closeTitle",children:t}),(0,Oo.jsx)("path",{d:"M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"})]});var Ui={};Y(Ui,{enUS:()=>Tf,nlNL:()=>wf});var Tf={assistant:[{type:0,value:"Assistant"}],close:[{type:0,value:"Close"}]},wf={assistant:[{type:0,value:"Assistent"}],close:[{type:0,value:"Sluiten"}]};var Se=require("react/jsx-runtime"),kf=["search","personal-collection-search","search-autocomplete"];function Rf(t,e,n,o={}){var s;let r="";return kf.includes(e)?r=Qd(Pi(t,n,{stripAgentPart:!0}),(s=o.searchKeywords)!=null?s:[n]):r=Pi(t,n,o),o.placeholders===!0&&(r=Zd(r)),r}var Pf=()=>{},If=({selected:t,suggestion:e})=>{let n=R(Ui),o=k("inlineSuggestions"),r=(0,Do.useSelector)(Cn),[s,i]=(0,At.useState)(!1),a=k("enableSuggestionFeedback"),d=(0,Do.useSelector)(g=>g.input.text),l=(0,Do.useDispatch)(),c=S("TextSuggestion",Kc),p=(0,At.useRef)(null),u=e.source==="assistant",f=a&&!u;(0,At.useEffect)(()=>{let g=setTimeout(()=>{l(gl({text:e.text,suggestion:e}))},500);return()=>{clearTimeout(g)}},[e]),Uc(p,"click",()=>{l(ye({suggestion:e,text:e.text,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"}))});let h=()=>{l(Vt({source:e.source,text:e.text,assistantCode:e.assistantCode}))},m=(0,At.useMemo)(()=>Rf(e.text,e.source,r,{stripAgentPart:o,placeholders:!0,searchKeywords:e.searchKeywords}),[o,e.text,e.source,r,e.searchKeywords]);return e.source==="gpt"&&!o?null:(0,Se.jsxs)("div",{className:c.root,onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),children:[(0,Se.jsx)(I,{ref:p,as:"button","data-testid":"suggestions-overlay-item",selected:t,onClick:Pf,children:e.source==="assistant"?(0,Se.jsxs)("div",{className:c.assistantContainer,children:[(0,Se.jsx)(Ki.Interweave,{containerTagName:"div",tagName:"span",className:c.formattedTextTruncated,content:m}),(0,Se.jsx)("span",{className:c.assistantBadge,children:n("assistant")})]}):(0,Se.jsx)(Ki.Interweave,{containerTagName:"div",tagName:"span",className:c.formattedText,content:m})}),f&&s&&(0,Se.jsx)("div",{className:c.actions,children:(0,Se.jsx)(rs,{source:"overlay",context:d,suggestion:e})}),u&&s&&(0,Se.jsx)("div",{className:c.closeIconContainer,children:(0,Se.jsx)("button",{type:"button",className:c.closeIcon,onClick:h,title:n("close"),children:(0,Se.jsx)(zc,{title:n("close")})})})]})},Wc=If;var jc=require("react/jsx-runtime"),Lf=({suggestions:t,selectedIndex:e,reverse:n})=>(0,Vc.useMemo)(()=>{let r=t.map((s,i)=>(0,jc.jsx)(Wc,{index:i,selected:i===e,suggestion:s},`${s.text}-${s.source}`));return n?r.reverse():r},[t,e,n]),us=Lf;var $c={root:"dd-PfvRI",paper:"dd-HYlyY"};var _o=require("react/jsx-runtime"),Af=()=>{let t=(0,ps.useRef)(null),e=S("InlineSuggestionsOverlay",$c),n=(0,ct.useSelector)(qe),o=(0,ct.useDispatch)(),r=(0,ct.useSelector)(ne),s=(0,ct.useSelector)(bn),i=(0,ct.useSelector)(ds),a=k("showTextSuggestions"),d=(0,ct.useSelector)(Wt),l=(0,ct.useSelector)(to);return Rt(()=>{setTimeout(()=>{o(Lt({collapse:!0,skipWhenInputFocus:!0}))})}),(0,ps.useEffect)(()=>{let c=t.current;if(!c||!c.parentElement)return;c.parentElement.style.left="0px";let p=c.getBoundingClientRect();c.parentElement.style.left=`${Math.min(window.innerWidth-4-p.right,0)}px`}),i||!n||!a||d.length===0||r!==!0||s===!1?null:(0,_o.jsx)("div",{className:e.root,"data-variant":"inline",children:(0,_o.jsx)("div",{ref:t,className:e.paper,children:(0,_o.jsx)(ae,{children:(0,_o.jsx)(us,{suggestions:d,selectedIndex:l})})})})},Gc=Af;var Mt=O(require("react"));var qc={root:"dd-7zvcP",dialogContent:"dd-4C0lK",continueButton:"dd-YUPQW",buttonContinueWrapper:"dd-IKpYs",nicknameInput:"dd-rxhGp",titleWrapper:"dd-nw3nD",title:"dd-5iof5",closeButtonWrapper:"dd-UUAzA",closeButton:"dd-7rjP5",buttonsWrapper:"dd-5e9Xb",errorMessage:"dd--5VgX",errorLink:"dd-u461n"};var Xc=require("react-redux");var zi={};Y(zi,{enUS:()=>Mf,nlNL:()=>Nf});var Mf={title:[{type:0,value:"Enter your nickname"}],close:[{type:0,value:"Close"}],nicknameDialogTitle:[{type:0,value:"Please enter the name you'd like customers to see during chat conversations. This nickname will be used across your Deepdesk environment."}],nicknameDialogInputPlaceholder:[{type:0,value:"Enter your nickname"}],nicknameDialogContinueButton:[{type:0,value:"Continue"}],nicknameDialogError:[{type:0,value:"Nickname cannot be empty or spaces only"}],nicknameDialogEmojiError:[{type:0,value:"You cannot use emojis in this field."}],nicknameDialogSaveError:[{type:0,value:"We couldn't save your details just now. Please try again, or update it at "},{type:1,value:"account"},{type:0,value:".deepdesk.com/admin/user-settings"}],nicknameDialogSaveErrorWithoutLink:[{type:0,value:"We couldn\u2019t save your details just now. Please try again later, or update them in My Deepdesk \u2192 Settings."}]},Nf={title:[{type:0,value:"Voer je bijnaam in"}],close:[{type:0,value:"Sluiten"}],nicknameDialogTitle:[{type:0,value:"Voer de naam in die je wilt dat klanten zien tijdens chatgesprekken. Deze bijnaam wordt gebruikt in je Deepdesk-omgeving."}],nicknameDialogInputPlaceholder:[{type:0,value:"Voer je bijnaam in"}],nicknameDialogContinueButton:[{type:0,value:"Doorgaan"}],nicknameDialogError:[{type:0,value:"Bijnaam mag niet leeg of alleen spaties zijn"}],nicknameDialogEmojiError:[{type:0,value:"Je kunt geen emoji's gebruiken in dit veld."}],nicknameDialogSaveError:[{type:0,value:"We konden je gegevens nu niet opslaan. Probeer het opnieuw of werk het bij op "},{type:1,value:"account"},{type:0,value:".deepdesk.com/admin/user-settings"}],nicknameDialogSaveErrorWithoutLink:[{type:0,value:"We konden je gegevens nu niet opslaan. Probeer het opnieuw later, of werk ze bij in My Deepdesk \u2192 Instellingen."}]};var Q=require("react/jsx-runtime"),Jc=({onClose:t,onSave:e,id:n,error:o})=>{let[r,s]=(0,Mt.useState)(""),[i,a]=(0,Mt.useState)(!1),[d,l]=(0,Mt.useState)(!1),c=S("Nickname",qc),p=Mt.default.useRef(null),u=(0,Xc.useSelector)(b=>b.info.showNicknameDialog),f=R(zi),h=k("adminUrl");(0,Mt.useEffect)(()=>{o&&a(!0)},[o]);let m=()=>{if(!p.current)return;r.trim()?p.current.setCustomValidity(""):p.current.setCustomValidity(f("nicknameDialogError")),p.current.reportValidity()},g=b=>{b.preventDefault();let T=r.trim(),C=b.currentTarget.querySelector("#nickname-input");if(!T){C.setCustomValidity(f("nicknameDialogError")),C.reportValidity();return}C.setCustomValidity(""),e(T)};return(0,Q.jsxs)(Nn,{isOpen:u,"datatest-id":n,onClose:t||(()=>{}),onBack:t||(()=>{}),children:[(0,Q.jsx)("div",{className:c.titleWrapper,children:(0,Q.jsx)("h1",{className:c.title,children:f("title")})}),(0,Q.jsxs)("form",{className:c.dialogContent,onSubmit:g,children:[(0,Q.jsx)("p",{children:f("nicknameDialogTitle")}),i&&o&&(0,Q.jsx)("div",{className:c.errorMessage,children:h?(()=>{let b=f("nicknameDialogSaveError",{account:h}),T=`${h}.deepdesk.com/admin/user-settings`,C=b.indexOf(T);if(C!==-1){let w=b.substring(0,C),L=b.substring(C+T.length);return(0,Q.jsxs)(Q.Fragment,{children:[w,(0,Q.jsx)("a",{href:T,target:"_blank",rel:"noopener noreferrer",className:c.errorLink,children:T}),L]})}return b})():f("nicknameDialogSaveErrorWithoutLink")}),(0,Q.jsx)("input",{required:!0,minLength:1,maxLength:20,"data-testid":"nickname-input",id:"nickname-input",className:c.nicknameInput,type:"text",placeholder:f("nicknameDialogInputPlaceholder"),value:r,onChange:b=>{l(new RegExp("\\p{Extended_Pictographic}","u").test(b.target.value)),s(b.target.value)},onBlur:m,ref:p}),d&&(0,Q.jsx)("div",{className:c.errorMessage,role:"alert",children:f("nicknameDialogEmojiError")}),(0,Q.jsxs)("div",{className:c.buttonsWrapper,children:[o?(0,Q.jsx)("div",{className:c.closeButtonWrapper,children:(0,Q.jsx)("button",{type:"button",className:c.closeButton,onClick:()=>t==null?void 0:t(),children:f("close")})}):null,(0,Q.jsx)("div",{className:c.buttonContinueWrapper,children:(0,Q.jsx)("button",{type:"submit",className:c.continueButton,disabled:!r.trim()||new RegExp("\\p{Extended_Pictographic}","u").test(r),children:f("nicknameDialogContinueButton")})})]})]})]})};var Qc=require("react-redux");var Fo=require("react/jsx-runtime"),Of=({children:t})=>{let n=k("locale").replace("-","");return(0,Fo.jsx)(pi.Provider,{value:n,children:t})},Df=({store:t,customStyles:e={},children:n})=>(0,Fo.jsx)(Qc.Provider,{store:t,children:(0,Fo.jsx)(Of,{children:(0,Fo.jsx)(Zn.Provider,{value:e,children:n})})}),ut=Df;var ms=O(require("classnames")),Un=require("react"),Ue=require("react-redux");var Zc=require("react");function Yc(t,e){let[n,o]=(0,Zc.useState)(()=>{if(typeof window=="undefined")return e;try{let s=window.localStorage.getItem(t);return s?JSON.parse(s):e}catch(s){return E.error(s),e}});return[n,s=>{try{let i=s instanceof Function?s(n):s;o(i),typeof window!="undefined"&&window.localStorage.setItem(t,JSON.stringify(i))}catch(i){E.error(i)}}]}var eu=()=>/Mac/i.test(navigator.platform);var nu=O(require("classnames")),pt=require("react");var Wi={};Y(Wi,{enUS:()=>_f,nlNL:()=>Ff});var _f={loginPlease:[{type:8,value:"login",children:[{type:0,value:"Sign in"}]},{type:0,value:" to enable "},{type:1,value:"productName"},{type:0,value:"."}],snooze:[{type:0,value:"Snooze for "},{type:8,value:"min",children:[{type:0,value:"10 minutes"}]},{type:0,value:", "},{type:8,value:"hour",children:[{type:0,value:"1 hour"}]},{type:0,value:" or "},{type:8,value:"day",children:[{type:0,value:"1 day"}]}]},Ff={loginPlease:[{type:8,value:"login",children:[{type:0,value:"Log in"}]},{type:0,value:" bij "},{type:1,value:"productName"},{type:0,value:"."}],snooze:[{type:0,value:"Snooze voor "},{type:8,value:"min",children:[{type:0,value:"10 minuten"}]},{type:0,value:", "},{type:8,value:"hour",children:[{type:0,value:"1 uur"}]},{type:0,value:" of "},{type:8,value:"day",children:[{type:0,value:"1 dag"}]}]};var tu={root:"dd-uTPjX",anchor:"dd-C8lsZ",anchorButton:"dd-IoSx9"};var Nt=require("react/jsx-runtime"),Vi=(t,e,n)=>o=>(0,Nt.jsx)("button",{className:t.anchorButton,type:"button",value:e,onClick:n,children:o},e),Hf=({className:t,loginUrl:e,isEmbedded:n,onSnooze:o,onLogIn:r})=>{let s=R(Wi),i=me(),a=S("Login",tu),d=k("productName"),l=(0,pt.useCallback)(g=>{g.preventDefault(),o&&o(Number.parseInt(g.target.value,10))},[]),c=(0,pt.useCallback)(g=>{g.preventDefault(),i.send(Pn,!0)},[e]),p=(0,pt.useMemo)(()=>g=>(0,Nt.jsx)("a",{onClick:T=>{T.preventDefault(),r()},href:e,className:a.anchor,target:"_blank",rel:"noreferrer",children:g},"login"),[e]),u=(0,pt.useCallback)(g=>(0,Nt.jsx)("button",{type:"button",className:a.anchorButton,onClick:c,children:g},"prompt"),[c]),{min:f,hour:h,day:m}=(0,pt.useMemo)(()=>({min:Vi(a,600,l),hour:Vi(a,3600,l),day:Vi(a,3600*12,l)}),[]);return(0,Nt.jsxs)("div",{className:(0,nu.default)(t,a.root),children:[s("loginPlease",{login:n?u:p,productName:d}),o&&(0,Nt.jsxs)(pt.Fragment,{children:[(0,Nt.jsx)("br",{}),s("snooze",{min:f,hour:h,day:m})]})]})},gs=Hf;var ru=require("react-redux");var ou={root:"dd-DoQhb",text:"dd-Jwnev"};var Ho=require("react/jsx-runtime"),Bf=({title:t})=>{let e=S("SearchTrigger",ou),n=(0,ru.useDispatch)(),o=V();return(0,Ho.jsxs)("button",{type:"button",className:e.root,onClick:()=>{n(Oe(!0)),o("open search",{via:"autocomplete-overlay"})},children:[(0,Ho.jsx)(Fn,{}),(0,Ho.jsx)("span",{className:e.text,children:t})]})},su=Bf;var ji={};Y(ji,{enUS:()=>Uf,nlNL:()=>Kf});var Uf={arrowHint:[{type:0,value:"Tip: use arrow keys to navigate suggestions"}],searchHintWindows:[{type:0,value:"Press CTRL+"},{type:1,value:"searchTriggerKey"},{type:0,value:" to search"}],searchHintMac:[{type:0,value:"Press CMD+"},{type:1,value:"searchTriggerKey"},{type:0,value:" to search"}],open:[{type:0,value:"Open "},{type:1,value:"productName"}],collapse:[{type:0,value:"Close"}],search:[{type:0,value:"Search"}],dismiss:[{type:0,value:"Dismiss"}],dismissError:[{type:0,value:"Dismiss error"}]},Kf={arrowHint:[{type:0,value:"Tip: Selecteer suggesties met pijltoetsen"}],searchHintWindows:[{type:0,value:"Druk CTRL+"},{type:1,value:"searchTriggerKey"},{type:0,value:" om te zoeken"}],searchHintMac:[{type:0,value:"Druk CMD+"},{type:1,value:"searchTriggerKey"},{type:0,value:" om te zoeken"}],open:[{type:0,value:"Open "},{type:1,value:"productName"}],collapse:[{type:0,value:"Sluiten"}],search:[{type:0,value:"Zoeken"}],dismiss:[{type:0,value:"Sluiten"}],dismissError:[{type:0,value:"Foutmelding sluiten"}]};var iu={root:"dd-oa7Vc",isInline:"dd-bwk31",toggleButton:"dd-MSB8Z",toggleButtonWrapper:"dd-ZkCzT",toggleButtonWrapperHidden:"dd-Sq66c",isCollapsed:"dd-vkrPk",collapsible:"dd-CWQJe",hints:"dd-IOoo3",hintsHidden:"dd-psVuT",triggers:"dd-toIoo",triggersRight:"dd-mc4l2",loginError:"dd-KCXeb",loginErrorMessage:"dd-Bv-BG",loginErrorDismiss:"dd-iSCjU"};var K=require("react/jsx-runtime"),zf=({onLogIn:t})=>{let e=S("SuggestionsOverlay",iu),n=R(ji),o=(0,Ue.useSelector)(qe),r=(0,Ue.useSelector)(pl),s=(0,Ue.useDispatch)(),i=(0,Un.useRef)(null),a=k("searchTriggerKey"),d=k("productName"),l=(0,Ue.useSelector)(ds),c=(0,Ue.useSelector)(ne),p=(0,Ue.useSelector)(Ya),u=(0,Ue.useSelector)(bn),[f,h]=(0,Un.useState)(null),m=k("showSearch"),g=k("showTextSuggestions"),b=k("adminUrl"),T=k("isEmbedded"),C=k("suggestionsPlacement"),[w,L]=Yc("dd-snooze-until-ms",0),N=l||w>Date.now(),B=(0,Ue.useSelector)(Wt),X=(0,Ue.useSelector)(to),Le=B.filter(W=>W.source!=="gpt").length,Ce=()=>{N&&L(0),s(Fc(!N))},_=W=>{let Ye=Date.now()+W*1e3;L(Ye),E.info(`Snooze until: ${new Date(Ye)}`),s(Lt({collapse:!0}))};return(0,Un.useEffect)(()=>{Le===0&&h(null)},[B,Le]),Rt(()=>{s(Lt({collapse:!0,skipWhenInputFocus:!0}))}),c===null||u===!1?null:c===!1?(0,K.jsxs)("div",{ref:i,className:(0,ms.default)(e.root,{[e.isCollapsed]:N}),children:[!N&&(0,K.jsxs)("div",{className:e.triggers,children:[(0,K.jsx)("div",{style:{flex:1}}),(0,K.jsx)("div",{className:e.triggersRight,children:(0,K.jsx)(Bt,{className:e.toggleButton,title:n("collapse"),onClick:Ce,isCollapsed:!1})})]}),(0,K.jsx)("div",{className:e.toggleButtonWrapper,children:(0,K.jsx)(Bt,{className:e.toggleButton,title:n("open",{productName:d}),onClick:Ce,isCollapsed:!0})}),(0,K.jsxs)("div",{className:e.collapsible,children:[p&&(0,K.jsxs)("div",{className:e.loginError,children:[(0,K.jsx)("span",{className:e.loginErrorMessage,children:p}),(0,K.jsx)("button",{type:"button",className:e.loginErrorDismiss,onClick:()=>s(ar()),"aria-label":n("dismissError"),children:n("dismiss")})]}),(0,K.jsx)(gs,{loginUrl:b,isEmbedded:T,onLogIn:t,onSnooze:_})]})]}):!r||!o?null:(0,K.jsxs)("div",{ref:i,className:(0,ms.default)(e.root,{[e.isCollapsed]:N}),children:[!N&&(0,K.jsxs)("div",{className:e.triggers,children:[(0,K.jsx)("div",{style:{flex:1},children:m&&(0,K.jsx)("div",{style:{display:"inline-block"},onFocus:()=>{},onMouseOver:()=>h(n(eu()?"searchHintMac":"searchHintWindows",{searchTriggerKey:a.toUpperCase()})),onMouseLeave:()=>h(null),children:(0,K.jsx)(su,{title:n("search")})})}),(0,K.jsxs)("div",{className:e.triggersRight,onFocus:()=>{},children:[(0,K.jsx)("div",{className:(0,ms.default)(!f&&e.hintsHidden,e.hints),children:f}),(0,K.jsx)(Bt,{className:e.toggleButton,title:n("collapse"),onClick:Ce,isCollapsed:!1})]})]}),(0,K.jsx)("div",{className:e.toggleButtonWrapper,children:(0,K.jsx)(Bt,{className:e.toggleButton,title:n("open",{productName:d}),onClick:Ce,isCollapsed:!0})}),Le>0&&g&&(0,K.jsx)("div",{className:e.collapsible,onFocus:()=>{},children:(0,K.jsx)(ae,{children:(0,K.jsx)(us,{suggestions:B,selectedIndex:X,reverse:C==="above"})})})]})},au=zf;var Rs=O(require("classnames")),ku=require("interweave"),ft=require("react"),Ru=require("react-redux");var Kn=require("react");function fs(t){return t.contentEditable==="true"}function Wf(t){let e=0,n=0,o=window.getSelection();if(o.rangeCount!==0){let r=o.getRangeAt(0),s=r.cloneRange();s.selectNodeContents(t),s.setEnd(r.endContainer,r.endOffset),n=s.toString().length,s.selectNodeContents(t),s.setEnd(r.startContainer,r.startOffset),e=s.toString().length}return{selectionStart:e,selectionEnd:n}}function lu(t){let{selectionStart:e,selectionEnd:n}=fs(t)?Wf(t):t;return[e,n]}function du(t){let[,e]=(0,Kn.useState)(),n=(0,Kn.useRef)(null);return n.current=lu(t),(0,Kn.useEffect)(()=>{let o=()=>{var a;let[r,s]=(a=n.current)!=null?a:[],i=lu(t);(!i||r!==i[0]||s!==i[1])&&(n.current=i,e({}))};return t.addEventListener("keyup",o),t.addEventListener("click",o),t.addEventListener("focus",o),document.addEventListener("selectionchange",o),()=>{t.removeEventListener("keyup",o),t.removeEventListener("click",o),t.removeEventListener("focus",o),document.removeEventListener("selectionchange",o)}},[t]),n.current}function cu(t,e){if(!e)return;let n=t,{value:o}=n,[r,s]=e,i=o.match(sr);if(!i||i.length===0)return;let a=0;i.find(d=>{let l=o.indexOf(d,a);return r>l&&s<l+d.length?(n.selectionStart=l,n.selectionEnd=l+d.length,!0):(a=l+d.length,!1)})}var uu=require("react"),Vf=["div","span","mark","strong","b","i","u","em"];function $i(t,e,n=0){var s;let o=t[t.length-1],r=typeof o=="object"&&o!==null?(s=o.props)==null?void 0:s.tagName:void 0;if(r==="br")return t.pop(),[...t,...e,o];if(Vf.includes(r)){let i=Array.isArray(o.props.children)?o.props.children:[o.props.children];return[...t.slice(0,t.length-1),(0,uu.cloneElement)(o,{children:$i(i,e,n+1)})]}return[...t,...e]}function ln(t){return t.tagName.toLowerCase()==="textarea"}var pu={root:"dd-7-cgW",container:"dd-PsRQ8",agentText:"dd-qnW-V",tabText:"dd-cUHUr",hint:"dd-v7fSg",matchSelection:"dd-8cr8y",focus:"dd-3tr9l",resetIndent:"dd-TvQfZ",matchKeyword:"dd-oJkRD",matchPlaceholder:"dd-QvNoo",hover:"dd--wi0R",hintText:"dd-7gQQh",popover:"dd-xbRu-",popoverRoot:"dd-rA2x8",popoverContentContainer:"dd-JHICl",popoverContent:"dd--mfkC",selectionOptions:"dd-p52wn",selectionOptionsIsHidden:"dd-sSTDp",selectionOptionsButton:"dd-Q6kRY",caret:"dd-jIhc8",popoverSuggestionsRoot:"dd-iFDbL",suggestionsOverlayInputStyles:"dd-zzENA"};var yu=O(require("classnames")),vu=require("interweave"),bs=require("react");var zn=require("react");function gu(t,e){let n;return[(...o)=>{window.cancelAnimationFrame(n);let r=e?e(...o):o;n=window.requestAnimationFrame(()=>{t(...r)})},()=>window.cancelAnimationFrame(n)]}function hs(t){let e=(0,zn.useRef)(null),[n,o]=(0,zn.useState)(!1);return(0,zn.useEffect)(()=>{var c;let r=!1,s=Number.parseFloat((c=window.getComputedStyle(document.body).zoom)!=null?c:"1"),[i,a]=gu((p,u)=>{let f=e.current;if(!f)return;let h=p/s,m=u/s,g=f.getBoundingClientRect(),b=h>g.x&&h<g.x+g.width&&m>g.y&&m<g.y+g.height;b&&!r?(r=!0,o(!0)):!b&&r&&(r=!1,o(!1))},({clientX:p,clientY:u})=>[p,u]),[d,l]=gu(()=>{r=!1,o(!1)});return t.addEventListener("mousemove",i),t.addEventListener("mouseleave",d),()=>{a(),l(),t.removeEventListener("mousemove",i),t.removeEventListener("mouseleave",d)}},[e]),[e,n]}function mu(t){return t.replace(/[.*+^${}()|[\]\\]/g,"\\$&")}function ys(t){return e=>{t.forEach(n=>{typeof n=="function"?n(e):n!=null&&(n.current=e)})}}function fu(t){return t!=null}var hu=O(require("classnames")),vs=require("react");var gt={root:"dd-7-cgW",container:"dd-PsRQ8",agentText:"dd-qnW-V",tabText:"dd-cUHUr",hint:"dd-v7fSg",matchSelection:"dd-8cr8y",focus:"dd-3tr9l",resetIndent:"dd-TvQfZ",matchKeyword:"dd-oJkRD",matchPlaceholder:"dd-QvNoo",hover:"dd--wi0R",hintText:"dd-7gQQh",popover:"dd-xbRu-",popoverRoot:"dd-rA2x8",popoverContentContainer:"dd-JHICl",popoverContent:"dd--mfkC",selectionOptions:"dd-p52wn",selectionOptionsIsHidden:"dd-sSTDp",selectionOptionsButton:"dd-Q6kRY",caret:"dd-jIhc8",popoverSuggestionsRoot:"dd-iFDbL",suggestionsOverlayInputStyles:"dd-zzENA"};var Gi=require("react/jsx-runtime"),xs=(0,vs.forwardRef)((r,o)=>{var s=r,{className:t,children:e}=s,n=M(s,["className","children"]);let i=(0,vs.useRef)(null),a=S("TabCompletion",gt);return(0,Gi.jsx)("div",x(y({ref:ys([i,o]),className:(0,hu.default)(t,a.popoverContentContainer)},n),{children:(0,Gi.jsx)("div",{className:a.popoverContent,children:e})}))});var Ot=require("react/jsx-runtime"),jf=t=>e=>{let n=Si(e);return"top"in n&&(n.width=t.width-(e.left-t.left)-10),n},$f=({inputElement:t,boundaryRef:e,inputStyle:n,children:o,suggestion:r})=>{let s=S("TabCompletion",gt),i=Fr(),a=(0,bs.useMemo)(()=>jf(t.getBoundingClientRect()),[t]),[d,l]=hs(t);return(0,bs.useEffect)(()=>{l?i.open():i.close()},[l]),(0,Ot.jsxs)("span",{children:[(0,Ot.jsx)("mark",{ref:ys([d,i.triggerRef]),className:(0,yu.default)(s.matchKeyword,{[s.hover]:l}),"aria-haspopup":"dialog","aria-expanded":i.opened?"true":"false",children:o}),i.opened&&(0,Ot.jsx)(An,{className:s.popover,triggerRef:i.triggerRef,boundaryRef:e,position:"below",align:"start",toStyle:a,children:(0,Ot.jsx)(xs,{style:n,children:(0,Ot.jsx)("div",{className:s.hintText,children:r})})})]})},Ss=class extends vu.Matcher{constructor(){super(...arguments);this.keywordMatches=[];this.preparedKeywordMatches=[];this.usedKeywordMatches=new Set}onBeforeParse(n,o){return o.keywordMatches&&o.keywordMatches!==this.keywordMatches&&(this.preparedKeywordMatches=o.keywordMatches.map(r=>x(y({},r),{keywordRegex:new RegExp(`\\b${mu(r.keyword)}\\b`,"i")})),this.keywordMatches=o.keywordMatches),this.usedKeywordMatches.clear(),n}match(n){let o=this.preparedKeywordMatches.map(s=>{if(this.usedKeywordMatches.has(s))return null;let i=n.match(s.keywordRegex);if(!i)return null;let a=n.charAt(i.index-1),d=n.charAt(i.index+s.keyword.length);return a==="{"&&d==="}"?null:{index:i.index,length:i[0].length,match:i[0],matchString:i[0],suggestion:s.suggestion,preparedKeywordMatch:s,valid:!0}}).filter(fu);if(o.length===0)return null;let r=o.reduce((s,i)=>i.index<s.index?i:s);return this.usedKeywordMatches.add(r.preparedKeywordMatch),r}replaceWith(n,o){return(0,Ot.jsx)($f,{inputElement:o.inputElement,suggestion:o.suggestion,inputStyle:o.inputStyle,boundaryRef:o.boundaryRef,children:n},`keyword_${o.matchString}_${o.key}`)}asTag(){return"mark"}};var xu=require("interweave"),Su=O(require("classnames"));var qi=require("react/jsx-runtime"),Gf=({inputElement:t,children:e})=>{let n=S("TabCompletion",gt),[o,r]=hs(t);return(0,qi.jsx)("mark",{ref:o,className:(0,Su.default)(n.matchPlaceholder,{[n.hover]:r}),children:e})},Cs=class extends xu.Matcher{match(e){let n=e.match(/(((\$!\{)|(\{))[a-zA-Z0-9_.]+\}(?!\}))/);return n?{index:n.index,length:n[0].length,match:n[0],matchString:n[0],valid:!0}:null}replaceWith(e,n){return(0,qi.jsx)(Gf,{inputElement:n.inputElement,children:e},`placeholder_${n.matchString}_${n.key}`)}asTag(){return"mark"}};var ws=O(require("classnames")),Eu=require("interweave"),ce=require("react"),ks=require("react-redux");var Xi=require("react/jsx-runtime"),bu=()=>(0,Xi.jsx)("svg",{width:"1.3em",height:"1.3em",focusable:"false","aria-hidden":"true",viewBox:"0 0 24 24","data-testid":"InsertLinkIcon",tabIndex:-1,children:(0,Xi.jsx)("path",{fill:"currentColor",d:"M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76 0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71 0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71 0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76 0 5-2.24 5-5s-2.24-5-5-5z"})});var Xe=require("react"),Bo=require("react-redux"),Tu=O(require("lodash.debounce"));var Cu={root:"dd-ky-Bv",content:"dd-kV5e1"};function Ts(t,e,n){var r;let o=((r=t.imageSizes)==null?void 0:r[e])||t.image||n;if(!o)return null;try{return new URL(o).toString()}catch(s){return null}}function Ji(t){return t.replace("https://www.","").replace("https://","")}var Pe=require("react/jsx-runtime"),qf=3,Xf=t=>({image:t.image||"",text:t.text,id:t.id,title:t.title}),Jf=({onSelectLink:t,onDismiss:e,placeholder:n,visitUrlText:o,linkCount:r=qf})=>{let s=S("LinkSearch",Cu),[i,a]=(0,Xe.useState)(""),d=(0,Bo.useDispatch)(),l=(0,Bo.useSelector)(yc("url")),c=(0,Bo.useSelector)(_l("URL")),p=(0,Xe.useMemo)(()=>c.map(Xf),[c]),[u,f]=(0,Xe.useState)(p.length-1),h=k("fallbackImage"),m=C=>{let w=C.target;a(w.value)},g=(C,w)=>{C.stopPropagation(),C.preventDefault(),window.open(w,"_blank")},b=C=>{var N;let w=u-1<0?p.length-1:u-1,L=u+1===p.length?0:u+1;C.code==="Escape"&&(a(""),e()),C.code==="ArrowUp"&&f(w),C.code==="ArrowDown"&&f(L),C.code==="Enter"&&t(((N=p[u])==null?void 0:N.text)||i)},T=(0,Xe.useCallback)((0,Tu.default)(C=>{d(Gt({query:C,type:"URL",tags:["link-search"]}))},300),[]);return(0,Xe.useEffect)(()=>{i&&T(i)},[i]),(0,Xe.useEffect)(()=>()=>{d(hr())},[]),(0,Pe.jsxs)("div",{className:s.root,children:[(0,Pe.jsx)(ae,{withDivider:!0,children:(i?p:l).slice(0,r).map((C,w)=>(0,Pe.jsx)(I,{selected:u===w,onClick:()=>t(C.text),"data-testid":"linksearch-suggestion",children:(0,Pe.jsxs)(F,{children:[(0,Pe.jsx)(F.Image,{src:Ts(C,"small",h||void 0),title:C.title||C.text}),(0,Pe.jsxs)(F.Content,{className:s.content,cropText:!0,children:[(0,Pe.jsx)(F.Title,{children:C.title||Ji(C.text)}),C.title&&Ji(C.text)]}),(0,Pe.jsx)(I.Actions,{children:(0,Pe.jsx)(I.ActionButton,{label:o,onClick:L=>g(L,C.text)})})]})},C.text))}),(0,Pe.jsx)(xo,{value:i,onChange:m,autoFocus:!0,placeholder:n,onKeyUp:b})]})},wu=Jf;var Qi={};Y(Qi,{enUS:()=>Qf,nlNL:()=>Zf});var Qf={insertLink:[{type:0,value:"Insert link"}],linkInputPlaceholder:[{type:0,value:"Search, type or paste link"}],visitUrl:[{type:0,value:"Visit"}],addToPersonalCollection:[{type:0,value:"Add to Personal Collection"}]},Zf={insertLink:[{type:0,value:"Voeg link toe"}],linkInputPlaceholder:[{type:0,value:"Zoek, typ of plak link"}],visitUrl:[{type:0,value:"Bekijk"}],addToPersonalCollection:[{type:0,value:"Toevoegen aan Personal Collection"}]};var oe=require("react/jsx-runtime"),Yf=(0,ce.forwardRef)((t,e)=>{let n=S("TabCompletion",gt);return(0,oe.jsx)("mark",{ref:e,className:(0,ws.default)(n.matchSelection)},"selection-start")}),eh=({startRef:t,boundaryRef:e,inputStyle:n,inputElement:o,children:r})=>{let s=R(Qi),i=S("TabCompletion",gt),a=k("addToPersonalCollection"),d=(0,ks.useSelector)(kt("/admin/personal-collection/new")),l=(0,ce.useRef)(null),c=(0,ce.useRef)(null),[p,u]=(0,ce.useState)(null),f=(0,ks.useDispatch)(),h=Fr(document.activeElement===o),[m]=(0,ce.useState)(()=>document.createRange());h.triggerRef.current=m,(0,ce.useEffect)(()=>()=>m.detach(),[]),(0,ce.useEffect)(()=>{let b=t.current,T=l.current;!b||!T||(m.setStart(b,0),m.setEnd(T,0))},[t.current,l.current]),Rt(()=>{h.close()});let g=(0,ce.useCallback)(b=>{let T=m.toString(),C=/^http(s?):\/\//.test(b)?b:`https://${b}`,w=`[${T}](${C})`;f(ye({text:w,suggestion:{text:w,source:"search-url",type:"url"},eventMetrics:{inputType:"mouse"},replace:"selection"}))},[]);return(0,oe.jsxs)("span",{children:[(0,oe.jsx)("mark",{ref:l,className:(0,ws.default)(i.matchSelection),"aria-haspopup":"dialog","aria-expanded":h.opened?"true":"false",children:r}),h.opened&&(0,oe.jsx)(An,{className:i.popoverRoot,triggerRef:h.triggerRef,boundaryRef:e,position:"above",align:"start",children:(0,oe.jsxs)(xs,{style:n,ref:c,children:[(0,oe.jsxs)("div",{className:(0,ws.default)(i.selectionOptions,{[i.selectionOptionsIsHidden]:p!==null}),children:[(0,oe.jsxs)("button",{type:"button",tabIndex:p===null?-1:void 0,className:i.selectionOptionsButton,onClick:()=>u("insertLink"),children:[(0,oe.jsx)(bu,{}),(0,oe.jsx)("span",{children:"\xA0"}),(0,oe.jsx)("span",{children:s("insertLink")})]}),a&&d&&(0,oe.jsx)("button",{type:"button",tabIndex:p===null?-1:void 0,className:i.selectionOptionsButton,onClick:()=>{let b=m.toString(),T=`${d}?text=${encodeURIComponent(b)}`;window.open(T,"_blank")},children:(0,oe.jsx)("span",{children:s("addToPersonalCollection")})})]}),p==="insertLink"&&(0,oe.jsx)(wu,{placeholder:s("linkInputPlaceholder"),visitUrlText:s("visitUrl"),onSelectLink:g,onDismiss:()=>{u(null),h.close()}})]})})]},"selection-end")},Es=class extends Eu.Matcher{constructor(){super(...arguments);this.charCount=0;this.foundIndex=0;this.startRef=null}onBeforeParse(n,o){return this.props=o,this.charCount=0,this.startRef=(0,ce.createRef)(),this.foundIndex=0,n}match(n){if(!this.props||this.props.selection===null||this.foundIndex===2)return null;let[o,r]=this.props.selection;if(o===r)return null;let s=this.foundIndex===0?o:r,i=s>=this.charCount&&s<=this.charCount+n.length?{index:s-this.charCount,length:0,match:"",valid:!0}:null;i&&this.foundIndex++;let a=this.foundIndex===1;return i&&a?this.charCount+=s-this.charCount:this.charCount+=n.length,i?y({isStart:a},i):null}replaceWith(n,o){return o.isStart?(0,oe.jsx)(Yf,{ref:this.startRef}):(0,oe.jsx)(eh,{inputElement:o.inputElement,startRef:this.startRef,boundaryRef:o.boundaryRef,inputStyle:o.inputStyle})}asTag(){return"mark"}};var Pu=require("react-redux");var mt=require("react/jsx-runtime"),th=({enabled:t,content:e,tabText:n,showTabHint:o,showTabCompletion:r,showStyleSuggestions:s,keywordMatches:i,inputElement:a,source:d})=>{let l=S("TabCompletion",pu),c=k("insertLink"),p=k("addToPersonalCollection"),u=k("showMidSentenceSuggestions"),f=k("inlineSuggestions"),h=du(a),m=(0,ft.useRef)(null),g=(0,Pu.useSelector)(ne);(0,ft.useEffect)(()=>{ln(a)&&h&&cu(a,h)},[h]);let b=(0,ft.useCallback)(w=>{if(!r||!n)return w;let L=[(0,mt.jsx)("span",{className:l.resetIndent,children:"\u200B"},"u200B"),(0,mt.jsx)("span",{"data-testid":"tab-completion",className:(0,Rs.default)(l.tabText,l.resetIndent),"data-source":d,children:n},"tabText")];return o&&L.push((0,mt.jsx)("span",{className:(0,Rs.default)(l.hint,l.resetIndent),children:(0,mt.jsx)(nr,{keyCode:"tab"},"tabHint")},"tabHint")),$i(w,L)},[r,n,o]),T=(0,ft.useMemo)(()=>{let w=[];return(c||p)&&w.push(new Es("selection")),w.push(new Cs("placeholders")),s&&w.push(new Ss("keywords")),w},[f,c,p,s]),C=(0,ft.useMemo)(()=>{let w=window.getComputedStyle(a);return{"--dd-color":w.color,"--dd-font-size":w.fontSize,"--dd-font-family":w.fontFamily,"--dd-font-variant":w.fontVariant}},[]);return!t||!g?null:(0,mt.jsxs)("div",{ref:w=>{w!=null&&w.parentElement&&(m.current=w==null?void 0:w.parentElement)},className:l.root,style:C,children:[(0,mt.jsx)(ku.Interweave,{tagName:"span",containerTagName:"div",className:(0,Rs.default)(l.container,l.agentText),disableLineBreaks:ln(a),content:e||"\u200B",onAfterParse:b,matchers:T,selection:h,keywordMatches:i,inputElement:a,inputStyle:C,boundaryRef:m,inlineSuggestionsOnlyAtEnd:!u}),(0,mt.jsx)("br",{})]},"tab-completion")},nh=t=>{var g,b,T;let{input:e,ui:n,settings:o,styleSuggestions:r,conversation:s}=t,i=Tn({input:e}),a=(i==null?void 0:i.text)||"",d=(i==null?void 0:i.source)||"",l=(g=e.html)!=null?g:Dn(e.text),c=a.indexOf(e.text)===0?a.slice(e.text.length):"",{showTabHint:p}=n,{isSupported:u}=s,{showTabCompletion:f,visible:h,showStyleSuggestions:m}=o;return{showTabHint:p,showStyleSuggestions:m,showTabCompletion:f&&qe(t),content:l,tabText:c,source:d,keywordMatches:(T=(b=r.list)==null?void 0:b.keywordMatches)!=null?T:[],enabled:h&&u!==!1}},Iu=(0,Ru.connect)(nh)(th);var Dt=require("react"),q=require("react-redux");var Uo=require("@reduxjs/toolkit");var oh={token:null,interval:null},Zi=(0,Uo.createAsyncThunk)("passwordlessToken/getTemporaryPasswordlessToken",(t,e)=>v(null,null,function*(){let{deepdeskAPI:n}=e.extra;return{token:yield n.requestPasswordlessToken()}})),Yi=(0,Uo.createAsyncThunk)("passwordlessToken/pollPasswordlessToken",(t={},e)=>{let{interval:n=1e3*60*10}=t,{dispatch:o}=e;return o(Zi()),setInterval(()=>o(Zi()),n)}),Lu=(0,Uo.createSlice)({name:"passwordlessToken",initialState:oh,reducers:{stopPollPasswordlessToken(t){t.interval&&clearInterval(t.interval),t.interval=null}},extraReducers:t=>{t.addCase(Zi.fulfilled,(e,n)=>{e.token=n.payload.token}),t.addCase(Yi.fulfilled,(e,n)=>{e.interval=n.payload})}}),{stopPollPasswordlessToken:Au}=Lu.actions,Mu=Lu.reducer;var Nu=require("@reduxjs/toolkit");function rh(t){return"buttonText"in t&&"eventName"in t}function Ou(t){if(t)return rh(t)?{label:t.buttonText,event:t.eventName,value:t.payload}:t}function sh(t){return t==null?void 0:t.map(e=>Ou(e))}function ih(t){let e=0;for(let n=0;n<t.length;n++)e=(e<<5)-e+t.charCodeAt(n),e|=0;return e}var Du=(0,Nu.createSelector)([ed],t=>t.map(n=>{let o=Ou(n.callToAction),r=sh(n.callToActions);return x(y(y(y({text:n.response,title:n.name},o?{callToAction:o}:{}),r!=null&&r.length?{callToActions:r}:{}),n.message!==void 0?{message:n.message}:{}),{editable:n.editable,isLoading:n.isLoading,evaluationId:n.evaluationId,rule:{id:ih(n.code),label:n.code,name:n.name,description:n.name}})}));var Ps=require("react"),ta=O(require("classnames"));var ea=require("react/jsx-runtime"),Wn=()=>(0,ea.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",children:(0,ea.jsx)("path",{d:"M502.6 70.63l-61.25-61.25C435.4 3.371 427.2 0 418.7 0H255.1c-35.35 0-64 28.66-64 64l.0195 256C192 355.4 220.7 384 256 384h192c35.2 0 64-28.8 64-64V93.25C512 84.77 508.6 76.63 502.6 70.63zM464 320c0 8.836-7.164 16-16 16H255.1c-8.838 0-16-7.164-16-16L239.1 64.13c0-8.836 7.164-16 16-16h128L384 96c0 17.67 14.33 32 32 32h47.1V320zM272 448c0 8.836-7.164 16-16 16H63.1c-8.838 0-16-7.164-16-16L47.98 192.1c0-8.836 7.164-16 16-16H160V128H63.99c-35.35 0-64 28.65-64 64l.0098 256C.002 483.3 28.66 512 64 512h192c35.2 0 64-28.8 64-64v-32h-47.1L272 448z"})});var _u={root:"dd-WcEru",entity:"dd-LfP8y",entityText:"dd-L-v0f",iconWrapper:"dd-9Deh1",icon:"dd-tM7E2",iconClicked:"dd-EEdDL"};var Je=require("react/jsx-runtime"),ah=({entities:t})=>{let e=S("EntitiesWidgetList",_u),[n,o]=(0,Ps.useState)(void 0),r=V(),s=()=>{o(void 0)},i=a=>{t&&(o(t.indexOf(a)),Ve(a.text),r("entity copied",{entity:a,type:"copy"}))};return(0,Ps.useEffect)(()=>{let a=setTimeout(s,500);return()=>{clearTimeout(a)}},[n]),!t||t.length===0?null:(0,Je.jsx)("div",{className:e.root,"data-testid":"widget-entities-list",children:t.map((a,d)=>(0,Je.jsxs)("button",{title:a.text,className:e.entity,type:"button",onClick:()=>i(a),children:[(0,Je.jsx)("span",{className:e.entityText,children:a.text}),(0,Je.jsxs)("span",{className:e.iconWrapper,children:[(0,Je.jsx)("span",{className:(0,ta.default)(e.icon),children:(0,Je.jsx)(Wn,{})}),(0,Je.jsx)("span",{className:(0,ta.default)(e.icon,n===d&&e.iconClicked),children:(0,Je.jsx)(Wn,{})})]})]},a.text))})},Fu=ah;var na=require("react/jsx-runtime"),Hu=()=>(0,na.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,na.jsx)("path",{d:"M17 13.5v6H5v-12h6m3-3h6v6m0-6-9 9",stroke:"currentColor",strokeWidth:"1.5",fill:"none",fillRule:"evenodd",strokeLinecap:"round",strokeLinejoin:"round"})});var ju=require("react"),$u=require("react-redux");var Bu={root:"dd-ohnXe",trigger:"dd-7i-S3",button:"dd-t53Cg",nav:"dd-qZFnm",item:"dd-FZC0F"};var Uu={root:"dd-nazq3",rotation:"dd-3EHTv"};var zu=require("react/jsx-runtime"),lh=({size:t=12})=>{let e=S("LoadingSpinner",Uu);return(0,zu.jsx)("span",{"data-testid":"loading-spinner",style:{width:`${t}px`,height:`${t}px`},className:e.root})},Ku=lh;var oa=require("react/jsx-runtime"),Wu=()=>(0,oa.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 0 512 512",fill:"currentColor",children:(0,oa.jsx)("path",{d:"M256 32c14.2 0 27.3 7.5 34.5 19.8l216 368c7.3 12.4 7.3 27.7 .2 40.1S486.3 480 472 480H40c-14.3 0-27.6-7.7-34.7-20.1s-7-27.8 .2-40.1l216-368C228.7 39.5 241.8 32 256 32zm0 128c-13.3 0-24 10.7-24 24V296c0 13.3 10.7 24 24 24s24-10.7 24-24V184c0-13.3-10.7-24-24-24zm32 224c0-17.7-14.3-32-32-32s-32 14.3-32 32s14.3 32 32 32s32-14.3 32-32z"})});var Ko=require("react/jsx-runtime"),Vu=t=>(0,Ko.jsxs)("svg",x(y({xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 448 512","aria-labelledby":"checkTitle"},t),{children:[(0,Ko.jsx)("title",{id:"checkTitle",children:"Check"}),(0,Ko.jsx)("path",{fill:"#666",d:"M438.6 105.4c12.5 12.5 12.5 32.8 0 45.3l-256 256c-12.5 12.5-32.8 12.5-45.3 0l-128-128c-12.5-12.5-12.5-32.8 0-45.3s32.8-12.5 45.3 0L160 338.7 393.4 105.4c12.5-12.5 32.8-12.5 45.3 0z"})]}));var ra={};Y(ra,{enUS:()=>dh,nlNL:()=>ch});var dh={error:[{type:0,value:"Something went wrong"}]},ch={error:[{type:0,value:"Er ging iets fout"}]};var be=require("react/jsx-runtime"),uh=3e3,ph=({assistantOptions:t})=>{let e=S("OnDemandAssistants",Bu),n=R(ra),o=(0,ju.useRef)(),r=Sr(We),s=(0,$u.useSelector)(zd),i=V(),a=s.filter(c=>c.isPinned),d=s.filter(c=>!c.isPinned),l=c=>v(null,null,function*(){clearTimeout(o.current),i("trigger on demand assistant",{assistantCode:c}),yield r.call(x(y({},t),{assistantCode:c})),o.current=setTimeout(()=>r.reset(),uh)});return s.length===0?null:(0,be.jsxs)("div",{className:e.root,children:[a.map(({assistant:c,assistantName:p,displayName:u})=>(0,be.jsx)("button",{type:"button",className:e.button,disabled:r.state==="loading",onClick:()=>l(c),children:u||p},c)),d.length>0&&(0,be.jsxs)(ee,{placement:"top-end",children:[(0,be.jsx)(ee.Trigger,{className:e.trigger,disabled:r.state==="loading",children:(0,be.jsx)(ns,{"data-testid":"trigger"})}),(0,be.jsx)(ee.Content,{className:e.nav,"data-testid":"popover",children:d.map(({assistant:c,assistantName:p,displayName:u})=>(0,be.jsx)(ee.Button,{className:e.item,disabled:r.state==="loading",onClick:()=>l(c),children:u||p},c))})]}),r.state==="loading"&&(0,be.jsx)(Ku,{}),r.state==="done"&&(0,be.jsx)(Vu,{"data-testid":"trigger-done"}),r.state==="error"&&(0,be.jsx)(Rd,{trigger:(0,be.jsx)(Wu,{}),children:n("error")})]})},Gu=ph;var Xu=require("react-redux");var zo={};Y(zo,{enUS:()=>gh,nlNL:()=>mh});var gh={useCue:[{type:0,value:"Add to message"}],__summarizerAssistant__:[{type:0,value:"Summary"}],copyCue:[{type:0,value:"Copy"}],removeCue:[{type:0,value:"Close"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}]},mh={useCue:[{type:0,value:"Voeg toe aan bericht"}],__summarizerAssistant__:[{type:0,value:"Samenvatting"}],copyCue:[{type:0,value:"Kopi\xEBren"}],removeCue:[{type:0,value:"Sluiten"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}]};var dn=require("react");var sa={title:"dd-YBHrC",fadeup:"dd-cRM0K",fadedown:"dd-7D4Pq",selected:"dd-bueui",actions:"dd-9Iqn9",ctaMessage:"dd-ge8nB",thumbsUp:"dd-6QwVx",thumbsDown:"dd-d3E8l",form:"dd-sPNU2",formInput:"dd-F3E4I",formSubmit:"dd-vw5S0",actionButton:"dd-cCWyJ",editableCue:"dd-nWSD-",inputSpace:"dd-DGYB1"};var re=require("react/jsx-runtime"),fh=500,hh=100,yh=({content:t,onChange:e,onCopy:n})=>{let o=(0,dn.useRef)(null),r=S("WidgetCue",sa);return(0,dn.useEffect)(()=>{let s=o.current;if(!s)return;s.style.setProperty("height","0px");let i=Math.min(Math.max(s.scrollHeight,hh),fh);s.style.setProperty("height",`${i}px`)},[t]),(0,re.jsx)("textarea",{ref:o,className:r.editableCue,onCopy:n,onChange:e,value:t})},vh=({cue:t,onCallToAction:e,onRemove:n,onCopy:o,onUse:r})=>{var m;let s=S("WidgetCue",sa),i=R(zo),a=V(),d=k("hasKeyboardInput"),[l,c]=(0,dn.useState)(t.text),p=g=>{let b=g?x(y({},t),{callToAction:g}):t;e&&e(l,b),n(t)},u=(g,b)=>{o&&o(g,t),b&&Et(b,s.fadeup)},f=g=>{r&&r(g,t)},h=g=>{g.preventDefault(),g.stopPropagation(),n(t)};return(0,dn.useEffect)(()=>{a("Assistant response displayed",{evaluationId:t.evaluationId,assistantCode:t.rule.label,assistantOutput:t.text})},[]),(0,re.jsxs)(I,{"data-testid":"cue",children:[(0,re.jsx)(F,{children:(0,re.jsxs)(F.Content,{children:[t.title&&(0,re.jsx)(F.Title,{className:s.title,"data-testid":"widget-cue-title",children:t.rule.label.startsWith("__")?i(t.rule.label):t.title}),t.message&&(0,re.jsx)("p",{className:s.ctaMessage,children:t.message}),t.editable?(0,re.jsx)(yh,{content:l,onCopy:()=>{let g=document.getSelection();g&&u(g.toString())},onChange:g=>{var b;return c((b=g.target.value)!=null?b:"")}}):(0,re.jsx)(Qt,{content:t.text,useLabel:i("useCue"),copyLabel:i("copyCue"),onCopy:u,onUse:d?f:void 0})]})}),(0,re.jsxs)(I.ButtonsContainer,{children:[(0,re.jsxs)("div",{className:s.actions,children:[(0,re.jsx)(I.Button,{onClick:g=>{var b;return u((b=Ir(l,"reply")[0])!=null?b:l,g.target)},variant:"primary",children:i("copyCue")}),t.callToAction&&(0,re.jsx)(I.Button,{onClick:()=>p(),variant:"primary",children:t.callToAction.label}),(m=t.callToActions)==null?void 0:m.map((g,b)=>(0,re.jsx)(I.Button,{onClick:()=>p(g),variant:"primary",children:g.label},`${g.event}-${g.label}-${b}`)),(0,re.jsx)(I.Button,{onClick:h,variant:"secondary",children:i("removeCue")})]}),(0,re.jsx)(Or,{evaluationId:t.evaluationId,assistantCode:t.rule.label,assistantOutput:t.text,feedbackText:t.text,feedbackType:"assistant"})]})]})},qu=vh;var Vn=require("react/jsx-runtime"),xh=({cues:t})=>{let e=(0,Xu.useDispatch)(),n=me(),o=R(zo),r=V(),s=l=>{e(Ar({code:l.rule.label})),r("Assistant response closed",{evaluationId:l.evaluationId,assistantCode:l.rule.label,assistantOutput:l.text})},i=(l,c)=>{Ve(l),r("Assistant response copied",{evaluationId:c.evaluationId,assistantCode:c.rule.label,assistantOutput:c.text,copiedText:l})},a=(l,c)=>{var p;c.callToAction&&(e(Lr(c)),r("Assistant call to action",{evaluationId:c.evaluationId,assistantCode:c.rule.label,assistantOutput:c.text,eventName:c.callToAction.event,value:(p=c.callToAction.value)!=null?p:l}))},d=(l,c)=>{var p;n.send(nt,{text:l,suggestion:{source:"assistant",assistantCode:(p=c.rule)==null?void 0:p.label,sourceText:l}}),r("Assistant response used",{evaluationId:c.evaluationId,assistantCode:c.rule.label,assistantOutput:c.text,usedText:l})};return(0,Vn.jsx)(Vn.Fragment,{children:t.map(l=>l.isLoading?(0,Vn.jsx)(Br,{title:l.rule.label.startsWith("__")?o(l.rule.label):l.title},l.rule.id):(0,Vn.jsx)(qu,{cue:l,onCallToAction:a,onRemove:s,onCopy:i,onUse:d},l.evaluationId))})},Ju=xh;var Is=require("react");var Qu={root:"dd-cvTAY",label:"dd-QWQxD",value:"dd-WSUHF",copyButton:"dd-67o9H",copyButtonText:"dd-oos-l",isTrue:"dd--1g2O",isFalse:"dd-sz2ir"};var he=require("react/jsx-runtime");function Sh(t,e){return e.split(".").reduce((n,o)=>!n||typeof n!="object"||!(o in n)?null:n[o],t)}var Zu=({data:t,schema:e})=>{let n=S("WidgetCustomData",Qu),o=r=>{Ve(r)};return(0,Is.useEffect)(()=>{E.info("Custom data",t,e)},[t]),(0,he.jsx)("dl",{className:n.root,children:e.map(r=>{let s=Sh(t,r.path);return(0,he.jsxs)(Is.Fragment,{children:[(0,he.jsx)("dt",{className:n.label,children:r.label}),(0,he.jsx)("dd",{className:n.value,children:r.type==="boolean"&&s?(0,he.jsx)("span",{className:n.isTrue,children:r.trueValue}):r.type==="boolean"&&!s?(0,he.jsx)("span",{className:n.isFalse,children:r.falseValue}):r.type==="array"&&Array.isArray(s)&&s.length>0?(0,he.jsxs)("button",{type:"button",onClick:()=>o(s.join(", ")),className:n.copyButton,children:[(0,he.jsx)("span",{className:n.copyButtonText,children:s.join(", ")}),(0,he.jsx)(Wn,{})]}):typeof s=="string"||typeof s=="number"?(0,he.jsxs)("button",{type:"button",onClick:()=>o(`${s}`),className:n.copyButton,children:[(0,he.jsx)("span",{className:n.copyButtonText,children:s}),(0,he.jsx)(Wn,{})]}):"-"})]},r.label)})})};var ep=require("react");var bh=/(https?:\/\/[^\s]+)/,Yu=t=>t.split(" ").find(e=>bh.test(e));var Ie=require("react/jsx-runtime"),Ch=({suggestion:t,lines:e,onUse:n})=>{var p;let o=t.text||t.url||t.message,r=Yu(o),s=R(Io),i=k("showImages"),a=k("fallbackImage"),d=k("hasKeyboardInput"),l=u=>{u.preventDefault(),u.stopPropagation(),d&&n(o)},c=(0,ep.useCallback)(u=>{window.open(r,"_blank"),u.stopPropagation(),u.preventDefault()},[r]);return(0,Ie.jsxs)(I,{onClick:d?l:void 0,"data-testid":"edit-suggestion",children:[(0,Ie.jsxs)(F,{children:[i&&t.image&&(0,Ie.jsx)(F.Image,{src:Ts(t,"small",a||void 0),title:t.title}),(0,Ie.jsxs)(F.Content,{children:[t.title&&(0,Ie.jsx)(F.Title,{"data-testid":"widget-suggestion-title",children:t.title}),t.searchKeywords&&((p=t.searchKeywords)==null?void 0:p.length)>0&&(0,Ie.jsx)(I.Labels,{labels:t.searchKeywords}),(0,Ie.jsx)(F.Content,{cropText:e==="single",lineClamp:e==="multiple",children:o})]})]}),(0,Ie.jsxs)(I.Actions,{children:[r&&(0,Ie.jsx)(I.ActionButton,{onClick:c,label:s("visitUrl")}),d&&(0,Ie.jsx)(I.ActionButton,{primary:!0,onClick:l,label:s("useSuggestion")})]})]})},tp=Ch;var Wo=require("react/jsx-runtime"),Th=({lines:t,suggestions:e})=>{let n=me(),o=(r,s)=>{n.send(nt,{text:r,suggestion:x(y({},s),{source:s.source,sourceText:s.text})})};return(0,Wo.jsx)(Wo.Fragment,{children:e.map(r=>(0,Wo.jsx)(tp,{suggestion:r,lines:t,onUse:s=>o(s,r)},r.text||r.url||r.message))})},np=Th;var Vo={};Y(Vo,{enUS:()=>wh,nlNL:()=>Eh});var wh={waiting:[{type:0,value:"Loading\u2026"}],waitingForConversation:[{type:0,value:"Waiting for conversation\u2026"}],notSupported:[{type:0,value:"This conversation is not supported"}],noResults:[{type:0,value:"No results found\u2026"}],titleCues:[{type:0,value:"Assistant updates"}],actions:[{type:0,value:"Shortcuts"}],linkStudioLogin:[{type:0,value:"My "},{type:1,value:"productName"}],linkSummary:[{type:0,value:"Summarize"}],linkKnowledgeSearch:[{type:0,value:"Knowledge Assist"}],linkSearch:[{type:0,value:"Search"}],close:[{type:0,value:"Close"}]},Eh={waiting:[{type:0,value:"Laden\u2026"}],waitingForConversation:[{type:0,value:"Wachten op gesprek\u2026"}],notSupported:[{type:0,value:"Dit gesprek wordt niet ondersteund"}],noResults:[{type:0,value:"Geen resultaten gevonden\u2026"}],titleCues:[{type:0,value:"Assistant updates"}],actions:[{type:0,value:"Shortcuts"}],linkStudioLogin:[{type:0,value:"Mijn "},{type:1,value:"productName"}],linkSummary:[{type:0,value:"Gesprek samenvatten"}],linkKnowledgeSearch:[{type:0,value:"Knowledge assist"}],linkSearch:[{type:0,value:"Zoeken"}],close:[{type:0,value:"Sluiten"}]};var jn={root:"dd-W9VCG",loginText:"dd--dS6t",stateText:"dd-348OC",footer:"dd-tvofr",shortcutList:"dd-MuKK-",shortcut:"dd-5CnK9",footerShortcut:"dd-dH7XJ",link:"dd-DRo0x"};var P=require("react/jsx-runtime"),op=(t,e)=>{let n=(0,q.useSelector)(ne);(0,Dt.useEffect)(()=>n?e.every(o=>!!o)?t():()=>{}:()=>{},[...e,n])},kh=({onLogIn:t})=>{let e=S("Widget",jn),n=k("isEmbedded"),o=k("adminUrl");return(0,P.jsx)("div",{className:e.loginText,children:(0,P.jsx)("div",{children:(0,P.jsx)(gs,{isEmbedded:n,loginUrl:o,onLogIn:t})})},"login")},ia=({text:t})=>{let e=S("Widget",jn);return(0,P.jsx)("div",{className:e.stateText,children:(0,P.jsx)("div",{children:(0,P.jsx)("p",{children:t})})},"notification")},Rh=()=>{let t=R(Vo),e=(0,q.useDispatch)(),n=S("Widget",jn),o=k("showSearch"),r=k("isEmbedded"),s=(0,q.useSelector)(kt("/admin/")),i=me(),a=k("productName"),d=V();return op(()=>{if(r)return e(Yi()),()=>{e(Au())}},[e,r]),!o&&!s?null:(0,P.jsxs)("div",{className:n.shortcutList,children:[o&&(0,P.jsx)(I.Button,{"data-testid":"shortcut-search","aria-label":t("linkSearch"),className:n.shortcut,icon:(0,P.jsx)(Fn,{}),onClick:()=>{i.send("ShowCommandPalette",{isOpen:!0}),d("open search",{via:"widget-shortcut"})},children:t("linkSearch")}),s&&(0,P.jsx)(I.Button,{as:"a",target:"_blank",icon:(0,P.jsx)(Hu,{}),href:s,"data-testid":"shortcut-studio-login","aria-label":t("linkStudioLogin",{productName:a}),className:n.shortcut,rel:"noreferrer",onClick:()=>{d("open my deepdesk",{via:"widget-shortcut"})},children:t("linkStudioLogin",{productName:a})})]})},Ph=({title:t,content:e})=>{let n=R(Vo),[o,r]=(0,Dt.useState)(!0);return o?(0,P.jsx)(Ke,{"data-testid":"custom-data-banner",type:"custom-data-banner",title:t,children:(0,P.jsx)(ae,{withDivider:!0,children:(0,P.jsxs)(I,{children:[(0,P.jsx)(F,{children:(0,P.jsx)(F.Content,{children:(0,P.jsx)(Qt,{content:e})})}),(0,P.jsx)(I.ButtonsContainer,{children:(0,P.jsx)(I.Button,{onClick:()=>r(!1),children:n("close")})})]})})}):null},Ih=()=>{let t=(0,q.useDispatch)(),e=(0,q.useSelector)(Co),n=(0,q.useSelector)(Vd),o=(0,q.useSelector)(Du),r=(0,q.useSelector)(El),s=(0,q.useSelector)(es),i=(0,q.useSelector)(ss),a=(0,q.useSelector)(Yt),d=(0,q.useSelector)(ze);return(0,Dt.useEffect)(()=>{r&&!n&&E.warn("Custom data provided, but no schema.")},[r,n]),op(()=>{e.forEach(({type:l})=>{l==="entities"?t(He()):ir.includes(l)||t(Be(l))})},[t,d,a]),(0,Dt.useEffect)(()=>{o.length>0&&!e.some(l=>l.type==="cues")&&E.warn("Received cues, but cues are not configured in widget.")},[e,o]),(0,P.jsx)(Dt.Fragment,{children:e.map(({type:l,title:c,amount:p,lines:u,schema:f,property:h})=>{var m,g;switch(l){case"entities":return s&&s.length>0&&(0,P.jsx)(Ke,{type:l,title:c,"data-testid":`type-${l}`,children:(0,P.jsx)(Fu,{entities:s})},l);case"cues":return o&&o.length>0&&(0,P.jsx)(Ke,{type:l,title:c,"data-testid":`type-${l}`,children:(0,P.jsx)(ae,{withDivider:!0,children:(0,P.jsx)(Ju,{cues:o})})},l);case"custom-data-banner":return r&&h&&r[h]&&(0,P.jsx)(Ph,{title:c,content:String(r[h])},l);case"custom-data":return r&&f&&(0,P.jsx)(Ke,{type:l,title:c,"data-testid":`type-${l}`,children:(0,P.jsx)(ae,{withDivider:!0,children:(0,P.jsx)(Zu,{data:r,schema:f})})},l);default:return((g=(m=i[l])==null?void 0:m.suggestions)==null?void 0:g.length)>0&&(0,P.jsx)(Ke,{type:l,title:c,"data-testid":`type-${l}`,children:(0,P.jsx)(ae,{withDivider:!0,children:(0,P.jsx)(np,{lines:u,contentType:l,suggestions:i[l].suggestions.slice(0,p)||[]})})},l)}})})},aa=({children:t})=>{let e=S("Widget",jn);return(0,P.jsx)("div",{className:e.footer,children:t})},la=({children:t})=>{let e=S("Widget",jn);return(0,P.jsx)("div",{className:e.root,"data-testid":"widget",children:t})},Lh=({onLogIn:t,knowledgeAssistOptions:e={},assistantOptions:n={transcript:"in-memory-transcript"}})=>{let o=R(Vo),r=(0,q.useSelector)(bn),s=(0,q.useSelector)(ne),i=(0,q.useSelector)(ll),a=(0,q.useSelector)(Yt),d=(0,q.useSelector)(Wd("knowledge-assist")),l=(0,q.useSelector)(jd);return r===!1?(0,P.jsx)(ia,{text:o("notSupported")}):s===!1?(0,P.jsx)(kh,{onLogIn:t}):s===null?(0,P.jsx)(ia,{text:o("waiting")}):!i||!a?(0,P.jsx)(ia,{text:o("waitingForConversation")}):(0,P.jsx)(la,{children:(0,P.jsxs)(Vr,{initialQuestion:e.initialQuestion,assistantCode:l!=null?l:void 0,evaluateKnowledgeAssistFn:yo,children:[(0,P.jsxs)(yn,{children:[(0,P.jsx)(Rh,{}),(0,P.jsx)(Ih,{}),d&&(0,P.jsx)($r,{title:d.title,emptyState:e.emptyState})]}),(0,P.jsxs)(aa,{children:[d&&(0,P.jsx)(jr,{}),(0,P.jsx)(Gu,{assistantOptions:n})]})]})})},rp=Lh;function $n(t){let e=new Range;return e.selectNodeContents(t),e}function sp(t,e,n){try{return _t(t,e,n),!0}catch(o){return!1}}function Ls(t){return"tagName"in t&&(t.tagName==="DIV"||t.tagName==="P")}function As(t){return"tagName"in t&&t.tagName==="BR"}var jo=/[\u200B-\u200D\uFEFF]/g;function _t(t,e,n){let o=new Range;if(t.firstChild===null&&e===0&&n===0)return o.selectNodeContents(t),o;let r=0,s=!1;function i(d,l){let c=-1,p=/[\u200B-\u200D\uFEFF]/;if(!p.test(d))return l;for(let u=0;u<=d.length;u++)if(p.test(d[u])||c++,c===l)return u;throw new Error("Offset out of range")}function a(d){switch(d.nodeType){case Node.TEXT_NODE:{let l=d.textContent,c=l.replace(jo,""),p=r+c.length,u=e>=r&&e<=p,f=n>=r&&n<=p;if(u){let h=i(l,e-r);h===0&&!f?o.setStartBefore(d):o.setStart(d,h)}f&&(o.setEnd(d,i(l,n-r)),s=!0),r=p;break}case Node.ELEMENT_NODE:{if(As(d)&&(r===e&&o.setStartBefore(d),r++,r===n)){o.setEndAfter(d),s=!0;return}for(let c=0;c<d.childNodes.length&&(a(d.childNodes[c]),!s);c++);let l=d.lastChild;Ls(d)&&l&&!Ls(l)&&!As(l)&&r++;break}default:break}}if(a(t),o.startContainer===document)throw new Error("Offsets out of bound");return o}function $o(t,e){if(!t.contains(e.startContainer)||!t.contains(e.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:o,endContainer:r,endOffset:s,collapsed:i}=e,a,d,l=0;function c(p){let u=p===t,f=p===n,h=p===r;switch(p.nodeType){case Node.TEXT_NODE:{let m=p.textContent;f&&(a=l+m.substring(0,o).replace(jo,"").length),h&&(d=l+m.substring(0,s).replace(jo,"").length),l+=m.replace(jo,"").length;break}case Node.ELEMENT_NODE:{if(As(p)&&p.nextSibling){l++;break}!u&&Ls(p)&&p.previousSibling&&l++;for(let m=0;m<p.childNodes.length;m++){let g=f&&m===o,b=h&&m===s;if(g&&(a=l),b&&(d=l),d!==void 0||((!g||!i)&&c(p.childNodes[m]),h&&m===s-1&&(d=l),d!==void 0))break}h&&(d=l);break}default:break}}if(c(t),d===void 0)throw new Error("Could not determine start and end");return{start:a!=null?a:d,end:d}}function Go(t,e){if(!t.contains(e.startContainer)||!t.contains(e.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:o,endContainer:r,endOffset:s,collapsed:i}=e,a=0,d="";function l(c){let p=c===t,u=c===n,f=c===r;switch(u&&(a=1),c.nodeType){case Node.TEXT_NODE:{if(a!==1)return;let h=u?o:0,m=f?s:void 0;d+=c.textContent.replace(jo,"").substring(h,m);break}case Node.ELEMENT_NODE:{if(!i&&a===1&&As(c)&&c.nextSibling){d+=`
9
9
  `;break}!p&&!i&&a===1&&Ls(c)&&c.previousSibling&&(d+=`
10
- `);let h=u?o:0,m=f?Math.min(s,c.childNodes.length):c.childNodes.length;for(let g=h;g<m&&(l(c.childNodes[g]),a!==2);g++);break}default:break}f&&(a=2)}return l(t),d}var ip=(i=>(i.CUT="Cut",i.BACKSPACE="Backspace",i.DELETE="Delete",i.ERASEEOF="EraseEof",i.UNDO="Undo",i.CLEAR="Clear",i))(ip||{}),ht=class{constructor(e){this.element=e;this.isFocused=!1;this.isActive=!0;this.isDisposed=!1;this.eventListeners={};this.disposeHandlers=[];this.cachedText="";this.cachedCaretPosition=null;this.cachedSelection={start:0,end:0};this.cachedHTML="";this.isSubmitting=!1;this.isPossibleClearInputAction=!1;this.cachedText=this.getText(),this.cachedHTML=this.getHTML(),this.cachedSelection=this.getSelection(),this.listen()}addEventListener(e,n){let o=r=>{n(r)};this.element.addEventListener(e,o),this.disposeHandlers.push(()=>{this.element.removeEventListener(e,o)})}removeEventListener(e,n){this.element.removeEventListener(e,n)}handleInteraction(){let e=this.getText(),n=this.getHTML(),o=this.getSelection(),r=this.cachedCaretPosition===null;if(!this.isActive||(e===""&&this.cachedText!==""&&!this.isPossibleClearInputAction&&this.emit("submit"),e!==this.cachedText?(this.cachedText=e,this.cachedHTML=n,r=!0,this.emit("change",{plainText:e,rawHTML:n})):n!==null&&n!==this.cachedHTML&&(this.cachedHTML=n,r=!0,this.emit("change",{plainText:e,rawHTML:n})),(o.start!==this.cachedSelection.start||o.end!==this.cachedSelection.end)&&(this.cachedSelection=o,r=!0,this.emit("selection",o)),!r))return;let s=this.getCaretPosition();Ct(s,this.cachedCaretPosition)||(this.cachedCaretPosition=s,this.emit("caretposition",s))}handleClick(){this.handleInteraction()}handleFocus(){let e=!this.isFocused;this.isFocused=!0,e&&this.emit("focus"),this.handleInteraction()}handleBlur(){this.isPossibleClearInputAction=!1;let e=this.isFocused;this.isFocused=!1,e&&this.emit("blur")}handleKeyDown(e){let{key:n,ctrlKey:o,metaKey:r}=e;this.isPossibleClearInputAction=Object.values(ip).includes(n)||n.toLowerCase()==="z"&&(o||r),this.emit("keydown",e)}handleKeyUp(e){this.handleInteraction(),this.emit("keyup",e)}handleCut(){this.isPossibleClearInputAction=!0,this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(e){var o,r;let n=((o=e.clipboardData)==null?void 0:o.getData("text"))||((r=e.clipboardData)==null?void 0:r.getData("text/plain"))||"";this.emit("paste",{pastedText:n,selectionText:this.getSelectedText()})}listen(){this.addEventListener("keydown",n=>this.handleKeyDown(n)),this.addEventListener("keyup",n=>this.handleKeyUp(n)),this.addEventListener("input",()=>this.handleInteraction()),this.addEventListener("change",()=>this.handleInteraction()),this.addEventListener("focus",()=>this.handleFocus()),this.addEventListener("blur",()=>this.handleBlur()),this.addEventListener("cut",()=>this.handleCut()),this.addEventListener("paste",n=>this.handlePaste(n)),this.addEventListener("click",()=>this.handleInteraction()),document.activeElement===this.element&&(this.isFocused=!0);let e=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});e.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{e.disconnect()})}focus(){this.element.focus()}emit(e,...n){this.isDisposed||this.eventListeners[e]&&this.eventListeners[e].forEach(o=>{o(...n)})}on(e,n){this.isDisposed||(this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(n))}off(e,n){if(!this.eventListeners[e])return;let o=this.eventListeners[e].indexOf(n);o!==-1&&this.eventListeners[e].splice(o,1)}activate(){let e=this.isActive===!1;this.isActive=!0,e&&this.handleInteraction()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(e=>e()),this.eventListeners={},this.isDisposed=!0}};function ap(t){return t.top!==0||t.left!==0||t.height!==0||t.width!==0}var cn=class extends ht{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),Go(this.element,n)}getHTML(){return this.element.innerHTML||""}getRange(){let n=this.getRootNode();if(n.activeElement!==this.element)return null;let o="getSelection"in n?n.getSelection():window.getSelection();if(!o)return null;let r=o.rangeCount>0?o.getRangeAt(0):null;if(!r)return null;let s=this.element.ownerDocument.createRange();return s.setStart(r==null?void 0:r.startContainer,r==null?void 0:r.startOffset),s.setEnd(r==null?void 0:r.endContainer,r==null?void 0:r.endOffset),!s||!this.element.contains(s.startContainer)||!this.element.contains(s.endContainer)?null:s}getCaretPosition(){let n=this.getRange();if(!n||!n.collapsed||!("getBoundingClientRect"in n))return null;let o=n.getBoundingClientRect();return!ap(o)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),o=n.getBoundingClientRect(),n.deleteContents(),!ap(o))?null:{top:o.top+o.height,left:o.left}}getSelection(){let n=this.getRange();if(n)return $o(this.element,n);let o=this.lastKnownSelection;if(o&&sp(this.element,o.start,o.end))return o;let r=$n(this.element);return r.collapse(!1),$o(this.element,r)}getSelectedText(){let{start:n,end:o}=this.getSelection();return Go(this.element,_t(this.element,n,o))}listen(){super.listen();let n=new MutationObserver(s=>{var i,a;s.length===2&&s[0].addedNodes.length===1&&((i=s[0].addedNodes[0])==null?void 0:i.textContent)==="\u2060"&&((a=s[1].removedNodes[0])==null?void 0:a.textContent)==="\u2060"||setTimeout(()=>{this.handleInteraction()},0)});n.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0}),this.disposeHandlers.push(()=>n.disconnect());let o=this.element.isContentEditable,r=new MutationObserver(()=>{this.element.isContentEditable!==o&&(o=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});r.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>r.disconnect())}};var Ah=["direction","boxSizing","width","height","overflowX","overflowY","borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth","borderStyle","paddingTop","paddingRight","paddingBottom","paddingLeft","fontStyle","fontVariant","fontWeight","fontStretch","fontSize","fontSizeAdjust","lineHeight","fontFamily","textAlign","textTransform","textIndent","textDecoration","letterSpacing","wordSpacing","tabSize"];function lp(t,e){let n="mozInnerScreenX"in window,o=document.createElement("div");o.id="input-textarea-caret-position-mirror-div";let r=o.style,s=window.getComputedStyle(t),i=t.ownerDocument.body;r.whiteSpace="pre-wrap",r.wordWrap="break-word",r.position="absolute",r.visibility="hidden",Ah.forEach(c=>{r[c]=s[c]}),n?t.scrollHeight>Number.parseInt(s.height)&&(r.overflowY="scroll"):r.overflow="hidden",o.textContent=t.value.substring(0,e);let a=document.createElement("span");a.textContent=t.value.substring(e)||".",o.appendChild(a),i.appendChild(o);let d=t.getBoundingClientRect(),l={top:d.top-t.scrollTop+a.offsetTop+Number.parseInt(s.borderTopWidth)+a.offsetHeight,left:d.left-t.scrollLeft+a.offsetLeft+Number.parseInt(s.borderLeftWidth)};return i.removeChild(o),l}var un=class extends ht{constructor(){super(...arguments);this.lastKnownSelection=null}getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:n,selectionEnd:o}=this.element;return{start:n,end:o}}getSelectedText(){let n=this.getSelection();return n?this.getText().slice(n.start,n.end):""}getCaretPosition(){return lp(this.element,this.element.selectionEnd)}listen(){super.listen();let n=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var s;return(s=n==null?void 0:n.get)==null?void 0:s.call(this.element)},set:s=>{var i;(i=n==null?void 0:n.set)==null||i.call(this.element,s),this.handleInteraction()}}),this.addEventListener("scroll",()=>{this.emit("caretposition",this.getCaretPosition())});let o=this.element.disabled,r=new MutationObserver(()=>{this.element.disabled!==o&&(o=this.element.disabled,this.emit(o?"disabled":"enabled"))});r.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>r.disconnect())}};function dp(t,e,n){let o=`deepdesk-iframe-${t}`,r=document.getElementById(o);if(r)return r;let s=document.createElement("iframe"),i=new URL(e);return Object.entries(n).forEach(([a,d])=>{i.searchParams.append(a,d)}),s.style.position="absolute",s.style.left="-999em",s.style.width="0px",s.style.height="0px",s.tabIndex=-1,s.id=o,s.title=`iframe-${t}`,s.src=i.toString(),window.document.body.appendChild(s),s}function Mh(t){if(typeof t!="string")return t;try{return JSON.parse(t)}catch(e){return t}}var da=class{constructor(e){this.name=e;this.disposeHandlers=[];this.broadcastChannel=new BroadcastChannel(e)}onMessage(e){this.broadcastChannel.addEventListener("message",e),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",e)})}postMessage(e){this.broadcastChannel.postMessage(JSON.stringify(e))}close(){this.disposeHandlers.forEach(e=>e()),this.broadcastChannel.close()}},ca=class{constructor(e,n,o){this.name=e;this.targetOrigin=n;this.options=o;this.disposeHandlers=[];this.iframe=dp(e,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}onMessage(e){window.addEventListener("message",e),this.disposeHandlers.push(()=>{window.removeEventListener("message",e)})}postMessage(e){var n;(n=this.iframe.contentWindow)==null||n.postMessage(JSON.stringify(e),this.targetOrigin)}close(){var e;this.disposeHandlers.forEach(n=>n()),(e=this.iframe)==null||e.remove()}},ua=class{constructor(e){this.params=e;this.deepdeskUrl=e.deepdeskUrl,this.eventMap=e.eventMap,this.externalId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setExternalId(e){this.externalId!==e&&(this.cleanup(),E.info("Set externalId",e),this.externalId=e,this.channel=this.createChannel(e))}createChannel(e){let n=this.params.createCustomChannel?this.params.createCustomChannel(e):this.isCrossOrigin?new ca(e,this.deepdeskUrl,{debug:!0}):new da(e),o=r=>{var i,a;if(r.origin!==this.deepdeskUrl)return;let s=Mh(r.data);typeof s!="object"||s.type!=="event"||s.channel!==e||(E.info("Received broadcast event",this.externalId,r),(a=(i=this.eventMap)[s.name])==null||a.call(i,s.payload))};return n.onMessage(o),n}send(e,n,o){var i,a;E.info("Broadcast event",{externalId:this.externalId,name:e,payload:n});let r={type:"event",name:e,payload:n};o!==!1&&((a=(i=this.eventMap)[e])==null||a.call(i,n));let s=this.externalId==="deepdesk-general"?this.defaultChannel:this.channel;s==null||s.postMessage(x(y({},r),{channel:this.externalId}))}cleanup(e=!1){var n,o;(n=this.channel)==null||n.close(),this.channel=void 0,e&&((o=this.defaultChannel)==null||o.close(),this.defaultChannel=void 0)}},cp=ua;function Nh(t){return t.replace(/(_\w)/g,e=>e[1].toUpperCase())}function z(t){return Array.isArray(t)?t.map(z):typeof t=="object"&&t!==null?Object.keys(t).reduce((e,n)=>x(y({},e),{[Nh(n)]:z(t[n])}),{}):t}function Oh(t){return t.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}function ue(t){return Array.isArray(t)?t.map(ue):typeof t=="object"&&t!==null?Object.keys(t).reduce((e,n)=>x(y({},e),{[Oh(n)]:ue(t[n])}),{}):t}var Gn=class extends Error{constructor(n,o){super(n);this.body=o;this.name="CustomError"}};var pa=t=>new Promise(e=>{setTimeout(e,t)});var pn=class extends Gn{constructor(){super(...arguments);this.name="ClientError"}},ma=class extends Gn{constructor(){super(...arguments);this.name="ServerError"}},ga=new Map;function Dh(t){return v(this,null,function*(){if(t.status===204)return t.text().catch(()=>{}),null;let e=t.headers.get("content-type");if(e!=null&&e.includes("application/json"))return t.json();let n=yield t.text();return n===""?null:(E.warn("Unexpected response body:",n.slice(0,20)),JSON.parse(n))})}var gn=class{constructor(e="",n={}){this.baseUrl=e;this.options=n;this.latestRequestByUrl={};this.refreshingToken=null;this.lastFailedRefreshAt=null;this.failedRefreshCooldown=1e4;var o;this.fetch=(o=n.fetch)!=null?o:window.fetch.bind(window)}patchFetch(e){this.fetch=e(this.fetch)}setCsrfToken(e){this.csrfToken=e}request(e,n={}){return new Promise((o,r)=>{let s={isAborted:!1,reject:r},i=`${this.baseUrl}${e}`,a=this.fetch,d=n.method===void 0||n.method.toLowerCase()==="get",N=n,{useCache:l=!1,abortLatest:c=!1,attempts:p=1,retryDelay:u=500,refreshTokenOn401:f=!0,retryOnError:h=B=>B instanceof TypeError,retryOnResponse:m=B=>B.status>=500,version:g=null}=N,b=M(N,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]);if(l){if(!d)throw new Error(`Can't use 'useCache' for ${n.method}`);if(ga.has(i)){o(ga.get(i));return}}let T=x(y({credentials:"include"},b),{headers:y({Accept:"application/json","Content-Type":"application/json"},b.headers)});!d&&this.csrfToken&&(T.headers=x(y({},T.headers),{"X-CSRFToken":this.csrfToken})),typeof g=="string"&&(T.headers=x(y({},T.headers),{"X-Deepdesk-API-Version":g}));let C=p,w=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[i]&&c&&(this.latestRequestByUrl[i].isAborted=!0,this.latestRequestByUrl[i].reject(new Error("Aborted"))),this.latestRequestByUrl[i]=s;let L=()=>v(this,null,function*(){return C--,a(i,T).then(B=>v(this,null,function*(){return m(B)&&!s.isAborted&&C>0?(yield pa(u),L()):B.status===401&&f===!0&&w===!1?(w=!0,yield this.refreshToken(),L()):B})).catch(B=>v(this,null,function*(){if(h(B)&&!s.isAborted&&C>0)return yield pa(u),L();throw B}))});L().then(B=>v(this,null,function*(){let X=yield Dh(B);if(delete this.latestRequestByUrl[i],B.status>=500){r(new ma("Server Error",X));return}if(B.status===401){r(new pn("Unauthorized",X));return}if(B.status===403){r(new pn("Forbidden",X));return}if(B.status===404){r(new pn("Not Found",X));return}if(B.status>=400){r(new pn("Bad Request",X));return}l&&ga.set(i,X),o(X)})).catch(B=>{r(B)})})}validateToken(){return v(this,null,function*(){let e,n,o;try{({has_valid_access_token:e,is_logged_in:n,has_valid_refresh_token:o}=yield this.get("/apis/admin/session/validate/",{refreshTokenOn401:!1}))}catch(r){return!1}if(!e){if(!o)return!1;try{yield this.refreshToken();let{is_logged_in:r}=yield this.get("/apis/admin/session/validate/",{refreshTokenOn401:!1});return r}catch(r){return!1}}return n})}refreshToken(){let e=Date.now();return this.lastFailedRefreshAt&&e-this.lastFailedRefreshAt<this.failedRefreshCooldown?Promise.reject(new pn("Unauthorized","Failed to refresh token")):this.refreshingToken?this.refreshingToken:(this.refreshingToken=this.get("/apis/admin/session/refresh/",{refreshTokenOn401:!1}).catch(n=>{throw(n==null?void 0:n.message)==="Unauthorized"&&(this.lastFailedRefreshAt=Date.now()),n}).finally(()=>{this.refreshingToken=null}),this.refreshingToken)}get(e,n){return this.request(e,n)}post(e,n,o){return this.request(e,y({method:"POST",body:JSON.stringify(n)},o))}patch(e,n,o){return this.request(e,y({method:"PATCH",body:JSON.stringify(n)},o))}put(e,n,o){return this.request(e,y({method:"PUT",body:JSON.stringify(n)},o))}delete(e,n){return this.request(e,y({method:"DELETE"},n))}};var up;(e=>{let t;(a=>(a.SUCCESS="success",a.FAILURE="failure",a.CONDITIONS_NOT_MET="conditions_not_met",a.MAX_RECURSION_LEVEL="max_recursion_level",a.NO_ACCESS_TO_ASSISTANT="no_access_to_assistant"))(t=e.EvaluationStatus||(e.EvaluationStatus={}))})(up||(up={}));function fa(t){return x(y({},z(t)),{metadata:t.metadata})}var mn=class mn{constructor(e,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new gn(e,{fetch:n.fetch}),this.client.patchFetch(o=>(r,s)=>v(this,null,function*(){let i=yield o(r,s);return this.handleDeepdeskVersionHeaders(i),i}))}preflight(){return v(this,null,function*(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let e=yield this.getCsrfToken();this.client.setCsrfToken(e)}return this.options.token?(mn.exchangeTokenPromise||(mn.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),mn.exchangeTokenPromise):Promise.resolve()})}createConversation(e){return v(this,null,function*(){var o;yield this.preflight(),E.info(`Creating conversation for session ${e.externalId} and agent ${e.agentId}`);let n=yield this.client.post("/api/v2/conversations",x(y({chat_start_time:new Date().toISOString()},ue(e)),{metadata:(o=e.metadata)!=null?o:{}}));return fa(n)})}getMe(){return v(this,null,function*(){let e=yield this.client.get("/apis/admin/session/me/");return z(e)})}postIdentity(e){return v(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/me/identities/",ue(e))})}patchMe(e){return v(this,null,function*(){yield this.preflight();let n=yield this.client.patch("/apis/admin/session/me/",ue(e));return z(n)})}getProfile(e){return v(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${e}/`,{useCache:!0});return z(n)})}getKnowledgeAssistant(e){return v(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${e}/`,{useCache:!0});return z(n)})}getContentTypes(){return v(this,null,function*(){let e=yield this.client.get("/apis/admin/content-types/",{useCache:!0});return z(e)})}getAccount(){return v(this,null,function*(){let e=yield this.client.get("/apis/admin/account/",{useCache:!0});return z(e)})}getPlatformConfig(e){return v(this,null,function*(){let n=e!==void 0?`/platform/config/${e}/`:"/platform/config/",{config:o}=yield this.client.get(n,{useCache:!0});return z(o)})}checkUserExists(e){return v(this,null,function*(){let{exists:n}=yield this.client.get(`/apis/admin/users/exists?external_id=${e}`,{version:"v1"});return n})}getConversationByExternalId(o){return v(this,arguments,function*(e,n={}){yield this.preflight(),E.info(`Getting conversation for session ${e}`);let{attempts:r=1,retryDelay:s=1e3}=n,i=yield this.client.get(`/api/v2/conversations/by_external_id/${e}`,{attempts:r,retryDelay:s,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"});return E.info(`Successfully retrieved conversation ${i.id} for session ${e}`),fa(i)})}isConversationSupported(o){return v(this,arguments,function*(e,n={}){E.info(`Check if conversation for session ${e} is supported`);let{attempts:r=1,retryDelay:s=1e3}=n;return(yield this.client.get(`/api/v2/conversations/by_external_id/${e}/has_active_profile`,{attempts:r,retryDelay:s,retryOnResponse:a=>a.status===404||a.status>=500})).has_active_profile})}updateConversation(e,n){return v(this,null,function*(){var s;yield this.preflight();let o=ue(n);n.metadata&&(o.metadata=(s=n.metadata)!=null?s:{});let r=yield this.client.put(`/api/v2/conversations/${e}`,o);return fa(r)})}postMessages(e,n){return v(this,null,function*(){yield this.preflight(),yield this.client.post(`/api/v2/conversations/${e}/messages`,n.map(o=>x(y({},ue(o)),{metadata:o.metadata})))})}sendEvent(e,n){return v(this,null,function*(){yield this.preflight();let a=n,{data:o}=a,r=M(a,["data"]),s=Object.entries(this.latestReceivedDeepdeskVersions).reduce((d,[l,c])=>x(y({},d),{[l]:c}),{}),i=["platform","agentId","agentName","agentEmail","conversationId"].reduce((d,l)=>(r[l]&&(d[l]=r[l]),d),{});return this.client.post("/api/v2/events",ue(x(y(y({},s),i),{data:o,name:e})),{version:"v2"})})}getEntities(e){return v(this,null,function*(){return yield this.preflight(),yield this.client.post("/api/v2/entities",{messages:e.filter(o=>o.text)})})}getTemporaryExchangeToken(){return v(this,null,function*(){return(yield this.client.get("/apis/admin/session/exchange-token/")).jwt})}exchangeTokenForAccessCookie(e){return v(this,null,function*(){return this.client.post("/apis/admin/session/jwt/",{jwt:e}).catch(n=>{throw E.warn(`Invalid token '${e}'`),n})})}authenticateWithKey(e,n){return v(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/api-key/",ue(n),{refreshTokenOn401:!1,headers:{apikey:e}})})}getTextSuggestions(r){return v(this,arguments,function*(e,n={},o){if(yield this.preflight(),o==="sticky-messages")throw new Error("Use getPinnedMessages instead");return(yield this.client.post(`/api/v2/conversations/${e}/recommend/${o}`,ue(n),{abortLatest:!0})).map(i=>x(y({},z(i)),{text:i.text||i.url||i.message,source:o,type:o})).filter((i,a,d)=>a===d.findIndex(l=>l.text===i.text))})}isLoggedIn(){return v(this,null,function*(){return yield this.preflight(),this.client.validateToken()})}getAutocompleteSuggestions(e,n){return v(this,null,function*(){return yield this.preflight(),(yield this.client.post(`/api/v2/conversations/${e}/autocomplete`,ue(n),{abortLatest:!0})).map(r=>({score:1,source:r.source,sourceText:r.source_text,text:r.label,trainingJobs:r.training_jobs,searchKeywords:r.search_keywords,type:r.source})).filter((r,s,i)=>s===i.findIndex(a=>a.text===r.text))})}getPinnedMessages(e){return v(this,null,function*(){let n=yield this.client.get(`/api/v2/profiles/${e}/pinned-messages`,{abortLatest:!0});return z(n).map(o=>x(y({},o),{text:o.message,source:"sticky-messages",type:"pinned-message"}))})}getStyleSuggestions(e){return v(this,null,function*(){let n=yield this.client.post("/api/v2/style-suggestions",ue(e),{abortLatest:!0,version:"v2"});return z(n)})}search(e){return v(this,null,function*(){let n=yield this.client.post(`/api/v2/profiles/${e.profile}/search`,ue(e));return z(n)})}requestLoginByEmail(e){return v(this,null,function*(){yield this.preflight();let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:e});return z(n)})}requestPasswordlessToken(){return v(this,null,function*(){let e=yield this.client.get("/apis/admin/session/passwordless/request/");return z(e.token)})}getCsrfToken(){return v(this,null,function*(){let{token:e}=yield this.client.get("/apis/admin/session/csrf/");return e})}verifyLoginToken(e){return v(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/login/",{token:e});return z(n)})}evaluateAssistant(e,n){return v(this,null,function*(){var i;yield this.preflight();let o=new URLSearchParams;n!=null&&n.externalConversationId&&o.append("external_conversation_id",n.externalConversationId);let r=n!=null&&n.threadId?`/api/v2/assistants/${e}/threads/${n==null?void 0:n.threadId}/evaluate?${o.toString()}`:`/api/v2/assistants/${e}/evaluate?${o.toString()}`,s=yield this.client.post(r,{input:(i=n==null?void 0:n.input)!=null?i:{},conversation:n==null?void 0:n.transcript});return z(s)})}createAssistantThread(e){return v(this,null,function*(){yield this.preflight();let{assistantCode:n}=e,o=yield this.client.post(`/apis/admin/assistants/${n}/threads/`,{});return z(o)})}postMessageToAssistantThread(e){return v(this,null,function*(){yield this.preflight();let{assistantCode:n,threadId:o,message:r}=e,s=yield this.client.post(`/apis/admin/assistants/${n}/threads/${o}/messages/`,{content:r,role:"user"});return z(s)})}translateMessages(e){return v(this,null,function*(){yield this.preflight();let n=yield this.client.post("/api/v2/translate",ue(e));return z(n)})}handleDeepdeskVersionHeaders(e){e.headers.forEach((n,o)=>{let r=o.toLowerCase(),s=r.match(Xa);if(!n||!s)return;let i=s[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&n&&a!==n&&E.warn(`Overwritten Version header ${r}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[i]=n})}};mn.exchangeTokenPromise=null;var yt=mn;var Ms=class{constructor(e){this.options=e;this.socket=null;this.maxReconnectAttempts=5;this.reconnectInterval=25e3;this.cleanupCallbacks=[];var n,o;this.socket,this.eventListeners=new Map,this.url=e.url,this.maxReconnectAttempts=(n=e.maxReconnectAttempts)!=null?n:this.maxReconnectAttempts,this.reconnectInterval=(o=e.reconnectInterval)!=null?o:this.reconnectInterval,this.shouldReconnect=e.shouldReconnect}connect(){let e=()=>this.cleanup();window.addEventListener("beforeunload",e),this.cleanupCallbacks.push(()=>window.removeEventListener("beforeunload",e)),this.reconnect()}setupListeners(){this.socket&&(this.socket.onmessage=e=>{var n;try{let o=z(JSON.parse(e.data));o.event&&this.eventListeners.has(o.event)&&((n=this.eventListeners.get(o.event))==null||n.forEach(r=>r(o.data)))}catch(o){console.error("Error parsing WebSocket message:",o)}},this.socket.onclose=e=>{console.log("WebSocket connection closed:",e),setTimeout(()=>{this.reconnect()},this.reconnectInterval)},this.socket.onerror=e=>{console.error("WebSocket error:",e)})}reconnect(){var e,n;if(this.maxReconnectAttempts<=0){console.error("Max reconnect attempts reached, closing WebSocket connection."),(e=this.socket)==null||e.close();return}if(!this.shouldReconnect()){console.error("Should not reconnect, closing WebSocket connection."),(n=this.socket)==null||n.close();return}this.socket&&(this.socket.onmessage=null,this.socket.onclose=null,this.socket.onerror=null,this.socket.close()),this.socket=new WebSocket(this.url),this.setupListeners(),this.maxReconnectAttempts--}send(e,n){if(!this.socket){console.error("WebSocket connection is not open.");return}this.socket.send(JSON.stringify({event:e,data:n}))}on(e,n){this.eventListeners.has(e)||this.eventListeners.set(e,[]);let o=this.eventListeners.get(e);o&&!o.includes(n)&&o.push(n)}close(){var e;(e=this.socket)==null||e.close()}cleanup(){this.close(),this.cleanupCallbacks.forEach(e=>e()),this.cleanupCallbacks=[]}};var _s=require("@reduxjs/toolkit");var gp=require("@reduxjs/toolkit");var pp={startTime:null,stopTime:null},mp=t=>t.handlingTime,fp=(0,gp.createSlice)({name:"handlingTime",initialState:pp,reducers:{handlingTimeStart(t){if(t.startTime&&!t.stopTime)throw new Error("Timing already started");t.startTime=new Date,t.stopTime=null},handlingTimeStop(t){if(!t.startTime)throw new Error("Timing not started");t.stopTime=new Date},handlingTimeReset(t){t.startTime=null,t.stopTime=null}},extraReducers:t=>{t.addCase(J,()=>pp)}}),{handlingTimeStart:hp,handlingTimeStop:Ns,handlingTimeReset:yp}=fp.actions,vp=fp.reducer;var xp=(t={})=>{let e=y({onAuthError:Sn(!1)},t);return n=>o=>r=>("error"in r&&r.error.message==="Unauthorized"&&n.dispatch(e.onAuthError),o(r))};var Ds=require("@reduxjs/toolkit");var Os={list:{keywordMatches:[]},fetchState:"idle"};var fn=(0,Ds.createAsyncThunk)("styleSuggestions/getAll",(n,o)=>v(null,[n,o],function*({text:t},e){var d;let{deepdeskAPI:r}=e.extra,s=e.getState(),{showStyleSuggestions:i}=s.settings,a=(d=s.conversation.current)==null?void 0:d.profileCode;if(!i)return Os.list;if(!a)throw new Error("No current conversation to fetch pinned messages");return r.getStyleSuggestions({profileCode:a,message:t})})),_h=(0,Ds.createSlice)({name:"styleSuggestions",initialState:Os,reducers:{},extraReducers:t=>{t.addCase(fn.pending,e=>{e.fetchState="loading"}).addCase(fn.rejected,e=>{e.fetchState="error"}).addCase(fn.fulfilled,(e,n)=>{e.fetchState="done",Ct(e.list,n.payload)||(e.list=n.payload)}).addCase(jt,e=>{e.list=Os.list}).addCase(J,()=>Os)}}),Sp=_h.reducer;var bp=(t={})=>{let e,n=!0,o=y({getStyleSuggestions:fn,debounce:500},t);return r=>s=>i=>{var f;let a=r.getState().input.text,d=s(i),l=r.getState();if(l.auth.isLoggedIn!==!0)return d;let{showStyleSuggestions:c}=l.settings;if(!((f=l.conversation.current)==null?void 0:f.id)||!c)return d;let{text:u}=l.input;return u===a&&!n||(clearTimeout(e),u==="")||(e=setTimeout(()=>{n=!1,r.dispatch(o.getStyleSuggestions({text:u}))},t.debounce)),d}};function Fh(t,e){return t.text===e.text&&t.selection.start===e.selection.start&&t.selection.end===e.selection.end}var Cp=(t={})=>{let e=y({getTextSuggestions:Be,getAutocompleteSuggestions:Ao,debounce:200,check:qe},t),n;return o=>r=>s=>{var m;let{input:i}=o.getState(),a=r(s),d=o.getState();if(d.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:l,showTabCompletion:c}=d.settings,p=(m=d.conversation.current)==null?void 0:m.id,u=s.type===is.toString();if(!p||!l&&!c)return a;let{input:f}=d;return Fh(f,i)&&!u||(clearTimeout(n),!e.check(d))||(n=setTimeout(()=>{let g=Cn(d);g===""?o.dispatch(e.getTextSuggestions("default")):o.dispatch(e.getAutocompleteSuggestions(g))},u?0:e.debounce)),a}};var Tp=fn.fulfilled.toString();function Hh(t,e){let n=new Set([...e.keywordMatches.map(r=>r.keyword)]),o=[];return n.forEach(r=>{let s=t.keywordMatches.filter(d=>d.keyword===r),i=e.keywordMatches.filter(d=>d.keyword===r),a=i.length-s.length;a<=0||o.push(...i.slice(0,a))}),o}var wp=t=>e=>n=>o=>{var l;if(o.type!==Tp){n(o);return}let r=e.getState().styleSuggestions.list;n(o);let s=e.getState(),i=s.styleSuggestions.list,a=(l=s.conversation)==null?void 0:l.current;if(r===i)return;let d=Hh(r,i);o.type===Tp&&d.length>0&&t.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:d}})};var Bh=(0,_s.combineReducers)({assistants:id,auth:ol,conversation:dl,contentTypes:Kd,passwordlessToken:Mu,entities:cc,handlingTime:vp,info:Ml,input:Cl,settings:cd,profile:$d,search:Hl,styleSuggestions:Sp,ui:Hc,textSuggestions:Sc});function Ep(t){return(0,_s.configureStore)({reducer:Bh,middleware:e=>{var o;let n=e({thunk:{extraArgument:{dynamicThunkObject:t.dynamicThunkObject,deepdeskAPI:t.deepdeskAPI}},serializableCheck:!1}).concat(xp()).concat(Cp({debounce:200})).concat(bp({debounce:500})).concat(wp(t.deepdeskAPI));return((o=t.middleware)!=null?o:[]).reduce((r,s)=>r.concat(s),n)},preloadedState:t.preloadedState})}var Uh=t=>{var e,n;return(n=(e=t==null?void 0:t.type)==null?void 0:e.toLowerCase())!=null?n:"unknown"},Kh=t=>e=>n=>o=>{var d,l;let r=e.getState(),s=Xt("inlineSuggestions")(r),i=Xt("autoSelectSuggestion")(r)||s;switch(o.type){case Sn.toString():{!o.payload&&t.emit("logout",void 0);break}case He.fulfilled.toString():o.payload.length>0&&t.sendEvent("entities found",{conversationId:(d=r.conversation.current)==null?void 0:d.id,data:{entities:o.payload}});break;case jt.toString():t.logSendMessage(o.payload);break;case Lr.toString():t.emit("call-to-action",{cue:o.payload});break;case We.fulfilled.toString():o.isBroadcasted||t.broadcast(ni,o,!1);break;default:break}let a=n(o);switch(o.type){case jt.toString():t.handleAfterSendMessage(o.payload);break;case No.toString():t.onUpdateShowTabHint(o.payload);break;case Ns.toString():t.logHandlingTime();break;case wn.toString():t.broadcast(vr,o);break;case Vt.toString():t.broadcast(vr,o);break;case Ar.toString():e.dispatch(Vt({source:"assistant",assistantCode:o.payload.code}));break;case"analytics/logEvent/fulfilled":{let c=r.assistants.cues.find(p=>p.code===o.meta.arg.data.assistantCode);t.emit("event",x(y({},o.meta.arg),{cue:c}));break}case ye.toString():{let{start:c,end:p}=r.input.selection;t.emit("select-suggestion",x(y({type:Uh(o.payload.suggestion)},o.payload),{replace:o.payload.replace==="selection"?{start:c,end:p}:{start:0,end:p}})),s&&e.dispatch(Tt([]));break}case ur.toString():t.emit("select-image",o.payload),t.sendEvent("Image attached",{conversationId:(l=r.conversation.current)==null?void 0:l.id,data:{path:o.payload.suggestion.image,title:o.payload.suggestion.title}});break;case Tt.toString():{i&&o.payload.length>0&&e.dispatch(pr(0));break}default:break}return a},kp=Kh;var Rp=require("@reduxjs/toolkit");function ha(t){return t.toISOString().replace("T"," ").replace("Z","")}var zh=(t,e)=>e.version,Pp=(0,Rp.createSelector)([En,ze,mp,zh],(t,e,n,o)=>{if(!e)return E.warn("No conversationId for handling time metrics"),null;let{startTime:r,stopTime:s}=n;return!r||!s?(E.warn("No startTime and stopTime for handling time metrics"),null):{conversationId:e,clientVersion:o,agentId:t==null?void 0:t.agentId,agentName:t==null?void 0:t.agentName,agentEmail:t==null?void 0:t.agentEmail,timeStart:ha(r),timeStop:ha(s)}});function Ip(t,e){let{text:n,metrics:{numPaste:o,pastes:r,textSuggestions:s}}=t.input,i=n.length;return{source:"agent",clientVersion:e.version,pastes:r,lenTextTotal:i,numPastes:o,suggestions:s}}var qo=class extends Error{};function Wh(){let t,e;return{promise:new Promise((o,r)=>{t=o,e=r}),resolve:t,reject:e}}var Fs=class{constructor(){this.queues={}}push(e,n){let o=()=>{let s=this.queues[e][1];s?(this.queues[e]=[s.promise,null],s.resolve()):delete this.queues[e]};if(!this.queues[e]){let s=n().finally(o);return this.queues[e]=[s,null],s}this.queues[e][1]&&this.queues[e][1].reject(new qo("Queued async function is outdated"));let r=Wh();return this.queues[e][1]=r,r.promise.then(()=>n().finally(o))}};function ya(t,e){var s;let n=t.closest(e);if(n)return n;let o=t.getRootNode().host;if(o instanceof HTMLElement)return ya(o,e);let r=(s=t.ownerDocument.defaultView)==null?void 0:s.frameElement;return r?ya(r,e):null}function va(t,e){return ya(t,e)}var Vh={accepted:"onConversationAcceptedAssistants","new-message":"onConversationNewMessageAssistants",ended:"onConversationEndedAssistants"},Lp=(t,e)=>{var r,s,i;if(!((i=(s=(r=t.uiConfig)==null?void 0:r.widget)==null?void 0:s.types.find(a=>a.type==="cues"))==null?void 0:i.isActive))return E.warn("Triggered a conversation assistant, but cues are not configured in widget."),[];let o=t[Vh[e]];return o&&o.length>0?o.map(a=>a.code):(E.warn(`No assistant set in profile for conversation event "${e}"`),[])};function Ap(t){return typeof t=="object"&&t!==null&&"name"in t&&"message"in t}function jh(t){return typeof t=="object"&&t!==null&&"tagName"in t}function Hs(t){return jh(t)&&(ln(t)||fs(t))}var Np,Qe=new Map,$h=["bottom","height","left","right","top","width"],Mp=(t,e)=>!t&&!e?!1:t&&!e||!t&&e?!0:$h.some(n=>t[n]!==e[n]);function Op(t){var n,o,r;if(t.ownerDocument===document)return[];let e=(r=(o=(n=t.ownerDocument)==null?void 0:n.defaultView)==null?void 0:o.frameElement)!=null?r:null;return e?[e,...Op(e)]:[]}function Dp(t,e){return!t||!e?null:x(y({},t),{top:t.top+e.top,left:t.left+e.left})}var Bs=!1,_p=()=>{Bs=!0;let t=[];if(Qe.forEach((e,n)=>{if(!n.isConnected){e.rect=null,t.push(e),Qe.delete(n);return}let o=n.getBoundingClientRect();Mp(o,e.rect)&&(e.rect=o,t.push(e))}),t.forEach(e=>{let n=e.parentRects?e.parentRects.reduce(Dp,e.rect):e.rect;Mp(n,e.totalRect)&&e.callbacks.forEach(o=>o(n)),e.totalRect=n}),Qe.size===0){Bs=!1;return}Np=window.requestAnimationFrame(_p)};function xa(t,e){let n=Op(t),o=[],r=n.map((s,i)=>xa(s,a=>{o[i]=a;let d=Qe.get(t);if(!d)return;let l=o.reduce(Dp,d.rect);d.callbacks.forEach(c=>c(l))}));return{observe(s=!0){if(r.forEach(i=>i.observe(!1)),Qe.has(t)){let i=Qe.get(t);i.callbacks.push(e),i.rect&&e(i.rect)}else Qe.set(t,{rect:void 0,callbacks:[e],parentRects:o});s&&!Bs&&_p()},unobserve(){r.forEach(i=>i.unobserve());let s=Qe.get(t);if(s){let i=s.callbacks.indexOf(e);i>=0&&s.callbacks.splice(i,1),s.callbacks.length||Qe.delete(t),Qe.size||(cancelAnimationFrame(Np),Bs=!1)}}}}var Fp,Ze=new Map,Hp=()=>{Ze.forEach((t,e)=>{if(!e.isConnected){Ze.delete(e);return}let{clientHeight:n,scrollHeight:o}=e,r=o>n;t.visible!==r&&(t.visible=r,t.callbacks.forEach(s=>s(t.visible)))}),Ze.size!==0&&(Fp=window.requestAnimationFrame(Hp))};function Bp(t,e){return{observe(){let n=Ze.size===0;Ze.has(t)?Ze.get(t).callbacks.push(e):Ze.set(t,{visible:void 0,callbacks:[e]}),n&&Hp()},unobserve(){let n=Ze.get(t);if(n){let o=n.callbacks.indexOf(e);o>=0&&n.callbacks.splice(o,1),n.callbacks.length||Ze.delete(t),Ze.size||cancelAnimationFrame(Fp)}}}}var Sa=["borderLeftWidth","borderRightWidth","borderTopWidth","borderBottomWidth","borderStyle","boxSizing","color","overflowWrap","fontFamily","fontSize","fontSizeAdjust","fontStretch","fontWeight","fontKerning","lineHeight","letterSpacing","paddingLeft","paddingTop","paddingRight","paddingBottom","width","height","textIndent","whiteSpace","wordBreak","wordSpacing","wordWrap"];function ba(t,e,n){return n.forEach(o=>{e.style[o]=t[o]})}function qn(t){return Number.parseFloat(t)}function Us(t){return Math.round(t*1e6)}function Up(t){return t/1e6}function Ca(t,e,n){if(t.boxSizing==="content-box")return;let{clientWidth:o}=e,r=qn(t.width),s=qn(t.borderLeftWidth),i=qn(t.borderRightWidth),a=qn(t.paddingRight),d=Up(Us(r)-Us(s)-Us(i)),l=Up(Us(o));if(d-l>2){let c=d-l;n.style.paddingRight=`${a+c}px`}}function Xo(t,e={}){var c,p;let n=e.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=(c=e.position)!=null?c:"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",Jt(n);let o=window.getComputedStyle(t),r=!0,s=()=>{n.scrollTop=t.scrollTop};ba(o,n,Sa),Ca(o,t,n),e.mirrorOverflow&&(n.style.overflow="hidden",t.addEventListener("scroll",s));let i=Bp(t,()=>{ba(o,n,Sa),Ca(o,t,n),s(),setTimeout(s,0)}),a,d=!0,l=xa(t,u=>{if(u===null){e.onRemove&&e.onRemove(),n.remove();return}if(!d&&e.onMoveStart&&(Promise.resolve().then(()=>e.onMoveStart()),d=!0),clearTimeout(a),a=setTimeout(()=>{e.onMoveEnd&&e.onMoveEnd(),d=!1},200),u.height===0&&u.width===0){if(r===!0)return;e.onHide&&e.onHide(),n.style.display="none",r=!0;return}if(ba(o,n,Sa),Ca(o,t,n),s(),e.placement==="below"&&n.classList.add("below"),n.style.top=`${u.top}px`,n.style.left=`${u.left}px`,e.closestScrollElement&&e.closestScrollElement!==t){let f=e.closestScrollElement.getBoundingClientRect(),h=window.getComputedStyle(e.closestScrollElement),m=qn(h.borderTopWidth),g=qn(h.borderBottomWidth),b=f.top+m-u.top,T=u.top+u.height+-(f.top+f.height-g);n.style.clipPath=`inset(${b}px 0px ${T}px 0px)`}r&&(n.style.display="block",e.onShow&&e.onShow(),r=!1)});return e.appendTo?e.appendTo.appendChild(n):(p=t.parentElement)==null||p.appendChild(n),l.observe(),i.observe(),[n,()=>{t.removeEventListener("scroll",s),l.unobserve(),i.unobserve(),n.remove()}]}function Gh(t){return t.offsetParent!==null}function Kp(t){if(!Gh(t))return!1;let e=t.getBoundingClientRect();return e.top>=0&&e.left>=0&&e.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&e.right<=(window.innerWidth||document.documentElement.clientWidth)}function Ks(t,e,n=100){let o=Kp(t);e({isVisible:o});let r=setInterval(()=>{let s=Kp(t);s!==o&&(o=s,e({isVisible:o}))},n);return()=>{clearTimeout(r)}}var zp=(t,e)=>({value(){try{let n=sessionStorage.getItem(`dd-${t}`);if(!n)return e;try{return JSON.parse(n)}catch(o){return e}}catch(n){return e}},update(n){try{sessionStorage.setItem(`dd-${t}`,JSON.stringify(n))}catch(o){E.warn("[Deepdesk] SessionStorage is blocked by browser")}}});var H=require("react/jsx-runtime");var Wp=zp("showTabHint",!0),Xn=class Xn{constructor({deepdeskUrl:e,version:n=Xn.version||"unknown",locale:o="en-US",token:r,fetch:s,productName:i,createCustomChannel:a,websocketClient:d=Ms}){this.inputMediator=null;this.eventListeners={};this.unmountHandlers=[];this.disposeHandlers=[];this.inlineSuggestions=null;this.aboveSuggestions=null;this.belowSuggestions=null;this.floatingMenu=null;this.widgetElement=null;this.widgetRoot=null;this.nicknameDialogUnsubscribe=null;this.nicknameDialogFailed=!1;this.dynamicThunkObject={};this.queues=new Fs;this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;let l=e.replace(/\/api$/,"");this.deepdeskApi=new yt(l,{token:r,fetch:s}),this.version=n,this.instanceId=Xn.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[kp({broadcast:(h,m,g)=>{this.broadcastEvents.send(h,m,g)},emit:(h,m)=>this.emit(h,m),handleAfterSendMessage:h=>this.handleAfterSendMessage(h),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:h=>this.logSendMessage(h),onUpdateShowTabHint:h=>Wp.update(h),sendEvent:(h,m)=>this.deepdeskApi.sendEvent(h,m)})]};this.store=Ep(c),this.broadcastEvents=new cp({debug:!0,deepdeskUrl:l,eventMap:Bl(this.store),createCustomChannel:a}),this.disposeHandlers.push(()=>{this.broadcastEvents.cleanup()}),this.ws=new d({url:`${l}/api/v2/me/realtime`.replace("https","wss"),reconnectInterval:25e3,shouldReconnect:()=>v(this,null,function*(){var h;return(h=ne(this.state))!=null?h:!1})}),this.whenLoggedIn(()=>this.ws.connect()),this.store.dispatch(No(Wp.value())),this.store.dispatch(Mr({locale:o,adminUrl:l,productName:i}));let p=[],u=h=>{if(!h.conversationId)return;let m=()=>{this.conversationId()===h.conversationId&&this.store.dispatch(sd(h))};this.hasConversation()?m():p.push(m)};this.ws.on("assistants::direct_response",u),this.ws.on("assistants::user_notification",u),this.ws.on("assistants::response_chunk",h=>{if(!h.conversationId)return;let m=()=>{this.conversationId()===h.conversationId&&this.store.dispatch(rd(h))};this.hasConversation()?m():p.push(m)}),this.ws.on("assistants::suggest_as_reply",h=>{if(!h.conversationId)return;let m=()=>{this.conversationId()===h.conversationId&&this.store.dispatch(wn([{text:h.payload.message,type:"text",source:"assistant",assistantCode:h.code,sourceLabel:h.name}]))};this.hasConversation()?m():p.push(m)});let f=this.whenConversationLoaded(()=>{var h;this.broadcastEvents.setExternalId((h=this.state.conversation.current)==null?void 0:h.externalId),p.forEach(m=>m()),p.length=0});this.disposeHandlers.push(()=>{this.ws.cleanup(),p.length=0,f()})}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){var e;return(e=Wt(this.state)[this.state.input.selectedSuggestionIndex])!=null?e:null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}externalId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.externalId}shouldAbort(){return this.state.conversation.isSupported===!1?(E.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(E.warn("Profile has not been loaded (yet)"),!0):(E.warn("No conversation loaded (yet)"),!0)}whenLoggedIn(e){if(ne(this.state))e();else{let n=this.subscribe(ne,o=>{o&&e()});this.disposeHandlers.push(()=>{n()})}}login(){return this.store.dispatch(Sn(null)),this.store.dispatch(tt()),new Promise(e=>{this.whenLoggedIn(()=>e())})}isLoggedIn(){return v(this,null,function*(){return(yield this.store.dispatch(tt())).payload})}isConversationSupported(e,n){return v(this,null,function*(){return(yield this.store.dispatch(Xs({externalId:e,options:n}))).payload})}createConversation(e){return v(this,null,function*(){var o;return this.hasConversation()&&this.externalId()!==e.externalId&&this.resetConversation(),(yield this.store.dispatch(lr(x(y({},e),{metadata:(o=e.metadata)!=null?o:{}})))).payload})}getConversationByExternalId(e,n){return v(this,null,function*(){return this.hasConversation()&&this.externalId()!==e&&this.resetConversation(),(yield this.store.dispatch(dr({externalId:e,options:n}))).payload})}upsertConversation(e){return v(this,null,function*(){var o;return this.hasConversation()&&this.externalId()!==e.externalId&&this.resetConversation(),(yield this.store.dispatch(Js(x(y({},e),{metadata:(o=e.metadata)!=null?o:{}})))).payload})}postMessages(e){return v(this,null,function*(){yield this.store.dispatch(Qs(e))})}updateConversation(e){return v(this,null,function*(){return(yield this.store.dispatch(cr(e))).payload})}resetConversation(){this.store.dispatch(J()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}configure(e){this.store.dispatch(Mr(e))}setVisitorInfo(e){this.store.dispatch(Pl(e))}setCustomData(e){this.store.dispatch(Il(e))}setAgentInfo(e,n){return v(this,null,function*(){var r;yield this.store.dispatch(no(y(y({},e),n))),(r=this.state.info.agentInfo)!=null&&r.agentNickname||this.broadcastEvents.send(yr,{showNicknameDialog:!0})})}setAgentSettings(e){return v(this,null,function*(){yield this.store.dispatch(Ys(e))})}getAgentSettings(){return v(this,null,function*(){return(yield this.store.dispatch(ei())).payload})}refresh(){return v(this,null,function*(){if(this.shouldAbort())return Promise.resolve();let e=[];return e.push(this.refreshTextSuggestions()),e.push(this.refreshWidgetSuggestions()),Promise.all(e).then(()=>{})})}syncInputMediator(){this.inputMediator&&this.store.dispatch(gr({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()}))}notifyExternalSuggestion(e){this.store.dispatch(ye(e))}evaluateAssistant(e,n){return v(this,null,function*(){var d;let{input:o={},transcript:r,showCuesInWidget:s=!0,includeMetadata:i}=n||{},a=yield this.store.dispatch(We({assistantCode:e,transcript:r,includeMetadata:i,input:o,skipState:!s}));if(a.error)throw new Error(`Assistant evaluation failed: ${(d=a.payload)!=null?d:a.error.message}`);return a.payload.output})}evaluateConversationAssistant(e,n){return v(this,null,function*(){yield this.loadProfileConfig();let o=this.state.profile.data;if(!o){E.warn("Can't evaluate assistant when profile is not loaded yet.");return}let r=Lp(o,e);yield Promise.all(r.map(s=>this.queues.push(s,()=>v(this,null,function*(){yield this.evaluateAssistant(s,y({includeMetadata:!0},n))})).catch(i=>{if(i instanceof qo){E.warn(`Queued assistant "${s}" was outdated and dropped`);return}throw i})))})}handleKeyDown(e){let{overlayCollapsed:n,openOverlayWhenTyping:o}=this.state.ui,{textSuggestions:r,selectedSuggestionIndex:s,selection:i}=this.state.input,{inlineSuggestions:a,autoSelectSuggestion:d,showTextSuggestions:l,suggestionsPlacement:c}=this.settings,p=a||d,u=c==="inline"||c==="below"?"below":"above",f=r.length>0;if(this.store.dispatch(fl(Zs(e))),!qe(this.state)||e.key!=="Tab"&&!l)return;let h=()=>{n||!f||i&&(e.shiftKey||(this.store.dispatch(vl()),e.preventDefault()))},m=()=>{n||!f||p&&s<=0||i&&(e.shiftKey||(this.store.dispatch(xl()),e.preventDefault()))};switch(e.key){case"ArrowUp":u==="below"?m():h();break;case"ArrowDown":{u==="below"?h():m();break}case"Escape":{n||(this.store.dispatch(pr(-1)),this.store.dispatch(Lt({collapse:!0})),this.store.dispatch(_c(!0)),e.preventDefault());break}case"Tab":{e.preventDefault();let g=Tn(this.state);if(!g)return;this.store.dispatch(No(!1)),this.store.dispatch(ye({text:g.text,suggestion:g,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(p||this.state.input.selectedSuggestionIndex===-1)return;let g=Tn(this.state);if(!g)return;this.store.dispatch(ye({text:g.text,suggestion:g,eventMetrics:{inputType:"space"},replace:"until-selection-end"}));break}case"Enter":{if(p||e.shiftKey||this.state.input.selectedSuggestionIndex===-1)return;let g=Tn(this.state);if(!g)return;this.store.dispatch(ye({text:g.text,suggestion:g,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),e.preventDefault();break}default:}n&&o&&this.store.dispatch(Lt({collapse:!1}))}handleAfterSendMessage(e){this.emit("send-message",e),this.store.dispatch(Tt([]))}handlingTimeStart(){this.state.handlingTime.startTime||(E.info("Start handling time"),this.store.dispatch(hp()))}handlingTimeStop(){this.state.handlingTime.startTime&&(E.info("Stop handling time"),this.store.dispatch(Ns()))}logSendMessage(e){let n=Ip(this.state,{version:this.version});n&&(e&&(Object.assign(n,{text:e}),Object.assign(n,{lenTextTotal:e.length})),this.deepdeskApi.sendEvent("Send Message",{conversationId:this.conversationId(),data:n}),this.emit("send-message-event",n))}logHandlingTime(){let e=Pp(this.state,{version:this.version});e&&(this.deepdeskApi.sendEvent("Handling Time",{conversationId:this.conversationId(),data:e}),this.store.dispatch(yp()))}notifySubmit(e={}){var n;this.shouldAbort()||(this.store.dispatch(jt((n=e.text)!=null?n:this.state.input.text)),this.store.dispatch(bl()))}emit(e,n){let o=this.eventListeners[e];o&&o.forEach(r=>{try{r(n)}catch(s){E.warn(`The following error occurred in deepdeskSDK.on('${e}', handler)`),E.error(s)}})}on(e,n){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(n),()=>{this.off(e,n)}}off(e,n){if(!e&&!n){this.eventListeners={};return}let o;this.eventListeners[e]&&(o=this.eventListeners[e].indexOf(n),o>-1&&this.eventListeners[e].splice(o,1))}setConversationQuery(e){this.dynamicThunkObject.conversationQuery=e}setPlatformVariables(e){this.store.dispatch(Ll(e))}whenConversationLoaded(e){let n=s=>{var i;return(i=s.conversation.current)==null?void 0:i.id},o=()=>this.loadProfileConfig().then(()=>e());return n(this.state)&&o(),this.subscribe(n,s=>{s&&o()})}overlayContainerFactory(e,n,o,r){let[s,i]=Xo(n,o);return s.setAttribute("translate","no"),s.dataset.testid=e,r&&s.classList.add(r),[s,i]}createInlineContainer(e,n){var a;let o=document.createElement("div");o.style.position="absolute",o.style.top="0px",o.style.left="0px",o.style.height="0px",o.style.width="0px";let r=document.createElement("div");r.style.display="none",r.style.position="absolute",r.style.height="0px",r.style.width="0px",r.style.backgroundColor="red",o.appendChild(r);let s=(a=e.ownerDocument.defaultView)==null?void 0:a.frameElement,i=s?s.ownerDocument.defaultView:null;if(s&&(i===window||(i==null?void 0:i.parent)===window)){let[d,l]=Xo(s,{appendTo:document.body,onMoveStart:()=>{r.style.display="none"}});d.dataset.testid=n,d.style.zIndex="2",d.appendChild(o),this.unmountHandlers.push(()=>{l()})}else document.body.appendChild(o);return r}createContainer(e,n=document.body){let o=window.getComputedStyle(n),r=document.createElement("div");return Jt(r),r.dataset.testid=e,r.style.color=o.color,r.style.fontSize=o.fontSize,r.style.fontFamily=o.fontFamily,r.style.fontVariant=o.fontVariant,r.setAttribute("translate","no"),n.appendChild(r),r}storeMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,n=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(e,n),E.info(`Stored analytics for ${this.conversationId()}`)}catch(e){}}restoreMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,n=window.sessionStorage.getItem(e);if(!n)return;let o=JSON.parse(n);o.text.trim()===this.state.input.text.trim()?(E.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(Sl(o.metrics))):E.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(e)}catch(e){}}mount(e,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!Hs(e))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let u=n,{customStyles:o,closestScrollSelector:r,floatingMenuParent:s,appendOverlayTo:i,inputMediator:a}=u,d=M(u,["customStyles","closestScrollSelector","floatingMenuParent","appendOverlayTo","inputMediator"]),l={customStyles:o,closestScrollSelector:r,floatingMenuParent:s,appendOverlayTo:i};this.configure(d),this.settings.automaticHandlingTime&&this.setupHandlingTime(e),Jt(e),this.inputMediator=a||(ln(e)?new un(e):new cn(e)),this.inputMediator.on("change",({plainText:f,rawHTML:h})=>{this.store.dispatch(gr({text:f,html:h}))}),this.inputMediator.on("keyup",f=>{this.store.dispatch(hl(Zs(f)))}),this.inputMediator.on("keydown",f=>{this.handleKeyDown(f)}),this.inputMediator.on("paste",({pastedText:f,selectionText:h})=>{this.store.dispatch(yl({text:f,selectionText:h}))}),this.inputMediator.on("cut",({selectionText:f})=>{this.store.dispatch(ml(f))});let c;this.inputMediator.on("selection",f=>{clearTimeout(c),f===null?c=setTimeout(()=>{f!==null&&this.store.dispatch(mr(f))},500):this.store.dispatch(mr(f))}),this.unmountHandlers.push(()=>{clearTimeout(c)}),this.inputMediator.on("disabled",()=>{var f;(f=this.inputMediator)==null||f.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{this.settings.detectSubmit&&this.notifySubmit()}),this.inputMediator.on("blur",()=>{this.store.dispatch(cs(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(cs(!0))}),this.renderSuggestions(e,l),this.subscribe(Xt("inlineSuggestions"),()=>{this.renderSuggestions(e,l)}),this.subscribe(Xt("suggestionsPlacement"),()=>{this.renderSuggestions(e,l)});let p=this.renderOverlays(n);this.unmountHandlers.push(()=>{p.unmount()}),this.store.dispatch(gr({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()})),this.store.dispatch(mr(this.inputMediator.getSelection())),this.store.dispatch(cs(this.inputMediator.isFocused)),this.unmountHandlers.push(()=>{this.state.input.text!==""&&this.storeMetrics()}),this.whenConversationLoaded(()=>{this.restoreMetrics(),this.syncInputMediator(),this.refreshTextSuggestions(),this.promptForNickname()}),this.isMounted=!0}promptForNickname(e){if(this.nicknameDialogUnsubscribe||this.nicknameDialogFailed)return;let n=this.createContainer("nickname-dialog",document.body);document.body.appendChild(n);let o=(0,vt.createRoot)(n),r=null,s=a=>{r=a,i()},i=()=>{o==null||o.render((0,H.jsx)(ut,{store:this.store,children:(0,H.jsx)(ot,{broadcastEvents:this.broadcastEvents,children:(0,H.jsx)(Jc,{id:"deepdesk-nickname-dialog",error:r,onSave:a=>v(this,null,function*(){try{yield this.store.dispatch(kl({agentNickname:a})).unwrap(),console.log("setAgentNickname",a),this.broadcastEvents.send(yr,{showNicknameDialog:!1}),this.nicknameDialogUnsubscribe&&this.nicknameDialogUnsubscribe()}catch(d){E.error("Error setting agent nickname",d),s("error"),this.nicknameDialogFailed=!0}})})})}))};i(),this.nicknameDialogUnsubscribe=()=>{o.unmount(),n.remove(),this.nicknameDialogUnsubscribe=null}}subscribe(e,n){let o=e(this.store.getState());return this.store.subscribe(()=>{let r=e(this.store.getState());r!==o&&(o=r,n(o))})}unmount(){var e,n,o,r,s;(e=this.inlineSuggestions)==null||e.unmount(),(n=this.aboveSuggestions)==null||n.unmount(),(o=this.belowSuggestions)==null||o.unmount(),(r=this.floatingMenu)==null||r.unmount(),this.unmountHandlers.forEach(i=>i()),this.unmountHandlers=[],(s=this.inputMediator)==null||s.dispose(),this.nicknameDialogUnsubscribe&&this.nicknameDialogUnsubscribe(),this.isMounted=!1}dispose(){this.unmount(),this.unmountWidget(),this.disposeHandlers.forEach(e=>e()),this.disposeHandlers=[],this.off()}renderSuggestions(e,n){var o,r,s,i;(o=this.floatingMenu)==null||o.unmount(),(r=this.inlineSuggestions)==null||r.unmount(),(s=this.aboveSuggestions)==null||s.unmount(),(i=this.belowSuggestions)==null||i.unmount(),this.settings.floatingMenu&&(this.floatingMenu=this.renderFloatingMenu(e,n)),this.settings.inlineSuggestions||this.settings.suggestionsPlacement==="inline"?this.inlineSuggestions=this.renderInlineSuggestions(e,n):this.settings.suggestionsPlacement==="below"?this.belowSuggestions=this.renderAboveOrBelowSuggestions(e,n,"below"):this.aboveSuggestions=this.renderAboveOrBelowSuggestions(e,n,"above")}renderInlineSuggestions(e,n){let{customStyles:o}=n,r=this.createInlineContainer(e,"deepdesk-caret"),s=(0,vt.createRoot)(r);s.render((0,H.jsx)(ut,{store:this.store,customStyles:o,children:(0,H.jsx)(ot,{broadcastEvents:this.broadcastEvents,children:(0,H.jsx)(Gc,{})})}));let i=a=>{a?(r.style.display="block",r.style.top=`${a.top}px`,r.style.left=`${a.left}px`):r.style.display="none"};return this.inputMediator.on("caretposition",i),{unmount:()=>{var a;(a=this.inputMediator)==null||a.off("caretposition",i),s.unmount(),r.remove()}}}renderAboveOrBelowSuggestions(e,n,o){let{customStyles:r,closestScrollSelector:s,appendOverlayTo:i}=n,a=s&&va(e,s)||void 0,[d,l]=this.overlayContainerFactory("deepdesk-tab-completion",a||e,{appendTo:i,closestScrollElement:a,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),[c,p]=this.overlayContainerFactory("deepdesk-suggestions-overlay",a||e,{appendTo:i,placement:o},r==null?void 0:r.suggestionsRootNode),u=(0,vt.createRoot)(d);u.render((0,H.jsx)(ut,{store:this.store,customStyles:r,children:(0,H.jsx)(ot,{broadcastEvents:this.broadcastEvents,children:(0,H.jsx)(Iu,{inputElement:e})})}));let f=(0,vt.createRoot)(c);return f.render((0,H.jsx)(ut,{store:this.store,customStyles:r,children:(0,H.jsx)(ot,{broadcastEvents:this.broadcastEvents,children:(0,H.jsx)(au,{onLogIn:()=>this.loginViaPopup().catch(h=>E.warn(h.message))})})})),{unmount(){u.unmount(),f.unmount(),l(),p()}}}renderFloatingMenu(e,n){let{customStyles:o,closestScrollSelector:r,appendOverlayTo:s,floatingMenuParent:i}=n,a=r&&va(e,r)||void 0,[d,l]=this.overlayContainerFactory("floating-menu",a||e,{appendTo:i!=null?i:s},o==null?void 0:o.floatingMenuParent),c=(0,vt.createRoot)(d);return c.render((0,H.jsx)(ut,{store:this.store,customStyles:o,children:(0,H.jsx)(ot,{broadcastEvents:this.broadcastEvents,children:(0,H.jsx)(Nc,{onLogIn:()=>this.loginViaPopup().catch(p=>E.warn(p.message))})})})),{unmount(){c.unmount(),l()}}}renderOverlays(e){let{customStyles:n}=e,o=this.createContainer("deepdesk-overlays"),r=(0,vt.createRoot)(o);return r.render((0,H.jsx)(ut,{store:this.store,customStyles:n,children:(0,H.jsx)(ot,{broadcastEvents:this.broadcastEvents,children:(0,H.jsx)(kc,{})})})),{unmount(){r.unmount(),o.remove()}}}renderWidget(e,n={}){if(this.widgetElement&&E.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:o,showImages:r,isEmbedded:s}=n;this.widgetElement=e,this.configure({showImages:r,isEmbedded:s}),this.widgetRoot=(0,vt.createRoot)(e),this.widgetRoot.render((0,H.jsx)(ut,{store:this.store,customStyles:o,children:(0,H.jsx)(ot,{broadcastEvents:this.broadcastEvents,children:(0,H.jsx)(rp,{assistantOptions:n.assistantOptions,knowledgeAssistOptions:n.knowledgeAssist,onLogIn:()=>this.loginViaPopup().catch(i=>E.warn(i.message))})})}))}unmountWidget(){var e,n;(n=(e=this.widgetRoot)==null?void 0:e.unmount)==null||n.call(e),this.widgetRoot=null,this.widgetElement=null}renderKnowledgeAssistantWidget(e,n,o={}){let{customStyles:r,initialQuestion:s}=o,i=(0,vt.createRoot)(n);return i.render((0,H.jsx)(ut,{store:this.store,customStyles:r,children:(0,H.jsx)(ot,{broadcastEvents:this.broadcastEvents,children:(0,H.jsx)(la,{children:(0,H.jsxs)(Vr,{assistantCode:e,initialQuestion:s,evaluateKnowledgeAssistFn:yo,children:[(0,H.jsx)(yn,{children:(0,H.jsx)($r,{title:o.title,emptyState:o.emptyState})}),(0,H.jsx)(aa,{children:(0,H.jsx)(jr,{})})]})})})})),{unmount(){i.unmount()}}}setupHandlingTime(e){let n=Ks(e,({isVisible:o})=>{o?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){Ap(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(()=>v(this,null,function*(){yield this.store.dispatch(bo());let e=Yt(this.state);e&&this.store.dispatch(Mr({showSearch:e.search,showImageSearch:e.imageSearch,showEntitiesCommand:e.entitiesCommand,showSummaryCommand:!!e.summarizerAssistantNew,showKnowledgeSearch:!!e.knowledgeAssistantNew||!!e.knowledgeAssistant,recommendTextSuggestions:e.recommendTextSuggestions}))})),this.loadProfileConfigPromise)}loginViaPopup(e){return v(this,null,function*(){return new Promise((n,o)=>{this.store.dispatch(ar());let r=new MessageChannel,s=r.port1,i=this.settings.adminUrl,a=new URL(e!=null&&e.url?e==null?void 0:e.url:`${i}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let d=!1,l=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",p),clearInterval(u)};s.onmessage=f=>v(this,null,function*(){var h,m;if((h=f.data)!=null&&h.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((m=f.data)==null?void 0:m.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(ro),d=!0,r.port1.close(),n()}catch(g){console.error(g),o(g)}finally{d=!0,l()}});let c=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");c===null&&o(new Error("Popup blocked by browser"));let p=f=>v(this,null,function*(){var h;if(f.origin===a.origin)switch((h=f.data)==null?void 0:h.type){case"deepdesk-popup-request-origin":{try{let m=JSON.stringify({type:"deepdesk-popup-parent-origin"});c==null||c.postMessage(m,a.origin)}catch(m){E.error("Error posting message to popup",m),o(m)}break}case"deepdesk-popup-loaded":{try{let m=JSON.stringify({type:"deepdesk-popup-create-channel"});c==null||c.postMessage(m,a.origin,[r.port2])}catch(m){E.error("Error posting message to popup",m),o(m)}break}case"deepdesk-popup-error":{if(l(),f.data.message==="Platform account url mismatch"){let m=`Please contact your administrator: The platform account url (${f.data.targetOrigin}) is misconfigured as it differs from the origin of the page that opened the popup (${f.data.openerOrigin}).`;E.warn(m),this.store.dispatch(qs(m)),o(new Error(m))}if(f.data.message==="Timeout"){let m="Please contact your administrator: Popup timed out. Check if the account's platform url is configured correctly.";E.warn(m),this.store.dispatch(qs(m)),o(new Error(m))}o(new Error(f.data.message));break}}});window.addEventListener("message",p);let u=setInterval(()=>{c&&!c.closed||(l(),d||o(new Error("Popup closed by user")))},200);this.disposeHandlers.push(l)})})}translateMessages(e){return this.deepdeskApi.translateMessages(e)}refreshTextSuggestions(){return v(this,null,function*(){this.isMounted&&(yield this.store.dispatch(is()))})}refreshWidgetSuggestions(){return v(this,null,function*(){if(!this.widgetRoot)return;let{uiConfig:e}=this.state.profile.data;if(!e.widget)return;let n=Co(this.state);try{n.forEach(({type:o})=>{switch(o){case"entities":this.store.dispatch(He());break;case"pinned-messages":case"sticky-messages":break;default:ir.includes(o)||this.store.dispatch(Be(o))}})}catch(o){this.handleError(o)}})}};Xn.version="19.1.2-beta.2",Xn.count=0;var Jo=Xn;function qh(t){return v(this,null,function*(){var r,s,i;let n=yield((r=t.fetch)!=null?r:window.fetch)(t.url),o=yield n.blob();return new File([o],t.name,{type:(i=(s=t.mimeType)!=null?s:n.headers.get("Content-Type"))!=null?i:"image/jpeg"})})}function Vp(t,e){return v(this,null,function*(){let n=yield qh(e),o=new Event("change",{bubbles:!0,cancelable:!0});try{Object.defineProperty(t,"files",{configurable:!0,get:()=>[n]}),t.dispatchEvent(o)}finally{Object.hasOwn(t,"files")&&delete t.files}})}function jp(t,e,n){return v(this,null,function*(){yield new yt(t).authenticateWithKey(e,n)})}function $p(t){return t.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function Gp(o,r){return v(this,arguments,function*(t,e,n={}){var p,u;let{value:s}=t,{start:i,end:a}=(p=n.replace)!=null?p:{start:0,end:s.length},d=`${s.slice(0,i)}${e}${s.slice(a)}`,l=(u=n.selectionAfter)!=null?u:{start:i+e.length,end:i+e.length},c=()=>{if(n.setValue)return n.setValue(d);t.value=d};return Promise.resolve(c()).then(()=>{t.selectionStart=l.start,t.selectionEnd=l.end,t.blur(),t.focus()})})}function qp(o,r){return v(this,arguments,function*(t,e,n={}){let s=n.replace?_t(t,n.replace.start,n.replace.end):$n(t),i,a=()=>{if(n.setRange)return n.setRange(s.cloneRange());s.deleteContents(),i=document.createElement("span"),s.insertNode(i),n.insertBRs!==!1?e.split(`
10
+ `);let h=u?o:0,m=f?Math.min(s,c.childNodes.length):c.childNodes.length;for(let g=h;g<m&&(l(c.childNodes[g]),a!==2);g++);break}default:break}f&&(a=2)}return l(t),d}var ip=(i=>(i.CUT="Cut",i.BACKSPACE="Backspace",i.DELETE="Delete",i.ERASEEOF="EraseEof",i.UNDO="Undo",i.CLEAR="Clear",i))(ip||{}),ht=class{constructor(e){this.element=e;this.isFocused=!1;this.isActive=!0;this.isDisposed=!1;this.eventListeners={};this.disposeHandlers=[];this.cachedText="";this.cachedCaretPosition=null;this.cachedSelection={start:0,end:0};this.cachedHTML="";this.isSubmitting=!1;this.isPossibleClearInputAction=!1;this.cachedText=this.getText(),this.cachedHTML=this.getHTML(),this.cachedSelection=this.getSelection(),this.listen()}addEventListener(e,n){let o=r=>{n(r)};this.element.addEventListener(e,o),this.disposeHandlers.push(()=>{this.element.removeEventListener(e,o)})}removeEventListener(e,n){this.element.removeEventListener(e,n)}handleInteraction(){let e=this.getText(),n=this.getHTML(),o=this.getSelection(),r=this.cachedCaretPosition===null;if(!this.isActive||(e===""&&this.cachedText!==""&&!this.isPossibleClearInputAction&&this.emit("submit"),e!==this.cachedText?(this.cachedText=e,this.cachedHTML=n,r=!0,this.emit("change",{plainText:e,rawHTML:n})):n!==null&&n!==this.cachedHTML&&(this.cachedHTML=n,r=!0,this.emit("change",{plainText:e,rawHTML:n})),(o.start!==this.cachedSelection.start||o.end!==this.cachedSelection.end)&&(this.cachedSelection=o,r=!0,this.emit("selection",o)),!r))return;let s=this.getCaretPosition();Ct(s,this.cachedCaretPosition)||(this.cachedCaretPosition=s,this.emit("caretposition",s))}handleClick(){this.handleInteraction()}handleFocus(){let e=!this.isFocused;this.isFocused=!0,e&&this.emit("focus"),this.handleInteraction()}handleBlur(){this.isPossibleClearInputAction=!1;let e=this.isFocused;this.isFocused=!1,e&&this.emit("blur")}handleKeyDown(e){let{key:n,ctrlKey:o,metaKey:r}=e;this.isPossibleClearInputAction=Object.values(ip).includes(n)||n.toLowerCase()==="z"&&(o||r),this.emit("keydown",e)}handleKeyUp(e){this.handleInteraction(),this.emit("keyup",e)}handleCut(){this.isPossibleClearInputAction=!0,this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(e){var o,r;let n=((o=e.clipboardData)==null?void 0:o.getData("text"))||((r=e.clipboardData)==null?void 0:r.getData("text/plain"))||"";this.emit("paste",{pastedText:n,selectionText:this.getSelectedText()})}listen(){this.addEventListener("keydown",n=>this.handleKeyDown(n)),this.addEventListener("keyup",n=>this.handleKeyUp(n)),this.addEventListener("input",()=>this.handleInteraction()),this.addEventListener("change",()=>this.handleInteraction()),this.addEventListener("focus",()=>this.handleFocus()),this.addEventListener("blur",()=>this.handleBlur()),this.addEventListener("cut",()=>this.handleCut()),this.addEventListener("paste",n=>this.handlePaste(n)),this.addEventListener("click",()=>this.handleInteraction()),document.activeElement===this.element&&(this.isFocused=!0);let e=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});e.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{e.disconnect()})}focus(){this.element.focus()}emit(e,...n){this.isDisposed||this.eventListeners[e]&&this.eventListeners[e].forEach(o=>{o(...n)})}on(e,n){this.isDisposed||(this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(n))}off(e,n){if(!this.eventListeners[e])return;let o=this.eventListeners[e].indexOf(n);o!==-1&&this.eventListeners[e].splice(o,1)}activate(){let e=this.isActive===!1;this.isActive=!0,e&&this.handleInteraction()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(e=>e()),this.eventListeners={},this.isDisposed=!0}};function ap(t){return t.top!==0||t.left!==0||t.height!==0||t.width!==0}var cn=class extends ht{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),Go(this.element,n)}getHTML(){return this.element.innerHTML||""}getRange(){let n=this.getRootNode();if(n.activeElement!==this.element)return null;let o="getSelection"in n?n.getSelection():window.getSelection();if(!o)return null;let r=o.rangeCount>0?o.getRangeAt(0):null;if(!r)return null;let s=this.element.ownerDocument.createRange();return s.setStart(r==null?void 0:r.startContainer,r==null?void 0:r.startOffset),s.setEnd(r==null?void 0:r.endContainer,r==null?void 0:r.endOffset),!s||!this.element.contains(s.startContainer)||!this.element.contains(s.endContainer)?null:s}getCaretPosition(){let n=this.getRange();if(!n||!n.collapsed||!("getBoundingClientRect"in n))return null;let o=n.getBoundingClientRect();return!ap(o)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),o=n.getBoundingClientRect(),n.deleteContents(),!ap(o))?null:{top:o.top+o.height,left:o.left}}getSelection(){let n=this.getRange();if(n)return $o(this.element,n);let o=this.lastKnownSelection;if(o&&sp(this.element,o.start,o.end))return o;let r=$n(this.element);return r.collapse(!1),$o(this.element,r)}getSelectedText(){let{start:n,end:o}=this.getSelection();return Go(this.element,_t(this.element,n,o))}listen(){super.listen();let n=new MutationObserver(s=>{var i,a;s.length===2&&s[0].addedNodes.length===1&&((i=s[0].addedNodes[0])==null?void 0:i.textContent)==="\u2060"&&((a=s[1].removedNodes[0])==null?void 0:a.textContent)==="\u2060"||setTimeout(()=>{this.handleInteraction()},0)});n.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0}),this.disposeHandlers.push(()=>n.disconnect());let o=this.element.isContentEditable,r=new MutationObserver(()=>{this.element.isContentEditable!==o&&(o=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});r.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>r.disconnect())}};var Ah=["direction","boxSizing","width","height","overflowX","overflowY","borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth","borderStyle","paddingTop","paddingRight","paddingBottom","paddingLeft","fontStyle","fontVariant","fontWeight","fontStretch","fontSize","fontSizeAdjust","lineHeight","fontFamily","textAlign","textTransform","textIndent","textDecoration","letterSpacing","wordSpacing","tabSize"];function lp(t,e){let n="mozInnerScreenX"in window,o=document.createElement("div");o.id="input-textarea-caret-position-mirror-div";let r=o.style,s=window.getComputedStyle(t),i=t.ownerDocument.body;r.whiteSpace="pre-wrap",r.wordWrap="break-word",r.position="absolute",r.visibility="hidden",Ah.forEach(c=>{r[c]=s[c]}),n?t.scrollHeight>Number.parseInt(s.height)&&(r.overflowY="scroll"):r.overflow="hidden",o.textContent=t.value.substring(0,e);let a=document.createElement("span");a.textContent=t.value.substring(e)||".",o.appendChild(a),i.appendChild(o);let d=t.getBoundingClientRect(),l={top:d.top-t.scrollTop+a.offsetTop+Number.parseInt(s.borderTopWidth)+a.offsetHeight,left:d.left-t.scrollLeft+a.offsetLeft+Number.parseInt(s.borderLeftWidth)};return i.removeChild(o),l}var un=class extends ht{constructor(){super(...arguments);this.lastKnownSelection=null}getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:n,selectionEnd:o}=this.element;return{start:n,end:o}}getSelectedText(){let n=this.getSelection();return n?this.getText().slice(n.start,n.end):""}getCaretPosition(){return lp(this.element,this.element.selectionEnd)}listen(){super.listen();let n=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var s;return(s=n==null?void 0:n.get)==null?void 0:s.call(this.element)},set:s=>{var i;(i=n==null?void 0:n.set)==null||i.call(this.element,s),this.handleInteraction()}}),this.addEventListener("scroll",()=>{this.emit("caretposition",this.getCaretPosition())});let o=this.element.disabled,r=new MutationObserver(()=>{this.element.disabled!==o&&(o=this.element.disabled,this.emit(o?"disabled":"enabled"))});r.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>r.disconnect())}};function dp(t,e,n){let o=`deepdesk-iframe-${t}`,r=document.getElementById(o);if(r)return r;let s=document.createElement("iframe"),i=new URL(e);return Object.entries(n).forEach(([a,d])=>{i.searchParams.append(a,d)}),s.style.position="absolute",s.style.left="-999em",s.style.width="0px",s.style.height="0px",s.tabIndex=-1,s.id=o,s.title=`iframe-${t}`,s.src=i.toString(),window.document.body.appendChild(s),s}function Mh(t){if(typeof t!="string")return t;try{return JSON.parse(t)}catch(e){return t}}var da=class{constructor(e){this.name=e;this.disposeHandlers=[];this.broadcastChannel=new BroadcastChannel(e)}onMessage(e){this.broadcastChannel.addEventListener("message",e),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",e)})}postMessage(e){this.broadcastChannel.postMessage(JSON.stringify(e))}close(){this.disposeHandlers.forEach(e=>e()),this.broadcastChannel.close()}},ca=class{constructor(e,n,o){this.name=e;this.targetOrigin=n;this.options=o;this.disposeHandlers=[];this.iframe=dp(e,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}onMessage(e){window.addEventListener("message",e),this.disposeHandlers.push(()=>{window.removeEventListener("message",e)})}postMessage(e){var n;(n=this.iframe.contentWindow)==null||n.postMessage(JSON.stringify(e),this.targetOrigin)}close(){var e;this.disposeHandlers.forEach(n=>n()),(e=this.iframe)==null||e.remove()}},ua=class{constructor(e){this.params=e;this.deepdeskUrl=e.deepdeskUrl,this.eventMap=e.eventMap,this.externalId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setExternalId(e){this.externalId!==e&&(this.cleanup(),E.info("Set externalId",e),this.externalId=e,this.channel=this.createChannel(e))}createChannel(e){let n=this.params.createCustomChannel?this.params.createCustomChannel(e):this.isCrossOrigin?new ca(e,this.deepdeskUrl,{debug:!0}):new da(e),o=r=>{var i,a;if(r.origin!==this.deepdeskUrl)return;let s=Mh(r.data);typeof s!="object"||s.type!=="event"||s.channel!==e||(E.info("Received broadcast event",this.externalId,r),(a=(i=this.eventMap)[s.name])==null||a.call(i,s.payload))};return n.onMessage(o),n}send(e,n,o){var i,a;E.info("Broadcast event",{externalId:this.externalId,name:e,payload:n});let r={type:"event",name:e,payload:n};o!==!1&&((a=(i=this.eventMap)[e])==null||a.call(i,n));let s=this.externalId==="deepdesk-general"?this.defaultChannel:this.channel;s==null||s.postMessage(x(y({},r),{channel:this.externalId}))}cleanup(e=!1){var n,o;(n=this.channel)==null||n.close(),this.channel=void 0,e&&((o=this.defaultChannel)==null||o.close(),this.defaultChannel=void 0)}},cp=ua;function Nh(t){return t.replace(/(_\w)/g,e=>e[1].toUpperCase())}function z(t){return Array.isArray(t)?t.map(z):typeof t=="object"&&t!==null?Object.keys(t).reduce((e,n)=>x(y({},e),{[Nh(n)]:z(t[n])}),{}):t}function Oh(t){return t.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}function ue(t){return Array.isArray(t)?t.map(ue):typeof t=="object"&&t!==null?Object.keys(t).reduce((e,n)=>x(y({},e),{[Oh(n)]:ue(t[n])}),{}):t}var Gn=class extends Error{constructor(n,o){super(n);this.body=o;this.name="CustomError"}};var pa=t=>new Promise(e=>{setTimeout(e,t)});var pn=class extends Gn{constructor(){super(...arguments);this.name="ClientError"}},ma=class extends Gn{constructor(){super(...arguments);this.name="ServerError"}},ga=new Map;function Dh(t){return v(this,null,function*(){if(t.status===204)return t.text().catch(()=>{}),null;let e=t.headers.get("content-type");if(e!=null&&e.includes("application/json"))return t.json();let n=yield t.text();return n===""?null:(E.warn("Unexpected response body:",n.slice(0,20)),JSON.parse(n))})}var gn=class{constructor(e="",n={}){this.baseUrl=e;this.options=n;this.latestRequestByUrl={};this.refreshingToken=null;this.lastFailedRefreshAt=null;this.failedRefreshCooldown=1e4;var o;this.fetch=(o=n.fetch)!=null?o:window.fetch.bind(window)}patchFetch(e){this.fetch=e(this.fetch)}setCsrfToken(e){this.csrfToken=e}request(e,n={}){return new Promise((o,r)=>{let s={isAborted:!1,reject:r},i=`${this.baseUrl}${e}`,a=this.fetch,d=n.method===void 0||n.method.toLowerCase()==="get",N=n,{useCache:l=!1,abortLatest:c=!1,attempts:p=1,retryDelay:u=500,refreshTokenOn401:f=!0,retryOnError:h=B=>B instanceof TypeError,retryOnResponse:m=B=>B.status>=500,version:g=null}=N,b=M(N,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]);if(l){if(!d)throw new Error(`Can't use 'useCache' for ${n.method}`);if(ga.has(i)){o(ga.get(i));return}}let T=x(y({credentials:"include"},b),{headers:y({Accept:"application/json","Content-Type":"application/json"},b.headers)});!d&&this.csrfToken&&(T.headers=x(y({},T.headers),{"X-CSRFToken":this.csrfToken})),typeof g=="string"&&(T.headers=x(y({},T.headers),{"X-Deepdesk-API-Version":g}));let C=p,w=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[i]&&c&&(this.latestRequestByUrl[i].isAborted=!0,this.latestRequestByUrl[i].reject(new Error("Aborted"))),this.latestRequestByUrl[i]=s;let L=()=>v(this,null,function*(){return C--,a(i,T).then(B=>v(this,null,function*(){return m(B)&&!s.isAborted&&C>0?(yield pa(u),L()):B.status===401&&f===!0&&w===!1?(w=!0,yield this.refreshToken(),L()):B})).catch(B=>v(this,null,function*(){if(h(B)&&!s.isAborted&&C>0)return yield pa(u),L();throw B}))});L().then(B=>v(this,null,function*(){let X=yield Dh(B);if(delete this.latestRequestByUrl[i],B.status>=500){r(new ma("Server Error",X));return}if(B.status===401){r(new pn("Unauthorized",X));return}if(B.status===403){r(new pn("Forbidden",X));return}if(B.status===404){r(new pn("Not Found",X));return}if(B.status>=400){r(new pn("Bad Request",X));return}l&&ga.set(i,X),o(X)})).catch(B=>{r(B)})})}validateToken(){return v(this,null,function*(){let e,n,o;try{({has_valid_access_token:e,is_logged_in:n,has_valid_refresh_token:o}=yield this.get("/apis/admin/session/validate/",{refreshTokenOn401:!1}))}catch(r){return!1}if(!e){if(!o)return!1;try{yield this.refreshToken();let{is_logged_in:r}=yield this.get("/apis/admin/session/validate/",{refreshTokenOn401:!1});return r}catch(r){return!1}}return n})}refreshToken(){let e=Date.now();return this.lastFailedRefreshAt&&e-this.lastFailedRefreshAt<this.failedRefreshCooldown?Promise.reject(new pn("Unauthorized","Failed to refresh token")):this.refreshingToken?this.refreshingToken:(this.refreshingToken=this.get("/apis/admin/session/refresh/",{refreshTokenOn401:!1}).catch(n=>{throw(n==null?void 0:n.message)==="Unauthorized"&&(this.lastFailedRefreshAt=Date.now()),n}).finally(()=>{this.refreshingToken=null}),this.refreshingToken)}get(e,n){return this.request(e,n)}post(e,n,o){return this.request(e,y({method:"POST",body:JSON.stringify(n)},o))}patch(e,n,o){return this.request(e,y({method:"PATCH",body:JSON.stringify(n)},o))}put(e,n,o){return this.request(e,y({method:"PUT",body:JSON.stringify(n)},o))}delete(e,n){return this.request(e,y({method:"DELETE"},n))}};var up;(e=>{let t;(a=>(a.SUCCESS="success",a.FAILURE="failure",a.CONDITIONS_NOT_MET="conditions_not_met",a.MAX_RECURSION_LEVEL="max_recursion_level",a.NO_ACCESS_TO_ASSISTANT="no_access_to_assistant"))(t=e.EvaluationStatus||(e.EvaluationStatus={}))})(up||(up={}));function fa(t){return x(y({},z(t)),{metadata:t.metadata})}var mn=class mn{constructor(e,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new gn(e,{fetch:n.fetch}),this.client.patchFetch(o=>(r,s)=>v(this,null,function*(){let i=yield o(r,s);return this.handleDeepdeskVersionHeaders(i),i}))}preflight(){return v(this,null,function*(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let e=yield this.getCsrfToken();this.client.setCsrfToken(e)}return this.options.token?(mn.exchangeTokenPromise||(mn.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),mn.exchangeTokenPromise):Promise.resolve()})}createConversation(e){return v(this,null,function*(){var o;yield this.preflight(),E.info(`Creating conversation for session ${e.externalId} and agent ${e.agentId}`);let n=yield this.client.post("/api/v2/conversations",x(y({chat_start_time:new Date().toISOString()},ue(e)),{metadata:(o=e.metadata)!=null?o:{}}));return fa(n)})}getMe(){return v(this,null,function*(){let e=yield this.client.get("/apis/admin/session/me/");return z(e)})}postIdentity(e){return v(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/me/identities/",ue(e))})}patchMe(e){return v(this,null,function*(){yield this.preflight();let n=yield this.client.patch("/apis/admin/session/me/",ue(e));return z(n)})}getProfile(e){return v(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${e}/`,{useCache:!0});return z(n)})}getKnowledgeAssistant(e){return v(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${e}/`,{useCache:!0});return z(n)})}getContentTypes(){return v(this,null,function*(){let e=yield this.client.get("/apis/admin/content-types/",{useCache:!0});return z(e)})}getAccount(){return v(this,null,function*(){let e=yield this.client.get("/apis/admin/account/",{useCache:!0});return z(e)})}getPlatformConfig(e){return v(this,null,function*(){let n=e!==void 0?`/platform/config/${e}/`:"/platform/config/",{config:o}=yield this.client.get(n,{useCache:!0});return z(o)})}checkUserExists(e){return v(this,null,function*(){let{exists:n}=yield this.client.get(`/apis/admin/users/exists?external_id=${e}`,{version:"v1"});return n})}getConversationByExternalId(o){return v(this,arguments,function*(e,n={}){yield this.preflight(),E.info(`Getting conversation for session ${e}`);let{attempts:r=1,retryDelay:s=1e3}=n,i=yield this.client.get(`/api/v2/conversations/by_external_id/${e}`,{attempts:r,retryDelay:s,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"});return E.info(`Successfully retrieved conversation ${i.id} for session ${e}`),fa(i)})}isConversationSupported(o){return v(this,arguments,function*(e,n={}){E.info(`Check if conversation for session ${e} is supported`);let{attempts:r=1,retryDelay:s=1e3}=n;return(yield this.client.get(`/api/v2/conversations/by_external_id/${e}/has_active_profile`,{attempts:r,retryDelay:s,retryOnResponse:a=>a.status===404||a.status>=500})).has_active_profile})}updateConversation(e,n){return v(this,null,function*(){var s;yield this.preflight();let o=ue(n);n.metadata&&(o.metadata=(s=n.metadata)!=null?s:{});let r=yield this.client.put(`/api/v2/conversations/${e}`,o);return fa(r)})}postMessages(e,n){return v(this,null,function*(){yield this.preflight(),yield this.client.post(`/api/v2/conversations/${e}/messages`,n.map(o=>x(y({},ue(o)),{metadata:o.metadata})))})}sendEvent(e,n){return v(this,null,function*(){yield this.preflight();let a=n,{data:o}=a,r=M(a,["data"]),s=Object.entries(this.latestReceivedDeepdeskVersions).reduce((d,[l,c])=>x(y({},d),{[l]:c}),{}),i=["platform","agentId","agentName","agentEmail","conversationId"].reduce((d,l)=>(r[l]&&(d[l]=r[l]),d),{});return this.client.post("/api/v2/events",ue(x(y(y({},s),i),{data:o,name:e})),{version:"v2"})})}getEntities(e){return v(this,null,function*(){return yield this.preflight(),yield this.client.post("/api/v2/entities",{messages:e.filter(o=>o.text)})})}getTemporaryExchangeToken(){return v(this,null,function*(){return(yield this.client.get("/apis/admin/session/exchange-token/")).jwt})}exchangeTokenForAccessCookie(e){return v(this,null,function*(){return this.client.post("/apis/admin/session/jwt/",{jwt:e}).catch(n=>{throw E.warn(`Invalid token '${e}'`),n})})}authenticateWithKey(e,n){return v(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/api-key/",ue(n),{refreshTokenOn401:!1,headers:{apikey:e}})})}getTextSuggestions(r){return v(this,arguments,function*(e,n={},o){if(yield this.preflight(),o==="sticky-messages")throw new Error("Use getPinnedMessages instead");return(yield this.client.post(`/api/v2/conversations/${e}/recommend/${o}`,ue(n),{abortLatest:!0})).map(i=>x(y({},z(i)),{text:i.text||i.url||i.message,source:o,type:o})).filter((i,a,d)=>a===d.findIndex(l=>l.text===i.text))})}isLoggedIn(){return v(this,null,function*(){return yield this.preflight(),this.client.validateToken()})}getAutocompleteSuggestions(e,n){return v(this,null,function*(){return yield this.preflight(),(yield this.client.post(`/api/v2/conversations/${e}/autocomplete`,ue(n),{abortLatest:!0})).map(r=>({score:1,source:r.source,sourceText:r.source_text,text:r.label,trainingJobs:r.training_jobs,searchKeywords:r.search_keywords,type:r.source})).filter((r,s,i)=>s===i.findIndex(a=>a.text===r.text))})}getPinnedMessages(e){return v(this,null,function*(){let n=yield this.client.get(`/api/v2/profiles/${e}/pinned-messages`,{abortLatest:!0});return z(n).map(o=>x(y({},o),{text:o.message,source:"sticky-messages",type:"pinned-message"}))})}getStyleSuggestions(e){return v(this,null,function*(){let n=yield this.client.post("/api/v2/style-suggestions",ue(e),{abortLatest:!0,version:"v2"});return z(n)})}search(e){return v(this,null,function*(){let n=yield this.client.post(`/api/v2/profiles/${e.profile}/search`,ue(e));return z(n)})}requestLoginByEmail(e){return v(this,null,function*(){yield this.preflight();let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:e});return z(n)})}requestPasswordlessToken(){return v(this,null,function*(){let e=yield this.client.get("/apis/admin/session/passwordless/request/");return z(e.token)})}getCsrfToken(){return v(this,null,function*(){let{token:e}=yield this.client.get("/apis/admin/session/csrf/");return e})}verifyLoginToken(e){return v(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/login/",{token:e});return z(n)})}evaluateAssistant(e,n){return v(this,null,function*(){var i;yield this.preflight();let o=new URLSearchParams;n!=null&&n.externalConversationId&&o.append("external_conversation_id",n.externalConversationId);let r=n!=null&&n.threadId?`/api/v2/assistants/${e}/threads/${n==null?void 0:n.threadId}/evaluate?${o.toString()}`:`/api/v2/assistants/${e}/evaluate?${o.toString()}`,s=yield this.client.post(r,{input:(i=n==null?void 0:n.input)!=null?i:{},conversation:n==null?void 0:n.transcript});return z(s)})}createAssistantThread(e){return v(this,null,function*(){yield this.preflight();let{assistantCode:n}=e,o=yield this.client.post(`/apis/admin/assistants/${n}/threads/`,{});return z(o)})}postMessageToAssistantThread(e){return v(this,null,function*(){yield this.preflight();let{assistantCode:n,threadId:o,message:r}=e,s=yield this.client.post(`/apis/admin/assistants/${n}/threads/${o}/messages/`,{content:r,role:"user"});return z(s)})}translateMessages(e){return v(this,null,function*(){yield this.preflight();let n=yield this.client.post("/api/v2/translate",ue(e));return z(n)})}handleDeepdeskVersionHeaders(e){e.headers.forEach((n,o)=>{let r=o.toLowerCase(),s=r.match(Xa);if(!n||!s)return;let i=s[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&n&&a!==n&&E.warn(`Overwritten Version header ${r}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[i]=n})}};mn.exchangeTokenPromise=null;var yt=mn;var Ms=class{constructor(e){this.options=e;this.socket=null;this.maxReconnectAttempts=5;this.reconnectInterval=25e3;this.cleanupCallbacks=[];var n,o;this.socket,this.eventListeners=new Map,this.url=e.url,this.maxReconnectAttempts=(n=e.maxReconnectAttempts)!=null?n:this.maxReconnectAttempts,this.reconnectInterval=(o=e.reconnectInterval)!=null?o:this.reconnectInterval,this.shouldReconnect=e.shouldReconnect}connect(){let e=()=>this.cleanup();window.addEventListener("beforeunload",e),this.cleanupCallbacks.push(()=>window.removeEventListener("beforeunload",e)),this.reconnect()}setupListeners(){this.socket&&(this.socket.onmessage=e=>{var n;try{let o=z(JSON.parse(e.data));o.event&&this.eventListeners.has(o.event)&&((n=this.eventListeners.get(o.event))==null||n.forEach(r=>r(o.data)))}catch(o){console.error("Error parsing WebSocket message:",o)}},this.socket.onclose=e=>{console.log("WebSocket connection closed:",e),setTimeout(()=>{this.reconnect()},this.reconnectInterval)},this.socket.onerror=e=>{console.error("WebSocket error:",e)})}reconnect(){var e,n;if(this.maxReconnectAttempts<=0){console.error("Max reconnect attempts reached, closing WebSocket connection."),(e=this.socket)==null||e.close();return}if(!this.shouldReconnect()){console.error("Should not reconnect, closing WebSocket connection."),(n=this.socket)==null||n.close();return}this.socket&&(this.socket.onmessage=null,this.socket.onclose=null,this.socket.onerror=null,this.socket.close()),this.socket=new WebSocket(this.url),this.setupListeners(),this.maxReconnectAttempts--}send(e,n){if(!this.socket){console.error("WebSocket connection is not open.");return}this.socket.send(JSON.stringify({event:e,data:n}))}on(e,n){this.eventListeners.has(e)||this.eventListeners.set(e,[]);let o=this.eventListeners.get(e);o&&!o.includes(n)&&o.push(n)}close(){var e;(e=this.socket)==null||e.close()}cleanup(){this.close(),this.cleanupCallbacks.forEach(e=>e()),this.cleanupCallbacks=[]}};var _s=require("@reduxjs/toolkit");var gp=require("@reduxjs/toolkit");var pp={startTime:null,stopTime:null},mp=t=>t.handlingTime,fp=(0,gp.createSlice)({name:"handlingTime",initialState:pp,reducers:{handlingTimeStart(t){if(t.startTime&&!t.stopTime)throw new Error("Timing already started");t.startTime=new Date,t.stopTime=null},handlingTimeStop(t){if(!t.startTime)throw new Error("Timing not started");t.stopTime=new Date},handlingTimeReset(t){t.startTime=null,t.stopTime=null}},extraReducers:t=>{t.addCase(J,()=>pp)}}),{handlingTimeStart:hp,handlingTimeStop:Ns,handlingTimeReset:yp}=fp.actions,vp=fp.reducer;var xp=(t={})=>{let e=y({onAuthError:Sn(!1)},t);return n=>o=>r=>("error"in r&&r.error.message==="Unauthorized"&&n.dispatch(e.onAuthError),o(r))};var Ds=require("@reduxjs/toolkit");var Os={list:{keywordMatches:[]},fetchState:"idle"};var fn=(0,Ds.createAsyncThunk)("styleSuggestions/getAll",(n,o)=>v(null,[n,o],function*({text:t},e){var d;let{deepdeskAPI:r}=e.extra,s=e.getState(),{showStyleSuggestions:i}=s.settings,a=(d=s.conversation.current)==null?void 0:d.profileCode;if(!i)return Os.list;if(!a)throw new Error("No current conversation to fetch pinned messages");return r.getStyleSuggestions({profileCode:a,message:t})})),_h=(0,Ds.createSlice)({name:"styleSuggestions",initialState:Os,reducers:{},extraReducers:t=>{t.addCase(fn.pending,e=>{e.fetchState="loading"}).addCase(fn.rejected,e=>{e.fetchState="error"}).addCase(fn.fulfilled,(e,n)=>{e.fetchState="done",Ct(e.list,n.payload)||(e.list=n.payload)}).addCase(jt,e=>{e.list=Os.list}).addCase(J,()=>Os)}}),Sp=_h.reducer;var bp=(t={})=>{let e,n=!0,o=y({getStyleSuggestions:fn,debounce:500},t);return r=>s=>i=>{var f;let a=r.getState().input.text,d=s(i),l=r.getState();if(l.auth.isLoggedIn!==!0)return d;let{showStyleSuggestions:c}=l.settings;if(!((f=l.conversation.current)==null?void 0:f.id)||!c)return d;let{text:u}=l.input;return u===a&&!n||(clearTimeout(e),u==="")||(e=setTimeout(()=>{n=!1,r.dispatch(o.getStyleSuggestions({text:u}))},t.debounce)),d}};function Fh(t,e){return t.text===e.text&&t.selection.start===e.selection.start&&t.selection.end===e.selection.end}var Cp=(t={})=>{let e=y({getTextSuggestions:Be,getAutocompleteSuggestions:Ao,debounce:200,check:qe},t),n;return o=>r=>s=>{var m;let{input:i}=o.getState(),a=r(s),d=o.getState();if(d.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:l,showTabCompletion:c}=d.settings,p=(m=d.conversation.current)==null?void 0:m.id,u=s.type===is.toString();if(!p||!l&&!c)return a;let{input:f}=d;return Fh(f,i)&&!u||(clearTimeout(n),!e.check(d))||(n=setTimeout(()=>{let g=Cn(d);g===""?o.dispatch(e.getTextSuggestions("default")):o.dispatch(e.getAutocompleteSuggestions(g))},u?0:e.debounce)),a}};var Tp=fn.fulfilled.toString();function Hh(t,e){let n=new Set([...e.keywordMatches.map(r=>r.keyword)]),o=[];return n.forEach(r=>{let s=t.keywordMatches.filter(d=>d.keyword===r),i=e.keywordMatches.filter(d=>d.keyword===r),a=i.length-s.length;a<=0||o.push(...i.slice(0,a))}),o}var wp=t=>e=>n=>o=>{var l;if(o.type!==Tp){n(o);return}let r=e.getState().styleSuggestions.list;n(o);let s=e.getState(),i=s.styleSuggestions.list,a=(l=s.conversation)==null?void 0:l.current;if(r===i)return;let d=Hh(r,i);o.type===Tp&&d.length>0&&t.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:d}})};var Bh=(0,_s.combineReducers)({assistants:id,auth:ol,conversation:dl,contentTypes:Kd,passwordlessToken:Mu,entities:cc,handlingTime:vp,info:Ml,input:Cl,settings:cd,profile:$d,search:Hl,styleSuggestions:Sp,ui:Hc,textSuggestions:Sc});function Ep(t){return(0,_s.configureStore)({reducer:Bh,middleware:e=>{var o;let n=e({thunk:{extraArgument:{dynamicThunkObject:t.dynamicThunkObject,deepdeskAPI:t.deepdeskAPI}},serializableCheck:!1}).concat(xp()).concat(Cp({debounce:200})).concat(bp({debounce:500})).concat(wp(t.deepdeskAPI));return((o=t.middleware)!=null?o:[]).reduce((r,s)=>r.concat(s),n)},preloadedState:t.preloadedState})}var Uh=t=>{var e,n;return(n=(e=t==null?void 0:t.type)==null?void 0:e.toLowerCase())!=null?n:"unknown"},Kh=t=>e=>n=>o=>{var d,l;let r=e.getState(),s=Xt("inlineSuggestions")(r),i=Xt("autoSelectSuggestion")(r)||s;switch(o.type){case Sn.toString():{!o.payload&&t.emit("logout",void 0);break}case He.fulfilled.toString():o.payload.length>0&&t.sendEvent("entities found",{conversationId:(d=r.conversation.current)==null?void 0:d.id,data:{entities:o.payload}});break;case jt.toString():t.logSendMessage(o.payload);break;case Lr.toString():t.emit("call-to-action",{cue:o.payload});break;case We.fulfilled.toString():o.isBroadcasted||t.broadcast(ni,o,!1);break;default:break}let a=n(o);switch(o.type){case jt.toString():t.handleAfterSendMessage(o.payload);break;case No.toString():t.onUpdateShowTabHint(o.payload);break;case Ns.toString():t.logHandlingTime();break;case wn.toString():t.broadcast(vr,o);break;case Vt.toString():t.broadcast(vr,o);break;case Ar.toString():e.dispatch(Vt({source:"assistant",assistantCode:o.payload.code}));break;case"analytics/logEvent/fulfilled":{let c=r.assistants.cues.find(p=>p.code===o.meta.arg.data.assistantCode);t.emit("event",x(y({},o.meta.arg),{cue:c}));break}case ye.toString():{let{start:c,end:p}=r.input.selection;t.emit("select-suggestion",x(y({type:Uh(o.payload.suggestion)},o.payload),{replace:o.payload.replace==="selection"?{start:c,end:p}:{start:0,end:p}})),s&&e.dispatch(Tt([]));break}case ur.toString():t.emit("select-image",o.payload),t.sendEvent("Image attached",{conversationId:(l=r.conversation.current)==null?void 0:l.id,data:{path:o.payload.suggestion.image,title:o.payload.suggestion.title}});break;case Tt.toString():{i&&o.payload.length>0&&e.dispatch(pr(0));break}default:break}return a},kp=Kh;var Rp=require("@reduxjs/toolkit");function ha(t){return t.toISOString().replace("T"," ").replace("Z","")}var zh=(t,e)=>e.version,Pp=(0,Rp.createSelector)([En,ze,mp,zh],(t,e,n,o)=>{if(!e)return E.warn("No conversationId for handling time metrics"),null;let{startTime:r,stopTime:s}=n;return!r||!s?(E.warn("No startTime and stopTime for handling time metrics"),null):{conversationId:e,clientVersion:o,agentId:t==null?void 0:t.agentId,agentName:t==null?void 0:t.agentName,agentEmail:t==null?void 0:t.agentEmail,timeStart:ha(r),timeStop:ha(s)}});function Ip(t,e){let{text:n,metrics:{numPaste:o,pastes:r,textSuggestions:s}}=t.input,i=n.length;return{source:"agent",clientVersion:e.version,pastes:r,lenTextTotal:i,numPastes:o,suggestions:s}}var qo=class extends Error{};function Wh(){let t,e;return{promise:new Promise((o,r)=>{t=o,e=r}),resolve:t,reject:e}}var Fs=class{constructor(){this.queues={}}push(e,n){let o=()=>{let s=this.queues[e][1];s?(this.queues[e]=[s.promise,null],s.resolve()):delete this.queues[e]};if(!this.queues[e]){let s=n().finally(o);return this.queues[e]=[s,null],s}this.queues[e][1]&&this.queues[e][1].reject(new qo("Queued async function is outdated"));let r=Wh();return this.queues[e][1]=r,r.promise.then(()=>n().finally(o))}};function ya(t,e){var s;let n=t.closest(e);if(n)return n;let o=t.getRootNode().host;if(o instanceof HTMLElement)return ya(o,e);let r=(s=t.ownerDocument.defaultView)==null?void 0:s.frameElement;return r?ya(r,e):null}function va(t,e){return ya(t,e)}var Vh={accepted:"onConversationAcceptedAssistants","new-message":"onConversationNewMessageAssistants",ended:"onConversationEndedAssistants"},Lp=(t,e)=>{var r,s,i;if(!((i=(s=(r=t.uiConfig)==null?void 0:r.widget)==null?void 0:s.types.find(a=>a.type==="cues"))==null?void 0:i.isActive))return E.warn("Triggered a conversation assistant, but cues are not configured in widget."),[];let o=t[Vh[e]];return o&&o.length>0?o.map(a=>a.code):(E.warn(`No assistant set in profile for conversation event "${e}"`),[])};function Ap(t){return typeof t=="object"&&t!==null&&"name"in t&&"message"in t}function jh(t){return typeof t=="object"&&t!==null&&"tagName"in t}function Hs(t){return jh(t)&&(ln(t)||fs(t))}var Np,Qe=new Map,$h=["bottom","height","left","right","top","width"],Mp=(t,e)=>!t&&!e?!1:t&&!e||!t&&e?!0:$h.some(n=>t[n]!==e[n]);function Op(t){var n,o,r;if(t.ownerDocument===document)return[];let e=(r=(o=(n=t.ownerDocument)==null?void 0:n.defaultView)==null?void 0:o.frameElement)!=null?r:null;return e?[e,...Op(e)]:[]}function Dp(t,e){return!t||!e?null:x(y({},t),{top:t.top+e.top,left:t.left+e.left})}var Bs=!1,_p=()=>{Bs=!0;let t=[];if(Qe.forEach((e,n)=>{if(!n.isConnected){e.rect=null,t.push(e),Qe.delete(n);return}let o=n.getBoundingClientRect();Mp(o,e.rect)&&(e.rect=o,t.push(e))}),t.forEach(e=>{let n=e.parentRects?e.parentRects.reduce(Dp,e.rect):e.rect;Mp(n,e.totalRect)&&e.callbacks.forEach(o=>o(n)),e.totalRect=n}),Qe.size===0){Bs=!1;return}Np=window.requestAnimationFrame(_p)};function xa(t,e){let n=Op(t),o=[],r=n.map((s,i)=>xa(s,a=>{o[i]=a;let d=Qe.get(t);if(!d)return;let l=o.reduce(Dp,d.rect);d.callbacks.forEach(c=>c(l))}));return{observe(s=!0){if(r.forEach(i=>i.observe(!1)),Qe.has(t)){let i=Qe.get(t);i.callbacks.push(e),i.rect&&e(i.rect)}else Qe.set(t,{rect:void 0,callbacks:[e],parentRects:o});s&&!Bs&&_p()},unobserve(){r.forEach(i=>i.unobserve());let s=Qe.get(t);if(s){let i=s.callbacks.indexOf(e);i>=0&&s.callbacks.splice(i,1),s.callbacks.length||Qe.delete(t),Qe.size||(cancelAnimationFrame(Np),Bs=!1)}}}}var Fp,Ze=new Map,Hp=()=>{Ze.forEach((t,e)=>{if(!e.isConnected){Ze.delete(e);return}let{clientHeight:n,scrollHeight:o}=e,r=o>n;t.visible!==r&&(t.visible=r,t.callbacks.forEach(s=>s(t.visible)))}),Ze.size!==0&&(Fp=window.requestAnimationFrame(Hp))};function Bp(t,e){return{observe(){let n=Ze.size===0;Ze.has(t)?Ze.get(t).callbacks.push(e):Ze.set(t,{visible:void 0,callbacks:[e]}),n&&Hp()},unobserve(){let n=Ze.get(t);if(n){let o=n.callbacks.indexOf(e);o>=0&&n.callbacks.splice(o,1),n.callbacks.length||Ze.delete(t),Ze.size||cancelAnimationFrame(Fp)}}}}var Sa=["borderLeftWidth","borderRightWidth","borderTopWidth","borderBottomWidth","borderStyle","boxSizing","color","overflowWrap","fontFamily","fontSize","fontSizeAdjust","fontStretch","fontWeight","fontKerning","lineHeight","letterSpacing","paddingLeft","paddingTop","paddingRight","paddingBottom","width","height","textIndent","whiteSpace","wordBreak","wordSpacing","wordWrap"];function ba(t,e,n){return n.forEach(o=>{e.style[o]=t[o]})}function qn(t){return Number.parseFloat(t)}function Us(t){return Math.round(t*1e6)}function Up(t){return t/1e6}function Ca(t,e,n){if(t.boxSizing==="content-box")return;let{clientWidth:o}=e,r=qn(t.width),s=qn(t.borderLeftWidth),i=qn(t.borderRightWidth),a=qn(t.paddingRight),d=Up(Us(r)-Us(s)-Us(i)),l=Up(Us(o));if(d-l>2){let c=d-l;n.style.paddingRight=`${a+c}px`}}function Xo(t,e={}){var c,p;let n=e.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=(c=e.position)!=null?c:"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",Jt(n);let o=window.getComputedStyle(t),r=!0,s=()=>{n.scrollTop=t.scrollTop};ba(o,n,Sa),Ca(o,t,n),e.mirrorOverflow&&(n.style.overflow="hidden",t.addEventListener("scroll",s));let i=Bp(t,()=>{ba(o,n,Sa),Ca(o,t,n),s(),setTimeout(s,0)}),a,d=!0,l=xa(t,u=>{if(u===null){e.onRemove&&e.onRemove(),n.remove();return}if(!d&&e.onMoveStart&&(Promise.resolve().then(()=>e.onMoveStart()),d=!0),clearTimeout(a),a=setTimeout(()=>{e.onMoveEnd&&e.onMoveEnd(),d=!1},200),u.height===0&&u.width===0){if(r===!0)return;e.onHide&&e.onHide(),n.style.display="none",r=!0;return}if(ba(o,n,Sa),Ca(o,t,n),s(),e.placement==="below"&&n.classList.add("below"),n.style.top=`${u.top}px`,n.style.left=`${u.left}px`,e.closestScrollElement&&e.closestScrollElement!==t){let f=e.closestScrollElement.getBoundingClientRect(),h=window.getComputedStyle(e.closestScrollElement),m=qn(h.borderTopWidth),g=qn(h.borderBottomWidth),b=f.top+m-u.top,T=u.top+u.height+-(f.top+f.height-g);n.style.clipPath=`inset(${b}px 0px ${T}px 0px)`}r&&(n.style.display="block",e.onShow&&e.onShow(),r=!1)});return e.appendTo?e.appendTo.appendChild(n):(p=t.parentElement)==null||p.appendChild(n),l.observe(),i.observe(),[n,()=>{t.removeEventListener("scroll",s),l.unobserve(),i.unobserve(),n.remove()}]}function Gh(t){return t.offsetParent!==null}function Kp(t){if(!Gh(t))return!1;let e=t.getBoundingClientRect();return e.top>=0&&e.left>=0&&e.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&e.right<=(window.innerWidth||document.documentElement.clientWidth)}function Ks(t,e,n=100){let o=Kp(t);e({isVisible:o});let r=setInterval(()=>{let s=Kp(t);s!==o&&(o=s,e({isVisible:o}))},n);return()=>{clearTimeout(r)}}var zp=(t,e)=>({value(){try{let n=sessionStorage.getItem(`dd-${t}`);if(!n)return e;try{return JSON.parse(n)}catch(o){return e}}catch(n){return e}},update(n){try{sessionStorage.setItem(`dd-${t}`,JSON.stringify(n))}catch(o){E.warn("[Deepdesk] SessionStorage is blocked by browser")}}});var H=require("react/jsx-runtime");var Wp=zp("showTabHint",!0),Xn=class Xn{constructor({deepdeskUrl:e,version:n=Xn.version||"unknown",locale:o="en-US",token:r,fetch:s,productName:i,createCustomChannel:a,websocketClient:d=Ms}){this.inputMediator=null;this.eventListeners={};this.unmountHandlers=[];this.disposeHandlers=[];this.inlineSuggestions=null;this.aboveSuggestions=null;this.belowSuggestions=null;this.floatingMenu=null;this.widgetElement=null;this.widgetRoot=null;this.nicknameDialogUnsubscribe=null;this.nicknameDialogFailed=!1;this.dynamicThunkObject={};this.queues=new Fs;this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;let l=e.replace(/\/api$/,"");this.deepdeskApi=new yt(l,{token:r,fetch:s}),this.version=n,this.instanceId=Xn.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[kp({broadcast:(h,m,g)=>{this.broadcastEvents.send(h,m,g)},emit:(h,m)=>this.emit(h,m),handleAfterSendMessage:h=>this.handleAfterSendMessage(h),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:h=>this.logSendMessage(h),onUpdateShowTabHint:h=>Wp.update(h),sendEvent:(h,m)=>this.deepdeskApi.sendEvent(h,m)})]};this.store=Ep(c),this.broadcastEvents=new cp({debug:!0,deepdeskUrl:l,eventMap:Bl(this.store),createCustomChannel:a}),this.disposeHandlers.push(()=>{this.broadcastEvents.cleanup()}),this.ws=new d({url:`${l}/api/v2/me/realtime`.replace("https","wss"),reconnectInterval:25e3,shouldReconnect:()=>v(this,null,function*(){var h;return(h=ne(this.state))!=null?h:!1})}),this.whenLoggedIn(()=>this.ws.connect()),this.store.dispatch(No(Wp.value())),this.store.dispatch(Mr({locale:o,adminUrl:l,productName:i}));let p=[],u=h=>{if(!h.conversationId)return;let m=()=>{this.conversationId()===h.conversationId&&this.store.dispatch(sd(h))};this.hasConversation()?m():p.push(m)};this.ws.on("assistants::direct_response",u),this.ws.on("assistants::user_notification",u),this.ws.on("assistants::response_chunk",h=>{if(!h.conversationId)return;let m=()=>{this.conversationId()===h.conversationId&&this.store.dispatch(rd(h))};this.hasConversation()?m():p.push(m)}),this.ws.on("assistants::suggest_as_reply",h=>{if(!h.conversationId)return;let m=()=>{this.conversationId()===h.conversationId&&this.store.dispatch(wn([{text:h.payload.message,type:"text",source:"assistant",assistantCode:h.code,sourceLabel:h.name}]))};this.hasConversation()?m():p.push(m)});let f=this.whenConversationLoaded(()=>{var h;this.broadcastEvents.setExternalId((h=this.state.conversation.current)==null?void 0:h.externalId),p.forEach(m=>m()),p.length=0});this.disposeHandlers.push(()=>{this.ws.cleanup(),p.length=0,f()})}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){var e;return(e=Wt(this.state)[this.state.input.selectedSuggestionIndex])!=null?e:null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}externalId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.externalId}shouldAbort(){return this.state.conversation.isSupported===!1?(E.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(E.warn("Profile has not been loaded (yet)"),!0):(E.warn("No conversation loaded (yet)"),!0)}whenLoggedIn(e){if(ne(this.state))e();else{let n=this.subscribe(ne,o=>{o&&e()});this.disposeHandlers.push(()=>{n()})}}login(){return this.store.dispatch(Sn(null)),this.store.dispatch(tt()),new Promise(e=>{this.whenLoggedIn(()=>e())})}isLoggedIn(){return v(this,null,function*(){return(yield this.store.dispatch(tt())).payload})}isConversationSupported(e,n){return v(this,null,function*(){return(yield this.store.dispatch(Xs({externalId:e,options:n}))).payload})}createConversation(e){return v(this,null,function*(){var o;return this.hasConversation()&&this.externalId()!==e.externalId&&this.resetConversation(),(yield this.store.dispatch(lr(x(y({},e),{metadata:(o=e.metadata)!=null?o:{}})))).payload})}getConversationByExternalId(e,n){return v(this,null,function*(){return this.hasConversation()&&this.externalId()!==e&&this.resetConversation(),(yield this.store.dispatch(dr({externalId:e,options:n}))).payload})}upsertConversation(e){return v(this,null,function*(){var o;return this.hasConversation()&&this.externalId()!==e.externalId&&this.resetConversation(),(yield this.store.dispatch(Js(x(y({},e),{metadata:(o=e.metadata)!=null?o:{}})))).payload})}postMessages(e){return v(this,null,function*(){yield this.store.dispatch(Qs(e))})}updateConversation(e){return v(this,null,function*(){return(yield this.store.dispatch(cr(e))).payload})}resetConversation(){this.store.dispatch(J()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}configure(e){this.store.dispatch(Mr(e))}setVisitorInfo(e){this.store.dispatch(Pl(e))}setCustomData(e){this.store.dispatch(Il(e))}setAgentInfo(e,n){return v(this,null,function*(){var r;yield this.store.dispatch(no(y(y({},e),n))),(r=this.state.info.agentInfo)!=null&&r.agentNickname||this.broadcastEvents.send(yr,{showNicknameDialog:!0})})}setAgentSettings(e){return v(this,null,function*(){yield this.store.dispatch(Ys(e))})}getAgentSettings(){return v(this,null,function*(){return(yield this.store.dispatch(ei())).payload})}refresh(){return v(this,null,function*(){if(this.shouldAbort())return Promise.resolve();let e=[];return e.push(this.refreshTextSuggestions()),e.push(this.refreshWidgetSuggestions()),Promise.all(e).then(()=>{})})}syncInputMediator(){this.inputMediator&&this.store.dispatch(gr({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()}))}notifyExternalSuggestion(e){this.store.dispatch(ye(e))}evaluateAssistant(e,n){return v(this,null,function*(){var d;let{input:o={},transcript:r,showCuesInWidget:s=!0,includeMetadata:i}=n||{},a=yield this.store.dispatch(We({assistantCode:e,transcript:r,includeMetadata:i,input:o,skipState:!s}));if(a.error)throw new Error(`Assistant evaluation failed: ${(d=a.payload)!=null?d:a.error.message}`);return a.payload.output})}evaluateConversationAssistant(e,n){return v(this,null,function*(){yield this.loadProfileConfig();let o=this.state.profile.data;if(!o){E.warn("Can't evaluate assistant when profile is not loaded yet.");return}let r=Lp(o,e);yield Promise.all(r.map(s=>this.queues.push(s,()=>v(this,null,function*(){yield this.evaluateAssistant(s,y({includeMetadata:!0},n))})).catch(i=>{if(i instanceof qo){E.warn(`Queued assistant "${s}" was outdated and dropped`);return}throw i})))})}handleKeyDown(e){let{overlayCollapsed:n,openOverlayWhenTyping:o}=this.state.ui,{textSuggestions:r,selectedSuggestionIndex:s,selection:i}=this.state.input,{inlineSuggestions:a,autoSelectSuggestion:d,showTextSuggestions:l,suggestionsPlacement:c}=this.settings,p=a||d,u=c==="inline"||c==="below"?"below":"above",f=r.length>0;if(this.store.dispatch(fl(Zs(e))),!qe(this.state)||e.key!=="Tab"&&!l)return;let h=()=>{n||!f||i&&(e.shiftKey||(this.store.dispatch(vl()),e.preventDefault()))},m=()=>{n||!f||p&&s<=0||i&&(e.shiftKey||(this.store.dispatch(xl()),e.preventDefault()))};switch(e.key){case"ArrowUp":u==="below"?m():h();break;case"ArrowDown":{u==="below"?h():m();break}case"Escape":{n||(this.store.dispatch(pr(-1)),this.store.dispatch(Lt({collapse:!0})),this.store.dispatch(_c(!0)),e.preventDefault());break}case"Tab":{e.preventDefault();let g=Tn(this.state);if(!g)return;this.store.dispatch(No(!1)),this.store.dispatch(ye({text:g.text,suggestion:g,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(p||this.state.input.selectedSuggestionIndex===-1)return;let g=Tn(this.state);if(!g)return;this.store.dispatch(ye({text:g.text,suggestion:g,eventMetrics:{inputType:"space"},replace:"until-selection-end"}));break}case"Enter":{if(p||e.shiftKey||this.state.input.selectedSuggestionIndex===-1)return;let g=Tn(this.state);if(!g)return;this.store.dispatch(ye({text:g.text,suggestion:g,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),e.preventDefault();break}default:}n&&o&&this.store.dispatch(Lt({collapse:!1}))}handleAfterSendMessage(e){this.emit("send-message",e),this.store.dispatch(Tt([]))}handlingTimeStart(){this.state.handlingTime.startTime||(E.info("Start handling time"),this.store.dispatch(hp()))}handlingTimeStop(){this.state.handlingTime.startTime&&(E.info("Stop handling time"),this.store.dispatch(Ns()))}logSendMessage(e){let n=Ip(this.state,{version:this.version});n&&(e&&(Object.assign(n,{text:e}),Object.assign(n,{lenTextTotal:e.length})),this.deepdeskApi.sendEvent("Send Message",{conversationId:this.conversationId(),data:n}),this.emit("send-message-event",n))}logHandlingTime(){let e=Pp(this.state,{version:this.version});e&&(this.deepdeskApi.sendEvent("Handling Time",{conversationId:this.conversationId(),data:e}),this.store.dispatch(yp()))}notifySubmit(e={}){var n;this.shouldAbort()||(this.store.dispatch(jt((n=e.text)!=null?n:this.state.input.text)),this.store.dispatch(bl()))}emit(e,n){let o=this.eventListeners[e];o&&o.forEach(r=>{try{r(n)}catch(s){E.warn(`The following error occurred in deepdeskSDK.on('${e}', handler)`),E.error(s)}})}on(e,n){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(n),()=>{this.off(e,n)}}off(e,n){if(!e&&!n){this.eventListeners={};return}let o;this.eventListeners[e]&&(o=this.eventListeners[e].indexOf(n),o>-1&&this.eventListeners[e].splice(o,1))}setConversationQuery(e){this.dynamicThunkObject.conversationQuery=e}setPlatformVariables(e){this.store.dispatch(Ll(e))}whenConversationLoaded(e){let n=s=>{var i;return(i=s.conversation.current)==null?void 0:i.id},o=()=>this.loadProfileConfig().then(()=>e());return n(this.state)&&o(),this.subscribe(n,s=>{s&&o()})}overlayContainerFactory(e,n,o,r){let[s,i]=Xo(n,o);return s.setAttribute("translate","no"),s.dataset.testid=e,r&&s.classList.add(r),[s,i]}createInlineContainer(e,n){var a;let o=document.createElement("div");o.style.position="absolute",o.style.top="0px",o.style.left="0px",o.style.height="0px",o.style.width="0px";let r=document.createElement("div");r.style.display="none",r.style.position="absolute",r.style.height="0px",r.style.width="0px",r.style.backgroundColor="red",o.appendChild(r);let s=(a=e.ownerDocument.defaultView)==null?void 0:a.frameElement,i=s?s.ownerDocument.defaultView:null;if(s&&(i===window||(i==null?void 0:i.parent)===window)){let[d,l]=Xo(s,{appendTo:document.body,onMoveStart:()=>{r.style.display="none"}});d.dataset.testid=n,d.style.zIndex="2",d.appendChild(o),this.unmountHandlers.push(()=>{l()})}else document.body.appendChild(o);return r}createContainer(e,n=document.body){let o=window.getComputedStyle(n),r=document.createElement("div");return Jt(r),r.dataset.testid=e,r.style.color=o.color,r.style.fontSize=o.fontSize,r.style.fontFamily=o.fontFamily,r.style.fontVariant=o.fontVariant,r.setAttribute("translate","no"),n.appendChild(r),r}storeMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,n=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(e,n),E.info(`Stored analytics for ${this.conversationId()}`)}catch(e){}}restoreMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,n=window.sessionStorage.getItem(e);if(!n)return;let o=JSON.parse(n);o.text.trim()===this.state.input.text.trim()?(E.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(Sl(o.metrics))):E.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(e)}catch(e){}}mount(e,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!Hs(e))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let u=n,{customStyles:o,closestScrollSelector:r,floatingMenuParent:s,appendOverlayTo:i,inputMediator:a}=u,d=M(u,["customStyles","closestScrollSelector","floatingMenuParent","appendOverlayTo","inputMediator"]),l={customStyles:o,closestScrollSelector:r,floatingMenuParent:s,appendOverlayTo:i};this.configure(d),this.settings.automaticHandlingTime&&this.setupHandlingTime(e),Jt(e),this.inputMediator=a||(ln(e)?new un(e):new cn(e)),this.inputMediator.on("change",({plainText:f,rawHTML:h})=>{this.store.dispatch(gr({text:f,html:h}))}),this.inputMediator.on("keyup",f=>{this.store.dispatch(hl(Zs(f)))}),this.inputMediator.on("keydown",f=>{this.handleKeyDown(f)}),this.inputMediator.on("paste",({pastedText:f,selectionText:h})=>{this.store.dispatch(yl({text:f,selectionText:h}))}),this.inputMediator.on("cut",({selectionText:f})=>{this.store.dispatch(ml(f))});let c;this.inputMediator.on("selection",f=>{clearTimeout(c),f===null?c=setTimeout(()=>{f!==null&&this.store.dispatch(mr(f))},500):this.store.dispatch(mr(f))}),this.unmountHandlers.push(()=>{clearTimeout(c)}),this.inputMediator.on("disabled",()=>{var f;(f=this.inputMediator)==null||f.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{this.settings.detectSubmit&&this.notifySubmit()}),this.inputMediator.on("blur",()=>{this.store.dispatch(cs(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(cs(!0))}),this.renderSuggestions(e,l),this.subscribe(Xt("inlineSuggestions"),()=>{this.renderSuggestions(e,l)}),this.subscribe(Xt("suggestionsPlacement"),()=>{this.renderSuggestions(e,l)});let p=this.renderOverlays(n);this.unmountHandlers.push(()=>{p.unmount()}),this.store.dispatch(gr({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()})),this.store.dispatch(mr(this.inputMediator.getSelection())),this.store.dispatch(cs(this.inputMediator.isFocused)),this.unmountHandlers.push(()=>{this.state.input.text!==""&&this.storeMetrics()}),this.whenConversationLoaded(()=>{this.restoreMetrics(),this.syncInputMediator(),this.refreshTextSuggestions(),this.promptForNickname()}),this.isMounted=!0}promptForNickname(e){if(this.nicknameDialogUnsubscribe||this.nicknameDialogFailed)return;let n=this.createContainer("nickname-dialog",document.body);document.body.appendChild(n);let o=(0,vt.createRoot)(n),r=null,s=a=>{r=a,i()},i=()=>{o==null||o.render((0,H.jsx)(ut,{store:this.store,children:(0,H.jsx)(ot,{broadcastEvents:this.broadcastEvents,children:(0,H.jsx)(Jc,{id:"deepdesk-nickname-dialog",error:r,onSave:a=>v(this,null,function*(){try{yield this.store.dispatch(kl({agentNickname:a})).unwrap(),console.log("setAgentNickname",a),this.broadcastEvents.send(yr,{showNicknameDialog:!1}),this.nicknameDialogUnsubscribe&&this.nicknameDialogUnsubscribe()}catch(d){E.error("Error setting agent nickname",d),s("error"),this.nicknameDialogFailed=!0}})})})}))};i(),this.nicknameDialogUnsubscribe=()=>{o.unmount(),n.remove(),this.nicknameDialogUnsubscribe=null}}subscribe(e,n){let o=e(this.store.getState());return this.store.subscribe(()=>{let r=e(this.store.getState());r!==o&&(o=r,n(o))})}unmount(){var e,n,o,r,s;(e=this.inlineSuggestions)==null||e.unmount(),(n=this.aboveSuggestions)==null||n.unmount(),(o=this.belowSuggestions)==null||o.unmount(),(r=this.floatingMenu)==null||r.unmount(),this.unmountHandlers.forEach(i=>i()),this.unmountHandlers=[],(s=this.inputMediator)==null||s.dispose(),this.nicknameDialogUnsubscribe&&this.nicknameDialogUnsubscribe(),this.isMounted=!1}dispose(){this.unmount(),this.unmountWidget(),this.disposeHandlers.forEach(e=>e()),this.disposeHandlers=[],this.off()}renderSuggestions(e,n){var o,r,s,i;(o=this.floatingMenu)==null||o.unmount(),(r=this.inlineSuggestions)==null||r.unmount(),(s=this.aboveSuggestions)==null||s.unmount(),(i=this.belowSuggestions)==null||i.unmount(),this.settings.floatingMenu&&(this.floatingMenu=this.renderFloatingMenu(e,n)),this.settings.inlineSuggestions||this.settings.suggestionsPlacement==="inline"?this.inlineSuggestions=this.renderInlineSuggestions(e,n):this.settings.suggestionsPlacement==="below"?this.belowSuggestions=this.renderAboveOrBelowSuggestions(e,n,"below"):this.aboveSuggestions=this.renderAboveOrBelowSuggestions(e,n,"above")}renderInlineSuggestions(e,n){let{customStyles:o}=n,r=this.createInlineContainer(e,"deepdesk-caret"),s=(0,vt.createRoot)(r);s.render((0,H.jsx)(ut,{store:this.store,customStyles:o,children:(0,H.jsx)(ot,{broadcastEvents:this.broadcastEvents,children:(0,H.jsx)(Gc,{})})}));let i=a=>{a?(r.style.display="block",r.style.top=`${a.top}px`,r.style.left=`${a.left}px`):r.style.display="none"};return this.inputMediator.on("caretposition",i),{unmount:()=>{var a;(a=this.inputMediator)==null||a.off("caretposition",i),s.unmount(),r.remove()}}}renderAboveOrBelowSuggestions(e,n,o){let{customStyles:r,closestScrollSelector:s,appendOverlayTo:i}=n,a=s&&va(e,s)||void 0,[d,l]=this.overlayContainerFactory("deepdesk-tab-completion",a||e,{appendTo:i,closestScrollElement:a,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),[c,p]=this.overlayContainerFactory("deepdesk-suggestions-overlay",a||e,{appendTo:i,placement:o},r==null?void 0:r.suggestionsRootNode),u=(0,vt.createRoot)(d);u.render((0,H.jsx)(ut,{store:this.store,customStyles:r,children:(0,H.jsx)(ot,{broadcastEvents:this.broadcastEvents,children:(0,H.jsx)(Iu,{inputElement:e})})}));let f=(0,vt.createRoot)(c);return f.render((0,H.jsx)(ut,{store:this.store,customStyles:r,children:(0,H.jsx)(ot,{broadcastEvents:this.broadcastEvents,children:(0,H.jsx)(au,{onLogIn:()=>this.loginViaPopup().catch(h=>E.warn(h.message))})})})),{unmount(){u.unmount(),f.unmount(),l(),p()}}}renderFloatingMenu(e,n){let{customStyles:o,closestScrollSelector:r,appendOverlayTo:s,floatingMenuParent:i}=n,a=r&&va(e,r)||void 0,[d,l]=this.overlayContainerFactory("floating-menu",a||e,{appendTo:i!=null?i:s},o==null?void 0:o.floatingMenuParent),c=(0,vt.createRoot)(d);return c.render((0,H.jsx)(ut,{store:this.store,customStyles:o,children:(0,H.jsx)(ot,{broadcastEvents:this.broadcastEvents,children:(0,H.jsx)(Nc,{onLogIn:()=>this.loginViaPopup().catch(p=>E.warn(p.message))})})})),{unmount(){c.unmount(),l()}}}renderOverlays(e){let{customStyles:n}=e,o=this.createContainer("deepdesk-overlays"),r=(0,vt.createRoot)(o);return r.render((0,H.jsx)(ut,{store:this.store,customStyles:n,children:(0,H.jsx)(ot,{broadcastEvents:this.broadcastEvents,children:(0,H.jsx)(kc,{})})})),{unmount(){r.unmount(),o.remove()}}}renderWidget(e,n={}){if(this.widgetElement&&E.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:o,showImages:r,isEmbedded:s}=n;this.widgetElement=e,this.configure({showImages:r,isEmbedded:s}),this.widgetRoot=(0,vt.createRoot)(e),this.widgetRoot.render((0,H.jsx)(ut,{store:this.store,customStyles:o,children:(0,H.jsx)(ot,{broadcastEvents:this.broadcastEvents,children:(0,H.jsx)(rp,{assistantOptions:n.assistantOptions,knowledgeAssistOptions:n.knowledgeAssist,onLogIn:()=>this.loginViaPopup().catch(i=>E.warn(i.message))})})}))}unmountWidget(){var e,n;(n=(e=this.widgetRoot)==null?void 0:e.unmount)==null||n.call(e),this.widgetRoot=null,this.widgetElement=null}renderKnowledgeAssistantWidget(e,n,o={}){let{customStyles:r,initialQuestion:s}=o,i=(0,vt.createRoot)(n);return i.render((0,H.jsx)(ut,{store:this.store,customStyles:r,children:(0,H.jsx)(ot,{broadcastEvents:this.broadcastEvents,children:(0,H.jsx)(la,{children:(0,H.jsxs)(Vr,{assistantCode:e,initialQuestion:s,evaluateKnowledgeAssistFn:yo,children:[(0,H.jsx)(yn,{children:(0,H.jsx)($r,{title:o.title,emptyState:o.emptyState})}),(0,H.jsx)(aa,{children:(0,H.jsx)(jr,{})})]})})})})),{unmount(){i.unmount()}}}setupHandlingTime(e){let n=Ks(e,({isVisible:o})=>{o?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){Ap(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(()=>v(this,null,function*(){yield this.store.dispatch(bo());let e=Yt(this.state);e&&this.store.dispatch(Mr({showSearch:e.search,showImageSearch:e.imageSearch,showEntitiesCommand:e.entitiesCommand,showSummaryCommand:!!e.summarizerAssistantNew,showKnowledgeSearch:!!e.knowledgeAssistantNew||!!e.knowledgeAssistant,recommendTextSuggestions:e.recommendTextSuggestions}))})),this.loadProfileConfigPromise)}loginViaPopup(e){return v(this,null,function*(){return new Promise((n,o)=>{this.store.dispatch(ar());let r=new MessageChannel,s=r.port1,i=this.settings.adminUrl,a=new URL(e!=null&&e.url?e==null?void 0:e.url:`${i}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let d=!1,l=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",p),clearInterval(u)};s.onmessage=f=>v(this,null,function*(){var h,m;if((h=f.data)!=null&&h.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((m=f.data)==null?void 0:m.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(ro),d=!0,r.port1.close(),n()}catch(g){console.error(g),o(g)}finally{d=!0,l()}});let c=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");c===null&&o(new Error("Popup blocked by browser"));let p=f=>v(this,null,function*(){var h;if(f.origin===a.origin)switch((h=f.data)==null?void 0:h.type){case"deepdesk-popup-request-origin":{try{let m=JSON.stringify({type:"deepdesk-popup-parent-origin"});c==null||c.postMessage(m,a.origin)}catch(m){E.error("Error posting message to popup",m),o(m)}break}case"deepdesk-popup-loaded":{try{let m=JSON.stringify({type:"deepdesk-popup-create-channel"});c==null||c.postMessage(m,a.origin,[r.port2])}catch(m){E.error("Error posting message to popup",m),o(m)}break}case"deepdesk-popup-error":{if(l(),f.data.message==="Platform account url mismatch"){let m=`Please contact your administrator: The platform account url (${f.data.targetOrigin}) is misconfigured as it differs from the origin of the page that opened the popup (${f.data.openerOrigin}).`;E.warn(m),this.store.dispatch(qs(m)),o(new Error(m))}if(f.data.message==="Timeout"){let m="Please contact your administrator: Popup timed out. Check if the account's platform url is configured correctly.";E.warn(m),this.store.dispatch(qs(m)),o(new Error(m))}o(new Error(f.data.message));break}}});window.addEventListener("message",p);let u=setInterval(()=>{c&&!c.closed||(l(),d||o(new Error("Popup closed by user")))},200);this.disposeHandlers.push(l)})})}translateMessages(e){return this.deepdeskApi.translateMessages(e)}refreshTextSuggestions(){return v(this,null,function*(){this.isMounted&&(yield this.store.dispatch(is()))})}refreshWidgetSuggestions(){return v(this,null,function*(){if(!this.widgetRoot)return;let{uiConfig:e}=this.state.profile.data;if(!e.widget)return;let n=Co(this.state);try{n.forEach(({type:o})=>{switch(o){case"entities":this.store.dispatch(He());break;case"pinned-messages":case"sticky-messages":break;default:ir.includes(o)||this.store.dispatch(Be(o))}})}catch(o){this.handleError(o)}})}};Xn.version="19.2.0",Xn.count=0;var Jo=Xn;function qh(t){return v(this,null,function*(){var r,s,i;let n=yield((r=t.fetch)!=null?r:window.fetch)(t.url),o=yield n.blob();return new File([o],t.name,{type:(i=(s=t.mimeType)!=null?s:n.headers.get("Content-Type"))!=null?i:"image/jpeg"})})}function Vp(t,e){return v(this,null,function*(){let n=yield qh(e),o=new Event("change",{bubbles:!0,cancelable:!0});try{Object.defineProperty(t,"files",{configurable:!0,get:()=>[n]}),t.dispatchEvent(o)}finally{Object.hasOwn(t,"files")&&delete t.files}})}function jp(t,e,n){return v(this,null,function*(){yield new yt(t).authenticateWithKey(e,n)})}function $p(t){return t.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function Gp(o,r){return v(this,arguments,function*(t,e,n={}){var p,u;let{value:s}=t,{start:i,end:a}=(p=n.replace)!=null?p:{start:0,end:s.length},d=`${s.slice(0,i)}${e}${s.slice(a)}`,l=(u=n.selectionAfter)!=null?u:{start:i+e.length,end:i+e.length},c=()=>{if(n.setValue)return n.setValue(d);t.value=d};return Promise.resolve(c()).then(()=>{t.selectionStart=l.start,t.selectionEnd=l.end,t.blur(),t.focus()})})}function qp(o,r){return v(this,arguments,function*(t,e,n={}){let s=n.replace?_t(t,n.replace.start,n.replace.end):$n(t),i,a=()=>{if(n.setRange)return n.setRange(s.cloneRange());s.deleteContents(),i=document.createElement("span"),s.insertNode(i),n.insertBRs!==!1?e.split(`
11
11
  `).reverse().forEach((d,l)=>{l>0&&s.insertNode(document.createElement("br")),s.insertNode(document.createTextNode(d))}):s.insertNode(document.createTextNode(e))};return Promise.resolve(a()).then(()=>{try{if(n.selectionAfter!==!1){t.focus();let d=n.selectionAfter?_t(t,n.selectionAfter.start,n.selectionAfter.end):(s.collapse(!1),s),l=window.getSelection();l==null||l.removeAllRanges(),l==null||l.addRange(d)}if(!i)return;i.scrollIntoView&&i.scrollIntoView({block:"nearest",inline:"nearest"})}finally{i&&i.remove()}})})}function Xh(t){let e=document.createElement("template");return e.innerHTML=t.replace(/(\[([^\]]+)])\(([^)]+)\)/g,'<a href="$3" target="_blank" rel="noopener noreferrer">$2</a>'),e.content}function Jh(t){let e=document.createDocumentFragment();return t.split(`
12
12
  `).forEach((n,o)=>{o>0&&e.appendChild(document.createElement("br"));let r={index:0},s=0;for(;r=n.slice(s).match(/(\[([^\]]+)])\(([^)]+)\)/);){let i=document.createElement("a");i.href=r[3],i.setAttribute("target","_blank"),i.setAttribute("rel","noopener noreferrer"),i.appendChild(document.createTextNode(r[2])),e.appendChild(document.createTextNode(n.slice(s,s+r.index))),e.appendChild(i),s=s+r.index+r[0].length}e.appendChild(document.createTextNode(n.slice(s)))}),e}function Xp(t,e){let n=t.parentElement;if(!n){console.warn("No insert point found");return}let{display:o}=window.getComputedStyle(n);o.includes("block")||o==="table-cell"?n==null||n.insertBefore(e,t.nextSibling):Xp(n,e)}function Jp(r,s){return v(this,arguments,function*(t,e,{isBlock:n,isHTML:o}={}){let i;t.dispatchEvent(new InputEvent("beforeinput",{inputType:"insertText",data:e,bubbles:!0,cancelable:!0}));let a=()=>{var u;let d=(u=t.ownerDocument.defaultView)!=null?u:window,l=d.getSelection();if((!l||l.rangeCount===0)&&(t.focus(),l=d.getSelection()),!l||l.rangeCount===0)return;let c=l.getRangeAt(0);if(!c)return;i=document.createElement("span"),c.insertNode(i);let p=o?Xh(e):Jh(e);n?Xp(c.startContainer,p):(c.insertNode(p),c.collapse(!1))};return Promise.resolve(a()).then(()=>{if(t.dispatchEvent(new InputEvent("input",{inputType:"insertText",data:e,bubbles:!0,cancelable:!0})),t.focus(),!!i)try{i.scrollIntoView&&i.scrollIntoView({block:"nearest",inline:"nearest"})}finally{i&&i.remove()}})})}0&&(module.exports={Card,ContentEditableInput,DeepdeskAPI,DeepdeskSDK,HTTPClient,InputMediator,InputType,KeyboardHint,Label,Locale,Section,SectionList,Sources,Suggestion,SuggestionList,TextAreaInput,ToggleButton,attachFile,authenticateWithKey,createFullRange,createOverlayContainer,createRangeFromOffsets,escapeHTML,formatTextMarkup,getRangeOffsets,getRangeText,insertCKEditor,isHTML,isSupportedInputElement,logEvent,updateContentEditable,updateTextArea,useClickOutsideRoot,useStyles,waitForElementVisibilityChange});