@deepdesk/deepdesk-sdk 19.0.2-beta.7 → 19.0.2-beta.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs.js +5 -5
- package/dist/index.esm.js +5 -5
- package/dist/index.iife.js +5 -5
- package/package.json +1 -1
package/dist/index.esm.js
CHANGED
|
@@ -4,15 +4,15 @@ Try polyfilling it using "@formatjs/intl-pluralrules"
|
|
|
4
4
|
c-17.9,17.9-27.3,40.1-27.3,65.7C163.4,163,163.4,233,163.4,233z M465.5,267.9V477c0,9.4-3.4,17.9-10.2,24.7
|
|
5
5
|
c-6.8,6.8-15.4,10.2-24.7,10.2h-349c-9.4,0-17.9-3.4-24.7-10.2c-6.8-6.8-10.2-15.4-10.2-24.7V267.9c0-9.4,3.4-17.9,10.2-24.7
|
|
6
6
|
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
|
|
7
|
-
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 jl}from"react/jsx-runtime";var Mf={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},$l=({className:t,color:e})=>jl("svg",{className:t,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:jl("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:Mf[e||"pink"]})});var Gl={root:"dd-LbeUM",text:"dd-Dpfn1",isLoggedIn:"dd-XvHAn",isLoggedOut:"dd-21y-z",icon:"dd-8rLqS",logo:"dd-slXhD",lock:"dd-ByzlR"};var vs={};X(vs,{enUS:()=>Nf,nlNL:()=>Of});var Nf={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},Of={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};import{useDispatch as Ff}from"react-redux";import{jsx as xs,jsxs as ql}from"react/jsx-runtime";var Xl=({onLogIn:t})=>{let e=R(vs),n=E("floatingMenu"),o=E("productName"),r=Ff(),s=_f(J),i=x("FloatingMenu",Gl);if(s===null||n===!1)return null;let a=()=>{s===!0?r(ge(!0)):t()};return ql("button",{type:"button",className:Df(i.root,{[i.isLoggedIn]:s,[i.isLoggedOut]:!s}),onClick:a,children:[xs("div",{className:i.text,children:e(s?"search":"signin",{productName:o})}),ql("div",{className:i.icon,children:[xs($l,{className:i.logo,color:"pink"}),s===!1&&xs(Vl,{className:i.lock})]})]})};import{useEffect as rh,useRef as sh}from"react";import{useDispatch as ih,useSelector as Kt}from"react-redux";import{useEffect as Hf}from"react";function gt(t){Hf(()=>{let e=n=>{n.isWithinRoot||t(n)};return document.body.addEventListener("mouseup",e),()=>{document.body.removeEventListener("mouseup",e)}},[t])}function ft(t){t.addEventListener("mouseup",e=>{e.isWithinRoot=!0},!0)}function Te(t){let{showMidSentenceSuggestions:e,showSuggestionsBeforePattern:n,showSuggestionsAfterPattern:o}=t.settings,{text:r,selection:s}=t.input;return s.start!==s.end?!1:s.end>=r.length?!0:e?n&&new RegExp(n).test(r.substring(s.end))||o&&new RegExp(o).test(r.substring(0,s.end))?!0:n===!1&&o===!1:!1}import{createSlice as Bf}from"@reduxjs/toolkit";var Uf={showTabHint:!1,inputHasFocus:!1,overlayCollapsed:!1,openOverlayWhenTyping:!1,overlayCollapsedUserOverwrite:!1},No=({ui:t})=>t.overlayCollapsed,Jl=Bf({name:"ui",initialState:Uf,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:Nn,setInputFocus:Oo,setOverlayCollapsed:Je,setOpenOverlayWhenTyping:Ql,setOverlayCollapsedUserOverwrite:Zl}=Jl.actions,Yl=Jl.reducer;import{useMemo as th}from"react";import{Interweave as rd}from"interweave";import{useEffect as $f,useMemo as Gf,useRef as qf,useState as Xf}from"react";import{useDispatch as Jf,useSelector as sd}from"react-redux";import{useEffect as Kf}from"react";function ed(t,e,n){Kf(()=>{let o=t.current;return o?(o.addEventListener(e,n),()=>{o.removeEventListener(e,n)}):()=>{}},[t,e,n])}var td={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 nd,jsxs as zf}from"react/jsx-runtime";var od=({title:t})=>zf("svg",{xmlns:"http://www.w3.org/2000/svg",width:"18px",height:"18px",viewBox:"0 0 24 24","aria-labelledby":"closeTitle",children:[nd("title",{id:"closeTitle",children:t}),nd("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 Ss={};X(Ss,{enUS:()=>Wf,nlNL:()=>Vf});var Wf={assistant:[{type:0,value:"Assistant"}],close:[{type:0,value:"Close"}]},Vf={assistant:[{type:0,value:"Assistent"}],close:[{type:0,value:"Sluiten"}]};import{jsx as De,jsxs as id}from"react/jsx-runtime";var Qf=["search","personal-collection-search","search-autocomplete"];function Zf(t,e,n,o={}){var s;let r="";return Qf.includes(e)?r=el(os(t,n,{stripAgentPart:!0}),(s=o.searchKeywords)!=null?s:[n]):r=os(t,n,o),o.placeholders===!0&&(r=tl(r)),r}var Yf=()=>{},eh=({selected:t,suggestion:e})=>{let n=R(Ss),o=E("inlineSuggestions"),r=sd(At),[s,i]=Xf(!1),a=E("enableSuggestionFeedback"),d=sd(h=>h.input.text),l=Jf(),c=x("TextSuggestion",td),u=qf(null),p=e.source==="assistant",g=a&&!p;$f(()=>{let h=setTimeout(()=>{l(ta({text:e.text,suggestion:e}))},500);return()=>{clearTimeout(h)}},[e]),ed(u,"click",()=>{l(re({suggestion:e,text:e.text,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"}))});let f=()=>{l(it({source:e.source,text:e.text,assistantCode:e.assistantCode}))},m=Gf(()=>Zf(e.text,e.source,r,{stripAgentPart:o,placeholders:!0,searchKeywords:e.searchKeywords}),[o,e.text,e.source,r,e.searchKeywords]);return e.source==="gpt"&&!o?null:id("div",{className:c.root,onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),children:[De(M,{ref:u,as:"button","data-testid":"suggestions-overlay-item",selected:t,onClick:Yf,children:e.source==="assistant"?id("div",{className:c.assistantContainer,children:[De(rd,{containerTagName:"div",tagName:"span",className:c.formattedTextTruncated,content:m}),De("span",{className:c.assistantBadge,children:n("assistant")})]}):De(rd,{containerTagName:"div",tagName:"span",className:c.formattedText,content:m})}),g&&s&&De("div",{className:c.actions,children:De(Io,{source:"overlay",context:d,suggestion:e})}),p&&s&&De("div",{className:c.closeIconContainer,children:De("button",{type:"button",className:c.closeIcon,onClick:f,title:n("close"),children:De(od,{title:n("close")})})})]})},ad=eh;import{jsx as oh}from"react/jsx-runtime";var nh=({suggestions:t,selectedIndex:e,reverse:n})=>th(()=>{let r=t.map((s,i)=>oh(ad,{index:i,selected:i===e,suggestion:s},`${s.text}-${s.source}`));return n?r.reverse():r},[t,e,n]),Do=nh;var ld={root:"dd-PfvRI",paper:"dd-HYlyY"};import{jsx as _o}from"react/jsx-runtime";var ah=()=>{let t=sh(null),e=x("InlineSuggestionsOverlay",ld),n=Kt(Te),o=ih(),r=Kt(J),s=Kt(Lt),i=Kt(No),a=E("showTextSuggestions"),d=Kt(st),l=Kt(cn);return gt(()=>{setTimeout(()=>{o(Je({collapse:!0,skipWhenInputFocus:!0}))})}),rh(()=>{let c=t.current;if(!c||!c.parentElement)return;c.parentElement.style.left="0px";let u=c.getBoundingClientRect();c.parentElement.style.left=`${Math.min(window.innerWidth-4-u.right,0)}px`}),i||!n||!a||d.length===0||r!==!0||s===!1?null:_o("div",{className:e.root,"data-variant":"inline",children:_o("div",{ref:t,className:e.paper,children:_o(te,{children:_o(Do,{suggestions:d,selectedIndex:l})})})})},dd=ah;import{Provider as lh}from"react-redux";import{jsx as Fo}from"react/jsx-runtime";var dh=({children:t})=>{let n=E("locale").replace("-","");return Fo(Jr.Provider,{value:n,children:t})},ch=({store:t,customStyles:e={},children:n})=>Fo(lh,{store:t,children:Fo(dh,{children:Fo(sn.Provider,{value:e,children:n})})}),_e=ch;import Es from"classnames";import{useEffect as Ch,useRef as Th,useState as wh}from"react";import{useDispatch as Eh,useSelector as Qe}from"react-redux";import{useState as ph}from"react";function cd(t,e){let[n,o]=ph(()=>{if(typeof window=="undefined")return e;try{let s=window.localStorage.getItem(t);return s?JSON.parse(s):e}catch(s){return k.error(s),e}});return[n,s=>{try{let i=s instanceof Function?s(n):s;o(i),typeof window!="undefined"&&window.localStorage.setItem(t,JSON.stringify(i))}catch(i){k.error(i)}}]}var pd=()=>/Mac/i.test(navigator.platform);import gh from"classnames";import{Fragment as fh,useCallback as Cs,useMemo as md}from"react";var bs={};X(bs,{enUS:()=>uh,nlNL:()=>mh});var uh={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"}]}]},mh={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 ud={root:"dd-uTPjX",anchor:"dd-C8lsZ",anchorButton:"dd-IoSx9"};import{jsx as Ho,jsxs as gd}from"react/jsx-runtime";var Ts=(t,e,n)=>o=>Ho("button",{className:t.anchorButton,type:"button",value:e,onClick:n,children:o},e),hh=({className:t,loginUrl:e,isEmbedded:n,onSnooze:o,onLogIn:r})=>{let s=R(bs),i=ne(),a=x("Login",ud),d=E("productName"),l=Cs(h=>{h.preventDefault(),o&&o(Number.parseInt(h.target.value,10))},[]),c=Cs(h=>{h.preventDefault(),i.send(_t,!0)},[e]),u=md(()=>h=>Ho("a",{onClick:T=>{T.preventDefault(),r()},href:e,className:a.anchor,target:"_blank",rel:"noreferrer",children:h},"login"),[e]),p=Cs(h=>Ho("button",{type:"button",className:a.anchorButton,onClick:c,children:h},"prompt"),[c]),{min:g,hour:f,day:m}=md(()=>({min:Ts(a,600,l),hour:Ts(a,3600,l),day:Ts(a,3600*12,l)}),[]);return gd("div",{className:gh(t,a.root),children:[s("loginPlease",{login:n?p:u,productName:d}),o&&gd(fh,{children:[Ho("br",{}),s("snooze",{min:g,hour:f,day:m})]})]})},Bo=hh;import{useDispatch as yh}from"react-redux";var fd={root:"dd-DoQhb",text:"dd-Jwnev"};import{jsx as hd,jsxs as xh}from"react/jsx-runtime";var vh=({title:t})=>{let e=x("SearchTrigger",fd),n=yh(),o=K();return xh("button",{type:"button",className:e.root,onClick:()=>{n(ge(!0)),o("open search",{via:"autocomplete-overlay"})},children:[hd(Bt,{}),hd("span",{className:e.text,children:t})]})},yd=vh;var ws={};X(ws,{enUS:()=>Sh,nlNL:()=>bh});var Sh={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"}]},bh={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 vd={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 q,jsxs as ht}from"react/jsx-runtime";var kh=({onLogIn:t})=>{let e=x("SuggestionsOverlay",vd),n=R(ws),o=Qe(Te),r=Qe(ea),s=Eh(),i=Th(null),a=E("searchTriggerKey"),d=E("productName"),l=Qe(No),c=Qe(J),u=Qe(Ki),p=Qe(Lt),[g,f]=wh(null),m=E("showSearch"),h=E("showTextSuggestions"),C=E("adminUrl"),T=E("isEmbedded"),b=E("suggestionsPlacement"),[w,I]=cd("dd-snooze-until-ms",0),N=l||w>Date.now(),_=Qe(st),W=Qe(cn),ce=_.filter(U=>U.source!=="gpt").length,ae=()=>{N&&I(0),s(Zl(!N))},O=U=>{let Pe=Date.now()+U*1e3;I(Pe),k.info(`Snooze until: ${new Date(Pe)}`),s(Je({collapse:!0}))};return Ch(()=>{ce===0&&f(null)},[_,ce]),gt(()=>{s(Je({collapse:!0,skipWhenInputFocus:!0}))}),c===null||p===!1?null:c===!1?ht("div",{ref:i,className:Es(e.root,{[e.isCollapsed]:N}),children:[!N&&ht("div",{className:e.triggers,children:[q("div",{style:{flex:1}}),q("div",{className:e.triggersRight,children:q(Et,{className:e.toggleButton,title:n("collapse"),onClick:ae,isCollapsed:!1})})]}),q("div",{className:e.toggleButtonWrapper,children:q(Et,{className:e.toggleButton,title:n("open",{productName:d}),onClick:ae,isCollapsed:!0})}),ht("div",{className:e.collapsible,children:[u&&ht("div",{className:e.loginError,children:[q("span",{className:e.loginErrorMessage,children:u}),q("button",{type:"button",className:e.loginErrorDismiss,onClick:()=>s(Yn()),"aria-label":n("dismissError"),children:n("dismiss")})]}),q(Bo,{loginUrl:C,isEmbedded:T,onLogIn:t,onSnooze:O})]})]}):!r||!o?null:ht("div",{ref:i,className:Es(e.root,{[e.isCollapsed]:N}),children:[!N&&ht("div",{className:e.triggers,children:[q("div",{style:{flex:1},children:m&&q("div",{style:{display:"inline-block"},onFocus:()=>{},onMouseOver:()=>f(n(pd()?"searchHintMac":"searchHintWindows",{searchTriggerKey:a.toUpperCase()})),onMouseLeave:()=>f(null),children:q(yd,{title:n("search")})})}),ht("div",{className:e.triggersRight,onFocus:()=>{},children:[q("div",{className:Es(!g&&e.hintsHidden,e.hints),children:g}),q(Et,{className:e.toggleButton,title:n("collapse"),onClick:ae,isCollapsed:!1})]})]}),q("div",{className:e.toggleButtonWrapper,children:q(Et,{className:e.toggleButton,title:n("open",{productName:d}),onClick:ae,isCollapsed:!0})}),ce>0&&h&&q("div",{className:e.collapsible,onFocus:()=>{},children:q(te,{children:q(Do,{suggestions:_,selectedIndex:W,reverse:b==="above"})})})]})},xd=kh;import Ds from"classnames";import{Interweave as Ey}from"interweave";import{useCallback as ky,useEffect as Ry,useMemo as Vd,useRef as Py}from"react";import{connect as Iy}from"react-redux";import{useEffect as Rh,useRef as Ph,useState as Ih}from"react";function Uo(t){return t.contentEditable==="true"}function Lh(t){let e=0,n=0,o=window.getSelection();if(o.rangeCount!==0){let r=o.getRangeAt(0),s=r.cloneRange();s.selectNodeContents(t),s.setEnd(r.endContainer,r.endOffset),n=s.toString().length,s.selectNodeContents(t),s.setEnd(r.startContainer,r.startOffset),e=s.toString().length}return{selectionStart:e,selectionEnd:n}}function Sd(t){let{selectionStart:e,selectionEnd:n}=Uo(t)?Lh(t):t;return[e,n]}function bd(t){let[,e]=Ih(),n=Ph(null);return n.current=Sd(t),Rh(()=>{let o=()=>{var a;let[r,s]=(a=n.current)!=null?a:[],i=Sd(t);(!i||r!==i[0]||s!==i[1])&&(n.current=i,e({}))};return t.addEventListener("keyup",o),t.addEventListener("click",o),t.addEventListener("focus",o),document.addEventListener("selectionchange",o),()=>{t.removeEventListener("keyup",o),t.removeEventListener("click",o),t.removeEventListener("focus",o),document.removeEventListener("selectionchange",o)}},[t]),n.current}function Cd(t,e){if(!e)return;let n=t,{value:o}=n,[r,s]=e,i=o.match(Xn);if(!i||i.length===0)return;let a=0;i.find(d=>{let l=o.indexOf(d,a);return r>l&&s<l+d.length?(n.selectionStart=l,n.selectionEnd=l+d.length,!0):(a=l+d.length,!1)})}import{cloneElement as Ah}from"react";var Mh=["div","span","mark","strong","b","i","u","em"];function ks(t,e,n=0){var s;let o=t[t.length-1],r=typeof o=="object"&&o!==null?(s=o.props)==null?void 0:s.tagName:void 0;if(r==="br")return t.pop(),[...t,...e,o];if(Mh.includes(r)){let i=Array.isArray(o.props.children)?o.props.children:[o.props.children];return[...t.slice(0,t.length-1),Ah(o,{children:ks(i,e,n+1)})]}return[...t,...e]}function yt(t){return t.tagName.toLowerCase()==="textarea"}var Td={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 Zh from"classnames";import{Matcher as Yh}from"interweave";import{useEffect as ey,useMemo as ty}from"react";import{useEffect as Nh,useRef as Oh,useState as Dh}from"react";function wd(t,e){let n;return[(...o)=>{window.cancelAnimationFrame(n);let r=e?e(...o):o;n=window.requestAnimationFrame(()=>{t(...r)})},()=>window.cancelAnimationFrame(n)]}function Ko(t){let e=Oh(null),[n,o]=Dh(!1);return Nh(()=>{var c;let r=!1,s=Number.parseFloat((c=window.getComputedStyle(document.body).zoom)!=null?c:"1"),[i,a]=wd((u,p)=>{let g=e.current;if(!g)return;let f=u/s,m=p/s,h=g.getBoundingClientRect(),C=f>h.x&&f<h.x+h.width&&m>h.y&&m<h.y+h.height;C&&!r?(r=!0,o(!0)):!C&&r&&(r=!1,o(!1))},({clientX:u,clientY:p})=>[u,p]),[d,l]=wd(()=>{r=!1,o(!1)});return t.addEventListener("mousemove",i),t.addEventListener("mouseleave",d),()=>{a(),l(),t.removeEventListener("mousemove",i),t.removeEventListener("mouseleave",d)}},[e]),[e,n]}function Ed(t){return t.replace(/[.*+^${}()|[\]\\]/g,"\\$&")}function zo(t){return e=>{t.forEach(n=>{typeof n=="function"?n(e):n!=null&&(n.current=e)})}}function kd(t){return t!=null}import Ad from"classnames";import{createRef as jh,useCallback as Ps,useMemo as $h,useRef as Gh,useState as qh}from"react";import{useState as _h,useLayoutEffect as Fh}from"react";var Hh=["bottom","height","left","right","top","width"],Bh=(t={},e={})=>Hh.some(n=>t[n]!==e[n]),Fe=new Map,Rd,Pd=()=>{let t=[],e=[];Fe.forEach((n,o)=>{if(o instanceof Element&&!o.isConnected){e.push(o);return}let r=o.getBoundingClientRect();Bh(r,n.rect)&&(n.rect=r,t.push(n))}),e.forEach(n=>{Fe.delete(n)}),t.forEach(n=>{n.callbacks.forEach(o=>o(n.rect))}),Rd=window.requestAnimationFrame(Pd)};function Uh(t,e){return{observe(){let n=Fe.size===0;if(Fe.has(t)){let o=Fe.get(t);o.callbacks.push(e),o.rect&&e(o.rect)}else Fe.set(t,{rect:void 0,hasRectChanged:!1,callbacks:[e]});n&&Pd()},unobserve(){let n=Fe.get(t);if(n){let o=n.callbacks.indexOf(e);o>=0&&n.callbacks.splice(o,1),n.callbacks.length||Fe.delete(t),Fe.size||cancelAnimationFrame(Rd)}}}}function Rs(t){let[e,n]=_h(null);return Fh(()=>{if(!t.current)return;let o=Uh(t.current,r=>{n(r)});return o.observe(),()=>{o.unobserve()}},[t]),e}import{useContext as Kh,useLayoutEffect as zh,useState as Wh}from"react";import{createPortal as Vh}from"react-dom";var Id={root:"dd-r-dgo"};var Ld=({children:t,parentNode:e})=>{let[n,o]=Wh(null),r=Kh(sn);return zh(()=>{let s=document.createElement("div");return ft(s),s.classList.add(Id.root),r!=null&&r.portalRootNode&&s.classList.add(r==null?void 0:r.portalRootNode),(e||document.body).appendChild(s),o(s),()=>{s.isConnected&&s.remove()}},[]),n?Vh(t,n):null};var we={ref:"dd-iz-KP",root:"dd-vEMon",positionAbove:"dd-mUCxM",positionBelow:"dd-7oZI7",positionLeft:"dd-BiWvD",positionRight:"dd-JIWea",alignStart:"dd-5ivu6",alignCenter:"dd-rnVkP",alignEnd:"dd-gZBp4"};import{jsx as Is}from"react/jsx-runtime";var Wo=(t=!1)=>{let[e,n]=qh(t),o=Ps(()=>n(!0),[]),r=Ps(()=>n(!1),[]),s=Ps(()=>n(a=>!a),[]),i=Gh(null);return{opened:e,open:o,close:r,toggle:s,triggerRef:i}};function Ls(t,e=null,n=0){if(!t)return{display:"none"};let o=e?t.top-e.top<0||t.top<e.top-n?e.top-n:t.top+t.height>e.top+e.height+n?e.top+e.height+n-t.height:t.top:t.top,r=e?t.left<e.left-n?e.left-n:t.left+t.width>e.left+e.width+n?e.left+e.width+n-t.width:t.left:t.left;return{top:o,left:r,height:t.height,width:t.width}}var zt=l=>{var c=l,{className:t,triggerRef:e,boundaryRef:n=jh(),position:o="above",align:r="center",children:s,toStyle:i=Ls,parentNode:a}=c,d=A(c,["className","triggerRef","boundaryRef","position","align","children","toStyle","parentNode"]);let u=Rs(e),p=Rs(n),g=$h(()=>i(u,p,0),[u,p]);return Is(Ld,{parentNode:a,children:Is("div",S(y({className:Ad(we.ref,{[we.positionAbove]:o==="above",[we.positionBelow]:o==="below",[we.positionLeft]:o==="left",[we.positionRight]:o==="right",[we.alignStart]:r==="start",[we.alignCenter]:r==="center",[we.alignEnd]:r==="end"}),style:g},d),{role:"dialog",children:Is("div",{className:Ad(t,we.root),children:s})}))})};import Xh from"classnames";import{forwardRef as Jh,useRef as Qh}from"react";var He={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 Md}from"react/jsx-runtime";var Vo=Jh((r,o)=>{var s=r,{className:t,children:e}=s,n=A(s,["className","children"]);let i=Qh(null),a=x("TabCompletion",He);return Md("div",S(y({ref:zo([i,o]),className:Xh(t,a.popoverContentContainer)},n),{children:Md("div",{className:a.popoverContent,children:e})}))});import{jsx as On,jsxs as ry}from"react/jsx-runtime";var ny=t=>e=>{let n=Ls(e);return"top"in n&&(n.width=t.width-(e.left-t.left)-10),n},oy=({inputElement:t,boundaryRef:e,inputStyle:n,children:o,suggestion:r})=>{let s=x("TabCompletion",He),i=Wo(),a=ty(()=>ny(t.getBoundingClientRect()),[t]),[d,l]=Ko(t);return ey(()=>{l?i.open():i.close()},[l]),ry("span",{children:[On("mark",{ref:zo([d,i.triggerRef]),className:Zh(s.matchKeyword,{[s.hover]:l}),"aria-haspopup":"dialog","aria-expanded":i.opened?"true":"false",children:o}),i.opened&&On(zt,{className:s.popover,triggerRef:i.triggerRef,boundaryRef:e,position:"below",align:"start",toStyle:a,children:On(Vo,{style:n,children:On("div",{className:s.hintText,children:r})})})]})},jo=class extends Yh{constructor(){super(...arguments);this.keywordMatches=[];this.preparedKeywordMatches=[];this.usedKeywordMatches=new Set}onBeforeParse(n,o){return o.keywordMatches&&o.keywordMatches!==this.keywordMatches&&(this.preparedKeywordMatches=o.keywordMatches.map(r=>S(y({},r),{keywordRegex:new RegExp(`\\b${Ed(r.keyword)}\\b`,"i")})),this.keywordMatches=o.keywordMatches),this.usedKeywordMatches.clear(),n}match(n){let o=this.preparedKeywordMatches.map(s=>{if(this.usedKeywordMatches.has(s))return null;let i=n.match(s.keywordRegex);if(!i)return null;let a=n.charAt(i.index-1),d=n.charAt(i.index+s.keyword.length);return a==="{"&&d==="}"?null:{index:i.index,length:i[0].length,match:i[0],matchString:i[0],suggestion:s.suggestion,preparedKeywordMatch:s,valid:!0}}).filter(kd);if(o.length===0)return null;let r=o.reduce((s,i)=>i.index<s.index?i:s);return this.usedKeywordMatches.add(r.preparedKeywordMatch),r}replaceWith(n,o){return On(oy,{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 sy}from"interweave";import iy from"classnames";import{jsx as Nd}from"react/jsx-runtime";var ay=({inputElement:t,children:e})=>{let n=x("TabCompletion",He),[o,r]=Ko(t);return Nd("mark",{ref:o,className:iy(n.matchPlaceholder,{[n.hover]:r}),children:e})},$o=class extends sy{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 Nd(ay,{inputElement:n.inputElement,children:e},`placeholder_${n.matchString}_${n.key}`)}asTag(){return"mark"}};import Os from"classnames";import{Matcher as yy}from"interweave";import{createRef as vy,forwardRef as xy,useCallback as Sy,useEffect as Kd,useRef as zd,useState as Wd}from"react";import{useDispatch as by,useSelector as Cy}from"react-redux";import{jsx as Od}from"react/jsx-runtime";var Dd=()=>Od("svg",{width:"1.3em",height:"1.3em",focusable:"false","aria-hidden":"true",viewBox:"0 0 24 24","data-testid":"InsertLinkIcon",tabIndex:-1,children:Od("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 ly,useEffect as Fd,useMemo as dy,useState as Hd}from"react";import{useDispatch as cy,useSelector as Bd}from"react-redux";import py from"lodash.debounce";var _d={root:"dd-ky-Bv",content:"dd-kV5e1"};function Go(t,e,n){var r;let o=((r=t.imageSizes)==null?void 0:r[e])||t.image||n;if(!o)return null;try{return new URL(o).toString()}catch(s){return null}}function As(t){return t.replace("https://www.","").replace("https://","")}import{jsx as vt,jsxs as Ms}from"react/jsx-runtime";var uy=3,my=t=>({image:t.image||"",text:t.text,id:t.id,title:t.title}),gy=({onSelectLink:t,onDismiss:e,placeholder:n,visitUrlText:o,linkCount:r=uy})=>{let s=x("LinkSearch",_d),[i,a]=Hd(""),d=cy(),l=Bd(Ol("url")),c=Bd(wa("URL")),u=dy(()=>c.map(my),[c]),[p,g]=Hd(u.length-1),f=E("fallbackImage"),m=b=>{let w=b.target;a(w.value)},h=(b,w)=>{b.stopPropagation(),b.preventDefault(),window.open(w,"_blank")},C=b=>{var N;let w=p-1<0?u.length-1:p-1,I=p+1===u.length?0:p+1;b.code==="Escape"&&(a(""),e()),b.code==="ArrowUp"&&g(w),b.code==="ArrowDown"&&g(I),b.code==="Enter"&&t(((N=u[p])==null?void 0:N.text)||i)},T=ly(py(b=>{d(lt({query:b,type:"URL",tags:["link-search"]}))},300),[]);return Fd(()=>{i&&T(i)},[i]),Fd(()=>()=>{d(co())},[]),Ms("div",{className:s.root,children:[vt(te,{withDivider:!0,children:(i?u:l).slice(0,r).map((b,w)=>vt(M,{selected:p===w,onClick:()=>t(b.text),"data-testid":"linksearch-suggestion",children:Ms(D,{children:[vt(D.Image,{src:Go(b,"small",f||void 0),title:b.title||b.text}),Ms(D.Content,{className:s.content,cropText:!0,children:[vt(D.Title,{children:b.title||As(b.text)}),b.title&&As(b.text)]}),vt(M.Actions,{children:vt(M.ActionButton,{label:o,onClick:I=>h(I,b.text)})})]})},b.text))}),vt(wn,{value:i,onChange:m,autoFocus:!0,placeholder:n,onKeyUp:C})]})},Ud=gy;var Ns={};X(Ns,{enUS:()=>fy,nlNL:()=>hy});var fy={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"}]},hy={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 ye,jsxs as qo}from"react/jsx-runtime";var Ty=xy((t,e)=>{let n=x("TabCompletion",He);return ye("mark",{ref:e,className:Os(n.matchSelection)},"selection-start")}),wy=({startRef:t,boundaryRef:e,inputStyle:n,inputElement:o,children:r})=>{let s=R(Ns),i=x("TabCompletion",He),a=E("addToPersonalCollection"),d=Cy(Xe("/admin/personal-collection/new")),l=zd(null),c=zd(null),[u,p]=Wd(null),g=E("insertLinkAsHtml"),f=by(),m=Wo(document.activeElement===o),[h]=Wd(()=>document.createRange());m.triggerRef.current=h,Kd(()=>()=>h.detach(),[]),Kd(()=>{let T=t.current,b=l.current;!T||!b||(h.setStart(T,0),h.setEnd(b,0))},[t.current,l.current]),gt(()=>{m.close()});let C=Sy(T=>{let b=h.toString(),w=/^http(s?):\/\//.test(T)?T:`https://${T}`,I=g?`<a href="${w}" target="_blank">${b}</a>`:`[${b}](${w})`;f(re({text:I,suggestion:{text:I,source:"search-url",type:"url"},eventMetrics:{inputType:"mouse"},replace:"selection"}))},[]);return qo("span",{children:[ye("mark",{ref:l,className:Os(i.matchSelection),"aria-haspopup":"dialog","aria-expanded":m.opened?"true":"false",children:r}),m.opened&&ye(zt,{className:i.popoverRoot,triggerRef:m.triggerRef,boundaryRef:e,position:"above",align:"start",children:qo(Vo,{style:n,ref:c,children:[qo("div",{className:Os(i.selectionOptions,{[i.selectionOptionsIsHidden]:u!==null}),children:[qo("button",{type:"button",tabIndex:u===null?-1:void 0,className:i.selectionOptionsButton,onClick:()=>p("insertLink"),children:[ye(Dd,{}),ye("span",{children:"\xA0"}),ye("span",{children:s("insertLink")})]}),a&&d&&ye("button",{type:"button",tabIndex:u===null?-1:void 0,className:i.selectionOptionsButton,onClick:()=>{let T=h.toString(),b=`${d}?text=${encodeURIComponent(T)}`;window.open(b,"_blank")},children:ye("span",{children:s("addToPersonalCollection")})})]}),u==="insertLink"&&ye(Ud,{placeholder:s("linkInputPlaceholder"),visitUrlText:s("visitUrl"),onSelectLink:C,onDismiss:()=>{p(null),m.close()}})]})})]},"selection-end")},Xo=class extends yy{constructor(){super(...arguments);this.charCount=0;this.foundIndex=0;this.startRef=null}onBeforeParse(n,o){return this.props=o,this.charCount=0,this.startRef=vy(),this.foundIndex=0,n}match(n){if(!this.props||this.props.selection===null||this.foundIndex===2)return null;let[o,r]=this.props.selection;if(o===r)return null;let s=this.foundIndex===0?o:r,i=s>=this.charCount&&s<=this.charCount+n.length?{index:s-this.charCount,length:0,match:"",valid:!0}:null;i&&this.foundIndex++;let a=this.foundIndex===1;return i&&a?this.charCount+=s-this.charCount:this.charCount+=n.length,i?y({isStart:a},i):null}replaceWith(n,o){return o.isStart?ye(Ty,{ref:this.startRef}):ye(wy,{inputElement:o.inputElement,startRef:this.startRef,boundaryRef:o.boundaryRef,inputStyle:o.inputStyle})}asTag(){return"mark"}};import{useSelector as Ly}from"react-redux";import{jsx as Wt,jsxs as Ny}from"react/jsx-runtime";var Ay=({enabled:t,content:e,tabText:n,showTabHint:o,showTabCompletion:r,showStyleSuggestions:s,keywordMatches:i,inputElement:a,source:d})=>{let l=x("TabCompletion",Td),c=E("insertLink"),u=E("addToPersonalCollection"),p=E("showMidSentenceSuggestions"),g=E("inlineSuggestions"),f=bd(a),m=Py(null),h=Ly(J);Ry(()=>{yt(a)&&f&&Cd(a,f)},[f]);let C=ky(w=>{if(!r||!n)return w;let I=[Wt("span",{className:l.resetIndent,children:"\u200B"},"u200B"),Wt("span",{"data-testid":"tab-completion",className:Ds(l.tabText,l.resetIndent),"data-source":d,children:n},"tabText")];return o&&I.push(Wt("span",{className:Ds(l.hint,l.resetIndent),children:Wt(Rr,{keyCode:"tab"},"tabHint")},"tabHint")),ks(w,I)},[r,n,o]),T=Vd(()=>{let w=[];return(c||u)&&w.push(new Xo("selection")),w.push(new $o("placeholders")),s&&w.push(new jo("keywords")),w},[g,c,u,s]),b=Vd(()=>{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||!h?null:Ny("div",{ref:w=>{w!=null&&w.parentElement&&(m.current=w==null?void 0:w.parentElement)},className:l.root,style:b,children:[Wt(Ey,{tagName:"span",containerTagName:"div",className:Ds(l.container,l.agentText),disableLineBreaks:yt(a),content:e||"\u200B",onAfterParse:C,matchers:T,selection:f,keywordMatches:i,inputElement:a,inputStyle:b,boundaryRef:m,inlineSuggestionsOnlyAtEnd:!p}),Wt("br",{})]},"tab-completion")},My=t=>{var h,C,T;let{input:e,ui:n,settings:o,styleSuggestions:r,conversation:s}=t,i=Mt({input:e}),a=(i==null?void 0:i.text)||"",d=(i==null?void 0:i.source)||"",l=(h=e.html)!=null?h:In(e.text),c=a.indexOf(e.text)===0?a.slice(e.text.length):"",{showTabHint:u}=n,{isSupported:p}=s,{showTabCompletion:g,visible:f,showStyleSuggestions:m}=o;return{showTabHint:u,showStyleSuggestions:m,showTabCompletion:g&&Te(t),content:l,tabText:c,source:d,keywordMatches:(T=(C=r.list)==null?void 0:C.keywordMatches)!=null?T:[],enabled:f&&p!==!1}},jd=Iy(My)(Ay);import{Fragment as Yv,useEffect as Js,useState as ex}from"react";import{useDispatch as jc,useSelector as Z}from"react-redux";import{createAction as Gd,createAsyncThunk as qd,createSlice as Dy}from"@reduxjs/toolkit";import{Marked as Oy}from"marked";var Jo=(t,e)=>{let n=[],o=new Oy,r=s=>{s.type==="code"&&s.lang===e&&n.push(s.text)};return o.use({walkTokens:r}),o.parse(t),n};var $d={cues:[],threads:{},pending:[]},Xd=t=>{var e;return(e=t.assistants)==null?void 0:e.cues};var Jd=t=>e=>{var n,o;return(o=(n=e.assistants)==null?void 0:n.threads[t])!=null?o:null},Qo=Gd("assistants/callToAction"),Dn=qd("assistants/evaluateKnowledgeAssistant",(t,e)=>v(null,null,function*(){var l;let{threadId:n}=t,{onNewThreadId:o}=t,{deepdeskAPI:r}=e.extra,s=e.getState(),{platformVariables:i}=s.info;n||(n=(yield r.createAssistantThread({assistantCode:t.assistantCode})).id,o&&o(n)),yield r.postMessageToAssistantThread({assistantCode:t.assistantCode,threadId:n,message:t.input});let a=yield e.dispatch(Ee(S(y({skipState:!0},t),{input:{},threadId:n})));if(a.error)throw new Error(a.error.message);let d=a.payload.output[0];return{threadId:n,question:t.input,evaluationId:a.payload.evaluationId,answer:{answer:me(d.response,i!=null?i:{}),sources:(l=d.sources)!=null?l:[]}}})),pM=Gd("assistants/extractedTextSuggestions"),Ee=qd("assistants/evaluate",(t,e)=>v(null,null,function*(){var m;let{deepdeskAPI:n,dynamicThunkObject:o}=e.extra,{transcript:r,input:s={},threadId:i}=t,a=e.getState(),{platformVariables:d}=a.info,l=(m=a.conversation.current)==null?void 0:m.externalId,c;if(r==="in-memory-transcript"){if(!o.conversationQuery)throw new Error("Can't include in-memory-transcript, setConversationQuery is not defined");c=yield o.conversationQuery()}else Array.isArray(r)&&(c=r);if(t.includeMetadata){if(!a.conversation.current)throw new Error("Can't include metadata, no current conversation");let{metadata:h}=a.conversation.current;Object.assign(s,{metadata:h})}let u=yield n.evaluateAssistant(t.assistantCode,{input:s,transcript:c,externalConversationId:l,threadId:i});if(u.evaluationStatus!=="success")return e.rejectWithValue(`Assistant ${t.assistantCode} evaluation failed: ${u.evaluationStatus}`);let g=(Array.isArray(u.output)?u.output:[u.output]).map(h=>S(y({},h),{name:me(h.name,d),response:me(h.response,d)})),f=[];return g.forEach(h=>{let C=Jo(h.response,"reply"),T=C.length>0?C:[h.response];f.push(...T.map(b=>({text:b,type:"text",source:"assistant",assistantCode:h.code,sourceLabel:h.name})))}),f.length>0&&e.dispatch(Nt(f)),S(y({},u),{output:g})})),Qd=Dy({name:"assistants",initialState:$d,reducers:{resetCues(t){t.cues=[]},removeCueByCode(t,e){t.cues=t.cues.filter(n=>n.code!==e.payload.code)},removeThreadById(t,e){delete t.threads[e.payload]},receiveChunk(t,e){let{code:n,name:o,payload:r,evaluationId:s}=e.payload,i=t.cues.findIndex(a=>a.code===n);i!==-1?t.cues[i].response+=r.text:t.cues.push({code:n,name:o,evaluationId:s,response:r.text})},userNotification(t,e){let n=t.cues.filter(d=>d.code!==e.payload.code),{code:o,name:r,evaluationId:s,payload:i}=e.payload,{callToAction:a}=i;t.cues=[...n,{code:o,name:r,evaluationId:s,response:i.message,editable:i.editableMessage,callToAction:a&&{label:a.displayName,event:a.onClickEvent,value:a.eventPayload}}]}},extraReducers:t=>{t.addCase(Ee.pending,(e,n)=>{e.pending.includes(n.meta.arg.assistantCode)&&k.warn(`Assistant ${n.meta.arg.assistantCode} already evaluating`),e.pending.push(n.meta.arg.assistantCode)}).addCase(Ee.rejected,(e,n)=>{var r;k.warn((r=n.error)==null?void 0:r.message);let o=e.pending.indexOf(n.meta.arg.assistantCode);o!==-1&&e.pending.splice(o,1)}).addCase(Ee.fulfilled,(e,n)=>{let o=e.pending.indexOf(n.meta.arg.assistantCode);if(o!==-1&&e.pending.splice(o,1),n.meta.arg.skipState)return;let{evaluationId:r,output:s}=n.payload,i=s.map(l=>l.code),a=e.cues.filter(l=>!i.includes(l.code)),d=s.map(l=>S(y({},l),{evaluationId:r}));e.cues=[...a,...d]}).addCase(Dn.fulfilled,(e,n)=>{let s=n.payload,{threadId:o}=s,r=A(s,["threadId"]);e.threads[o]=[...e.threads[o]||[],r]}).addCase(V,()=>$d)}}),{removeCueByCode:Zo,resetCues:uM,removeThreadById:Zd,receiveChunk:Yd,userNotification:ec}=Qd.actions,tc=Qd.reducer;import{createAsyncThunk as nc,createSlice as _y}from"@reduxjs/toolkit";var Fy={token:null,interval:null},_s=nc("passwordlessToken/getTemporaryPasswordlessToken",(t,e)=>v(null,null,function*(){let{deepdeskAPI:n}=e.extra;return{token:yield n.requestPasswordlessToken()}})),Fs=nc("passwordlessToken/pollPasswordlessToken",(t={},e)=>{let{interval:n=1e3*60*10}=t,{dispatch:o}=e;return o(_s()),setInterval(()=>o(_s()),n)}),oc=_y({name:"passwordlessToken",initialState:Fy,reducers:{stopPollPasswordlessToken(t){t.interval&&clearInterval(t.interval),t.interval=null}},extraReducers:t=>{t.addCase(_s.fulfilled,(e,n)=>{e.token=n.payload.token}),t.addCase(Fs.fulfilled,(e,n)=>{e.interval=n.payload})}}),{stopPollPasswordlessToken:rc}=oc.actions,sc=oc.reducer;import{createSelector as Hy}from"@reduxjs/toolkit";function By(t){let e=0;for(let n=0;n<t.length;n++)e=(e<<5)-e+t.charCodeAt(n),e|=0;return e}var ic=Hy([Xd],t=>t.map(n=>({text:n.response,title:n.name,callToAction:n.callToAction,editable:n.editable,isLoading:n.isLoading,evaluationId:n.evaluationId,rule:{id:By(n.code),label:n.code,name:n.name,description:n.name}})));import{useEffect as Uy,useState as Ky}from"react";import dc from"classnames";import{jsx as ac}from"react/jsx-runtime";var Vt=()=>ac("svg",{width:"1em",height:"1em",viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",children:ac("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 lc={root:"dd-WcEru",entity:"dd-LfP8y",entityText:"dd-L-v0f",iconWrapper:"dd-9Deh1",icon:"dd-tM7E2",iconClicked:"dd-EEdDL"};import{jsx as jt,jsxs as cc}from"react/jsx-runtime";var zy=({entities:t})=>{let e=x("EntitiesWidgetList",lc),[n,o]=Ky(void 0),r=K(),s=()=>{o(void 0)},i=a=>{t&&(o(t.indexOf(a)),Se(a.text),r("entity copied",{entity:a,type:"copy"}))};return Uy(()=>{let a=setTimeout(s,500);return()=>{clearTimeout(a)}},[n]),!t||t.length===0?null:jt("div",{className:e.root,"data-testid":"widget-entities-list",children:t.map((a,d)=>cc("button",{title:a.text,className:e.entity,type:"button",onClick:()=>i(a),children:[jt("span",{className:e.entityText,children:a.text}),cc("span",{className:e.iconWrapper,children:[jt("span",{className:dc(e.icon),children:jt(Vt,{})}),jt("span",{className:dc(e.icon,n===d&&e.iconClicked),children:jt(Vt,{})})]})]},a.text))})},pc=zy;import{jsx as uc}from"react/jsx-runtime";var mc=()=>uc("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:uc("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 Jy}from"react";import{useSelector as Qy}from"react-redux";import{useRef as Wy,useState as Hs}from"react";import{useDispatch as Vy}from"react-redux";function Yo(t,e){let n=Wy(t);n.current=t;let[o,r]=Hs(void 0),[s,i]=Hs(void 0),[a,d]=Hs("idle"),l=Vy();return{error:s,state:a,data:o,call:p=>v(null,null,function*(){d("loading"),yield l(n.current(p)).unwrap().then(g=>{r(g),d("done"),e!=null&&e.onSuccess&&(e==null||e.onSuccess(g))}).catch(g=>{i(g),d("error"),e!=null&&e.onError&&(e==null||e.onError(g))})}),reset:()=>{d("idle"),r(void 0),i(void 0)}}}var gc={root:"dd-ohnXe",trigger:"dd-7i-S3",button:"dd-t53Cg",nav:"dd-qZFnm",item:"dd-FZC0F"};var fc={root:"dd-nazq3",rotation:"dd-3EHTv"};import{jsx as $y}from"react/jsx-runtime";var jy=({size:t=12})=>{let e=x("LoadingSpinner",fc);return $y("span",{"data-testid":"loading-spinner",style:{width:`${t}px`,height:`${t}px`},className:e.root})},hc=jy;import{jsx as yc}from"react/jsx-runtime";var vc=()=>yc("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 0 512 512",fill:"currentColor",children:yc("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 xc,jsxs as Gy}from"react/jsx-runtime";var Sc=t=>Gy("svg",S(y({xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 448 512","aria-labelledby":"checkTitle"},t),{children:[xc("title",{id:"checkTitle",children:"Check"}),xc("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 Bs={};X(Bs,{enUS:()=>qy,nlNL:()=>Xy});var qy={error:[{type:0,value:"Something went wrong"}]},Xy={error:[{type:0,value:"Er ging iets fout"}]};import{jsx as Be,jsxs as bc}from"react/jsx-runtime";var Zy=3e3,Yy=({assistantOptions:t})=>{let e=x("OnDemandAssistants",gc),n=R(Bs),o=Jy(),r=Yo(Ee),s=Qy(Ga),i=K(),a=s.filter(c=>c.isPinned),d=s.filter(c=>!c.isPinned),l=c=>v(null,null,function*(){clearTimeout(o.current),i("trigger on demand assistant",{assistantCode:c}),yield r.call(S(y({},t),{assistantCode:c})),o.current=setTimeout(()=>r.reset(),Zy)});return s.length===0?null:bc("div",{className:e.root,children:[a.map(({assistant:c,assistantName:u,displayName:p})=>Be("button",{type:"button",className:e.button,disabled:r.state==="loading",onClick:()=>l(c),children:p||u},c)),d.length>0&&bc($,{placement:"top-end",children:[Be($.Trigger,{className:e.trigger,disabled:r.state==="loading",children:Be(ko,{"data-testid":"trigger"})}),Be($.Content,{className:e.nav,"data-testid":"popover",children:d.map(({assistant:c,assistantName:u,displayName:p})=>Be($.Button,{className:e.item,disabled:r.state==="loading",onClick:()=>l(c),children:p||u},c))})]}),r.state==="loading"&&Be(hc,{}),r.state==="done"&&Be(Sc,{"data-testid":"trigger-done"}),r.state==="error"&&Be(al,{trigger:Be(vc,{}),children:n("error")})]})},Cc=Yy;import{useDispatch as Ev}from"react-redux";import{useRef as nv}from"react";var Tc={loadingBar:"dd-6as-V",placeHolderShimmer:"dd-TFYmA"};import{jsx as tv}from"react/jsx-runtime";var ev=({width:t})=>{let e=x("LoadingProgressBar",Tc);return tv("div",{className:e.loadingBar,style:{width:t}})},er=ev;import{jsx as $t,jsxs as ov}from"react/jsx-runtime";var tr=({title:t})=>{let e=nv(null);return qn(e),$t(M,{ref:e,children:$t(D,{children:ov(D.Content,{children:[$t(D.Title,{children:t}),$t(er,{width:"60%"}),$t(er,{width:"90%"}),$t(er,{width:"50%"})]})})})};var _n={};X(_n,{enUS:()=>rv,nlNL:()=>sv});var rv={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"}]},sv={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 Ac,useRef as xv,useState as Sv}from"react";import zs from"classnames";import{useState as lv}from"react";import{jsx as wc}from"react/jsx-runtime";var Us=t=>wc("svg",S(y({width:"16",height:"16",fill:"#000000"},t),{viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:wc("path",{fillRule:"evenodd",d:"M6.57086468,14.9173453 C6.38997052,14.9711236 6.19835748,15 6,15 L4,15 C2.8954305,15 2,14.1045695 2,13 L2,4 C2,2.8954305 2.8954305,2 4,2 L6,2 C6.68685475,2 7.29284112,2.34623869 7.65294381,2.87370078 C7.95642355,2.67736738 8.29504785,2.51351337 8.66312366,2.3818197 C9.50544052,2.08044754 10.3408482,1.9879107 10.9989281,1.99971266 C11.0150698,2.00005426 13.3487605,2.00015005 18,2 C20.7551411,2 22,6.05643086 22,12 C22,13.6824804 20.8695981,15 19,15 L15.9269768,15 C15.9359266,15.0245465 15.9451954,15.0497804 15.9547911,15.0757271 C16.007193,15.2174219 16.2391583,15.8256341 16.2970775,15.9810953 C16.4872151,16.4914441 16.6259612,16.9026411 16.7382242,17.3098712 C16.9079007,17.9253665 17,18.4798886 17,19 C17,20.4720069 16.091867,21.3862822 14.748281,21.777514 C14.1422801,21.9539723 13.6147967,22.0000922 13.0076976,22.0000008 L12.5204954,22 L12.2202699,21.6261158 C11.2556275,20.4248034 7.64562469,16.4822788 6.57086468,14.9173453 Z M8,13 C8,13.2401953 8.04443154,13.4528921 8.14171093,13.6800176 C8.40663864,14.2985643 11.914268,18.1371493 13.4599624,19.9848695 C13.7113931,19.9660111 13.9483736,19.9273712 14.1891338,19.8572655 C14.7621788,19.6904035 15,19.4509737 15,19 C15,18.6834183 14.9359344,18.2976852 14.8101464,17.8413935 C14.7161494,17.500423 14.5944107,17.1396301 14.4229225,16.6793379 C14.3689242,16.5344009 14.1358033,15.923159 14.0789589,15.7694517 C13.9489218,15.4178313 13.8632547,15.1589343 13.8046536,14.9236885 C13.5555377,13.9236468 13.8054549,13 15,13 L19,13 C19.6912225,13 20,12.6401099 20,12 C20,7.20925475 19.015127,4 18,4 C15.9322103,4 15.9322103,4 10.9655994,3.99940813 C10.5253746,3.99154158 9.91062406,4.05963657 9.33687634,4.2649175 C8.45196659,4.58152894 8,5.09776992 8,6 L8,13 Z M4,4 L4,13 L6,13 L6,4 L4,4 Z"})}));import{jsx as Ec}from"react/jsx-runtime";var kc=t=>Ec("svg",S(y({width:"16",height:"16",fill:"#000000"},t),{viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:Ec("path",{fillRule:"evenodd",d:"M7.65336736,21.1256786 C7.2933164,21.6534897 6.68712411,22 6,22 L4,22 C2.8954305,22 2,21.1045695 2,20 L2,11 C2,9.8954305 2.8954305,9 4,9 L6,9 C6.198171,9 6.38961023,9.02882212 6.57035446,9.08250314 C7.6444817,7.51807482 11.2554748,3.57449216 12.2202699,2.37298955 L12.5204954,1.99910538 L13,1.99910538 C13.6147967,1.99901314 14.1422801,2.04513312 14.748281,2.22159137 C16.091867,2.61282321 17,3.52709845 17,4.99910538 C17,5.51921677 16.9079007,6.07373891 16.7382242,6.68923415 C16.6259612,7.09646424 16.4872151,7.50766133 16.2970775,8.01801005 C16.2391583,8.17347129 16.007193,8.78168345 15.9547911,8.92337824 C15.9451954,8.94932503 15.9359266,8.9745589 15.9269768,8.99910538 L19,8.99910538 C20.8695981,8.99910538 22,10.316625 22,11.9991054 C22,17.9426745 20.7551411,21.9991054 18,21.9991054 L11.0344006,21.9985135 C10.3408482,22.0111947 9.50544052,21.9186578 8.66312366,21.6172857 C8.29521907,21.4856533 7.9567386,21.3218904 7.65336736,21.1256786 Z M8,17.9991054 C8,18.9013355 8.45196659,19.4175764 9.33687634,19.7341879 C9.91062406,19.9394688 10.5253746,20.0075638 10.963066,19.9997143 C10.9703499,19.9995545 10.9703499,19.9995545 11,19.9991054 L18,19.9991054 C19.015127,19.9991054 20,16.7898506 20,11.9991054 C20,11.3589955 19.6912225,10.9991054 19,10.9991054 L15,10.9991054 C13.8054549,10.9991054 13.5555377,10.0754586 13.8046536,9.07541689 C13.8632547,8.84017106 13.9489218,8.5812741 14.0789589,8.22965366 C14.1358033,8.07594642 14.3689242,7.46470447 14.4229225,7.31976744 C14.5944107,6.85947528 14.7161494,6.4986824 14.8101464,6.1577119 C14.9359344,5.70142019 15,5.31568707 15,4.99910538 C15,4.54813166 14.7621788,4.30870189 14.1891338,4.1418399 C13.9483736,4.07173418 13.7113931,4.0330943 13.4599624,4.01423587 C11.914268,5.86195611 8.40663864,9.70054105 8.14171093,10.3190878 C8.04443154,10.5462133 8,10.7589101 8,10.9991054 L8,17.9991054 Z M4,11 L4,20 L6,20 L6,11 L4,11 Z"})}));function Ze(t,e){var r;let n=t.cloneNode(!0);n.style.top=`${t.offsetTop}px`,n.style.left=`${t.offsetLeft}px`,n.style.position="absolute",e.split(" ").forEach(s=>{n.classList.add(s)}),n.addEventListener("animationend",()=>n.remove()),(r=t.parentElement)==null||r.appendChild(n)}var Ks={};X(Ks,{enUS:()=>iv,nlNL:()=>av});var iv={thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}]},av={thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}]};var Rc={thumbs:"dd-5F1zq",fadeup:"dd-eTmY-",fadedown:"dd-sS85z",selected:"dd-rid-f",thumbsUp:"dd-4poEf",thumbsDown:"dd-3KozS"};import{useSelector as Pc}from"react-redux";import{jsx as Gt,jsxs as cv}from"react/jsx-runtime";var dv=({assistantCode:t,assistantOutput:e,evaluationId:n,feedbackType:o,feedbackText:r})=>{let s=x("FeedbackThumbs",Rc),i=E("enableFeedbackForm"),a=Pc(xe),d=Pc(Xe(`/admin/feedback?conversationId=${a}&evaluationId=${n}&type=${o}&text=${r}&assistantCode=${t}&assistantOutput=${e}`)),l=R(Ks),c=K(),[u,p]=lv(null),g=h=>{c("Assistant response feedback",{assistantCode:t,assistantOutput:e,evaluationId:n,rating:h})},f=h=>{h.stopPropagation(),Ze(h.target,s.fadeup),p("up"),g("up")},m=h=>{h.stopPropagation(),Ze(h.target,s.fadedown),p("down"),g("down")};return cv("div",{className:s.thumbs,children:[Gt(M.Button,{title:l("thumbsUp"),onClick:f,icon:Gt(kc,{}),className:zs(s.thumbsUp,u==="up"&&s.selected),disabled:!!u}),i&&d?Gt(M.Button,{as:"a",title:l("thumbsDown"),href:d,target:"_blank",rel:"noreferrer",onClick:m,icon:Gt(Us,{}),className:zs(s.thumbsDown,u==="down"&&s.selected),disabled:!!u}):Gt(M.Button,{title:l("thumbsDown"),onClick:m,icon:Gt(Us,{}),className:zs(s.thumbsDown,u==="down"&&s.selected),disabled:!!u})]})},nr=dv;import pv from"dompurify";import{Fragment as Lc,useMemo as uv,useRef as mv,useState as gv}from"react";var Ic={root:"dd-L7b3z",popover:"dd-OQOTB",options:"dd-Y12RE",arrow:"dd-cv33T",copyIcon:"dd-6xOsH",option:"dd-9oFX4",divider:"dd-aiZf8",fadeup:"dd-Jq9pd"};import{marked as fv}from"marked";import{jsx as Fn,jsxs as or}from"react/jsx-runtime";function hv(t){return`<button type="button" data-copy-icon class=${t}><svg version="1.1" x="0px" y="0px" viewBox="0 0 115.77 122.88" width="10px" height="10px" fill="black"><g><path d="M89.62,13.96v7.73h12.19h0.01v0.02c3.85,0.01,7.34,1.57,9.86,4.1c2.5,2.51,4.06,5.98,4.07,9.82h0.02v0.02 v73.27v0.01h-0.02c-0.01,3.84-1.57,7.33-4.1,9.86c-2.51,2.5-5.98,4.06-9.82,4.07v0.02h-0.02h-61.7H40.1v-0.02 c-3.84-0.01-7.34-1.57-9.86-4.1c-2.5-2.51-4.06-5.98-4.07-9.82h-0.02v-0.02V92.51H13.96h-0.01v-0.02c-3.84-0.01-7.34-1.57-9.86-4.1 c-2.5-2.51-4.06-5.98-4.07-9.82H0v-0.02V13.96v-0.01h0.02c0.01-3.85,1.58-7.34,4.1-9.86c2.51-2.5,5.98-4.06,9.82-4.07V0h0.02h61.7 h0.01v0.02c3.85,0.01,7.34,1.57,9.86,4.1c2.5,2.51,4.06,5.98,4.07,9.82h0.02V13.96L89.62,13.96z M79.04,21.69v-7.73v-0.02h0.02 c0-0.91-0.39-1.75-1.01-2.37c-0.61-0.61-1.46-1-2.37-1v0.02h-0.01h-61.7h-0.02v-0.02c-0.91,0-1.75,0.39-2.37,1.01 c-0.61,0.61-1,1.46-1,2.37h0.02v0.01v64.59v0.02h-0.02c0,0.91,0.39,1.75,1.01,2.37c0.61,0.61,1.46,1,2.37,1v-0.02h0.01h12.19V35.65 v-0.01h0.02c0.01-3.85,1.58-7.34,4.1-9.86c2.51-2.5,5.98-4.06,9.82-4.07v-0.02h0.02H79.04L79.04,21.69z M105.18,108.92V35.65v-0.02 h0.02c0-0.91-0.39-1.75-1.01-2.37c-0.61-0.61-1.46-1-2.37-1v0.02h-0.01h-61.7h-0.02v-0.02c-0.91,0-1.75,0.39-2.37,1.01 c-0.61,0.61-1,1.46-1,2.37h0.02v0.01v73.27v0.02h-0.02c0,0.91,0.39,1.75,1.01,2.37c0.61,0.61,1.46,1,2.37,1v-0.02h0.01h61.7h0.02 v0.02c0.91,0,1.75-0.39,2.37-1.01c0.61-0.61,1-1.46,1-2.37h-0.02V108.92L105.18,108.92z"/></g></svg></button>`}function Ws(t){var n;let e=t.cloneNode(!0);return e.querySelectorAll("div,button").forEach(o=>o.remove()),e.querySelectorAll("p, h1, h2, h3, h4, h5, h6").forEach(o=>{o.after(document.createTextNode(`
|
|
7
|
+
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 jl}from"react/jsx-runtime";var Mf={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},$l=({className:t,color:e})=>jl("svg",{className:t,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:jl("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:Mf[e||"pink"]})});var Gl={root:"dd-LbeUM",text:"dd-Dpfn1",isLoggedIn:"dd-XvHAn",isLoggedOut:"dd-21y-z",icon:"dd-8rLqS",logo:"dd-slXhD",lock:"dd-ByzlR"};var vs={};X(vs,{enUS:()=>Nf,nlNL:()=>Of});var Nf={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},Of={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};import{useDispatch as Ff}from"react-redux";import{jsx as xs,jsxs as ql}from"react/jsx-runtime";var Xl=({onLogIn:t})=>{let e=R(vs),n=E("floatingMenu"),o=E("productName"),r=Ff(),s=_f(J),i=x("FloatingMenu",Gl);if(s===null||n===!1)return null;let a=()=>{s===!0?r(ge(!0)):t()};return ql("button",{type:"button",className:Df(i.root,{[i.isLoggedIn]:s,[i.isLoggedOut]:!s}),onClick:a,children:[xs("div",{className:i.text,children:e(s?"search":"signin",{productName:o})}),ql("div",{className:i.icon,children:[xs($l,{className:i.logo,color:"pink"}),s===!1&&xs(Vl,{className:i.lock})]})]})};import{useEffect as rh,useRef as sh}from"react";import{useDispatch as ih,useSelector as Kt}from"react-redux";import{useEffect as Hf}from"react";function gt(t){Hf(()=>{let e=n=>{n.isWithinRoot||t(n)};return document.body.addEventListener("mouseup",e),()=>{document.body.removeEventListener("mouseup",e)}},[t])}function ft(t){t.addEventListener("mouseup",e=>{e.isWithinRoot=!0},!0)}function Te(t){let{showMidSentenceSuggestions:e,showSuggestionsBeforePattern:n,showSuggestionsAfterPattern:o}=t.settings,{text:r,selection:s}=t.input;return s.start!==s.end?!1:s.end>=r.length?!0:e?n&&new RegExp(n).test(r.substring(s.end))||o&&new RegExp(o).test(r.substring(0,s.end))?!0:n===!1&&o===!1:!1}import{createSlice as Bf}from"@reduxjs/toolkit";var Uf={showTabHint:!1,inputHasFocus:!1,overlayCollapsed:!1,openOverlayWhenTyping:!1,overlayCollapsedUserOverwrite:!1},No=({ui:t})=>t.overlayCollapsed,Jl=Bf({name:"ui",initialState:Uf,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:Nn,setInputFocus:Oo,setOverlayCollapsed:Je,setOpenOverlayWhenTyping:Ql,setOverlayCollapsedUserOverwrite:Zl}=Jl.actions,Yl=Jl.reducer;import{useMemo as th}from"react";import{Interweave as rd}from"interweave";import{useEffect as $f,useMemo as Gf,useRef as qf,useState as Xf}from"react";import{useDispatch as Jf,useSelector as sd}from"react-redux";import{useEffect as Kf}from"react";function ed(t,e,n){Kf(()=>{let o=t.current;return o?(o.addEventListener(e,n),()=>{o.removeEventListener(e,n)}):()=>{}},[t,e,n])}var td={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 nd,jsxs as zf}from"react/jsx-runtime";var od=({title:t})=>zf("svg",{xmlns:"http://www.w3.org/2000/svg",width:"18px",height:"18px",viewBox:"0 0 24 24","aria-labelledby":"closeTitle",children:[nd("title",{id:"closeTitle",children:t}),nd("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 Ss={};X(Ss,{enUS:()=>Wf,nlNL:()=>Vf});var Wf={assistant:[{type:0,value:"Assistant"}],close:[{type:0,value:"Close"}]},Vf={assistant:[{type:0,value:"Assistent"}],close:[{type:0,value:"Sluiten"}]};import{jsx as De,jsxs as id}from"react/jsx-runtime";var Qf=["search","personal-collection-search","search-autocomplete"];function Zf(t,e,n,o={}){var s;let r="";return Qf.includes(e)?r=el(os(t,n,{stripAgentPart:!0}),(s=o.searchKeywords)!=null?s:[n]):r=os(t,n,o),o.placeholders===!0&&(r=tl(r)),r}var Yf=()=>{},eh=({selected:t,suggestion:e})=>{let n=R(Ss),o=E("inlineSuggestions"),r=sd(At),[s,i]=Xf(!1),a=E("enableSuggestionFeedback"),d=sd(h=>h.input.text),l=Jf(),c=x("TextSuggestion",td),u=qf(null),p=e.source==="assistant",g=a&&!p;$f(()=>{let h=setTimeout(()=>{l(ta({text:e.text,suggestion:e}))},500);return()=>{clearTimeout(h)}},[e]),ed(u,"click",()=>{l(re({suggestion:e,text:e.text,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"}))});let f=()=>{l(it({source:e.source,text:e.text,assistantCode:e.assistantCode}))},m=Gf(()=>Zf(e.text,e.source,r,{stripAgentPart:o,placeholders:!0,searchKeywords:e.searchKeywords}),[o,e.text,e.source,r,e.searchKeywords]);return e.source==="gpt"&&!o?null:id("div",{className:c.root,onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),children:[De(M,{ref:u,as:"button","data-testid":"suggestions-overlay-item",selected:t,onClick:Yf,children:e.source==="assistant"?id("div",{className:c.assistantContainer,children:[De(rd,{containerTagName:"div",tagName:"span",className:c.formattedTextTruncated,content:m}),De("span",{className:c.assistantBadge,children:n("assistant")})]}):De(rd,{containerTagName:"div",tagName:"span",className:c.formattedText,content:m})}),g&&s&&De("div",{className:c.actions,children:De(Io,{source:"overlay",context:d,suggestion:e})}),p&&s&&De("div",{className:c.closeIconContainer,children:De("button",{type:"button",className:c.closeIcon,onClick:f,title:n("close"),children:De(od,{title:n("close")})})})]})},ad=eh;import{jsx as oh}from"react/jsx-runtime";var nh=({suggestions:t,selectedIndex:e,reverse:n})=>th(()=>{let r=t.map((s,i)=>oh(ad,{index:i,selected:i===e,suggestion:s},`${s.text}-${s.source}`));return n?r.reverse():r},[t,e,n]),Do=nh;var ld={root:"dd-PfvRI",paper:"dd-HYlyY"};import{jsx as _o}from"react/jsx-runtime";var ah=()=>{let t=sh(null),e=x("InlineSuggestionsOverlay",ld),n=Kt(Te),o=ih(),r=Kt(J),s=Kt(Lt),i=Kt(No),a=E("showTextSuggestions"),d=Kt(st),l=Kt(cn);return gt(()=>{setTimeout(()=>{o(Je({collapse:!0,skipWhenInputFocus:!0}))})}),rh(()=>{let c=t.current;if(!c||!c.parentElement)return;c.parentElement.style.left="0px";let u=c.getBoundingClientRect();c.parentElement.style.left=`${Math.min(window.innerWidth-4-u.right,0)}px`}),i||!n||!a||d.length===0||r!==!0||s===!1?null:_o("div",{className:e.root,"data-variant":"inline",children:_o("div",{ref:t,className:e.paper,children:_o(te,{children:_o(Do,{suggestions:d,selectedIndex:l})})})})},dd=ah;import{Provider as lh}from"react-redux";import{jsx as Fo}from"react/jsx-runtime";var dh=({children:t})=>{let n=E("locale").replace("-","");return Fo(Jr.Provider,{value:n,children:t})},ch=({store:t,customStyles:e={},children:n})=>Fo(lh,{store:t,children:Fo(dh,{children:Fo(sn.Provider,{value:e,children:n})})}),_e=ch;import Es from"classnames";import{useEffect as Ch,useRef as Th,useState as wh}from"react";import{useDispatch as Eh,useSelector as Qe}from"react-redux";import{useState as ph}from"react";function cd(t,e){let[n,o]=ph(()=>{if(typeof window=="undefined")return e;try{let s=window.localStorage.getItem(t);return s?JSON.parse(s):e}catch(s){return k.error(s),e}});return[n,s=>{try{let i=s instanceof Function?s(n):s;o(i),typeof window!="undefined"&&window.localStorage.setItem(t,JSON.stringify(i))}catch(i){k.error(i)}}]}var pd=()=>/Mac/i.test(navigator.platform);import gh from"classnames";import{Fragment as fh,useCallback as Cs,useMemo as md}from"react";var bs={};X(bs,{enUS:()=>uh,nlNL:()=>mh});var uh={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"}]}]},mh={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 ud={root:"dd-uTPjX",anchor:"dd-C8lsZ",anchorButton:"dd-IoSx9"};import{jsx as Ho,jsxs as gd}from"react/jsx-runtime";var Ts=(t,e,n)=>o=>Ho("button",{className:t.anchorButton,type:"button",value:e,onClick:n,children:o},e),hh=({className:t,loginUrl:e,isEmbedded:n,onSnooze:o,onLogIn:r})=>{let s=R(bs),i=ne(),a=x("Login",ud),d=E("productName"),l=Cs(h=>{h.preventDefault(),o&&o(Number.parseInt(h.target.value,10))},[]),c=Cs(h=>{h.preventDefault(),i.send(_t,!0)},[e]),u=md(()=>h=>Ho("a",{onClick:T=>{T.preventDefault(),r()},href:e,className:a.anchor,target:"_blank",rel:"noreferrer",children:h},"login"),[e]),p=Cs(h=>Ho("button",{type:"button",className:a.anchorButton,onClick:c,children:h},"prompt"),[c]),{min:g,hour:f,day:m}=md(()=>({min:Ts(a,600,l),hour:Ts(a,3600,l),day:Ts(a,3600*12,l)}),[]);return gd("div",{className:gh(t,a.root),children:[s("loginPlease",{login:n?p:u,productName:d}),o&&gd(fh,{children:[Ho("br",{}),s("snooze",{min:g,hour:f,day:m})]})]})},Bo=hh;import{useDispatch as yh}from"react-redux";var fd={root:"dd-DoQhb",text:"dd-Jwnev"};import{jsx as hd,jsxs as xh}from"react/jsx-runtime";var vh=({title:t})=>{let e=x("SearchTrigger",fd),n=yh(),o=K();return xh("button",{type:"button",className:e.root,onClick:()=>{n(ge(!0)),o("open search",{via:"autocomplete-overlay"})},children:[hd(Bt,{}),hd("span",{className:e.text,children:t})]})},yd=vh;var ws={};X(ws,{enUS:()=>Sh,nlNL:()=>bh});var Sh={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"}]},bh={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 vd={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 q,jsxs as ht}from"react/jsx-runtime";var kh=({onLogIn:t})=>{let e=x("SuggestionsOverlay",vd),n=R(ws),o=Qe(Te),r=Qe(ea),s=Eh(),i=Th(null),a=E("searchTriggerKey"),d=E("productName"),l=Qe(No),c=Qe(J),u=Qe(Ki),p=Qe(Lt),[g,f]=wh(null),m=E("showSearch"),h=E("showTextSuggestions"),C=E("adminUrl"),T=E("isEmbedded"),b=E("suggestionsPlacement"),[w,I]=cd("dd-snooze-until-ms",0),N=l||w>Date.now(),_=Qe(st),W=Qe(cn),ce=_.filter(U=>U.source!=="gpt").length,ae=()=>{N&&I(0),s(Zl(!N))},O=U=>{let Pe=Date.now()+U*1e3;I(Pe),k.info(`Snooze until: ${new Date(Pe)}`),s(Je({collapse:!0}))};return Ch(()=>{ce===0&&f(null)},[_,ce]),gt(()=>{s(Je({collapse:!0,skipWhenInputFocus:!0}))}),c===null||p===!1?null:c===!1?ht("div",{ref:i,className:Es(e.root,{[e.isCollapsed]:N}),children:[!N&&ht("div",{className:e.triggers,children:[q("div",{style:{flex:1}}),q("div",{className:e.triggersRight,children:q(Et,{className:e.toggleButton,title:n("collapse"),onClick:ae,isCollapsed:!1})})]}),q("div",{className:e.toggleButtonWrapper,children:q(Et,{className:e.toggleButton,title:n("open",{productName:d}),onClick:ae,isCollapsed:!0})}),ht("div",{className:e.collapsible,children:[u&&ht("div",{className:e.loginError,children:[q("span",{className:e.loginErrorMessage,children:u}),q("button",{type:"button",className:e.loginErrorDismiss,onClick:()=>s(Yn()),"aria-label":n("dismissError"),children:n("dismiss")})]}),q(Bo,{loginUrl:C,isEmbedded:T,onLogIn:t,onSnooze:O})]})]}):!r||!o?null:ht("div",{ref:i,className:Es(e.root,{[e.isCollapsed]:N}),children:[!N&&ht("div",{className:e.triggers,children:[q("div",{style:{flex:1},children:m&&q("div",{style:{display:"inline-block"},onFocus:()=>{},onMouseOver:()=>f(n(pd()?"searchHintMac":"searchHintWindows",{searchTriggerKey:a.toUpperCase()})),onMouseLeave:()=>f(null),children:q(yd,{title:n("search")})})}),ht("div",{className:e.triggersRight,onFocus:()=>{},children:[q("div",{className:Es(!g&&e.hintsHidden,e.hints),children:g}),q(Et,{className:e.toggleButton,title:n("collapse"),onClick:ae,isCollapsed:!1})]})]}),q("div",{className:e.toggleButtonWrapper,children:q(Et,{className:e.toggleButton,title:n("open",{productName:d}),onClick:ae,isCollapsed:!0})}),ce>0&&h&&q("div",{className:e.collapsible,onFocus:()=>{},children:q(te,{children:q(Do,{suggestions:_,selectedIndex:W,reverse:b==="above"})})})]})},xd=kh;import Ds from"classnames";import{Interweave as Ey}from"interweave";import{useCallback as ky,useEffect as Ry,useMemo as Vd,useRef as Py}from"react";import{connect as Iy}from"react-redux";import{useEffect as Rh,useRef as Ph,useState as Ih}from"react";function Uo(t){return t.contentEditable==="true"}function Lh(t){let e=0,n=0,o=window.getSelection();if(o.rangeCount!==0){let r=o.getRangeAt(0),s=r.cloneRange();s.selectNodeContents(t),s.setEnd(r.endContainer,r.endOffset),n=s.toString().length,s.selectNodeContents(t),s.setEnd(r.startContainer,r.startOffset),e=s.toString().length}return{selectionStart:e,selectionEnd:n}}function Sd(t){let{selectionStart:e,selectionEnd:n}=Uo(t)?Lh(t):t;return[e,n]}function bd(t){let[,e]=Ih(),n=Ph(null);return n.current=Sd(t),Rh(()=>{let o=()=>{var a;let[r,s]=(a=n.current)!=null?a:[],i=Sd(t);(!i||r!==i[0]||s!==i[1])&&(n.current=i,e({}))};return t.addEventListener("keyup",o),t.addEventListener("click",o),t.addEventListener("focus",o),document.addEventListener("selectionchange",o),()=>{t.removeEventListener("keyup",o),t.removeEventListener("click",o),t.removeEventListener("focus",o),document.removeEventListener("selectionchange",o)}},[t]),n.current}function Cd(t,e){if(!e)return;let n=t,{value:o}=n,[r,s]=e,i=o.match(Xn);if(!i||i.length===0)return;let a=0;i.find(d=>{let l=o.indexOf(d,a);return r>l&&s<l+d.length?(n.selectionStart=l,n.selectionEnd=l+d.length,!0):(a=l+d.length,!1)})}import{cloneElement as Ah}from"react";var Mh=["div","span","mark","strong","b","i","u","em"];function ks(t,e,n=0){var s;let o=t[t.length-1],r=typeof o=="object"&&o!==null?(s=o.props)==null?void 0:s.tagName:void 0;if(r==="br")return t.pop(),[...t,...e,o];if(Mh.includes(r)){let i=Array.isArray(o.props.children)?o.props.children:[o.props.children];return[...t.slice(0,t.length-1),Ah(o,{children:ks(i,e,n+1)})]}return[...t,...e]}function yt(t){return t.tagName.toLowerCase()==="textarea"}var Td={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 Zh from"classnames";import{Matcher as Yh}from"interweave";import{useEffect as ey,useMemo as ty}from"react";import{useEffect as Nh,useRef as Oh,useState as Dh}from"react";function wd(t,e){let n;return[(...o)=>{window.cancelAnimationFrame(n);let r=e?e(...o):o;n=window.requestAnimationFrame(()=>{t(...r)})},()=>window.cancelAnimationFrame(n)]}function Ko(t){let e=Oh(null),[n,o]=Dh(!1);return Nh(()=>{var c;let r=!1,s=Number.parseFloat((c=window.getComputedStyle(document.body).zoom)!=null?c:"1"),[i,a]=wd((u,p)=>{let g=e.current;if(!g)return;let f=u/s,m=p/s,h=g.getBoundingClientRect(),C=f>h.x&&f<h.x+h.width&&m>h.y&&m<h.y+h.height;C&&!r?(r=!0,o(!0)):!C&&r&&(r=!1,o(!1))},({clientX:u,clientY:p})=>[u,p]),[d,l]=wd(()=>{r=!1,o(!1)});return t.addEventListener("mousemove",i),t.addEventListener("mouseleave",d),()=>{a(),l(),t.removeEventListener("mousemove",i),t.removeEventListener("mouseleave",d)}},[e]),[e,n]}function Ed(t){return t.replace(/[.*+^${}()|[\]\\]/g,"\\$&")}function zo(t){return e=>{t.forEach(n=>{typeof n=="function"?n(e):n!=null&&(n.current=e)})}}function kd(t){return t!=null}import Ad from"classnames";import{createRef as jh,useCallback as Ps,useMemo as $h,useRef as Gh,useState as qh}from"react";import{useState as _h,useLayoutEffect as Fh}from"react";var Hh=["bottom","height","left","right","top","width"],Bh=(t={},e={})=>Hh.some(n=>t[n]!==e[n]),Fe=new Map,Rd,Pd=()=>{let t=[],e=[];Fe.forEach((n,o)=>{if(o instanceof Element&&!o.isConnected){e.push(o);return}let r=o.getBoundingClientRect();Bh(r,n.rect)&&(n.rect=r,t.push(n))}),e.forEach(n=>{Fe.delete(n)}),t.forEach(n=>{n.callbacks.forEach(o=>o(n.rect))}),Rd=window.requestAnimationFrame(Pd)};function Uh(t,e){return{observe(){let n=Fe.size===0;if(Fe.has(t)){let o=Fe.get(t);o.callbacks.push(e),o.rect&&e(o.rect)}else Fe.set(t,{rect:void 0,hasRectChanged:!1,callbacks:[e]});n&&Pd()},unobserve(){let n=Fe.get(t);if(n){let o=n.callbacks.indexOf(e);o>=0&&n.callbacks.splice(o,1),n.callbacks.length||Fe.delete(t),Fe.size||cancelAnimationFrame(Rd)}}}}function Rs(t){let[e,n]=_h(null);return Fh(()=>{if(!t.current)return;let o=Uh(t.current,r=>{n(r)});return o.observe(),()=>{o.unobserve()}},[t]),e}import{useContext as Kh,useLayoutEffect as zh,useState as Wh}from"react";import{createPortal as Vh}from"react-dom";var Id={root:"dd-r-dgo"};var Ld=({children:t,parentNode:e})=>{let[n,o]=Wh(null),r=Kh(sn);return zh(()=>{let s=document.createElement("div");return ft(s),s.classList.add(Id.root),r!=null&&r.portalRootNode&&s.classList.add(r==null?void 0:r.portalRootNode),(e||document.body).appendChild(s),o(s),()=>{s.isConnected&&s.remove()}},[]),n?Vh(t,n):null};var we={ref:"dd-iz-KP",root:"dd-vEMon",positionAbove:"dd-mUCxM",positionBelow:"dd-7oZI7",positionLeft:"dd-BiWvD",positionRight:"dd-JIWea",alignStart:"dd-5ivu6",alignCenter:"dd-rnVkP",alignEnd:"dd-gZBp4"};import{jsx as Is}from"react/jsx-runtime";var Wo=(t=!1)=>{let[e,n]=qh(t),o=Ps(()=>n(!0),[]),r=Ps(()=>n(!1),[]),s=Ps(()=>n(a=>!a),[]),i=Gh(null);return{opened:e,open:o,close:r,toggle:s,triggerRef:i}};function Ls(t,e=null,n=0){if(!t)return{display:"none"};let o=e?t.top-e.top<0||t.top<e.top-n?e.top-n:t.top+t.height>e.top+e.height+n?e.top+e.height+n-t.height:t.top:t.top,r=e?t.left<e.left-n?e.left-n:t.left+t.width>e.left+e.width+n?e.left+e.width+n-t.width:t.left:t.left;return{top:o,left:r,height:t.height,width:t.width}}var zt=l=>{var c=l,{className:t,triggerRef:e,boundaryRef:n=jh(),position:o="above",align:r="center",children:s,toStyle:i=Ls,parentNode:a}=c,d=A(c,["className","triggerRef","boundaryRef","position","align","children","toStyle","parentNode"]);let u=Rs(e),p=Rs(n),g=$h(()=>i(u,p,0),[u,p]);return Is(Ld,{parentNode:a,children:Is("div",S(y({className:Ad(we.ref,{[we.positionAbove]:o==="above",[we.positionBelow]:o==="below",[we.positionLeft]:o==="left",[we.positionRight]:o==="right",[we.alignStart]:r==="start",[we.alignCenter]:r==="center",[we.alignEnd]:r==="end"}),style:g},d),{role:"dialog",children:Is("div",{className:Ad(t,we.root),children:s})}))})};import Xh from"classnames";import{forwardRef as Jh,useRef as Qh}from"react";var He={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 Md}from"react/jsx-runtime";var Vo=Jh((r,o)=>{var s=r,{className:t,children:e}=s,n=A(s,["className","children"]);let i=Qh(null),a=x("TabCompletion",He);return Md("div",S(y({ref:zo([i,o]),className:Xh(t,a.popoverContentContainer)},n),{children:Md("div",{className:a.popoverContent,children:e})}))});import{jsx as On,jsxs as ry}from"react/jsx-runtime";var ny=t=>e=>{let n=Ls(e);return"top"in n&&(n.width=t.width-(e.left-t.left)-10),n},oy=({inputElement:t,boundaryRef:e,inputStyle:n,children:o,suggestion:r})=>{let s=x("TabCompletion",He),i=Wo(),a=ty(()=>ny(t.getBoundingClientRect()),[t]),[d,l]=Ko(t);return ey(()=>{l?i.open():i.close()},[l]),ry("span",{children:[On("mark",{ref:zo([d,i.triggerRef]),className:Zh(s.matchKeyword,{[s.hover]:l}),"aria-haspopup":"dialog","aria-expanded":i.opened?"true":"false",children:o}),i.opened&&On(zt,{className:s.popover,triggerRef:i.triggerRef,boundaryRef:e,position:"below",align:"start",toStyle:a,children:On(Vo,{style:n,children:On("div",{className:s.hintText,children:r})})})]})},jo=class extends Yh{constructor(){super(...arguments);this.keywordMatches=[];this.preparedKeywordMatches=[];this.usedKeywordMatches=new Set}onBeforeParse(n,o){return o.keywordMatches&&o.keywordMatches!==this.keywordMatches&&(this.preparedKeywordMatches=o.keywordMatches.map(r=>S(y({},r),{keywordRegex:new RegExp(`\\b${Ed(r.keyword)}\\b`,"i")})),this.keywordMatches=o.keywordMatches),this.usedKeywordMatches.clear(),n}match(n){let o=this.preparedKeywordMatches.map(s=>{if(this.usedKeywordMatches.has(s))return null;let i=n.match(s.keywordRegex);if(!i)return null;let a=n.charAt(i.index-1),d=n.charAt(i.index+s.keyword.length);return a==="{"&&d==="}"?null:{index:i.index,length:i[0].length,match:i[0],matchString:i[0],suggestion:s.suggestion,preparedKeywordMatch:s,valid:!0}}).filter(kd);if(o.length===0)return null;let r=o.reduce((s,i)=>i.index<s.index?i:s);return this.usedKeywordMatches.add(r.preparedKeywordMatch),r}replaceWith(n,o){return On(oy,{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 sy}from"interweave";import iy from"classnames";import{jsx as Nd}from"react/jsx-runtime";var ay=({inputElement:t,children:e})=>{let n=x("TabCompletion",He),[o,r]=Ko(t);return Nd("mark",{ref:o,className:iy(n.matchPlaceholder,{[n.hover]:r}),children:e})},$o=class extends sy{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 Nd(ay,{inputElement:n.inputElement,children:e},`placeholder_${n.matchString}_${n.key}`)}asTag(){return"mark"}};import Os from"classnames";import{Matcher as yy}from"interweave";import{createRef as vy,forwardRef as xy,useCallback as Sy,useEffect as Kd,useRef as zd,useState as Wd}from"react";import{useDispatch as by,useSelector as Cy}from"react-redux";import{jsx as Od}from"react/jsx-runtime";var Dd=()=>Od("svg",{width:"1.3em",height:"1.3em",focusable:"false","aria-hidden":"true",viewBox:"0 0 24 24","data-testid":"InsertLinkIcon",tabIndex:-1,children:Od("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 ly,useEffect as Fd,useMemo as dy,useState as Hd}from"react";import{useDispatch as cy,useSelector as Bd}from"react-redux";import py from"lodash.debounce";var _d={root:"dd-ky-Bv",content:"dd-kV5e1"};function Go(t,e,n){var r;let o=((r=t.imageSizes)==null?void 0:r[e])||t.image||n;if(!o)return null;try{return new URL(o).toString()}catch(s){return null}}function As(t){return t.replace("https://www.","").replace("https://","")}import{jsx as vt,jsxs as Ms}from"react/jsx-runtime";var uy=3,my=t=>({image:t.image||"",text:t.text,id:t.id,title:t.title}),gy=({onSelectLink:t,onDismiss:e,placeholder:n,visitUrlText:o,linkCount:r=uy})=>{let s=x("LinkSearch",_d),[i,a]=Hd(""),d=cy(),l=Bd(Ol("url")),c=Bd(wa("URL")),u=dy(()=>c.map(my),[c]),[p,g]=Hd(u.length-1),f=E("fallbackImage"),m=b=>{let w=b.target;a(w.value)},h=(b,w)=>{b.stopPropagation(),b.preventDefault(),window.open(w,"_blank")},C=b=>{var N;let w=p-1<0?u.length-1:p-1,I=p+1===u.length?0:p+1;b.code==="Escape"&&(a(""),e()),b.code==="ArrowUp"&&g(w),b.code==="ArrowDown"&&g(I),b.code==="Enter"&&t(((N=u[p])==null?void 0:N.text)||i)},T=ly(py(b=>{d(lt({query:b,type:"URL",tags:["link-search"]}))},300),[]);return Fd(()=>{i&&T(i)},[i]),Fd(()=>()=>{d(co())},[]),Ms("div",{className:s.root,children:[vt(te,{withDivider:!0,children:(i?u:l).slice(0,r).map((b,w)=>vt(M,{selected:p===w,onClick:()=>t(b.text),"data-testid":"linksearch-suggestion",children:Ms(D,{children:[vt(D.Image,{src:Go(b,"small",f||void 0),title:b.title||b.text}),Ms(D.Content,{className:s.content,cropText:!0,children:[vt(D.Title,{children:b.title||As(b.text)}),b.title&&As(b.text)]}),vt(M.Actions,{children:vt(M.ActionButton,{label:o,onClick:I=>h(I,b.text)})})]})},b.text))}),vt(wn,{value:i,onChange:m,autoFocus:!0,placeholder:n,onKeyUp:C})]})},Ud=gy;var Ns={};X(Ns,{enUS:()=>fy,nlNL:()=>hy});var fy={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"}]},hy={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 ye,jsxs as qo}from"react/jsx-runtime";var Ty=xy((t,e)=>{let n=x("TabCompletion",He);return ye("mark",{ref:e,className:Os(n.matchSelection)},"selection-start")}),wy=({startRef:t,boundaryRef:e,inputStyle:n,inputElement:o,children:r})=>{let s=R(Ns),i=x("TabCompletion",He),a=E("addToPersonalCollection"),d=Cy(Xe("/admin/personal-collection/new")),l=zd(null),c=zd(null),[u,p]=Wd(null),g=E("insertLinkAsHtml"),f=by(),m=Wo(document.activeElement===o),[h]=Wd(()=>document.createRange());m.triggerRef.current=h,Kd(()=>()=>h.detach(),[]),Kd(()=>{let T=t.current,b=l.current;!T||!b||(h.setStart(T,0),h.setEnd(b,0))},[t.current,l.current]),gt(()=>{m.close()});let C=Sy(T=>{let b=h.toString(),w=/^http(s?):\/\//.test(T)?T:`https://${T}`,I=g?`<a href="${w}" target="_blank">${b}</a>`:`[${b}](${w})`;f(re({text:I,suggestion:{text:I,source:"search-url",type:"url"},eventMetrics:{inputType:"mouse"},replace:"selection"}))},[]);return qo("span",{children:[ye("mark",{ref:l,className:Os(i.matchSelection),"aria-haspopup":"dialog","aria-expanded":m.opened?"true":"false",children:r}),m.opened&&ye(zt,{className:i.popoverRoot,triggerRef:m.triggerRef,boundaryRef:e,position:"above",align:"start",children:qo(Vo,{style:n,ref:c,children:[qo("div",{className:Os(i.selectionOptions,{[i.selectionOptionsIsHidden]:u!==null}),children:[qo("button",{type:"button",tabIndex:u===null?-1:void 0,className:i.selectionOptionsButton,onClick:()=>p("insertLink"),children:[ye(Dd,{}),ye("span",{children:"\xA0"}),ye("span",{children:s("insertLink")})]}),a&&d&&ye("button",{type:"button",tabIndex:u===null?-1:void 0,className:i.selectionOptionsButton,onClick:()=>{let T=h.toString(),b=`${d}?text=${encodeURIComponent(T)}`;window.open(b,"_blank")},children:ye("span",{children:s("addToPersonalCollection")})})]}),u==="insertLink"&&ye(Ud,{placeholder:s("linkInputPlaceholder"),visitUrlText:s("visitUrl"),onSelectLink:C,onDismiss:()=>{p(null),m.close()}})]})})]},"selection-end")},Xo=class extends yy{constructor(){super(...arguments);this.charCount=0;this.foundIndex=0;this.startRef=null}onBeforeParse(n,o){return this.props=o,this.charCount=0,this.startRef=vy(),this.foundIndex=0,n}match(n){if(!this.props||this.props.selection===null||this.foundIndex===2)return null;let[o,r]=this.props.selection;if(o===r)return null;let s=this.foundIndex===0?o:r,i=s>=this.charCount&&s<=this.charCount+n.length?{index:s-this.charCount,length:0,match:"",valid:!0}:null;i&&this.foundIndex++;let a=this.foundIndex===1;return i&&a?this.charCount+=s-this.charCount:this.charCount+=n.length,i?y({isStart:a},i):null}replaceWith(n,o){return o.isStart?ye(Ty,{ref:this.startRef}):ye(wy,{inputElement:o.inputElement,startRef:this.startRef,boundaryRef:o.boundaryRef,inputStyle:o.inputStyle})}asTag(){return"mark"}};import{useSelector as Ly}from"react-redux";import{jsx as Wt,jsxs as Ny}from"react/jsx-runtime";var Ay=({enabled:t,content:e,tabText:n,showTabHint:o,showTabCompletion:r,showStyleSuggestions:s,keywordMatches:i,inputElement:a,source:d})=>{let l=x("TabCompletion",Td),c=E("insertLink"),u=E("addToPersonalCollection"),p=E("showMidSentenceSuggestions"),g=E("inlineSuggestions"),f=bd(a),m=Py(null),h=Ly(J);Ry(()=>{yt(a)&&f&&Cd(a,f)},[f]);let C=ky(w=>{if(!r||!n)return w;let I=[Wt("span",{className:l.resetIndent,children:"\u200B"},"u200B"),Wt("span",{"data-testid":"tab-completion",className:Ds(l.tabText,l.resetIndent),"data-source":d,children:n},"tabText")];return o&&I.push(Wt("span",{className:Ds(l.hint,l.resetIndent),children:Wt(Rr,{keyCode:"tab"},"tabHint")},"tabHint")),ks(w,I)},[r,n,o]),T=Vd(()=>{let w=[];return(c||u)&&w.push(new Xo("selection")),w.push(new $o("placeholders")),s&&w.push(new jo("keywords")),w},[g,c,u,s]),b=Vd(()=>{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||!h?null:Ny("div",{ref:w=>{w!=null&&w.parentElement&&(m.current=w==null?void 0:w.parentElement)},className:l.root,style:b,children:[Wt(Ey,{tagName:"span",containerTagName:"div",className:Ds(l.container,l.agentText),disableLineBreaks:yt(a),content:e||"\u200B",onAfterParse:C,matchers:T,selection:f,keywordMatches:i,inputElement:a,inputStyle:b,boundaryRef:m,inlineSuggestionsOnlyAtEnd:!p}),Wt("br",{})]},"tab-completion")},My=t=>{var h,C,T;let{input:e,ui:n,settings:o,styleSuggestions:r,conversation:s}=t,i=Mt({input:e}),a=(i==null?void 0:i.text)||"",d=(i==null?void 0:i.source)||"",l=(h=e.html)!=null?h:In(e.text),c=a.indexOf(e.text)===0?a.slice(e.text.length):"",{showTabHint:u}=n,{isSupported:p}=s,{showTabCompletion:g,visible:f,showStyleSuggestions:m}=o;return{showTabHint:u,showStyleSuggestions:m,showTabCompletion:g&&Te(t),content:l,tabText:c,source:d,keywordMatches:(T=(C=r.list)==null?void 0:C.keywordMatches)!=null?T:[],enabled:f&&p!==!1}},jd=Iy(My)(Ay);import{Fragment as Yv,useEffect as Js,useState as ex}from"react";import{useDispatch as jc,useSelector as Z}from"react-redux";import{createAction as Gd,createAsyncThunk as qd,createSlice as Dy}from"@reduxjs/toolkit";import{Marked as Oy}from"marked";var Jo=(t,e)=>{let n=[],o=new Oy,r=s=>{s.type==="code"&&s.lang===e&&n.push(s.text)};return o.use({walkTokens:r}),o.parse(t),n};var $d={cues:[],threads:{},pending:[]},Xd=t=>{var e;return(e=t.assistants)==null?void 0:e.cues};var Jd=t=>e=>{var n,o;return(o=(n=e.assistants)==null?void 0:n.threads[t])!=null?o:null},Qo=Gd("assistants/callToAction"),Dn=qd("assistants/evaluateKnowledgeAssistant",(t,e)=>v(null,null,function*(){var l;let{threadId:n}=t,{onNewThreadId:o}=t,{deepdeskAPI:r}=e.extra,s=e.getState(),{platformVariables:i}=s.info;n||(n=(yield r.createAssistantThread({assistantCode:t.assistantCode})).id,o&&o(n)),yield r.postMessageToAssistantThread({assistantCode:t.assistantCode,threadId:n,message:t.input});let a=yield e.dispatch(Ee(S(y({skipState:!0},t),{input:{},threadId:n})));if(a.error)throw new Error(a.error.message);let d=a.payload.output[0];return{threadId:n,question:t.input,evaluationId:a.payload.evaluationId,answer:{answer:me(d.response,i!=null?i:{}),sources:(l=d.sources)!=null?l:[]}}})),pM=Gd("assistants/extractedTextSuggestions"),Ee=qd("assistants/evaluate",(t,e)=>v(null,null,function*(){var m;let{deepdeskAPI:n,dynamicThunkObject:o}=e.extra,{transcript:r,input:s={},threadId:i}=t,a=e.getState(),{platformVariables:d}=a.info,l=(m=a.conversation.current)==null?void 0:m.externalId,c;if(r==="in-memory-transcript"){if(!o.conversationQuery)throw new Error("Can't include in-memory-transcript, setConversationQuery is not defined");c=yield o.conversationQuery()}else Array.isArray(r)&&(c=r);if(t.includeMetadata){if(!a.conversation.current)throw new Error("Can't include metadata, no current conversation");let{metadata:h}=a.conversation.current;Object.assign(s,{metadata:h})}let u=yield n.evaluateAssistant(t.assistantCode,{input:s,transcript:c,externalConversationId:l,threadId:i});if(u.evaluationStatus!=="success")return e.rejectWithValue(`Assistant ${t.assistantCode} evaluation failed: ${u.evaluationStatus}`);let g=(Array.isArray(u.output)?u.output:[u.output]).map(h=>S(y({},h),{name:me(h.name,d),response:me(h.response,d)})),f=[];return g.forEach(h=>{let C=Jo(h.response,"reply"),T=C.length>0?C:[h.response];f.push(...T.map(b=>({text:b,type:"text",source:"assistant",assistantCode:h.code,sourceLabel:h.name})))}),f.length>0&&e.dispatch(Nt(f)),S(y({},u),{output:g})})),Qd=Dy({name:"assistants",initialState:$d,reducers:{resetCues(t){t.cues=[]},removeCueByCode(t,e){t.cues=t.cues.filter(n=>n.code!==e.payload.code)},removeThreadById(t,e){delete t.threads[e.payload]},receiveChunk(t,e){let{code:n,name:o,payload:r,evaluationId:s}=e.payload,i=t.cues.findIndex(a=>a.code===n);i!==-1?t.cues[i].response+=r.text:t.cues.push({code:n,name:o,evaluationId:s,response:r.text})},userNotification(t,e){let n=t.cues.filter(d=>d.code!==e.payload.code),{code:o,name:r,evaluationId:s,payload:i}=e.payload,{callToAction:a}=i;t.cues=[...n,{code:o,name:r,evaluationId:s,response:i.message,editable:i.editableMessage,callToAction:a&&{label:a.displayName,event:a.onClickEvent,value:a.eventPayload}}]}},extraReducers:t=>{t.addCase(Ee.pending,(e,n)=>{e.pending.includes(n.meta.arg.assistantCode)&&k.warn(`Assistant ${n.meta.arg.assistantCode} already evaluating`),e.pending.push(n.meta.arg.assistantCode)}).addCase(Ee.rejected,(e,n)=>{var r;k.warn((r=n.error)==null?void 0:r.message);let o=e.pending.indexOf(n.meta.arg.assistantCode);o!==-1&&e.pending.splice(o,1)}).addCase(Ee.fulfilled,(e,n)=>{let o=e.pending.indexOf(n.meta.arg.assistantCode);if(o!==-1&&e.pending.splice(o,1),n.meta.arg.skipState)return;let{evaluationId:r,output:s}=n.payload,i=s.map(l=>l.code),a=e.cues.filter(l=>!i.includes(l.code)),d=s.map(l=>S(y({},l),{evaluationId:r}));e.cues=[...a,...d]}).addCase(Dn.fulfilled,(e,n)=>{let s=n.payload,{threadId:o}=s,r=A(s,["threadId"]);e.threads[o]=[...e.threads[o]||[],r]}).addCase(V,()=>$d)}}),{removeCueByCode:Zo,resetCues:uM,removeThreadById:Zd,receiveChunk:Yd,userNotification:ec}=Qd.actions,tc=Qd.reducer;import{createAsyncThunk as nc,createSlice as _y}from"@reduxjs/toolkit";var Fy={token:null,interval:null},_s=nc("passwordlessToken/getTemporaryPasswordlessToken",(t,e)=>v(null,null,function*(){let{deepdeskAPI:n}=e.extra;return{token:yield n.requestPasswordlessToken()}})),Fs=nc("passwordlessToken/pollPasswordlessToken",(t={},e)=>{let{interval:n=1e3*60*10}=t,{dispatch:o}=e;return o(_s()),setInterval(()=>o(_s()),n)}),oc=_y({name:"passwordlessToken",initialState:Fy,reducers:{stopPollPasswordlessToken(t){t.interval&&clearInterval(t.interval),t.interval=null}},extraReducers:t=>{t.addCase(_s.fulfilled,(e,n)=>{e.token=n.payload.token}),t.addCase(Fs.fulfilled,(e,n)=>{e.interval=n.payload})}}),{stopPollPasswordlessToken:rc}=oc.actions,sc=oc.reducer;import{createSelector as Hy}from"@reduxjs/toolkit";function By(t){let e=0;for(let n=0;n<t.length;n++)e=(e<<5)-e+t.charCodeAt(n),e|=0;return e}var ic=Hy([Xd],t=>t.map(n=>({text:n.response,title:n.name,callToAction:n.callToAction,editable:n.editable,isLoading:n.isLoading,evaluationId:n.evaluationId,rule:{id:By(n.code),label:n.code,name:n.name,description:n.name}})));import{useEffect as Uy,useState as Ky}from"react";import dc from"classnames";import{jsx as ac}from"react/jsx-runtime";var Vt=()=>ac("svg",{width:"1em",height:"1em",viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",children:ac("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 lc={root:"dd-WcEru",entity:"dd-LfP8y",entityText:"dd-L-v0f",iconWrapper:"dd-9Deh1",icon:"dd-tM7E2",iconClicked:"dd-EEdDL"};import{jsx as jt,jsxs as cc}from"react/jsx-runtime";var zy=({entities:t})=>{let e=x("EntitiesWidgetList",lc),[n,o]=Ky(void 0),r=K(),s=()=>{o(void 0)},i=a=>{t&&(o(t.indexOf(a)),Se(a.text),r("entity copied",{entity:a,type:"copy"}))};return Uy(()=>{let a=setTimeout(s,500);return()=>{clearTimeout(a)}},[n]),!t||t.length===0?null:jt("div",{className:e.root,"data-testid":"widget-entities-list",children:t.map((a,d)=>cc("button",{title:a.text,className:e.entity,type:"button",onClick:()=>i(a),children:[jt("span",{className:e.entityText,children:a.text}),cc("span",{className:e.iconWrapper,children:[jt("span",{className:dc(e.icon),children:jt(Vt,{})}),jt("span",{className:dc(e.icon,n===d&&e.iconClicked),children:jt(Vt,{})})]})]},a.text))})},pc=zy;import{jsx as uc}from"react/jsx-runtime";var mc=()=>uc("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:uc("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 Jy}from"react";import{useSelector as Qy}from"react-redux";import{useRef as Wy,useState as Hs}from"react";import{useDispatch as Vy}from"react-redux";function Yo(t,e){let n=Wy(t);n.current=t;let[o,r]=Hs(void 0),[s,i]=Hs(void 0),[a,d]=Hs("idle"),l=Vy();return{error:s,state:a,data:o,call:p=>v(null,null,function*(){d("loading"),yield l(n.current(p)).unwrap().then(g=>{r(g),d("done"),e!=null&&e.onSuccess&&(e==null||e.onSuccess(g))}).catch(g=>{i(g),d("error"),e!=null&&e.onError&&(e==null||e.onError(g))})}),reset:()=>{d("idle"),r(void 0),i(void 0)}}}var gc={root:"dd-ohnXe",trigger:"dd-7i-S3",button:"dd-t53Cg",nav:"dd-qZFnm",item:"dd-FZC0F"};var fc={root:"dd-nazq3",rotation:"dd-3EHTv"};import{jsx as $y}from"react/jsx-runtime";var jy=({size:t=12})=>{let e=x("LoadingSpinner",fc);return $y("span",{"data-testid":"loading-spinner",style:{width:`${t}px`,height:`${t}px`},className:e.root})},hc=jy;import{jsx as yc}from"react/jsx-runtime";var vc=()=>yc("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 0 512 512",fill:"currentColor",children:yc("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 xc,jsxs as Gy}from"react/jsx-runtime";var Sc=t=>Gy("svg",S(y({xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 448 512","aria-labelledby":"checkTitle"},t),{children:[xc("title",{id:"checkTitle",children:"Check"}),xc("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 Bs={};X(Bs,{enUS:()=>qy,nlNL:()=>Xy});var qy={error:[{type:0,value:"Something went wrong"}]},Xy={error:[{type:0,value:"Er ging iets fout"}]};import{jsx as Be,jsxs as bc}from"react/jsx-runtime";var Zy=3e3,Yy=({assistantOptions:t})=>{let e=x("OnDemandAssistants",gc),n=R(Bs),o=Jy(),r=Yo(Ee),s=Qy(Ga),i=K(),a=s.filter(c=>c.isPinned),d=s.filter(c=>!c.isPinned),l=c=>v(null,null,function*(){clearTimeout(o.current),i("trigger on demand assistant",{assistantCode:c}),yield r.call(S(y({},t),{assistantCode:c})),o.current=setTimeout(()=>r.reset(),Zy)});return s.length===0?null:bc("div",{className:e.root,children:[a.map(({assistant:c,assistantName:u,displayName:p})=>Be("button",{type:"button",className:e.button,disabled:r.state==="loading",onClick:()=>l(c),children:p||u},c)),d.length>0&&bc($,{placement:"top-end",children:[Be($.Trigger,{className:e.trigger,disabled:r.state==="loading",children:Be(ko,{"data-testid":"trigger"})}),Be($.Content,{className:e.nav,"data-testid":"popover",children:d.map(({assistant:c,assistantName:u,displayName:p})=>Be($.Button,{className:e.item,disabled:r.state==="loading",onClick:()=>l(c),children:p||u},c))})]}),r.state==="loading"&&Be(hc,{}),r.state==="done"&&Be(Sc,{"data-testid":"trigger-done"}),r.state==="error"&&Be(al,{trigger:Be(vc,{}),children:n("error")})]})},Cc=Yy;import{useDispatch as Ev}from"react-redux";import{useRef as nv}from"react";var Tc={loadingBar:"dd-6as-V",placeHolderShimmer:"dd-TFYmA"};import{jsx as tv}from"react/jsx-runtime";var ev=({width:t})=>{let e=x("LoadingProgressBar",Tc);return tv("div",{className:e.loadingBar,style:{width:t}})},er=ev;import{jsx as $t,jsxs as ov}from"react/jsx-runtime";var tr=({title:t})=>{let e=nv(null);return qn(e),$t(M,{ref:e,children:$t(D,{children:ov(D.Content,{children:[$t(D.Title,{children:t}),$t(er,{width:"60%"}),$t(er,{width:"90%"}),$t(er,{width:"50%"})]})})})};var _n={};X(_n,{enUS:()=>rv,nlNL:()=>sv});var rv={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"}]},sv={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 Ac,useRef as xv,useState as Sv}from"react";import zs from"classnames";import{useState as lv}from"react";import{jsx as wc}from"react/jsx-runtime";var Us=t=>wc("svg",S(y({width:"16",height:"16",fill:"#000000"},t),{viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:wc("path",{fillRule:"evenodd",d:"M6.57086468,14.9173453 C6.38997052,14.9711236 6.19835748,15 6,15 L4,15 C2.8954305,15 2,14.1045695 2,13 L2,4 C2,2.8954305 2.8954305,2 4,2 L6,2 C6.68685475,2 7.29284112,2.34623869 7.65294381,2.87370078 C7.95642355,2.67736738 8.29504785,2.51351337 8.66312366,2.3818197 C9.50544052,2.08044754 10.3408482,1.9879107 10.9989281,1.99971266 C11.0150698,2.00005426 13.3487605,2.00015005 18,2 C20.7551411,2 22,6.05643086 22,12 C22,13.6824804 20.8695981,15 19,15 L15.9269768,15 C15.9359266,15.0245465 15.9451954,15.0497804 15.9547911,15.0757271 C16.007193,15.2174219 16.2391583,15.8256341 16.2970775,15.9810953 C16.4872151,16.4914441 16.6259612,16.9026411 16.7382242,17.3098712 C16.9079007,17.9253665 17,18.4798886 17,19 C17,20.4720069 16.091867,21.3862822 14.748281,21.777514 C14.1422801,21.9539723 13.6147967,22.0000922 13.0076976,22.0000008 L12.5204954,22 L12.2202699,21.6261158 C11.2556275,20.4248034 7.64562469,16.4822788 6.57086468,14.9173453 Z M8,13 C8,13.2401953 8.04443154,13.4528921 8.14171093,13.6800176 C8.40663864,14.2985643 11.914268,18.1371493 13.4599624,19.9848695 C13.7113931,19.9660111 13.9483736,19.9273712 14.1891338,19.8572655 C14.7621788,19.6904035 15,19.4509737 15,19 C15,18.6834183 14.9359344,18.2976852 14.8101464,17.8413935 C14.7161494,17.500423 14.5944107,17.1396301 14.4229225,16.6793379 C14.3689242,16.5344009 14.1358033,15.923159 14.0789589,15.7694517 C13.9489218,15.4178313 13.8632547,15.1589343 13.8046536,14.9236885 C13.5555377,13.9236468 13.8054549,13 15,13 L19,13 C19.6912225,13 20,12.6401099 20,12 C20,7.20925475 19.015127,4 18,4 C15.9322103,4 15.9322103,4 10.9655994,3.99940813 C10.5253746,3.99154158 9.91062406,4.05963657 9.33687634,4.2649175 C8.45196659,4.58152894 8,5.09776992 8,6 L8,13 Z M4,4 L4,13 L6,13 L6,4 L4,4 Z"})}));import{jsx as Ec}from"react/jsx-runtime";var kc=t=>Ec("svg",S(y({width:"16",height:"16",fill:"#000000"},t),{viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:Ec("path",{fillRule:"evenodd",d:"M7.65336736,21.1256786 C7.2933164,21.6534897 6.68712411,22 6,22 L4,22 C2.8954305,22 2,21.1045695 2,20 L2,11 C2,9.8954305 2.8954305,9 4,9 L6,9 C6.198171,9 6.38961023,9.02882212 6.57035446,9.08250314 C7.6444817,7.51807482 11.2554748,3.57449216 12.2202699,2.37298955 L12.5204954,1.99910538 L13,1.99910538 C13.6147967,1.99901314 14.1422801,2.04513312 14.748281,2.22159137 C16.091867,2.61282321 17,3.52709845 17,4.99910538 C17,5.51921677 16.9079007,6.07373891 16.7382242,6.68923415 C16.6259612,7.09646424 16.4872151,7.50766133 16.2970775,8.01801005 C16.2391583,8.17347129 16.007193,8.78168345 15.9547911,8.92337824 C15.9451954,8.94932503 15.9359266,8.9745589 15.9269768,8.99910538 L19,8.99910538 C20.8695981,8.99910538 22,10.316625 22,11.9991054 C22,17.9426745 20.7551411,21.9991054 18,21.9991054 L11.0344006,21.9985135 C10.3408482,22.0111947 9.50544052,21.9186578 8.66312366,21.6172857 C8.29521907,21.4856533 7.9567386,21.3218904 7.65336736,21.1256786 Z M8,17.9991054 C8,18.9013355 8.45196659,19.4175764 9.33687634,19.7341879 C9.91062406,19.9394688 10.5253746,20.0075638 10.963066,19.9997143 C10.9703499,19.9995545 10.9703499,19.9995545 11,19.9991054 L18,19.9991054 C19.015127,19.9991054 20,16.7898506 20,11.9991054 C20,11.3589955 19.6912225,10.9991054 19,10.9991054 L15,10.9991054 C13.8054549,10.9991054 13.5555377,10.0754586 13.8046536,9.07541689 C13.8632547,8.84017106 13.9489218,8.5812741 14.0789589,8.22965366 C14.1358033,8.07594642 14.3689242,7.46470447 14.4229225,7.31976744 C14.5944107,6.85947528 14.7161494,6.4986824 14.8101464,6.1577119 C14.9359344,5.70142019 15,5.31568707 15,4.99910538 C15,4.54813166 14.7621788,4.30870189 14.1891338,4.1418399 C13.9483736,4.07173418 13.7113931,4.0330943 13.4599624,4.01423587 C11.914268,5.86195611 8.40663864,9.70054105 8.14171093,10.3190878 C8.04443154,10.5462133 8,10.7589101 8,10.9991054 L8,17.9991054 Z M4,11 L4,20 L6,20 L6,11 L4,11 Z"})}));function Ze(t,e){var r;let n=t.cloneNode(!0);n.style.top=`${t.offsetTop}px`,n.style.left=`${t.offsetLeft}px`,n.style.position="absolute",e.split(" ").forEach(s=>{n.classList.add(s)}),n.addEventListener("animationend",()=>n.remove()),(r=t.parentElement)==null||r.appendChild(n)}var Ks={};X(Ks,{enUS:()=>iv,nlNL:()=>av});var iv={thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}]},av={thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}]};var Rc={thumbs:"dd-5F1zq",fadeup:"dd-eTmY-",fadedown:"dd-sS85z",selected:"dd-rid-f",thumbsUp:"dd-4poEf",thumbsDown:"dd-3KozS"};import{useSelector as Pc}from"react-redux";import{jsx as Gt,jsxs as cv}from"react/jsx-runtime";var dv=({assistantCode:t,assistantOutput:e,evaluationId:n,feedbackType:o,feedbackText:r})=>{let s=x("FeedbackThumbs",Rc),i=E("enableFeedbackForm"),a=Pc(xe),d=Pc(Xe(`/admin/feedback?conversationId=${a}&evaluationId=${n}&type=${o}&text=${r}&assistantCode=${t}&assistantOutput=${e}`)),l=R(Ks),c=K(),[u,p]=lv(null),g=h=>{c("Assistant response feedback",{assistantCode:t,assistantOutput:e,evaluationId:n,rating:h})},f=h=>{h.stopPropagation(),Ze(h.target,s.fadeup),p("up"),g("up")},m=h=>{h.stopPropagation(),Ze(h.target,s.fadedown),p("down"),g("down")};return cv("div",{className:s.thumbs,children:[Gt(M.Button,{title:l("thumbsUp"),onClick:f,icon:Gt(kc,{}),className:zs(s.thumbsUp,u==="up"&&s.selected),disabled:!!u}),i&&d?Gt(M.Button,{as:"a",title:l("thumbsDown"),href:d,target:"_blank",rel:"noreferrer",onClick:m,icon:Gt(Us,{}),className:zs(s.thumbsDown,u==="down"&&s.selected),disabled:!!u}):Gt(M.Button,{title:l("thumbsDown"),onClick:m,icon:Gt(Us,{}),className:zs(s.thumbsDown,u==="down"&&s.selected),disabled:!!u})]})},nr=dv;import pv from"dompurify";import{Fragment as Lc,useMemo as uv,useRef as mv,useState as gv}from"react";var Ic={root:"dd-L7b3z",popover:"dd-OQOTB",options:"dd-Y12RE",arrow:"dd-cv33T",copyIcon:"dd-6xOsH",option:"dd-9oFX4",divider:"dd-aiZf8",fadeup:"dd-Jq9pd"};import{marked as fv}from"marked";import{jsx as Fn,jsxs as or}from"react/jsx-runtime";function hv(t){return`<button type="button" data-copy-icon class=${t}><svg version="1.1" x="0px" y="0px" viewBox="0 0 115.77 122.88" width="10px" height="10px" fill="black"><g><path d="M89.62,13.96v7.73h12.19h0.01v0.02c3.85,0.01,7.34,1.57,9.86,4.1c2.5,2.51,4.06,5.98,4.07,9.82h0.02v0.02 v73.27v0.01h-0.02c-0.01,3.84-1.57,7.33-4.1,9.86c-2.51,2.5-5.98,4.06-9.82,4.07v0.02h-0.02h-61.7H40.1v-0.02 c-3.84-0.01-7.34-1.57-9.86-4.1c-2.5-2.51-4.06-5.98-4.07-9.82h-0.02v-0.02V92.51H13.96h-0.01v-0.02c-3.84-0.01-7.34-1.57-9.86-4.1 c-2.5-2.51-4.06-5.98-4.07-9.82H0v-0.02V13.96v-0.01h0.02c0.01-3.85,1.58-7.34,4.1-9.86c2.51-2.5,5.98-4.06,9.82-4.07V0h0.02h61.7 h0.01v0.02c3.85,0.01,7.34,1.57,9.86,4.1c2.5,2.51,4.06,5.98,4.07,9.82h0.02V13.96L89.62,13.96z M79.04,21.69v-7.73v-0.02h0.02 c0-0.91-0.39-1.75-1.01-2.37c-0.61-0.61-1.46-1-2.37-1v0.02h-0.01h-61.7h-0.02v-0.02c-0.91,0-1.75,0.39-2.37,1.01 c-0.61,0.61-1,1.46-1,2.37h0.02v0.01v64.59v0.02h-0.02c0,0.91,0.39,1.75,1.01,2.37c0.61,0.61,1.46,1,2.37,1v-0.02h0.01h12.19V35.65 v-0.01h0.02c0.01-3.85,1.58-7.34,4.1-9.86c2.51-2.5,5.98-4.06,9.82-4.07v-0.02h0.02H79.04L79.04,21.69z M105.18,108.92V35.65v-0.02 h0.02c0-0.91-0.39-1.75-1.01-2.37c-0.61-0.61-1.46-1-2.37-1v0.02h-0.01h-61.7h-0.02v-0.02c-0.91,0-1.75,0.39-2.37,1.01 c-0.61,0.61-1,1.46-1,2.37h0.02v0.01v73.27v0.02h-0.02c0,0.91,0.39,1.75,1.01,2.37c0.61,0.61,1.46,1,2.37,1v-0.02h0.01h61.7h0.02 v0.02c0.91,0,1.75-0.39,2.37-1.01c0.61-0.61,1-1.46,1-2.37h-0.02V108.92L105.18,108.92z"/></g></svg></button>`}function Ws(t){var o;let e=t.cloneNode(!0);e.querySelectorAll("div,button").forEach(r=>r.remove()),e.querySelectorAll("p, h1, h2, h3, h4, h5, h6").forEach(r=>{r.after(document.createTextNode(`
|
|
8
8
|
|
|
9
|
-
`))}),e.querySelectorAll("br").forEach(
|
|
10
|
-
`))})
|
|
9
|
+
`))}),e.querySelectorAll("br").forEach(r=>{r.replaceWith(document.createTextNode(`
|
|
10
|
+
`))});let n=((o=e.textContent)!=null?o:"").replace(/\n{3,}/g,`
|
|
11
11
|
|
|
12
|
-
`).trim()}function yv(t){return t.replace(/\r\n/g,`
|
|
12
|
+
`).trim();return n=n.replace(/^```\w*\n?/,"").replace(/\n?```$/,""),n}function yv(t){return t.replace(/\r\n/g,`
|
|
13
13
|
`)}var vv=({content:t,useLabel:e,copyLabel:n,onCopy:o,onUse:r})=>{let s=x("Markdown",Ic),i=mv(null),[a,d]=gv(null),l=uv(()=>{let m=fv.parse(yv(t));return pv.sanitize(m.toString()).replaceAll("</code>",`${hv(s.copyIcon)}</code>`).replaceAll('<a href="','<a target="_blank" rel="noreferrer noopener" href="')},[t]),c=m=>{var T;let h=m.target,C=!!((T=i.current)!=null&&T.querySelector("code"));if(["A","BUTTON"].includes(h.tagName)){d(null);return}a||C&&h.tagName!=="CODE"||!C&&h!==i.current||(h.addEventListener("mouseleave",()=>d(null),{once:!0}),d(h))},u=()=>{if(!a)return;d(null);let m=a.querySelector("button");m&&(Ze(m,s.fadeup),o==null||o(Ws(a)))},p=m=>{let h=m.target;if(h.tagName==="A"){let C=h.getAttribute("href")||"";if(h.getAttribute("target")==="_blank"&&/^https?:\/\//.test(C))return;m.stopPropagation();return}"copyIcon"in h.dataset&&(Ze(h,s.fadeup),o==null||o(Ws(h.parentElement)))},g=()=>{!a||!r||(d(null),r(Ws(a)))},f=m=>{if(m===null)return;let h=m.getBoundingClientRect();h.left<0?m.style.transform=`translateX(${-h.left+2}px)`:h.right>window.innerWidth&&(m.style.transform=`translateX(${window.innerWidth-h.right-2}px)`)};return or(Lc,{children:[a&&(o||r)&&or(zt,{triggerRef:{current:a},className:s.popover,parentNode:a,children:[or("div",{className:s.options,ref:f,children:[o&&(a==null?void 0:a.tagName)==="CODE"&&Fn("button",{type:"button",className:s.option,onClick:u,children:n}),r&&or(Lc,{children:[Fn("div",{className:s.divider}),Fn("button",{type:"button",className:s.option,onClick:g,children:e})]})]}),Fn("div",{className:s.arrow})]}),Fn("div",{ref:i,"data-testid":"widget-markdown-content",className:s.root,dangerouslySetInnerHTML:{__html:l},onMouseOver:c,onClick:p})]})},xt=vv;var Vs={title:"dd-YBHrC",fadeup:"dd-cRM0K",fadedown:"dd-7D4Pq",selected:"dd-bueui",actions:"dd-9Iqn9",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 Ue,jsxs as rr}from"react/jsx-runtime";var bv=500,Cv=100,Tv=({content:t,onChange:e,onCopy:n})=>{let o=xv(null),r=x("WidgetCue",Vs);return Ac(()=>{let s=o.current;if(!s)return;s.style.setProperty("height","0px");let i=Math.min(Math.max(s.scrollHeight,Cv),bv);s.style.setProperty("height",`${i}px`)},[t]),Ue("textarea",{ref:o,className:r.editableCue,onCopy:n,onChange:e,value:t})},wv=({cue:t,onCallToAction:e,onRemove:n,onCopy:o,onUse:r})=>{let s=x("WidgetCue",Vs),i=R(_n),a=K(),d=E("hasKeyboardInput"),[l,c]=Sv(t.text),u=t.editable?l:Jo(t.text,"reply").join(`
|
|
14
14
|
`)||t.text,p=()=>{e&&e(l,t),n(t)},g=(h,C)=>{o&&o(h,t),C&&Ze(C,s.fadeup)},f=h=>{r&&r(h,t)},m=h=>{h.preventDefault(),h.stopPropagation(),n(t)};return Ac(()=>{a("Assistant response displayed",{evaluationId:t.evaluationId,assistantCode:t.rule.label,assistantOutput:t.text})},[]),rr(M,{"data-testid":"cue",children:[Ue(D,{children:rr(D.Content,{children:[t.title&&Ue(D.Title,{className:s.title,"data-testid":"widget-cue-title",children:t.rule.label.startsWith("__")?i(t.rule.label):t.title}),t.editable?Ue(Tv,{content:l,onCopy:()=>{let h=document.getSelection();h&&g(h.toString())},onChange:h=>{var C;return c((C=h.target.value)!=null?C:"")}}):Ue(xt,{content:t.text,useLabel:i("useCue"),copyLabel:i("copyCue"),onCopy:g,onUse:d?f:void 0})]})}),rr(M.ButtonsContainer,{children:[rr("div",{className:s.actions,children:[Ue(M.Button,{onClick:h=>g(u,h.target),variant:"primary",children:i("copyCue")}),t.callToAction&&Ue(M.Button,{onClick:p,variant:"primary",children:t.callToAction.label}),Ue(M.Button,{onClick:m,variant:"secondary",children:i("removeCue")})]}),Ue(nr,{evaluationId:t.evaluationId,assistantCode:t.rule.label,assistantOutput:t.text,feedbackText:t.text,feedbackType:"assistant"})]})]})},Mc=wv;import{Fragment as Rv,jsx as js}from"react/jsx-runtime";var kv=({cues:t})=>{let e=Ev(),n=ne(),o=R(_n),r=K(),s=l=>{e(Zo({code:l.rule.label})),r("Assistant response closed",{evaluationId:l.evaluationId,assistantCode:l.rule.label,assistantOutput:l.text})},i=(l,c)=>{Se(l),r("Assistant response copied",{evaluationId:c.evaluationId,assistantCode:c.rule.label,assistantOutput:c.text,copiedText:l})},a=(l,c)=>{var u;c.callToAction&&(e(Qo(c)),r("Assistant call to action",{evaluationId:c.evaluationId,assistantCode:c.rule.label,assistantOutput:c.text,eventName:c.callToAction.event,value:(u=c.callToAction.value)!=null?u:l}))},d=(l,c)=>{var u;n.send(Ae,{text:l,suggestion:{source:"assistant",assistantCode:(u=c.rule)==null?void 0:u.label,sourceText:l}}),r("Assistant response used",{evaluationId:c.evaluationId,assistantCode:c.rule.label,assistantOutput:c.text,usedText:l})};return js(Rv,{children:t.map(l=>l.isLoading?js(tr,{title:l.rule.label.startsWith("__")?o(l.rule.label):l.title},l.rule.id):js(Mc,{cue:l,onCallToAction:a,onRemove:s,onCopy:i,onUse:d},l.evaluationId))})},Nc=kv;import{Fragment as Pv,useEffect as Iv}from"react";var Oc={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 Ke,jsxs as $s}from"react/jsx-runtime";function Lv(t,e){return e.split(".").reduce((n,o)=>!n||typeof n!="object"||!(o in n)?null:n[o],t)}var Dc=({data:t,schema:e})=>{let n=x("WidgetCustomData",Oc),o=r=>{Se(r)};return Iv(()=>{k.info("Custom data",t,e)},[t]),Ke("dl",{className:n.root,children:e.map(r=>{let s=Lv(t,r.path);return $s(Pv,{children:[Ke("dt",{className:n.label,children:r.label}),Ke("dd",{className:n.value,children:r.type==="boolean"&&s?Ke("span",{className:n.isTrue,children:r.trueValue}):r.type==="boolean"&&!s?Ke("span",{className:n.isFalse,children:r.falseValue}):r.type==="array"&&Array.isArray(s)&&s.length>0?$s("button",{type:"button",onClick:()=>o(s.join(", ")),className:n.copyButton,children:[Ke("span",{className:n.copyButtonText,children:s.join(", ")}),Ke(Vt,{})]}):typeof s=="string"||typeof s=="number"?$s("button",{type:"button",onClick:()=>o(`${s}`),className:n.copyButton,children:[Ke("span",{className:n.copyButtonText,children:s}),Ke(Vt,{})]}):"-"})]},r.label)})})};import{createContext as Fv,Fragment as Hv,useContext as qs,useEffect as Bv,useRef as Bc,useState as St}from"react";import{useDispatch as Uv,useSelector as Kv}from"react-redux";var qt={};X(qt,{enUS:()=>Av,nlNL:()=>Mv});var Av={inputPlaceholder:[{type:0,value:"What is your question?"}],useCue:[{type:0,value:"Add to message"}],copyCue:[{type:0,value:"Copy"}],removeCue:[{type:0,value:"Close"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}],submitLabel:[{type:0,value:"Submit"}],resetLabel:[{type:0,value:"Reset"}],showMore:[{type:0,value:"Show "},{type:1,value:"amount"},{type:0,value:" more"}]},Mv={inputPlaceholder:[{type:0,value:"Wat is je vraag?"}],useCue:[{type:0,value:"Voeg toe aan bericht"}],copyCue:[{type:0,value:"Kopi\xEBren"}],removeCue:[{type:0,value:"Sluiten"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}],submitLabel:[{type:0,value:"Verzend"}],resetLabel:[{type:0,value:"Gesprek wissen"}],showMore:[{type:0,value:"Toon "},{type:1,value:"amount"},{type:0,value:" meer"}]};var sr={form:"dd-pleCH",formInput:"dd-pGJMY",formSubmit:"dd--gkRg",actionButton:"dd-I2NEH",resetContainer:"dd-qKIDX",sources:"dd-xf9c6",source:"dd-a-vyX",tooltip:"dd-EsgcZ",linkContent:"dd-gARDA",showMoreSources:"dd-uDGi-"};import{useRef as Dv}from"react";var _c={error:"dd-CoAuB"};var Gs={};X(Gs,{enUS:()=>Nv,nlNL:()=>Ov});var Nv={errorPrefix:[{type:0,value:"Error:"}]},Ov={errorPrefix:[{type:0,value:"Foutmelding:"}]};import{jsx as Fc,jsxs as _v}from"react/jsx-runtime";var Hc=({message:t})=>{let e=Dv(null),n=x("WidgetCardError",_c),o=R(Gs);return qn(e),Fc(M,{ref:e,children:Fc(D,{children:_v(D.Content,{className:n.error,children:[o("errorPrefix")," ",t]})})})};import{jsx as H,jsxs as ze}from"react/jsx-runtime";var zv=3,Wv=({sources:t,onClick:e})=>{let n=R(qt),o=x("WidgetKnowledgeAssistant",sr),[r,s]=St(!1),i=r?t:t.slice(0,zv);return i.length===0?null:ze("ul",{className:o.sources,children:[i.map(a=>H("li",{className:o.source,"data-testid":"knowledge-assist-source",children:ze($,{tooltip:!0,placement:"top-start",children:[H($.Trigger,{as:"a",rel:"noreferrer",target:"_blank",href:a.url,onClick:()=>e(a),children:H("span",{className:o.linkContent,children:a.name})}),a.url&&H($.Content,{className:o.tooltip,children:decodeURIComponent(a.url)})]})},a.name)),i<t&&H("button",{type:"button",className:o.showMoreSources,onClick:()=>s(!0),children:n("showMore",{amount:t.length-i.length})})]})},Vv=({title:t,description:e})=>H(M,{"data-testid":"knowledge-assist-empty-state",children:H(D,{children:ze(D.Content,{children:[H(D.Title,{children:t}),H(xt,{content:e})]})})}),jv=({innerRef:t,item:e,hasKeyboardInput:n,onCopy:o,onUse:r,onSourceClick:s})=>{var d;let i=R(qt),a=qs(ir);return ze(M,{"data-testid":"knowledge-assist-answer",ref:t,children:[H(D,{children:ze(D.Content,{children:[H(D.Title,{children:e.question}),H(xt,{content:e.answer.answer,useLabel:i("useCue"),copyLabel:i("copyCue"),onCopy:o,onUse:n?r:void 0}),H(Wv,{sources:(d=e.answer.sources)!=null?d:[],onClick:s})]})}),a.assistantCode&&ze(M.ButtonsContainer,{children:[H("div",{}),H(nr,{evaluationId:e.evaluationId,feedbackType:"assistant",assistantCode:a.assistantCode,assistantOutput:e.answer.answer,feedbackText:e.answer.answer})]})]})},ir=Fv(null),ar=({assistantCode:t,evaluateKnowledgeAssistFn:e,initialQuestion:n,children:o})=>{let[r,s]=St(null),[i,a]=St(!1),[d,l]=St(null),[c,u]=St(!!n),[p,g]=St(null),f=Uv(),m=K(),h=Yo(b=>{if(!t)throw new Error("No knowledge assistant was defined");return l(null),e({assistantCode:t,input:b,threadId:r,onNewThreadId(w){s(w)}})},{onSuccess(b){var w;m("Assistant response displayed",{evaluationId:b.evaluationId,assistantCode:t,assistantOutput:b.answer.answer,input:b.question,sources:(w=b.answer.sources)!=null?w:[]}),u(!1)},onError(b){var w;l((w=b.message)!=null?w:"Unknown error")}}),C=b=>v(null,null,function*(){a(!0),g(b),yield h.call(b),a(!1),g(null)}),T={isEnabled:!!t,assistantCode:t,isSubmitting:i,threadId:r,pendingInput:p,errorMessage:d,onSubmit:C,onReset(){r&&f(Zd(r)),l(null),s(null),t&&m("Assistant thread reset",{threadId:r!=null?r:void 0,assistantCode:t})}};return Bv(()=>{n&&T.isEnabled&&C(n)},[n]),H(ir.Provider,{value:T,children:o})},lr=()=>{let t=R(qt),e=x("WidgetKnowledgeAssistant",sr),n=qs(ir),o=Bc(null),[r,s]=St(""),i=d=>{s(d.target.value)},a=d=>{d.preventDefault(),n.onSubmit(r).then(()=>{var l;o.current&&((l=o.current)==null||l.focus(),s(""))})};return n.isEnabled?ze("form",{className:e.form,onSubmit:a,children:[H("input",{ref:o,className:e.formInput,placeholder:t("inputPlaceholder"),type:"text",disabled:n.isSubmitting,value:r,onChange:i}),H("button",{type:"submit",disabled:n.isSubmitting||r==="",className:e.formSubmit,children:t("submitLabel")})]}):null},dr=({title:t,emptyState:e})=>{var f,m;let n=R(qt),o=K(),r=x("WidgetKnowledgeAssistant",sr),s=Bc(null),i=qs(ir),a=(m=Kv(Jd((f=i.threadId)!=null?f:-1)))!=null?m:[],d=E("hasKeyboardInput"),l=ne(),c=(h,C)=>{Se(h),i.assistantCode&&o("Assistant response copied",{assistantCode:i.assistantCode,assistantOutput:h,copiedText:h,evaluationId:C.evaluationId})},u=(h,C)=>{i.assistantCode&&o("Assistant source clicked",{evaluationId:C.evaluationId,assistantCode:i.assistantCode,source:h})},p=h=>{h.preventDefault(),i.onReset()},g=(h,C)=>{l.send(Ae,{text:h,suggestion:{source:"assistant",sourceText:h}}),i.assistantCode&&o("Assistant response used",{assistantCode:i.assistantCode,evaluationId:C.evaluationId,assistantOutput:C.answer.answer,usedText:h})};return!i.isEnabled||(a==null?void 0:a.length)===0&&!i.isSubmitting&&!e&&!i.errorMessage?null:ze(Hv,{children:[H(Ie,{type:"knowledge",title:t,"data-testid":"knowledge",children:ze(te,{withDivider:!0,children:[e&&a.length===0&&!i.pendingInput&&H(Vv,y({},e)),a.map((h,C)=>H(jv,{innerRef:C===a.length-1?s:void 0,item:h,hasKeyboardInput:d,onCopy:T=>c(T,h),onUse:T=>g(T,h),onSourceClick:T=>u(T,h)},`${h.question}_${h.answer}_${C}`)),i.pendingInput&&H(tr,{title:i.pendingInput}),i.errorMessage&&H(Hc,{message:i.errorMessage})]})}),a.length>0&&H("div",{className:r.resetContainer,children:H(M.Button,{disabled:i.threadId===null||i.isSubmitting,onClick:p,children:n("resetLabel")})})]})};import{useCallback as Gv}from"react";var $v=/(https?:\/\/[^\s]+)/,Kc=t=>t.split(" ").find(e=>$v.test(e));import{jsx as Xt,jsxs as cr}from"react/jsx-runtime";var qv=({suggestion:t,lines:e,onUse:n})=>{var u;let o=t.text||t.url||t.message,r=Kc(o),s=R(Ln),i=E("showImages"),a=E("fallbackImage"),d=E("hasKeyboardInput"),l=p=>{p.preventDefault(),p.stopPropagation(),d&&n(o)},c=Gv(p=>{window.open(r,"_blank"),p.stopPropagation(),p.preventDefault()},[r]);return cr(M,{onClick:d?l:void 0,"data-testid":"edit-suggestion",children:[cr(D,{children:[i&&t.image&&Xt(D.Image,{src:Go(t,"small",a||void 0),title:t.title}),cr(D.Content,{children:[t.title&&Xt(D.Title,{"data-testid":"widget-suggestion-title",children:t.title}),t.searchKeywords&&((u=t.searchKeywords)==null?void 0:u.length)>0&&Xt(M.Labels,{labels:t.searchKeywords}),Xt(D.Content,{cropText:e==="single",lineClamp:e==="multiple",children:o})]})]}),cr(M.Actions,{children:[r&&Xt(M.ActionButton,{onClick:c,label:s("visitUrl")}),d&&Xt(M.ActionButton,{primary:!0,onClick:l,label:s("useSuggestion")})]})]})},zc=qv;import{Fragment as Jv,jsx as Wc}from"react/jsx-runtime";var Xv=({lines:t,suggestions:e})=>{let n=ne(),o=(r,s)=>{n.send(Ae,{text:r,suggestion:S(y({},s),{source:s.source,sourceText:s.text})})};return Wc(Jv,{children:e.map(r=>Wc(zc,{suggestion:r,lines:t,onUse:s=>o(s,r)},r.text||r.url||r.message))})},Vc=Xv;var Hn={};X(Hn,{enUS:()=>Qv,nlNL:()=>Zv});var Qv={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"}]},Zv={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 Jt={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 P,jsxs as Bn}from"react/jsx-runtime";var $c=(t,e)=>{let n=Z(J);Js(()=>n?e.every(o=>!!o)?t():()=>{}:()=>{},[...e,n])},tx=({onLogIn:t})=>{let e=x("Widget",Jt),n=E("isEmbedded"),o=E("adminUrl");return P("div",{className:e.loginText,children:P("div",{children:P(Bo,{isEmbedded:n,loginUrl:o,onLogIn:t})})},"login")},Xs=({text:t})=>{let e=x("Widget",Jt);return P("div",{className:e.stateText,children:P("div",{children:P("p",{children:t})})},"notification")},nx=()=>{let t=R(Hn),e=jc(),n=x("Widget",Jt),o=E("showSearch"),r=E("isEmbedded"),s=Z(Xe("/admin/")),i=ne(),a=E("productName"),d=K();return $c(()=>{if(r)return e(Fs()),()=>{e(rc())}},[e,r]),!o&&!s?null:Bn("div",{className:n.shortcutList,children:[o&&P(M.Button,{"data-testid":"shortcut-search","aria-label":t("linkSearch"),className:n.shortcut,icon:P(Bt,{}),onClick:()=>{i.send("ShowCommandPalette",{isOpen:!0}),d("open search",{via:"widget-shortcut"})},children:t("linkSearch")}),s&&P(M.Button,{as:"a",target:"_blank",icon:P(mc,{}),href:s,"data-testid":"shortcut-studio-login","aria-label":t("linkStudioLogin",{productName:a}),className:n.shortcut,rel:"noreferrer",onClick:()=>{d("open my deepdesk",{via:"widget-shortcut"})},children:t("linkStudioLogin",{productName:a})})]})},ox=({title:t,content:e})=>{let n=R(Hn),[o,r]=ex(!0);return o?P(Ie,{"data-testid":"custom-data-banner",type:"custom-data-banner",title:t,children:P(te,{withDivider:!0,children:Bn(M,{children:[P(D,{children:P(D.Content,{children:P(xt,{content:e})})}),P(M.ButtonsContainer,{children:P(M.Button,{onClick:()=>r(!1),children:n("close")})})]})})}):null},rx=()=>{let t=jc(),e=Z(Rn),n=Z(Xa),o=Z(ic),r=Z(ma),s=Z(Eo),i=Z(Lo),a=Z(ct),d=Z(xe);return Js(()=>{!!r&&!n&&k.warn("Custom data provided, but no schema.")},[r,n]),$c(()=>{e.forEach(({type:l})=>{l==="entities"?t(fe()):Jn.includes(l)||t(he(l))})},[t,d,a]),Js(()=>{o.length>0&&!e.some(l=>l.type==="cues")&&k.warn("Received cues, but cues are not configured in widget.")},[e,o]),P(Yv,{children:e.map(({type:l,title:c,amount:u,lines:p,schema:g,property:f})=>{var m,h;switch(l){case"entities":return s&&s.length>0&&P(Ie,{type:l,title:c,"data-testid":`type-${l}`,children:P(pc,{entities:s})},l);case"cues":return o&&o.length>0&&P(Ie,{type:l,title:c,"data-testid":`type-${l}`,children:P(te,{withDivider:!0,children:P(Nc,{cues:o})})},l);case"custom-data-banner":return r&&f&&r[f]&&P(ox,{title:c,content:String(r[f])},l);case"custom-data":return r&&g&&P(Ie,{type:l,title:c,"data-testid":`type-${l}`,children:P(te,{withDivider:!0,children:P(Dc,{data:r,schema:g})})},l);default:return((h=(m=i[l])==null?void 0:m.suggestions)==null?void 0:h.length)>0&&P(Ie,{type:l,title:c,"data-testid":`type-${l}`,children:P(te,{withDivider:!0,children:P(Vc,{lines:p,contentType:l,suggestions:i[l].suggestions.slice(0,u)||[]})})},l)}})})},Qs=({children:t})=>{let e=x("Widget",Jt);return P("div",{className:e.footer,children:t})},Zs=({children:t})=>{let e=x("Widget",Jt);return P("div",{className:e.root,"data-testid":"widget",children:t})},sx=({onLogIn:t,knowledgeAssistOptions:e={},assistantOptions:n={transcript:"in-memory-transcript"}})=>{let o=R(Hn),r=Z(Lt),s=Z(J),i=Z(Ji),a=Z(ct),d=Z(qa("knowledge-assist")),l=Z(Ja);return r===!1?P(Xs,{text:o("notSupported")}):s===!1?P(tx,{onLogIn:t}):s===null?P(Xs,{text:o("waiting")}):!i||!a?P(Xs,{text:o("waitingForConversation")}):P(Zs,{children:Bn(ar,{initialQuestion:e.initialQuestion,assistantCode:l!=null?l:void 0,evaluateKnowledgeAssistFn:Dn,children:[Bn(an,{children:[P(nx,{}),P(rx,{}),d&&P(dr,{title:d.title,emptyState:e.emptyState})]}),Bn(Qs,{children:[d&&P(lr,{}),P(Cc,{assistantOptions:n})]})]})})},Gc=sx;function Kn(t){let e=new Range;return e.selectNodeContents(t),e}function qc(t,e,n){try{return bt(t,e,n),!0}catch(o){return!1}}function pr(t){return"tagName"in t&&(t.tagName==="DIV"||t.tagName==="P")}function ur(t){return"tagName"in t&&t.tagName==="BR"}var Un=/[\u200B-\u200D\uFEFF]/g;function bt(t,e,n){let o=new Range;if(t.firstChild===null&&e===0&&n===0)return o.selectNodeContents(t),o;let r=0,s=!1;function i(d,l){let c=-1,u=/[\u200B-\u200D\uFEFF]/;if(!u.test(d))return l;for(let p=0;p<=d.length;p++)if(u.test(d[p])||c++,c===l)return p;throw new Error("Offset out of range")}function a(d){switch(d.nodeType){case Node.TEXT_NODE:{let l=d.textContent,c=l.replace(Un,""),u=r+c.length,p=e>=r&&e<=u,g=n>=r&&n<=u;if(p){let f=i(l,e-r);f===0&&!g?o.setStartBefore(d):o.setStart(d,f)}g&&(o.setEnd(d,i(l,n-r)),s=!0),r=u;break}case Node.ELEMENT_NODE:{if(ur(d)&&(r===e&&o.setStartBefore(d),r++,r===n)){o.setEndAfter(d),s=!0;return}for(let c=0;c<d.childNodes.length&&(a(d.childNodes[c]),!s);c++);let l=d.lastChild;pr(d)&&l&&!pr(l)&&!ur(l)&&r++;break}default:break}}if(a(t),o.startContainer===document)throw new Error("Offsets out of bound");return o}function mr(t,e){if(!t.contains(e.startContainer)||!t.contains(e.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:o,endContainer:r,endOffset:s,collapsed:i}=e,a,d,l=0;function c(u){let p=u===t,g=u===n,f=u===r;switch(u.nodeType){case Node.TEXT_NODE:{let m=u.textContent;g&&(a=l+m.substring(0,o).replace(Un,"").length),f&&(d=l+m.substring(0,s).replace(Un,"").length),l+=m.replace(Un,"").length;break}case Node.ELEMENT_NODE:{if(ur(u)&&u.nextSibling){l++;break}!p&&pr(u)&&u.previousSibling&&l++;for(let m=0;m<u.childNodes.length;m++){let h=g&&m===o,C=f&&m===s;if(h&&(a=l),C&&(d=l),d!==void 0||((!h||!i)&&c(u.childNodes[m]),f&&m===s-1&&(d=l),d!==void 0))break}f&&(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 gr(t,e){if(!t.contains(e.startContainer)||!t.contains(e.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:o,endContainer:r,endOffset:s,collapsed:i}=e,a=0,d="";function l(c){let u=c===t,p=c===n,g=c===r;switch(p&&(a=1),c.nodeType){case Node.TEXT_NODE:{if(a!==1)return;let f=p?o:0,m=g?s:void 0;d+=c.textContent.replace(Un,"").substring(f,m);break}case Node.ELEMENT_NODE:{if(!i&&a===1&&ur(c)&&c.nextSibling){d+=`
|
|
15
15
|
`;break}!u&&!i&&a===1&&pr(c)&&c.previousSibling&&(d+=`
|
|
16
|
-
`);let f=p?o:0,m=g?Math.min(s,c.childNodes.length):c.childNodes.length;for(let h=f;h<m&&(l(c.childNodes[h]),a!==2);h++);break}default:break}g&&(a=2)}return l(t),d}var Xc=(i=>(i.CUT="Cut",i.BACKSPACE="Backspace",i.DELETE="Delete",i.ERASEEOF="EraseEof",i.UNDO="Undo",i.CLEAR="Clear",i))(Xc||{}),Ye=class{constructor(e){this.element=e;this.isFocused=!1;this.isActive=!0;this.isDisposed=!1;this.eventListeners={};this.disposeHandlers=[];this.cachedText="";this.cachedCaretPosition=null;this.cachedSelection={start:0,end:0};this.cachedHTML="";this.isSubmitting=!1;this.isPossibleClearInputAction=!1;this.cachedText=this.getText(),this.cachedHTML=this.getHTML(),this.cachedSelection=this.getSelection(),this.listen()}addEventListener(e,n){let o=r=>{n(r)};this.element.addEventListener(e,o),this.disposeHandlers.push(()=>{this.element.removeEventListener(e,o)})}removeEventListener(e,n){this.element.removeEventListener(e,n)}handleInteraction(){let e=this.getText(),n=this.getHTML(),o=this.getSelection(),r=this.cachedCaretPosition===null;if(!this.isActive||(e===""&&this.cachedText!==""&&!this.isPossibleClearInputAction&&this.emit("submit"),e!==this.cachedText?(this.cachedText=e,this.cachedHTML=n,r=!0,this.emit("change",{plainText:e,rawHTML:n})):n!==null&&n!==this.cachedHTML&&(this.cachedHTML=n,r=!0,this.emit("change",{plainText:e,rawHTML:n})),(o.start!==this.cachedSelection.start||o.end!==this.cachedSelection.end)&&(this.cachedSelection=o,r=!0,this.emit("selection",o)),!r))return;let s=this.getCaretPosition();$e(s,this.cachedCaretPosition)||(this.cachedCaretPosition=s,this.emit("caretposition",s))}handleClick(){this.handleInteraction()}handleFocus(){let e=!this.isFocused;this.isFocused=!0,e&&this.emit("focus"),this.handleInteraction()}handleBlur(){this.isPossibleClearInputAction=!1;let e=this.isFocused;this.isFocused=!1,e&&this.emit("blur")}handleKeyDown(e){let{key:n,ctrlKey:o,metaKey:r}=e;this.isPossibleClearInputAction=Object.values(Xc).includes(n)||n.toLowerCase()==="z"&&(o||r),this.emit("keydown",e)}handleKeyUp(e){this.handleInteraction(),this.emit("keyup",e)}handleCut(){this.isPossibleClearInputAction=!0,this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(e){var o,r;let n=((o=e.clipboardData)==null?void 0:o.getData("text"))||((r=e.clipboardData)==null?void 0:r.getData("text/plain"))||"";this.emit("paste",{pastedText:n,selectionText:this.getSelectedText()})}listen(){this.addEventListener("keydown",n=>this.handleKeyDown(n)),this.addEventListener("keyup",n=>this.handleKeyUp(n)),this.addEventListener("input",()=>this.handleInteraction()),this.addEventListener("change",()=>this.handleInteraction()),this.addEventListener("focus",()=>this.handleFocus()),this.addEventListener("blur",()=>this.handleBlur()),this.addEventListener("cut",()=>this.handleCut()),this.addEventListener("paste",n=>this.handlePaste(n)),this.addEventListener("click",()=>this.handleInteraction()),document.activeElement===this.element&&(this.isFocused=!0);let e=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});e.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{e.disconnect()})}focus(){this.element.focus()}emit(e,...n){this.isDisposed||this.eventListeners[e]&&this.eventListeners[e].forEach(o=>{o(...n)})}on(e,n){this.isDisposed||(this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(n))}off(e,n){if(!this.eventListeners[e])return;let o=this.eventListeners[e].indexOf(n);o!==-1&&this.eventListeners[e].splice(o,1)}activate(){let e=this.isActive===!1;this.isActive=!0,e&&this.handleInteraction()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(e=>e()),this.eventListeners={},this.isDisposed=!0}};function Jc(t){return t.top!==0||t.left!==0||t.height!==0||t.width!==0}var Qt=class extends Ye{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),gr(this.element,n)}getHTML(){return this.element.innerHTML||""}getRange(){let n=this.getRootNode();if(n.activeElement!==this.element)return null;let o="getSelection"in n?n.getSelection():window.getSelection();if(!o)return null;let r=o.rangeCount>0?o.getRangeAt(0):null;if(!r)return null;let s=this.element.ownerDocument.createRange();return s.setStart(r==null?void 0:r.startContainer,r==null?void 0:r.startOffset),s.setEnd(r==null?void 0:r.endContainer,r==null?void 0:r.endOffset),!s||!this.element.contains(s.startContainer)||!this.element.contains(s.endContainer)?null:s}getCaretPosition(){let n=this.getRange();if(!n||!n.collapsed||!("getBoundingClientRect"in n))return null;let o=n.getBoundingClientRect();return!Jc(o)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),o=n.getBoundingClientRect(),n.deleteContents(),!Jc(o))?null:{top:o.top+o.height,left:o.left}}getSelection(){let n=this.getRange();if(n)return mr(this.element,n);let o=this.lastKnownSelection;if(o&&qc(this.element,o.start,o.end))return o;let r=Kn(this.element);return r.collapse(!1),mr(this.element,r)}getSelectedText(){let{start:n,end:o}=this.getSelection();return gr(this.element,bt(this.element,n,o))}listen(){super.listen();let n=new MutationObserver(s=>{var i,a;s.length===2&&s[0].addedNodes.length===1&&((i=s[0].addedNodes[0])==null?void 0:i.textContent)==="\u2060"&&((a=s[1].removedNodes[0])==null?void 0:a.textContent)==="\u2060"||setTimeout(()=>{this.handleInteraction()},0)});n.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0}),this.disposeHandlers.push(()=>n.disconnect());let o=this.element.isContentEditable,r=new MutationObserver(()=>{this.element.isContentEditable!==o&&(o=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});r.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>r.disconnect())}};var ix=["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 Qc(t,e){let n="mozInnerScreenX"in window,o=document.createElement("div");o.id="input-textarea-caret-position-mirror-div";let r=o.style,s=window.getComputedStyle(t),i=t.ownerDocument.body;r.whiteSpace="pre-wrap",r.wordWrap="break-word",r.position="absolute",r.visibility="hidden",ix.forEach(c=>{r[c]=s[c]}),n?t.scrollHeight>Number.parseInt(s.height)&&(r.overflowY="scroll"):r.overflow="hidden",o.textContent=t.value.substring(0,e);let a=document.createElement("span");a.textContent=t.value.substring(e)||".",o.appendChild(a),i.appendChild(o);let d=t.getBoundingClientRect(),l={top:d.top-t.scrollTop+a.offsetTop+Number.parseInt(s.borderTopWidth)+a.offsetHeight,left:d.left-t.scrollLeft+a.offsetLeft+Number.parseInt(s.borderLeftWidth)};return i.removeChild(o),l}var Zt=class extends Ye{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 Qc(this.element,this.element.selectionEnd)}listen(){super.listen();let n=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var s;return(s=n==null?void 0:n.get)==null?void 0:s.call(this.element)},set:s=>{var i;(i=n==null?void 0:n.set)==null||i.call(this.element,s),this.handleInteraction()}}),this.addEventListener("scroll",()=>{this.emit("caretposition",this.getCaretPosition())});let o=this.element.disabled,r=new MutationObserver(()=>{this.element.disabled!==o&&(o=this.element.disabled,this.emit(o?"disabled":"enabled"))});r.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>r.disconnect())}};function Zc(t,e,n){let o=`deepdesk-iframe-${t}`,r=document.getElementById(o);if(r)return r;let s=document.createElement("iframe"),i=new URL(e);return Object.entries(n).forEach(([a,d])=>{i.searchParams.append(a,d)}),s.style.position="absolute",s.style.left="-999em",s.style.width="0px",s.style.height="0px",s.tabIndex=-1,s.id=o,s.title=`iframe-${t}`,s.src=i.toString(),window.document.body.appendChild(s),s}function ax(t){if(typeof t!="string")return t;try{return JSON.parse(t)}catch(e){return t}}var Ys=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()}},ei=class{constructor(e,n,o){this.name=e;this.targetOrigin=n;this.options=o;this.disposeHandlers=[];this.iframe=Zc(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()}},ti=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 ei(e,this.deepdeskUrl,{debug:!0}):new Ys(e),o=r=>{var i,a;if(r.origin!==this.deepdeskUrl)return;let s=ax(r.data);typeof s!="object"||s.type!=="event"||s.channel!==e||(k.info("Received broadcast event",this.externalId,r),(a=(i=this.eventMap)[s.name])==null||a.call(i,s.payload))};return n.onMessage(o),n}send(e,n,o){var i,a;k.info("Broadcast event",{externalId:this.externalId,name:e,payload:n});let r={type:"event",name:e,payload:n};o!==!1&&((a=(i=this.eventMap)[e])==null||a.call(i,n));let s=this.externalId==="deepdesk-general"?this.defaultChannel:this.channel;s==null||s.postMessage(S(y({},r),{channel:this.externalId}))}cleanup(e=!1){var n,o;(n=this.channel)==null||n.close(),this.channel=void 0,e&&((o=this.defaultChannel)==null||o.close(),this.defaultChannel=void 0)}},Yc=ti;function lx(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)=>S(y({},e),{[lx(n)]:B(t[n])}),{}):t}function dx(t){return t.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}function Y(t){return Array.isArray(t)?t.map(Y):typeof t=="object"&&t!==null?Object.keys(t).reduce((e,n)=>S(y({},e),{[dx(n)]:Y(t[n])}),{}):t}var Yt=class extends Error{constructor(n,o){super(n);this.body=o;this.name="CustomError"}};var ni=t=>new Promise(e=>{setTimeout(e,t)});var en=class extends Yt{constructor(){super(...arguments);this.name="ClientError"}},ri=class extends Yt{constructor(){super(...arguments);this.name="ServerError"}},oi=new Map;function cx(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 et=class et{constructor(e="",n={}){this.baseUrl=e;this.options=n;this.latestRequestByUrl={};var o;this.fetch=(o=n.fetch)!=null?o:window.fetch.bind(window)}patchFetch(e){this.fetch=e(this.fetch)}setCsrfToken(e){this.csrfToken=e}request(e,n={}){return new Promise((o,r)=>{let s={isAborted:!1,reject:r},i=`${this.baseUrl}${e}`,a=this.fetch,d=n.method===void 0||n.method.toLowerCase()==="get",N=n,{useCache:l=!1,abortLatest:c=!1,attempts:u=1,retryDelay:p=500,refreshTokenOn401:g=!0,retryOnError:f=_=>_ instanceof TypeError,retryOnResponse:m=_=>_.status>=500,version:h=null}=N,C=A(N,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]);if(l){if(!d)throw new Error(`Can't use 'useCache' for ${n.method}`);if(oi.has(i)){o(oi.get(i));return}}let T=S(y({credentials:"include"},C),{headers:y({Accept:"application/json","Content-Type":"application/json"},C.headers)});!d&&this.csrfToken&&(T.headers=S(y({},T.headers),{"X-CSRFToken":this.csrfToken})),typeof h=="string"&&(T.headers=S(y({},T.headers),{"X-Deepdesk-API-Version":h}));let b=u,w=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[i]&&c&&(this.latestRequestByUrl[i].isAborted=!0,this.latestRequestByUrl[i].reject(new Error("Aborted"))),this.latestRequestByUrl[i]=s;let I=()=>v(this,null,function*(){return b--,a(i,T).then(_=>v(this,null,function*(){return m(_)&&!s.isAborted&&b>0?(yield ni(p),I()):_.status===401&&g===!0&&w===!1?(w=!0,yield this.refreshToken(),I()):_})).catch(_=>v(this,null,function*(){if(f(_)&&!s.isAborted&&b>0)return yield ni(p),I();throw _}))});I().then(_=>v(this,null,function*(){let W=yield cx(_);if(delete this.latestRequestByUrl[i],_.status>=500){r(new ri("Server Error",W));return}if(_.status===401){r(new en("Unauthorized",W));return}if(_.status===403){r(new en("Forbidden",W));return}if(_.status===404){r(new en("Not Found",W));return}if(_.status>=400){r(new en("Bad Request",W));return}l&&oi.set(i,W),o(W)})).catch(_=>{r(_)})})}validateToken(){return v(this,null,function*(){let{has_valid_access_token:e,is_logged_in:n}=yield this.get("/apis/admin/session/validate/");if(!e)try{yield this.refreshToken();let{is_logged_in:o}=yield this.get("/apis/admin/session/validate/");return o}catch(o){return!1}return n})}refreshToken(){return et.refreshingToken||(et.refreshingToken=this.get("/apis/admin/session/refresh/",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{et.refreshingToken=null},1e3*60)})),et.refreshingToken}get(e,n){return this.request(e,n)}post(e,n,o){return this.request(e,y({method:"POST",body:JSON.stringify(n)},o))}patch(e,n,o){return this.request(e,y({method:"PATCH",body:JSON.stringify(n)},o))}put(e,n,o){return this.request(e,y({method:"PUT",body:JSON.stringify(n)},o))}delete(e,n){return this.request(e,y({method:"DELETE"},n))}};et.refreshingToken=null;var tn=et;var ep;(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={}))})(ep||(ep={}));function si(t){return S(y({},B(t)),{metadata:t.metadata})}var Ct=class Ct{constructor(e,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new tn(e,{fetch:n.fetch}),this.client.patchFetch(o=>(r,s)=>v(this,null,function*(){let i=yield o(r,s);return this.handleDeepdeskVersionHeaders(i),i}))}preflight(){return v(this,null,function*(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let e=yield this.getCsrfToken();this.client.setCsrfToken(e)}return this.options.token?(Ct.exchangeTokenPromise||(Ct.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),Ct.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",S(y({chat_start_time:new Date().toISOString()},Y(e)),{metadata:(o=e.metadata)!=null?o:{}}));return si(n)})}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/",Y(e))})}patchMe(e){return v(this,null,function*(){yield this.preflight();let n=yield this.client.patch("/apis/admin/session/me/",Y(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:r=1,retryDelay:s=1e3}=n,i=yield this.client.get(`/api/v2/conversations/by_external_id/${e}`,{attempts:r,retryDelay:s,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"});return k.info(`Successfully retrieved conversation ${i.id} for session ${e}`),si(i)})}isConversationSupported(o){return v(this,arguments,function*(e,n={}){k.info(`Check if conversation for session ${e} is supported`);let{attempts:r=1,retryDelay:s=1e3}=n;return(yield this.client.get(`/api/v2/conversations/by_external_id/${e}/has_active_profile`,{attempts:r,retryDelay:s,retryOnResponse:a=>a.status===404||a.status>=500})).has_active_profile})}updateConversation(e,n){return v(this,null,function*(){var s;yield this.preflight();let o=Y(n);n.metadata&&(o.metadata=(s=n.metadata)!=null?s:{});let r=yield this.client.put(`/api/v2/conversations/${e}`,o);return si(r)})}postMessages(e,n){return v(this,null,function*(){yield this.preflight(),yield this.client.post(`/api/v2/conversations/${e}/messages`,n.map(o=>S(y({},Y(o)),{metadata:o.metadata})))})}sendEvent(e,n){return v(this,null,function*(){yield this.preflight();let a=n,{data:o}=a,r=A(a,["data"]),s=Object.entries(this.latestReceivedDeepdeskVersions).reduce((d,[l,c])=>S(y({},d),{[l]:c}),{}),i=["platform","agentId","agentName","agentEmail","conversationId"].reduce((d,l)=>(r[l]&&(d[l]=r[l]),d),{});return this.client.post("/api/v2/events",Y(S(y(y({},s),i),{data:o,name:e})),{version:"v2"})})}getEntities(e){return v(this,null,function*(){return yield this.preflight(),yield this.client.post("/api/v2/entities",{messages:e.filter(o=>o.text)})})}getTemporaryExchangeToken(){return v(this,null,function*(){return(yield this.client.get("/apis/admin/session/exchange-token/")).jwt})}exchangeTokenForAccessCookie(e){return v(this,null,function*(){return this.client.post("/apis/admin/session/jwt/",{jwt:e}).catch(n=>{throw 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/",Y(n),{refreshTokenOn401:!1,headers:{apikey:e}})})}getTextSuggestions(r){return v(this,arguments,function*(e,n={},o){if(yield this.preflight(),o==="sticky-messages")throw new Error("Use getPinnedMessages instead");return(yield this.client.post(`/api/v2/conversations/${e}/recommend/${o}`,Y(n),{abortLatest:!0})).map(i=>S(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`,Y(n),{abortLatest:!0})).map(r=>({score:1,source:r.source,sourceText:r.source_text,text:r.label,trainingJobs:r.training_jobs,searchKeywords:r.search_keywords,type:r.source})).filter((r,s,i)=>s===i.findIndex(a=>a.text===r.text))})}getPinnedMessages(e){return v(this,null,function*(){let n=yield this.client.get(`/api/v2/profiles/${e}/pinned-messages`,{abortLatest:!0});return B(n).map(o=>S(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",Y(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`,Y(e));return B(n)})}requestLoginByEmail(e){return v(this,null,function*(){yield this.preflight();let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:e});return 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 i;yield this.preflight();let o=new URLSearchParams;n!=null&&n.externalConversationId&&o.append("external_conversation_id",n.externalConversationId);let r=n!=null&&n.threadId?`/api/v2/assistants/${e}/threads/${n==null?void 0:n.threadId}/evaluate?${o.toString()}`:`/api/v2/assistants/${e}/evaluate?${o.toString()}`,s=yield this.client.post(r,{input:(i=n==null?void 0:n.input)!=null?i:{},conversation:n==null?void 0:n.transcript});return B(s)})}createAssistantThread(e){return v(this,null,function*(){yield this.preflight();let{assistantCode:n}=e,o=yield this.client.post(`/apis/admin/assistants/${n}/threads/`,{});return B(o)})}postMessageToAssistantThread(e){return v(this,null,function*(){yield this.preflight();let{assistantCode:n,threadId:o,message:r}=e,s=yield this.client.post(`/apis/admin/assistants/${n}/threads/${o}/messages/`,{content:r,role:"user"});return B(s)})}translateMessages(e){return v(this,null,function*(){yield this.preflight();let n=yield this.client.post("/api/v2/translate",Y(e));return B(n)})}handleDeepdeskVersionHeaders(e){e.headers.forEach((n,o)=>{let r=o.toLowerCase(),s=r.match(Di);if(!n||!s)return;let i=s[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&n&&a!==n&&k.warn(`Overwritten Version header ${r}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[i]=n})}};Ct.exchangeTokenPromise=null;var tt=Ct;import{combineReducers as yx,configureStore as vx}from"@reduxjs/toolkit";import{createSlice as px}from"@reduxjs/toolkit";var tp={startTime:null,stopTime:null},np=t=>t.handlingTime,op=px({name:"handlingTime",initialState:tp,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(V,()=>tp)}}),{handlingTimeStart:rp,handlingTimeStop:fr,handlingTimeReset:sp}=op.actions,ip=op.reducer;var ap=(t={})=>{let e=y({onAuthError:Pt(!1)},t);return n=>o=>r=>("error"in r&&r.error.message==="Unauthorized"&&n.dispatch(e.onAuthError),o(r))};import{createAsyncThunk as ux,createSlice as mx}from"@reduxjs/toolkit";var hr={list:{keywordMatches:[]},fetchState:"idle"};var Tt=ux("styleSuggestions/getAll",(n,o)=>v(null,[n,o],function*({text:t},e){var d;let{deepdeskAPI:r}=e.extra,s=e.getState(),{showStyleSuggestions:i}=s.settings,a=(d=s.conversation.current)==null?void 0:d.profileCode;if(!i)return hr.list;if(!a)throw new Error("No current conversation to fetch pinned messages");return r.getStyleSuggestions({profileCode:a,message:t})})),gx=mx({name:"styleSuggestions",initialState:hr,reducers:{},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",$e(e.list,n.payload)||(e.list=n.payload)}).addCase(at,e=>{e.list=hr.list}).addCase(V,()=>hr)}}),lp=gx.reducer;var dp=(t={})=>{let e,n=!0,o=y({getStyleSuggestions:Tt,debounce:500},t);return r=>s=>i=>{var g;let a=r.getState().input.text,d=s(i),l=r.getState();if(l.auth.isLoggedIn!==!0)return d;let{showStyleSuggestions:c}=l.settings;if(!((g=l.conversation.current)==null?void 0:g.id)||!c)return d;let{text:p}=l.input;return p===a&&!n||(clearTimeout(e),p==="")||(e=setTimeout(()=>{n=!1,r.dispatch(o.getStyleSuggestions({text:p}))},t.debounce)),d}};function fx(t,e){return t.text===e.text&&t.selection.start===e.selection.start&&t.selection.end===e.selection.end}var cp=(t={})=>{let e=y({getTextSuggestions:he,getAutocompleteSuggestions:Mn,debounce:200,check:Te},t),n;return o=>r=>s=>{var m;let{input:i}=o.getState(),a=r(s),d=o.getState();if(d.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:l,showTabCompletion:c}=d.settings,u=(m=d.conversation.current)==null?void 0:m.id,p=s.type===Ao.toString();if(!u||!l&&!c)return a;let{input:g}=d;return fx(g,i)&&!p||(clearTimeout(n),!e.check(d))||(n=setTimeout(()=>{let h=At(d);h===""?o.dispatch(e.getTextSuggestions("default")):o.dispatch(e.getAutocompleteSuggestions(h))},p?0:e.debounce)),a}};var pp=Tt.fulfilled.toString();function hx(t,e){let n=new Set([...e.keywordMatches.map(r=>r.keyword)]),o=[];return n.forEach(r=>{let s=t.keywordMatches.filter(d=>d.keyword===r),i=e.keywordMatches.filter(d=>d.keyword===r),a=i.length-s.length;a<=0||o.push(...i.slice(0,a))}),o}var up=t=>e=>n=>o=>{var l;if(o.type!==pp){n(o);return}let r=e.getState().styleSuggestions.list;n(o);let s=e.getState(),i=s.styleSuggestions.list,a=(l=s.conversation)==null?void 0:l.current;if(r===i)return;let d=hx(r,i);o.type===pp&&d.length>0&&t.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:d}})};var xx=yx({assistants:tc,auth:ji,conversation:Qi,contentTypes:$a,passwordlessToken:sc,entities:Tl,handlingTime:ip,info:Sa,input:ca,settings:Hi,profile:Qa,search:ka,styleSuggestions:lp,ui:Yl,textSuggestions:Fl});function mp(t){return vx({reducer:xx,middleware:e=>{var o;let n=e({thunk:{extraArgument:{dynamicThunkObject:t.dynamicThunkObject,deepdeskAPI:t.deepdeskAPI}},serializableCheck:!1}).concat(ap()).concat(cp({debounce:200})).concat(dp({debounce:500})).concat(up(t.deepdeskAPI));return((o=t.middleware)!=null?o:[]).reduce((r,s)=>r.concat(s),n)},preloadedState:t.preloadedState})}var Sx=t=>{var e,n;return(n=(e=t==null?void 0:t.type)==null?void 0:e.toLowerCase())!=null?n:"unknown"},bx=t=>e=>n=>o=>{var a,d;let r=e.getState(),s=Rt("inlineSuggestions")(r);switch(o.type){case Pt.toString():{!o.payload&&t.emit("logout",void 0);break}case fe.fulfilled.toString():o.payload.length>0&&t.sendEvent("entities found",{conversationId:(a=r.conversation.current)==null?void 0:a.id,data:{entities:o.payload}});break;case at.toString():t.logSendMessage(o.payload);break;case Qo.toString():t.emit("call-to-action",{cue:o.payload});break;case Ee.fulfilled.toString():o.isBroadcasted||t.broadcast(Ur,o,!1);break;default:break}let i=n(o);switch(o.type){case at.toString():t.handleAfterSendMessage(o.payload);break;case Nn.toString():t.onUpdateShowTabHint(o.payload);break;case fr.toString():t.logHandlingTime();break;case Nt.toString():t.broadcast(uo,o);break;case it.toString():t.broadcast(uo,o);break;case Zo.toString():e.dispatch(it({source:"assistant",assistantCode:o.payload.code}));break;case"analytics/logEvent/fulfilled":{let l=r.assistants.cues.find(c=>c.code===o.meta.arg.data.assistantCode);t.emit("event",S(y({},o.meta.arg),{cue:l}));break}case re.toString():{let{start:l,end:c}=r.input.selection;t.emit("select-suggestion",S(y({type:Sx(o.payload.suggestion)},o.payload),{replace:o.payload.replace==="selection"?{start:l,end:c}:{start:0,end:c}})),s&&e.dispatch(Ge([]));break}case oo.toString():t.emit("select-image",o.payload),t.sendEvent("Image attached",{conversationId:(d=r.conversation.current)==null?void 0:d.id,data:{path:o.payload.suggestion.image,title:o.payload.suggestion.title}});break;case Ge.toString():{s&&o.payload.length>0&&e.dispatch(ro(0));break}default:break}return i},gp=bx;import{createSelector as Cx}from"@reduxjs/toolkit";function ii(t){return t.toISOString().replace("T"," ").replace("Z","")}var Tx=(t,e)=>e.version,fp=Cx([Ot,xe,np,Tx],(t,e,n,o)=>{if(!e)return k.warn("No conversationId for handling time metrics"),null;let{startTime:r,stopTime:s}=n;return!r||!s?(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:ii(r),timeStop:ii(s)}});function hp(t,e){let{text:n,metrics:{numPaste:o,pastes:r,textSuggestions:s}}=t.input,i=n.length;return{source:"agent",clientVersion:e.version,pastes:r,lenTextTotal:i,numPastes:o,suggestions:s}}function ai(t,e){var s;let n=t.closest(e);if(n)return n;let o=t.getRootNode().host;if(o instanceof HTMLElement)return ai(o,e);let r=(s=t.ownerDocument.defaultView)==null?void 0:s.frameElement;return r?ai(r,e):null}function li(t,e){return ai(t,e)}function yp(t){return typeof t=="object"&&t!==null&&"name"in t&&"message"in t}function wx(t){return typeof t=="object"&&t!==null&&"tagName"in t}function di(t){return wx(t)&&(yt(t)||Uo(t))}var xp,ke=new Map,Ex=["bottom","height","left","right","top","width"],vp=(t,e)=>!t&&!e?!1:t&&!e||!t&&e?!0:Ex.some(n=>t[n]!==e[n]);function Sp(t){var n,o,r;if(t.ownerDocument===document)return[];let e=(r=(o=(n=t.ownerDocument)==null?void 0:n.defaultView)==null?void 0:o.frameElement)!=null?r:null;return e?[e,...Sp(e)]:[]}function bp(t,e){return!t||!e?null:S(y({},t),{top:t.top+e.top,left:t.left+e.left})}var yr=!1,Cp=()=>{yr=!0;let t=[];if(ke.forEach((e,n)=>{if(!n.isConnected){e.rect=null,t.push(e),ke.delete(n);return}let o=n.getBoundingClientRect();vp(o,e.rect)&&(e.rect=o,t.push(e))}),t.forEach(e=>{let n=e.parentRects?e.parentRects.reduce(bp,e.rect):e.rect;vp(n,e.totalRect)&&e.callbacks.forEach(o=>o(n)),e.totalRect=n}),ke.size===0){yr=!1;return}xp=window.requestAnimationFrame(Cp)};function ci(t,e){let n=Sp(t),o=[],r=n.map((s,i)=>ci(s,a=>{o[i]=a;let d=ke.get(t);if(!d)return;let l=o.reduce(bp,d.rect);d.callbacks.forEach(c=>c(l))}));return{observe(s=!0){if(r.forEach(i=>i.observe(!1)),ke.has(t)){let i=ke.get(t);i.callbacks.push(e),i.rect&&e(i.rect)}else ke.set(t,{rect:void 0,callbacks:[e],parentRects:o});s&&!yr&&Cp()},unobserve(){r.forEach(i=>i.unobserve());let s=ke.get(t);if(s){let i=s.callbacks.indexOf(e);i>=0&&s.callbacks.splice(i,1),s.callbacks.length||ke.delete(t),ke.size||(cancelAnimationFrame(xp),yr=!1)}}}}var Tp,Re=new Map,wp=()=>{Re.forEach((t,e)=>{if(!e.isConnected){Re.delete(e);return}let{clientHeight:n,scrollHeight:o}=e,r=o>n;t.visible!==r&&(t.visible=r,t.callbacks.forEach(s=>s(t.visible)))}),Re.size!==0&&(Tp=window.requestAnimationFrame(wp))};function Ep(t,e){return{observe(){let n=Re.size===0;Re.has(t)?Re.get(t).callbacks.push(e):Re.set(t,{visible:void 0,callbacks:[e]}),n&&wp()},unobserve(){let n=Re.get(t);if(n){let o=n.callbacks.indexOf(e);o>=0&&n.callbacks.splice(o,1),n.callbacks.length||Re.delete(t),Re.size||cancelAnimationFrame(Tp)}}}}var pi=["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 ui(t,e,n){return n.forEach(o=>{e.style[o]=t[o]})}function nn(t){return Number.parseFloat(t)}function vr(t){return Math.round(t*1e6)}function kp(t){return t/1e6}function mi(t,e,n){if(t.boxSizing==="content-box")return;let{clientWidth:o}=e,r=nn(t.width),s=nn(t.borderLeftWidth),i=nn(t.borderRightWidth),a=nn(t.paddingRight),d=kp(vr(r)-vr(s)-vr(i)),l=kp(vr(o));if(d-l>2){let c=d-l;n.style.paddingRight=`${a+c}px`}}function xr(t,e={}){var c,u;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",ft(n);let o=window.getComputedStyle(t),r=!0,s=()=>{n.scrollTop=t.scrollTop};ui(o,n,pi),mi(o,t,n),e.mirrorOverflow&&(n.style.overflow="hidden",t.addEventListener("scroll",s));let i=Ep(t,()=>{ui(o,n,pi),mi(o,t,n),s(),setTimeout(s,0)}),a,d=!0,l=ci(t,p=>{if(p===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),p.height===0&&p.width===0){if(r===!0)return;e.onHide&&e.onHide(),n.style.display="none",r=!0;return}if(ui(o,n,pi),mi(o,t,n),s(),e.placement==="below"&&n.classList.add("below"),n.style.top=`${p.top}px`,n.style.left=`${p.left}px`,e.closestScrollElement&&e.closestScrollElement!==t){let g=e.closestScrollElement.getBoundingClientRect(),f=window.getComputedStyle(e.closestScrollElement),m=nn(f.borderTopWidth),h=nn(f.borderBottomWidth),C=g.top+m-p.top,T=p.top+p.height+-(g.top+g.height-h);n.style.clipPath=`inset(${C}px 0px ${T}px 0px)`}r&&(n.style.display="block",e.onShow&&e.onShow(),r=!1)});return e.appendTo?e.appendTo.appendChild(n):(u=t.parentElement)==null||u.appendChild(n),l.observe(),i.observe(),[n,()=>{t.removeEventListener("scroll",s),l.unobserve(),i.unobserve(),n.remove()}]}var Rp=(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")}}});function kx(t){return t.offsetParent!==null}function Pp(t){if(!kx(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 gi(t,e,n=100){let o=Pp(t);e({isVisible:o});let r=setInterval(()=>{let s=Pp(t);s!==o&&(o=s,e({isVisible:o}))},n);return()=>{clearTimeout(r)}}var zn=class extends Error{};function Rx(){let t,e;return{promise:new Promise((o,r)=>{t=o,e=r}),resolve:t,reject:e}}var Sr=class{constructor(){this.queues={}}push(e,n){let o=()=>{let s=this.queues[e][1];s?(this.queues[e]=[s.promise,null],s.resolve()):delete this.queues[e]};if(!this.queues[e]){let s=n().finally(o);return this.queues[e]=[s,null],s}this.queues[e][1]&&this.queues[e][1].reject(new zn("Queued async function is outdated"));let r=Rx();return this.queues[e][1]=r,r.promise.then(()=>n().finally(o))}};var Px={accepted:"onConversationAcceptedAssistants","new-message":"onConversationNewMessageAssistants",ended:"onConversationEndedAssistants"},Ip=(t,e)=>{var r,s,i;if(!((i=(s=(r=t.uiConfig)==null?void 0:r.widget)==null?void 0:s.types.find(a=>a.type==="cues"))==null?void 0:i.isActive))return k.warn("Triggered a conversation assistant, but cues are not configured in widget."),[];let o=t[Px[e]];return o&&o.length>0?o.map(a=>a.code):(k.warn(`No assistant set in profile for conversation event "${e}"`),[])};var br=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(r=>r(o.data)))}catch(o){console.error("Error parsing WebSocket message:",o)}},this.socket.onclose=e=>{console.log("WebSocket connection closed:",e),setTimeout(()=>{this.reconnect()},this.reconnectInterval)},this.socket.onerror=e=>{console.error("WebSocket error:",e)})}reconnect(){var e,n;if(this.maxReconnectAttempts<=0){console.error("Max reconnect attempts reached, closing WebSocket connection."),(e=this.socket)==null||e.close();return}if(!this.shouldReconnect()){console.error("Should not reconnect, closing WebSocket connection."),(n=this.socket)==null||n.close();return}this.socket&&(this.socket.onmessage=null,this.socket.onclose=null,this.socket.onerror=null,this.socket.close()),this.socket=new WebSocket(this.url),this.setupListeners(),this.maxReconnectAttempts--}send(e,n){if(!this.socket){console.error("WebSocket connection is not open.");return}this.socket.send(JSON.stringify({event:e,data:n}))}on(e,n){this.eventListeners.has(e)||this.eventListeners.set(e,[]);let o=this.eventListeners.get(e);o&&!o.includes(n)&&o.push(n)}close(){var e;(e=this.socket)==null||e.close()}cleanup(){this.close(),this.cleanupCallbacks.forEach(e=>e()),this.cleanupCallbacks=[]}};import Ax,{useState as hi,useEffect as Mx}from"react";var Lp={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 Nx}from"react-redux";var fi={};X(fi,{enUS:()=>Ix,nlNL:()=>Lx});var Ix={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."}]},Lx={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 Ox,jsx as ve,jsxs as Cr}from"react/jsx-runtime";var Ap=({onClose:t,onSave:e,id:n,error:o})=>{let[r,s]=hi(""),[i,a]=hi(!1),[d,l]=hi(!1),c=x("Nickname",Lp),u=Ax.useRef(null),p=Nx(C=>C.info.showNicknameDialog),g=R(fi),f=E("adminUrl");Mx(()=>{o&&a(!0)},[o]);let m=()=>{if(!u.current)return;r.trim()?u.current.setCustomValidity(""):u.current.setCustomValidity(g("nicknameDialogError")),u.current.reportValidity()},h=C=>{C.preventDefault();let T=r.trim(),b=C.currentTarget.querySelector("#nickname-input");if(!T){b.setCustomValidity(g("nicknameDialogError")),b.reportValidity();return}b.setCustomValidity(""),e(T)};return Cr(Ft,{isOpen:p,"datatest-id":n,onClose:t||(()=>{}),onBack:t||(()=>{}),children:[ve("div",{className:c.titleWrapper,children:ve("h1",{className:c.title,children:g("title")})}),Cr("form",{className:c.dialogContent,onSubmit:h,children:[ve("p",{children:g("nicknameDialogTitle")}),i&&o&&ve("div",{className:c.errorMessage,children:f?(()=>{let C=g("nicknameDialogSaveError",{account:f}),T=`${f}.deepdesk.com/admin/user-settings`,b=C.indexOf(T);if(b!==-1){let w=C.substring(0,b),I=C.substring(b+T.length);return Cr(Ox,{children:[w,ve("a",{href:T,target:"_blank",rel:"noopener noreferrer",className:c.errorLink,children:T}),I]})}return C})():g("nicknameDialogSaveErrorWithoutLink")}),ve("input",{required:!0,minLength:1,maxLength:20,"data-testid":"nickname-input",id:"nickname-input",className:c.nicknameInput,type:"text",placeholder:g("nicknameDialogInputPlaceholder"),value:r,onChange:C=>{l(new RegExp("\\p{Extended_Pictographic}","u").test(C.target.value)),s(C.target.value)},onBlur:m,ref:u}),d&&ve("div",{className:c.errorMessage,role:"alert",children:g("nicknameDialogEmojiError")}),Cr("div",{className:c.buttonsWrapper,children:[o?ve("div",{className:c.closeButtonWrapper,children:ve("button",{type:"button",className:c.closeButton,onClick:()=>t==null?void 0:t(),children:g("close")})}):null,ve("div",{className:c.buttonContinueWrapper,children:ve("button",{type:"submit",className:c.continueButton,disabled:!r.trim()||new RegExp("\\p{Extended_Pictographic}","u").test(r),children:g("nicknameDialogContinueButton")})})]})]})]})};import{jsx as F,jsxs as Dx}from"react/jsx-runtime";var Mp=Rp("showTabHint",!0),on=class on{constructor({deepdeskUrl:e,version:n=on.version||"unknown",locale:o="en-US",token:r,fetch:s,productName:i,createCustomChannel:a,websocketClient:d=br}){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 Sr;this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;let l=e.replace(/\/api$/,"");this.deepdeskApi=new tt(l,{token:r,fetch:s}),this.version=n,this.instanceId=on.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[gp({broadcast:(f,m,h)=>{this.broadcastEvents.send(f,m,h)},emit:(f,m)=>this.emit(f,m),handleAfterSendMessage:f=>this.handleAfterSendMessage(f),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:f=>this.logSendMessage(f),onUpdateShowTabHint:f=>Mp.update(f),sendEvent:(f,m)=>this.deepdeskApi.sendEvent(f,m)})]};this.store=mp(c),this.broadcastEvents=new Yc({debug:!0,deepdeskUrl:l,eventMap:Ra(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 f;return(f=J(this.state))!=null?f:!1})}),this.whenLoggedIn(()=>this.ws.connect()),this.store.dispatch(Nn(Mp.value())),this.store.dispatch(Zn({locale:o,adminUrl:l,productName:i}));let u=[],p=f=>{if(!f.conversationId)return;let m=()=>{this.conversationId()===f.conversationId&&this.store.dispatch(ec(f))};this.hasConversation()?m():u.push(m)};this.ws.on("assistants::direct_response",p),this.ws.on("assistants::user_notification",p),this.ws.on("assistants::response_chunk",f=>{if(!f.conversationId)return;let m=()=>{this.conversationId()===f.conversationId&&this.store.dispatch(Yd(f))};this.hasConversation()?m():u.push(m)}),this.ws.on("assistants::suggest_as_reply",f=>{if(!f.conversationId)return;let m=()=>{this.conversationId()===f.conversationId&&this.store.dispatch(Nt([{text:f.payload.message,type:"text",source:"assistant",assistantCode:f.code,sourceLabel:f.name}]))};this.hasConversation()?m():u.push(m)});let g=this.whenConversationLoaded(()=>{var f;this.broadcastEvents.setExternalId((f=this.state.conversation.current)==null?void 0:f.externalId),u.forEach(m=>m()),u.length=0});this.disposeHandlers.push(()=>{this.ws.cleanup(),u.length=0,g()})}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){var e;return(e=st(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(J(this.state))e();else{let n=this.subscribe(J,o=>{o&&e()});this.disposeHandlers.push(()=>{n()})}}login(){return this.store.dispatch(Pt(null)),this.store.dispatch(Le()),new Promise(e=>{this.whenLoggedIn(()=>e())})}isLoggedIn(){return v(this,null,function*(){return(yield this.store.dispatch(Le())).payload})}isConversationSupported(e,n){return v(this,null,function*(){return(yield this.store.dispatch(Nr({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(eo(S(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(to({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(Or(S(y({},e),{metadata:(o=e.metadata)!=null?o:{}})))).payload})}postMessages(e){return v(this,null,function*(){yield this.store.dispatch(Dr(e))})}updateConversation(e){return v(this,null,function*(){return(yield this.store.dispatch(no(e))).payload})}resetConversation(){this.store.dispatch(V()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}configure(e){this.store.dispatch(Zn(e))}setVisitorInfo(e){this.store.dispatch(ha(e))}setCustomData(e){this.store.dispatch(ya(e))}setAgentInfo(e,n){return v(this,null,function*(){var r;yield this.store.dispatch(pn(y(y({},e),n))),((r=this.state.info.agentInfo)==null?void 0:r.agentNickname)||this.broadcastEvents.send(po,{showNicknameDialog:!0})})}setAgentSettings(e){return v(this,null,function*(){yield this.store.dispatch(Fr(e))})}getAgentSettings(){return v(this,null,function*(){return(yield this.store.dispatch(Hr())).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(so({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()}))}notifyExternalSuggestion(e){this.store.dispatch(re(e))}evaluateAssistant(e,n){return v(this,null,function*(){var d;let{input:o={},transcript:r,showCuesInWidget:s=!0,includeMetadata:i}=n||{},a=yield this.store.dispatch(Ee({assistantCode:e,transcript:r,includeMetadata:i,input:o,skipState:!s}));if(a.error)throw new Error(`Assistant evaluation failed: ${(d=a.payload)!=null?d:a.error.message}`);return a.payload.output})}evaluateConversationAssistant(e,n){return v(this,null,function*(){yield this.loadProfileConfig();let o=this.state.profile.data;if(!o){k.warn("Can't evaluate assistant when profile is not loaded yet.");return}let r=Ip(o,e);yield Promise.all(r.map(s=>this.queues.push(s,()=>v(this,null,function*(){yield this.evaluateAssistant(s,y({includeMetadata:!0},n))})).catch(i=>{if(i instanceof zn){k.warn(`Queued assistant "${s}" was outdated and dropped`);return}throw i})))})}handleKeyDown(e){let{overlayCollapsed:n,openOverlayWhenTyping:o}=this.state.ui,{textSuggestions:r,selectedSuggestionIndex:s,selection:i}=this.state.input,{inlineSuggestions:a,showTextSuggestions:d,suggestionsPlacement:l}=this.settings,c=l==="inline"||l==="below"?"below":"above",u=r.length>0;if(this.store.dispatch(oa(_r(e))),!Te(this.state)||e.key!=="Tab"&&!d)return;let p=()=>{n||!u||i&&(e.shiftKey||(this.store.dispatch(ia()),e.preventDefault()))},g=()=>{n||!u||a&&s<=0||i&&(e.shiftKey||(this.store.dispatch(aa()),e.preventDefault()))};switch(e.key){case"ArrowUp":c==="below"?g():p();break;case"ArrowDown":{c==="below"?p():g();break}case"Escape":{n||(this.store.dispatch(ro(-1)),this.store.dispatch(Je({collapse:!0})),this.store.dispatch(Ql(!0)),e.preventDefault());break}case"Tab":{e.preventDefault();let f=Mt(this.state);if(!f)return;this.store.dispatch(Nn(!1)),this.store.dispatch(re({text:f.text,suggestion:f,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(this.settings.inlineSuggestions||this.state.input.selectedSuggestionIndex===-1)return;let f=Mt(this.state);if(!f)return;this.store.dispatch(re({text:f.text,suggestion:f,eventMetrics:{inputType:"space"},replace:"until-selection-end"}));break}case"Enter":{if(this.settings.inlineSuggestions||e.shiftKey||this.state.input.selectedSuggestionIndex===-1)return;let f=Mt(this.state);if(!f)return;this.store.dispatch(re({text:f.text,suggestion:f,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),e.preventDefault();break}default:}n&&o&&this.store.dispatch(Je({collapse:!1}))}handleAfterSendMessage(e){this.emit("send-message",e),this.store.dispatch(Ge([]))}handlingTimeStart(){this.state.handlingTime.startTime||(k.info("Start handling time"),this.store.dispatch(rp()))}handlingTimeStop(){this.state.handlingTime.startTime&&(k.info("Stop handling time"),this.store.dispatch(fr()))}logSendMessage(e){let n=hp(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=fp(this.state,{version:this.version});e&&(this.deepdeskApi.sendEvent("Handling Time",{conversationId:this.conversationId(),data:e}),this.store.dispatch(sp()))}notifySubmit(e={}){var n;this.shouldAbort()||(this.store.dispatch(at((n=e.text)!=null?n:this.state.input.text)),this.store.dispatch(da()))}emit(e,n){let o=this.eventListeners[e];o&&o.forEach(r=>{try{r(n)}catch(s){k.warn(`The following error occurred in deepdeskSDK.on('${e}', handler)`),k.error(s)}})}on(e,n){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(n),()=>{this.off(e,n)}}off(e,n){if(!e&&!n){this.eventListeners={};return}let o;this.eventListeners[e]&&(o=this.eventListeners[e].indexOf(n),o>-1&&this.eventListeners[e].splice(o,1))}setConversationQuery(e){this.dynamicThunkObject.conversationQuery=e}setPlatformVariables(e){this.store.dispatch(va(e))}whenConversationLoaded(e){let n=s=>{var i;return(i=s.conversation.current)==null?void 0:i.id},o=()=>this.loadProfileConfig().then(()=>e());return n(this.state)&&o(),this.subscribe(n,s=>{s&&o()})}overlayContainerFactory(e,n,o,r){let[s,i]=xr(n,o);return s.setAttribute("translate","no"),s.dataset.testid=e,r&&s.classList.add(r),[s,i]}createInlineContainer(e,n){var a;let o=document.createElement("div");o.style.position="absolute",o.style.top="0px",o.style.left="0px",o.style.height="0px",o.style.width="0px";let r=document.createElement("div");r.style.display="none",r.style.position="absolute",r.style.height="0px",r.style.width="0px",r.style.backgroundColor="red",o.appendChild(r);let s=(a=e.ownerDocument.defaultView)==null?void 0:a.frameElement,i=s?s.ownerDocument.defaultView:null;if(s&&(i===window||(i==null?void 0:i.parent)===window)){let[d,l]=xr(s,{appendTo:document.body,onMoveStart:()=>{r.style.display="none"}});d.dataset.testid=n,d.style.zIndex="2",d.appendChild(o),this.unmountHandlers.push(()=>{l()})}else document.body.appendChild(o);return r}createContainer(e,n=document.body){let o=window.getComputedStyle(n),r=document.createElement("div");return ft(r),r.dataset.testid=e,r.style.color=o.color,r.style.fontSize=o.fontSize,r.style.fontFamily=o.fontFamily,r.style.fontVariant=o.fontVariant,r.setAttribute("translate","no"),n.appendChild(r),r}storeMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,n=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(e,n),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(la(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(!di(e))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let p=n,{customStyles:o,closestScrollSelector:r,floatingMenuParent:s,appendOverlayTo:i,inputMediator:a}=p,d=A(p,["customStyles","closestScrollSelector","floatingMenuParent","appendOverlayTo","inputMediator"]),l={customStyles:o,closestScrollSelector:r,floatingMenuParent:s,appendOverlayTo:i};this.configure(d),this.settings.automaticHandlingTime&&this.setupHandlingTime(e),ft(e),this.inputMediator=a||(yt(e)?new Zt(e):new Qt(e)),this.inputMediator.on("change",({plainText:g,rawHTML:f})=>{this.store.dispatch(so({text:g,html:f}))}),this.inputMediator.on("keyup",g=>{this.store.dispatch(ra(_r(g)))}),this.inputMediator.on("keydown",g=>{this.handleKeyDown(g)}),this.inputMediator.on("paste",({pastedText:g,selectionText:f})=>{this.store.dispatch(sa({text:g,selectionText:f}))}),this.inputMediator.on("cut",({selectionText:g})=>{this.store.dispatch(na(g))});let c;this.inputMediator.on("selection",g=>{clearTimeout(c),g===null?c=setTimeout(()=>{g!==null&&this.store.dispatch(io(g))},500):this.store.dispatch(io(g))}),this.unmountHandlers.push(()=>{clearTimeout(c)}),this.inputMediator.on("disabled",()=>{var g;(g=this.inputMediator)==null||g.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(Oo(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(Oo(!0))}),this.renderSuggestions(e,l),this.subscribe(Rt("inlineSuggestions"),()=>{this.renderSuggestions(e,l)}),this.subscribe(Rt("suggestionsPlacement"),()=>{this.renderSuggestions(e,l)});let u=this.renderOverlays(n);this.unmountHandlers.push(()=>{u.unmount()}),this.store.dispatch(so({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()})),this.store.dispatch(io(this.inputMediator.getSelection())),this.store.dispatch(Oo(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=nt(n),r=null,s=a=>{r=a,i()},i=()=>{o==null||o.render(F(_e,{store:this.store,children:F(Me,{broadcastEvents:this.broadcastEvents,children:F(Ap,{id:"deepdesk-nickname-dialog",error:r,onSave:a=>v(this,null,function*(){try{yield this.store.dispatch(ga({agentNickname:a})).unwrap(),console.log("setAgentNickname",a),this.broadcastEvents.send(po,{showNicknameDialog:!1}),this.nicknameDialogUnsubscribe&&this.nicknameDialogUnsubscribe()}catch(d){k.error("Error setting agent nickname",d),s("error"),this.nicknameDialogFailed=!0}})})})}))};i(),this.nicknameDialogUnsubscribe=()=>{o.unmount(),n.remove(),this.nicknameDialogUnsubscribe=null}}subscribe(e,n){let o=e(this.store.getState());return this.store.subscribe(()=>{let r=e(this.store.getState());r!==o&&(o=r,n(o))})}unmount(){var e,n,o,r,s;(e=this.inlineSuggestions)==null||e.unmount(),(n=this.aboveSuggestions)==null||n.unmount(),(o=this.belowSuggestions)==null||o.unmount(),(r=this.floatingMenu)==null||r.unmount(),this.unmountHandlers.forEach(i=>i()),this.unmountHandlers=[],(s=this.inputMediator)==null||s.dispose(),this.nicknameDialogUnsubscribe&&this.nicknameDialogUnsubscribe(),this.isMounted=!1}dispose(){this.unmount(),this.unmountWidget(),this.disposeHandlers.forEach(e=>e()),this.disposeHandlers=[],this.off()}renderSuggestions(e,n){var o,r,s,i;(o=this.floatingMenu)==null||o.unmount(),(r=this.inlineSuggestions)==null||r.unmount(),(s=this.aboveSuggestions)==null||s.unmount(),(i=this.belowSuggestions)==null||i.unmount(),this.settings.floatingMenu&&(this.floatingMenu=this.renderFloatingMenu(e,n)),this.settings.inlineSuggestions||this.settings.suggestionsPlacement==="inline"?this.inlineSuggestions=this.renderInlineSuggestions(e,n):this.settings.suggestionsPlacement==="below"?this.belowSuggestions=this.renderAboveOrBelowSuggestions(e,n,"below"):this.aboveSuggestions=this.renderAboveOrBelowSuggestions(e,n,"above")}renderInlineSuggestions(e,n){let{customStyles:o}=n,r=this.createInlineContainer(e,"deepdesk-caret"),s=nt(r);s.render(F(_e,{store:this.store,customStyles:o,children:F(Me,{broadcastEvents:this.broadcastEvents,children:F(dd,{})})}));let i=a=>{a?(r.style.display="block",r.style.top=`${a.top}px`,r.style.left=`${a.left}px`):r.style.display="none"};return this.inputMediator.on("caretposition",i),{unmount:()=>{var a;(a=this.inputMediator)==null||a.off("caretposition",i),s.unmount(),r.remove()}}}renderAboveOrBelowSuggestions(e,n,o){let{customStyles:r,closestScrollSelector:s,appendOverlayTo:i}=n,a=s&&li(e,s)||void 0,[d,l]=this.overlayContainerFactory("deepdesk-tab-completion",a||e,{appendTo:i,closestScrollElement:a,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),[c,u]=this.overlayContainerFactory("deepdesk-suggestions-overlay",a||e,{appendTo:i,placement:o},r==null?void 0:r.suggestionsRootNode),p=nt(d);p.render(F(_e,{store:this.store,customStyles:r,children:F(Me,{broadcastEvents:this.broadcastEvents,children:F(jd,{inputElement:e})})}));let g=nt(c);return g.render(F(_e,{store:this.store,customStyles:r,children:F(Me,{broadcastEvents:this.broadcastEvents,children:F(xd,{onLogIn:()=>this.loginViaPopup().catch(f=>k.warn(f.message))})})})),{unmount(){p.unmount(),g.unmount(),l(),u()}}}renderFloatingMenu(e,n){let{customStyles:o,closestScrollSelector:r,appendOverlayTo:s,floatingMenuParent:i}=n,a=r&&li(e,r)||void 0,[d,l]=this.overlayContainerFactory("floating-menu",a||e,{appendTo:i!=null?i:s},o==null?void 0:o.floatingMenuParent),c=nt(d);return c.render(F(_e,{store:this.store,customStyles:o,children:F(Me,{broadcastEvents:this.broadcastEvents,children:F(Xl,{onLogIn:()=>this.loginViaPopup().catch(u=>k.warn(u.message))})})})),{unmount(){c.unmount(),l()}}}renderOverlays(e){let{customStyles:n}=e,o=this.createContainer("deepdesk-overlays"),r=nt(o);return r.render(F(_e,{store:this.store,customStyles:n,children:F(Me,{broadcastEvents:this.broadcastEvents,children:F(Wl,{})})})),{unmount(){r.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:r,isEmbedded:s,insertLinkAsHtml:i}=n;this.widgetElement=e,this.configure({showImages:r,isEmbedded:s,insertLinkAsHtml:i}),this.widgetRoot=nt(e),this.widgetRoot.render(F(_e,{store:this.store,customStyles:o,children:F(Me,{broadcastEvents:this.broadcastEvents,children:F(Gc,{assistantOptions:n.assistantOptions,knowledgeAssistOptions:n.knowledgeAssist,onLogIn:()=>this.loginViaPopup().catch(a=>k.warn(a.message))})})}))}unmountWidget(){var e,n;(n=(e=this.widgetRoot)==null?void 0:e.unmount)==null||n.call(e),this.widgetRoot=null,this.widgetElement=null}renderKnowledgeAssistantWidget(e,n,o={}){let{customStyles:r,initialQuestion:s}=o,i=nt(n);return i.render(F(_e,{store:this.store,customStyles:r,children:F(Me,{broadcastEvents:this.broadcastEvents,children:F(Zs,{children:Dx(ar,{assistantCode:e,initialQuestion:s,evaluateKnowledgeAssistFn:Dn,children:[F(an,{children:F(dr,{title:o.title,emptyState:o.emptyState})}),F(Qs,{children:F(lr,{})})]})})})})),{unmount(){i.unmount()}}}setupHandlingTime(e){let n=gi(e,({isVisible:o})=>{o?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){yp(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(()=>v(this,null,function*(){yield this.store.dispatch(kn());let e=ct(this.state);e&&this.store.dispatch(Zn({showSearch:e.search,showImageSearch:e.imageSearch,showEntitiesCommand:e.entitiesCommand,showSummaryCommand:!!e.summarizerAssistantNew,showKnowledgeSearch:!!e.knowledgeAssistantNew||!!e.knowledgeAssistant,recommendTextSuggestions:e.recommendTextSuggestions}))})),this.loadProfileConfigPromise)}loginViaPopup(e){return v(this,null,function*(){return new Promise((n,o)=>{this.store.dispatch(Yn());let r=new MessageChannel,s=r.port1,i=this.settings.adminUrl,a=new URL(e!=null&&e.url?e==null?void 0:e.url:`${i}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let d=!1,l=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",u),clearInterval(p)};s.onmessage=g=>v(this,null,function*(){var f,m;if((f=g.data)!=null&&f.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((m=g.data)==null?void 0:m.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(mn),d=!0,r.port1.close(),n()}catch(h){console.error(h),o(h)}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 u=g=>v(this,null,function*(){var f;if(g.origin===a.origin)switch((f=g.data)==null?void 0:f.type){case"deepdesk-popup-request-origin":{try{let m=JSON.stringify({type:"deepdesk-popup-parent-origin"});c==null||c.postMessage(m,a.origin)}catch(m){k.error("Error posting message to popup",m),o(m)}break}case"deepdesk-popup-loaded":{try{let m=JSON.stringify({type:"deepdesk-popup-create-channel"});c==null||c.postMessage(m,a.origin,[r.port2])}catch(m){k.error("Error posting message to popup",m),o(m)}break}case"deepdesk-popup-error":{if(l(),g.data.message==="Platform account url mismatch"){let m=`Please contact your administrator: The platform account url (${g.data.targetOrigin}) is misconfigured as it differs from the origin of the page that opened the popup (${g.data.openerOrigin}).`;k.warn(m),this.store.dispatch(Mr(m)),o(new Error(m))}if(g.data.message==="Timeout"){let m="Please contact your administrator: Popup timed out. Check if the account's platform url is configured correctly.";k.warn(m),this.store.dispatch(Mr(m)),o(new Error(m))}o(new Error(g.data.message));break}}});window.addEventListener("message",u);let p=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(Ao()))})}refreshWidgetSuggestions(){return v(this,null,function*(){if(!this.widgetRoot)return;let{uiConfig:e}=this.state.profile.data;if(!e.widget)return;let n=Rn(this.state);try{n.forEach(({type:o})=>{switch(o){case"entities":this.store.dispatch(fe());break;case"pinned-messages":case"sticky-messages":break;default:Jn.includes(o)||this.store.dispatch(he(o))}})}catch(o){this.handleError(o)}})}};on.version="19.0.2-beta.7",on.count=0;var Tr=on;function _x(t){return v(this,null,function*(){var r,s,i;let n=yield((r=t.fetch)!=null?r:window.fetch)(t.url),o=yield n.blob();return new File([o],t.name,{type:(i=(s=t.mimeType)!=null?s:n.headers.get("Content-Type"))!=null?i:"image/jpeg"})})}function Fx(t,e){return v(this,null,function*(){let n=yield _x(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 Hx(t,e,n){return v(this,null,function*(){yield new tt(t).authenticateWithKey(e,n)})}function Bx(t){return t.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function Ux(o,r){return v(this,arguments,function*(t,e,n={}){var u,p;let{value:s}=t,{start:i,end:a}=(u=n.replace)!=null?u:{start:0,end:s.length},d=`${s.slice(0,i)}${e}${s.slice(a)}`,l=(p=n.selectionAfter)!=null?p:{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 Kx(o,r){return v(this,arguments,function*(t,e,n={}){let s=n.replace?bt(t,n.replace.start,n.replace.end):Kn(t),i,a=()=>{if(n.setRange)return n.setRange(s.cloneRange());s.deleteContents(),i=document.createElement("span"),s.insertNode(i),n.insertBRs!==!1?e.split(`
|
|
16
|
+
`);let f=p?o:0,m=g?Math.min(s,c.childNodes.length):c.childNodes.length;for(let h=f;h<m&&(l(c.childNodes[h]),a!==2);h++);break}default:break}g&&(a=2)}return l(t),d}var Xc=(i=>(i.CUT="Cut",i.BACKSPACE="Backspace",i.DELETE="Delete",i.ERASEEOF="EraseEof",i.UNDO="Undo",i.CLEAR="Clear",i))(Xc||{}),Ye=class{constructor(e){this.element=e;this.isFocused=!1;this.isActive=!0;this.isDisposed=!1;this.eventListeners={};this.disposeHandlers=[];this.cachedText="";this.cachedCaretPosition=null;this.cachedSelection={start:0,end:0};this.cachedHTML="";this.isSubmitting=!1;this.isPossibleClearInputAction=!1;this.cachedText=this.getText(),this.cachedHTML=this.getHTML(),this.cachedSelection=this.getSelection(),this.listen()}addEventListener(e,n){let o=r=>{n(r)};this.element.addEventListener(e,o),this.disposeHandlers.push(()=>{this.element.removeEventListener(e,o)})}removeEventListener(e,n){this.element.removeEventListener(e,n)}handleInteraction(){let e=this.getText(),n=this.getHTML(),o=this.getSelection(),r=this.cachedCaretPosition===null;if(!this.isActive||(e===""&&this.cachedText!==""&&!this.isPossibleClearInputAction&&this.emit("submit"),e!==this.cachedText?(this.cachedText=e,this.cachedHTML=n,r=!0,this.emit("change",{plainText:e,rawHTML:n})):n!==null&&n!==this.cachedHTML&&(this.cachedHTML=n,r=!0,this.emit("change",{plainText:e,rawHTML:n})),(o.start!==this.cachedSelection.start||o.end!==this.cachedSelection.end)&&(this.cachedSelection=o,r=!0,this.emit("selection",o)),!r))return;let s=this.getCaretPosition();$e(s,this.cachedCaretPosition)||(this.cachedCaretPosition=s,this.emit("caretposition",s))}handleClick(){this.handleInteraction()}handleFocus(){let e=!this.isFocused;this.isFocused=!0,e&&this.emit("focus"),this.handleInteraction()}handleBlur(){this.isPossibleClearInputAction=!1;let e=this.isFocused;this.isFocused=!1,e&&this.emit("blur")}handleKeyDown(e){let{key:n,ctrlKey:o,metaKey:r}=e;this.isPossibleClearInputAction=Object.values(Xc).includes(n)||n.toLowerCase()==="z"&&(o||r),this.emit("keydown",e)}handleKeyUp(e){this.handleInteraction(),this.emit("keyup",e)}handleCut(){this.isPossibleClearInputAction=!0,this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(e){var o,r;let n=((o=e.clipboardData)==null?void 0:o.getData("text"))||((r=e.clipboardData)==null?void 0:r.getData("text/plain"))||"";this.emit("paste",{pastedText:n,selectionText:this.getSelectedText()})}listen(){this.addEventListener("keydown",n=>this.handleKeyDown(n)),this.addEventListener("keyup",n=>this.handleKeyUp(n)),this.addEventListener("input",()=>this.handleInteraction()),this.addEventListener("change",()=>this.handleInteraction()),this.addEventListener("focus",()=>this.handleFocus()),this.addEventListener("blur",()=>this.handleBlur()),this.addEventListener("cut",()=>this.handleCut()),this.addEventListener("paste",n=>this.handlePaste(n)),this.addEventListener("click",()=>this.handleInteraction()),document.activeElement===this.element&&(this.isFocused=!0);let e=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});e.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{e.disconnect()})}focus(){this.element.focus()}emit(e,...n){this.isDisposed||this.eventListeners[e]&&this.eventListeners[e].forEach(o=>{o(...n)})}on(e,n){this.isDisposed||(this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(n))}off(e,n){if(!this.eventListeners[e])return;let o=this.eventListeners[e].indexOf(n);o!==-1&&this.eventListeners[e].splice(o,1)}activate(){let e=this.isActive===!1;this.isActive=!0,e&&this.handleInteraction()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(e=>e()),this.eventListeners={},this.isDisposed=!0}};function Jc(t){return t.top!==0||t.left!==0||t.height!==0||t.width!==0}var Qt=class extends Ye{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),gr(this.element,n)}getHTML(){return this.element.innerHTML||""}getRange(){let n=this.getRootNode();if(n.activeElement!==this.element)return null;let o="getSelection"in n?n.getSelection():window.getSelection();if(!o)return null;let r=o.rangeCount>0?o.getRangeAt(0):null;if(!r)return null;let s=this.element.ownerDocument.createRange();return s.setStart(r==null?void 0:r.startContainer,r==null?void 0:r.startOffset),s.setEnd(r==null?void 0:r.endContainer,r==null?void 0:r.endOffset),!s||!this.element.contains(s.startContainer)||!this.element.contains(s.endContainer)?null:s}getCaretPosition(){let n=this.getRange();if(!n||!n.collapsed||!("getBoundingClientRect"in n))return null;let o=n.getBoundingClientRect();return!Jc(o)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),o=n.getBoundingClientRect(),n.deleteContents(),!Jc(o))?null:{top:o.top+o.height,left:o.left}}getSelection(){let n=this.getRange();if(n)return mr(this.element,n);let o=this.lastKnownSelection;if(o&&qc(this.element,o.start,o.end))return o;let r=Kn(this.element);return r.collapse(!1),mr(this.element,r)}getSelectedText(){let{start:n,end:o}=this.getSelection();return gr(this.element,bt(this.element,n,o))}listen(){super.listen();let n=new MutationObserver(s=>{var i,a;s.length===2&&s[0].addedNodes.length===1&&((i=s[0].addedNodes[0])==null?void 0:i.textContent)==="\u2060"&&((a=s[1].removedNodes[0])==null?void 0:a.textContent)==="\u2060"||setTimeout(()=>{this.handleInteraction()},0)});n.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0}),this.disposeHandlers.push(()=>n.disconnect());let o=this.element.isContentEditable,r=new MutationObserver(()=>{this.element.isContentEditable!==o&&(o=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});r.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>r.disconnect())}};var ix=["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 Qc(t,e){let n="mozInnerScreenX"in window,o=document.createElement("div");o.id="input-textarea-caret-position-mirror-div";let r=o.style,s=window.getComputedStyle(t),i=t.ownerDocument.body;r.whiteSpace="pre-wrap",r.wordWrap="break-word",r.position="absolute",r.visibility="hidden",ix.forEach(c=>{r[c]=s[c]}),n?t.scrollHeight>Number.parseInt(s.height)&&(r.overflowY="scroll"):r.overflow="hidden",o.textContent=t.value.substring(0,e);let a=document.createElement("span");a.textContent=t.value.substring(e)||".",o.appendChild(a),i.appendChild(o);let d=t.getBoundingClientRect(),l={top:d.top-t.scrollTop+a.offsetTop+Number.parseInt(s.borderTopWidth)+a.offsetHeight,left:d.left-t.scrollLeft+a.offsetLeft+Number.parseInt(s.borderLeftWidth)};return i.removeChild(o),l}var Zt=class extends Ye{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 Qc(this.element,this.element.selectionEnd)}listen(){super.listen();let n=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var s;return(s=n==null?void 0:n.get)==null?void 0:s.call(this.element)},set:s=>{var i;(i=n==null?void 0:n.set)==null||i.call(this.element,s),this.handleInteraction()}}),this.addEventListener("scroll",()=>{this.emit("caretposition",this.getCaretPosition())});let o=this.element.disabled,r=new MutationObserver(()=>{this.element.disabled!==o&&(o=this.element.disabled,this.emit(o?"disabled":"enabled"))});r.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>r.disconnect())}};function Zc(t,e,n){let o=`deepdesk-iframe-${t}`,r=document.getElementById(o);if(r)return r;let s=document.createElement("iframe"),i=new URL(e);return Object.entries(n).forEach(([a,d])=>{i.searchParams.append(a,d)}),s.style.position="absolute",s.style.left="-999em",s.style.width="0px",s.style.height="0px",s.tabIndex=-1,s.id=o,s.title=`iframe-${t}`,s.src=i.toString(),window.document.body.appendChild(s),s}function ax(t){if(typeof t!="string")return t;try{return JSON.parse(t)}catch(e){return t}}var Ys=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()}},ei=class{constructor(e,n,o){this.name=e;this.targetOrigin=n;this.options=o;this.disposeHandlers=[];this.iframe=Zc(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()}},ti=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 ei(e,this.deepdeskUrl,{debug:!0}):new Ys(e),o=r=>{var i,a;if(r.origin!==this.deepdeskUrl)return;let s=ax(r.data);typeof s!="object"||s.type!=="event"||s.channel!==e||(k.info("Received broadcast event",this.externalId,r),(a=(i=this.eventMap)[s.name])==null||a.call(i,s.payload))};return n.onMessage(o),n}send(e,n,o){var i,a;k.info("Broadcast event",{externalId:this.externalId,name:e,payload:n});let r={type:"event",name:e,payload:n};o!==!1&&((a=(i=this.eventMap)[e])==null||a.call(i,n));let s=this.externalId==="deepdesk-general"?this.defaultChannel:this.channel;s==null||s.postMessage(S(y({},r),{channel:this.externalId}))}cleanup(e=!1){var n,o;(n=this.channel)==null||n.close(),this.channel=void 0,e&&((o=this.defaultChannel)==null||o.close(),this.defaultChannel=void 0)}},Yc=ti;function lx(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)=>S(y({},e),{[lx(n)]:B(t[n])}),{}):t}function dx(t){return t.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}function Y(t){return Array.isArray(t)?t.map(Y):typeof t=="object"&&t!==null?Object.keys(t).reduce((e,n)=>S(y({},e),{[dx(n)]:Y(t[n])}),{}):t}var Yt=class extends Error{constructor(n,o){super(n);this.body=o;this.name="CustomError"}};var ni=t=>new Promise(e=>{setTimeout(e,t)});var en=class extends Yt{constructor(){super(...arguments);this.name="ClientError"}},ri=class extends Yt{constructor(){super(...arguments);this.name="ServerError"}},oi=new Map;function cx(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 et=class et{constructor(e="",n={}){this.baseUrl=e;this.options=n;this.latestRequestByUrl={};var o;this.fetch=(o=n.fetch)!=null?o:window.fetch.bind(window)}patchFetch(e){this.fetch=e(this.fetch)}setCsrfToken(e){this.csrfToken=e}request(e,n={}){return new Promise((o,r)=>{let s={isAborted:!1,reject:r},i=`${this.baseUrl}${e}`,a=this.fetch,d=n.method===void 0||n.method.toLowerCase()==="get",N=n,{useCache:l=!1,abortLatest:c=!1,attempts:u=1,retryDelay:p=500,refreshTokenOn401:g=!0,retryOnError:f=_=>_ instanceof TypeError,retryOnResponse:m=_=>_.status>=500,version:h=null}=N,C=A(N,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]);if(l){if(!d)throw new Error(`Can't use 'useCache' for ${n.method}`);if(oi.has(i)){o(oi.get(i));return}}let T=S(y({credentials:"include"},C),{headers:y({Accept:"application/json","Content-Type":"application/json"},C.headers)});!d&&this.csrfToken&&(T.headers=S(y({},T.headers),{"X-CSRFToken":this.csrfToken})),typeof h=="string"&&(T.headers=S(y({},T.headers),{"X-Deepdesk-API-Version":h}));let b=u,w=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[i]&&c&&(this.latestRequestByUrl[i].isAborted=!0,this.latestRequestByUrl[i].reject(new Error("Aborted"))),this.latestRequestByUrl[i]=s;let I=()=>v(this,null,function*(){return b--,a(i,T).then(_=>v(this,null,function*(){return m(_)&&!s.isAborted&&b>0?(yield ni(p),I()):_.status===401&&g===!0&&w===!1?(w=!0,yield this.refreshToken(),I()):_})).catch(_=>v(this,null,function*(){if(f(_)&&!s.isAborted&&b>0)return yield ni(p),I();throw _}))});I().then(_=>v(this,null,function*(){let W=yield cx(_);if(delete this.latestRequestByUrl[i],_.status>=500){r(new ri("Server Error",W));return}if(_.status===401){r(new en("Unauthorized",W));return}if(_.status===403){r(new en("Forbidden",W));return}if(_.status===404){r(new en("Not Found",W));return}if(_.status>=400){r(new en("Bad Request",W));return}l&&oi.set(i,W),o(W)})).catch(_=>{r(_)})})}validateToken(){return v(this,null,function*(){let{has_valid_access_token:e,is_logged_in:n}=yield this.get("/apis/admin/session/validate/");if(!e)try{yield this.refreshToken();let{is_logged_in:o}=yield this.get("/apis/admin/session/validate/");return o}catch(o){return!1}return n})}refreshToken(){return et.refreshingToken||(et.refreshingToken=this.get("/apis/admin/session/refresh/",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{et.refreshingToken=null},1e3*60)})),et.refreshingToken}get(e,n){return this.request(e,n)}post(e,n,o){return this.request(e,y({method:"POST",body:JSON.stringify(n)},o))}patch(e,n,o){return this.request(e,y({method:"PATCH",body:JSON.stringify(n)},o))}put(e,n,o){return this.request(e,y({method:"PUT",body:JSON.stringify(n)},o))}delete(e,n){return this.request(e,y({method:"DELETE"},n))}};et.refreshingToken=null;var tn=et;var ep;(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={}))})(ep||(ep={}));function si(t){return S(y({},B(t)),{metadata:t.metadata})}var Ct=class Ct{constructor(e,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new tn(e,{fetch:n.fetch}),this.client.patchFetch(o=>(r,s)=>v(this,null,function*(){let i=yield o(r,s);return this.handleDeepdeskVersionHeaders(i),i}))}preflight(){return v(this,null,function*(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let e=yield this.getCsrfToken();this.client.setCsrfToken(e)}return this.options.token?(Ct.exchangeTokenPromise||(Ct.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),Ct.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",S(y({chat_start_time:new Date().toISOString()},Y(e)),{metadata:(o=e.metadata)!=null?o:{}}));return si(n)})}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/",Y(e))})}patchMe(e){return v(this,null,function*(){yield this.preflight();let n=yield this.client.patch("/apis/admin/session/me/",Y(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:r=1,retryDelay:s=1e3}=n,i=yield this.client.get(`/api/v2/conversations/by_external_id/${e}`,{attempts:r,retryDelay:s,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"});return k.info(`Successfully retrieved conversation ${i.id} for session ${e}`),si(i)})}isConversationSupported(o){return v(this,arguments,function*(e,n={}){k.info(`Check if conversation for session ${e} is supported`);let{attempts:r=1,retryDelay:s=1e3}=n;return(yield this.client.get(`/api/v2/conversations/by_external_id/${e}/has_active_profile`,{attempts:r,retryDelay:s,retryOnResponse:a=>a.status===404||a.status>=500})).has_active_profile})}updateConversation(e,n){return v(this,null,function*(){var s;yield this.preflight();let o=Y(n);n.metadata&&(o.metadata=(s=n.metadata)!=null?s:{});let r=yield this.client.put(`/api/v2/conversations/${e}`,o);return si(r)})}postMessages(e,n){return v(this,null,function*(){yield this.preflight(),yield this.client.post(`/api/v2/conversations/${e}/messages`,n.map(o=>S(y({},Y(o)),{metadata:o.metadata})))})}sendEvent(e,n){return v(this,null,function*(){yield this.preflight();let a=n,{data:o}=a,r=A(a,["data"]),s=Object.entries(this.latestReceivedDeepdeskVersions).reduce((d,[l,c])=>S(y({},d),{[l]:c}),{}),i=["platform","agentId","agentName","agentEmail","conversationId"].reduce((d,l)=>(r[l]&&(d[l]=r[l]),d),{});return this.client.post("/api/v2/events",Y(S(y(y({},s),i),{data:o,name:e})),{version:"v2"})})}getEntities(e){return v(this,null,function*(){return yield this.preflight(),yield this.client.post("/api/v2/entities",{messages:e.filter(o=>o.text)})})}getTemporaryExchangeToken(){return v(this,null,function*(){return(yield this.client.get("/apis/admin/session/exchange-token/")).jwt})}exchangeTokenForAccessCookie(e){return v(this,null,function*(){return this.client.post("/apis/admin/session/jwt/",{jwt:e}).catch(n=>{throw 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/",Y(n),{refreshTokenOn401:!1,headers:{apikey:e}})})}getTextSuggestions(r){return v(this,arguments,function*(e,n={},o){if(yield this.preflight(),o==="sticky-messages")throw new Error("Use getPinnedMessages instead");return(yield this.client.post(`/api/v2/conversations/${e}/recommend/${o}`,Y(n),{abortLatest:!0})).map(i=>S(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`,Y(n),{abortLatest:!0})).map(r=>({score:1,source:r.source,sourceText:r.source_text,text:r.label,trainingJobs:r.training_jobs,searchKeywords:r.search_keywords,type:r.source})).filter((r,s,i)=>s===i.findIndex(a=>a.text===r.text))})}getPinnedMessages(e){return v(this,null,function*(){let n=yield this.client.get(`/api/v2/profiles/${e}/pinned-messages`,{abortLatest:!0});return B(n).map(o=>S(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",Y(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`,Y(e));return B(n)})}requestLoginByEmail(e){return v(this,null,function*(){yield this.preflight();let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:e});return 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 i;yield this.preflight();let o=new URLSearchParams;n!=null&&n.externalConversationId&&o.append("external_conversation_id",n.externalConversationId);let r=n!=null&&n.threadId?`/api/v2/assistants/${e}/threads/${n==null?void 0:n.threadId}/evaluate?${o.toString()}`:`/api/v2/assistants/${e}/evaluate?${o.toString()}`,s=yield this.client.post(r,{input:(i=n==null?void 0:n.input)!=null?i:{},conversation:n==null?void 0:n.transcript});return B(s)})}createAssistantThread(e){return v(this,null,function*(){yield this.preflight();let{assistantCode:n}=e,o=yield this.client.post(`/apis/admin/assistants/${n}/threads/`,{});return B(o)})}postMessageToAssistantThread(e){return v(this,null,function*(){yield this.preflight();let{assistantCode:n,threadId:o,message:r}=e,s=yield this.client.post(`/apis/admin/assistants/${n}/threads/${o}/messages/`,{content:r,role:"user"});return B(s)})}translateMessages(e){return v(this,null,function*(){yield this.preflight();let n=yield this.client.post("/api/v2/translate",Y(e));return B(n)})}handleDeepdeskVersionHeaders(e){e.headers.forEach((n,o)=>{let r=o.toLowerCase(),s=r.match(Di);if(!n||!s)return;let i=s[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&n&&a!==n&&k.warn(`Overwritten Version header ${r}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[i]=n})}};Ct.exchangeTokenPromise=null;var tt=Ct;import{combineReducers as yx,configureStore as vx}from"@reduxjs/toolkit";import{createSlice as px}from"@reduxjs/toolkit";var tp={startTime:null,stopTime:null},np=t=>t.handlingTime,op=px({name:"handlingTime",initialState:tp,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(V,()=>tp)}}),{handlingTimeStart:rp,handlingTimeStop:fr,handlingTimeReset:sp}=op.actions,ip=op.reducer;var ap=(t={})=>{let e=y({onAuthError:Pt(!1)},t);return n=>o=>r=>("error"in r&&r.error.message==="Unauthorized"&&n.dispatch(e.onAuthError),o(r))};import{createAsyncThunk as ux,createSlice as mx}from"@reduxjs/toolkit";var hr={list:{keywordMatches:[]},fetchState:"idle"};var Tt=ux("styleSuggestions/getAll",(n,o)=>v(null,[n,o],function*({text:t},e){var d;let{deepdeskAPI:r}=e.extra,s=e.getState(),{showStyleSuggestions:i}=s.settings,a=(d=s.conversation.current)==null?void 0:d.profileCode;if(!i)return hr.list;if(!a)throw new Error("No current conversation to fetch pinned messages");return r.getStyleSuggestions({profileCode:a,message:t})})),gx=mx({name:"styleSuggestions",initialState:hr,reducers:{},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",$e(e.list,n.payload)||(e.list=n.payload)}).addCase(at,e=>{e.list=hr.list}).addCase(V,()=>hr)}}),lp=gx.reducer;var dp=(t={})=>{let e,n=!0,o=y({getStyleSuggestions:Tt,debounce:500},t);return r=>s=>i=>{var g;let a=r.getState().input.text,d=s(i),l=r.getState();if(l.auth.isLoggedIn!==!0)return d;let{showStyleSuggestions:c}=l.settings;if(!((g=l.conversation.current)==null?void 0:g.id)||!c)return d;let{text:p}=l.input;return p===a&&!n||(clearTimeout(e),p==="")||(e=setTimeout(()=>{n=!1,r.dispatch(o.getStyleSuggestions({text:p}))},t.debounce)),d}};function fx(t,e){return t.text===e.text&&t.selection.start===e.selection.start&&t.selection.end===e.selection.end}var cp=(t={})=>{let e=y({getTextSuggestions:he,getAutocompleteSuggestions:Mn,debounce:200,check:Te},t),n;return o=>r=>s=>{var m;let{input:i}=o.getState(),a=r(s),d=o.getState();if(d.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:l,showTabCompletion:c}=d.settings,u=(m=d.conversation.current)==null?void 0:m.id,p=s.type===Ao.toString();if(!u||!l&&!c)return a;let{input:g}=d;return fx(g,i)&&!p||(clearTimeout(n),!e.check(d))||(n=setTimeout(()=>{let h=At(d);h===""?o.dispatch(e.getTextSuggestions("default")):o.dispatch(e.getAutocompleteSuggestions(h))},p?0:e.debounce)),a}};var pp=Tt.fulfilled.toString();function hx(t,e){let n=new Set([...e.keywordMatches.map(r=>r.keyword)]),o=[];return n.forEach(r=>{let s=t.keywordMatches.filter(d=>d.keyword===r),i=e.keywordMatches.filter(d=>d.keyword===r),a=i.length-s.length;a<=0||o.push(...i.slice(0,a))}),o}var up=t=>e=>n=>o=>{var l;if(o.type!==pp){n(o);return}let r=e.getState().styleSuggestions.list;n(o);let s=e.getState(),i=s.styleSuggestions.list,a=(l=s.conversation)==null?void 0:l.current;if(r===i)return;let d=hx(r,i);o.type===pp&&d.length>0&&t.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:d}})};var xx=yx({assistants:tc,auth:ji,conversation:Qi,contentTypes:$a,passwordlessToken:sc,entities:Tl,handlingTime:ip,info:Sa,input:ca,settings:Hi,profile:Qa,search:ka,styleSuggestions:lp,ui:Yl,textSuggestions:Fl});function mp(t){return vx({reducer:xx,middleware:e=>{var o;let n=e({thunk:{extraArgument:{dynamicThunkObject:t.dynamicThunkObject,deepdeskAPI:t.deepdeskAPI}},serializableCheck:!1}).concat(ap()).concat(cp({debounce:200})).concat(dp({debounce:500})).concat(up(t.deepdeskAPI));return((o=t.middleware)!=null?o:[]).reduce((r,s)=>r.concat(s),n)},preloadedState:t.preloadedState})}var Sx=t=>{var e,n;return(n=(e=t==null?void 0:t.type)==null?void 0:e.toLowerCase())!=null?n:"unknown"},bx=t=>e=>n=>o=>{var a,d;let r=e.getState(),s=Rt("inlineSuggestions")(r);switch(o.type){case Pt.toString():{!o.payload&&t.emit("logout",void 0);break}case fe.fulfilled.toString():o.payload.length>0&&t.sendEvent("entities found",{conversationId:(a=r.conversation.current)==null?void 0:a.id,data:{entities:o.payload}});break;case at.toString():t.logSendMessage(o.payload);break;case Qo.toString():t.emit("call-to-action",{cue:o.payload});break;case Ee.fulfilled.toString():o.isBroadcasted||t.broadcast(Ur,o,!1);break;default:break}let i=n(o);switch(o.type){case at.toString():t.handleAfterSendMessage(o.payload);break;case Nn.toString():t.onUpdateShowTabHint(o.payload);break;case fr.toString():t.logHandlingTime();break;case Nt.toString():t.broadcast(uo,o);break;case it.toString():t.broadcast(uo,o);break;case Zo.toString():e.dispatch(it({source:"assistant",assistantCode:o.payload.code}));break;case"analytics/logEvent/fulfilled":{let l=r.assistants.cues.find(c=>c.code===o.meta.arg.data.assistantCode);t.emit("event",S(y({},o.meta.arg),{cue:l}));break}case re.toString():{let{start:l,end:c}=r.input.selection;t.emit("select-suggestion",S(y({type:Sx(o.payload.suggestion)},o.payload),{replace:o.payload.replace==="selection"?{start:l,end:c}:{start:0,end:c}})),s&&e.dispatch(Ge([]));break}case oo.toString():t.emit("select-image",o.payload),t.sendEvent("Image attached",{conversationId:(d=r.conversation.current)==null?void 0:d.id,data:{path:o.payload.suggestion.image,title:o.payload.suggestion.title}});break;case Ge.toString():{s&&o.payload.length>0&&e.dispatch(ro(0));break}default:break}return i},gp=bx;import{createSelector as Cx}from"@reduxjs/toolkit";function ii(t){return t.toISOString().replace("T"," ").replace("Z","")}var Tx=(t,e)=>e.version,fp=Cx([Ot,xe,np,Tx],(t,e,n,o)=>{if(!e)return k.warn("No conversationId for handling time metrics"),null;let{startTime:r,stopTime:s}=n;return!r||!s?(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:ii(r),timeStop:ii(s)}});function hp(t,e){let{text:n,metrics:{numPaste:o,pastes:r,textSuggestions:s}}=t.input,i=n.length;return{source:"agent",clientVersion:e.version,pastes:r,lenTextTotal:i,numPastes:o,suggestions:s}}function ai(t,e){var s;let n=t.closest(e);if(n)return n;let o=t.getRootNode().host;if(o instanceof HTMLElement)return ai(o,e);let r=(s=t.ownerDocument.defaultView)==null?void 0:s.frameElement;return r?ai(r,e):null}function li(t,e){return ai(t,e)}function yp(t){return typeof t=="object"&&t!==null&&"name"in t&&"message"in t}function wx(t){return typeof t=="object"&&t!==null&&"tagName"in t}function di(t){return wx(t)&&(yt(t)||Uo(t))}var xp,ke=new Map,Ex=["bottom","height","left","right","top","width"],vp=(t,e)=>!t&&!e?!1:t&&!e||!t&&e?!0:Ex.some(n=>t[n]!==e[n]);function Sp(t){var n,o,r;if(t.ownerDocument===document)return[];let e=(r=(o=(n=t.ownerDocument)==null?void 0:n.defaultView)==null?void 0:o.frameElement)!=null?r:null;return e?[e,...Sp(e)]:[]}function bp(t,e){return!t||!e?null:S(y({},t),{top:t.top+e.top,left:t.left+e.left})}var yr=!1,Cp=()=>{yr=!0;let t=[];if(ke.forEach((e,n)=>{if(!n.isConnected){e.rect=null,t.push(e),ke.delete(n);return}let o=n.getBoundingClientRect();vp(o,e.rect)&&(e.rect=o,t.push(e))}),t.forEach(e=>{let n=e.parentRects?e.parentRects.reduce(bp,e.rect):e.rect;vp(n,e.totalRect)&&e.callbacks.forEach(o=>o(n)),e.totalRect=n}),ke.size===0){yr=!1;return}xp=window.requestAnimationFrame(Cp)};function ci(t,e){let n=Sp(t),o=[],r=n.map((s,i)=>ci(s,a=>{o[i]=a;let d=ke.get(t);if(!d)return;let l=o.reduce(bp,d.rect);d.callbacks.forEach(c=>c(l))}));return{observe(s=!0){if(r.forEach(i=>i.observe(!1)),ke.has(t)){let i=ke.get(t);i.callbacks.push(e),i.rect&&e(i.rect)}else ke.set(t,{rect:void 0,callbacks:[e],parentRects:o});s&&!yr&&Cp()},unobserve(){r.forEach(i=>i.unobserve());let s=ke.get(t);if(s){let i=s.callbacks.indexOf(e);i>=0&&s.callbacks.splice(i,1),s.callbacks.length||ke.delete(t),ke.size||(cancelAnimationFrame(xp),yr=!1)}}}}var Tp,Re=new Map,wp=()=>{Re.forEach((t,e)=>{if(!e.isConnected){Re.delete(e);return}let{clientHeight:n,scrollHeight:o}=e,r=o>n;t.visible!==r&&(t.visible=r,t.callbacks.forEach(s=>s(t.visible)))}),Re.size!==0&&(Tp=window.requestAnimationFrame(wp))};function Ep(t,e){return{observe(){let n=Re.size===0;Re.has(t)?Re.get(t).callbacks.push(e):Re.set(t,{visible:void 0,callbacks:[e]}),n&&wp()},unobserve(){let n=Re.get(t);if(n){let o=n.callbacks.indexOf(e);o>=0&&n.callbacks.splice(o,1),n.callbacks.length||Re.delete(t),Re.size||cancelAnimationFrame(Tp)}}}}var pi=["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 ui(t,e,n){return n.forEach(o=>{e.style[o]=t[o]})}function nn(t){return Number.parseFloat(t)}function vr(t){return Math.round(t*1e6)}function kp(t){return t/1e6}function mi(t,e,n){if(t.boxSizing==="content-box")return;let{clientWidth:o}=e,r=nn(t.width),s=nn(t.borderLeftWidth),i=nn(t.borderRightWidth),a=nn(t.paddingRight),d=kp(vr(r)-vr(s)-vr(i)),l=kp(vr(o));if(d-l>2){let c=d-l;n.style.paddingRight=`${a+c}px`}}function xr(t,e={}){var c,u;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",ft(n);let o=window.getComputedStyle(t),r=!0,s=()=>{n.scrollTop=t.scrollTop};ui(o,n,pi),mi(o,t,n),e.mirrorOverflow&&(n.style.overflow="hidden",t.addEventListener("scroll",s));let i=Ep(t,()=>{ui(o,n,pi),mi(o,t,n),s(),setTimeout(s,0)}),a,d=!0,l=ci(t,p=>{if(p===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),p.height===0&&p.width===0){if(r===!0)return;e.onHide&&e.onHide(),n.style.display="none",r=!0;return}if(ui(o,n,pi),mi(o,t,n),s(),e.placement==="below"&&n.classList.add("below"),n.style.top=`${p.top}px`,n.style.left=`${p.left}px`,e.closestScrollElement&&e.closestScrollElement!==t){let g=e.closestScrollElement.getBoundingClientRect(),f=window.getComputedStyle(e.closestScrollElement),m=nn(f.borderTopWidth),h=nn(f.borderBottomWidth),C=g.top+m-p.top,T=p.top+p.height+-(g.top+g.height-h);n.style.clipPath=`inset(${C}px 0px ${T}px 0px)`}r&&(n.style.display="block",e.onShow&&e.onShow(),r=!1)});return e.appendTo?e.appendTo.appendChild(n):(u=t.parentElement)==null||u.appendChild(n),l.observe(),i.observe(),[n,()=>{t.removeEventListener("scroll",s),l.unobserve(),i.unobserve(),n.remove()}]}var Rp=(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")}}});function kx(t){return t.offsetParent!==null}function Pp(t){if(!kx(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 gi(t,e,n=100){let o=Pp(t);e({isVisible:o});let r=setInterval(()=>{let s=Pp(t);s!==o&&(o=s,e({isVisible:o}))},n);return()=>{clearTimeout(r)}}var zn=class extends Error{};function Rx(){let t,e;return{promise:new Promise((o,r)=>{t=o,e=r}),resolve:t,reject:e}}var Sr=class{constructor(){this.queues={}}push(e,n){let o=()=>{let s=this.queues[e][1];s?(this.queues[e]=[s.promise,null],s.resolve()):delete this.queues[e]};if(!this.queues[e]){let s=n().finally(o);return this.queues[e]=[s,null],s}this.queues[e][1]&&this.queues[e][1].reject(new zn("Queued async function is outdated"));let r=Rx();return this.queues[e][1]=r,r.promise.then(()=>n().finally(o))}};var Px={accepted:"onConversationAcceptedAssistants","new-message":"onConversationNewMessageAssistants",ended:"onConversationEndedAssistants"},Ip=(t,e)=>{var r,s,i;if(!((i=(s=(r=t.uiConfig)==null?void 0:r.widget)==null?void 0:s.types.find(a=>a.type==="cues"))==null?void 0:i.isActive))return k.warn("Triggered a conversation assistant, but cues are not configured in widget."),[];let o=t[Px[e]];return o&&o.length>0?o.map(a=>a.code):(k.warn(`No assistant set in profile for conversation event "${e}"`),[])};var br=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(r=>r(o.data)))}catch(o){console.error("Error parsing WebSocket message:",o)}},this.socket.onclose=e=>{console.log("WebSocket connection closed:",e),setTimeout(()=>{this.reconnect()},this.reconnectInterval)},this.socket.onerror=e=>{console.error("WebSocket error:",e)})}reconnect(){var e,n;if(this.maxReconnectAttempts<=0){console.error("Max reconnect attempts reached, closing WebSocket connection."),(e=this.socket)==null||e.close();return}if(!this.shouldReconnect()){console.error("Should not reconnect, closing WebSocket connection."),(n=this.socket)==null||n.close();return}this.socket&&(this.socket.onmessage=null,this.socket.onclose=null,this.socket.onerror=null,this.socket.close()),this.socket=new WebSocket(this.url),this.setupListeners(),this.maxReconnectAttempts--}send(e,n){if(!this.socket){console.error("WebSocket connection is not open.");return}this.socket.send(JSON.stringify({event:e,data:n}))}on(e,n){this.eventListeners.has(e)||this.eventListeners.set(e,[]);let o=this.eventListeners.get(e);o&&!o.includes(n)&&o.push(n)}close(){var e;(e=this.socket)==null||e.close()}cleanup(){this.close(),this.cleanupCallbacks.forEach(e=>e()),this.cleanupCallbacks=[]}};import Ax,{useState as hi,useEffect as Mx}from"react";var Lp={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 Nx}from"react-redux";var fi={};X(fi,{enUS:()=>Ix,nlNL:()=>Lx});var Ix={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."}]},Lx={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 Ox,jsx as ve,jsxs as Cr}from"react/jsx-runtime";var Ap=({onClose:t,onSave:e,id:n,error:o})=>{let[r,s]=hi(""),[i,a]=hi(!1),[d,l]=hi(!1),c=x("Nickname",Lp),u=Ax.useRef(null),p=Nx(C=>C.info.showNicknameDialog),g=R(fi),f=E("adminUrl");Mx(()=>{o&&a(!0)},[o]);let m=()=>{if(!u.current)return;r.trim()?u.current.setCustomValidity(""):u.current.setCustomValidity(g("nicknameDialogError")),u.current.reportValidity()},h=C=>{C.preventDefault();let T=r.trim(),b=C.currentTarget.querySelector("#nickname-input");if(!T){b.setCustomValidity(g("nicknameDialogError")),b.reportValidity();return}b.setCustomValidity(""),e(T)};return Cr(Ft,{isOpen:p,"datatest-id":n,onClose:t||(()=>{}),onBack:t||(()=>{}),children:[ve("div",{className:c.titleWrapper,children:ve("h1",{className:c.title,children:g("title")})}),Cr("form",{className:c.dialogContent,onSubmit:h,children:[ve("p",{children:g("nicknameDialogTitle")}),i&&o&&ve("div",{className:c.errorMessage,children:f?(()=>{let C=g("nicknameDialogSaveError",{account:f}),T=`${f}.deepdesk.com/admin/user-settings`,b=C.indexOf(T);if(b!==-1){let w=C.substring(0,b),I=C.substring(b+T.length);return Cr(Ox,{children:[w,ve("a",{href:T,target:"_blank",rel:"noopener noreferrer",className:c.errorLink,children:T}),I]})}return C})():g("nicknameDialogSaveErrorWithoutLink")}),ve("input",{required:!0,minLength:1,maxLength:20,"data-testid":"nickname-input",id:"nickname-input",className:c.nicknameInput,type:"text",placeholder:g("nicknameDialogInputPlaceholder"),value:r,onChange:C=>{l(new RegExp("\\p{Extended_Pictographic}","u").test(C.target.value)),s(C.target.value)},onBlur:m,ref:u}),d&&ve("div",{className:c.errorMessage,role:"alert",children:g("nicknameDialogEmojiError")}),Cr("div",{className:c.buttonsWrapper,children:[o?ve("div",{className:c.closeButtonWrapper,children:ve("button",{type:"button",className:c.closeButton,onClick:()=>t==null?void 0:t(),children:g("close")})}):null,ve("div",{className:c.buttonContinueWrapper,children:ve("button",{type:"submit",className:c.continueButton,disabled:!r.trim()||new RegExp("\\p{Extended_Pictographic}","u").test(r),children:g("nicknameDialogContinueButton")})})]})]})]})};import{jsx as F,jsxs as Dx}from"react/jsx-runtime";var Mp=Rp("showTabHint",!0),on=class on{constructor({deepdeskUrl:e,version:n=on.version||"unknown",locale:o="en-US",token:r,fetch:s,productName:i,createCustomChannel:a,websocketClient:d=br}){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 Sr;this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;let l=e.replace(/\/api$/,"");this.deepdeskApi=new tt(l,{token:r,fetch:s}),this.version=n,this.instanceId=on.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[gp({broadcast:(f,m,h)=>{this.broadcastEvents.send(f,m,h)},emit:(f,m)=>this.emit(f,m),handleAfterSendMessage:f=>this.handleAfterSendMessage(f),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:f=>this.logSendMessage(f),onUpdateShowTabHint:f=>Mp.update(f),sendEvent:(f,m)=>this.deepdeskApi.sendEvent(f,m)})]};this.store=mp(c),this.broadcastEvents=new Yc({debug:!0,deepdeskUrl:l,eventMap:Ra(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 f;return(f=J(this.state))!=null?f:!1})}),this.whenLoggedIn(()=>this.ws.connect()),this.store.dispatch(Nn(Mp.value())),this.store.dispatch(Zn({locale:o,adminUrl:l,productName:i}));let u=[],p=f=>{if(!f.conversationId)return;let m=()=>{this.conversationId()===f.conversationId&&this.store.dispatch(ec(f))};this.hasConversation()?m():u.push(m)};this.ws.on("assistants::direct_response",p),this.ws.on("assistants::user_notification",p),this.ws.on("assistants::response_chunk",f=>{if(!f.conversationId)return;let m=()=>{this.conversationId()===f.conversationId&&this.store.dispatch(Yd(f))};this.hasConversation()?m():u.push(m)}),this.ws.on("assistants::suggest_as_reply",f=>{if(!f.conversationId)return;let m=()=>{this.conversationId()===f.conversationId&&this.store.dispatch(Nt([{text:f.payload.message,type:"text",source:"assistant",assistantCode:f.code,sourceLabel:f.name}]))};this.hasConversation()?m():u.push(m)});let g=this.whenConversationLoaded(()=>{var f;this.broadcastEvents.setExternalId((f=this.state.conversation.current)==null?void 0:f.externalId),u.forEach(m=>m()),u.length=0});this.disposeHandlers.push(()=>{this.ws.cleanup(),u.length=0,g()})}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){var e;return(e=st(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(J(this.state))e();else{let n=this.subscribe(J,o=>{o&&e()});this.disposeHandlers.push(()=>{n()})}}login(){return this.store.dispatch(Pt(null)),this.store.dispatch(Le()),new Promise(e=>{this.whenLoggedIn(()=>e())})}isLoggedIn(){return v(this,null,function*(){return(yield this.store.dispatch(Le())).payload})}isConversationSupported(e,n){return v(this,null,function*(){return(yield this.store.dispatch(Nr({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(eo(S(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(to({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(Or(S(y({},e),{metadata:(o=e.metadata)!=null?o:{}})))).payload})}postMessages(e){return v(this,null,function*(){yield this.store.dispatch(Dr(e))})}updateConversation(e){return v(this,null,function*(){return(yield this.store.dispatch(no(e))).payload})}resetConversation(){this.store.dispatch(V()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}configure(e){this.store.dispatch(Zn(e))}setVisitorInfo(e){this.store.dispatch(ha(e))}setCustomData(e){this.store.dispatch(ya(e))}setAgentInfo(e,n){return v(this,null,function*(){var r;yield this.store.dispatch(pn(y(y({},e),n))),((r=this.state.info.agentInfo)==null?void 0:r.agentNickname)||this.broadcastEvents.send(po,{showNicknameDialog:!0})})}setAgentSettings(e){return v(this,null,function*(){yield this.store.dispatch(Fr(e))})}getAgentSettings(){return v(this,null,function*(){return(yield this.store.dispatch(Hr())).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(so({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()}))}notifyExternalSuggestion(e){this.store.dispatch(re(e))}evaluateAssistant(e,n){return v(this,null,function*(){var d;let{input:o={},transcript:r,showCuesInWidget:s=!0,includeMetadata:i}=n||{},a=yield this.store.dispatch(Ee({assistantCode:e,transcript:r,includeMetadata:i,input:o,skipState:!s}));if(a.error)throw new Error(`Assistant evaluation failed: ${(d=a.payload)!=null?d:a.error.message}`);return a.payload.output})}evaluateConversationAssistant(e,n){return v(this,null,function*(){yield this.loadProfileConfig();let o=this.state.profile.data;if(!o){k.warn("Can't evaluate assistant when profile is not loaded yet.");return}let r=Ip(o,e);yield Promise.all(r.map(s=>this.queues.push(s,()=>v(this,null,function*(){yield this.evaluateAssistant(s,y({includeMetadata:!0},n))})).catch(i=>{if(i instanceof zn){k.warn(`Queued assistant "${s}" was outdated and dropped`);return}throw i})))})}handleKeyDown(e){let{overlayCollapsed:n,openOverlayWhenTyping:o}=this.state.ui,{textSuggestions:r,selectedSuggestionIndex:s,selection:i}=this.state.input,{inlineSuggestions:a,showTextSuggestions:d,suggestionsPlacement:l}=this.settings,c=l==="inline"||l==="below"?"below":"above",u=r.length>0;if(this.store.dispatch(oa(_r(e))),!Te(this.state)||e.key!=="Tab"&&!d)return;let p=()=>{n||!u||i&&(e.shiftKey||(this.store.dispatch(ia()),e.preventDefault()))},g=()=>{n||!u||a&&s<=0||i&&(e.shiftKey||(this.store.dispatch(aa()),e.preventDefault()))};switch(e.key){case"ArrowUp":c==="below"?g():p();break;case"ArrowDown":{c==="below"?p():g();break}case"Escape":{n||(this.store.dispatch(ro(-1)),this.store.dispatch(Je({collapse:!0})),this.store.dispatch(Ql(!0)),e.preventDefault());break}case"Tab":{e.preventDefault();let f=Mt(this.state);if(!f)return;this.store.dispatch(Nn(!1)),this.store.dispatch(re({text:f.text,suggestion:f,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(this.settings.inlineSuggestions||this.state.input.selectedSuggestionIndex===-1)return;let f=Mt(this.state);if(!f)return;this.store.dispatch(re({text:f.text,suggestion:f,eventMetrics:{inputType:"space"},replace:"until-selection-end"}));break}case"Enter":{if(this.settings.inlineSuggestions||e.shiftKey||this.state.input.selectedSuggestionIndex===-1)return;let f=Mt(this.state);if(!f)return;this.store.dispatch(re({text:f.text,suggestion:f,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),e.preventDefault();break}default:}n&&o&&this.store.dispatch(Je({collapse:!1}))}handleAfterSendMessage(e){this.emit("send-message",e),this.store.dispatch(Ge([]))}handlingTimeStart(){this.state.handlingTime.startTime||(k.info("Start handling time"),this.store.dispatch(rp()))}handlingTimeStop(){this.state.handlingTime.startTime&&(k.info("Stop handling time"),this.store.dispatch(fr()))}logSendMessage(e){let n=hp(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=fp(this.state,{version:this.version});e&&(this.deepdeskApi.sendEvent("Handling Time",{conversationId:this.conversationId(),data:e}),this.store.dispatch(sp()))}notifySubmit(e={}){var n;this.shouldAbort()||(this.store.dispatch(at((n=e.text)!=null?n:this.state.input.text)),this.store.dispatch(da()))}emit(e,n){let o=this.eventListeners[e];o&&o.forEach(r=>{try{r(n)}catch(s){k.warn(`The following error occurred in deepdeskSDK.on('${e}', handler)`),k.error(s)}})}on(e,n){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(n),()=>{this.off(e,n)}}off(e,n){if(!e&&!n){this.eventListeners={};return}let o;this.eventListeners[e]&&(o=this.eventListeners[e].indexOf(n),o>-1&&this.eventListeners[e].splice(o,1))}setConversationQuery(e){this.dynamicThunkObject.conversationQuery=e}setPlatformVariables(e){this.store.dispatch(va(e))}whenConversationLoaded(e){let n=s=>{var i;return(i=s.conversation.current)==null?void 0:i.id},o=()=>this.loadProfileConfig().then(()=>e());return n(this.state)&&o(),this.subscribe(n,s=>{s&&o()})}overlayContainerFactory(e,n,o,r){let[s,i]=xr(n,o);return s.setAttribute("translate","no"),s.dataset.testid=e,r&&s.classList.add(r),[s,i]}createInlineContainer(e,n){var a;let o=document.createElement("div");o.style.position="absolute",o.style.top="0px",o.style.left="0px",o.style.height="0px",o.style.width="0px";let r=document.createElement("div");r.style.display="none",r.style.position="absolute",r.style.height="0px",r.style.width="0px",r.style.backgroundColor="red",o.appendChild(r);let s=(a=e.ownerDocument.defaultView)==null?void 0:a.frameElement,i=s?s.ownerDocument.defaultView:null;if(s&&(i===window||(i==null?void 0:i.parent)===window)){let[d,l]=xr(s,{appendTo:document.body,onMoveStart:()=>{r.style.display="none"}});d.dataset.testid=n,d.style.zIndex="2",d.appendChild(o),this.unmountHandlers.push(()=>{l()})}else document.body.appendChild(o);return r}createContainer(e,n=document.body){let o=window.getComputedStyle(n),r=document.createElement("div");return ft(r),r.dataset.testid=e,r.style.color=o.color,r.style.fontSize=o.fontSize,r.style.fontFamily=o.fontFamily,r.style.fontVariant=o.fontVariant,r.setAttribute("translate","no"),n.appendChild(r),r}storeMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,n=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(e,n),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(la(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(!di(e))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let p=n,{customStyles:o,closestScrollSelector:r,floatingMenuParent:s,appendOverlayTo:i,inputMediator:a}=p,d=A(p,["customStyles","closestScrollSelector","floatingMenuParent","appendOverlayTo","inputMediator"]),l={customStyles:o,closestScrollSelector:r,floatingMenuParent:s,appendOverlayTo:i};this.configure(d),this.settings.automaticHandlingTime&&this.setupHandlingTime(e),ft(e),this.inputMediator=a||(yt(e)?new Zt(e):new Qt(e)),this.inputMediator.on("change",({plainText:g,rawHTML:f})=>{this.store.dispatch(so({text:g,html:f}))}),this.inputMediator.on("keyup",g=>{this.store.dispatch(ra(_r(g)))}),this.inputMediator.on("keydown",g=>{this.handleKeyDown(g)}),this.inputMediator.on("paste",({pastedText:g,selectionText:f})=>{this.store.dispatch(sa({text:g,selectionText:f}))}),this.inputMediator.on("cut",({selectionText:g})=>{this.store.dispatch(na(g))});let c;this.inputMediator.on("selection",g=>{clearTimeout(c),g===null?c=setTimeout(()=>{g!==null&&this.store.dispatch(io(g))},500):this.store.dispatch(io(g))}),this.unmountHandlers.push(()=>{clearTimeout(c)}),this.inputMediator.on("disabled",()=>{var g;(g=this.inputMediator)==null||g.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(Oo(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(Oo(!0))}),this.renderSuggestions(e,l),this.subscribe(Rt("inlineSuggestions"),()=>{this.renderSuggestions(e,l)}),this.subscribe(Rt("suggestionsPlacement"),()=>{this.renderSuggestions(e,l)});let u=this.renderOverlays(n);this.unmountHandlers.push(()=>{u.unmount()}),this.store.dispatch(so({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()})),this.store.dispatch(io(this.inputMediator.getSelection())),this.store.dispatch(Oo(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=nt(n),r=null,s=a=>{r=a,i()},i=()=>{o==null||o.render(F(_e,{store:this.store,children:F(Me,{broadcastEvents:this.broadcastEvents,children:F(Ap,{id:"deepdesk-nickname-dialog",error:r,onSave:a=>v(this,null,function*(){try{yield this.store.dispatch(ga({agentNickname:a})).unwrap(),console.log("setAgentNickname",a),this.broadcastEvents.send(po,{showNicknameDialog:!1}),this.nicknameDialogUnsubscribe&&this.nicknameDialogUnsubscribe()}catch(d){k.error("Error setting agent nickname",d),s("error"),this.nicknameDialogFailed=!0}})})})}))};i(),this.nicknameDialogUnsubscribe=()=>{o.unmount(),n.remove(),this.nicknameDialogUnsubscribe=null}}subscribe(e,n){let o=e(this.store.getState());return this.store.subscribe(()=>{let r=e(this.store.getState());r!==o&&(o=r,n(o))})}unmount(){var e,n,o,r,s;(e=this.inlineSuggestions)==null||e.unmount(),(n=this.aboveSuggestions)==null||n.unmount(),(o=this.belowSuggestions)==null||o.unmount(),(r=this.floatingMenu)==null||r.unmount(),this.unmountHandlers.forEach(i=>i()),this.unmountHandlers=[],(s=this.inputMediator)==null||s.dispose(),this.nicknameDialogUnsubscribe&&this.nicknameDialogUnsubscribe(),this.isMounted=!1}dispose(){this.unmount(),this.unmountWidget(),this.disposeHandlers.forEach(e=>e()),this.disposeHandlers=[],this.off()}renderSuggestions(e,n){var o,r,s,i;(o=this.floatingMenu)==null||o.unmount(),(r=this.inlineSuggestions)==null||r.unmount(),(s=this.aboveSuggestions)==null||s.unmount(),(i=this.belowSuggestions)==null||i.unmount(),this.settings.floatingMenu&&(this.floatingMenu=this.renderFloatingMenu(e,n)),this.settings.inlineSuggestions||this.settings.suggestionsPlacement==="inline"?this.inlineSuggestions=this.renderInlineSuggestions(e,n):this.settings.suggestionsPlacement==="below"?this.belowSuggestions=this.renderAboveOrBelowSuggestions(e,n,"below"):this.aboveSuggestions=this.renderAboveOrBelowSuggestions(e,n,"above")}renderInlineSuggestions(e,n){let{customStyles:o}=n,r=this.createInlineContainer(e,"deepdesk-caret"),s=nt(r);s.render(F(_e,{store:this.store,customStyles:o,children:F(Me,{broadcastEvents:this.broadcastEvents,children:F(dd,{})})}));let i=a=>{a?(r.style.display="block",r.style.top=`${a.top}px`,r.style.left=`${a.left}px`):r.style.display="none"};return this.inputMediator.on("caretposition",i),{unmount:()=>{var a;(a=this.inputMediator)==null||a.off("caretposition",i),s.unmount(),r.remove()}}}renderAboveOrBelowSuggestions(e,n,o){let{customStyles:r,closestScrollSelector:s,appendOverlayTo:i}=n,a=s&&li(e,s)||void 0,[d,l]=this.overlayContainerFactory("deepdesk-tab-completion",a||e,{appendTo:i,closestScrollElement:a,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),[c,u]=this.overlayContainerFactory("deepdesk-suggestions-overlay",a||e,{appendTo:i,placement:o},r==null?void 0:r.suggestionsRootNode),p=nt(d);p.render(F(_e,{store:this.store,customStyles:r,children:F(Me,{broadcastEvents:this.broadcastEvents,children:F(jd,{inputElement:e})})}));let g=nt(c);return g.render(F(_e,{store:this.store,customStyles:r,children:F(Me,{broadcastEvents:this.broadcastEvents,children:F(xd,{onLogIn:()=>this.loginViaPopup().catch(f=>k.warn(f.message))})})})),{unmount(){p.unmount(),g.unmount(),l(),u()}}}renderFloatingMenu(e,n){let{customStyles:o,closestScrollSelector:r,appendOverlayTo:s,floatingMenuParent:i}=n,a=r&&li(e,r)||void 0,[d,l]=this.overlayContainerFactory("floating-menu",a||e,{appendTo:i!=null?i:s},o==null?void 0:o.floatingMenuParent),c=nt(d);return c.render(F(_e,{store:this.store,customStyles:o,children:F(Me,{broadcastEvents:this.broadcastEvents,children:F(Xl,{onLogIn:()=>this.loginViaPopup().catch(u=>k.warn(u.message))})})})),{unmount(){c.unmount(),l()}}}renderOverlays(e){let{customStyles:n}=e,o=this.createContainer("deepdesk-overlays"),r=nt(o);return r.render(F(_e,{store:this.store,customStyles:n,children:F(Me,{broadcastEvents:this.broadcastEvents,children:F(Wl,{})})})),{unmount(){r.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:r,isEmbedded:s,insertLinkAsHtml:i}=n;this.widgetElement=e,this.configure({showImages:r,isEmbedded:s,insertLinkAsHtml:i}),this.widgetRoot=nt(e),this.widgetRoot.render(F(_e,{store:this.store,customStyles:o,children:F(Me,{broadcastEvents:this.broadcastEvents,children:F(Gc,{assistantOptions:n.assistantOptions,knowledgeAssistOptions:n.knowledgeAssist,onLogIn:()=>this.loginViaPopup().catch(a=>k.warn(a.message))})})}))}unmountWidget(){var e,n;(n=(e=this.widgetRoot)==null?void 0:e.unmount)==null||n.call(e),this.widgetRoot=null,this.widgetElement=null}renderKnowledgeAssistantWidget(e,n,o={}){let{customStyles:r,initialQuestion:s}=o,i=nt(n);return i.render(F(_e,{store:this.store,customStyles:r,children:F(Me,{broadcastEvents:this.broadcastEvents,children:F(Zs,{children:Dx(ar,{assistantCode:e,initialQuestion:s,evaluateKnowledgeAssistFn:Dn,children:[F(an,{children:F(dr,{title:o.title,emptyState:o.emptyState})}),F(Qs,{children:F(lr,{})})]})})})})),{unmount(){i.unmount()}}}setupHandlingTime(e){let n=gi(e,({isVisible:o})=>{o?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){yp(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(()=>v(this,null,function*(){yield this.store.dispatch(kn());let e=ct(this.state);e&&this.store.dispatch(Zn({showSearch:e.search,showImageSearch:e.imageSearch,showEntitiesCommand:e.entitiesCommand,showSummaryCommand:!!e.summarizerAssistantNew,showKnowledgeSearch:!!e.knowledgeAssistantNew||!!e.knowledgeAssistant,recommendTextSuggestions:e.recommendTextSuggestions}))})),this.loadProfileConfigPromise)}loginViaPopup(e){return v(this,null,function*(){return new Promise((n,o)=>{this.store.dispatch(Yn());let r=new MessageChannel,s=r.port1,i=this.settings.adminUrl,a=new URL(e!=null&&e.url?e==null?void 0:e.url:`${i}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let d=!1,l=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",u),clearInterval(p)};s.onmessage=g=>v(this,null,function*(){var f,m;if((f=g.data)!=null&&f.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((m=g.data)==null?void 0:m.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(mn),d=!0,r.port1.close(),n()}catch(h){console.error(h),o(h)}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 u=g=>v(this,null,function*(){var f;if(g.origin===a.origin)switch((f=g.data)==null?void 0:f.type){case"deepdesk-popup-request-origin":{try{let m=JSON.stringify({type:"deepdesk-popup-parent-origin"});c==null||c.postMessage(m,a.origin)}catch(m){k.error("Error posting message to popup",m),o(m)}break}case"deepdesk-popup-loaded":{try{let m=JSON.stringify({type:"deepdesk-popup-create-channel"});c==null||c.postMessage(m,a.origin,[r.port2])}catch(m){k.error("Error posting message to popup",m),o(m)}break}case"deepdesk-popup-error":{if(l(),g.data.message==="Platform account url mismatch"){let m=`Please contact your administrator: The platform account url (${g.data.targetOrigin}) is misconfigured as it differs from the origin of the page that opened the popup (${g.data.openerOrigin}).`;k.warn(m),this.store.dispatch(Mr(m)),o(new Error(m))}if(g.data.message==="Timeout"){let m="Please contact your administrator: Popup timed out. Check if the account's platform url is configured correctly.";k.warn(m),this.store.dispatch(Mr(m)),o(new Error(m))}o(new Error(g.data.message));break}}});window.addEventListener("message",u);let p=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(Ao()))})}refreshWidgetSuggestions(){return v(this,null,function*(){if(!this.widgetRoot)return;let{uiConfig:e}=this.state.profile.data;if(!e.widget)return;let n=Rn(this.state);try{n.forEach(({type:o})=>{switch(o){case"entities":this.store.dispatch(fe());break;case"pinned-messages":case"sticky-messages":break;default:Jn.includes(o)||this.store.dispatch(he(o))}})}catch(o){this.handleError(o)}})}};on.version="19.0.2-beta.8",on.count=0;var Tr=on;function _x(t){return v(this,null,function*(){var r,s,i;let n=yield((r=t.fetch)!=null?r:window.fetch)(t.url),o=yield n.blob();return new File([o],t.name,{type:(i=(s=t.mimeType)!=null?s:n.headers.get("Content-Type"))!=null?i:"image/jpeg"})})}function Fx(t,e){return v(this,null,function*(){let n=yield _x(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 Hx(t,e,n){return v(this,null,function*(){yield new tt(t).authenticateWithKey(e,n)})}function Bx(t){return t.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function Ux(o,r){return v(this,arguments,function*(t,e,n={}){var u,p;let{value:s}=t,{start:i,end:a}=(u=n.replace)!=null?u:{start:0,end:s.length},d=`${s.slice(0,i)}${e}${s.slice(a)}`,l=(p=n.selectionAfter)!=null?p:{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 Kx(o,r){return v(this,arguments,function*(t,e,n={}){let s=n.replace?bt(t,n.replace.start,n.replace.end):Kn(t),i,a=()=>{if(n.setRange)return n.setRange(s.cloneRange());s.deleteContents(),i=document.createElement("span"),s.insertNode(i),n.insertBRs!==!1?e.split(`
|
|
17
17
|
`).reverse().forEach((d,l)=>{l>0&&s.insertNode(document.createElement("br")),s.insertNode(document.createTextNode(d))}):s.insertNode(document.createTextNode(e))};return Promise.resolve(a()).then(()=>{try{if(n.selectionAfter!==!1){t.focus();let d=n.selectionAfter?bt(t,n.selectionAfter.start,n.selectionAfter.end):(s.collapse(!1),s),l=window.getSelection();l==null||l.removeAllRanges(),l==null||l.addRange(d)}if(!i)return;i.scrollIntoView&&i.scrollIntoView({block:"nearest",inline:"nearest"})}finally{i&&i.remove()}})})}function zx(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 Wx(t){let e=document.createDocumentFragment();return t.split(`
|
|
18
18
|
`).forEach((n,o)=>{o>0&&e.appendChild(document.createElement("br"));let r={index:0},s=0;for(;r=n.slice(s).match(/(\[([^\]]+)])\(([^)]+)\)/);){let i=document.createElement("a");i.href=r[3],i.setAttribute("target","_blank"),i.setAttribute("rel","noopener noreferrer"),i.appendChild(document.createTextNode(r[2])),e.appendChild(document.createTextNode(n.slice(s,s+r.index))),e.appendChild(i),s=s+r.index+r[0].length}e.appendChild(document.createTextNode(n.slice(s)))}),e}function Np(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):Np(n,e)}function Vx(r,s){return v(this,arguments,function*(t,e,{isBlock:n,isHTML:o}={}){let i;t.dispatchEvent(new InputEvent("beforeinput",{inputType:"insertText",data:e,bubbles:!0,cancelable:!0}));let a=()=>{var p;let d=(p=t.ownerDocument.defaultView)!=null?p: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 u=o?zx(e):Wx(e);n?Np(c.startContainer,u):(c.insertNode(u),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{D as Card,Qt as ContentEditableInput,tt as DeepdeskAPI,Tr as DeepdeskSDK,tn as HTTPClient,Ye as InputMediator,kt as InputType,Rr as KeyboardHint,Yp as Label,Qn as Locale,Ie as Section,an as SectionList,je as Sources,M as Suggestion,te as SuggestionList,Zt as TextAreaInput,Et as ToggleButton,Fx as attachFile,Hx as authenticateWithKey,Kn as createFullRange,xr as createOverlayContainer,bt as createRangeFromOffsets,In as escapeHTML,Bx as formatTextMarkup,mr as getRangeOffsets,gr as getRangeText,Vx as insertCKEditor,bo as isHTML,di as isSupportedInputElement,ms as logEvent,Kx as updateContentEditable,Ux as updateTextArea,gt as useClickOutsideRoot,x as useStyles,gi as waitForElementVisibilityChange};
|