@deepdesk/deepdesk-sdk 19.4.2-beta.3 → 19.5.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.esm.js CHANGED
@@ -8,6 +8,6 @@ Try polyfilling it using "@formatjs/intl-pluralrules"
8
8
  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
9
9
  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`})})});import{jsx as Rd}from"react/jsx-runtime";var Wh={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},Pd=({className:t,color:e})=>Rd("svg",{className:t,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:Rd("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:Wh[e||"pink"]})});var Id={root:"dd-LbeUM",text:"dd-Dpfn1",isLoggedIn:"dd-XvHAn",isLoggedOut:"dd-21y-z",icon:"dd-8rLqS",logo:"dd-slXhD",lock:"dd-ByzlR"};var Kr={};J(Kr,{enUS:()=>zh,nlNL:()=>Vh});var zh={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},Vh={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};import{useDispatch as qh}from"react-redux";import{jsx as Wr,jsxs as Ad}from"react/jsx-runtime";var Ld=({onLogIn:t})=>{let e=P(Kr),n=E("floatingMenu"),o=E("productName"),s=qh(),r=$h(Q),i=b("FloatingMenu",Id);if(r===null||n===!1)return null;let a=()=>{r===!0?s(me(!0)):t()};return Ad("button",{type:"button",className:jh(i.root,{[i.isLoggedIn]:r,[i.isLoggedOut]:!r}),onClick:a,children:[Wr("div",{className:i.text,children:e(r?"search":"signin",{productName:o})}),Ad("div",{className:i.icon,children:[Wr(Pd,{className:i.logo,color:"pink"}),r===!1&&Wr(kd,{className:i.lock})]})]})};import{useEffect as yy,useRef as vy}from"react";import{useDispatch as Sy,useSelector as wt}from"react-redux";function Re(t){let{showMidSentenceSuggestions:e,showSuggestionsBeforePattern:n,showSuggestionsAfterPattern:o}=t.settings,{text:s,selection:r}=t.input;return r.end<t.input.suggestionTextStart||r.start!==r.end?!1:r.end>=s.length?!0:e?n&&new RegExp(n).test(s.substring(r.end))||o&&new RegExp(o).test(s.substring(0,r.end))?!0:n===!1&&o===!1:!1}import{createSlice as Gh}from"@reduxjs/toolkit";var Xh={showTabHint:!1,inputHasFocus:!1,overlayCollapsed:!1,openOverlayWhenTyping:!1,overlayCollapsedUserOverwrite:!1},Zo=({ui:t})=>t.overlayCollapsed,Md=Gh({name:"ui",initialState:Xh,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:Fn,setInputFocus:Yo,setOverlayCollapsed:tt,setOpenOverlayWhenTyping:Nd,setOverlayCollapsedUserOverwrite:Od}=Md.actions,Dd=Md.reducer;var _d={styleRow:"dd-prYfH",styleSuggestion:"dd-JTmXy"};import{jsx as es}from"react/jsx-runtime";var Jh=({match:t,selected:e,styles:n})=>es(M,{as:"button",selected:e,className:n.styleRow,"data-testid":"style-suggestion-item",title:t.suggestion,children:es("span",{className:n.styleSuggestion,children:t.suggestion})}),Qh=({matches:t,selectedIndex:e})=>{let n=b("StyleSuggestionList",_d);return es(Y,{children:t.map((o,s)=>es(Jh,{match:o,selected:e===s,styles:n},`${o.keyword}-${s}`))})},ts=Qh;import{useMemo as py}from"react";import{Interweave as Kd}from"interweave";import{useEffect as oy,useMemo as sy,useRef as ry,useState as iy}from"react";import{useDispatch as ay,useSelector as Wd}from"react-redux";import{useEffect as Zh}from"react";function Fd(t,e,n){Zh(()=>{let o=t.current;return o?(o.addEventListener(e,n),()=>{o.removeEventListener(e,n)}):()=>{}},[t,e,n])}var Hd={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"};import{jsx as Bd,jsxs as Yh}from"react/jsx-runtime";var Ud=({title:t})=>Yh("svg",{xmlns:"http://www.w3.org/2000/svg",width:"18px",height:"18px",viewBox:"0 0 24 24","aria-labelledby":"closeTitle",children:[Bd("title",{id:"closeTitle",children:t}),Bd("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 zr={};J(zr,{enUS:()=>ey,nlNL:()=>ty});var ey={assistant:[{type:0,value:"Assistant"}],close:[{type:0,value:"Close"}]},ty={assistant:[{type:0,value:"Assistent"}],close:[{type:0,value:"Sluiten"}]};import{jsx as Ke,jsxs as zd}from"react/jsx-runtime";var ly=["search","personal-collection-search","search-autocomplete"];function dy(t,e,n,o={}){var r;let s="";return ly.includes(e)?s=Ul(Pr(t,n,{stripAgentPart:!0}),(r=o.searchKeywords)!=null?r:[n]):s=Pr(t,n,o),o.placeholders===!0&&(s=Kl(s)),s}var cy=()=>{},uy=({selected:t,suggestion:e})=>{let n=P(zr),o=E("inlineSuggestions"),s=Wd(dt),[r,i]=iy(!1),a=E("enableSuggestionFeedback"),d=Wd(m=>m.input.text),l=ay(),c=b("TextSuggestion",Hd),p=ry(null),u=e.source==="assistant",f=a&&!u;oy(()=>{let m=setTimeout(()=>{l(ia({text:e.text,suggestion:e}))},500);return()=>{clearTimeout(m)}},[e]),Fd(p,"click",()=>{l(ie({suggestion:e,text:e.text,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"}))});let h=()=>{l(ut({source:e.source,text:e.text,assistantCode:e.assistantCode}))},g=sy(()=>dy(e.text,e.source,s,{stripAgentPart:o,placeholders:!0,searchKeywords:e.searchKeywords}),[o,e.text,e.source,s,e.searchKeywords]);return e.source==="gpt"&&!o?null:zd("div",{className:c.root,onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),children:[Ke(M,{ref:p,as:"button","data-testid":"suggestions-overlay-item",selected:t,onClick:cy,children:e.source==="assistant"?zd("div",{className:c.assistantContainer,children:[Ke(Kd,{containerTagName:"div",tagName:"span",className:c.formattedTextTruncated,content:g}),Ke("span",{className:c.assistantBadge,children:n("assistant")})]}):Ke(Kd,{containerTagName:"div",tagName:"span",className:c.formattedText,content:g})}),f&&r&&Ke("div",{className:c.actions,children:Ke(Go,{source:"overlay",context:d,suggestion:e})}),u&&r&&Ke("div",{className:c.closeIconContainer,children:Ke("button",{type:"button",className:c.closeIcon,onClick:h,title:n("close"),children:Ke(Ud,{title:n("close")})})})]})},Vd=uy;import{jsx as my}from"react/jsx-runtime";var gy=({suggestions:t,selectedIndex:e,reverse:n})=>py(()=>{let s=t.map((r,i)=>my(Vd,{index:i,selected:i===e,suggestion:r},`${r.text}-${r.source}`));return n?s.reverse():s},[t,e,n]),ns=gy;var jd={root:"dd-PfvRI",paper:"dd-HYlyY"};import{createAsyncThunk as fy,createSlice as hy}from"@reduxjs/toolkit";var os={list:{keywordMatches:[]},fetchState:"idle"},ss=t=>t.styleSuggestions.list,Tt=fy("styleSuggestions/getAll",(n,o)=>v(null,[n,o],function*({text:t},e){var d;let{deepdeskAPI:s}=e.extra,r=e.getState(),{showStyleSuggestions:i}=r.settings,a=(d=r.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 s.getStyleSuggestions({profileCode:a,message:t})})),$d=hy({name:"styleSuggestions",initialState:os,reducers:{commitStyleSuggestion(t,e){let{keyword:n,suggestion:o}=e.payload;t.list.keywordMatches=t.list.keywordMatches.filter(s=>s.keyword.toLowerCase()!==n.toLowerCase()||s.suggestion!==o)}},extraReducers:t=>{t.addCase(Tt.pending,e=>{e.fetchState="loading"}).addCase(Tt.rejected,e=>{e.fetchState="error"}).addCase(Tt.fulfilled,(e,n)=>{e.fetchState="done",Xe(e.list,n.payload)||(e.list=n.payload)}).addCase(pt,e=>{e.list=os.list}).addCase(j,()=>os)}}),{commitStyleSuggestion:qd}=$d.actions,Gd=$d.reducer;var rs=t=>{let e=new Set;return t.filter(({keyword:n,suggestion:o})=>{let s=JSON.stringify([n.toLowerCase(),o]);return e.has(s)?!1:(e.add(s),!0)})};import{jsx as is,jsxs as by}from"react/jsx-runtime";var xy=()=>{var m;let t=vy(null),e=b("InlineSuggestionsOverlay",jd),n=wt(Re),o=Sy(),s=wt(Q),r=wt(Dt),i=wt(Zo),a=E("showTextSuggestions"),d=wt(ct),l=wt(pn),c=E("showStyleSuggestions"),p=E("showStyleSuggestionList"),u=wt(ss),f=c&&p?rs((m=u.keywordMatches)!=null?m:[]):[],h=f.length>0,g=a&&d.length>0;return ht(()=>{setTimeout(()=>{o(tt({collapse:!0,skipWhenInputFocus:!0}))})}),yy(()=>{let S=t.current;if(!S||!S.parentElement)return;S.parentElement.style.left="0px";let C=S.getBoundingClientRect();S.parentElement.style.left=`${Math.min(window.innerWidth-4-C.right,0)}px`}),i||s!==!0||r===!1||!n&&!h||!g&&!h?null:is("div",{className:e.root,"data-variant":"inline",children:by("div",{ref:t,className:e.paper,children:[h&&is(ts,{matches:f,selectedIndex:-1}),g&&is(Y,{children:is(ns,{suggestions:d,selectedIndex:l})})]})})},Xd=xy;import wy,{useState as jr,useEffect as Ey}from"react";var Jd={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"};import{useSelector as ky}from"react-redux";var Vr={};J(Vr,{enUS:()=>Cy,nlNL:()=>Ty});var Cy={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."}]},Ty={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."}]};import{Fragment as Ry,jsx as ye,jsxs as as}from"react/jsx-runtime";var Qd=({onClose:t,onSave:e,id:n,error:o})=>{let[s,r]=jr(""),[i,a]=jr(!1),[d,l]=jr(!1),c=b("Nickname",Jd),p=wy.useRef(null),u=ky(S=>S.info.showNicknameDialog),f=P(Vr),h=E("adminUrl");Ey(()=>{o&&a(!0)},[o]);let g=()=>{if(!p.current)return;s.trim()?p.current.setCustomValidity(""):p.current.setCustomValidity(f("nicknameDialogError")),p.current.reportValidity()},m=S=>{S.preventDefault();let C=s.trim(),T=S.currentTarget.querySelector("#nickname-input");if(!C){T.setCustomValidity(f("nicknameDialogError")),T.reportValidity();return}T.setCustomValidity(""),e(C)};return as(jt,{isOpen:u,"datatest-id":n,onClose:t||(()=>{}),onBack:t||(()=>{}),children:[ye("div",{className:c.titleWrapper,children:ye("h1",{className:c.title,children:f("title")})}),as("form",{className:c.dialogContent,onSubmit:m,children:[ye("p",{children:f("nicknameDialogTitle")}),i&&o&&ye("div",{className:c.errorMessage,children:h?(()=>{let S=f("nicknameDialogSaveError",{account:h}),C=`${h}.deepdesk.com/admin/user-settings`,T=S.indexOf(C);if(T!==-1){let w=S.substring(0,T),A=S.substring(T+C.length);return as(Ry,{children:[w,ye("a",{href:C,target:"_blank",rel:"noopener noreferrer",className:c.errorLink,children:C}),A]})}return S})():f("nicknameDialogSaveErrorWithoutLink")}),ye("input",{required:!0,minLength:1,maxLength:20,"data-testid":"nickname-input",id:"nickname-input",className:c.nicknameInput,type:"text",placeholder:f("nicknameDialogInputPlaceholder"),value:s,onChange:S=>{l(new RegExp("\\p{Extended_Pictographic}","u").test(S.target.value)),r(S.target.value)},onBlur:g,ref:p}),d&&ye("div",{className:c.errorMessage,role:"alert",children:f("nicknameDialogEmojiError")}),as("div",{className:c.buttonsWrapper,children:[o?ye("div",{className:c.closeButtonWrapper,children:ye("button",{type:"button",className:c.closeButton,onClick:()=>t==null?void 0:t(),children:f("close")})}):null,ye("div",{className:c.buttonContinueWrapper,children:ye("button",{type:"submit",className:c.continueButton,disabled:!s.trim()||new RegExp("\\p{Extended_Pictographic}","u").test(s),children:f("nicknameDialogContinueButton")})})]})]})]})};import{Provider as Py}from"react-redux";import{jsx as ls}from"react/jsx-runtime";var Iy=({children:t})=>{let n=E("locale").replace("-","");return ls(dr.Provider,{value:n,children:t})},Ay=({store:t,customStyles:e={},children:n})=>ls(Py,{store:t,children:ls(Iy,{children:ls(an.Provider,{value:e,children:n})})}),We=Ay;import Jr from"classnames";import{useEffect as Wy,useRef as zy,useState as Vy}from"react";import{useDispatch as jy,useSelector as ze}from"react-redux";import{useState as Ly}from"react";function Zd(t,e){let[n,o]=Ly(()=>{if(typeof window=="undefined")return e;try{let r=window.localStorage.getItem(t);return r?JSON.parse(r):e}catch(r){return k.error(r),e}});return[n,r=>{try{let i=r instanceof Function?r(n):r;o(i),typeof window!="undefined"&&window.localStorage.setItem(t,JSON.stringify(i))}catch(i){k.error(i)}}]}var Yd=()=>/Mac/i.test(navigator.platform);import Oy from"classnames";import{Fragment as Dy,useCallback as qr,useMemo as tc}from"react";var $r={};J($r,{enUS:()=>My,nlNL:()=>Ny});var My={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"}]}]},Ny={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 ec={root:"dd-uTPjX",anchor:"dd-C8lsZ",anchorButton:"dd-IoSx9"};import{jsx as ds,jsxs as nc}from"react/jsx-runtime";var Gr=(t,e,n)=>o=>ds("button",{className:t.anchorButton,type:"button",value:e,onClick:n,children:o},e),_y=({className:t,loginUrl:e,isEmbedded:n,onSnooze:o,onLogIn:s})=>{let r=P($r),i=oe(),a=b("Login",ec),d=E("productName"),l=E("signInViaPopup"),c=n&&!l,p=qr(C=>{C.preventDefault(),o&&o(Number.parseInt(C.target.value,10))},[]),u=qr(C=>{C.preventDefault(),i.send(Ut,!0)},[e]),f=tc(()=>C=>ds("a",{onClick:w=>{w.preventDefault(),s()},href:e,className:a.anchor,target:"_blank",rel:"noreferrer",children:C},"login"),[e]),h=qr(C=>ds("button",{type:"button",className:a.anchorButton,onClick:u,children:C},"prompt"),[u]),{min:g,hour:m,day:S}=tc(()=>({min:Gr(a,600,p),hour:Gr(a,3600,p),day:Gr(a,3600*12,p)}),[]);return nc("div",{className:Oy(t,a.root),children:[r("loginPlease",{login:c?h:f,productName:d}),o&&nc(Dy,{children:[ds("br",{}),r("snooze",{min:g,hour:m,day:S})]})]})},cs=_y;import{useDispatch as Fy}from"react-redux";var oc={root:"dd-DoQhb",text:"dd-Jwnev"};import{jsx as sc,jsxs as By}from"react/jsx-runtime";var Hy=({title:t})=>{let e=b("SearchTrigger",oc),n=Fy(),o=z();return By("button",{type:"button",className:e.root,onClick:()=>{n(me(!0)),o("open search",{via:"autocomplete-overlay"})},children:[sc(qt,{}),sc("span",{className:e.text,children:t})]})},rc=Hy;var Xr={};J(Xr,{enUS:()=>Uy,nlNL:()=>Ky});var Uy={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"}]},Ky={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 ic={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"};import{jsx as G,jsxs as nt}from"react/jsx-runtime";var $y=({onLogIn:t})=>{var W;let e=b("SuggestionsOverlay",ic),n=P(Xr),o=ze(Re),s=ze(ra),r=jy(),i=zy(null),a=E("searchTriggerKey"),d=E("productName"),l=ze(Zo),c=ze(Q),p=ze(qi),u=ze(Dt),[f,h]=Vy(null),g=E("showSearch"),m=E("showTextSuggestions"),S=E("adminUrl"),C=E("isEmbedded"),T=E("suggestionsPlacement"),[w,A]=Zd("dd-snooze-until-ms",0),R=l||w>Date.now(),I=ze(ct),U=ze(pn),ce=E("showStyleSuggestions"),Ae=E("showStyleSuggestionList"),D=ze(ss),K=ce&&Ae?rs((W=D.keywordMatches)!=null?W:[]):[],be=K.length>0,X=I.filter(Le=>Le.source!=="gpt").length,it=()=>{R&&A(0),r(Od(!R))},N=Le=>{let It=Date.now()+Le*1e3;A(It),k.info(`Snooze until: ${new Date(It)}`),r(tt({collapse:!0}))};return Wy(()=>{X===0&&h(null)},[I,X]),ht(()=>{r(tt({collapse:!0,skipWhenInputFocus:!0}))}),c===null||u===!1?null:c===!1?nt("div",{ref:i,className:Jr(e.root,{[e.isCollapsed]:R}),children:[!R&&nt("div",{className:e.triggers,children:[G("div",{style:{flex:1}}),G("div",{className:e.triggersRight,children:G(Lt,{className:e.toggleButton,title:n("collapse"),onClick:it,isCollapsed:!1})})]}),G("div",{className:e.toggleButtonWrapper,children:G(Lt,{className:e.toggleButton,title:n("open",{productName:d}),onClick:it,isCollapsed:!0})}),nt("div",{className:e.collapsible,children:[p&&nt("div",{className:e.loginError,children:[G("span",{className:e.loginErrorMessage,children:p}),G("button",{type:"button",className:e.loginErrorDismiss,onClick:()=>r(no()),"aria-label":n("dismissError"),children:n("dismiss")})]}),G(cs,{loginUrl:S,isEmbedded:C,onLogIn:t,onSnooze:N})]})]}):!s||!o&&!be?null:nt("div",{ref:i,className:Jr(e.root,{[e.isCollapsed]:R}),children:[!R&&nt("div",{className:e.triggers,children:[G("div",{style:{flex:1},children:g&&G("div",{style:{display:"inline-block"},onFocus:()=>{},onMouseOver:()=>h(n(Yd()?"searchHintMac":"searchHintWindows",{searchTriggerKey:a.toUpperCase()})),onMouseLeave:()=>h(null),children:G(rc,{title:n("search")})})}),nt("div",{className:e.triggersRight,onFocus:()=>{},children:[G("div",{className:Jr(!f&&e.hintsHidden,e.hints),children:f}),G(Lt,{className:e.toggleButton,title:n("collapse"),onClick:it,isCollapsed:!1})]})]}),G("div",{className:e.toggleButtonWrapper,children:G(Lt,{className:e.toggleButton,title:n("open",{productName:d}),onClick:it,isCollapsed:!0})}),(be||X>0&&m)&&nt("div",{className:e.collapsible,onFocus:()=>{},children:[be&&G(ts,{matches:K,selectedIndex:-1}),X>0&&m&&G(Y,{children:G(ns,{suggestions:I,selectedIndex:U,reverse:T==="above"})})]})]})},ac=$y;import ni from"classnames";import{Interweave as Mv}from"interweave";import{useCallback as Nv,useEffect as Ov,useMemo as kc,useRef as Dv}from"react";import{connect as _v}from"react-redux";import{useEffect as qy,useRef as Gy,useState as Xy}from"react";function us(t){return t.contentEditable==="true"}function Jy(t){let e=0,n=0,o=window.getSelection();if(o.rangeCount!==0){let s=o.getRangeAt(0),r=s.cloneRange();r.selectNodeContents(t),r.setEnd(s.endContainer,s.endOffset),n=r.toString().length,r.selectNodeContents(t),r.setEnd(s.startContainer,s.startOffset),e=r.toString().length}return{selectionStart:e,selectionEnd:n}}function lc(t){let{selectionStart:e,selectionEnd:n}=us(t)?Jy(t):t;return[e,n]}function dc(t){let[,e]=Xy(),n=Gy(null);return n.current=lc(t),qy(()=>{let o=()=>{var a;let[s,r]=(a=n.current)!=null?a:[],i=lc(t);(!i||s!==i[0]||r!==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 cc(t,e){if(!e)return;let n=t,{value:o}=n,[s,r]=e,i=o.match(Zn);if(!i||i.length===0)return;let a=0;i.find(d=>{let l=o.indexOf(d,a);return s>l&&r<l+d.length?(n.selectionStart=l,n.selectionEnd=l+d.length,!0):(a=l+d.length,!1)})}import{cloneElement as Qy}from"react";var Zy=["div","span","mark","strong","b","i","u","em"];function Qr(t,e,n=0){var r;let o=t[t.length-1],s=typeof o=="object"&&o!==null?(r=o.props)==null?void 0:r.tagName:void 0;if(s==="br")return t.pop(),[...t,...e,o];if(Zy.includes(s)){let i=Array.isArray(o.props.children)?o.props.children:[o.props.children];return[...t.slice(0,t.length-1),Qy(o,{children:Qr(i,e,n+1)})]}return[...t,...e]}function Et(t){return t.tagName.toLowerCase()==="textarea"}var uc={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"};import rv from"classnames";import{Matcher as iv}from"interweave";import{useEffect as av,useMemo as lv}from"react";import{useEffect as Yy,useRef as ev,useState as tv}from"react";function pc(t,e){let n;return[(...o)=>{window.cancelAnimationFrame(n);let s=e?e(...o):o;n=window.requestAnimationFrame(()=>{t(...s)})},()=>window.cancelAnimationFrame(n)]}function ps(t){let e=ev(null),[n,o]=tv(!1);return Yy(()=>{var c;let s=!1,r=Number.parseFloat((c=window.getComputedStyle(document.body).zoom)!=null?c:"1"),[i,a]=pc((p,u)=>{let f=e.current;if(!f)return;let h=p/r,g=u/r,m=f.getBoundingClientRect(),S=h>m.x&&h<m.x+m.width&&g>m.y&&g<m.y+m.height;S&&!s?(s=!0,o(!0)):!S&&s&&(s=!1,o(!1))},({clientX:p,clientY:u})=>[p,u]),[d,l]=pc(()=>{s=!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 gs(t){return t.replace(/[.*+^${}()|[\]\\]/g,"\\$&")}function ms(t){return e=>{t.forEach(n=>{typeof n=="function"?n(e):n!=null&&(n.current=e)})}}function gc(t){return t!=null}import nv from"classnames";import{forwardRef as ov,useRef as sv}from"react";var Ve={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"};import{jsx as mc}from"react/jsx-runtime";var fs=ov((s,o)=>{var r=s,{className:t,children:e}=r,n=O(r,["className","children"]);let i=sv(null),a=b("TabCompletion",Ve);return mc("div",x(y({ref:ms([i,o]),className:nv(t,a.popoverContentContainer)},n),{children:mc("div",{className:a.popoverContent,children:e})}))});import{jsx as Hn,jsxs as uv}from"react/jsx-runtime";var dv=t=>e=>{let n=yr(e);return"top"in n&&(n.width=t.width-(e.left-t.left)-10),n},cv=({inputElement:t,boundaryRef:e,inputStyle:n,children:o,suggestion:s})=>{let r=b("TabCompletion",Ve),i=Ao(),a=lv(()=>dv(t.getBoundingClientRect()),[t]),[d,l]=ps(t);return av(()=>{l?i.open():i.close()},[l]),uv("span",{children:[Hn("mark",{ref:ms([d,i.triggerRef]),className:rv(r.matchKeyword,{[r.hover]:l}),"aria-haspopup":"dialog","aria-expanded":i.opened?"true":"false",children:o}),i.opened&&Hn(Wt,{className:r.popover,triggerRef:i.triggerRef,boundaryRef:e,position:"below",align:"start",toStyle:a,children:Hn(fs,{style:n,children:Hn("div",{className:r.hintText,children:s})})})]})},hs=class extends iv{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(s=>x(y({},s),{keywordRegex:new RegExp(`\\b${gs(s.keyword)}\\b`,"i")})),this.keywordMatches=o.keywordMatches),this.usedKeywordMatches.clear(),n}match(n){let o=this.preparedKeywordMatches.map(r=>{if(this.usedKeywordMatches.has(r))return null;let i=n.match(r.keywordRegex);if(!i)return null;let a=n.charAt(i.index-1),d=n.charAt(i.index+r.keyword.length);return a==="{"&&d==="}"?null:{index:i.index,length:i[0].length,match:i[0],matchString:i[0],suggestion:r.suggestion,preparedKeywordMatch:r,valid:!0}}).filter(gc);if(o.length===0)return null;let s=o.reduce((r,i)=>i.index<r.index?i:r);return this.usedKeywordMatches.add(s.preparedKeywordMatch),s}replaceWith(n,o){return Hn(cv,{inputElement:o.inputElement,suggestion:o.suggestion,inputStyle:o.inputStyle,boundaryRef:o.boundaryRef,children:n},`keyword_${o.matchString}_${o.key}`)}asTag(){return"mark"}};import{Matcher as pv}from"interweave";import gv from"classnames";import{jsx as fc}from"react/jsx-runtime";var mv=({inputElement:t,children:e})=>{let n=b("TabCompletion",Ve),[o,s]=ps(t);return fc("mark",{ref:o,className:gv(n.matchPlaceholder,{[n.hover]:s}),children:e})},ys=class extends pv{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 fc(mv,{inputElement:n.inputElement,children:e},`placeholder_${n.matchString}_${n.key}`)}asTag(){return"mark"}};import ti from"classnames";import{Matcher as wv}from"interweave";import{createRef as Ev,forwardRef as kv,useCallback as Rv,useEffect as Tc,useRef as wc,useState as Ec}from"react";import{useDispatch as Pv,useSelector as Iv}from"react-redux";import{jsx as hc}from"react/jsx-runtime";var yc=()=>hc("svg",{width:"1.3em",height:"1.3em",focusable:"false","aria-hidden":"true",viewBox:"0 0 24 24","data-testid":"InsertLinkIcon",tabIndex:-1,children:hc("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"})});import{useCallback as fv,useEffect as Sc,useMemo as hv,useState as xc}from"react";import{useDispatch as yv,useSelector as bc}from"react-redux";import vv from"lodash.debounce";var vc={root:"dd-ky-Bv",content:"dd-kV5e1"};function vs(t,e,n){var s;let o=((s=t.imageSizes)==null?void 0:s[e])||t.image||n;if(!o)return null;try{return new URL(o).toString()}catch(r){return null}}function Zr(t){return t.replace("https://www.","").replace("https://","")}import{jsx as kt,jsxs as Yr}from"react/jsx-runtime";var Sv=3,xv=t=>({image:t.image||"",text:t.text,id:t.id,title:t.title}),bv=({onSelectLink:t,onDismiss:e,placeholder:n,visitUrlText:o,linkCount:s=Sv})=>{let r=b("LinkSearch",vc),[i,a]=xc(""),d=yv(),l=bc(hd("url")),c=bc(Ia("URL")),p=hv(()=>c.map(xv),[c]),[u,f]=xc(p.length-1),h=E("fallbackImage"),g=T=>{let w=T.target;a(w.value)},m=(T,w)=>{T.stopPropagation(),T.preventDefault(),window.open(w,"_blank")},S=T=>{var R;let w=u-1<0?p.length-1:u-1,A=u+1===p.length?0:u+1;T.code==="Escape"&&(a(""),e()),T.code==="ArrowUp"&&f(w),T.code==="ArrowDown"&&f(A),T.code==="Enter"&&t(((R=p[u])==null?void 0:R.text)||i)},C=fv(vv(T=>{d(gt({query:T,type:"URL",tags:["link-search"]}))},300),[]);return Sc(()=>{i&&C(i)},[i]),Sc(()=>()=>{d(mo())},[]),Yr("div",{className:r.root,children:[kt(Y,{withDivider:!0,children:(i?p:l).slice(0,s).map((T,w)=>kt(M,{selected:u===w,onClick:()=>t(T.text),"data-testid":"linksearch-suggestion",children:Yr(_,{children:[kt(_.Image,{src:vs(T,"small",h||void 0),title:T.title||T.text}),Yr(_.Content,{className:r.content,cropText:!0,children:[kt(_.Title,{children:T.title||Zr(T.text)}),T.title&&Zr(T.text)]}),kt(M.Actions,{children:kt(M.ActionButton,{label:o,onClick:A=>m(A,T.text)})})]})},T.text))}),kt(Pn,{value:i,onChange:g,autoFocus:!0,placeholder:n,onKeyUp:S})]})},Cc=bv;var ei={};J(ei,{enUS:()=>Cv,nlNL:()=>Tv});var Cv={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"}]},Tv={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"}]};import{jsx as ve,jsxs as Ss}from"react/jsx-runtime";var Av=kv((t,e)=>{let n=b("TabCompletion",Ve);return ve("mark",{ref:e,className:ti(n.matchSelection)},"selection-start")}),Lv=({startRef:t,boundaryRef:e,inputStyle:n,inputElement:o,children:s})=>{let r=P(ei),i=b("TabCompletion",Ve),a=E("addToPersonalCollection"),d=Iv(Ze("/admin/personal-collection/new")),l=wc(null),c=wc(null),[p,u]=Ec(null),f=Pv(),h=Ao(document.activeElement===o),[g]=Ec(()=>document.createRange());h.triggerRef.current=g,Tc(()=>()=>g.detach(),[]),Tc(()=>{let S=t.current,C=l.current;!S||!C||(g.setStart(S,0),g.setEnd(C,0))},[t.current,l.current]),ht(()=>{h.close()});let m=Rv(S=>{let C=g.toString(),T=/^http(s?):\/\//.test(S)?S:`https://${S}`,w=`[${C}](${T})`;f(ie({text:w,suggestion:{text:w,source:"search-url",type:"url"},eventMetrics:{inputType:"mouse"},replace:"selection"}))},[]);return Ss("span",{children:[ve("mark",{ref:l,className:ti(i.matchSelection),"aria-haspopup":"dialog","aria-expanded":h.opened?"true":"false",children:s}),h.opened&&ve(Wt,{className:i.popoverRoot,triggerRef:h.triggerRef,boundaryRef:e,position:"above",align:"start",children:Ss(fs,{style:n,ref:c,children:[Ss("div",{className:ti(i.selectionOptions,{[i.selectionOptionsIsHidden]:p!==null}),children:[Ss("button",{type:"button",tabIndex:p===null?-1:void 0,className:i.selectionOptionsButton,onClick:()=>u("insertLink"),children:[ve(yc,{}),ve("span",{children:"\xA0"}),ve("span",{children:r("insertLink")})]}),a&&d&&ve("button",{type:"button",tabIndex:p===null?-1:void 0,className:i.selectionOptionsButton,onClick:()=>{let S=g.toString(),C=`${d}?text=${encodeURIComponent(S)}`;window.open(C,"_blank")},children:ve("span",{children:r("addToPersonalCollection")})})]}),p==="insertLink"&&ve(Cc,{placeholder:r("linkInputPlaceholder"),visitUrlText:r("visitUrl"),onSelectLink:m,onDismiss:()=>{u(null),h.close()}})]})})]},"selection-end")},xs=class extends wv{constructor(){super(...arguments);this.charCount=0;this.foundIndex=0;this.startRef=null}onBeforeParse(n,o){return this.props=o,this.charCount=0,this.startRef=Ev(),this.foundIndex=0,n}match(n){if(!this.props||this.props.selection===null||this.foundIndex===2)return null;let[o,s]=this.props.selection;if(o===s)return null;let r=this.foundIndex===0?o:s,i=r>=this.charCount&&r<=this.charCount+n.length?{index:r-this.charCount,length:0,match:"",valid:!0}:null;i&&this.foundIndex++;let a=this.foundIndex===1;return i&&a?this.charCount+=r-this.charCount:this.charCount+=n.length,i?y({isStart:a},i):null}replaceWith(n,o){return o.isStart?ve(Av,{ref:this.startRef}):ve(Lv,{inputElement:o.inputElement,startRef:this.startRef,boundaryRef:o.boundaryRef,inputStyle:o.inputStyle})}asTag(){return"mark"}};import{useSelector as Fv}from"react-redux";import{jsx as Xt,jsxs as Uv}from"react/jsx-runtime";var Hv=({enabled:t,content:e,tabText:n,showTabHint:o,showTabCompletion:s,showStyleSuggestions:r,keywordMatches:i,inputElement:a,source:d})=>{let l=b("TabCompletion",uc),c=E("insertLink"),p=E("addToPersonalCollection"),u=E("showMidSentenceSuggestions"),f=E("inlineSuggestions"),h=dc(a),g=Dv(null),m=Fv(Q);Ov(()=>{Et(a)&&h&&cc(a,h)},[h]);let S=Nv(w=>{if(!s||!n)return w;let A=[Xt("span",{className:l.resetIndent,children:"\u200B"},"u200B"),Xt("span",{"data-testid":"tab-completion",className:ni(l.tabText,l.resetIndent),"data-source":d,children:n},"tabText")];return o&&A.push(Xt("span",{className:ni(l.hint,l.resetIndent),children:Xt(Hs,{keyCode:"tab"},"tabHint")},"tabHint")),Qr(w,A)},[s,n,o]),C=kc(()=>{let w=[];return(c||p)&&w.push(new xs("selection")),w.push(new ys("placeholders")),r&&w.push(new hs("keywords")),w},[f,c,p,r]),T=kc(()=>{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||!m?null:Uv("div",{ref:w=>{w!=null&&w.parentElement&&(g.current=w==null?void 0:w.parentElement)},className:l.root,style:T,children:[Xt(Mv,{tagName:"span",containerTagName:"div",className:ni(l.container,l.agentText),disableLineBreaks:Et(a),content:e||"\u200B",onAfterParse:S,matchers:C,selection:h,keywordMatches:i,inputElement:a,inputStyle:T,boundaryRef:g,inlineSuggestionsOnlyAtEnd:!u}),Xt("br",{})]},"tab-completion")},Bv=t=>{var S,C,T;let{input:e,ui:n,settings:o,styleSuggestions:s,conversation:r}=t,i=_t({input:e}),a=(i==null?void 0:i.text)||"",d=(i==null?void 0:i.source)||"",l=(S=e.html)!=null?S:Nn(e.text),c=e.text.slice(e.suggestionTextStart,e.selection.end),p=a.indexOf(c)===0?a.slice(c.length):"",{showTabHint:u}=n,{isSupported:f}=r,{showTabCompletion:h,visible:g,showStyleSuggestions:m}=o;return{showTabHint:u,showStyleSuggestions:m,showTabCompletion:h&&Re(t),content:l,tabText:p,source:d,keywordMatches:(T=(C=s.list)==null?void 0:C.keywordMatches)!=null?T:[],enabled:g&&f!==!1}},Rc=_v(Bv)(Hv);import{Fragment as RS,useEffect as ci,useState as PS}from"react";import{useDispatch as ru,useSelector as te}from"react-redux";import{createAsyncThunk as Pc,createSlice as Kv}from"@reduxjs/toolkit";var Wv={token:null,interval:null},oi=Pc("passwordlessToken/getTemporaryPasswordlessToken",(t,e)=>v(null,null,function*(){let{deepdeskAPI:n}=e.extra;return{token:yield n.requestPasswordlessToken()}})),si=Pc("passwordlessToken/pollPasswordlessToken",(t={},e)=>{let{interval:n=1e3*60*10}=t,{dispatch:o}=e;return o(oi()),setInterval(()=>o(oi()),n)}),Ic=Kv({name:"passwordlessToken",initialState:Wv,reducers:{stopPollPasswordlessToken(t){t.interval&&clearInterval(t.interval),t.interval=null}},extraReducers:t=>{t.addCase(oi.fulfilled,(e,n)=>{e.token=n.payload.token}),t.addCase(si.fulfilled,(e,n)=>{e.interval=n.payload})}}),{stopPollPasswordlessToken:Ac}=Ic.actions,Lc=Ic.reducer;import{createSelector as zv}from"@reduxjs/toolkit";function Vv(t){return"buttonText"in t&&"eventName"in t}function Mc(t){if(t)return Vv(t)?{label:t.buttonText,event:t.eventName,value:t.payload}:t}function jv(t){return t==null?void 0:t.map(e=>Mc(e))}function $v(t){let e=0;for(let n=0;n<t.length;n++)e=(e<<5)-e+t.charCodeAt(n),e|=0;return e}var Nc=zv([ja,oo],(t,e)=>(e?t.filter(s=>!s.externalConversationId||s.externalConversationId===e):t).map(s=>{let r=Mc(s.callToAction),i=jv(s.callToActions);return x(y(y(y({text:s.response,title:s.name},r?{callToAction:r}:{}),i!=null&&i.length?{callToActions:i}:{}),s.message!==void 0?{message:s.message}:{}),{editable:s.editable,isLoading:s.isLoading,evaluationId:s.evaluationId,rule:{id:$v(s.code),label:s.code,name:s.name,description:s.name}})}));import{useEffect as qv,useState as Gv}from"react";import _c from"classnames";import{jsx as Oc}from"react/jsx-runtime";var Jt=()=>Oc("svg",{width:"1em",height:"1em",viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",children:Oc("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 Dc={root:"dd-WcEru",entity:"dd-LfP8y",entityText:"dd-L-v0f",iconWrapper:"dd-9Deh1",icon:"dd-tM7E2",iconClicked:"dd-EEdDL"};import{jsx as Qt,jsxs as Fc}from"react/jsx-runtime";var Xv=({entities:t})=>{let e=b("EntitiesWidgetList",Dc),[n,o]=Gv(void 0),s=z(),r=()=>{o(void 0)},i=a=>{t&&(o(t.indexOf(a)),Te(a.text),s("entity copied",{entity:a,type:"copy"}))};return qv(()=>{let a=setTimeout(r,500);return()=>{clearTimeout(a)}},[n]),!t||t.length===0?null:Qt("div",{className:e.root,"data-testid":"widget-entities-list",children:t.map((a,d)=>Fc("button",{title:a.text,className:e.entity,type:"button",onClick:()=>i(a),children:[Qt("span",{className:e.entityText,children:a.text}),Fc("span",{className:e.iconWrapper,children:[Qt("span",{className:_c(e.icon),children:Qt(Jt,{})}),Qt("span",{className:_c(e.icon,n===d&&e.iconClicked),children:Qt(Jt,{})})]})]},a.text))})},Hc=Xv;import{jsx as Bc}from"react/jsx-runtime";var Uc=()=>Bc("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:Bc("path",{d:"M17 13.5v6H5v-12h6m3-3h6v6m0-6-9 9",stroke:"currentColor",strokeWidth:"1.5",fill:"none",fillRule:"evenodd",strokeLinecap:"round",strokeLinejoin:"round"})});import{useRef as tS}from"react";import{useDispatch as nS,useSelector as oS}from"react-redux";var Kc={root:"dd-ohnXe",trigger:"dd-7i-S3",button:"dd-t53Cg",nav:"dd-qZFnm",item:"dd-FZC0F"};var Wc={root:"dd-nazq3",rotation:"dd-3EHTv"};import{jsx as Qv}from"react/jsx-runtime";var Jv=({size:t=12})=>{let e=b("LoadingSpinner",Wc);return Qv("span",{"data-testid":"loading-spinner",style:{width:`${t}px`,height:`${t}px`},className:e.root})},zc=Jv;import{jsx as Vc}from"react/jsx-runtime";var jc=()=>Vc("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 0 512 512",fill:"currentColor",children:Vc("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"})});import{jsx as $c,jsxs as Zv}from"react/jsx-runtime";var qc=t=>Zv("svg",x(y({xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 448 512","aria-labelledby":"checkTitle"},t),{children:[$c("title",{id:"checkTitle",children:"Check"}),$c("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 ri={};J(ri,{enUS:()=>Yv,nlNL:()=>eS});var Yv={error:[{type:0,value:"Something went wrong"}]},eS={error:[{type:0,value:"Er ging iets fout"}]};import{jsx as je,jsxs as Gc}from"react/jsx-runtime";var sS=3e3,rS=({assistantOptions:t})=>{let e=b("OnDemandAssistants",Kc),n=P(ri),o=tS(),s=nS(),r=yo(se),i=oS(Nl),a=z(),d=i.filter(u=>u.isPinned),l=i.filter(u=>!u.isPinned),c=()=>v(null,null,function*(){return t.attachments&&t.attachments.length>0?t.attachments:s(((u,f,h)=>v(null,null,function*(){let g;if(t.transcript==="in-memory-transcript"){let m=h.dynamicThunkObject.conversationQuery;if(m){let S=yield m();g=Array.isArray(S)?S:void 0}}else Array.isArray(t.transcript)&&(g=t.transcript);return cr({transcript:g})})))}),p=u=>v(null,null,function*(){clearTimeout(o.current);let f=yield c();a("trigger on demand assistant",{assistantCode:u}),yield r.call(y(x(y({},t),{assistantCode:u}),f.length>0?{attachments:f}:{})),o.current=setTimeout(()=>r.reset(),sS)});return i.length===0?null:Gc("div",{className:e.root,children:[d.map(({assistant:u,assistantName:f,displayName:h})=>je("button",{type:"button",className:e.button,disabled:r.state==="loading",onClick:()=>p(u),children:h||f},u)),l.length>0&&Gc($,{placement:"top-end",children:[je($.Trigger,{className:e.trigger,disabled:r.state==="loading",children:je(jo,{"data-testid":"trigger"})}),je($.Content,{className:e.nav,"data-testid":"popover",children:l.map(({assistant:u,assistantName:f,displayName:h})=>je($.Button,{className:e.item,disabled:r.state==="loading",onClick:()=>p(u),children:h||f},u))})]}),r.state==="loading"&&je(zc,{}),r.state==="done"&&je(qc,{"data-testid":"trigger-done"}),r.state==="error"&&je(yl,{trigger:je(jc,{}),children:n("error")})]})},Xc=rS;import{useDispatch as mS}from"react-redux";var Bn={};J(Bn,{enUS:()=>iS,nlNL:()=>aS});var iS={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"}]},aS={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"}]};import{useEffect as Jc,useRef as lS,useState as dS}from"react";var ii={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"};import{jsx as Se,jsxs as bs}from"react/jsx-runtime";var cS=500,uS=100,pS=({content:t,onChange:e,onCopy:n})=>{let o=lS(null),s=b("WidgetCue",ii);return Jc(()=>{let r=o.current;if(!r)return;r.style.setProperty("height","0px");let i=Math.min(Math.max(r.scrollHeight,uS),cS);r.style.setProperty("height",`${i}px`)},[t]),Se("textarea",{ref:o,className:s.editableCue,onCopy:n,onChange:e,value:t})},gS=({cue:t,onCallToAction:e,onRemove:n,onCopy:o,onUse:s})=>{var g;let r=b("WidgetCue",ii),i=P(Bn),a=z(),d=E("hasKeyboardInput"),[l,c]=dS(t.text),p=m=>{let S=m?x(y({},t),{callToAction:m}):t;e&&e(l,S),n(t)},u=(m,S)=>{o&&o(m,t),S&&Qe(S,r.fadeup)},f=m=>{s&&s(m,t)},h=m=>{m.preventDefault(),m.stopPropagation(),n(t)};return Jc(()=>{a("Assistant response displayed",{evaluationId:t.evaluationId,assistantCode:t.rule.label,assistantOutput:t.text})},[]),bs(M,{"data-testid":"cue",children:[Se(_,{children:bs(_.Content,{children:[t.title&&Se(_.Title,{className:r.title,"data-testid":"widget-cue-title",children:t.rule.label.startsWith("__")?i(t.rule.label):t.title}),t.message&&Se("p",{className:r.ctaMessage,children:t.message}),t.editable?Se(pS,{content:l,onCopy:()=>{let m=document.getSelection();m&&u(m.toString())},onChange:m=>{var S;return c((S=m.target.value)!=null?S:"")}}):Se(vt,{content:t.text,useLabel:i("useCue"),copyLabel:i("copyCue"),onCopy:u,onUse:d?f:void 0})]})}),bs(M.ButtonsContainer,{children:[bs("div",{className:r.actions,children:[Se(M.Button,{onClick:m=>{var S;return u((S=Eo(l,"reply")[0])!=null?S:l,m.target)},variant:"primary",children:i("copyCue")}),t.callToAction&&Se(M.Button,{onClick:()=>p(),variant:"primary",children:t.callToAction.label}),(g=t.callToActions)==null?void 0:g.map((m,S)=>Se(M.Button,{onClick:()=>p(m),variant:"primary",children:m.label},`${m.event}-${m.label}-${S}`)),Se(M.Button,{onClick:h,variant:"secondary",children:i("removeCue")})]}),Se(Io,{evaluationId:t.evaluationId,assistantCode:t.rule.label,assistantOutput:t.text,feedbackText:t.text,feedbackType:"assistant"})]})]})},Qc=gS;import{Fragment as hS,jsx as ai}from"react/jsx-runtime";var fS=({cues:t})=>{let e=mS(),n=oe(),o=P(Bn),s=z(),r=l=>{e(Ro({code:l.rule.label})),s("Assistant response closed",{evaluationId:l.evaluationId,assistantCode:l.rule.label,assistantOutput:l.text})},i=(l,c)=>{Te(l),s("Assistant response copied",{evaluationId:c.evaluationId,assistantCode:c.rule.label,assistantOutput:c.text,copiedText:l})},a=(l,c)=>{var p;c.callToAction&&(e(ko(c)),s("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(De,{text:l,suggestion:{source:"assistant",assistantCode:(p=c.rule)==null?void 0:p.label,sourceText:l}}),s("Assistant response used",{evaluationId:c.evaluationId,assistantCode:c.rule.label,assistantOutput:c.text,usedText:l})};return ai(hS,{children:t.map(l=>l.isLoading?ai(No,{title:l.rule.label.startsWith("__")?o(l.rule.label):l.title},l.rule.id):ai(Qc,{cue:l,onCallToAction:a,onRemove:r,onCopy:i,onUse:d},l.evaluationId))})},Zc=fS;import{Fragment as yS,useEffect as vS}from"react";var Yc={root:"dd-cvTAY",label:"dd-QWQxD",value:"dd-WSUHF",copyButton:"dd-67o9H",copyButtonText:"dd-oos-l",isTrue:"dd--1g2O",isFalse:"dd-sz2ir"};import{jsx as $e,jsxs as li}from"react/jsx-runtime";function SS(t,e){return e.split(".").reduce((n,o)=>!n||typeof n!="object"||!(o in n)?null:n[o],t)}var eu=({data:t,schema:e})=>{let n=b("WidgetCustomData",Yc),o=s=>{Te(s)};return vS(()=>{k.info("Custom data",t,e)},[t]),$e("dl",{className:n.root,children:e.map(s=>{let r=SS(t,s.path);return li(yS,{children:[$e("dt",{className:n.label,children:s.label}),$e("dd",{className:n.value,children:s.type==="boolean"&&r?$e("span",{className:n.isTrue,children:s.trueValue}):s.type==="boolean"&&!r?$e("span",{className:n.isFalse,children:s.falseValue}):s.type==="array"&&Array.isArray(r)&&r.length>0?li("button",{type:"button",onClick:()=>o(r.join(", ")),className:n.copyButton,children:[$e("span",{className:n.copyButtonText,children:r.join(", ")}),$e(Jt,{})]}):typeof r=="string"||typeof r=="number"?li("button",{type:"button",onClick:()=>o(`${r}`),className:n.copyButton,children:[$e("span",{className:n.copyButtonText,children:r}),$e(Jt,{})]}):"-"})]},s.label)})})};import{useCallback as bS}from"react";var xS=/(https?:\/\/[^\s]+)/,tu=t=>t.split(" ").find(e=>xS.test(e));import{jsx as Zt,jsxs as Cs}from"react/jsx-runtime";var CS=({suggestion:t,lines:e,onUse:n})=>{var p;let o=t.text||t.url||t.message,s=tu(o),r=P(On),i=E("showImages"),a=E("fallbackImage"),d=E("hasKeyboardInput"),l=u=>{u.preventDefault(),u.stopPropagation(),d&&n(o)},c=bS(u=>{window.open(s,"_blank"),u.stopPropagation(),u.preventDefault()},[s]);return Cs(M,{onClick:d?l:void 0,"data-testid":"edit-suggestion",children:[Cs(_,{children:[i&&t.image&&Zt(_.Image,{src:vs(t,"small",a||void 0),title:t.title}),Cs(_.Content,{children:[t.title&&Zt(_.Title,{"data-testid":"widget-suggestion-title",children:t.title}),t.searchKeywords&&((p=t.searchKeywords)==null?void 0:p.length)>0&&Zt(M.Labels,{labels:t.searchKeywords}),Zt(_.Content,{cropText:e==="single",lineClamp:e==="multiple",children:o})]})]}),Cs(M.Actions,{children:[s&&Zt(M.ActionButton,{onClick:c,label:r("visitUrl")}),d&&Zt(M.ActionButton,{primary:!0,onClick:l,label:r("useSuggestion")})]})]})},nu=CS;import{Fragment as wS,jsx as ou}from"react/jsx-runtime";var TS=({lines:t,suggestions:e})=>{let n=oe(),o=(s,r)=>{n.send(De,{text:s,suggestion:x(y({},r),{source:r.source,sourceText:r.text})})};return ou(wS,{children:e.map(s=>ou(nu,{suggestion:s,lines:t,onUse:r=>o(r,s)},s.text||s.url||s.message))})},su=TS;var Un={};J(Un,{enUS:()=>ES,nlNL:()=>kS});var ES={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"}]},kS={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 Yt={root:"dd-W9VCG",loginText:"dd--dS6t",stateText:"dd-348OC",footer:"dd-tvofr",shortcutList:"dd-MuKK-",shortcut:"dd-5CnK9",footerShortcut:"dd-dH7XJ",link:"dd-DRo0x"};import{jsx as L,jsxs as Kn}from"react/jsx-runtime";var iu=(t,e)=>{let n=te(Q);ci(()=>n?e.every(o=>!!o)?t():()=>{}:()=>{},[...e,n])},IS=({onLogIn:t})=>{let e=b("Widget",Yt),n=E("isEmbedded"),o=E("adminUrl");return L("div",{className:e.loginText,children:L("div",{children:L(cs,{isEmbedded:n,loginUrl:o,onLogIn:t})})},"login")},di=({text:t})=>{let e=b("Widget",Yt);return L("div",{className:e.stateText,children:L("div",{children:L("p",{children:t})})},"notification")},AS=()=>{let t=P(Un),e=ru(),n=b("Widget",Yt),o=E("showSearch"),s=E("isEmbedded"),r=te(Ze("/admin/")),i=oe(),a=E("productName"),d=z();return iu(()=>{if(s)return e(si()),()=>{e(Ac())}},[e,s]),!o&&!r?null:Kn("div",{className:n.shortcutList,children:[o&&L(M.Button,{"data-testid":"shortcut-search","aria-label":t("linkSearch"),className:n.shortcut,icon:L(qt,{}),onClick:()=>{i.send("ShowCommandPalette",{isOpen:!0}),d("open search",{via:"widget-shortcut"})},children:t("linkSearch")}),r&&L(M.Button,{as:"a",target:"_blank",icon:L(Uc,{}),href:r,"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})})]})},LS=({title:t,content:e})=>{let n=P(Un),[o,s]=PS(!0);return o?L(Me,{"data-testid":"custom-data-banner",type:"custom-data-banner",title:t,children:L(Y,{withDivider:!0,children:Kn(M,{children:[L(_,{children:L(_.Content,{children:L(vt,{content:e})})}),L(M.ButtonsContainer,{children:L(M.Button,{onClick:()=>s(!1),children:n("close")})})]})})}):null},MS=()=>{let t=ru(),e=te(Ln),n=te(Dl),o=te(Nc),s=te(va),r=te(Vo),i=te(Xo),a=te(et),d=te(Ce);return ci(()=>{s&&!n&&k.warn("Custom data provided, but no schema.")},[s,n]),iu(()=>{e.forEach(({type:l})=>{l==="entities"?t(fe()):Yn.includes(l)||t(he(l))})},[t,d,a]),ci(()=>{o.length>0&&!e.some(l=>l.type==="cues")&&k.warn("Received cues, but cues are not configured in widget.")},[e,o]),L(RS,{children:e.map(({type:l,title:c,amount:p,lines:u,schema:f,property:h})=>{var g,m;switch(l){case"entities":return r&&r.length>0&&L(Me,{type:l,title:c,"data-testid":`type-${l}`,children:L(Hc,{entities:r})},l);case"cues":return o&&o.length>0&&L(Me,{type:l,title:c,"data-testid":`type-${l}`,children:L(Y,{withDivider:!0,children:L(Zc,{cues:o})})},l);case"custom-data-banner":return s&&h&&s[h]&&L(LS,{title:c,content:String(s[h])},l);case"custom-data":return s&&f&&L(Me,{type:l,title:c,"data-testid":`type-${l}`,children:L(Y,{withDivider:!0,children:L(eu,{data:s,schema:f})})},l);default:return((m=(g=i[l])==null?void 0:g.suggestions)==null?void 0:m.length)>0&&L(Me,{type:l,title:c,"data-testid":`type-${l}`,children:L(Y,{withDivider:!0,children:L(su,{lines:u,contentType:l,suggestions:i[l].suggestions.slice(0,p)||[]})})},l)}})})},ui=({children:t})=>{let e=b("Widget",Yt);return L("div",{className:e.footer,children:t})},pi=({children:t})=>{let e=b("Widget",Yt);return L("div",{className:e.root,"data-testid":"widget",children:t})},NS=({onLogIn:t,knowledgeAssistOptions:e={},assistantOptions:n={transcript:"in-memory-transcript"}})=>{let o=P(Un),s=te(Dt),r=te(Q),i=te(oo),a=te(et),d=te(Ol("knowledge-assist")),l=te(_l);return s===!1?L(di,{text:o("notSupported")}):r===!1?L(IS,{onLogIn:t}):r===null?L(di,{text:o("waiting")}):!i||!a?L(di,{text:o("waitingForConversation")}):L(pi,{children:Kn(Fo,{initialQuestion:e.initialQuestion,assistantCode:l!=null?l:void 0,evaluateKnowledgeAssistFn:kn,children:[Kn(ln,{children:[L(AS,{}),L(MS,{}),d&&L(Bo,{title:d.title,emptyState:e.emptyState})]}),Kn(ui,{children:[d&&L(Ho,{}),L(Xc,{assistantOptions:n})]})]})})},au=NS;function zn(t){let e=new Range;return e.selectNodeContents(t),e}function lu(t,e,n){try{return Rt(t,e,n),!0}catch(o){return!1}}function Ts(t){return"tagName"in t&&(t.tagName==="DIV"||t.tagName==="P")}function ws(t){return"tagName"in t&&t.tagName==="BR"}var Wn=/[\u200B-\u200D\uFEFF]/g;function Rt(t,e,n){let o=new Range;if(t.firstChild===null&&e===0&&n===0)return o.selectNodeContents(t),o;let s=0,r=!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(Wn,""),p=s+c.length,u=e>=s&&e<=p,f=n>=s&&n<=p;if(u){let h=i(l,e-s);h===0&&!f?o.setStartBefore(d):o.setStart(d,h)}f&&(o.setEnd(d,i(l,n-s)),r=!0),s=p;break}case Node.ELEMENT_NODE:{if(ws(d)&&(s===e&&o.setStartBefore(d),s++,s===n)){o.setEndAfter(d),r=!0;return}for(let c=0;c<d.childNodes.length&&(a(d.childNodes[c]),!r);c++);let l=d.lastChild;Ts(d)&&l&&!Ts(l)&&!ws(l)&&s++;break}default:break}}if(a(t),o.startContainer===document)throw new Error("Offsets out of bound");return o}function Es(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:s,endOffset:r,collapsed:i}=e,a,d,l=0;function c(p){let u=p===t,f=p===n,h=p===s;switch(p.nodeType){case Node.TEXT_NODE:{let g=p.textContent;f&&(a=l+g.substring(0,o).replace(Wn,"").length),h&&(d=l+g.substring(0,r).replace(Wn,"").length),l+=g.replace(Wn,"").length;break}case Node.ELEMENT_NODE:{if(ws(p)&&p.nextSibling){l++;break}!u&&Ts(p)&&p.previousSibling&&l++;for(let g=0;g<p.childNodes.length;g++){let m=f&&g===o,S=h&&g===r;if(m&&(a=l),S&&(d=l),d!==void 0||((!m||!i)&&c(p.childNodes[g]),h&&g===r-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 ks(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:s,endOffset:r,collapsed:i}=e,a=0,d="";function l(c){let p=c===t,u=c===n,f=c===s;switch(u&&(a=1),c.nodeType){case Node.TEXT_NODE:{if(a!==1)return;let h=u?o:0,g=f?r:void 0;d+=c.textContent.replace(Wn,"").substring(h,g);break}case Node.ELEMENT_NODE:{if(!i&&a===1&&ws(c)&&c.nextSibling){d+=`
10
10
  `;break}!p&&!i&&a===1&&Ts(c)&&c.previousSibling&&(d+=`
11
- `);let h=u?o:0,g=f?Math.min(r,c.childNodes.length):c.childNodes.length;for(let m=h;m<g&&(l(c.childNodes[m]),a!==2);m++);break}default:break}f&&(a=2)}return l(t),d}var du=(i=>(i.CUT="Cut",i.BACKSPACE="Backspace",i.DELETE="Delete",i.ERASEEOF="EraseEof",i.UNDO="Undo",i.CLEAR="Clear",i))(du||{}),ot=class{constructor(e){this.element=e;this.isFocused=!1;this.isActive=!0;this.isDisposed=!1;this.eventListeners={};this.disposeHandlers=[];this.cachedText="";this.cachedSuggestionTextStart=0;this.cachedCaretPosition=null;this.cachedSelection={start:0,end:0};this.cachedHTML="";this.isSubmitting=!1;this.isPossibleClearInputAction=!1;this.cachedText=this.getText(),this.cachedSuggestionTextStart=this.getSuggestionTextStart(),this.cachedHTML=this.getHTML(),this.cachedSelection=this.getSelection(),this.listen()}addEventListener(e,n){let o=s=>{n(s)};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(),s=this.getSuggestionTextStart(),r=this.cachedCaretPosition===null;if(!this.isActive)return;e===""&&this.cachedText!==""&&!this.isPossibleClearInputAction&&this.emit("submit");let i=e!==this.cachedText,a=n!==null&&n!==this.cachedHTML,d=s!==this.cachedSuggestionTextStart;if((i||a||d)&&(i?(this.cachedText=e,this.cachedHTML=n):a&&(this.cachedHTML=n),this.cachedSuggestionTextStart=s,r=!0,this.emit("change",{plainText:e,rawHTML:n,suggestionTextStart:s})),(o.start!==this.cachedSelection.start||o.end!==this.cachedSelection.end)&&(this.cachedSelection=o,r=!0,this.emit("selection",o)),!r)return;let l=this.getCaretPosition();Xe(l,this.cachedCaretPosition)||(this.cachedCaretPosition=l,this.emit("caretposition",l))}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:s}=e;this.isPossibleClearInputAction=Object.values(du).includes(n)||n.toLowerCase()==="z"&&(o||s),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,s;let n=((o=e.clipboardData)==null?void 0:o.getData("text"))||((s=e.clipboardData)==null?void 0:s.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()})}getSuggestionTextStart(){return 0}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 cu(t){return t.top!==0||t.left!==0||t.height!==0||t.width!==0}var en=class extends ot{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),ks(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 s=o.rangeCount>0?o.getRangeAt(0):null;if(!s)return null;let r=this.element.ownerDocument.createRange();return r.setStart(s==null?void 0:s.startContainer,s==null?void 0:s.startOffset),r.setEnd(s==null?void 0:s.endContainer,s==null?void 0:s.endOffset),!r||!this.element.contains(r.startContainer)||!this.element.contains(r.endContainer)?null:r}getCaretPosition(){let n=this.getRange();if(!n||!n.collapsed||!("getBoundingClientRect"in n))return null;let o=n.getBoundingClientRect();return!cu(o)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),o=n.getBoundingClientRect(),n.deleteContents(),!cu(o))?null:{top:o.top+o.height,left:o.left}}getSelection(){let n=this.getRange();if(n)return Es(this.element,n);let o=this.lastKnownSelection;if(o&&lu(this.element,o.start,o.end))return o;let s=zn(this.element);return s.collapse(!1),Es(this.element,s)}getSelectedText(){let{start:n,end:o}=this.getSelection();return ks(this.element,Rt(this.element,n,o))}listen(){super.listen();let n=new MutationObserver(r=>{var i,a;r.length===2&&r[0].addedNodes.length===1&&((i=r[0].addedNodes[0])==null?void 0:i.textContent)==="\u2060"&&((a=r[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,s=new MutationObserver(()=>{this.element.isContentEditable!==o&&(o=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});s.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>s.disconnect())}};var OS=["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 uu(t,e){let n="mozInnerScreenX"in window,o=document.createElement("div");o.id="input-textarea-caret-position-mirror-div";let s=o.style,r=window.getComputedStyle(t),i=t.ownerDocument.body;s.whiteSpace="pre-wrap",s.wordWrap="break-word",s.position="absolute",s.visibility="hidden",OS.forEach(c=>{s[c]=r[c]}),n?t.scrollHeight>Number.parseInt(r.height)&&(s.overflowY="scroll"):s.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(r.borderTopWidth)+a.offsetHeight,left:d.left-t.scrollLeft+a.offsetLeft+Number.parseInt(r.borderLeftWidth)};return i.removeChild(o),l}var tn=class extends ot{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 uu(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 r;return(r=n==null?void 0:n.get)==null?void 0:r.call(this.element)},set:r=>{var i;(i=n==null?void 0:n.set)==null||i.call(this.element,r),this.handleInteraction()}}),this.addEventListener("scroll",()=>{this.emit("caretposition",this.getCaretPosition())});let o=this.element.disabled,s=new MutationObserver(()=>{this.element.disabled!==o&&(o=this.element.disabled,this.emit(o?"disabled":"enabled"))});s.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>s.disconnect())}};function pu(t,e,n){let o=`deepdesk-iframe-${t}`,s=document.getElementById(o);if(s)return s;let r=document.createElement("iframe"),i=new URL(e);return Object.entries(n).forEach(([a,d])=>{i.searchParams.append(a,d)}),r.style.position="absolute",r.style.left="-999em",r.style.width="0px",r.style.height="0px",r.tabIndex=-1,r.id=o,r.title=`iframe-${t}`,r.src=i.toString(),window.document.body.appendChild(r),r}function DS(t){if(typeof t!="string")return t;try{return JSON.parse(t)}catch(e){return t}}var gi=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()}},mi=class{constructor(e,n,o){this.name=e;this.targetOrigin=n;this.options=o;this.disposeHandlers=[];this.iframe=pu(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()}},fi=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(),k.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 mi(e,this.deepdeskUrl,{debug:!0}):new gi(e),o=s=>{var i,a;if(s.origin!==this.deepdeskUrl)return;let r=DS(s.data);typeof r!="object"||r.type!=="event"||r.channel!==e||(k.info("Received broadcast event",this.externalId,s),(a=(i=this.eventMap)[r.name])==null||a.call(i,r.payload))};return n.onMessage(o),n}send(e,n,o){var i,a;k.info("Broadcast event",{externalId:this.externalId,name:e,payload:n});let s={type:"event",name:e,payload:n};o!==!1&&((a=(i=this.eventMap)[e])==null||a.call(i,n));let r=this.externalId==="deepdesk-general"?this.defaultChannel:this.channel;r==null||r.postMessage(x(y({},s),{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)}},gu=fi;function _S(t){return t.replace(/(_\w)/g,e=>e[1].toUpperCase())}function B(t){return Array.isArray(t)?t.map(B):typeof t=="object"&&t!==null?Object.keys(t).reduce((e,n)=>x(y({},e),{[_S(n)]:B(t[n])}),{}):t}function FS(t){return t.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}function Z(t){return Array.isArray(t)?t.map(Z):typeof t=="object"&&t!==null?Object.keys(t).reduce((e,n)=>x(y({},e),{[FS(n)]:Z(t[n])}),{}):t}var nn=class extends Error{constructor(n,o){super(n);this.body=o;this.name="CustomError"}};var Vn=t=>new Promise(e=>{setTimeout(e,t)});var xe=class extends nn{constructor(){super(...arguments);this.name="ClientError"}},Rs=class extends nn{constructor(){super(...arguments);this.name="ServerError"}},hi=new Map;function mu(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:(k.warn("Unexpected response body:",n.slice(0,20)),JSON.parse(n))})}var on=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,s)=>{let r={isAborted:!1,reject:s},i=`${this.baseUrl}${e}`,a=this.fetch,d=n.method===void 0||n.method.toLowerCase()==="get",R=n,{useCache:l=!1,abortLatest:c=!1,attempts:p=1,retryDelay:u=500,refreshTokenOn401:f=!0,retryOnError:h=I=>I instanceof TypeError,retryOnResponse:g=I=>I.status>=500,version:m=null}=R,S=O(R,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]);if(l){if(!d)throw new Error(`Can't use 'useCache' for ${n.method}`);if(hi.has(i)){o(hi.get(i));return}}let C=x(y({credentials:"include"},S),{headers:y({Accept:"application/json","Content-Type":"application/json"},S.headers)});!d&&this.csrfToken&&(C.headers=x(y({},C.headers),{"X-CSRFToken":this.csrfToken})),typeof m=="string"&&(C.headers=x(y({},C.headers),{"X-Deepdesk-API-Version":m}));let T=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]=r;let A=()=>v(this,null,function*(){return T--,a(i,C).then(I=>v(this,null,function*(){return g(I)&&!r.isAborted&&T>0?(yield Vn(u),A()):I.status===401&&f===!0&&w===!1?(w=!0,yield this.refreshToken(),A()):I})).catch(I=>v(this,null,function*(){if(h(I)&&!r.isAborted&&T>0)return yield Vn(u),A();throw I}))});A().then(I=>v(this,null,function*(){let U=yield mu(I);if(delete this.latestRequestByUrl[i],I.status>=500){s(new Rs("Server Error",U));return}if(I.status===401){s(new xe("Unauthorized",U));return}if(I.status===403){s(new xe("Forbidden",U));return}if(I.status===404){s(new xe("Not Found",U));return}if(I.status>=400){s(new xe("Bad Request",U));return}l&&hi.set(i,U),o(U)})).catch(I=>{s(I)})})}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(s){return!1}if(!e){if(!o)return!1;try{yield this.refreshToken();let{is_logged_in:s}=yield this.get("/apis/admin/session/validate/",{refreshTokenOn401:!1});return s}catch(s){return!1}}return n})}refreshToken(){let e=Date.now();return this.lastFailedRefreshAt&&e-this.lastFailedRefreshAt<this.failedRefreshCooldown?Promise.reject(new xe("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))}postWithStatus(e,n,o){return this.requestWithStatus(e,y({method:"POST",body:JSON.stringify(n)},o))}requestWithStatus(e,n={}){return new Promise((o,s)=>{let r={isAborted:!1,reject:s},i=`${this.baseUrl}${e}`,a=this.fetch,A=n,{useCache:d=!1,abortLatest:l=!1,attempts:c=1,retryDelay:p=500,refreshTokenOn401:u=!0,retryOnError:f=R=>R instanceof TypeError,retryOnResponse:h=R=>R.status>=500,version:g=null}=A,m=O(A,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]),S=x(y({credentials:"include"},m),{headers:y({Accept:"application/json","Content-Type":"application/json"},m.headers)});this.csrfToken&&(S.headers=x(y({},S.headers),{"X-CSRFToken":this.csrfToken})),typeof g=="string"&&(S.headers=x(y({},S.headers),{"X-Deepdesk-API-Version":g}));let C=c,T=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[i]&&l&&(this.latestRequestByUrl[i].isAborted=!0,this.latestRequestByUrl[i].reject(new Error("Aborted"))),this.latestRequestByUrl[i]=r;let w=()=>v(this,null,function*(){return C--,a(i,S).then(R=>v(this,null,function*(){return h(R)&&!r.isAborted&&C>0?(yield Vn(p),w()):R.status===401&&u===!0&&T===!1?(T=!0,yield this.refreshToken(),w()):R})).catch(R=>v(this,null,function*(){if(f(R)&&!r.isAborted&&C>0)return yield Vn(p),w();throw R}))});w().then(R=>v(this,null,function*(){let I=yield mu(R);if(delete this.latestRequestByUrl[i],R.status>=500){s(new Rs("Server Error",I));return}if(R.status===401){s(new xe("Unauthorized",I));return}if(R.status===403){s(new xe("Forbidden",I));return}if(R.status===404){s(new xe("Not Found",I));return}if(R.status>=400){s(new xe("Bad Request",I));return}o({status:R.status,data:I})})).catch(R=>{delete this.latestRequestByUrl[i],s(R)})})}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 fu;(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={}))})(fu||(fu={}));function Ps(t){return x(y({},B(t)),{metadata:t.metadata})}var Pt=class Pt{constructor(e,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new on(e,{fetch:n.fetch}),this.client.patchFetch(o=>(s,r)=>v(this,null,function*(){let i=yield o(s,r);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?(Pt.exchangeTokenPromise||(Pt.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),Pt.exchangeTokenPromise):Promise.resolve()})}createConversation(e){return v(this,null,function*(){var o;yield this.preflight(),k.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()},Z(e)),{metadata:(o=e.metadata)!=null?o:{}}));return Ps(n)})}upsertConversation(e){return v(this,null,function*(){var c;yield this.preflight(),k.info(`Upserting conversation for session ${e.externalId} and agent ${e.agentId}`);let{status:n,data:o}=yield this.client.postWithStatus("/api/v2/conversations",x(y({chat_start_time:new Date().toISOString()},Z(e)),{metadata:(c=e.metadata)!=null?c:{}}),{version:"v2"}),s=Ps(o);if(n===201)return s;let{agentId:r,agentName:i,agentEmail:a,agentNickname:d,metadata:l}=e;return this.updateConversation(s.id,{agentId:r,agentEmail:a,agentName:i,agentNickname:d,metadata:l})})}getMe(){return v(this,null,function*(){let e=yield this.client.get("/apis/admin/session/me/");return B(e)})}postIdentity(e){return v(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/me/identities/",Z(e))})}patchMe(e){return v(this,null,function*(){yield this.preflight();let n=yield this.client.patch("/apis/admin/session/me/",Z(e));return B(n)})}getProfile(e){return v(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${e}/`,{useCache:!0});return B(n)})}getKnowledgeAssistant(e){return v(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${e}/`,{useCache:!0});return B(n)})}getContentTypes(){return v(this,null,function*(){let e=yield this.client.get("/apis/admin/content-types/",{useCache:!0});return B(e)})}getAccount(){return v(this,null,function*(){let e=yield this.client.get("/apis/admin/account/",{useCache:!0});return B(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 B(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(),k.info(`Getting conversation for session ${e}`);let{attempts:s=1,retryDelay:r=1e3}=n,i=yield this.client.get(`/api/v2/conversations/by_external_id/${e}`,{attempts:s,retryDelay:r,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"});return k.info(`Successfully retrieved conversation ${i.id} for session ${e}`),Ps(i)})}isConversationSupported(o){return v(this,arguments,function*(e,n={}){k.info(`Check if conversation for session ${e} is supported`);let{attempts:s=1,retryDelay:r=1e3}=n;return(yield this.client.get(`/api/v2/conversations/by_external_id/${e}/has_active_profile`,{attempts:s,retryDelay:r,retryOnResponse:a=>a.status===404||a.status>=500})).has_active_profile})}updateConversation(e,n){return v(this,null,function*(){var r;yield this.preflight();let o=Z(n);n.metadata&&(o.metadata=(r=n.metadata)!=null?r:{});let s=yield this.client.put(`/api/v2/conversations/${e}`,o);return Ps(s)})}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({},Z(o)),{metadata:o.metadata})))})}sendEvent(e,n){return v(this,null,function*(){yield this.preflight();let a=n,{data:o}=a,s=O(a,["data"]),r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((d,[l,c])=>x(y({},d),{[l]:c}),{}),i=["platform","agentId","agentName","agentEmail","conversationId"].reduce((d,l)=>(s[l]&&(d[l]=s[l]),d),{});return this.client.post("/api/v2/events",Z(x(y(y({},r),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 k.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/",Z(n),{refreshTokenOn401:!1,headers:{apikey:e}})})}getTextSuggestions(s){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}`,Z(n),{abortLatest:!0})).map(i=>x(y({},B(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`,Z(n),{abortLatest:!0})).map(s=>({score:1,source:s.source,sourceText:s.source_text,text:s.label,trainingJobs:s.training_jobs,searchKeywords:s.search_keywords,type:s.source})).filter((s,r,i)=>r===i.findIndex(a=>a.text===s.text))})}getPinnedMessages(e){return v(this,null,function*(){let n=yield this.client.get(`/api/v2/profiles/${e}/pinned-messages`,{abortLatest:!0});return B(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",Z(e),{abortLatest:!0,version:"v2"});return B(n)})}search(e){return v(this,null,function*(){let n=yield this.client.post(`/api/v2/profiles/${e.profile}/search`,Z(e));return B(n)})}loginWithPassword(e,n){return v(this,null,function*(){yield this.preflight();let o=yield this.client.post("/apis/admin/session/login/",{username:e,password:n},{refreshTokenOn401:!1});return B(o)})}logout(){return v(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/logout/",{},{refreshTokenOn401:!1})})}requestLoginByEmail(e){return v(this,null,function*(){yield this.preflight();let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:e});return B(n)})}requestPasswordlessToken(){return v(this,null,function*(){let e=yield this.client.get("/apis/admin/session/passwordless/request/");return B(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 B(n)})}evaluateAssistant(e,n){return v(this,null,function*(){var d,l,c;yield this.preflight();let o=new URLSearchParams;n!=null&&n.externalConversationId&&o.append("external_conversation_id",n.externalConversationId);let s=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()}`,r=p=>Z(p),i=(d=n==null?void 0:n.transcript)==null?void 0:d.map(p=>{var u;return y({source:p.source,text:p.text},(u=p.attachments)!=null&&u.length?{attachments:p.attachments.map(r)}:{})}),a=yield this.client.post(s,y({input:(l=n==null?void 0:n.input)!=null?l:{},conversation:i},(c=n==null?void 0:n.attachments)!=null&&c.length?{attachments:n.attachments.map(r)}:{}));return B(a)})}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 B(o)})}postMessageToAssistantThread(e){return v(this,null,function*(){yield this.preflight();let{assistantCode:n,threadId:o,message:s}=e,r=yield this.client.post(`/apis/admin/assistants/${n}/threads/${o}/messages/`,{content:s,role:"user"});return B(r)})}translateMessages(e){return v(this,null,function*(){yield this.preflight();let n=yield this.client.post("/api/v2/translate",Z(e));return B(n)})}handleDeepdeskVersionHeaders(e){e.headers.forEach((n,o)=>{let s=o.toLowerCase(),r=s.match(zi);if(!n||!r)return;let i=r[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&n&&a!==n&&k.warn(`Overwritten Version header ${s}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[i]=n})}};Pt.exchangeTokenPromise=null;var st=Pt;var Is=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=B(JSON.parse(e.data));o.event&&this.eventListeners.has(o.event)&&((n=this.eventListeners.get(o.event))==null||n.forEach(s=>s(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=[]}};import{combineReducers as KS,configureStore as WS}from"@reduxjs/toolkit";import{createSlice as HS}from"@reduxjs/toolkit";var hu={startTime:null,stopTime:null},yu=t=>t.handlingTime,vu=HS({name:"handlingTime",initialState:hu,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,()=>hu)}}),{handlingTimeStart:Su,handlingTimeStop:As,handlingTimeReset:xu}=vu.actions,bu=vu.reducer;var Cu=(t={})=>{let e=y({onAuthError:Nt(!1)},t);return n=>o=>s=>("error"in s&&s.error.message==="Unauthorized"&&n.dispatch(e.onAuthError),o(s))};var Tu=(t={})=>{let e,n=!0,o=y({getStyleSuggestions:Tt,debounce:500},t);return s=>r=>i=>{var f;let a=s.getState().input.text,d=r(i),l=s.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,s.dispatch(o.getStyleSuggestions({text:u}))},t.debounce)),d}};function BS(t,e){return t.text===e.text&&t.selection.start===e.selection.start&&t.selection.end===e.selection.end&&t.suggestionTextStart===e.suggestionTextStart}var wu=(t={})=>{let e=y({getTextSuggestions:he,getAutocompleteSuggestions:_n,debounce:200,check:Re},t),n;return o=>s=>r=>{var g;let{input:i}=o.getState(),a=s(r),d=o.getState();if(d.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:l,showTabCompletion:c}=d.settings,p=(g=d.conversation.current)==null?void 0:g.id,u=r.type===Jo.toString();if(!p||!l&&!c)return a;let{input:f}=d;return BS(f,i)&&!u||(clearTimeout(n),!e.check(d))||(n=setTimeout(()=>{let m=dt(d);m===""?o.dispatch(e.getTextSuggestions("default")):o.dispatch(e.getAutocompleteSuggestions(m))},u?0:e.debounce)),a}};var Eu=Tt.fulfilled.toString();function US(t,e){let n=new Set([...e.keywordMatches.map(s=>s.keyword)]),o=[];return n.forEach(s=>{let r=t.keywordMatches.filter(d=>d.keyword===s),i=e.keywordMatches.filter(d=>d.keyword===s),a=i.length-r.length;a<=0||o.push(...i.slice(0,a))}),o}var ku=t=>e=>n=>o=>{var l;if(o.type!==Eu){n(o);return}let s=e.getState().styleSuggestions.list;n(o);let r=e.getState(),i=r.styleSuggestions.list,a=(l=r.conversation)==null?void 0:l.current;if(s===i)return;let d=US(s,i);o.type===Eu&&d.length>0&&t.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:d}})};var zS=KS({assistants:Za,auth:Qi,conversation:na,contentTypes:Ml,passwordlessToken:Lc,entities:rd,handlingTime:bu,info:Ea,input:fa,settings:el,profile:Fl,search:La,styleSuggestions:Gd,ui:Dd,textSuggestions:Sd});function Ru(t){return WS({reducer:zS,middleware:e=>{var o;let n=e({thunk:{extraArgument:{dynamicThunkObject:t.dynamicThunkObject,deepdeskAPI:t.deepdeskAPI}},serializableCheck:!1}).concat(Cu()).concat(wu({debounce:200})).concat(Tu({debounce:500})).concat(ku(t.deepdeskAPI));return((o=t.middleware)!=null?o:[]).reduce((s,r)=>s.concat(r),n)},preloadedState:t.preloadedState})}function Pu(t,e,n){if(e==="")return null;let o=new RegExp(`\\b${gs(e)}\\b`,"gi"),s,r=null;for(;(s=o.exec(t))!==null&&!(s.index>n);)r={start:s.index,end:s.index+s[0].length};return r}var VS=t=>{var e,n;return(n=(e=t==null?void 0:t.type)==null?void 0:e.toLowerCase())!=null?n:"unknown"},jS=t=>e=>n=>o=>{var d,l,c,p,u,f;let s=e.getState(),r=ft("inlineSuggestions")(s),i=ft("autoSelectSuggestion")(s)||r;switch(o.type){case Nt.toString():{!o.payload&&t.emit("logout",void 0);break}case to.fulfilled.toString():{t.emit("logout",void 0);break}case fe.fulfilled.toString():o.payload.length>0&&t.sendEvent("entities found",{conversationId:(d=s.conversation.current)==null?void 0:d.id,data:{entities:o.payload}});break;case pt.toString():t.logSendMessage(o.payload);break;case ko.toString():t.emit("call-to-action",{cue:o.payload});break;case se.fulfilled.toString():if(!o.isBroadcasted){let{externalConversationId:h,currentExternalIdAtRequest:g}=(l=o.payload)!=null?l:{};(!h||!g||h===g)&&t.broadcast(Qs,o,!1)}break;case se.rejected.toString():break;default:break}let a=n(o);switch(o.type){case pt.toString():t.handleAfterSendMessage(o.payload);break;case Fn.toString():t.onUpdateShowTabHint(o.payload);break;case As.toString():t.logHandlingTime();break;case Ft.toString():t.broadcast(ho,o);break;case ut.toString():t.broadcast(ho,o);break;case Ro.toString():e.dispatch(ut({source:"assistant",assistantCode:o.payload.code}));break;case"analytics/logEvent/fulfilled":{let h=s.assistants.cues.find(g=>g.code===o.meta.arg.data.assistantCode);t.emit("event",x(y({},o.meta.arg),{cue:h}));break}case ie.toString():{let{start:h,end:g}=s.input.selection;t.emit("select-suggestion",x(y({type:VS(o.payload.suggestion)},o.payload),{replace:o.payload.replace==="selection"?{start:h,end:g}:{start:0,end:g}})),r&&e.dispatch(Je([]));break}case qd.toString():{let{keyword:h,suggestion:g,eventMetrics:m}=o.payload,{text:S,selection:C}=s.input,T=Pu(S,h,(c=C==null?void 0:C.end)!=null?c:S.length);if(!T)break;t.emit("select-suggestion",{text:g,type:"style",replace:T,suggestion:{text:g,source:"style"},eventMetrics:m});break}case ao.toString():t.emit("select-image",o.payload),t.sendEvent("Image attached",{conversationId:(p=s.conversation.current)==null?void 0:p.id,data:{path:o.payload.suggestion.image,title:o.payload.suggestion.title}});break;case Je.toString():{i&&o.payload.length>0&&e.dispatch(lo(0));break}case se.fulfilled.toString():{let{evaluationId:h,output:g,externalConversationId:m}=o.payload,S=o.meta.arg.assistantCode;if(t.emit("event",{name:"Assistant evaluation completed",data:{evaluationId:h,assistantCode:S,assistantOutput:qa(g),externalConversationId:m,evaluationStatus:"success"}}),!o.meta.arg.skipState){let C=e.getState().assistants.cues;t.emit("cues",C)}break}case se.rejected.toString():{let h=o.meta.arg.assistantCode,g=(f=o.meta.arg.externalConversationId)!=null?f:(u=e.getState().conversation.current)==null?void 0:u.externalId;t.emit("event",{name:"Assistant evaluation completed",data:{evaluationId:"",assistantCode:h,assistantOutput:"",externalConversationId:g,evaluationStatus:"failed"}});break}default:break}return a},Iu=jS;import{createSelector as $S}from"@reduxjs/toolkit";function yi(t){return t.toISOString().replace("T"," ").replace("Z","")}var qS=(t,e)=>e.version,Au=$S([Ht,Ce,yu,qS],(t,e,n,o)=>{if(!e)return k.warn("No conversationId for handling time metrics"),null;let{startTime:s,stopTime:r}=n;return!s||!r?(k.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:yi(s),timeStop:yi(r)}});function Lu(t,e){let{text:n,metrics:{numPaste:o,pastes:s,textSuggestions:r}}=t.input,i=n.length;return{source:"agent",clientVersion:e.version,pastes:s,lenTextTotal:i,numPastes:o,suggestions:r}}var jn=class extends Error{};function GS(){let t,e;return{promise:new Promise((o,s)=>{t=o,e=s}),resolve:t,reject:e}}var Ls=class{constructor(){this.queues={}}push(e,n){let o=()=>{let r=this.queues[e][1];r?(this.queues[e]=[r.promise,null],r.resolve()):delete this.queues[e]};if(!this.queues[e]){let r=n().finally(o);return this.queues[e]=[r,null],r}this.queues[e][1]&&this.queues[e][1].reject(new jn("Queued async function is outdated"));let s=GS();return this.queues[e][1]=s,s.promise.then(()=>n().finally(o))}};function vi(t,e){var r;let n=t.closest(e);if(n)return n;let o=t.getRootNode().host;if(o instanceof HTMLElement)return vi(o,e);let s=(r=t.ownerDocument.defaultView)==null?void 0:r.frameElement;return s?vi(s,e):null}function Si(t,e){return vi(t,e)}var XS={accepted:"onConversationAcceptedAssistants","new-message":"onConversationNewMessageAssistants",ended:"onConversationEndedAssistants"},Mu=(t,e)=>{var s,r,i;if(!((i=(r=(s=t.uiConfig)==null?void 0:s.widget)==null?void 0:r.types.find(a=>a.type==="cues"))==null?void 0:i.isActive))return k.warn("Triggered a conversation assistant, but cues are not configured in widget."),[];let o=t[XS[e]];return o&&o.length>0?o.map(a=>a.code):(k.warn(`No assistant set in profile for conversation event "${e}"`),[])};function Nu(t){return typeof t=="object"&&t!==null&&"name"in t&&"message"in t}function JS(t){return typeof t=="object"&&t!==null&&"tagName"in t}function xi(t){return JS(t)&&(Et(t)||us(t))}var Du,Pe=new Map,QS=["bottom","height","left","right","top","width"],Ou=(t,e)=>!t&&!e?!1:t&&!e||!t&&e?!0:QS.some(n=>t[n]!==e[n]);function _u(t){var n,o,s;if(t.ownerDocument===document)return[];let e=(s=(o=(n=t.ownerDocument)==null?void 0:n.defaultView)==null?void 0:o.frameElement)!=null?s:null;return e?[e,..._u(e)]:[]}function Fu(t,e){return!t||!e?null:x(y({},t),{top:t.top+e.top,left:t.left+e.left})}var Ms=!1,Hu=()=>{Ms=!0;let t=[];if(Pe.forEach((e,n)=>{if(!n.isConnected){e.rect=null,t.push(e),Pe.delete(n);return}let o=n.getBoundingClientRect();Ou(o,e.rect)&&(e.rect=o,t.push(e))}),t.forEach(e=>{let n=e.parentRects?e.parentRects.reduce(Fu,e.rect):e.rect;Ou(n,e.totalRect)&&e.callbacks.forEach(o=>o(n)),e.totalRect=n}),Pe.size===0){Ms=!1;return}Du=window.requestAnimationFrame(Hu)};function bi(t,e){let n=_u(t),o=[],s=n.map((r,i)=>bi(r,a=>{o[i]=a;let d=Pe.get(t);if(!d)return;let l=o.reduce(Fu,d.rect);d.callbacks.forEach(c=>c(l))}));return{observe(r=!0){if(s.forEach(i=>i.observe(!1)),Pe.has(t)){let i=Pe.get(t);i.callbacks.push(e),i.rect&&e(i.rect)}else Pe.set(t,{rect:void 0,callbacks:[e],parentRects:o});r&&!Ms&&Hu()},unobserve(){s.forEach(i=>i.unobserve());let r=Pe.get(t);if(r){let i=r.callbacks.indexOf(e);i>=0&&r.callbacks.splice(i,1),r.callbacks.length||Pe.delete(t),Pe.size||(cancelAnimationFrame(Du),Ms=!1)}}}}var Bu,Ie=new Map,Uu=()=>{Ie.forEach((t,e)=>{if(!e.isConnected){Ie.delete(e);return}let{clientHeight:n,scrollHeight:o}=e,s=o>n;t.visible!==s&&(t.visible=s,t.callbacks.forEach(r=>r(t.visible)))}),Ie.size!==0&&(Bu=window.requestAnimationFrame(Uu))};function Ku(t,e){return{observe(){let n=Ie.size===0;Ie.has(t)?Ie.get(t).callbacks.push(e):Ie.set(t,{visible:void 0,callbacks:[e]}),n&&Uu()},unobserve(){let n=Ie.get(t);if(n){let o=n.callbacks.indexOf(e);o>=0&&n.callbacks.splice(o,1),n.callbacks.length||Ie.delete(t),Ie.size||cancelAnimationFrame(Bu)}}}}var Ci=["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 Ti(t,e,n){return n.forEach(o=>{e.style[o]=t[o]})}function sn(t){return Number.parseFloat(t)}function Ns(t){return Math.round(t*1e6)}function Wu(t){return t/1e6}function wi(t,e,n){if(t.boxSizing==="content-box")return;let{clientWidth:o}=e,s=sn(t.width),r=sn(t.borderLeftWidth),i=sn(t.borderRightWidth),a=sn(t.paddingRight),d=Wu(Ns(s)-Ns(r)-Ns(i)),l=Wu(Ns(o));if(d-l>2){let c=d-l;n.style.paddingRight=`${a+c}px`}}function Os(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",yt(n);let o=window.getComputedStyle(t),s=!0,r=()=>{n.scrollTop=t.scrollTop};Ti(o,n,Ci),wi(o,t,n),e.mirrorOverflow&&(n.style.overflow="hidden",t.addEventListener("scroll",r));let i=Ku(t,()=>{Ti(o,n,Ci),wi(o,t,n),r(),setTimeout(r,0)}),a,d=!0,l=bi(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(s===!0)return;e.onHide&&e.onHide(),n.style.display="none",s=!0;return}if(Ti(o,n,Ci),wi(o,t,n),r(),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),g=sn(h.borderTopWidth),m=sn(h.borderBottomWidth),S=f.top+g-u.top,C=u.top+u.height+-(f.top+f.height-m);n.style.clipPath=`inset(${S}px 0px ${C}px 0px)`}s&&(n.style.display="block",e.onShow&&e.onShow(),s=!1)});return e.appendTo?e.appendTo.appendChild(n):(p=t.parentElement)==null||p.appendChild(n),l.observe(),i.observe(),[n,()=>{t.removeEventListener("scroll",r),l.unobserve(),i.unobserve(),n.remove()}]}function ZS(t){return t.offsetParent!==null}function zu(t){if(!ZS(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 Ei(t,e,n=100){let o=zu(t);e({isVisible:o});let s=setInterval(()=>{let r=zu(t);r!==o&&(o=r,e({isVisible:o}))},n);return()=>{clearTimeout(s)}}var Vu=(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){k.warn("[Deepdesk] SessionStorage is blocked by browser")}}});import{jsx as F,jsxs as YS}from"react/jsx-runtime";var ju=Vu("showTabHint",!0),rn=class rn{constructor({deepdeskUrl:e,version:n=rn.version||"unknown",locale:o="en-US",token:s,fetch:r,productName:i,createCustomChannel:a,websocketClient:d=Is}){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 Ls;this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;let l=e.replace(/\/api$/,"");this.deepdeskApi=new st(l,{token:s,fetch:r}),this.version=n,this.instanceId=rn.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[Iu({broadcast:(h,g,m)=>{this.broadcastEvents.send(h,g,m)},emit:(h,g)=>this.emit(h,g),handleAfterSendMessage:h=>this.handleAfterSendMessage(h),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:h=>this.logSendMessage(h),onUpdateShowTabHint:h=>ju.update(h),sendEvent:(h,g)=>this.deepdeskApi.sendEvent(h,g)})]};this.store=Ru(c),this.broadcastEvents=new gu({debug:!0,deepdeskUrl:l,eventMap:Ma(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=Q(this.state))!=null?h:!1})}),this.whenLoggedIn(()=>this.ws.connect()),this.store.dispatch(Fn(ju.value())),this.store.dispatch(Po({locale:o,adminUrl:l,productName:i}));let p=[],u=h=>{if(!h.conversationId)return;let g=()=>{this.conversationId()===h.conversationId&&this.store.dispatch(Qa(h))};this.hasConversation()?g():p.push(g)};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 g=()=>{this.conversationId()===h.conversationId&&this.store.dispatch(Ja(h))};this.hasConversation()?g():p.push(g)}),this.ws.on("assistants::suggest_as_reply",h=>{if(!h.conversationId)return;let g=()=>{this.conversationId()===h.conversationId&&this.store.dispatch(Ft([{text:h.payload.message,type:"text",source:"assistant",assistantCode:h.code,sourceLabel:h.name}]))};this.hasConversation()?g():p.push(g)});let f=this.whenConversationLoaded(()=>{var h;this.broadcastEvents.setExternalId((h=this.state.conversation.current)==null?void 0:h.externalId),p.forEach(g=>g()),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=ct(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?(k.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(k.warn("Profile has not been loaded (yet)"),!0):(k.warn("No conversation loaded (yet)"),!0)}whenLoggedIn(e){if(Q(this.state))e();else{let n=this.subscribe(Q,o=>{o&&e()});this.disposeHandlers.push(()=>{n()})}}login(){return this.store.dispatch(Nt(null)),this.store.dispatch(Oe()),new Promise(e=>{this.whenLoggedIn(()=>e())})}isLoggedIn(){return v(this,null,function*(){return(yield this.store.dispatch(Oe())).payload})}isConversationSupported(e,n){return v(this,null,function*(){return(yield this.store.dispatch(Vs({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(so(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(ro({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($s(e))})}updateConversation(e){return v(this,null,function*(){return(yield this.store.dispatch(io(e))).payload})}resetConversation(){this.store.dispatch(j()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}configure(e){this.store.dispatch(Po(e))}setVisitorInfo(e){this.store.dispatch(ba(e))}setCustomData(e){this.store.dispatch(Ca(e))}setAgentInfo(e,n){return v(this,null,function*(){var s;yield this.store.dispatch(gn(y(y({},e),n))),(s=this.state.info.agentInfo)!=null&&s.agentNickname||this.broadcastEvents.send(fo,{showNicknameDialog:!0})})}setAgentSettings(e){return v(this,null,function*(){yield this.store.dispatch(Gs(e))})}getAgentSettings(){return v(this,null,function*(){return(yield this.store.dispatch(Xs())).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(co({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),suggestionTextStart:this.inputMediator.getSuggestionTextStart()}))}notifyExternalSuggestion(e){this.store.dispatch(ie(e))}evaluateAssistant(e,n){return v(this,null,function*(){var c;let{input:o={},attachments:s=[],transcript:r,showCuesInWidget:i=!0,includeMetadata:a,externalConversationId:d}=n||{},l=yield this.store.dispatch(se({assistantCode:e,attachments:s,transcript:r,includeMetadata:a,input:o,externalConversationId:d,skipState:!i}));if(l.error)throw new Error(`Assistant evaluation failed: ${(c=l.payload)!=null?c:l.error.message}`);return l.payload.output})}evaluateConversationAssistant(e,n){return v(this,null,function*(){var c,p,f;yield this.loadProfileConfig();let o=this.state.profile.data;if(!o&&((c=this.state.conversation.current)!=null&&c.profileCode)&&(yield this.loadProfileConfig(),o=this.state.profile.data),!o){k.warn("Can't evaluate assistant when profile is not loaded yet.");return}let s=Mu(o,e),r=(p=n==null?void 0:n.showCuesInWidget)!=null?p:!0,u=n!=null?n:{},{showCuesInWidget:i}=u,a=O(u,["showCuesInWidget"]),d=(f=n==null?void 0:n.externalConversationId)!=null?f:this.hasConversation()?this.externalId():"",l=yield Promise.all(s.map(h=>this.queues.push(h,()=>v(this,null,function*(){var m,S;let g=yield this.store.dispatch(se(y(x(y({assistantCode:h,includeMetadata:!0},a),{skipState:!r}),n!=null&&n.attachments&&(n==null?void 0:n.attachments.length)>0?{attachments:n==null?void 0:n.attachments}:{})));if(g.error)throw new Error(`Assistant evaluation failed: ${(m=g.payload)!=null?m:g.error.message}`);return{assistantCode:h,evaluationId:g.payload.evaluationId,output:g.payload.output,externalConversationId:(S=g.payload.externalConversationId)!=null?S:d}})).catch(g=>{if(g instanceof jn)return k.warn(`Queued assistant "${h}" was outdated and dropped`),null;throw g})));if(!r)return l.filter(h=>h!==null)})}handleKeyDown(e){let{overlayCollapsed:n,openOverlayWhenTyping:o}=this.state.ui,{textSuggestions:s,selectedSuggestionIndex:r,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=s.length>0;if(this.store.dispatch(la(qs(e))),!Re(this.state)||e.key!=="Tab"&&!l)return;let h=()=>{n||!f||i&&(e.shiftKey||(this.store.dispatch(ua()),e.preventDefault()))},g=()=>{n||!f||p&&r<=0||i&&(e.shiftKey||(this.store.dispatch(pa()),e.preventDefault()))};switch(e.key){case"ArrowUp":u==="below"?g():h();break;case"ArrowDown":{u==="below"?h():g();break}case"Escape":{n||(this.store.dispatch(lo(-1)),this.store.dispatch(tt({collapse:!0})),this.store.dispatch(Nd(!0)),e.preventDefault());break}case"Tab":{e.preventDefault();let m=_t(this.state);if(!m)return;this.store.dispatch(Fn(!1)),this.store.dispatch(ie({text:m.text,suggestion:m,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(p||this.state.input.selectedSuggestionIndex===-1)return;let m=_t(this.state);if(!m)return;this.store.dispatch(ie({text:m.text,suggestion:m,eventMetrics:{inputType:"space"},replace:"until-selection-end"}));break}case"Enter":{if(p||e.shiftKey||this.state.input.selectedSuggestionIndex===-1)return;let m=_t(this.state);if(!m)return;this.store.dispatch(ie({text:m.text,suggestion:m,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),e.preventDefault();break}default:}n&&o&&this.store.dispatch(tt({collapse:!1}))}handleAfterSendMessage(e){this.emit("send-message",e),this.store.dispatch(Je([]))}handlingTimeStart(){this.state.handlingTime.startTime||(k.info("Start handling time"),this.store.dispatch(Su()))}handlingTimeStop(){this.state.handlingTime.startTime&&(k.info("Stop handling time"),this.store.dispatch(As()))}logSendMessage(e){let n=Lu(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=Au(this.state,{version:this.version});e&&(this.deepdeskApi.sendEvent("Handling Time",{conversationId:this.conversationId(),data:e}),this.store.dispatch(xu()))}notifySubmit(e={}){var n;this.shouldAbort()||(this.store.dispatch(pt((n=e.text)!=null?n:this.state.input.text)),this.store.dispatch(ma()))}emit(e,n){let o=this.eventListeners[e];o&&o.forEach(s=>{try{s(n)}catch(r){k.warn(`The following error occurred in deepdeskSDK.on('${e}', handler)`),k.error(r)}})}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(Ta(e))}whenConversationLoaded(e){let n=r=>{var i;return(i=r.conversation.current)==null?void 0:i.id},o=()=>this.loadProfileConfig().then(()=>e());return n(this.state)&&o(),this.subscribe(n,r=>{r&&o()})}overlayContainerFactory(e,n,o,s){let[r,i]=Os(n,o);return r.setAttribute("translate","no"),r.dataset.testid=e,s&&r.classList.add(s),[r,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 s=document.createElement("div");s.style.display="none",s.style.position="absolute",s.style.height="0px",s.style.width="0px",s.style.backgroundColor="red",o.appendChild(s);let r=(a=e.ownerDocument.defaultView)==null?void 0:a.frameElement,i=r?r.ownerDocument.defaultView:null;if(r&&(i===window||(i==null?void 0:i.parent)===window)){let[d,l]=Os(r,{appendTo:document.body,onMoveStart:()=>{s.style.display="none"}});d.dataset.testid=n,d.style.zIndex="2",d.appendChild(o),this.unmountHandlers.push(()=>{l()})}else document.body.appendChild(o);return s}createContainer(e,n=document.body){let o=window.getComputedStyle(n),s=document.createElement("div");return yt(s),s.dataset.testid=e,s.style.color=o.color,s.style.fontSize=o.fontSize,s.style.fontFamily=o.fontFamily,s.style.fontVariant=o.fontVariant,s.setAttribute("translate","no"),n.appendChild(s),s}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),k.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()?(k.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(ga(o.metrics))):k.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(!xi(e))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let u=n,{customStyles:o,closestScrollSelector:s,floatingMenuParent:r,appendOverlayTo:i,inputMediator:a}=u,d=O(u,["customStyles","closestScrollSelector","floatingMenuParent","appendOverlayTo","inputMediator"]),l={customStyles:o,closestScrollSelector:s,floatingMenuParent:r,appendOverlayTo:i};this.configure(d),this.settings.automaticHandlingTime&&this.setupHandlingTime(e),yt(e),this.inputMediator=a||(Et(e)?new tn(e):new en(e)),this.inputMediator.on("change",({plainText:f,rawHTML:h,suggestionTextStart:g})=>{this.store.dispatch(co({text:f,html:h,suggestionTextStart:g}))}),this.inputMediator.on("keyup",f=>{this.store.dispatch(da(qs(f)))}),this.inputMediator.on("keydown",f=>{this.handleKeyDown(f)}),this.inputMediator.on("paste",({pastedText:f,selectionText:h})=>{this.store.dispatch(ca({text:f,selectionText:h}))}),this.inputMediator.on("cut",({selectionText:f})=>{this.store.dispatch(aa(f))});let c;this.inputMediator.on("selection",f=>{clearTimeout(c),f===null?c=setTimeout(()=>{f!==null&&this.store.dispatch(uo(f))},500):this.store.dispatch(uo(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(Yo(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(Yo(!0))}),this.renderSuggestions(e,l),this.subscribe(ft("inlineSuggestions"),()=>{this.renderSuggestions(e,l)}),this.subscribe(ft("suggestionsPlacement"),()=>{this.renderSuggestions(e,l)});let p=this.renderOverlays(n);this.unmountHandlers.push(()=>{p.unmount()}),this.store.dispatch(co({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),suggestionTextStart:this.inputMediator.getSuggestionTextStart()})),this.store.dispatch(uo(this.inputMediator.getSelection())),this.store.dispatch(Yo(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=rt(n),s=null,r=a=>{s=a,i()},i=()=>{o==null||o.render(F(We,{store:this.store,children:F(_e,{broadcastEvents:this.broadcastEvents,children:F(Qd,{id:"deepdesk-nickname-dialog",error:s,onSave:a=>v(this,null,function*(){try{yield this.store.dispatch(Sa({agentNickname:a})).unwrap(),console.log("setAgentNickname",a),this.broadcastEvents.send(fo,{showNicknameDialog:!1}),this.nicknameDialogUnsubscribe&&this.nicknameDialogUnsubscribe()}catch(d){k.error("Error setting agent nickname",d),r("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 s=e(this.store.getState());s!==o&&(o=s,n(o))})}unmount(){var e,n,o,s,r;(e=this.inlineSuggestions)==null||e.unmount(),(n=this.aboveSuggestions)==null||n.unmount(),(o=this.belowSuggestions)==null||o.unmount(),(s=this.floatingMenu)==null||s.unmount(),this.unmountHandlers.forEach(i=>i()),this.unmountHandlers=[],(r=this.inputMediator)==null||r.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,s,r,i;(o=this.floatingMenu)==null||o.unmount(),(s=this.inlineSuggestions)==null||s.unmount(),(r=this.aboveSuggestions)==null||r.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,s=this.createInlineContainer(e,"deepdesk-caret"),r=rt(s);r.render(F(We,{store:this.store,customStyles:o,children:F(_e,{broadcastEvents:this.broadcastEvents,children:F(Xd,{})})}));let i=a=>{a?(s.style.display="block",s.style.top=`${a.top}px`,s.style.left=`${a.left}px`):s.style.display="none"};return this.inputMediator.on("caretposition",i),{unmount:()=>{var a;(a=this.inputMediator)==null||a.off("caretposition",i),r.unmount(),s.remove()}}}renderAboveOrBelowSuggestions(e,n,o){let{customStyles:s,closestScrollSelector:r,appendOverlayTo:i}=n,a=r&&Si(e,r)||void 0,[d,l]=this.overlayContainerFactory("deepdesk-tab-completion",a||e,{appendTo:i,closestScrollElement:a,mirrorOverflow:!0,onRemove:()=>this.unmount()},s==null?void 0:s.rootNode),[c,p]=this.overlayContainerFactory("deepdesk-suggestions-overlay",a||e,{appendTo:i,placement:o},s==null?void 0:s.suggestionsRootNode),u=rt(d);u.render(F(We,{store:this.store,customStyles:s,children:F(_e,{broadcastEvents:this.broadcastEvents,children:F(Rc,{inputElement:e})})}));let f=rt(c);return f.render(F(We,{store:this.store,customStyles:s,children:F(_e,{broadcastEvents:this.broadcastEvents,children:F(ac,{onLogIn:()=>this.loginViaPopup().catch(h=>k.warn(h.message))})})})),{unmount(){u.unmount(),f.unmount(),l(),p()}}}renderFloatingMenu(e,n){let{customStyles:o,closestScrollSelector:s,appendOverlayTo:r,floatingMenuParent:i}=n,a=s&&Si(e,s)||void 0,[d,l]=this.overlayContainerFactory("floating-menu",a||e,{appendTo:i!=null?i:r},o==null?void 0:o.floatingMenuParent),c=rt(d);return c.render(F(We,{store:this.store,customStyles:o,children:F(_e,{broadcastEvents:this.broadcastEvents,children:F(Ld,{onLogIn:()=>this.loginViaPopup().catch(p=>k.warn(p.message))})})})),{unmount(){c.unmount(),l()}}}renderOverlays(e){let{customStyles:n}=e,o=this.createContainer("deepdesk-overlays"),s=rt(o);return s.render(F(We,{store:this.store,customStyles:n,children:F(_e,{broadcastEvents:this.broadcastEvents,children:F(Ed,{})})})),{unmount(){s.unmount(),o.remove()}}}renderWidget(e,n={}){if(this.widgetElement&&k.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:o,showImages:s,isEmbedded:r,signInViaPopup:i,ssoUrl:a}=n;this.widgetElement=e,this.configure({showImages:s,isEmbedded:r,signInViaPopup:i});let d;if(a)try{d={url:new URL(a,this.settings.adminUrl).toString()}}catch(l){k.warn(`Invalid ssoUrl '${a}' passed to renderWidget`)}this.widgetRoot=rt(e),this.widgetRoot.render(F(We,{store:this.store,customStyles:o,children:F(_e,{broadcastEvents:this.broadcastEvents,children:F(au,{assistantOptions:n.assistantOptions,knowledgeAssistOptions:n.knowledgeAssist,onLogIn:()=>this.loginViaPopup(d).catch(l=>k.warn(l.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:s,initialQuestion:r}=o,i=rt(n);return i.render(F(We,{store:this.store,customStyles:s,children:F(_e,{broadcastEvents:this.broadcastEvents,children:F(pi,{children:YS(Fo,{assistantCode:e,initialQuestion:r,evaluateKnowledgeAssistFn:kn,children:[F(ln,{children:F(Bo,{title:o.title,emptyState:o.emptyState})}),F(ui,{children:F(Ho,{})})]})})})})),{unmount(){i.unmount()}}}setupHandlingTime(e){let n=Ei(e,({isVisible:o})=>{o?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){Nu(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfig(){var e;return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(e=this.state.conversation.current)!=null&&e.profileCode?(this.loadProfileConfigPromise=Promise.resolve().then(()=>v(this,null,function*(){yield this.store.dispatch(An()).unwrap();let n=et(this.state);n&&this.store.dispatch(Po({showSearch:n.search,showImageSearch:n.imageSearch,showEntitiesCommand:n.entitiesCommand,showSummaryCommand:!!n.summarizerAssistantNew,showKnowledgeSearch:!!n.knowledgeAssistantNew||!!n.knowledgeAssistant,recommendTextSuggestions:n.recommendTextSuggestions}))})).finally(()=>{et(this.state)||(this.loadProfileConfigPromise=null)}),this.loadProfileConfigPromise):Promise.resolve()}loginViaPopup(e){return v(this,null,function*(){return new Promise((n,o)=>{this.store.dispatch(no());let s=new MessageChannel,r=s.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)};r.onmessage=f=>v(this,null,function*(){var h,g;if((h=f.data)!=null&&h.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((g=f.data)==null?void 0:g.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(fn),d=!0,s.port1.close(),n()}catch(m){console.error(m),o(m)}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 g=JSON.stringify({type:"deepdesk-popup-parent-origin"});c==null||c.postMessage(g,a.origin)}catch(g){k.error("Error posting message to popup",g),o(g)}break}case"deepdesk-popup-loaded":{try{let g=JSON.stringify({type:"deepdesk-popup-create-channel"});c==null||c.postMessage(g,a.origin,[s.port2])}catch(g){k.error("Error posting message to popup",g),o(g)}break}case"deepdesk-popup-error":{if(l(),f.data.message==="Platform account url mismatch"){let g=`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}).`;k.warn(g),this.store.dispatch(zs(g)),o(new Error(g))}if(f.data.message==="Timeout"){let g="Please contact your administrator: Popup timed out. Check if the account's platform url is configured correctly.";k.warn(g),this.store.dispatch(zs(g)),o(new Error(g))}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(Jo()))})}refreshWidgetSuggestions(){return v(this,null,function*(){if(!this.widgetRoot)return;let{uiConfig:e}=this.state.profile.data;if(!e.widget)return;let n=Ln(this.state);try{n.forEach(({type:o})=>{switch(o){case"entities":this.store.dispatch(fe());break;case"pinned-messages":case"sticky-messages":break;default:Yn.includes(o)||this.store.dispatch(he(o))}})}catch(o){this.handleError(o)}})}};rn.version="19.4.2-beta.3",rn.count=0;var Ds=rn;function ex(t){return v(this,null,function*(){var s,r,i;let n=yield((s=t.fetch)!=null?s:window.fetch)(t.url),o=yield n.blob();return new File([o],t.name,{type:(i=(r=t.mimeType)!=null?r:n.headers.get("Content-Type"))!=null?i:"image/jpeg"})})}function tx(t,e){return v(this,null,function*(){let n=yield ex(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 nx(t,e,n){return v(this,null,function*(){yield new st(t).authenticateWithKey(e,n)})}function ox(t){return t.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function sx(o,s){return v(this,arguments,function*(t,e,n={}){var p,u;let{value:r}=t,{start:i,end:a}=(p=n.replace)!=null?p:{start:0,end:r.length},d=`${r.slice(0,i)}${e}${r.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 rx(o,s){return v(this,arguments,function*(t,e,n={}){let r=n.replace?Rt(t,n.replace.start,n.replace.end):zn(t),i,a=()=>{if(n.setRange)return n.setRange(r.cloneRange());r.deleteContents(),i=document.createElement("span"),r.insertNode(i),n.insertBRs!==!1?e.split(`
11
+ `);let h=u?o:0,g=f?Math.min(r,c.childNodes.length):c.childNodes.length;for(let m=h;m<g&&(l(c.childNodes[m]),a!==2);m++);break}default:break}f&&(a=2)}return l(t),d}var du=(i=>(i.CUT="Cut",i.BACKSPACE="Backspace",i.DELETE="Delete",i.ERASEEOF="EraseEof",i.UNDO="Undo",i.CLEAR="Clear",i))(du||{}),ot=class{constructor(e){this.element=e;this.isFocused=!1;this.isActive=!0;this.isDisposed=!1;this.eventListeners={};this.disposeHandlers=[];this.cachedText="";this.cachedSuggestionTextStart=0;this.cachedCaretPosition=null;this.cachedSelection={start:0,end:0};this.cachedHTML="";this.isSubmitting=!1;this.isPossibleClearInputAction=!1;this.cachedText=this.getText(),this.cachedSuggestionTextStart=this.getSuggestionTextStart(),this.cachedHTML=this.getHTML(),this.cachedSelection=this.getSelection(),this.listen()}addEventListener(e,n){let o=s=>{n(s)};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(),s=this.getSuggestionTextStart(),r=this.cachedCaretPosition===null;if(!this.isActive)return;e===""&&this.cachedText!==""&&!this.isPossibleClearInputAction&&this.emit("submit");let i=e!==this.cachedText,a=n!==null&&n!==this.cachedHTML,d=s!==this.cachedSuggestionTextStart;if((i||a||d)&&(i?(this.cachedText=e,this.cachedHTML=n):a&&(this.cachedHTML=n),this.cachedSuggestionTextStart=s,r=!0,this.emit("change",{plainText:e,rawHTML:n,suggestionTextStart:s})),(o.start!==this.cachedSelection.start||o.end!==this.cachedSelection.end)&&(this.cachedSelection=o,r=!0,this.emit("selection",o)),!r)return;let l=this.getCaretPosition();Xe(l,this.cachedCaretPosition)||(this.cachedCaretPosition=l,this.emit("caretposition",l))}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:s}=e;this.isPossibleClearInputAction=Object.values(du).includes(n)||n.toLowerCase()==="z"&&(o||s),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,s;let n=((o=e.clipboardData)==null?void 0:o.getData("text"))||((s=e.clipboardData)==null?void 0:s.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()})}getSuggestionTextStart(){return 0}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 cu(t){return t.top!==0||t.left!==0||t.height!==0||t.width!==0}var en=class extends ot{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),ks(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 s=o.rangeCount>0?o.getRangeAt(0):null;if(!s)return null;let r=this.element.ownerDocument.createRange();return r.setStart(s==null?void 0:s.startContainer,s==null?void 0:s.startOffset),r.setEnd(s==null?void 0:s.endContainer,s==null?void 0:s.endOffset),!r||!this.element.contains(r.startContainer)||!this.element.contains(r.endContainer)?null:r}getCaretPosition(){let n=this.getRange();if(!n||!n.collapsed||!("getBoundingClientRect"in n))return null;let o=n.getBoundingClientRect();return!cu(o)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),o=n.getBoundingClientRect(),n.deleteContents(),!cu(o))?null:{top:o.top+o.height,left:o.left}}getSelection(){let n=this.getRange();if(n)return Es(this.element,n);let o=this.lastKnownSelection;if(o&&lu(this.element,o.start,o.end))return o;let s=zn(this.element);return s.collapse(!1),Es(this.element,s)}getSelectedText(){let{start:n,end:o}=this.getSelection();return ks(this.element,Rt(this.element,n,o))}listen(){super.listen();let n=new MutationObserver(r=>{var i,a;r.length===2&&r[0].addedNodes.length===1&&((i=r[0].addedNodes[0])==null?void 0:i.textContent)==="\u2060"&&((a=r[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,s=new MutationObserver(()=>{this.element.isContentEditable!==o&&(o=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});s.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>s.disconnect())}};var OS=["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 uu(t,e){let n="mozInnerScreenX"in window,o=document.createElement("div");o.id="input-textarea-caret-position-mirror-div";let s=o.style,r=window.getComputedStyle(t),i=t.ownerDocument.body;s.whiteSpace="pre-wrap",s.wordWrap="break-word",s.position="absolute",s.visibility="hidden",OS.forEach(c=>{s[c]=r[c]}),n?t.scrollHeight>Number.parseInt(r.height)&&(s.overflowY="scroll"):s.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(r.borderTopWidth)+a.offsetHeight,left:d.left-t.scrollLeft+a.offsetLeft+Number.parseInt(r.borderLeftWidth)};return i.removeChild(o),l}var tn=class extends ot{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 uu(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 r;return(r=n==null?void 0:n.get)==null?void 0:r.call(this.element)},set:r=>{var i;(i=n==null?void 0:n.set)==null||i.call(this.element,r),this.handleInteraction()}}),this.addEventListener("scroll",()=>{this.emit("caretposition",this.getCaretPosition())});let o=this.element.disabled,s=new MutationObserver(()=>{this.element.disabled!==o&&(o=this.element.disabled,this.emit(o?"disabled":"enabled"))});s.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>s.disconnect())}};function pu(t,e,n){let o=`deepdesk-iframe-${t}`,s=document.getElementById(o);if(s)return s;let r=document.createElement("iframe"),i=new URL(e);return Object.entries(n).forEach(([a,d])=>{i.searchParams.append(a,d)}),r.style.position="absolute",r.style.left="-999em",r.style.width="0px",r.style.height="0px",r.tabIndex=-1,r.id=o,r.title=`iframe-${t}`,r.src=i.toString(),window.document.body.appendChild(r),r}function DS(t){if(typeof t!="string")return t;try{return JSON.parse(t)}catch(e){return t}}var gi=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()}},mi=class{constructor(e,n,o){this.name=e;this.targetOrigin=n;this.options=o;this.disposeHandlers=[];this.iframe=pu(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()}},fi=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(),k.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 mi(e,this.deepdeskUrl,{debug:!0}):new gi(e),o=s=>{var i,a;if(s.origin!==this.deepdeskUrl)return;let r=DS(s.data);typeof r!="object"||r.type!=="event"||r.channel!==e||(k.info("Received broadcast event",this.externalId,s),(a=(i=this.eventMap)[r.name])==null||a.call(i,r.payload))};return n.onMessage(o),n}send(e,n,o){var i,a;k.info("Broadcast event",{externalId:this.externalId,name:e,payload:n});let s={type:"event",name:e,payload:n};o!==!1&&((a=(i=this.eventMap)[e])==null||a.call(i,n));let r=this.externalId==="deepdesk-general"?this.defaultChannel:this.channel;r==null||r.postMessage(x(y({},s),{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)}},gu=fi;function _S(t){return t.replace(/(_\w)/g,e=>e[1].toUpperCase())}function B(t){return Array.isArray(t)?t.map(B):typeof t=="object"&&t!==null?Object.keys(t).reduce((e,n)=>x(y({},e),{[_S(n)]:B(t[n])}),{}):t}function FS(t){return t.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}function Z(t){return Array.isArray(t)?t.map(Z):typeof t=="object"&&t!==null?Object.keys(t).reduce((e,n)=>x(y({},e),{[FS(n)]:Z(t[n])}),{}):t}var nn=class extends Error{constructor(n,o){super(n);this.body=o;this.name="CustomError"}};var Vn=t=>new Promise(e=>{setTimeout(e,t)});var xe=class extends nn{constructor(){super(...arguments);this.name="ClientError"}},Rs=class extends nn{constructor(){super(...arguments);this.name="ServerError"}},hi=new Map;function mu(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:(k.warn("Unexpected response body:",n.slice(0,20)),JSON.parse(n))})}var on=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,s)=>{let r={isAborted:!1,reject:s},i=`${this.baseUrl}${e}`,a=this.fetch,d=n.method===void 0||n.method.toLowerCase()==="get",R=n,{useCache:l=!1,abortLatest:c=!1,attempts:p=1,retryDelay:u=500,refreshTokenOn401:f=!0,retryOnError:h=I=>I instanceof TypeError,retryOnResponse:g=I=>I.status>=500,version:m=null}=R,S=O(R,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]);if(l){if(!d)throw new Error(`Can't use 'useCache' for ${n.method}`);if(hi.has(i)){o(hi.get(i));return}}let C=x(y({credentials:"include"},S),{headers:y({Accept:"application/json","Content-Type":"application/json"},S.headers)});!d&&this.csrfToken&&(C.headers=x(y({},C.headers),{"X-CSRFToken":this.csrfToken})),typeof m=="string"&&(C.headers=x(y({},C.headers),{"X-Deepdesk-API-Version":m}));let T=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]=r;let A=()=>v(this,null,function*(){return T--,a(i,C).then(I=>v(this,null,function*(){return g(I)&&!r.isAborted&&T>0?(yield Vn(u),A()):I.status===401&&f===!0&&w===!1?(w=!0,yield this.refreshToken(),A()):I})).catch(I=>v(this,null,function*(){if(h(I)&&!r.isAborted&&T>0)return yield Vn(u),A();throw I}))});A().then(I=>v(this,null,function*(){let U=yield mu(I);if(delete this.latestRequestByUrl[i],I.status>=500){s(new Rs("Server Error",U));return}if(I.status===401){s(new xe("Unauthorized",U));return}if(I.status===403){s(new xe("Forbidden",U));return}if(I.status===404){s(new xe("Not Found",U));return}if(I.status>=400){s(new xe("Bad Request",U));return}l&&hi.set(i,U),o(U)})).catch(I=>{s(I)})})}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(s){return!1}if(!e){if(!o)return!1;try{yield this.refreshToken();let{is_logged_in:s}=yield this.get("/apis/admin/session/validate/",{refreshTokenOn401:!1});return s}catch(s){return!1}}return n})}refreshToken(){let e=Date.now();return this.lastFailedRefreshAt&&e-this.lastFailedRefreshAt<this.failedRefreshCooldown?Promise.reject(new xe("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))}postWithStatus(e,n,o){return this.requestWithStatus(e,y({method:"POST",body:JSON.stringify(n)},o))}requestWithStatus(e,n={}){return new Promise((o,s)=>{let r={isAborted:!1,reject:s},i=`${this.baseUrl}${e}`,a=this.fetch,A=n,{useCache:d=!1,abortLatest:l=!1,attempts:c=1,retryDelay:p=500,refreshTokenOn401:u=!0,retryOnError:f=R=>R instanceof TypeError,retryOnResponse:h=R=>R.status>=500,version:g=null}=A,m=O(A,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]),S=x(y({credentials:"include"},m),{headers:y({Accept:"application/json","Content-Type":"application/json"},m.headers)});this.csrfToken&&(S.headers=x(y({},S.headers),{"X-CSRFToken":this.csrfToken})),typeof g=="string"&&(S.headers=x(y({},S.headers),{"X-Deepdesk-API-Version":g}));let C=c,T=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[i]&&l&&(this.latestRequestByUrl[i].isAborted=!0,this.latestRequestByUrl[i].reject(new Error("Aborted"))),this.latestRequestByUrl[i]=r;let w=()=>v(this,null,function*(){return C--,a(i,S).then(R=>v(this,null,function*(){return h(R)&&!r.isAborted&&C>0?(yield Vn(p),w()):R.status===401&&u===!0&&T===!1?(T=!0,yield this.refreshToken(),w()):R})).catch(R=>v(this,null,function*(){if(f(R)&&!r.isAborted&&C>0)return yield Vn(p),w();throw R}))});w().then(R=>v(this,null,function*(){let I=yield mu(R);if(delete this.latestRequestByUrl[i],R.status>=500){s(new Rs("Server Error",I));return}if(R.status===401){s(new xe("Unauthorized",I));return}if(R.status===403){s(new xe("Forbidden",I));return}if(R.status===404){s(new xe("Not Found",I));return}if(R.status>=400){s(new xe("Bad Request",I));return}o({status:R.status,data:I})})).catch(R=>{delete this.latestRequestByUrl[i],s(R)})})}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 fu;(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={}))})(fu||(fu={}));function Ps(t){return x(y({},B(t)),{metadata:t.metadata})}var Pt=class Pt{constructor(e,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new on(e,{fetch:n.fetch}),this.client.patchFetch(o=>(s,r)=>v(this,null,function*(){let i=yield o(s,r);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?(Pt.exchangeTokenPromise||(Pt.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),Pt.exchangeTokenPromise):Promise.resolve()})}createConversation(e){return v(this,null,function*(){var o;yield this.preflight(),k.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()},Z(e)),{metadata:(o=e.metadata)!=null?o:{}}));return Ps(n)})}upsertConversation(e){return v(this,null,function*(){var c;yield this.preflight(),k.info(`Upserting conversation for session ${e.externalId} and agent ${e.agentId}`);let{status:n,data:o}=yield this.client.postWithStatus("/api/v2/conversations",x(y({chat_start_time:new Date().toISOString()},Z(e)),{metadata:(c=e.metadata)!=null?c:{}}),{version:"v2"}),s=Ps(o);if(n===201)return s;let{agentId:r,agentName:i,agentEmail:a,agentNickname:d,metadata:l}=e;return this.updateConversation(s.id,{agentId:r,agentEmail:a,agentName:i,agentNickname:d,metadata:l})})}getMe(){return v(this,null,function*(){let e=yield this.client.get("/apis/admin/session/me/");return B(e)})}postIdentity(e){return v(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/me/identities/",Z(e))})}patchMe(e){return v(this,null,function*(){yield this.preflight();let n=yield this.client.patch("/apis/admin/session/me/",Z(e));return B(n)})}getProfile(e){return v(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${e}/`,{useCache:!0});return B(n)})}getKnowledgeAssistant(e){return v(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${e}/`,{useCache:!0});return B(n)})}getContentTypes(){return v(this,null,function*(){let e=yield this.client.get("/apis/admin/content-types/",{useCache:!0});return B(e)})}getAccount(){return v(this,null,function*(){let e=yield this.client.get("/apis/admin/account/",{useCache:!0});return B(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 B(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(),k.info(`Getting conversation for session ${e}`);let{attempts:s=1,retryDelay:r=1e3}=n,i=yield this.client.get(`/api/v2/conversations/by_external_id/${e}`,{attempts:s,retryDelay:r,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"});return k.info(`Successfully retrieved conversation ${i.id} for session ${e}`),Ps(i)})}isConversationSupported(o){return v(this,arguments,function*(e,n={}){k.info(`Check if conversation for session ${e} is supported`);let{attempts:s=1,retryDelay:r=1e3}=n;return(yield this.client.get(`/api/v2/conversations/by_external_id/${e}/has_active_profile`,{attempts:s,retryDelay:r,retryOnResponse:a=>a.status===404||a.status>=500})).has_active_profile})}updateConversation(e,n){return v(this,null,function*(){var r;yield this.preflight();let o=Z(n);n.metadata&&(o.metadata=(r=n.metadata)!=null?r:{});let s=yield this.client.put(`/api/v2/conversations/${e}`,o);return Ps(s)})}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({},Z(o)),{metadata:o.metadata})))})}sendEvent(e,n){return v(this,null,function*(){yield this.preflight();let a=n,{data:o}=a,s=O(a,["data"]),r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((d,[l,c])=>x(y({},d),{[l]:c}),{}),i=["platform","agentId","agentName","agentEmail","conversationId"].reduce((d,l)=>(s[l]&&(d[l]=s[l]),d),{});return this.client.post("/api/v2/events",Z(x(y(y({},r),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 k.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/",Z(n),{refreshTokenOn401:!1,headers:{apikey:e}})})}getTextSuggestions(s){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}`,Z(n),{abortLatest:!0})).map(i=>x(y({},B(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`,Z(n),{abortLatest:!0})).map(s=>({score:1,source:s.source,sourceText:s.source_text,text:s.label,trainingJobs:s.training_jobs,searchKeywords:s.search_keywords,type:s.source})).filter((s,r,i)=>r===i.findIndex(a=>a.text===s.text))})}getPinnedMessages(e){return v(this,null,function*(){let n=yield this.client.get(`/api/v2/profiles/${e}/pinned-messages`,{abortLatest:!0});return B(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",Z(e),{abortLatest:!0,version:"v2"});return B(n)})}search(e){return v(this,null,function*(){let n=yield this.client.post(`/api/v2/profiles/${e.profile}/search`,Z(e));return B(n)})}loginWithPassword(e,n){return v(this,null,function*(){yield this.preflight();let o=yield this.client.post("/apis/admin/session/login/",{username:e,password:n},{refreshTokenOn401:!1});return B(o)})}logout(){return v(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/logout/",{},{refreshTokenOn401:!1})})}requestLoginByEmail(e){return v(this,null,function*(){yield this.preflight();let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:e});return B(n)})}requestPasswordlessToken(){return v(this,null,function*(){let e=yield this.client.get("/apis/admin/session/passwordless/request/");return B(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 B(n)})}evaluateAssistant(e,n){return v(this,null,function*(){var d,l,c;yield this.preflight();let o=new URLSearchParams;n!=null&&n.externalConversationId&&o.append("external_conversation_id",n.externalConversationId);let s=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()}`,r=p=>Z(p),i=(d=n==null?void 0:n.transcript)==null?void 0:d.map(p=>{var u;return y({source:p.source,text:p.text},(u=p.attachments)!=null&&u.length?{attachments:p.attachments.map(r)}:{})}),a=yield this.client.post(s,y({input:(l=n==null?void 0:n.input)!=null?l:{},conversation:i},(c=n==null?void 0:n.attachments)!=null&&c.length?{attachments:n.attachments.map(r)}:{}));return B(a)})}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 B(o)})}postMessageToAssistantThread(e){return v(this,null,function*(){yield this.preflight();let{assistantCode:n,threadId:o,message:s}=e,r=yield this.client.post(`/apis/admin/assistants/${n}/threads/${o}/messages/`,{content:s,role:"user"});return B(r)})}translateMessages(e){return v(this,null,function*(){yield this.preflight();let n=yield this.client.post("/api/v2/translate",Z(e));return B(n)})}handleDeepdeskVersionHeaders(e){e.headers.forEach((n,o)=>{let s=o.toLowerCase(),r=s.match(zi);if(!n||!r)return;let i=r[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&n&&a!==n&&k.warn(`Overwritten Version header ${s}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[i]=n})}};Pt.exchangeTokenPromise=null;var st=Pt;var Is=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=B(JSON.parse(e.data));o.event&&this.eventListeners.has(o.event)&&((n=this.eventListeners.get(o.event))==null||n.forEach(s=>s(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=[]}};import{combineReducers as KS,configureStore as WS}from"@reduxjs/toolkit";import{createSlice as HS}from"@reduxjs/toolkit";var hu={startTime:null,stopTime:null},yu=t=>t.handlingTime,vu=HS({name:"handlingTime",initialState:hu,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,()=>hu)}}),{handlingTimeStart:Su,handlingTimeStop:As,handlingTimeReset:xu}=vu.actions,bu=vu.reducer;var Cu=(t={})=>{let e=y({onAuthError:Nt(!1)},t);return n=>o=>s=>("error"in s&&s.error.message==="Unauthorized"&&n.dispatch(e.onAuthError),o(s))};var Tu=(t={})=>{let e,n=!0,o=y({getStyleSuggestions:Tt,debounce:500},t);return s=>r=>i=>{var f;let a=s.getState().input.text,d=r(i),l=s.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,s.dispatch(o.getStyleSuggestions({text:u}))},t.debounce)),d}};function BS(t,e){return t.text===e.text&&t.selection.start===e.selection.start&&t.selection.end===e.selection.end&&t.suggestionTextStart===e.suggestionTextStart}var wu=(t={})=>{let e=y({getTextSuggestions:he,getAutocompleteSuggestions:_n,debounce:200,check:Re},t),n;return o=>s=>r=>{var g;let{input:i}=o.getState(),a=s(r),d=o.getState();if(d.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:l,showTabCompletion:c}=d.settings,p=(g=d.conversation.current)==null?void 0:g.id,u=r.type===Jo.toString();if(!p||!l&&!c)return a;let{input:f}=d;return BS(f,i)&&!u||(clearTimeout(n),!e.check(d))||(n=setTimeout(()=>{let m=dt(d);m===""?o.dispatch(e.getTextSuggestions("default")):o.dispatch(e.getAutocompleteSuggestions(m))},u?0:e.debounce)),a}};var Eu=Tt.fulfilled.toString();function US(t,e){let n=new Set([...e.keywordMatches.map(s=>s.keyword)]),o=[];return n.forEach(s=>{let r=t.keywordMatches.filter(d=>d.keyword===s),i=e.keywordMatches.filter(d=>d.keyword===s),a=i.length-r.length;a<=0||o.push(...i.slice(0,a))}),o}var ku=t=>e=>n=>o=>{var l;if(o.type!==Eu){n(o);return}let s=e.getState().styleSuggestions.list;n(o);let r=e.getState(),i=r.styleSuggestions.list,a=(l=r.conversation)==null?void 0:l.current;if(s===i)return;let d=US(s,i);o.type===Eu&&d.length>0&&t.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:d}})};var zS=KS({assistants:Za,auth:Qi,conversation:na,contentTypes:Ml,passwordlessToken:Lc,entities:rd,handlingTime:bu,info:Ea,input:fa,settings:el,profile:Fl,search:La,styleSuggestions:Gd,ui:Dd,textSuggestions:Sd});function Ru(t){return WS({reducer:zS,middleware:e=>{var o;let n=e({thunk:{extraArgument:{dynamicThunkObject:t.dynamicThunkObject,deepdeskAPI:t.deepdeskAPI}},serializableCheck:!1}).concat(Cu()).concat(wu({debounce:200})).concat(Tu({debounce:500})).concat(ku(t.deepdeskAPI));return((o=t.middleware)!=null?o:[]).reduce((s,r)=>s.concat(r),n)},preloadedState:t.preloadedState})}function Pu(t,e,n){if(e==="")return null;let o=new RegExp(`\\b${gs(e)}\\b`,"gi"),s,r=null;for(;(s=o.exec(t))!==null&&!(s.index>n);)r={start:s.index,end:s.index+s[0].length};return r}var VS=t=>{var e,n;return(n=(e=t==null?void 0:t.type)==null?void 0:e.toLowerCase())!=null?n:"unknown"},jS=t=>e=>n=>o=>{var d,l,c,p,u,f;let s=e.getState(),r=ft("inlineSuggestions")(s),i=ft("autoSelectSuggestion")(s)||r;switch(o.type){case Nt.toString():{!o.payload&&t.emit("logout",void 0);break}case to.fulfilled.toString():{t.emit("logout",void 0);break}case fe.fulfilled.toString():o.payload.length>0&&t.sendEvent("entities found",{conversationId:(d=s.conversation.current)==null?void 0:d.id,data:{entities:o.payload}});break;case pt.toString():t.logSendMessage(o.payload);break;case ko.toString():t.emit("call-to-action",{cue:o.payload});break;case se.fulfilled.toString():if(!o.isBroadcasted){let{externalConversationId:h,currentExternalIdAtRequest:g}=(l=o.payload)!=null?l:{};(!h||!g||h===g)&&t.broadcast(Qs,o,!1)}break;case se.rejected.toString():break;default:break}let a=n(o);switch(o.type){case pt.toString():t.handleAfterSendMessage(o.payload);break;case Fn.toString():t.onUpdateShowTabHint(o.payload);break;case As.toString():t.logHandlingTime();break;case Ft.toString():t.broadcast(ho,o);break;case ut.toString():t.broadcast(ho,o);break;case Ro.toString():e.dispatch(ut({source:"assistant",assistantCode:o.payload.code}));break;case"analytics/logEvent/fulfilled":{let h=s.assistants.cues.find(g=>g.code===o.meta.arg.data.assistantCode);t.emit("event",x(y({},o.meta.arg),{cue:h}));break}case ie.toString():{let{start:h,end:g}=s.input.selection;t.emit("select-suggestion",x(y({type:VS(o.payload.suggestion)},o.payload),{replace:o.payload.replace==="selection"?{start:h,end:g}:{start:0,end:g}})),r&&e.dispatch(Je([]));break}case qd.toString():{let{keyword:h,suggestion:g,eventMetrics:m}=o.payload,{text:S,selection:C}=s.input,T=Pu(S,h,(c=C==null?void 0:C.end)!=null?c:S.length);if(!T)break;t.emit("select-suggestion",{text:g,type:"style",replace:T,suggestion:{text:g,source:"style"},eventMetrics:m});break}case ao.toString():t.emit("select-image",o.payload),t.sendEvent("Image attached",{conversationId:(p=s.conversation.current)==null?void 0:p.id,data:{path:o.payload.suggestion.image,title:o.payload.suggestion.title}});break;case Je.toString():{i&&o.payload.length>0&&e.dispatch(lo(0));break}case se.fulfilled.toString():{let{evaluationId:h,output:g,externalConversationId:m}=o.payload,S=o.meta.arg.assistantCode;if(t.emit("event",{name:"Assistant evaluation completed",data:{evaluationId:h,assistantCode:S,assistantOutput:qa(g),externalConversationId:m,evaluationStatus:"success"}}),!o.meta.arg.skipState){let C=e.getState().assistants.cues;t.emit("cues",C)}break}case se.rejected.toString():{let h=o.meta.arg.assistantCode,g=(f=o.meta.arg.externalConversationId)!=null?f:(u=e.getState().conversation.current)==null?void 0:u.externalId;t.emit("event",{name:"Assistant evaluation completed",data:{evaluationId:"",assistantCode:h,assistantOutput:"",externalConversationId:g,evaluationStatus:"failed"}});break}default:break}return a},Iu=jS;import{createSelector as $S}from"@reduxjs/toolkit";function yi(t){return t.toISOString().replace("T"," ").replace("Z","")}var qS=(t,e)=>e.version,Au=$S([Ht,Ce,yu,qS],(t,e,n,o)=>{if(!e)return k.warn("No conversationId for handling time metrics"),null;let{startTime:s,stopTime:r}=n;return!s||!r?(k.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:yi(s),timeStop:yi(r)}});function Lu(t,e){let{text:n,metrics:{numPaste:o,pastes:s,textSuggestions:r}}=t.input,i=n.length;return{source:"agent",clientVersion:e.version,pastes:s,lenTextTotal:i,numPastes:o,suggestions:r}}var jn=class extends Error{};function GS(){let t,e;return{promise:new Promise((o,s)=>{t=o,e=s}),resolve:t,reject:e}}var Ls=class{constructor(){this.queues={}}push(e,n){let o=()=>{let r=this.queues[e][1];r?(this.queues[e]=[r.promise,null],r.resolve()):delete this.queues[e]};if(!this.queues[e]){let r=n().finally(o);return this.queues[e]=[r,null],r}this.queues[e][1]&&this.queues[e][1].reject(new jn("Queued async function is outdated"));let s=GS();return this.queues[e][1]=s,s.promise.then(()=>n().finally(o))}};function vi(t,e){var r;let n=t.closest(e);if(n)return n;let o=t.getRootNode().host;if(o instanceof HTMLElement)return vi(o,e);let s=(r=t.ownerDocument.defaultView)==null?void 0:r.frameElement;return s?vi(s,e):null}function Si(t,e){return vi(t,e)}var XS={accepted:"onConversationAcceptedAssistants","new-message":"onConversationNewMessageAssistants",ended:"onConversationEndedAssistants"},Mu=(t,e)=>{var s,r,i;if(!((i=(r=(s=t.uiConfig)==null?void 0:s.widget)==null?void 0:r.types.find(a=>a.type==="cues"))==null?void 0:i.isActive))return k.warn("Triggered a conversation assistant, but cues are not configured in widget."),[];let o=t[XS[e]];return o&&o.length>0?o.map(a=>a.code):(k.warn(`No assistant set in profile for conversation event "${e}"`),[])};function Nu(t){return typeof t=="object"&&t!==null&&"name"in t&&"message"in t}function JS(t){return typeof t=="object"&&t!==null&&"tagName"in t}function xi(t){return JS(t)&&(Et(t)||us(t))}var Du,Pe=new Map,QS=["bottom","height","left","right","top","width"],Ou=(t,e)=>!t&&!e?!1:t&&!e||!t&&e?!0:QS.some(n=>t[n]!==e[n]);function _u(t){var n,o,s;if(t.ownerDocument===document)return[];let e=(s=(o=(n=t.ownerDocument)==null?void 0:n.defaultView)==null?void 0:o.frameElement)!=null?s:null;return e?[e,..._u(e)]:[]}function Fu(t,e){return!t||!e?null:x(y({},t),{top:t.top+e.top,left:t.left+e.left})}var Ms=!1,Hu=()=>{Ms=!0;let t=[];if(Pe.forEach((e,n)=>{if(!n.isConnected){e.rect=null,t.push(e),Pe.delete(n);return}let o=n.getBoundingClientRect();Ou(o,e.rect)&&(e.rect=o,t.push(e))}),t.forEach(e=>{let n=e.parentRects?e.parentRects.reduce(Fu,e.rect):e.rect;Ou(n,e.totalRect)&&e.callbacks.forEach(o=>o(n)),e.totalRect=n}),Pe.size===0){Ms=!1;return}Du=window.requestAnimationFrame(Hu)};function bi(t,e){let n=_u(t),o=[],s=n.map((r,i)=>bi(r,a=>{o[i]=a;let d=Pe.get(t);if(!d)return;let l=o.reduce(Fu,d.rect);d.callbacks.forEach(c=>c(l))}));return{observe(r=!0){if(s.forEach(i=>i.observe(!1)),Pe.has(t)){let i=Pe.get(t);i.callbacks.push(e),i.rect&&e(i.rect)}else Pe.set(t,{rect:void 0,callbacks:[e],parentRects:o});r&&!Ms&&Hu()},unobserve(){s.forEach(i=>i.unobserve());let r=Pe.get(t);if(r){let i=r.callbacks.indexOf(e);i>=0&&r.callbacks.splice(i,1),r.callbacks.length||Pe.delete(t),Pe.size||(cancelAnimationFrame(Du),Ms=!1)}}}}var Bu,Ie=new Map,Uu=()=>{Ie.forEach((t,e)=>{if(!e.isConnected){Ie.delete(e);return}let{clientHeight:n,scrollHeight:o}=e,s=o>n;t.visible!==s&&(t.visible=s,t.callbacks.forEach(r=>r(t.visible)))}),Ie.size!==0&&(Bu=window.requestAnimationFrame(Uu))};function Ku(t,e){return{observe(){let n=Ie.size===0;Ie.has(t)?Ie.get(t).callbacks.push(e):Ie.set(t,{visible:void 0,callbacks:[e]}),n&&Uu()},unobserve(){let n=Ie.get(t);if(n){let o=n.callbacks.indexOf(e);o>=0&&n.callbacks.splice(o,1),n.callbacks.length||Ie.delete(t),Ie.size||cancelAnimationFrame(Bu)}}}}var Ci=["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 Ti(t,e,n){return n.forEach(o=>{e.style[o]=t[o]})}function sn(t){return Number.parseFloat(t)}function Ns(t){return Math.round(t*1e6)}function Wu(t){return t/1e6}function wi(t,e,n){if(t.boxSizing==="content-box")return;let{clientWidth:o}=e,s=sn(t.width),r=sn(t.borderLeftWidth),i=sn(t.borderRightWidth),a=sn(t.paddingRight),d=Wu(Ns(s)-Ns(r)-Ns(i)),l=Wu(Ns(o));if(d-l>2){let c=d-l;n.style.paddingRight=`${a+c}px`}}function Os(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",yt(n);let o=window.getComputedStyle(t),s=!0,r=()=>{n.scrollTop=t.scrollTop};Ti(o,n,Ci),wi(o,t,n),e.mirrorOverflow&&(n.style.overflow="hidden",t.addEventListener("scroll",r));let i=Ku(t,()=>{Ti(o,n,Ci),wi(o,t,n),r(),setTimeout(r,0)}),a,d=!0,l=bi(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(s===!0)return;e.onHide&&e.onHide(),n.style.display="none",s=!0;return}if(Ti(o,n,Ci),wi(o,t,n),r(),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),g=sn(h.borderTopWidth),m=sn(h.borderBottomWidth),S=f.top+g-u.top,C=u.top+u.height+-(f.top+f.height-m);n.style.clipPath=`inset(${S}px 0px ${C}px 0px)`}s&&(n.style.display="block",e.onShow&&e.onShow(),s=!1)});return e.appendTo?e.appendTo.appendChild(n):(p=t.parentElement)==null||p.appendChild(n),l.observe(),i.observe(),[n,()=>{t.removeEventListener("scroll",r),l.unobserve(),i.unobserve(),n.remove()}]}function ZS(t){return t.offsetParent!==null}function zu(t){if(!ZS(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 Ei(t,e,n=100){let o=zu(t);e({isVisible:o});let s=setInterval(()=>{let r=zu(t);r!==o&&(o=r,e({isVisible:o}))},n);return()=>{clearTimeout(s)}}var Vu=(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){k.warn("[Deepdesk] SessionStorage is blocked by browser")}}});import{jsx as F,jsxs as YS}from"react/jsx-runtime";var ju=Vu("showTabHint",!0),rn=class rn{constructor({deepdeskUrl:e,version:n=rn.version||"unknown",locale:o="en-US",token:s,fetch:r,productName:i,createCustomChannel:a,websocketClient:d=Is}){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 Ls;this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;let l=e.replace(/\/api$/,"");this.deepdeskApi=new st(l,{token:s,fetch:r}),this.version=n,this.instanceId=rn.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[Iu({broadcast:(h,g,m)=>{this.broadcastEvents.send(h,g,m)},emit:(h,g)=>this.emit(h,g),handleAfterSendMessage:h=>this.handleAfterSendMessage(h),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:h=>this.logSendMessage(h),onUpdateShowTabHint:h=>ju.update(h),sendEvent:(h,g)=>this.deepdeskApi.sendEvent(h,g)})]};this.store=Ru(c),this.broadcastEvents=new gu({debug:!0,deepdeskUrl:l,eventMap:Ma(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=Q(this.state))!=null?h:!1})}),this.whenLoggedIn(()=>this.ws.connect()),this.store.dispatch(Fn(ju.value())),this.store.dispatch(Po({locale:o,adminUrl:l,productName:i}));let p=[],u=h=>{if(!h.conversationId)return;let g=()=>{this.conversationId()===h.conversationId&&this.store.dispatch(Qa(h))};this.hasConversation()?g():p.push(g)};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 g=()=>{this.conversationId()===h.conversationId&&this.store.dispatch(Ja(h))};this.hasConversation()?g():p.push(g)}),this.ws.on("assistants::suggest_as_reply",h=>{if(!h.conversationId)return;let g=()=>{this.conversationId()===h.conversationId&&this.store.dispatch(Ft([{text:h.payload.message,type:"text",source:"assistant",assistantCode:h.code,sourceLabel:h.name}]))};this.hasConversation()?g():p.push(g)});let f=this.whenConversationLoaded(()=>{var h;this.broadcastEvents.setExternalId((h=this.state.conversation.current)==null?void 0:h.externalId),p.forEach(g=>g()),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=ct(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?(k.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(k.warn("Profile has not been loaded (yet)"),!0):(k.warn("No conversation loaded (yet)"),!0)}whenLoggedIn(e){if(Q(this.state))e();else{let n=this.subscribe(Q,o=>{o&&e()});this.disposeHandlers.push(()=>{n()})}}login(){return this.store.dispatch(Nt(null)),this.store.dispatch(Oe()),new Promise(e=>{this.whenLoggedIn(()=>e())})}isLoggedIn(){return v(this,null,function*(){return(yield this.store.dispatch(Oe())).payload})}isConversationSupported(e,n){return v(this,null,function*(){return(yield this.store.dispatch(Vs({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(so(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(ro({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($s(e))})}updateConversation(e){return v(this,null,function*(){return(yield this.store.dispatch(io(e))).payload})}resetConversation(){this.store.dispatch(j()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}configure(e){this.store.dispatch(Po(e))}setVisitorInfo(e){this.store.dispatch(ba(e))}setCustomData(e){this.store.dispatch(Ca(e))}setAgentInfo(e,n){return v(this,null,function*(){var s;yield this.store.dispatch(gn(y(y({},e),n))),(s=this.state.info.agentInfo)!=null&&s.agentNickname||this.broadcastEvents.send(fo,{showNicknameDialog:!0})})}setAgentSettings(e){return v(this,null,function*(){yield this.store.dispatch(Gs(e))})}getAgentSettings(){return v(this,null,function*(){return(yield this.store.dispatch(Xs())).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(co({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),suggestionTextStart:this.inputMediator.getSuggestionTextStart()}))}notifyExternalSuggestion(e){this.store.dispatch(ie(e))}evaluateAssistant(e,n){return v(this,null,function*(){var c;let{input:o={},attachments:s=[],transcript:r,showCuesInWidget:i=!0,includeMetadata:a,externalConversationId:d}=n||{},l=yield this.store.dispatch(se({assistantCode:e,attachments:s,transcript:r,includeMetadata:a,input:o,externalConversationId:d,skipState:!i}));if(l.error)throw new Error(`Assistant evaluation failed: ${(c=l.payload)!=null?c:l.error.message}`);return l.payload.output})}evaluateConversationAssistant(e,n){return v(this,null,function*(){var c,p,f;yield this.loadProfileConfig();let o=this.state.profile.data;if(!o&&((c=this.state.conversation.current)!=null&&c.profileCode)&&(yield this.loadProfileConfig(),o=this.state.profile.data),!o){k.warn("Can't evaluate assistant when profile is not loaded yet.");return}let s=Mu(o,e),r=(p=n==null?void 0:n.showCuesInWidget)!=null?p:!0,u=n!=null?n:{},{showCuesInWidget:i}=u,a=O(u,["showCuesInWidget"]),d=(f=n==null?void 0:n.externalConversationId)!=null?f:this.hasConversation()?this.externalId():"",l=yield Promise.all(s.map(h=>this.queues.push(h,()=>v(this,null,function*(){var m,S;let g=yield this.store.dispatch(se(y(x(y({assistantCode:h,includeMetadata:!0},a),{skipState:!r}),n!=null&&n.attachments&&(n==null?void 0:n.attachments.length)>0?{attachments:n==null?void 0:n.attachments}:{})));if(g.error)throw new Error(`Assistant evaluation failed: ${(m=g.payload)!=null?m:g.error.message}`);return{assistantCode:h,evaluationId:g.payload.evaluationId,output:g.payload.output,externalConversationId:(S=g.payload.externalConversationId)!=null?S:d}})).catch(g=>{if(g instanceof jn)return k.warn(`Queued assistant "${h}" was outdated and dropped`),null;throw g})));if(!r)return l.filter(h=>h!==null)})}handleKeyDown(e){let{overlayCollapsed:n,openOverlayWhenTyping:o}=this.state.ui,{textSuggestions:s,selectedSuggestionIndex:r,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=s.length>0;if(this.store.dispatch(la(qs(e))),!Re(this.state)||e.key!=="Tab"&&!l)return;let h=()=>{n||!f||i&&(e.shiftKey||(this.store.dispatch(ua()),e.preventDefault()))},g=()=>{n||!f||p&&r<=0||i&&(e.shiftKey||(this.store.dispatch(pa()),e.preventDefault()))};switch(e.key){case"ArrowUp":u==="below"?g():h();break;case"ArrowDown":{u==="below"?h():g();break}case"Escape":{n||(this.store.dispatch(lo(-1)),this.store.dispatch(tt({collapse:!0})),this.store.dispatch(Nd(!0)),e.preventDefault());break}case"Tab":{e.preventDefault();let m=_t(this.state);if(!m)return;this.store.dispatch(Fn(!1)),this.store.dispatch(ie({text:m.text,suggestion:m,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(p||this.state.input.selectedSuggestionIndex===-1)return;let m=_t(this.state);if(!m)return;this.store.dispatch(ie({text:m.text,suggestion:m,eventMetrics:{inputType:"space"},replace:"until-selection-end"}));break}case"Enter":{if(p||e.shiftKey||this.state.input.selectedSuggestionIndex===-1)return;let m=_t(this.state);if(!m)return;this.store.dispatch(ie({text:m.text,suggestion:m,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),e.preventDefault();break}default:}n&&o&&this.store.dispatch(tt({collapse:!1}))}handleAfterSendMessage(e){this.emit("send-message",e),this.store.dispatch(Je([]))}handlingTimeStart(){this.state.handlingTime.startTime||(k.info("Start handling time"),this.store.dispatch(Su()))}handlingTimeStop(){this.state.handlingTime.startTime&&(k.info("Stop handling time"),this.store.dispatch(As()))}logSendMessage(e){let n=Lu(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=Au(this.state,{version:this.version});e&&(this.deepdeskApi.sendEvent("Handling Time",{conversationId:this.conversationId(),data:e}),this.store.dispatch(xu()))}notifySubmit(e={}){var n;this.shouldAbort()||(this.store.dispatch(pt((n=e.text)!=null?n:this.state.input.text)),this.store.dispatch(ma()))}emit(e,n){let o=this.eventListeners[e];o&&o.forEach(s=>{try{s(n)}catch(r){k.warn(`The following error occurred in deepdeskSDK.on('${e}', handler)`),k.error(r)}})}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(Ta(e))}whenConversationLoaded(e){let n=r=>{var i;return(i=r.conversation.current)==null?void 0:i.id},o=()=>this.loadProfileConfig().then(()=>e());return n(this.state)&&o(),this.subscribe(n,r=>{r&&o()})}overlayContainerFactory(e,n,o,s){let[r,i]=Os(n,o);return r.setAttribute("translate","no"),r.dataset.testid=e,s&&r.classList.add(s),[r,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 s=document.createElement("div");s.style.display="none",s.style.position="absolute",s.style.height="0px",s.style.width="0px",s.style.backgroundColor="red",o.appendChild(s);let r=(a=e.ownerDocument.defaultView)==null?void 0:a.frameElement,i=r?r.ownerDocument.defaultView:null;if(r&&(i===window||(i==null?void 0:i.parent)===window)){let[d,l]=Os(r,{appendTo:document.body,onMoveStart:()=>{s.style.display="none"}});d.dataset.testid=n,d.style.zIndex="2",d.appendChild(o),this.unmountHandlers.push(()=>{l()})}else document.body.appendChild(o);return s}createContainer(e,n=document.body){let o=window.getComputedStyle(n),s=document.createElement("div");return yt(s),s.dataset.testid=e,s.style.color=o.color,s.style.fontSize=o.fontSize,s.style.fontFamily=o.fontFamily,s.style.fontVariant=o.fontVariant,s.setAttribute("translate","no"),n.appendChild(s),s}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),k.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()?(k.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(ga(o.metrics))):k.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(!xi(e))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let u=n,{customStyles:o,closestScrollSelector:s,floatingMenuParent:r,appendOverlayTo:i,inputMediator:a}=u,d=O(u,["customStyles","closestScrollSelector","floatingMenuParent","appendOverlayTo","inputMediator"]),l={customStyles:o,closestScrollSelector:s,floatingMenuParent:r,appendOverlayTo:i};this.configure(d),this.settings.automaticHandlingTime&&this.setupHandlingTime(e),yt(e),this.inputMediator=a||(Et(e)?new tn(e):new en(e)),this.inputMediator.on("change",({plainText:f,rawHTML:h,suggestionTextStart:g})=>{this.store.dispatch(co({text:f,html:h,suggestionTextStart:g}))}),this.inputMediator.on("keyup",f=>{this.store.dispatch(da(qs(f)))}),this.inputMediator.on("keydown",f=>{this.handleKeyDown(f)}),this.inputMediator.on("paste",({pastedText:f,selectionText:h})=>{this.store.dispatch(ca({text:f,selectionText:h}))}),this.inputMediator.on("cut",({selectionText:f})=>{this.store.dispatch(aa(f))});let c;this.inputMediator.on("selection",f=>{clearTimeout(c),f===null?c=setTimeout(()=>{f!==null&&this.store.dispatch(uo(f))},500):this.store.dispatch(uo(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(Yo(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(Yo(!0))}),this.renderSuggestions(e,l),this.subscribe(ft("inlineSuggestions"),()=>{this.renderSuggestions(e,l)}),this.subscribe(ft("suggestionsPlacement"),()=>{this.renderSuggestions(e,l)});let p=this.renderOverlays(n);this.unmountHandlers.push(()=>{p.unmount()}),this.store.dispatch(co({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),suggestionTextStart:this.inputMediator.getSuggestionTextStart()})),this.store.dispatch(uo(this.inputMediator.getSelection())),this.store.dispatch(Yo(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=rt(n),s=null,r=a=>{s=a,i()},i=()=>{o==null||o.render(F(We,{store:this.store,children:F(_e,{broadcastEvents:this.broadcastEvents,children:F(Qd,{id:"deepdesk-nickname-dialog",error:s,onSave:a=>v(this,null,function*(){try{yield this.store.dispatch(Sa({agentNickname:a})).unwrap(),console.log("setAgentNickname",a),this.broadcastEvents.send(fo,{showNicknameDialog:!1}),this.nicknameDialogUnsubscribe&&this.nicknameDialogUnsubscribe()}catch(d){k.error("Error setting agent nickname",d),r("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 s=e(this.store.getState());s!==o&&(o=s,n(o))})}unmount(){var e,n,o,s,r;(e=this.inlineSuggestions)==null||e.unmount(),(n=this.aboveSuggestions)==null||n.unmount(),(o=this.belowSuggestions)==null||o.unmount(),(s=this.floatingMenu)==null||s.unmount(),this.unmountHandlers.forEach(i=>i()),this.unmountHandlers=[],(r=this.inputMediator)==null||r.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,s,r,i;(o=this.floatingMenu)==null||o.unmount(),(s=this.inlineSuggestions)==null||s.unmount(),(r=this.aboveSuggestions)==null||r.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,s=this.createInlineContainer(e,"deepdesk-caret"),r=rt(s);r.render(F(We,{store:this.store,customStyles:o,children:F(_e,{broadcastEvents:this.broadcastEvents,children:F(Xd,{})})}));let i=a=>{a?(s.style.display="block",s.style.top=`${a.top}px`,s.style.left=`${a.left}px`):s.style.display="none"};return this.inputMediator.on("caretposition",i),{unmount:()=>{var a;(a=this.inputMediator)==null||a.off("caretposition",i),r.unmount(),s.remove()}}}renderAboveOrBelowSuggestions(e,n,o){let{customStyles:s,closestScrollSelector:r,appendOverlayTo:i}=n,a=r&&Si(e,r)||void 0,[d,l]=this.overlayContainerFactory("deepdesk-tab-completion",a||e,{appendTo:i,closestScrollElement:a,mirrorOverflow:!0,onRemove:()=>this.unmount()},s==null?void 0:s.rootNode),[c,p]=this.overlayContainerFactory("deepdesk-suggestions-overlay",a||e,{appendTo:i,placement:o},s==null?void 0:s.suggestionsRootNode),u=rt(d);u.render(F(We,{store:this.store,customStyles:s,children:F(_e,{broadcastEvents:this.broadcastEvents,children:F(Rc,{inputElement:e})})}));let f=rt(c);return f.render(F(We,{store:this.store,customStyles:s,children:F(_e,{broadcastEvents:this.broadcastEvents,children:F(ac,{onLogIn:()=>this.loginViaPopup().catch(h=>k.warn(h.message))})})})),{unmount(){u.unmount(),f.unmount(),l(),p()}}}renderFloatingMenu(e,n){let{customStyles:o,closestScrollSelector:s,appendOverlayTo:r,floatingMenuParent:i}=n,a=s&&Si(e,s)||void 0,[d,l]=this.overlayContainerFactory("floating-menu",a||e,{appendTo:i!=null?i:r},o==null?void 0:o.floatingMenuParent),c=rt(d);return c.render(F(We,{store:this.store,customStyles:o,children:F(_e,{broadcastEvents:this.broadcastEvents,children:F(Ld,{onLogIn:()=>this.loginViaPopup().catch(p=>k.warn(p.message))})})})),{unmount(){c.unmount(),l()}}}renderOverlays(e){let{customStyles:n}=e,o=this.createContainer("deepdesk-overlays"),s=rt(o);return s.render(F(We,{store:this.store,customStyles:n,children:F(_e,{broadcastEvents:this.broadcastEvents,children:F(Ed,{})})})),{unmount(){s.unmount(),o.remove()}}}renderWidget(e,n={}){if(this.widgetElement&&k.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:o,showImages:s,isEmbedded:r,signInViaPopup:i,ssoUrl:a}=n;this.widgetElement=e,this.configure({showImages:s,isEmbedded:r,signInViaPopup:i});let d;if(a)try{d={url:new URL(a,this.settings.adminUrl).toString()}}catch(l){k.warn(`Invalid ssoUrl '${a}' passed to renderWidget`)}this.widgetRoot=rt(e),this.widgetRoot.render(F(We,{store:this.store,customStyles:o,children:F(_e,{broadcastEvents:this.broadcastEvents,children:F(au,{assistantOptions:n.assistantOptions,knowledgeAssistOptions:n.knowledgeAssist,onLogIn:()=>this.loginViaPopup(d).catch(l=>k.warn(l.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:s,initialQuestion:r}=o,i=rt(n);return i.render(F(We,{store:this.store,customStyles:s,children:F(_e,{broadcastEvents:this.broadcastEvents,children:F(pi,{children:YS(Fo,{assistantCode:e,initialQuestion:r,evaluateKnowledgeAssistFn:kn,children:[F(ln,{children:F(Bo,{title:o.title,emptyState:o.emptyState})}),F(ui,{children:F(Ho,{})})]})})})})),{unmount(){i.unmount()}}}setupHandlingTime(e){let n=Ei(e,({isVisible:o})=>{o?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){Nu(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfig(){var e;return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(e=this.state.conversation.current)!=null&&e.profileCode?(this.loadProfileConfigPromise=Promise.resolve().then(()=>v(this,null,function*(){yield this.store.dispatch(An()).unwrap();let n=et(this.state);n&&this.store.dispatch(Po({showSearch:n.search,showImageSearch:n.imageSearch,showEntitiesCommand:n.entitiesCommand,showSummaryCommand:!!n.summarizerAssistantNew,showKnowledgeSearch:!!n.knowledgeAssistantNew||!!n.knowledgeAssistant,recommendTextSuggestions:n.recommendTextSuggestions}))})).finally(()=>{et(this.state)||(this.loadProfileConfigPromise=null)}),this.loadProfileConfigPromise):Promise.resolve()}loginViaPopup(e){return v(this,null,function*(){return new Promise((n,o)=>{this.store.dispatch(no());let s=new MessageChannel,r=s.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)};r.onmessage=f=>v(this,null,function*(){var h,g;if((h=f.data)!=null&&h.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((g=f.data)==null?void 0:g.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(fn),d=!0,s.port1.close(),n()}catch(m){console.error(m),o(m)}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 g=JSON.stringify({type:"deepdesk-popup-parent-origin"});c==null||c.postMessage(g,a.origin)}catch(g){k.error("Error posting message to popup",g),o(g)}break}case"deepdesk-popup-loaded":{try{let g=JSON.stringify({type:"deepdesk-popup-create-channel"});c==null||c.postMessage(g,a.origin,[s.port2])}catch(g){k.error("Error posting message to popup",g),o(g)}break}case"deepdesk-popup-error":{if(l(),f.data.message==="Platform account url mismatch"){let g=`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}).`;k.warn(g),this.store.dispatch(zs(g)),o(new Error(g))}if(f.data.message==="Timeout"){let g="Please contact your administrator: Popup timed out. Check if the account's platform url is configured correctly.";k.warn(g),this.store.dispatch(zs(g)),o(new Error(g))}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(Jo()))})}refreshWidgetSuggestions(){return v(this,null,function*(){if(!this.widgetRoot)return;let{uiConfig:e}=this.state.profile.data;if(!e.widget)return;let n=Ln(this.state);try{n.forEach(({type:o})=>{switch(o){case"entities":this.store.dispatch(fe());break;case"pinned-messages":case"sticky-messages":break;default:Yn.includes(o)||this.store.dispatch(he(o))}})}catch(o){this.handleError(o)}})}};rn.version="19.5.0",rn.count=0;var Ds=rn;function ex(t){return v(this,null,function*(){var s,r,i;let n=yield((s=t.fetch)!=null?s:window.fetch)(t.url),o=yield n.blob();return new File([o],t.name,{type:(i=(r=t.mimeType)!=null?r:n.headers.get("Content-Type"))!=null?i:"image/jpeg"})})}function tx(t,e){return v(this,null,function*(){let n=yield ex(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 nx(t,e,n){return v(this,null,function*(){yield new st(t).authenticateWithKey(e,n)})}function ox(t){return t.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function sx(o,s){return v(this,arguments,function*(t,e,n={}){var p,u;let{value:r}=t,{start:i,end:a}=(p=n.replace)!=null?p:{start:0,end:r.length},d=`${r.slice(0,i)}${e}${r.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 rx(o,s){return v(this,arguments,function*(t,e,n={}){let r=n.replace?Rt(t,n.replace.start,n.replace.end):zn(t),i,a=()=>{if(n.setRange)return n.setRange(r.cloneRange());r.deleteContents(),i=document.createElement("span"),r.insertNode(i),n.insertBRs!==!1?e.split(`
12
12
  `).reverse().forEach((d,l)=>{l>0&&r.insertNode(document.createElement("br")),r.insertNode(document.createTextNode(d))}):r.insertNode(document.createTextNode(e))};return Promise.resolve(a()).then(()=>{try{if(n.selectionAfter!==!1){t.focus();let d=n.selectionAfter?Rt(t,n.selectionAfter.start,n.selectionAfter.end):(r.collapse(!1),r),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 ix(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 ax(t){let e=document.createDocumentFragment();return t.split(`
13
13
  `).forEach((n,o)=>{o>0&&e.appendChild(document.createElement("br"));let s={index:0},r=0;for(;s=n.slice(r).match(/(\[([^\]]+)])\(([^)]+)\)/);){let i=document.createElement("a");i.href=s[3],i.setAttribute("target","_blank"),i.setAttribute("rel","noopener noreferrer"),i.appendChild(document.createTextNode(s[2])),e.appendChild(document.createTextNode(n.slice(r,r+s.index))),e.appendChild(i),r=r+s.index+s[0].length}e.appendChild(document.createTextNode(n.slice(r)))}),e}function $u(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):$u(n,e)}function lx(s,r){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?ix(e):ax(e);n?$u(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()}})})}export{_ as Card,en as ContentEditableInput,st as DeepdeskAPI,Ds as DeepdeskSDK,on as HTTPClient,ot as InputMediator,Mt as InputType,Hs as KeyboardHint,pp as Label,eo as Locale,Me as Section,ln as SectionList,Ne as Sources,M as Suggestion,Y as SuggestionList,tn as TextAreaInput,Lt as ToggleButton,tx as attachFile,nx as authenticateWithKey,zn as createFullRange,Os as createOverlayContainer,Rt as createRangeFromOffsets,Nn as escapeHTML,ox as formatTextMarkup,Es as getRangeOffsets,ks as getRangeText,lx as insertCKEditor,Ko as isHTML,xi as isSupportedInputElement,Ys as logEvent,rx as updateContentEditable,sx as updateTextArea,ht as useClickOutsideRoot,b as useStyles,Ei as waitForElementVisibilityChange};