@deepdesk/deepdesk-sdk 10.10.3-beta.6 → 10.10.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs.js CHANGED
@@ -6,6 +6,6 @@ Try polyfilling it using "@formatjs/intl-pluralrules"
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
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`})})});var Ei=require("react/jsx-runtime"),gf={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},wp=({className:t,color:e})=>(0,Ei.jsx)("svg",{className:t,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:(0,Ei.jsx)("path",{d:"M172.03 0.0199966H0V86.03C47.5 86.03 86 124.54 86 172.04C86 124.54 124.51 86.03 172.01 86.03C219.51 86.03 258.03 124.54 258.03 172.04C258.03 219.54 219.52 258.05 172.01 258.05C124.5 258.05 86 219.54 86 172.04C86 219.54 47.5 258.05 0 258.05V344.06H172.03C267.04 344.06 344.06 267.04 344.06 172.03C344.06 77.02 267.04 0 172.03 0V0.0199966Z",fill:gf[e||"pink"]})});var Tp={root:"_root_1tvv4_1",text:"_text_1tvv4_18",isLoggedIn:"_isLoggedIn_1tvv4_25",isLoggedOut:"_isLoggedOut_1tvv4_29",icon:"_icon_1tvv4_39",logo:"_logo_1tvv4_44",lock:"_lock_1tvv4_49"};var ki={};G(ki,{enUS:()=>mf,nlNL:()=>ff});var mf={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},ff={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};var Ip=require("react-redux"),qt=require("react/jsx-runtime"),Rp=({onLogIn:t})=>{let e=T(ki),o=C("floatingMenu"),n=C("productName"),s=(0,Ip.useDispatch)(),r=(0,kp.useSelector)(ne),i=y("FloatingMenu",Tp);if(r===null||o===!1)return null;let a=()=>{r===!0?s(te(!0)):t()};return(0,qt.jsxs)("button",{className:(0,Ep.default)(i.root,{[i.isLoggedIn]:r,[i.isLoggedOut]:!r}),onClick:a,children:[(0,qt.jsx)("div",{className:i.text,children:e(r?"search":"signin",{productName:n})}),(0,qt.jsxs)("div",{className:i.icon,children:[(0,qt.jsx)(wp,{className:i.logo,color:"pink"}),r===!1&&(0,qt.jsx)(Cp,{className:i.lock})]})]})};var Qs=require("react"),et=require("react-redux");function ko(t){let{showMidSentenceSuggestions:e,showSuggestionsBeforePattern:o,showSuggestionsAfterPattern:n}=t.settings,{text:s,selection:r}=t.input.userCommitted;return r.start!==r.end?!1:r.end>=s.length?!0:e?o&&new RegExp(o).test(s.substring(r.end))||n&&new RegExp(n).test(s.substring(0,r.end))?!0:o===!1&&n===!1:!1}var Xs=require("react");var Mp=require("interweave"),Io=require("react"),$s=require("react-redux");var Pp=require("react");function Ap(t,e,o){(0,Pp.useEffect)(()=>{let n=t.current;return n?(n.addEventListener(e,o),()=>{n.removeEventListener(e,o)}):()=>{}},[t,e,o])}var Lp={root:"_root_4u430_1",actions:"_actions_4u430_8",badge:"_badge_4u430_15",formattedText:"_formattedText_4u430_19"};var Wt=require("react/jsx-runtime"),yf=["search","personal-collection-search","search-autocomplete"];function vf(t,e,o,n={}){let s="";return yf.includes(e)?s=Il(ei(t,o,{stripAgentPart:!0}),n.searchKeywords??[o]):s=ei(t,o,n),n.placeholders===!0&&(s=Rl(s)),s}var Sf=()=>{},_f=({index:t,selected:e,suggestion:o,onFeedback:n})=>{let s=C("inlineSuggestions"),r=(0,$s.useSelector)(so),i=(0,$s.useDispatch)(),a=y("TextSuggestion",Lp),l=(0,Io.useRef)(null);(0,Io.useEffect)(()=>{let p=setTimeout(()=>{i(Wa({text:o.text,suggestion:o}))},500);return()=>{clearTimeout(p)}},[o]),Ap(l,"click",()=>{i(ut(t)),i(ke({suggestion:o,text:o.text,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"}))});let c=(0,Io.useMemo)(()=>vf(o.text,o.source,r,{stripAgentPart:s,placeholders:!0,searchKeywords:o.searchKeywords}),[s,o.text,o.source,r,o.searchKeywords]);return o.source==="gpt"&&!s?null:(0,Wt.jsxs)("div",{className:a.root,onMouseEnter:()=>i(ut(t)),children:[(0,Wt.jsx)(D,{ref:l,as:"button","data-testid":"suggestions-overlay-item",selected:e,onClick:Sf,children:(0,Wt.jsx)(Mp.Interweave,{containerTagName:"div",noWrap:!1,tagName:"span",className:a.formattedText,content:c})}),e&&n&&(0,Wt.jsx)("div",{className:a.actions,children:(0,Wt.jsx)(ws,{onFeedback:()=>n(o),suggestion:o.text})})]})},Np=_f;var Ii=require("react/jsx-runtime"),xf=({onFeedback:t,suggestions:e,selectedIndex:o,reverse:n})=>{let s=(0,Xs.useMemo)(()=>{let r=e.map((i,a)=>(0,Ii.jsx)(Np,{index:a,selected:a===o,suggestion:i,onFeedback:t},`${i.text}-${i.source}`));return n?r.reverse():r},[e,o,n]);return(0,Ii.jsx)(Xs.Fragment,{children:s})},Zs=xf;var Op={root:"_root_otdbu_1",paper:"_paper_otdbu_11"};var hn=require("react/jsx-runtime"),bf=({textSuggestions:t,selectedIndex:e})=>{let o=(0,Qs.useRef)(null),n=y("InlineSuggestionsOverlay",Op),s=(0,et.useSelector)(ko),r=(0,et.useDispatch)(),i=(0,et.useSelector)(ne),a=(0,et.useSelector)(no),l=(0,et.useSelector)(Ds),c=C("showTextSuggestions");return po(()=>{r(yt({collapse:!0,skipWhenInputFocus:!0}))}),(0,Qs.useEffect)(()=>{let p=o.current;if(!p||!p.parentElement)return;p.parentElement.style.left="0px";let d=p.getBoundingClientRect();p.parentElement.style.left=`${Math.min(window.innerWidth-4-d.right,0)}px`}),l||!s||!c||t.length===0||i!==!0||a===!1?null:(0,hn.jsx)("div",{className:n.root,"data-variant":"inline",children:(0,hn.jsx)("div",{ref:o,className:n.paper,children:(0,hn.jsx)(Se,{children:(0,hn.jsx)(Zs,{suggestions:t,selectedIndex:e})})})})},Cf=({input:t})=>({selectedIndex:t.selectedSuggestionIndex,textSuggestions:t.textSuggestions}),Dp=(0,et.connect)(Cf)(bf);var Hp=require("react-redux");var yn=require("react/jsx-runtime"),wf=({children:t})=>{let o=C("locale").replace("-","");return(0,yn.jsx)(qr.Provider,{value:o,children:t})},Tf=({store:t,customStyles:e={},children:o})=>(0,yn.jsx)(Hp.Provider,{store:t,children:(0,yn.jsx)(wf,{children:(0,yn.jsx)(Do.Provider,{value:e,children:o})})}),Gt=Tf;var Ys=E(require("classnames")),Ro=require("react"),Ke=require("react-redux");var Bp=require("react");function Fp(t,e){let[o,n]=(0,Bp.useState)(()=>{if(typeof window>"u")return e;try{let r=window.localStorage.getItem(t);return r?JSON.parse(r):e}catch(r){return w.error(r),e}});return[o,r=>{try{let i=r instanceof Function?r(o):r;n(i),typeof window<"u"&&window.localStorage.setItem(t,JSON.stringify(i))}catch(i){w.error(i)}}]}var Up=E(require("classnames")),tt=require("react");var Ri={};G(Ri,{enUS:()=>Ef,nlNL:()=>kf});var Ef={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"}]}]},kf={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 Kp={root:"_root_1vfca_1",anchor:"_anchor_1vfca_6",anchorButton:"_anchorButton_1vfca_11"};var _t=require("react/jsx-runtime"),Pi=(t,e,o)=>n=>(0,_t.jsx)("button",{className:t.anchorButton,type:"button",value:e,onClick:o,children:n},e),If=({className:t,loginUrl:e,isEmbedded:o,onSnooze:n,onLogIn:s})=>{let r=T(Ri),i=xe(),a=y("Login",Kp),l=C("productName"),c=(0,tt.useCallback)(h=>{h.preventDefault(),n&&n(parseInt(h.target.value,10))},[]),p=(0,tt.useCallback)(h=>{h.preventDefault(),i.send(xo,!0)},[e]),d=(0,tt.useMemo)(()=>h=>(0,_t.jsx)("a",{onClick:S=>{S.preventDefault(),s()},href:e,className:a.anchor,target:"_blank",rel:"noreferrer",children:h},"login"),[e]),g=(0,tt.useCallback)(h=>(0,_t.jsx)("button",{type:"button",className:a.anchorButton,onClick:p,children:h},"prompt"),[p]),{min:u,hour:m,day:f}=(0,tt.useMemo)(()=>({min:Pi(a,60*10,c),hour:Pi(a,60*60,c),day:Pi(a,60*60*12,c)}),[]);return(0,_t.jsxs)("div",{className:(0,Up.default)(t,a.root),children:[r("loginPlease",{login:o?g:d,productName:l}),n&&(0,_t.jsxs)(tt.Fragment,{children:[(0,_t.jsx)("br",{}),r("snooze",{min:u,hour:m,day:f})]})]})},Js=If;var zp=require("react-redux");var jp={root:"_root_1g8fi_1",text:"_text_1g8fi_19"};var vn=require("react/jsx-runtime"),Rf=({title:t})=>{let e=y("SearchTrigger",jp),o=(0,zp.useDispatch)();return(0,vn.jsxs)("button",{type:"button",className:e.root,onClick:()=>o(te(!0)),children:[(0,vn.jsx)(ho,{}),(0,vn.jsx)("span",{className:e.text,children:t})]})},Vp=Rf;var Ai={};G(Ai,{enUS:()=>Pf,nlNL:()=>Af});var Pf={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"}]},Af={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"}]};var qp={root:"_root_onpov_1",isInline:"_isInline_onpov_14",toggleButton:"_toggleButton_onpov_21",toggleButtonWrapper:"_toggleButtonWrapper_onpov_25",toggleButtonWrapperHidden:"_toggleButtonWrapperHidden_onpov_32",isCollapsed:"_isCollapsed_onpov_36",collapsible:"_collapsible_onpov_36",hints:"_hints_onpov_44",hintsHidden:"_hintsHidden_onpov_51",triggers:"_triggers_onpov_56",triggersRight:"_triggersRight_onpov_71"};var B=require("react/jsx-runtime"),Lf=({textSuggestions:t,selectedIndex:e,onLogIn:o})=>{let n=y("SuggestionsOverlay",qp),s=T(Ai),r=(0,Ke.useSelector)(ko),i=Ua(),a=(0,Ke.useDispatch)(),l=(0,Ro.useRef)(null),c=C("searchTriggerKey"),p=C("productName"),d=(0,Ke.useSelector)(Ds),g=(0,Ke.useSelector)(ne),u=(0,Ke.useSelector)(no),[m,f]=(0,Ro.useState)(null),h=C("showSearch"),k=C("showTextSuggestions"),S=C("adminUrl"),x=C("isEmbedded"),[b,v]=Fp("dd-snooze-until-ms",0),A=d||b>Date.now(),M=(0,Ke.useSelector)(j=>j.input.text),K=t.filter(j=>j.source!=="gpt").length,L=()=>{A&&v(0),a(Tc(!A))},Z=j=>{a(Q({name:"suggestion feedback",data:{text:j.text,source:"overlay",context:M},options:{includeConversationData:!0}}))},I=j=>{let Qt=Date.now()+j*1e3;v(Qt),w.info(`Snooze until: ${new Date(Qt)}`),a(yt({collapse:!0}))};return(0,Ro.useEffect)(()=>{K===0&&f(null)},[t,K]),po(()=>{a(yt({collapse:!0,skipWhenInputFocus:!0}))}),g===null||u===!1?null:g===!1?(0,B.jsxs)("div",{ref:l,className:(0,Ys.default)(n.root,{[n.isCollapsed]:A}),children:[!A&&(0,B.jsxs)("div",{className:n.triggers,children:[(0,B.jsx)("div",{style:{flex:1}}),(0,B.jsx)("div",{className:n.triggersRight,children:(0,B.jsx)(Rt,{className:n.toggleButton,title:s("collapse"),onClick:L,isCollapsed:!1})})]}),(0,B.jsx)("div",{className:n.toggleButtonWrapper,children:(0,B.jsx)(Rt,{className:n.toggleButton,title:s("open",{productName:p}),onClick:L,isCollapsed:!0})}),(0,B.jsx)("div",{className:n.collapsible,children:(0,B.jsx)(Js,{loginUrl:S,isEmbedded:x,onLogIn:o,onSnooze:I})})]}):!i||!r?null:(0,B.jsxs)("div",{ref:l,className:(0,Ys.default)(n.root,{[n.isCollapsed]:A}),children:[!A&&(0,B.jsxs)("div",{className:n.triggers,children:[(0,B.jsx)("div",{style:{flex:1},children:h&&(0,B.jsx)("div",{style:{display:"inline-block"},onFocus:()=>{},onMouseOver:()=>f(s(Ps()?"searchHintMac":"searchHintWindows",{searchTriggerKey:c.toUpperCase()})),onMouseLeave:()=>f(null),children:(0,B.jsx)(Vp,{title:s("search")})})}),(0,B.jsxs)("div",{className:n.triggersRight,onFocus:()=>{},children:[(0,B.jsx)("div",{className:(0,Ys.default)(!m&&n.hintsHidden,n.hints),children:m}),(0,B.jsx)(Rt,{className:n.toggleButton,title:s("collapse"),onClick:L,isCollapsed:!1})]})]}),(0,B.jsx)("div",{className:n.toggleButtonWrapper,children:(0,B.jsx)(Rt,{className:n.toggleButton,title:s("open",{productName:p}),onClick:L,isCollapsed:!0})}),K>0&&k&&(0,B.jsx)("div",{className:n.collapsible,onFocus:()=>{},children:(0,B.jsx)(Se,{children:(0,B.jsx)(Zs,{onFeedback:Z,suggestions:t,selectedIndex:e,reverse:!0})})})]})},Mf=({input:t})=>({selectedIndex:t.selectedSuggestionIndex,textSuggestions:t.textSuggestions}),Wp=(0,Ke.connect)(Mf)(Lf);var ur=E(require("classnames")),dd=require("interweave"),st=require("react"),ud=require("react-redux");var Gp=require("react"),Nf=["div","span","mark","strong","b","i","u","em"];function Li(t,e,o=0){var r;let n=t[t.length-1],s=typeof n=="object"&&n!==null?(r=n.props)==null?void 0:r.tagName:void 0;if(s==="br")return t.pop(),[...t,...e,n];if(Nf.includes(s)){let i=Array.isArray(n.props.children)?n.props.children:[n.props.children];return[...t.slice(0,t.length-1),(0,Gp.cloneElement)(n,{children:Li(i,e,o+1)})]}return[...t,...e]}function xt(t){return t.tagName.toLowerCase()==="textarea"}var $p={root:"_root_81non_1",container:"_container_81non_3",agentText:"_agentText_81non_5",tabText:"_tabText_81non_6",hint:"_hint_81non_6",matchSelection:"_matchSelection_81non_10",focus:"_focus_81non_16",resetIndent:"_resetIndent_81non_20",matchKeyword:"_matchKeyword_81non_24",matchPlaceholder:"_matchPlaceholder_81non_25",hover:"_hover_81non_31",hintText:"_hintText_81non_64",popover:"_popover_81non_72",popoverRoot:"_popoverRoot_81non_77",popoverContentContainer:"_popoverContentContainer_81non_81",popoverContent:"_popoverContent_81non_81",selectionOptions:"_selectionOptions_81non_107",selectionOptionsIsHidden:"_selectionOptionsIsHidden_81non_112",selectionOptionsButton:"_selectionOptionsButton_81non_116",caret:"_caret_81non_132",popoverSuggestionsRoot:"_popoverSuggestionsRoot_81non_136",suggestionsOverlayInputStyles:"_suggestionsOverlayInputStyles_81non_141"};var nd=E(require("classnames")),sd=require("interweave"),lr=require("react");function Xp(t){return t.replace(/[.*+^${}()|[\]\\]/g,"\\$&")}function er(t){return e=>{t.forEach(o=>{typeof o=="function"?o(e):o!=null&&(o.current=e)})}}function Zp(t){return t!=null}var Ni=E(require("classnames")),be=require("react");var tr=require("react"),Of=["bottom","height","left","right","top","width"],Df=(t={},e={})=>Of.some(o=>t[o]!==e[o]),ot=new Map,Qp,Jp=()=>{let t=[],e=[];ot.forEach((o,n)=>{if(n instanceof Element&&!n.isConnected){e.push(n);return}let s=n.getBoundingClientRect();Df(s,o.rect)&&(o.rect=s,t.push(o))}),e.forEach(o=>{ot.delete(o)}),t.forEach(o=>{o.callbacks.forEach(n=>n(o.rect))}),Qp=window.requestAnimationFrame(Jp)};function Hf(t,e){return{observe(){let o=ot.size===0;if(ot.has(t)){let n=ot.get(t);n.callbacks.push(e),n.rect&&e(n.rect)}else ot.set(t,{rect:void 0,hasRectChanged:!1,callbacks:[e]});o&&Jp()},unobserve(){let o=ot.get(t);if(o){let n=o.callbacks.indexOf(e);n>=0&&o.callbacks.splice(n,1),o.callbacks.length||ot.delete(t),ot.size||cancelAnimationFrame(Qp)}}}}function Mi(t){let[e,o]=(0,tr.useState)(null);return(0,tr.useLayoutEffect)(()=>{if(!t.current)return;let n=Hf(t.current,s=>{o(s)});return n.observe(),()=>{n.unobserve()}},[t]),e}var Po=require("react"),ed=require("react-dom");var Yp={root:"_root_1jq08_1"};var td=({children:t})=>{let[e,o]=(0,Po.useState)(null),n=(0,Po.useContext)(Do);return(0,Po.useLayoutEffect)(()=>{let s=document.createElement("div");return Lt(s),s.classList.add(Yp.root),n!=null&&n.portalRootNode&&s.classList.add(n==null?void 0:n.portalRootNode),document.body.appendChild(s),o(s),()=>{s.isConnected&&document.body.removeChild(s)}},[]),e?(0,ed.createPortal)(t,e):null};var Ue={ref:"_ref_1rcyi_1",root:"_root_1rcyi_7",positionAbove:"_positionAbove_1rcyi_13",positionBelow:"_positionBelow_1rcyi_17",positionLeft:"_positionLeft_1rcyi_21",positionRight:"_positionRight_1rcyi_25",alignStart:"_alignStart_1rcyi_29",alignCenter:"_alignCenter_1rcyi_34",alignEnd:"_alignEnd_1rcyi_40"};var or=require("react/jsx-runtime"),nr=(t=!1)=>{let[e,o]=(0,be.useState)(t),n=(0,be.useCallback)(()=>o(!0),[]),s=(0,be.useCallback)(()=>o(!1),[]),r=(0,be.useCallback)(()=>o(a=>!a),[]),i=(0,be.useRef)(null);return{opened:e,open:n,close:s,toggle:r,triggerRef:i}};function Oi(t,e=null,o=0){if(!t)return{display:"none"};let n=e?t.top-e.top<0||t.top<e.top-o?e.top-o:t.top+t.height>e.top+e.height+o?e.top+e.height+o-t.height:t.top:t.top,s=e?t.left<e.left-o?e.left-o:t.left+t.width>e.left+e.width+o?e.left+e.width+o-t.width:t.left:t.left;return{top:n,left:s,height:t.height,width:t.width}}var sr=({className:t,triggerRef:e,boundaryRef:o=(0,be.createRef)(),position:n="above",align:s="center",children:r,toStyle:i=Oi,...a})=>{let l=Mi(e),c=Mi(o),p=(0,be.useMemo)(()=>i(l,c,0),[l,c]);return(0,or.jsx)(td,{children:(0,or.jsx)("div",{className:(0,Ni.default)(Ue.ref,{[Ue.positionAbove]:n==="above",[Ue.positionBelow]:n==="below",[Ue.positionLeft]:n==="left",[Ue.positionRight]:n==="right",[Ue.alignStart]:s==="start",[Ue.alignCenter]:s==="center",[Ue.alignEnd]:s==="end"}),style:p,...a,role:"dialog",children:(0,or.jsx)("div",{className:(0,Ni.default)(t,Ue.root),children:r})})})};var od=E(require("classnames")),rr=require("react");var Di=require("react/jsx-runtime"),ir=(0,rr.forwardRef)(({className:t,children:e,...o},n)=>{let s=(0,rr.useRef)(null),r=y("TabCompletion",Ve);return(0,Di.jsx)("div",{ref:er([s,n]),className:(0,od.default)(t,r.popoverContentContainer),...o,children:(0,Di.jsx)("div",{className:r.popoverContent,children:e})})});var bt=require("react/jsx-runtime"),Bf=t=>e=>{let o=Oi(e);return"top"in o&&(o.width=t.width-(e.left-t.left)-10),o},Ff=({inputElement:t,boundaryRef:e,inputStyle:o,children:n,suggestion:s})=>{let r=y("TabCompletion",Ve),i=nr(),a=(0,lr.useMemo)(()=>Bf(t.getBoundingClientRect()),[t]),[l,c]=hs(t);return(0,lr.useEffect)(()=>{c?i.open():i.close()},[c]),(0,bt.jsxs)("span",{children:[(0,bt.jsx)("mark",{ref:er([l,i.triggerRef]),className:(0,nd.default)(r.matchKeyword,{[r.hover]:c}),"aria-haspopup":"dialog","aria-expanded":i.opened?"true":"false",children:n}),i.opened&&(0,bt.jsx)(sr,{className:r.popover,triggerRef:i.triggerRef,boundaryRef:e,position:"below",align:"start",toStyle:a,children:(0,bt.jsx)(ir,{style:o,children:(0,bt.jsx)("div",{className:r.hintText,children:s})})})]})},ar=class extends sd.Matcher{keywordMatches=[];preparedKeywordMatches=[];usedKeywordMatches=new Set;onBeforeParse(e,o){return o.keywordMatches&&o.keywordMatches!==this.keywordMatches&&(this.preparedKeywordMatches=o.keywordMatches.map(n=>({...n,keywordRegex:new RegExp(`\\b${Xp(n.keyword)}\\b`,"i")})),this.keywordMatches=o.keywordMatches),this.usedKeywordMatches.clear(),e}match(e){let o=this.preparedKeywordMatches.map(s=>{if(this.usedKeywordMatches.has(s))return null;let r=e.match(s.keywordRegex);if(!r)return null;let i=e.charAt(r.index-1),a=e.charAt(r.index+s.keyword.length);return i==="{"&&a==="}"?null:{index:r.index,length:r[0].length,match:r[0],matchString:r[0],suggestion:s.suggestion,preparedKeywordMatch:s,valid:!0}}).filter(Zp);if(o.length===0)return null;let n=o.reduce((s,r)=>r.index<s.index?r:s);return this.usedKeywordMatches.add(n.preparedKeywordMatch),n}replaceWith(e,o){return(0,bt.jsx)(Ff,{inputElement:o.inputElement,suggestion:o.suggestion,inputStyle:o.inputStyle,boundaryRef:o.boundaryRef,children:e},`keyword_${o.matchString}_${o.key}`)}asTag(){return"mark"}};var pr=E(require("classnames")),cd=require("interweave"),ie=require("react"),pd=require("react-redux");var Hi=require("react/jsx-runtime"),rd=()=>(0,Hi.jsx)("svg",{width:"1.3em",height:"1.3em",focusable:"false","aria-hidden":"true",viewBox:"0 0 24 24","data-testid":"InsertLinkIcon",tabIndex:-1,children:(0,Hi.jsx)("path",{fill:"currentColor",d:"M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76 0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71 0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71 0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76 0 5-2.24 5-5s-2.24-5-5-5z"})});var Ct=require("react"),Sn=require("react-redux"),ad=E(require("lodash.debounce"));var id={root:"_root_1muu8_1",content:"_content_1muu8_7"};function cr(t,e,o){var s;let n=((s=t.imageSizes)==null?void 0:s[e])||t.image||o;if(!n)return null;try{return new URL(n).toString()}catch{return null}}function Bi(t){return t.replace("https://www.","").replace("https://","")}var Ce=require("react/jsx-runtime"),Kf=3,Uf=t=>({image:t.image||"",text:t.text,id:t.id,title:t.title}),jf=({onSelectLink:t,onDismiss:e,placeholder:o,visitUrlText:n,linkCount:s=Kf})=>{let r=y("LinkSearch",id),[i,a]=(0,Ct.useState)(""),l=(0,Sn.useDispatch)(),c=(0,Sn.useSelector)(Ns("url")),p=(0,Sn.useSelector)(Yl("URL",Uf)),[d,g]=(0,Ct.useState)(p.length-1),u=C("fallbackImage"),m=S=>{let x=S.target;a(x.value)},f=(S,x)=>{S.stopPropagation(),S.preventDefault(),window.open(x,"_blank")},h=S=>{var v;let x=d-1<0?p.length-1:d-1,b=d+1===p.length?0:d+1;S.code==="Escape"&&(a(""),e()),S.code==="ArrowUp"&&g(x),S.code==="ArrowDown"&&g(b),S.code==="Enter"&&t(((v=p[d])==null?void 0:v.text)||i)},k=(0,Ct.useCallback)((0,ad.default)(S=>{l(Ft({query:S,type:"URL",tags:["link-search"]}))},300),[]);return(0,Ct.useEffect)(()=>{i&&k(i)},[i]),(0,Ct.useEffect)(()=>()=>{l(Is())},[]),(0,Ce.jsxs)("div",{className:r.root,children:[(0,Ce.jsx)(Se,{withDivider:!0,children:(i?p:c).slice(0,s).map((S,x)=>(0,Ce.jsx)(D,{selected:d===x,onClick:()=>t(S.text),"data-testid":"linksearch-suggestion",children:(0,Ce.jsxs)(F,{children:[(0,Ce.jsx)(F.Image,{src:cr(S,"small",u||void 0),title:S.title||S.text}),(0,Ce.jsxs)(F.Content,{className:r.content,cropText:!0,children:[(0,Ce.jsx)(F.Title,{children:S.title||Bi(S.text)}),S.title&&Bi(S.text)]}),(0,Ce.jsx)(D.Actions,{children:(0,Ce.jsx)(D.ActionButton,{label:n,onClick:b=>f(b,S.text)})})]})},S.text))}),(0,Ce.jsx)(rn,{value:i,onChange:m,autoFocus:!0,placeholder:o,onKeyUp:h})]})},ld=jf;var Fi={};G(Fi,{enUS:()=>zf,nlNL:()=>Vf});var zf={insertLink:[{type:0,value:"Insert link"}],linkInputPlaceholder:[{type:0,value:"Search, type or paste link"}],visitUrl:[{type:0,value:"Visit"}]},Vf={insertLink:[{type:0,value:"Voeg link toe"}],linkInputPlaceholder:[{type:0,value:"Zoek, typ of plak link"}],visitUrl:[{type:0,value:"Bekijk"}]};var re=require("react/jsx-runtime"),qf=(0,ie.forwardRef)((t,e)=>{let o=y("TabCompletion",Ve);return(0,re.jsx)("mark",{ref:e,className:(0,pr.default)(o.matchSelection)},"selection-start")}),Wf=({startRef:t,boundaryRef:e,inputStyle:o,inputElement:n,children:s})=>{let r=T(Fi),i=y("TabCompletion",Ve),a=(0,ie.useRef)(null),l=(0,ie.useRef)(null),[c,p]=(0,ie.useState)(null),d=(0,pd.useDispatch)(),g=nr(document.activeElement===n),[u]=(0,ie.useState)(()=>document.createRange());g.triggerRef.current=u,(0,ie.useEffect)(()=>()=>u.detach(),[]),(0,ie.useEffect)(()=>{let f=t.current,h=a.current;!f||!h||(u.setStart(f,0),u.setEnd(h,0))},[t.current,a.current]),po(()=>{g.close()});let m=(0,ie.useCallback)(f=>{let h=u.toString(),k=/^http(s?):\/\//.test(f)?f:`https://${f}`;d(Zn({text:`[${h}](${k})`,replace:"selection"}))},[]);return(0,re.jsxs)("span",{children:[(0,re.jsx)("mark",{ref:a,className:(0,pr.default)(i.matchSelection),"aria-haspopup":"dialog","aria-expanded":g.opened?"true":"false",children:s}),g.opened&&(0,re.jsx)(sr,{className:i.popoverRoot,triggerRef:g.triggerRef,boundaryRef:e,position:"above",align:"start",children:(0,re.jsxs)(ir,{style:o,ref:l,children:[(0,re.jsx)("div",{className:(0,pr.default)(i.selectionOptions,{[i.selectionOptionsIsHidden]:c!==null}),children:(0,re.jsxs)("button",{type:"button",tabIndex:c===null?-1:void 0,className:i.selectionOptionsButton,onClick:()=>p("insertLink"),children:[(0,re.jsx)(rd,{}),(0,re.jsx)("span",{children:"\xA0"}),(0,re.jsx)("span",{children:r("insertLink")})]})}),c==="insertLink"&&(0,re.jsx)(ld,{placeholder:r("linkInputPlaceholder"),visitUrlText:r("visitUrl"),onSelectLink:m,onDismiss:()=>{p(null),g.close()}})]})})]},"selection-end")},dr=class extends cd.Matcher{charCount=0;foundIndex=0;startRef=null;props;onBeforeParse(e,o){return this.props=o,this.charCount=0,this.startRef=(0,ie.createRef)(),this.foundIndex=0,e}match(e){if(!this.props||this.props.selection===null||this.foundIndex===2)return null;let[o,n]=this.props.selection;if(o===n)return null;let s=this.foundIndex===0?o:n,r=s>=this.charCount&&s<=this.charCount+e.length?{index:s-this.charCount,length:0,match:"",valid:!0}:null;r&&this.foundIndex++;let i=this.foundIndex===1;return r&&i?this.charCount+=s-this.charCount:this.charCount+=e.length,r?{isStart:i,...r}:null}replaceWith(e,o){return o.isStart?(0,re.jsx)(qf,{ref:this.startRef}):(0,re.jsx)(Wf,{inputElement:o.inputElement,startRef:this.startRef,boundaryRef:o.boundaryRef,inputStyle:o.inputStyle})}asTag(){return"mark"}};var gd=require("react-redux");var nt=require("react/jsx-runtime"),Gf=({enabled:t,content:e,tabText:o,showTabHint:n,showTabCompletion:s,showStyleSuggestions:r,keywordMatches:i,inputElement:a,source:l})=>{let c=y("TabCompletion",$p),p=C("insertLink"),d=C("showMidSentenceSuggestions"),g=C("inlineSuggestions"),u=vs(a),m=(0,st.useRef)(null),f=(0,gd.useSelector)(ne);(0,st.useEffect)(()=>{xt(a)&&u&&Ss(a,u)},[u]);let h=(0,st.useCallback)(x=>{if(!s||!o)return x;let b=[(0,nt.jsx)("span",{className:c.resetIndent,children:"\u200B"},"u200B"),(0,nt.jsx)("span",{"data-testid":"tab-completion",className:(0,ur.default)(c.tabText,c.resetIndent),"data-source":l,children:o},"tabText")];return n&&b.push((0,nt.jsx)("span",{className:(0,ur.default)(c.hint,c.resetIndent),children:(0,nt.jsx)(Bn,{keyCode:"tab"},"tabHint")})),Li(x,b)},[s,o,n]),k=(0,st.useMemo)(()=>{let x=[];return p&&x.push(new dr("selection")),x.push(new lo("placeholders")),r&&x.push(new ar("keywords")),x},[g,p,r]),S=(0,st.useMemo)(()=>{let x=window.getComputedStyle(a);return{"--dd-color":x.color,"--dd-font-size":x.fontSize,"--dd-font-family":x.fontFamily,"--dd-font-variant":x.fontVariant}},[]);return!t||!f?null:(0,nt.jsxs)("div",{ref:x=>{x!=null&&x.parentElement&&(m.current=x==null?void 0:x.parentElement)},className:c.root,style:S,children:[(0,nt.jsx)(dd.Interweave,{tagName:"span",containerTagName:"div",className:(0,ur.default)(c.container,c.agentText),disableLineBreaks:xt(a),content:e||"\u200B",onAfterParse:h,matchers:k,selection:u,keywordMatches:i,inputElement:a,inputStyle:S,boundaryRef:m,inlineSuggestionsOnlyAtEnd:!d}),(0,nt.jsx)("br",{})]})},$f=({input:t,ui:e,settings:o,styleSuggestions:n,conversation:s})=>{var f;let{tabCompletionSuggestion:r}=t,i=(r==null?void 0:r.text)||"",a=(r==null?void 0:r.source)||"",l=t.html??go(t.text),c=i.indexOf(t.text)===0?i.slice(t.text.length):"",{showTabHint:p}=e,{isSupported:d}=s,{showTabCompletion:g,visible:u,showStyleSuggestions:m}=o;return{showTabHint:p,showStyleSuggestions:m,showTabCompletion:g,content:l,tabText:c,source:a,keywordMatches:((f=n.list)==null?void 0:f.keywordMatches)??[],enabled:u&&d!==!1}},md=(0,ud.connect)($f)(Gf);var ru=E(require("classnames")),iu=require("react"),X=require("react-redux");var wt=require("@reduxjs/toolkit");var fd={list:[],fetchState:"idle",isInitialRequest:null},yd=t=>t.autoflows.list||[],hd=t=>e=>{var o;return(o=e.list)==null?void 0:o.find(n=>n.triggerPayload===t)},rt=(0,wt.createAsyncThunk)("autoflows/getAll",async(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");return o.getAutoflows(t)}),Ki=(0,wt.createAsyncThunk)("autoflows/start",async(t,e)=>{let{dispatch:o}=e,{deepdeskBrokerAPI:n}=e.extra;if(!n)throw new Error("Deepdesk Broker not initialized");await n.startAutoflowSession(t),await o(rt(t.platformSessionId))}),Ui=(0,wt.createAsyncThunk)("autoflows/stop",async(t,e)=>{let{dispatch:o}=e,{deepdeskBrokerAPI:n}=e.extra;if(!n)throw new Error("Deepdesk Broker not initialized");await n.stopAutoflowSession(t.platformSessionId),await o(rt(t.platformSessionId))}),Xf=(0,wt.createSlice)({name:"autoflows",initialState:fd,reducers:{},extraReducers:t=>{t.addCase(Ki.pending,(e,o)=>{let n=hd(o.meta.arg.triggerPayload)(e);n.state="Started",n.isBusy=!0}),t.addCase(Ui.pending,(e,o)=>{let n=hd(o.meta.arg.triggerPayload)(e);n.state="Aborted",n.isBusy=!0}),t.addCase(rt.pending,e=>{e.isInitialRequest=e.isInitialRequest===null,e.fetchState="loading"}),t.addCase(rt.rejected,e=>{e.fetchState="error"}),t.addCase(rt.fulfilled,(e,o)=>{e.list=o.payload,e.fetchState="done"}),t.addCase(O,()=>fd)}}),vd=(0,wt.createAsyncThunk)("autoflows/openStream",(t,e)=>{let{dispatch:o}=e,{deepdeskBrokerAPI:n}=e.extra;if(!n)throw new Error("Deepdesk Broker not initialized");let s=n.openStream(t);s.on("sessionAborted",()=>{o(rt(t))}),s.on("sessionCompleted",()=>{o(rt(t))})}),Sd=(0,wt.createAsyncThunk)("autoflows/closeStream",(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");o.closeStream(t)}),_d=Xf.reducer;var Tt=require("@reduxjs/toolkit");var xd={list:[],fetchState:"idle",isInitialRequest:null,sentSuggestions:[],errorSuggestions:[],answeredSuggestions:[]},bd=t=>t.customMessages.list,Cd=t=>e=>!!e.customMessages.sentSuggestions.find(o=>o===t),wd=t=>e=>!!e.customMessages.answeredSuggestions.find(o=>o===t),Td=t=>e=>!!e.customMessages.errorSuggestions.find(o=>o===t),_n=(0,Tt.createAsyncThunk)("customMessages/getAll",async(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");return o.getCustomMessages(t)}),gr=(0,Tt.createAsyncThunk)("customMessages/send",async(t,e)=>{let{platformSessionId:o,suggestion:n}=t,{deepdeskBrokerAPI:s}=e.extra;if(!s)throw new Error("Deepdesk Broker not initialized");await s.sendCustomMessage(o,n)}),mr=(0,Tt.createAsyncThunk)("customMessages/answer",async(t,e)=>{let{platformSessionId:o,reply:n}=t,{deepdeskBrokerAPI:s}=e.extra;if(!s)throw new Error("Deepdesk Broker not initialized");await s.answerCustomMessage(o,n)}),Ed=(0,Tt.createSlice)({name:"customMessages",initialState:xd,reducers:{onCustomMessage(t,e){Array.isArray(e.payload)?t.list=e.payload:t.list=[e.payload]}},extraReducers:t=>{t.addCase(_n.pending,e=>{e.isInitialRequest=e.isInitialRequest===null,e.fetchState="loading"}).addCase(_n.rejected,e=>{e.fetchState="error"}).addCase(_n.fulfilled,(e,o)=>{e.fetchState="done",e.list=o.payload||[]}).addCase(gr.pending,(e,o)=>{e.sentSuggestions.push(o.meta.arg.suggestion.text),e.errorSuggestions=e.errorSuggestions.filter(n=>o.meta.arg.suggestion.text!==n)}).addCase(gr.rejected,(e,o)=>{let n=e.sentSuggestions.indexOf(o.meta.arg.suggestion.text);e.errorSuggestions.push(...e.sentSuggestions.splice(n,1))}).addCase(mr.pending,(e,o)=>{e.sentSuggestions.push(o.meta.arg.suggestion.text),e.answeredSuggestions.push(o.meta.arg.suggestion.text)}).addCase(mr.rejected,(e,o)=>{let n=e.answeredSuggestions.indexOf(o.meta.arg.suggestion.text);e.errorSuggestions.push(...e.sentSuggestions.splice(n,1)),e.answeredSuggestions.splice(n,1)}).addCase(O,()=>xd)}}),kd=(0,Tt.createAsyncThunk)("customMessages/openStream",(t,e)=>{let{dispatch:o}=e,{deepdeskBrokerAPI:n}=e.extra;if(!n)throw new Error("Deepdesk Broker not initialized");n.openStream(t).on("customMessageSuggestion",r=>{o(Ed.actions.onCustomMessage(r))})}),Id=(0,Tt.createAsyncThunk)("customMessages/closeStream",(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");o.closeStream(t)}),Rd=Ed.reducer;var xn=require("@reduxjs/toolkit"),Zf={token:null,accountUrl:null,interval:null},Pd=t=>e=>{let{passwordlessToken:{token:o,accountUrl:n}}=e;return o&&n?`${n}/apis/admin/session/passwordless/login/?token=${o}&redirect=${t}`:null},ji=(0,xn.createAsyncThunk)("passwordlessToken/getTemporaryPasswordlessToken",async(t,e)=>{let{deepdeskAPI:o}=e.extra,n=await o.requestPasswordlessToken();return{accountUrl:o.client.baseUrl,token:n}}),zi=(0,xn.createAsyncThunk)("passwordlessToken/pollPasswordlessToken",(t={},e)=>{let{interval:o=1e3*60*10}=t,{dispatch:n}=e;return n(ji()),setInterval(()=>n(ji()),o)}),Ad=(0,xn.createSlice)({name:"passwordlessToken",initialState:Zf,reducers:{stopPollPasswordlessToken(t){t.interval&&clearInterval(t.interval),t.interval=null}},extraReducers:t=>{t.addCase(ji.fulfilled,(e,o)=>{e.token=o.payload.token,e.accountUrl=o.payload.accountUrl}),t.addCase(zi.fulfilled,(e,o)=>{e.interval=o.payload})}}),{stopPollPasswordlessToken:Ld}=Ad.actions,Md=Ad.reducer;function Nd(t){let{customMessages:e,autoflows:o}=t;return o.fetchState==="loading"&&o.isInitialRequest===!0||e.fetchState==="loading"&&e.isInitialRequest===!0}var zd=require("react"),Vd=require("react-redux");var Kd=E(require("classnames")),Ud=require("react");var Dd=E(require("classnames"));var Od={root:"_root_838fd_1"};var Bd=require("react/jsx-runtime"),Qf=({className:t,children:e})=>{let o=y("Unicode",Od);return(0,Bd.jsx)("span",{className:(0,Dd.default)(t,o.root),children:e})},Hd=Qf;var Fd={isDisabled:"_isDisabled_1rmfm_1",buttonStart:"_buttonStart_1rmfm_5",root:"_root_1rmfm_8",buttonStop:"_buttonStop_1rmfm_8",stateBadge:"_stateBadge_1rmfm_19",isCompleted:"_isCompleted_1rmfm_26",isStarted:"_isStarted_1rmfm_30",isAborted:"_isAborted_1rmfm_34"};var Vi={};G(Vi,{enUS:()=>Jf,nlNL:()=>Yf});var Jf={start:[{type:0,value:"Start"}],stop:[{type:0,value:"Stop"}],aborted:[{type:0,value:"Stopped"}],completed:[{type:0,value:"Completed"}],Aborted:[{type:0,value:"Stopped"}],Started:[{type:0,value:"Running"}],Completed:[{type:0,value:"Completed"}]},Yf={start:[{type:0,value:"Start"}],stop:[{type:0,value:"Stop"}],aborted:[{type:0,value:"Stopped"}],completed:[{type:0,value:"Completed"}],Aborted:[{type:0,value:"Stopped"}],Started:[{type:0,value:"Running"}],Completed:[{type:0,value:"Completed"}]};var ge=require("react/jsx-runtime"),th=({disabled:t,state:e,displayName:o,description:n,onStartAutoflow:s,onStopAutoflow:r})=>{let i=y("Autoflow",Fd),a=T(Vi),l=e==="Started"?"stop":"start",c=l==="start"?"\u25B6":l==="stop"?"\u25FC":"";return(0,ge.jsxs)(D,{className:(0,Kd.default)(i.root,{[i.isDisabled]:t,[i.isCompleted]:e==="Completed",[i.isAborted]:e==="Aborted",[i.isStarted]:e==="Started"}),children:[(0,ge.jsx)(F,{children:(0,ge.jsxs)(F.Content,{children:[(0,ge.jsxs)(F.Title,{children:[e&&(0,ge.jsx)("span",{className:i.stateBadge,children:a(e)}),o]}),(0,ge.jsx)("span",{children:n})]})}),(0,ge.jsx)(D.Actions,{fixed:e==="Started",children:(0,ge.jsx)(D.ActionButton,{primary:!0,className:l==="start"?i.buttonStart:i.buttonStop,onClick:e==="Started"?r:s,disabled:t,label:(0,ge.jsxs)(Ud.Fragment,{children:[(0,ge.jsx)(Hd,{children:c})," ",(0,ge.jsx)("span",{children:a(l)})]})})})]})},jd=th;var qi=require("react/jsx-runtime"),oh=(t,e)=>{let o=e.filter(n=>n.state==="Started");return o.length>0?o.indexOf(t)===-1:!1},nh=({autoflows:t,onStartAutoflow:e,onStopAutoflow:o,platformSessionId:n})=>(0,qi.jsx)(zd.Fragment,{children:t.map(s=>(0,qi.jsx)(jd,{displayName:s.displayName,description:s.description,disabled:s.isBusy||oh(s,t),state:s.state,onStartAutoflow:()=>e({platformSessionId:n,triggerPayload:s.triggerPayload}),onStopAutoflow:()=>o({platformSessionId:n,triggerPayload:s.triggerPayload})},s.displayName))}),sh=({autoflows:t,conversation:e})=>{var o;return{autoflows:t.list,platformSessionId:(o=e.current)==null?void 0:o.sessionId}},rh={onStartAutoflow:Ki,onStopAutoflow:Ui},qd=(0,Vd.connect)(sh,rh)(nh);var fr=require("react"),Gd=require("react-redux"),$i=E(require("classnames"));var Wi=require("react/jsx-runtime"),Gi=()=>(0,Wi.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",children:(0,Wi.jsx)("path",{d:"M502.6 70.63l-61.25-61.25C435.4 3.371 427.2 0 418.7 0H255.1c-35.35 0-64 28.66-64 64l.0195 256C192 355.4 220.7 384 256 384h192c35.2 0 64-28.8 64-64V93.25C512 84.77 508.6 76.63 502.6 70.63zM464 320c0 8.836-7.164 16-16 16H255.1c-8.838 0-16-7.164-16-16L239.1 64.13c0-8.836 7.164-16 16-16h128L384 96c0 17.67 14.33 32 32 32h47.1V320zM272 448c0 8.836-7.164 16-16 16H63.1c-8.838 0-16-7.164-16-16L47.98 192.1c0-8.836 7.164-16 16-16H160V128H63.99c-35.35 0-64 28.65-64 64l.0098 256C.002 483.3 28.66 512 64 512h192c35.2 0 64-28.8 64-64v-32h-47.1L272 448z"})});var Wd={root:"_root_rjdyr_1",entity:"_entity_rjdyr_10",entityText:"_entityText_rjdyr_46",iconWrapper:"_iconWrapper_rjdyr_53",icon:"_icon_rjdyr_53",iconClicked:"_iconClicked_rjdyr_67"};var je=require("react/jsx-runtime"),ih=({entities:t})=>{let e=y("EntitiesWidgetList",Wd),[o,n]=(0,fr.useState)(void 0),s=(0,Gd.useDispatch)(),r=()=>{n(void 0)},i=a=>{t&&(n(t.indexOf(a)),ln(a.text),s(Q({name:"entity copied",data:{entity:a,type:"copy"}})))};return(0,fr.useEffect)(()=>{let a=setTimeout(r,500);return()=>{clearTimeout(a)}},[o]),!t||t.length===0?null:(0,je.jsx)("div",{className:e.root,"data-testid":"widget-entities-list",children:t.map((a,l)=>(0,je.jsxs)("button",{title:a.text,className:e.entity,type:"button",onClick:()=>i(a),children:[(0,je.jsx)("span",{className:e.entityText,children:a.text}),(0,je.jsxs)("span",{className:e.iconWrapper,children:[(0,je.jsx)("span",{className:(0,$i.default)(e.icon),children:(0,je.jsx)(Gi,{})}),(0,je.jsx)("span",{className:(0,$i.default)(e.icon,o===l&&e.iconClicked),children:(0,je.jsx)(Gi,{})})]})]},a.text))})},$d=ih;var Xd=E(require("classnames")),Xi=require("react"),$t=require("react-redux");var it={root:"_root_1e6ej_1",title:"_title_1e6ej_8",isUsed:"_isUsed_1e6ej_13",quickReplies:"_quickReplies_1e6ej_22",quickReply:"_quickReply_1e6ej_29",hasError:"_hasError_1e6ej_39",label:"_label_1e6ej_43",errorIcon:"_errorIcon_1e6ej_48"};var pe=require("react/jsx-runtime"),ah=({suggestion:t})=>{let e=T(Ht),o=(0,$t.useDispatch)(),n=(0,$t.useSelector)(Cd(t.text)),s=(0,$t.useSelector)(wd(t.text)),r=(0,$t.useSelector)(Td(t.text)),i=(0,$t.useSelector)(jn),{replyOptions:a}=t,l=(0,Xi.useCallback)(p=>{p.preventDefault(),p.stopPropagation(),!(n||!i)&&o(gr({platformSessionId:i,suggestion:t}))},[t,n,o,i]),c=(0,Xi.useCallback)(p=>{if(p.preventDefault(),p.stopPropagation(),!i||!a)return;let d=parseInt(p.target.dataset.index,10),g=a[d];o(mr({platformSessionId:i,reply:g,suggestion:t}))},[t,n,o,i]);return(0,pe.jsxs)(D,{onClick:l,className:(0,Xd.default)(it.root,{[it.isUsed]:n,[it.hasError]:r}),children:[(0,pe.jsx)(F,{children:(0,pe.jsxs)(F.Content,{children:[(0,pe.jsxs)(F.Title,{className:it.title,children:[t.text," ",(0,pe.jsx)(Fn,{className:it.label,children:"analyse tool"})," ",r&&(0,pe.jsx)("span",{className:it.errorIcon,role:"img","aria-label":e("sendingError"),title:e("sendingError"),children:"!"})]}),a&&a.length>0&&(0,pe.jsx)("ul",{className:it.quickReplies,children:a.map(p=>(0,pe.jsx)("li",{className:it.quickReply,children:p.title},p.title))})]})}),(0,pe.jsxs)(D.Actions,{fixed:r||n,children:[a&&a.length>0&&(0,pe.jsx)(D.DropdownButton,{label:e("answer"),disabled:s,children:a.map((p,d)=>(0,pe.jsx)(D.DropdownItem,{index:d,label:p.title,onClick:c},p.title))}),(0,pe.jsx)(D.ActionButton,{primary:!0,disabled:n,onClick:l,label:e(n?"suggestionSent":r?"tryAgain":"sendSuggestion")})]})]})},Zd=ah;var Zi=require("react/jsx-runtime"),Qd=()=>(0,Zi.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,Zi.jsx)("path",{d:"M17 13.5v6H5v-12h6m3-3h6v6m0-6-9 9",stroke:"currentColor",strokeWidth:"1.5",fill:"none",fillRule:"evenodd",strokeLinecap:"round",strokeLinejoin:"round"})});var eu=require("react-redux");var Jd=require("react");var me=require("react/jsx-runtime"),lh=({suggestion:t,lines:e,onEdit:o,onUse:n})=>{var g;let s=t.text||t.url||t.message,r=Rs(s),i=T(Ht),a=C("showImages"),l=C("fallbackImage"),c=u=>{u.preventDefault(),u.stopPropagation(),n(s)},p=u=>{u.preventDefault(),u.stopPropagation(),o(t)},d=(0,Jd.useCallback)(u=>{window.open(r,"_blank"),u.stopPropagation(),u.preventDefault()},[r]);return(0,me.jsxs)(D,{onClick:c,"data-testid":"edit-suggestion",children:[(0,me.jsxs)(F,{children:[a&&t.image&&(0,me.jsx)(F.Image,{src:cr(t,"small",l||void 0),title:t.title}),(0,me.jsxs)(F.Content,{children:[t.title&&(0,me.jsx)(F.Title,{"data-testid":"widget-suggestion-title",children:t.title}),t.searchKeywords&&((g=t.searchKeywords)==null?void 0:g.length)>0&&(0,me.jsx)(D.Labels,{labels:t.searchKeywords}),(0,me.jsx)(F.Content,{cropText:e==="single",lineClamp:e==="multiple",children:s})]})]}),(0,me.jsxs)(D.Actions,{children:[r&&(0,me.jsx)(D.ActionButton,{onClick:d,label:i("visitUrl")}),(0,me.jsx)(D.ActionButton,{primary:!0,onClick:p,label:i("preview")}),(0,me.jsx)(D.ActionButton,{primary:!0,onClick:c,label:i("useSuggestion")})]})]})},Yd=lh;var bn=require("react/jsx-runtime"),ch=({contentType:t,lines:e,suggestions:o})=>{let n=xe(),s=(0,eu.useSelector)(ht),r=a=>{n.send(hi,{state:s,suggestion:a,contentType:t})},i=(a,l)=>{n.send(Ze,{text:a,suggestion:{...l,source:l.source,sourceText:l.text}})};return(0,bn.jsx)(bn.Fragment,{children:o.map(a=>(0,bn.jsx)(Yd,{suggestion:a,lines:e,onEdit:l=>r(l),onUse:l=>i(l,a)},a.text||a.url||a.message))})},tu=ch;var Qi={};G(Qi,{enUS:()=>ph,nlNL:()=>dh});var ph={waiting:[{type:0,value:"Loading\u2026"}],notSupported:[{type:0,value:"This conversation is not supported"}],noResults:[{type:0,value:"No results found\u2026"}],titleAutoflows:[{type:0,value:"Autoflows"}],titleCustomMessages:[{type:0,value:"Quick replies"}],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"}]},dh={waiting:[{type:0,value:"Laden\u2026"}],notSupported:[{type:0,value:"Dit gesprek wordt niet ondersteund"}],noResults:[{type:0,value:"Geen resultaten gevonden\u2026"}],titleAutoflows:[{type:0,value:"Autoflows"}],titleCustomMessages:[{type:0,value:"Quick replies"}],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"}]};var ou={root:"_root_x0pwe_1",loginText:"_loginText_x0pwe_7",stateText:"_stateText_x0pwe_8",sectionList:"_sectionList_x0pwe_20",shortcutList:"_shortcutList_x0pwe_24",shortcut:"_shortcut_x0pwe_24",link:"_link_x0pwe_52"};var Ji=require("react/jsx-runtime"),nu=()=>(0,Ji.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:(0,Ji.jsx)("path",{d:"M543-340q16.595 0 28.798-12.202Q584-364.405 584-381t-12.202-28.798Q559.595-422 543-422t-28.798 12.202Q502-397.595 502-381t12.202 28.798Q526.405-340 543-340Zm-25-126h47q2-29 8.5-43t32.5-39q27-26 37.5-45.395Q654-612.79 654-639q0-45.882-31.5-74.941Q591-743 540-743q-38 0-68 20.5T428-665l45 19q11-25 27.5-38t39.5-13q29.778 0 48.389 17Q607-663 607-637q0 20-9 35t-32 32q-32 29-40 46.5t-8 57.5ZM260-200q-24 0-42-18t-18-42v-560q0-24 18-42t42-18h560q24 0 42 18t18 42v560q0 24-18 42t-42 18H260Zm0-60h560v-560H260v560ZM140-80q-24 0-42-18t-18-42v-620h60v620h620v60H140Zm120-740v560-560Z"})});var Yi=require("react/jsx-runtime"),su=()=>(0,Yi.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:(0,Yi.jsx)("path",{d:"M319-250h322v-60H319v60Zm0-170h322v-60H319v60ZM220-80q-24 0-42-18t-18-42v-680q0-24 18-42t42-18h361l219 219v521q0 24-18 42t-42 18H220Zm331-554v-186H220v680h520v-494H551ZM220-820v186-186 680-680Z"})});var R=require("react/jsx-runtime"),hr=(t,e)=>{let o=(0,X.useSelector)(ne);(0,iu.useEffect)(()=>o?e.every(n=>!!n)?t():()=>{}:()=>{},[...e,o])},uh=({onLogIn:t})=>{let e=T(Qi),o=(0,X.useDispatch)(),n=C("isEmbedded"),s=y("Widget",ou),r=C("showAutoflows"),i=C("showCustomMessages"),a=C("showSummaryCommand"),l=C("showKnowledgeSearch"),c=C("showSearch"),p=(0,X.useSelector)(St),d=(0,X.useSelector)(Ws),g=(0,X.useSelector)(yd),u=(0,X.useSelector)(Us),m=(0,X.useSelector)(bd),f=(0,X.useSelector)(zn),h=(0,X.useSelector)(no),k=(0,X.useSelector)(ne),S=(0,X.useSelector)(jn),x=(0,X.useSelector)(Nd),b=(0,X.useSelector)(ht),v=xe(),A=(0,X.useSelector)(pc),M=(0,X.useSelector)(Pd("/admin/")),K=C("adminUrl"),L=C("productName");if(hr(()=>(o(_n(S)),o(kd(S)),()=>{o(Id(S))}),[o,h,i,S]),hr(()=>(o(rt(S)),o(vd(S)),()=>{o(Sd(S))}),[o,h,r,S]),hr(()=>{d.forEach(({type:I})=>{o(I==="entities"?Le():Pe(I))})},[o,h,f,p]),hr(()=>(o(zi()),()=>{o(Ld())}),[o]),h===!1)return(0,R.jsx)("div",{className:s.stateText,children:(0,R.jsx)("div",{children:(0,R.jsx)("p",{children:e("notSupported")})})},"supported");if(k===!1)return(0,R.jsx)("div",{className:s.loginText,children:(0,R.jsx)("div",{children:(0,R.jsx)(Js,{isEmbedded:n,loginUrl:K,onLogIn:t})})},"login");if(!p||!S||k===null||A||x)return(0,R.jsx)("div",{className:s.stateText,children:(0,R.jsx)("div",{children:(0,R.jsx)("p",{children:e("waiting")})})},"waiting");let Z=c||a||l||M;return(0,R.jsx)("div",{className:(0,ru.default)(s.root),"data-testid":"widget",children:(0,R.jsxs)(Kn,{className:s.sectionList,children:[Z&&(0,R.jsx)(lt,{title:e("actions"),type:"shortcuts",children:(0,R.jsxs)("div",{className:s.shortcutList,children:[c&&(0,R.jsxs)("button",{className:s.shortcut,"data-testid":"shortcut-search",onClick:()=>v.send("ShowCommandPalette",{isOpen:!0}),children:[(0,R.jsx)(ho,{}),e("linkSearch")]}),a&&(0,R.jsxs)("button",{className:s.shortcut,"data-testid":"shortcut-summary",onClick:()=>v.send("ShowCommandPalette",{isOpen:!0,page:"summary"}),children:[(0,R.jsx)(su,{}),e("linkSummary")]}),l&&(0,R.jsxs)("button",{className:s.shortcut,"data-testid":"shortcut-knowledge-assist",onClick:()=>v.send("ShowCommandPalette",{isOpen:!0,page:"knowledgeAssist"}),children:[(0,R.jsx)(nu,{}),e("linkKnowledgeSearch")]}),M&&(0,R.jsxs)("a",{className:s.shortcut,target:"_blank",href:M,"data-testid":"shortcut-studio-login",rel:"noreferrer",children:[(0,R.jsx)(Qd,{}),e("linkStudioLogin",{productName:L})]})]})}),i&&m.length>0&&(0,R.jsx)(lt,{type:"custom-messages","data-testid":"custom-messages",children:(0,R.jsx)(Se,{withDivider:!0,children:m.map(I=>(0,R.jsx)(Zd,{suggestion:I},I.text))})}),r&&g.length>0&&(0,R.jsx)(lt,{type:"autoflows",title:e("titleAutoflows"),"data-testid":"autoflows",children:(0,R.jsx)(Se,{withDivider:!0,children:(0,R.jsx)(qd,{})})}),d.map(({type:I,title:j,amount:Qt,lines:No})=>{var Oo;switch(I){case"entities":return u&&u.length>0&&(0,R.jsx)(lt,{type:I,title:j,"data-testid":`type-${I}`,children:(0,R.jsx)($d,{entities:u})},I);default:return((Oo=b[I])==null?void 0:Oo.fetchState)==="done"&&b[I].suggestions.length>0&&(0,R.jsx)(lt,{type:I,title:j,"data-testid":`type-${I}`,children:(0,R.jsx)(Se,{withDivider:!0,children:(0,R.jsx)(tu,{lines:No,contentType:I,suggestions:b[I].suggestions.slice(0,Qt)||[]})})},I)}})]})})},au=uh;function Ao(t){let e=new Range;return e.selectNodeContents(t),e}function lu(t,e,o){try{return Et(t,e,o),!0}catch{return!1}}function yr(t){return"tagName"in t&&(t.tagName==="DIV"||t.tagName==="P")}function vr(t){return"tagName"in t&&t.tagName==="BR"}var Cn=/[\u200B-\u200D\uFEFF]/g;function Et(t,e,o){let n=new Range;if(t.firstChild===null&&e===0&&o===0)return n.selectNodeContents(t),n;let s=0,r=!1;function i(l,c){let p=-1,d=/[\u200B-\u200D\uFEFF]/;if(!d.test(l))return c;for(let g=0;g<=l.length;g++)if(d.test(l[g])||p++,p===c)return g;throw new Error("Offset out of range")}function a(l){switch(l.nodeType){case Node.TEXT_NODE:{let c=l.textContent,p=c.replace(Cn,""),d=s+p.length,g=e>=s&&e<=d,u=o>=s&&o<=d;if(g){let m=i(c,e-s);m===0&&!u?n.setStartBefore(l):n.setStart(l,m)}u&&(n.setEnd(l,i(c,o-s)),r=!0),s=d;break}case Node.ELEMENT_NODE:{if(vr(l)&&(s===e&&n.setStartBefore(l),s++,s===o)){n.setEndAfter(l),r=!0;return}for(let p=0;p<l.childNodes.length&&(a(l.childNodes[p]),!r);p++);let c=l.lastChild;yr(l)&&c&&!yr(c)&&!vr(c)&&s++;break}default:break}}if(a(t),n.startContainer===document)throw new Error("Offsets out of bound");return n}function wn(t,e){if(!t.contains(e.startContainer)||!t.contains(e.endContainer))throw new Error("Range not within root element");let{startContainer:o,startOffset:n,endContainer:s,endOffset:r,collapsed:i}=e,a,l,c=0;function p(d){let g=d===o,u=d===s;switch(d.nodeType){case Node.TEXT_NODE:{let m=d.textContent;g&&(a=c+m.substring(0,n).replace(Cn,"").length),u&&(l=c+m.substring(0,r).replace(Cn,"").length),c+=m.replace(Cn,"").length;break}case Node.ELEMENT_NODE:{let m=d.nextSibling===null;vr(d)&&!m&&c++;for(let f=0;f<d.childNodes.length;f++){let h=g&&f===n,k=u&&f===r;if(h&&(a=c),k&&(l=c),l!==void 0||((!h||!i)&&p(d.childNodes[f]),u&&f===r-1&&(l=c),l!==void 0))break}!u&&yr(d)&&!m&&c++,u&&(l=c);break}default:break}}if(p(t),l===void 0)throw new Error("Could not determine start and end");return{start:a??l,end:l}}function Tn(t,e){if(!t.contains(e.startContainer)||!t.contains(e.endContainer))throw new Error("Range not within root element");let{startContainer:o,startOffset:n,endContainer:s,endOffset:r}=e,i=-1,a="";function l(c){let p=c===o,d=c===s;switch(p&&i++,c.nodeType){case Node.TEXT_NODE:{if(i!==0)return;let g=p?n:0,u=d?r:void 0,m=c.textContent.replace(Cn,"");g===0&&u===void 0?a+=m:a+=m.substring(g,u);break}case Node.ELEMENT_NODE:{let g=c.nextSibling===null;i===0&&vr(c)&&!g&&(a+=`
8
8
  `);for(let u=p?n:0;u<(d?Math.min(r,c.childNodes.length):c.childNodes.length)&&(l(c.childNodes[u]),i!==1);u++);!d&&i===0&&yr(c)&&!g&&(a+=`
9
- `);break}default:break}d&&i++}return l(t),a}function cu(t){return t.top!==0||t.left!==0||t.height!==0||t.width!==0}var Xt=class extends qe{observer;lastKnownSelection=null;getRootNode(){return this.element.getRootNode()}getText(){let e=new Range;return e.selectNodeContents(this.element),Tn(this.element,e)}getHTML(){return this.element.innerHTML||""}getRange(){var r;let e=this.getRootNode();if(e.activeElement!==this.element)return null;let o="getSelection"in e?e.getSelection():window.getSelection();if(!o)return null;let n="getComposedRanges"in o&&e instanceof ShadowRoot?(r=o.getComposedRanges(e))==null?void 0:r[0]:o.rangeCount>0?o.getRangeAt(0):null;if(!n)return null;let s=this.element.ownerDocument.createRange();return s.setStart(n==null?void 0:n.startContainer,n==null?void 0:n.startOffset),s.setEnd(n==null?void 0:n.endContainer,n==null?void 0:n.endOffset),!s||!this.element.contains(s.startContainer)||!this.element.contains(s.endContainer)?null:s}getCaretPosition(){let e=this.getRange();if(!e||!e.collapsed||!("getBoundingClientRect"in e))return null;let o=e.getBoundingClientRect();return!cu(o)&&(e.insertNode(this.element.ownerDocument.createTextNode("\u2060")),o=e.getBoundingClientRect(),e.deleteContents(),!cu(o))?null:{top:o.top+o.height,left:o.left}}getSelection(){let e=this.getRange();if(e)return wn(this.element,e);let o=this.lastKnownSelection;if(o&&lu(this.element,o.start,o.end))return o;let n=Ao(this.element);return n.collapse(!1),wn(this.element,n)}getSelectedText(){let{start:e,end:o}=this.getSelection();return Tn(this.element,Et(this.element,e,o))}applyChanges(e){var s;if(!this.isActive)return;this.isSettingValue=!0;let o=this.getText(),n=e(this.element);return(s=this.observer)==null||s.takeRecords(),Promise.resolve(n).then(()=>{this.currentText=this.getText(),o!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(){super.listen(),this.observer=new MutationObserver(()=>{setTimeout(()=>{this.triggerChange()},0)}),this.observer.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0});let e=this.element.isContentEditable,o=new MutationObserver(()=>{this.element.isContentEditable!==e&&(e=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>o.disconnect())}dispose(){super.dispose(),this.observer&&this.observer.disconnect()}};function pu(t,e,o){let n=`deepdesk-iframe-${t}`,s=document.getElementById(n);if(s)return s;let r=document.createElement("iframe"),i=new URL(e);return Object.entries(o).forEach(([a,l])=>{i.searchParams.append(a,l)}),r.style.position="absolute",r.style.left="-999em",r.style.width="0px",r.style.height="0px",r.tabIndex=-1,r.id=n,r.title=`iframe-${t}`,r.src=i.toString(),window.document.body.appendChild(r),r}var ea=class{constructor(e){this.name=e;this.broadcastChannel=new BroadcastChannel(e)}broadcastChannel;disposeHandlers=[];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()}},ta=class{constructor(e,o,n){this.name=e;this.targetOrigin=o;this.options=n;this.iframe=pu(e,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}iframe;disposeHandlers=[];onMessage(e){window.addEventListener("message",e),this.disposeHandlers.push(()=>{window.removeEventListener("message",e)})}postMessage(e){var o;(o=this.iframe.contentWindow)==null||o.postMessage(JSON.stringify(e),this.targetOrigin)}close(){var e;this.disposeHandlers.forEach(o=>o()),(e=this.iframe)==null||e.remove()}},oa=class{constructor(e){this.params=e;this.deepdeskUrl=e.deepdeskUrl,this.eventMap=e.eventMap,this.sessionId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}sessionId;deepdeskUrl;channel;defaultChannel;eventMap;get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setSessionId(e){this.sessionId!==e&&(this.cleanup(),w.info("Set sessionId",e),this.sessionId=e,this.channel=this.createChannel(e))}createChannel(e){let o=this.params.createCustomChannel?this.params.createCustomChannel(e):this.isCrossOrigin?new ta(e,this.deepdeskUrl,{debug:!0}):new ea(e),n=s=>{var i,a;if(s.origin!==this.deepdeskUrl)return;let r=typeof s.data=="string"?JSON.parse(s.data):s.data;r.type==="event"&&r.channel===e&&(w.info("Received broadcast event",this.sessionId,s),(a=(i=this.eventMap)[r.name])==null||a.call(i,r.payload))};return o.onMessage(n),o}send(e,o){var r,i;w.info("Broadcast event",{sessionId:this.sessionId,name:e,payload:o});let n={type:"event",name:e,payload:o};(i=(r=this.eventMap)[e])==null||i.call(r,o);let s=this.sessionId==="deepdesk-general"?this.defaultChannel:this.channel;s==null||s.postMessage({...n,channel:this.sessionId})}cleanup(e=!1){var o,n;(o=this.channel)==null||o.close(),delete this.channel,e&&((n=this.defaultChannel)==null||n.close(),delete this.defaultChannel)}},du=oa;var Lo=class extends Error{constructor(o,n){super(o);this.body=n}name="CustomError"};var na=t=>new Promise(e=>{setTimeout(e,t)});var Mo=class extends Lo{name="ClientError"},sa=class extends Lo{name="ServerError"},Ne=class t{constructor(e="",o={}){this.baseUrl=e;this.options=o;o.fetch&&(this.fetch=o.fetch)}latestRequestByUrl={};csrfToken;fetch=window.fetch.bind(window);static refreshingToken=null;patchFetch(e){this.fetch=e(this.fetch)}setCsrfToken(e){this.csrfToken=e}request(e,o={}){return new Promise((n,s)=>{let r={isAborted:!1,reject:s},i=`${this.baseUrl}${e}`,a=this.fetch,{abortLatest:l=!1,attempts:c=1,retryDelay:p=500,refreshTokenOn401:d=!0,retryOnError:g=b=>b instanceof TypeError,retryOnResponse:u=b=>b.status>=500,version:m="v1",...f}=o,h={credentials:"include",...f,headers:{"Content-Type":"application/json",...f.headers}};o.method!==void 0&&o.method!=="GET"&&this.csrfToken&&(h.headers={...h.headers,"X-CSRFToken":this.csrfToken}),typeof m=="string"&&(h.headers={...h.headers,"X-Deepdesk-API-Version":m});let k=c,S=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[i]&&l&&(this.latestRequestByUrl[i].isAborted=!0,this.latestRequestByUrl[i].reject(new Error("Aborted"))),this.latestRequestByUrl[i]=r;let x=async()=>(k--,a(i,h).then(async b=>u(b)&&!r.isAborted&&k>0?(await na(p),x()):b.status===401&&d===!0&&S===!1?(S=!0,await this.refreshToken(),x()):b).catch(async b=>{if(g(b)&&!r.isAborted&&k>0)return await na(p),x();throw b}));x().then(b=>b.json().catch(()=>null).then(v=>{b.status>=500?s(new sa("Server Error",v)):b.status===401?s(new Mo("Unauthorized",v)):b.status===403?s(new Mo("Forbidden",v)):b.status===404?s(new Mo("Not Found",v)):b.status>=400&&s(new Mo("Bad Request",v)),delete this.latestRequestByUrl[i],n(v)})).catch(b=>{s(b)})})}async validateToken(){let{has_valid_access_token:e}=await this.get("/auth/validate");if(!e)return!1;let{is_logged_in:o}=await this.get("/apis/admin/session/validate/",{version:null});return!!o}refreshToken(){return t.refreshingToken||(t.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{t.refreshingToken=null},1e3*60)})),t.refreshingToken}get(e,o){return this.request(e,o)}post(e,o,n){return this.request(e,{method:"POST",body:JSON.stringify(o),...n})}patch(e,o,n){return this.request(e,{method:"PATCH",body:JSON.stringify(o),...n})}put(e,o,n){return this.request(e,{method:"PUT",body:JSON.stringify(o),...n})}delete(e,o){return this.request(e,{method:"DELETE",...o})}};var gh;(e=>{let t;(l=>(l.SEND_MESSAGE="Send Message",l.HANDLING_TIME="Handling Time",l.START_AUTOFLOW="Start Autoflow",l.ABORT_AUTOFLOW="Abort Autoflow",l.ADD_TO_PERSONAL_COLLECTION="Add to personal collection",l.DELETE_FROM_PERSONAL_COLLECTION="Delete from personal collection"))(t=e.EventType||={})})(gh||={});function Sr(t){return{...N(t),tags:t.tags}}var at=class t{constructor(e,o={}){this.options=o;this.client=new Ne(e,{fetch:o.fetch}),this.client.patchFetch(n=>async(s,r)=>{let i=await n(s,r);return this.handleDeepdeskVersionHeaders(i),i})}latestReceivedDeepdeskVersions={};client;shouldFetchCsrfToken=!0;static exchangeTokenPromise=null;async preflight(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let e=await this.getCsrfToken();this.client.setCsrfToken(e)}return this.options.token?(t.exchangeTokenPromise||(t.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),t.exchangeTokenPromise):Promise.resolve()}async createConversation(e){await this.preflight(),w.info(`Creating conversation for session ${e.sessionId} and agent ${e.agentId}`);let o=await this.client.post("/api/conversations",{...W(e),tags:e.tags},{version:"v2"});return Sr(o)}async getProfile(e){let o=await this.client.get(`/apis/admin/profiles/${e}/`,{version:null});return N(o)}async getKnowledgeAssistant(e){let o=await this.client.get(`/apis/admin/knowledge-assist/assistants/${e}/`,{version:null});return N(o)}async getContentTypes(){let e=await this.client.get("/apis/admin/content-types/",{version:null});return N(e)}async getPlatformConfig(){let{config:e}=await this.client.get("/platform/config/",{version:null});return N(e)}async checkUserExists(e){let{exists:o}=await this.client.get(`/apis/admin/users/exists?external_id=${e}`);return o}async getConversationBySessionId(e,o={}){await this.preflight(),w.info(`Getting conversation for session ${e}`);let{attempts:n=1,retryDelay:s=1e3}=o,r=await this.client.get(`/api/conversations/by_session_id/${e}`,{attempts:n,retryDelay:s,retryOnResponse:i=>i.status===404||i.status>=500,version:"v2"});return Sr(r)}async isConversationSupported(e,o={}){w.info(`Check if conversation for session ${e} is supported`);let{attempts:n=1,retryDelay:s=1e3}=o;return(await this.client.get(`/api/conversations/by_session_id/${e}/active_profile`,{attempts:n,retryDelay:s,retryOnResponse:i=>i.status===404||i.status>=500,version:"v2"})).has_active_profile}async updateConversation(e,o){let n=W(o);o.tags&&(n.tags=o.tags);let s=await this.client.put(`/api/conversations/${e}`,n,{version:"v2"});return Sr(s)}async postMessages(e,o){return(await this.client.post(`/api/conversations/${e}/messages`,o.map(s=>({...W(s),tags:s.tags})),{version:"v2"})).map(s=>Sr(s))}async sendEvent(e,o){let{data:n,...s}=o,r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((i,[a,l])=>({...i,[a]:l}),{});return this.client.post("/api/events",W({...r,...s,data:n,name:e}),{version:"v2"})}async sendEventV1(e,o){let n=Object.entries(this.latestReceivedDeepdeskVersions).reduce((s,[r,i])=>({...s,[r]:i}),{});return this.client.post("/api/events",{event:e,data:W({...o,...n})})}async getEntities(e){return(await this.client.post("/api/entities",{messages:e.filter(n=>n.text)})).entities}async getSummary(e,o={}){return(await this.client.post("/api/summary",{conversation:{messages:e.filter(s=>s.text&&s.source),agent_id:o.agentId,id:o.externalConversationId},prompt_instruction:o.promptInstruction,model:o.model})).summary}async getTemporaryExchangeToken(){return(await this.client.get("/auth/exchange-token",{version:null})).jwt}async exchangeTokenForAccessCookie(e){return this.client.post("/apis/admin/session/jwt/",{jwt:e},{version:null}).catch(o=>{throw w.warn(`Invalid token '${e}'`),o})}async authenticateWithKey(e,o){await this.client.post("/apis/admin/session/api-key/",W(o),{version:null,refreshTokenOn401:!1,headers:{apikey:e}})}async getTextSuggestions(e,o={},n){return n==="sticky-messages"?this.getPinnedMessages(e):(await this.client.post(`/api/conversations/${e}/recommend/${n}`,W(o),{abortLatest:!0})).map(r=>({...N(r),text:r.text||r.url||r.message,source:n,type:n})).filter((r,i,a)=>i===a.findIndex(l=>l.text===r.text))}async isLoggedIn(){return await this.preflight(),this.client.validateToken()}async getAutocompleteSuggestions(e,o){return(await this.client.post(`/api/conversations/${e}/autocomplete`,W(o),{abortLatest:!0})).map(s=>({score:1,source:s.source,sourceText:s.source_text,text:s.label,trainingJobs:s.training_jobs,searchKeywords:s.search_keywords,type:s.source})).filter((s,r,i)=>r===i.findIndex(a=>a.text===s.text))}async getPinnedMessages(e){let o=await this.client.get(`/api/conversations/${e}/sticky-messages`,{abortLatest:!0});return N(o).map(n=>({...n,text:n.message,source:"sticky-messages",type:"pinned-message"}))}async getStyleSuggestions(e){let o=await this.client.post("/api/style-suggestions",W(e),{abortLatest:!0});return N(o)}async search(e){let o=await this.client.post(`/api/profiles/${e.profile}/search`,W(e),{version:"v2"});return N(o)}async knowledgeAssist(e,o,n){let s=await this.client.post(`/api/knowledge-assist/assistants/${n}/search`,W({question:e.question,promptInstruction:e.promptInstruction,chatHistory:o.map(r=>({question:r.question,answer:r.answer.answer}))}),{version:"v2"});return N(s)}async requestLoginByEmail(e){let o=await this.client.post("/apis/admin/session/passwordless/request/",{email:e},{version:null});return N(o)}async requestPasswordlessToken(){let e=await this.client.get("/apis/admin/session/passwordless/request/",{version:null});return N(e.token)}async getCsrfToken(){let{token:e}=await this.client.get("/apis/admin/session/csrf/",{version:null});return e}async verifyLoginToken(e){let o=await this.client.post("/apis/admin/session/passwordless/login/",{token:e},{version:null});return N(o)}handleDeepdeskVersionHeaders(e){e.headers.forEach((o,n)=>{let s=n.toLowerCase(),r=s.match(Ra);if(!o||!r)return;let i=r[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&o&&a!==o&&w.warn(`Overwritten Version header ${s}: ${JSON.stringify(a)} -> ${JSON.stringify(o)}`),this.latestReceivedDeepdeskVersions[i]=o})}};var En=class{constructor(e,o){this.url=e;this.options={timeout:25e3,...o}}eventListeners={};options;timeoutTimer;eventSource;proxyEvent(e){this.eventSource.addEventListener(ci(e),o=>{let{data:n}=o;try{let s=JSON.parse(n);this.emit(e,N(s))}catch{w.warn(`Invalid JSON for ${e}: ${n}`)}})}connect(){clearTimeout(this.timeoutTimer);let e=new EventSource(this.url,{withCredentials:!0});this.eventSource=e;let o=!1;e.onopen=()=>{o=!0},e.onerror=()=>{o&&e.readyState===2&&this.connect()},this.timeoutTimer=setTimeout(()=>{e.close(),this.connect()},this.options.timeout),Object.keys(this.eventListeners).forEach(n=>{this.proxyEvent(n)})}disconnect(){var e;clearTimeout(this.timeoutTimer),this.eventListeners={},(e=this.eventSource)==null||e.close()}emit(e,o){this.eventListeners[e]&&this.eventListeners[e].forEach(n=>n(o))}on(e,o){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(o),this.proxyEvent(e),()=>{this.off(e,o)}}off(e,o){let n;this.eventListeners[e]&&(n=this.eventListeners[e].indexOf(o),n>-1&&this.eventListeners[e].splice(n,1))}};var mh;(e=>{let t;(r=>(r.Started="Started",r.Aborted="Aborted",r.Completed="Completed"))(t=e.AutoflowSessionState||={})})(mh||={});var kn=class{constructor(e,o={}){this.apiUrl=e;this.client=new Ne(e,o)}client;streams={};logger=w;async getCustomMessages(e){let o=await this.client.get(`/sessions/${e}/suggestions`);return N(o.suggestions)}async sendCustomMessage(e,o){let n=await this.client.post(`/sessions/${e}/messages`,W(o));return N(n)}async answerCustomMessage(e,o){await this.client.post(`/sessions/${e}/answers`,W(o))}async getAutoflows(e){let o=await this.client.get(`/sessions/${e}/autoflows`);return N(o.autoflows)}async startAutoflowSession(e){let o=await this.client.post("/autoflow-sessions",W(e));return N(o)}async stopAutoflowSession(e){await this.client.delete(`/autoflow-sessions/${e}`)}openStream(e){return this.streams[e]||(this.streams[e]=new En(`${this.apiUrl}/sessions/${e}/events`),this.streams[e].connect()),this.streams[e]}closeStream(e){this.streams[e]||(this.streams[e].disconnect(),delete this.streams[e])}};var Cr=require("@reduxjs/toolkit");var gu=require("@reduxjs/toolkit");var uu={startTime:null,stopTime:null},mu=(0,gu.createSlice)({name:"handlingTime",initialState:uu,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(O,()=>uu)}}),{handlingTimeStart:fu,handlingTimeStop:_r,handlingTimeReset:hu}=mu.actions,yu=mu.reducer;var vu=(t={})=>{let e={onAuthError:_o(!1),...t};return o=>n=>s=>("error"in s&&s.error.message==="Unauthorized"&&o.dispatch(e.onAuthError),n(s))};var br=require("@reduxjs/toolkit");var xr={list:{keywordMatches:[]},fetchState:"idle",isInitialRequest:null};var Zt=(0,br.createAsyncThunk)("styleSuggestions/getAll",async({text:t},e)=>{var i;let{deepdeskAPI:o}=e.extra,n=e.getState(),{showStyleSuggestions:s}=n.settings,r=(i=n.conversation.current)==null?void 0:i.profileCode;if(!s)return xr.list;if(!r)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:r,message:t})}),fh=(0,br.createSlice)({name:"styleSuggestions",initialState:xr,reducers:{},extraReducers:t=>{t.addCase(Zt.pending,e=>{e.isInitialRequest=e.isInitialRequest===null,e.fetchState="loading"}).addCase(Zt.rejected,e=>{e.fetchState="error"}).addCase(Zt.fulfilled,(e,o)=>{e.fetchState="done",pt(e.list,o.payload)||(e.list=o.payload)}).addCase(Pt,e=>{e.list=xr.list}).addCase(O,()=>xr)}}),Su=fh.reducer;var _u=(t={})=>{let e,o=!0,n={getStyleSuggestions:Zt,debounce:500,...t};return s=>r=>i=>{var u;let a=s.getState().input.text,l=r(i),c=s.getState();if(c.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:p}=c.settings;if(!((u=c.conversation.current)==null?void 0:u.id)||!p)return l;let{text:g}=c.input;return g===a&&!o||(clearTimeout(e),g==="")||(e=setTimeout(()=>{o=!1,s.dispatch(n.getStyleSuggestions({text:g}))},t.debounce)),l}};function hh(t,e){return t.text===e.text&&t.selection.start===e.selection.start&&t.selection.end===e.selection.end}var xu=(t={})=>{let e={getTextSuggestions:Pe,getAutocompleteSuggestions:en,debounce:200,check:ko,...t},o;return n=>s=>r=>{var f;let{input:{userCommitted:i}}=n.getState(),a=s(r),l=n.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:c,showTabCompletion:p}=l.settings,d=(f=l.conversation.current)==null?void 0:f.id,g=r.type===Os.toString();if(!d||!c&&!p)return a;let{input:{userCommitted:u}}=l;return hh(u,i)&&!g||(clearTimeout(o),!e.check(l))||(o=setTimeout(()=>{let h=so(l);h===""?n.dispatch(e.getTextSuggestions("default")):n.dispatch(e.getAutocompleteSuggestions(h))},g?0:e.debounce)),a}};var bu=Zt.fulfilled.toString();function yh(t,e){let o=new Set([...e.keywordMatches.map(s=>s.keyword)]),n=[];return o.forEach(s=>{let r=t.keywordMatches.filter(l=>l.keyword===s),i=e.keywordMatches.filter(l=>l.keyword===s),a=i.length-r.length;a<=0||n.push(...i.slice(0,a))}),n}var Cu=t=>e=>o=>n=>{var c;if(n.type!==bu){o(n);return}let s=e.getState().styleSuggestions.list;o(n);let r=e.getState(),i=r.styleSuggestions.list,a=(c=r.conversation)==null?void 0:c.current;if(s===i)return;let l=yh(s,i);n.type===bu&&l.length>0&&t.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var vh=(0,Cr.combineReducers)({activeSuggestion:xc,answer:dp,auth:Oc,autoflows:_d,conversation:Ha,contentTypes:Gc,customMessages:Rd,passwordlessToken:Md,entities:Qc,knowledgeAssistant:lp,handlingTime:yu,info:Xl,input:Nr.reducer,overlayInput:ae.reducer,settings:Ma,profile:mp,search:tc,summary:np,styleSuggestions:Su,ui:Ec,textSuggestions:fc});function wu(t){return(0,Cr.configureStore)({reducer:vh,middleware:e=>[...e({thunk:{extraArgument:{dynamicThunkObject:t.dynamicThunkObject,deepdeskAPI:t.deepdeskAPI,deepdeskBrokerAPI:t.deepdeskBrokerAPI}},serializableCheck:!1}),vu(),xu({debounce:200}),_u({debounce:500}),Cu(t.deepdeskAPI),...t.middleware?t.middleware:[]],preloadedState:t.preloadedState})}var Sh=t=>{var e;return((e=t==null?void 0:t.type)==null?void 0:e.toLowerCase())??"unknown"},_h=t=>e=>o=>n=>{var a;let s=e.getState(),r=Pr("inlineSuggestions")(s);switch(n.type){case $e.toString():{let l=Ns(n.payload.contentType)(e.getState()),c=l.indexOf(n.payload.suggestion);t.emit("edit-suggestion",{contentType:n.payload.contentType,index:c,suggestions:l});break}case _o.toString():{!n.payload&&t.emit("logout",void 0);break}case ke.toString():{let{start:l,end:c}=s.input.selection;t.emit("select-suggestion",{type:Sh(n.payload.suggestion),...n.payload,replace:n.payload.replace==="selection"?{start:l,end:c}:{start:0,end:c}},{mayApplyChanges:!0});break}case Zn.toString():{let{start:l,end:c}=s.input.selection;t.emit("replace",{...n.payload,replace:n.payload.replace==="selection"?{start:l,end:c}:{start:0,end:c}},{mayApplyChanges:!0});break}case Ko.toString():{let l=e.getState(),{text:c,selection:p}=l.input.userCommitted;t.emit("reset",{text:c,selectionAfter:p},{mayApplyChanges:!0});break}case es.toString():t.emit("select-image",n.payload,{mayApplyChanges:!0}),t.sendEvent("Image attached",{conversationId:s.conversation.current.id,data:{path:n.payload.suggestion.image,title:n.payload.suggestion.title}});break;case Le.fulfilled.toString():n.payload.length>0&&t.sendEvent("entities found",{conversationId:s.conversation.current.id,data:{entities:n.payload}});break;case Qe.fulfilled.toString():t.sendEvent("conversation summarized",{conversationId:s.conversation.current.id,data:{summary:n.payload.summary}});break;case Q.toString():t.sendEvent(n.payload.name,{conversationId:((a=n.payload.options)==null?void 0:a.includeConversationData)&&s.conversation.current.id,data:n.payload.data});break;case Qn.toString():t.handleKeyDown(n.payload);break;case Pt.toString():t.logSendMessage(n.payload);break;case Jn.toString():t.logSendEditSuggestionMessage(n.payload);break;case Yn.toString():t.handleInputChanged(n.payload);break;default:break}let i=o(n);switch(n.type){case Pt.toString():t.handleAfterSendMessage(n.payload);break;case tn.toString():t.onUpdateShowTabHint(n.payload);break;case _r.toString():t.logHandlingTime();break;case ke.toString():{r&&(e.dispatch(He([])),e.dispatch(ze()));break}case He.toString():{r&&n.payload.length>0&&e.dispatch(ut(0));break}default:break}return i},Tu=_h;function ra(t){return t.toISOString().replace("T"," ").replace("Z","")}function Eu(t,e){var s,r,i;let{startTime:o,stopTime:n}=t.handlingTime;if(!o||!n)throw new Error("No startTime and stopTime for handling time metrics");return{conversationId:t.conversation.current.id,clientVersion:e.version,agentId:(s=t.info.agentInfo)==null?void 0:s.agentId,agentName:(r=t.info.agentInfo)==null?void 0:r.agentName,agentEmail:(i=t.info.agentInfo)==null?void 0:i.agentEmail,timeStart:ra(o),timeStop:ra(n)}}function ia(t,e,o){var M,K,L;let{text:n,metrics:{numCharsTyped:s,numCharsPasted:r,numCharsCut:i,numCharsDeleted:a,numPaste:l,agentStartedTypingTimestamp:c,externalTimeTotalSeconds:p,pastes:d,cuts:g,deletions:u,textSuggestions:m,offeredTextSuggestions:f}}=e[t],h=n.length,S=m.reduce((Z,{text:I,searchTerm:j})=>Z+I.length-(j?j.length:0),0),x=c??Date.now(),b=(Date.now()-x)/1e3+(p||0),v=s/b,A=m.reduce((Z,{searchTerm:I})=>Z+(I?I.length:0),0);return{conversationId:e.conversation.current.id,source:"agent",text:n,clientVersion:o.version,pastes:d,cuts:g,deletions:u,lenTextTyped:s+A,lenTextTotal:h,lenTextAssisted:S,lenTextPasted:r,lenTextCut:i,lenTextDeleted:a,timeTotalSeconds:b,charsPerSecond:v,numPastes:l,textSuggestionsV2:m,suggestionsCounters:[{source:"gpt",countOffered:f.filter(Z=>Z.source==="gpt").length}],agentId:(M=e.info.agentInfo)==null?void 0:M.agentId,agentName:(K=e.info.agentInfo)==null?void 0:K.agentName,agentEmail:(L=e.info.agentInfo)==null?void 0:L.agentEmail}}function aa(t,e){var r;let o=t.closest(e);if(o)return o;let n=t.getRootNode().host;if(n instanceof HTMLElement)return aa(n,e);let s=(r=t.ownerDocument.defaultView)==null?void 0:r.frameElement;return s?aa(s,e):null}function ku(t,e){return aa(t,e)}function Iu(t){return typeof t=="object"&&t!==null&&"name"in t&&"message"in t}function xh(t){return typeof t=="object"&&t!==null&&"tagName"in t}function wr(t){return xh(t)&&(xt(t)||ys(t))}var Ru=(t,e)=>({value(){try{let o=sessionStorage.getItem(`dd-${t}`);if(!o)return e;try{return JSON.parse(o)}catch{return e}}catch{return e}},update(o){try{sessionStorage.setItem(`dd-${t}`,JSON.stringify(o))}catch{w.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function bh(t){return t.offsetParent!==null}function Pu(t){if(!bh(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 Tr(t,e,o=100){let n=Pu(t);e({isVisible:n});let s=setInterval(()=>{let r=Pu(t);r!==n&&(n=r,e({isVisible:n}))},o);return()=>{clearTimeout(s)}}var V=require("react/jsx-runtime");var Au=Ru("showTabHint",!0),In=class t{static version="10.10.3-beta.6";static count=0;deepdeskApi;inputMediator=null;version;broadcastEvents;eventListeners={};unmountHandlers=[];widgetRoot=null;dynamicThunkObject={};isMounted=!1;instanceId;shouldRender=!0;store;constructor({deepdeskUrl:e,brokerUrl:o,version:n=t.version||"unknown",locale:s="en-US",token:r,fetch:i,productName:a,createCustomChannel:l}){let c=e.replace(/\/api$/,"");this.deepdeskApi=new at(c,{token:r,fetch:i}),this.version=n,this.instanceId=t.count++;let p={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[Tu({emit:(d,g,u)=>this.emit(d,g,u),handleAfterSendMessage:d=>this.handleAfterSendMessage(d),handleInputChanged:d=>this.handleInputChanged(d),handleKeyDown:d=>this.handleKeyDown(d),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:d=>this.logSendMessage(d),logSendEditSuggestionMessage:d=>this.logSendEditMessage(d),onUpdateShowTabHint:d=>Au.update(d),sendEvent:(d,g)=>this.deepdeskApi.sendEvent(d,g)})]};o&&Object.assign(p,{deepdeskBrokerAPI:new kn(o)}),this.store=wu(p),this.broadcastEvents=new du({debug:!0,deepdeskUrl:c,eventMap:Dc(this.store),createCustomChannel:l}),this.store.dispatch(Fo),this.store.dispatch(tn(Au.value())),this.store.dispatch(Fo({locale:s,adminUrl:c,productName:a}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){return this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex]??null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(w.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(w.warn("Profile has not been loaded (yet)"),!0):(w.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(_o(null)),this.store.dispatch(Xe()),new Promise(e=>{let o=this.store.subscribe(()=>{let n=this.store.getState();ne(n)&&Rc(n)!=="loading"&&(o(),e())});this.unmountHandlers.push(()=>{o()})})}async isLoggedIn(){return(await this.store.dispatch(Xe())).payload}async setPlatformAgentId(e){try{if((await this.deepdeskApi.client.get("/apis/admin/session/me/",{version:null})).external_id)return;await this.deepdeskApi.client.request("/apis/admin/session/me/",{method:"PATCH",body:JSON.stringify({external_id:e}),version:null})}catch(o){w.warn("Failed to attach user:",o)}}async isConversationSupported(e,o){return(await this.store.dispatch(Lr({sessionId:e,options:o}))).payload}async createConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(Vn(e))).payload}async getConversationBySessionId(e,o){return this.hasConversation()&&this.sessionId()!==e&&this.resetConversation(),(await this.store.dispatch(qn({sessionId:e,options:o}))).payload}async upsertConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(Mr(e))).payload}async postMessages(e){return(await this.store.dispatch(Gn(e))).payload}async updateConversation(e){return(await this.store.dispatch(Wn(e))).payload}resetConversation(){this.store.dispatch(O()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}async getSummary(){let e=await this.store.dispatch(Qe());if(e.error)throw new Error(e.error.message);return e.payload.summary}configure(e){this.store.dispatch(Fo(e))}setVisitorInfo(e){this.store.dispatch($l(e))}async setAgentInfo(e){await this.store.dispatch(Zo(e))}async setAgentSettings(e){await this.store.dispatch(pi(e))}async getAgentSettings(){return(await this.store.dispatch(di())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let e=[];return this.store.dispatch(Os()),e.push(this.refreshWidgetSuggestions()),Promise.all(e).then(()=>{})}notifyInputChanged(e){this.store.dispatch(Yn(e))}notifyKeyDown(e){this.store.dispatch(Qn(e))}notifyPaste(e,o){this.store.dispatch(Za({text:e,selectionText:o}))}notifyCut(e){this.store.dispatch($a(e))}notifyExternalSuggestion(e){this.store.dispatch(ke(e)),this.store.dispatch(ze())}notifyEditSuggestion(e){this.store.dispatch(gc(e.contentType,e.suggestions)),this.store.dispatch($e({contentType:e.contentType,suggestion:typeof e.index=="number"?e.suggestions[e.index]:null}))}handleInputChanged(e){let{overlayCollapsed:o,openOverlayWhenTyping:n}=this.state.ui;o&&n&&this.store.dispatch(yt({collapse:!1})),this.inputMediator&&this.store.dispatch(ja({text:e,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(He([])))}handleKeyDown(e){let{overlayCollapsed:o}=this.state.ui,{textSuggestions:n,selectedSuggestionIndex:s,selection:r}=this.state.input,{inlineSuggestions:i}=this.state.settings,a=n.length>0,l=s!==-1;if(this.store.dispatch(Xa(Xn(e))),e.key!=="Tab"&&!this.settings.showTextSuggestions)return;let c=()=>{o||!a||r&&(e.shiftKey||(this.store.dispatch(qa()),i||this.stageSelectedSuggestion({inputType:"arrow"}),e.preventDefault()))},p=()=>{o||!a||i&&s<=0||r&&(e.shiftKey||(this.store.dispatch(Ga()),e.preventDefault(),!i&&(this.state.input.selectedSuggestionIndex===-1?this.store.dispatch(Ko()):this.stageSelectedSuggestion({inputType:"arrow"}))))};switch(e.key){case"Up":case"ArrowUp":i?p():c();return;case"Down":case"ArrowDown":{i?c():p();return}case"Esc":case"Escape":{i&&l&&this.store.dispatch(ut(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(ut(-1)),this.store.dispatch(Ko()),e.preventDefault()):o||(this.store.dispatch(yt({collapse:!0})),this.store.dispatch(wc(!0)),e.preventDefault());return}case"Tab":{let{userCommitted:d}=this.state.input,g=d.text.substring(0,d.selection.end),{tabCompletionSuggestion:u}=this.state.input;this.store.dispatch(tn(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!i&&this.settings.showTabCompletion&&u&&u.text.startsWith(g)&&(this.store.dispatch(ke({text:u.text,suggestion:u,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch(ze())),e.preventDefault();break}default:}}handleAfterSendMessage(e){this.emit("send-message",e),this.store.dispatch(Qa()),this.store.dispatch(He([]))}handlingTimeStart(){this.state.handlingTime.startTime||(w.info("Start handling time"),this.store.dispatch(fu()))}handlingTimeStop(){this.state.handlingTime.startTime&&(w.info("Stop handling time"),this.store.dispatch(_r()))}logSendMessage(e){let o=ia("input",this.state,{version:this.version});e&&(Object.assign(o,{text:e}),Object.assign(o,{lenTextTotal:e.length})),this.deepdeskApi.sendEventV1("Send Message",o),this.emit("send-message-event",o)}logSendEditMessage(e){let o=ia("overlayInput",this.state,{version:this.version});e&&Object.assign(o,{text:e}),this.store.dispatch(Va(this.state.overlayInput.metrics))}logHandlingTime(){let e=Eu(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",e),this.store.dispatch(hu())}notifySubmit(e={}){this.shouldAbort()||(this.store.dispatch(ze()),this.store.dispatch(Pt(e.text??this.state.input.text)))}stageSelectedSuggestion(e){let o=this.state.input.selectedSuggestionIndex,{textSuggestions:n}=this.state.input;this.store.dispatch(ke({text:n[o].text,suggestion:n[o],eventMetrics:e,replace:"until-selection-end"}))}emit(e,o,n={}){let s=()=>{this.eventListeners[e]&&this.eventListeners[e].forEach(r=>{try{r(o)}catch(i){w.warn(`The following error occurred in deepdeskSDK.on('${e}', handler)`),w.error(i)}})};this.inputMediator&&n.mayApplyChanges?this.inputMediator.applyChanges(s):s()}on(e,o){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(o),()=>{this.off(e,o)}}off(e,o){if(!e&&!o){this.eventListeners={};return}let n;this.eventListeners[e]&&(n=this.eventListeners[e].indexOf(o),n>-1&&this.eventListeners[e].splice(n,1))}setConversationQuery(e){this.dynamicThunkObject.conversationQuery=e}whenConversationLoaded(e){let o=()=>this.loadProfileConfig().then(()=>e());this.hasConversation()&&o();let n=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==n&&(n=this.hasConversation(),n&&o())})}overlayContainerFactory(e,o,n,s){let[r,i]=Mt(o,n);return r.setAttribute("translate","no"),r.dataset.testid=e,s&&r.classList.add(s),this.unmountHandlers.push(()=>{(0,we.unmountComponentAtNode)(r),i(),r.remove()}),r}createInlineContainer(e,o){var i;let n=document.createElement("div");n.style.position="absolute",n.style.top="0px",n.style.left="0px",n.style.height="0px",n.style.width="0px";let s=document.createElement("div");s.style.display="none",s.style.position="absolute",s.style.height="0px",s.style.width="0px",s.style.backgroundColor="red",n.appendChild(s);let r=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;if(r){let[a,l]=Mt(r,{appendTo:document.body,onMoveStart:()=>{s.style.display="none"}});a.dataset.testid=o,a.style.zIndex="2",a.appendChild(n),this.unmountHandlers.push(()=>{(0,we.unmountComponentAtNode)(s),l()})}else document.body.appendChild(n);return s}createContainer(e,o=document.body){let n=window.getComputedStyle(o),s=document.createElement("div");return Lt(s),s.dataset.testid=e,s.style.color=n.color,s.style.fontSize=n.fontSize,s.style.fontFamily=n.fontFamily,s.style.fontVariant=n.fontVariant,s.setAttribute("translate","no"),o.appendChild(s),this.unmountHandlers.push(()=>{(0,we.unmountComponentAtNode)(s),s.remove()}),s}storeMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,o=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(e,o),w.info(`Stored analytics for ${this.conversationId()}`)}catch{}}restoreMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,o=window.sessionStorage.getItem(e);if(!o)return;let n=JSON.parse(o);n.text.trim()===this.state.input.text.trim()?(w.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(Ya(n.metrics))):w.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(e)}catch{}}mount(e,o={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!wr(e))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let{customStyles:n={},showStyleSuggestions:s,showTabCompletion:r,showTextSuggestions:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:c,showSuggestionsAfterPattern:p,isEmbedded:d,detectSubmit:g,insertLink:u,inputMediator:m,closestScrollSelector:f,appendOverlayTo:h,inlineSuggestions:k,floatingMenu:S}=o;this.configure({showStyleSuggestions:s,showTabCompletion:r,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:c,showSuggestionsAfterPattern:p,showTextSuggestions:i,insertLink:u,isEmbedded:d,inlineSuggestions:k,floatingMenu:!!S}),o.automaticHandlingTime&&this.setupHandlingTime(e),Lt(e),this.inputMediator=m||(xt(e)?new We(e):new Xt(e)),this.inputMediator.on("change",({plainText:v})=>{this.notifyInputChanged(v)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(Ja({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",v=>{this.notifyKeyDown(v)}),this.inputMediator.on("paste",({pastedText:v,selectionText:A})=>{this.notifyPaste(v,A)}),this.inputMediator.on("cut",({selectionText:v})=>{this.notifyCut(v)});let x=f&&ku(e,f)||void 0;if(k){let{customStyles:v,appendOverlayTo:A}=o;if(xt(e))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let M=this.createInlineContainer(e,"deepdesk-caret");(0,we.render)((0,V.jsx)(Gt,{store:this.store,customStyles:v,children:(0,V.jsx)(jt,{broadcastEvents:this.broadcastEvents,children:(0,V.jsx)(Dp,{})})}),M),this.inputMediator.on("caret",L=>{this.store.dispatch(He([])),L?(M.style.display="block",M.style.top=`${L.top}px`,M.style.left=`${L.left}px`):M.style.display="none"});let K=this.overlayContainerFactory("floating-menu",x||e,{appendTo:typeof S=="object"&&"appendOverlayTo"in S?S.appendOverlayTo:A},v==null?void 0:v.floatingMenuRootNode);(0,we.render)((0,V.jsx)(Gt,{store:this.store,customStyles:v,children:(0,V.jsx)(jt,{broadcastEvents:this.broadcastEvents,children:(0,V.jsx)(Rp,{onLogIn:()=>this.loginViaPopup().catch(L=>w.warn(L.message))})})}),K)}else{let v=this.overlayContainerFactory("deepdesk-tab-completion",x||e,{appendTo:h,closestScrollElement:x,mirrorOverflow:!0,onRemove:()=>this.unmount()},n==null?void 0:n.rootNode),A=this.overlayContainerFactory("deepdesk-suggestions-overlay",x||e,{appendTo:h},n==null?void 0:n.suggestionsRootNode);(0,we.render)((0,V.jsx)(Gt,{store:this.store,customStyles:n,children:(0,V.jsx)(jt,{broadcastEvents:this.broadcastEvents,children:(0,V.jsx)(md,{inputElement:e})})}),v),(0,we.render)((0,V.jsx)(Gt,{store:this.store,customStyles:n,children:(0,V.jsx)(jt,{broadcastEvents:this.broadcastEvents,children:(0,V.jsx)(Wp,{onLogIn:()=>this.loginViaPopup().catch(M=>w.warn(M.message))})})}),A)}(0,we.render)((0,V.jsx)(Gt,{store:this.store,customStyles:n,children:(0,V.jsx)(jt,{broadcastEvents:this.broadcastEvents,children:(0,V.jsx)(bp,{})})}),this.createContainer("deepdesk-overlays"));let b;this.inputMediator.on("selection",v=>{clearTimeout(b),v===null?b=setTimeout(()=>{v!==null&&this.store.dispatch(Or(v))},500):this.store.dispatch(Or(v))}),this.inputMediator.on("disabled",()=>{var v;(v=this.inputMediator)==null||v.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{g&&this.notifySubmit()}),this.inputMediator.on("blur",()=>this.store.dispatch(vo(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(vo(!0))),this.store.dispatch(za({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.unmountHandlers.push(()=>{this.state.input.text!==""&&(this.store.dispatch(ze()),this.storeMetrics())}),this.whenConversationLoaded(()=>{var v;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((v=this.state.conversation.current)==null?void 0:v.sessionId)}),this.isMounted=!0}unmount(){var e;this.unmountHandlers.forEach(o=>o()),this.unmountHandlers=[],(e=this.inputMediator)==null||e.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(e,o={}){if(this.widgetRoot&&w.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:n,showImages:s,isEmbedded:r}=o;this.widgetRoot=e,this.configure({showImages:s,isEmbedded:r}),(0,we.render)((0,V.jsx)(Gt,{store:this.store,customStyles:n,children:(0,V.jsx)(jt,{broadcastEvents:this.broadcastEvents,children:(0,V.jsx)(au,{onLogIn:()=>this.loginViaPopup().catch(i=>w.warn(i.message))})})}),e),this.whenConversationLoaded(()=>{var i;this.broadcastEvents.setSessionId((i=this.state.conversation.current)==null?void 0:i.sessionId)})}unmountWidget(){this.widgetRoot&&(0,we.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(e){let o=Tr(e,({isVisible:n})=>{n?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),o()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){Iu(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(fn());let e=St(this.state);e&&(await this.store.dispatch(un()),this.store.dispatch(Fo({showSearch:e.search,showAutoflows:e.autoflows,showCustomMessages:e.customMessages,showImageSearch:e.imageSearch,showEntitiesCommand:e.entitiesCommand,showSummaryCommand:e.summarizer,showKnowledgeSearch:!!e.knowledgeAssistant,recommendTextSuggestions:e.recommendTextSuggestions})))}),this.loadProfileConfigPromise)}async loginViaPopup(e){return new Promise((o,n)=>{let s=new MessageChannel,r=s.port1,i=this.state.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 l=!1,c=()=>{p&&!p.closed&&p.close(),window.removeEventListener("message",d),clearInterval(g)};r.onmessage=async u=>{var m,f;if((m=u.data)!=null&&m.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((f=u.data)==null?void 0:f.jwt),await this.isLoggedIn(),this.broadcastEvents.send(sn),l=!0,s.port1.close(),o()}catch(h){console.error(h),n(h)}finally{l=!0,c()}};let p=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");p===null&&n(new Error("Popup blocked by browser"));let d=async u=>{var m;if(u.origin===a.origin)switch((m=u.data)==null?void 0:m.type){case"deepdesk-popup-loaded":{try{let f=JSON.stringify({type:"deepdesk-popup-create-channel"});p==null||p.postMessage(f,a.origin,[s.port2])}catch(f){w.error("Error posting message to popup",f),n(f)}break}case"deepdesk-popup-error":{c(),u.data.message==="Timeout"&&w.warn("Popup timed out. Check if the account's platform url is configured correctly."),n(new Error(u.data.message));break}}};window.addEventListener("message",d);let g=setInterval(()=>{p&&!p.closed||(c(),l||n(new Error("Popup closed by user")))},200);this.unmountHandlers.push(c)})}async checkForTrialMode(e){try{let{account:o}=await this.deepdeskApi.getPlatformConfig();if(!o.isTrial){this.shouldRender=!0;return}if(w.info("Trial is active"),!await this.deepdeskApi.checkUserExists(e))throw new Error("User is not in trial");this.shouldRender=!0}catch(o){let{message:n}=o;w.info(n),this.shouldRender=!1}}async refreshWidgetSuggestions(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:e}=this.state.profile.data;if(!e.widget)return;let o=Ws(this.state);try{o.forEach(({type:n})=>{n==="entities"?this.store.dispatch(Le()):this.store.dispatch(Pe(n))})}catch(n){this.handleError(n)}}};async function Lu(t,e,o={}){let{value:n}=t,{start:s,end:r}=o.replace??{start:0,end:n.length},i=`${n.slice(0,s)}${e}${n.slice(r)}`,a=o.selectionAfter??{start:s+e.length,end:s+e.length},l=()=>{if(o.setValue)return o.setValue(i);t.value=i};return Promise.resolve(l()).then(()=>{t.selectionStart=a.start,t.selectionEnd=a.end,t.blur(),t.focus()})}async function Mu(t,e,o={}){let n=o.replace?Et(t,o.replace.start,o.replace.end):Ao(t),s,r=()=>{if(o.setRange)return o.setRange(n.cloneRange());n.deleteContents(),s=document.createElement("span"),n.insertNode(s),o.insertBRs!==!1?e.split(`
9
+ `);break}default:break}d&&i++}return l(t),a}function cu(t){return t.top!==0||t.left!==0||t.height!==0||t.width!==0}var Xt=class extends qe{observer;lastKnownSelection=null;getRootNode(){return this.element.getRootNode()}getText(){let e=new Range;return e.selectNodeContents(this.element),Tn(this.element,e)}getHTML(){return this.element.innerHTML||""}getRange(){var r;let e=this.getRootNode();if(e.activeElement!==this.element)return null;let o="getSelection"in e?e.getSelection():window.getSelection();if(!o)return null;let n="getComposedRanges"in o&&e instanceof ShadowRoot?(r=o.getComposedRanges(e))==null?void 0:r[0]:o.rangeCount>0?o.getRangeAt(0):null;if(!n)return null;let s=this.element.ownerDocument.createRange();return s.setStart(n==null?void 0:n.startContainer,n==null?void 0:n.startOffset),s.setEnd(n==null?void 0:n.endContainer,n==null?void 0:n.endOffset),!s||!this.element.contains(s.startContainer)||!this.element.contains(s.endContainer)?null:s}getCaretPosition(){let e=this.getRange();if(!e||!e.collapsed||!("getBoundingClientRect"in e))return null;let o=e.getBoundingClientRect();return!cu(o)&&(e.insertNode(this.element.ownerDocument.createTextNode("\u2060")),o=e.getBoundingClientRect(),e.deleteContents(),!cu(o))?null:{top:o.top+o.height,left:o.left}}getSelection(){let e=this.getRange();if(e)return wn(this.element,e);let o=this.lastKnownSelection;if(o&&lu(this.element,o.start,o.end))return o;let n=Ao(this.element);return n.collapse(!1),wn(this.element,n)}getSelectedText(){let{start:e,end:o}=this.getSelection();return Tn(this.element,Et(this.element,e,o))}applyChanges(e){var s;if(!this.isActive)return;this.isSettingValue=!0;let o=this.getText(),n=e(this.element);return(s=this.observer)==null||s.takeRecords(),Promise.resolve(n).then(()=>{this.currentText=this.getText(),o!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(){super.listen(),this.observer=new MutationObserver(()=>{setTimeout(()=>{this.triggerChange()},0)}),this.observer.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0});let e=this.element.isContentEditable,o=new MutationObserver(()=>{this.element.isContentEditable!==e&&(e=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>o.disconnect())}dispose(){super.dispose(),this.observer&&this.observer.disconnect()}};function pu(t,e,o){let n=`deepdesk-iframe-${t}`,s=document.getElementById(n);if(s)return s;let r=document.createElement("iframe"),i=new URL(e);return Object.entries(o).forEach(([a,l])=>{i.searchParams.append(a,l)}),r.style.position="absolute",r.style.left="-999em",r.style.width="0px",r.style.height="0px",r.tabIndex=-1,r.id=n,r.title=`iframe-${t}`,r.src=i.toString(),window.document.body.appendChild(r),r}var ea=class{constructor(e){this.name=e;this.broadcastChannel=new BroadcastChannel(e)}broadcastChannel;disposeHandlers=[];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()}},ta=class{constructor(e,o,n){this.name=e;this.targetOrigin=o;this.options=n;this.iframe=pu(e,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}iframe;disposeHandlers=[];onMessage(e){window.addEventListener("message",e),this.disposeHandlers.push(()=>{window.removeEventListener("message",e)})}postMessage(e){var o;(o=this.iframe.contentWindow)==null||o.postMessage(JSON.stringify(e),this.targetOrigin)}close(){var e;this.disposeHandlers.forEach(o=>o()),(e=this.iframe)==null||e.remove()}},oa=class{constructor(e){this.params=e;this.deepdeskUrl=e.deepdeskUrl,this.eventMap=e.eventMap,this.sessionId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}sessionId;deepdeskUrl;channel;defaultChannel;eventMap;get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setSessionId(e){this.sessionId!==e&&(this.cleanup(),w.info("Set sessionId",e),this.sessionId=e,this.channel=this.createChannel(e))}createChannel(e){let o=this.params.createCustomChannel?this.params.createCustomChannel(e):this.isCrossOrigin?new ta(e,this.deepdeskUrl,{debug:!0}):new ea(e),n=s=>{var i,a;if(s.origin!==this.deepdeskUrl)return;let r=typeof s.data=="string"?JSON.parse(s.data):s.data;r.type==="event"&&r.channel===e&&(w.info("Received broadcast event",this.sessionId,s),(a=(i=this.eventMap)[r.name])==null||a.call(i,r.payload))};return o.onMessage(n),o}send(e,o){var r,i;w.info("Broadcast event",{sessionId:this.sessionId,name:e,payload:o});let n={type:"event",name:e,payload:o};(i=(r=this.eventMap)[e])==null||i.call(r,o);let s=this.sessionId==="deepdesk-general"?this.defaultChannel:this.channel;s==null||s.postMessage({...n,channel:this.sessionId})}cleanup(e=!1){var o,n;(o=this.channel)==null||o.close(),delete this.channel,e&&((n=this.defaultChannel)==null||n.close(),delete this.defaultChannel)}},du=oa;var Lo=class extends Error{constructor(o,n){super(o);this.body=n}name="CustomError"};var na=t=>new Promise(e=>{setTimeout(e,t)});var Mo=class extends Lo{name="ClientError"},sa=class extends Lo{name="ServerError"},Ne=class t{constructor(e="",o={}){this.baseUrl=e;this.options=o;o.fetch&&(this.fetch=o.fetch)}latestRequestByUrl={};csrfToken;fetch=window.fetch.bind(window);static refreshingToken=null;patchFetch(e){this.fetch=e(this.fetch)}setCsrfToken(e){this.csrfToken=e}request(e,o={}){return new Promise((n,s)=>{let r={isAborted:!1,reject:s},i=`${this.baseUrl}${e}`,a=this.fetch,{abortLatest:l=!1,attempts:c=1,retryDelay:p=500,refreshTokenOn401:d=!0,retryOnError:g=b=>b instanceof TypeError,retryOnResponse:u=b=>b.status>=500,version:m="v1",...f}=o,h={credentials:"include",...f,headers:{"Content-Type":"application/json",...f.headers}};o.method!==void 0&&o.method!=="GET"&&this.csrfToken&&(h.headers={...h.headers,"X-CSRFToken":this.csrfToken}),typeof m=="string"&&(h.headers={...h.headers,"X-Deepdesk-API-Version":m});let k=c,S=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[i]&&l&&(this.latestRequestByUrl[i].isAborted=!0,this.latestRequestByUrl[i].reject(new Error("Aborted"))),this.latestRequestByUrl[i]=r;let x=async()=>(k--,a(i,h).then(async b=>u(b)&&!r.isAborted&&k>0?(await na(p),x()):b.status===401&&d===!0&&S===!1?(S=!0,await this.refreshToken(),x()):b).catch(async b=>{if(g(b)&&!r.isAborted&&k>0)return await na(p),x();throw b}));x().then(b=>b.json().catch(()=>null).then(v=>{b.status>=500?s(new sa("Server Error",v)):b.status===401?s(new Mo("Unauthorized",v)):b.status===403?s(new Mo("Forbidden",v)):b.status===404?s(new Mo("Not Found",v)):b.status>=400&&s(new Mo("Bad Request",v)),delete this.latestRequestByUrl[i],n(v)})).catch(b=>{s(b)})})}async validateToken(){let{has_valid_access_token:e}=await this.get("/auth/validate");if(!e)return!1;let{is_logged_in:o}=await this.get("/apis/admin/session/validate/",{version:null});return!!o}refreshToken(){return t.refreshingToken||(t.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{t.refreshingToken=null},1e3*60)})),t.refreshingToken}get(e,o){return this.request(e,o)}post(e,o,n){return this.request(e,{method:"POST",body:JSON.stringify(o),...n})}patch(e,o,n){return this.request(e,{method:"PATCH",body:JSON.stringify(o),...n})}put(e,o,n){return this.request(e,{method:"PUT",body:JSON.stringify(o),...n})}delete(e,o){return this.request(e,{method:"DELETE",...o})}};var gh;(e=>{let t;(l=>(l.SEND_MESSAGE="Send Message",l.HANDLING_TIME="Handling Time",l.START_AUTOFLOW="Start Autoflow",l.ABORT_AUTOFLOW="Abort Autoflow",l.ADD_TO_PERSONAL_COLLECTION="Add to personal collection",l.DELETE_FROM_PERSONAL_COLLECTION="Delete from personal collection"))(t=e.EventType||={})})(gh||={});function Sr(t){return{...N(t),tags:t.tags}}var at=class t{constructor(e,o={}){this.options=o;this.client=new Ne(e,{fetch:o.fetch}),this.client.patchFetch(n=>async(s,r)=>{let i=await n(s,r);return this.handleDeepdeskVersionHeaders(i),i})}latestReceivedDeepdeskVersions={};client;shouldFetchCsrfToken=!0;static exchangeTokenPromise=null;async preflight(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let e=await this.getCsrfToken();this.client.setCsrfToken(e)}return this.options.token?(t.exchangeTokenPromise||(t.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),t.exchangeTokenPromise):Promise.resolve()}async createConversation(e){await this.preflight(),w.info(`Creating conversation for session ${e.sessionId} and agent ${e.agentId}`);let o=await this.client.post("/api/conversations",{...W(e),tags:e.tags},{version:"v2"});return Sr(o)}async getProfile(e){let o=await this.client.get(`/apis/admin/profiles/${e}/`,{version:null});return N(o)}async getKnowledgeAssistant(e){let o=await this.client.get(`/apis/admin/knowledge-assist/assistants/${e}/`,{version:null});return N(o)}async getContentTypes(){let e=await this.client.get("/apis/admin/content-types/",{version:null});return N(e)}async getPlatformConfig(){let{config:e}=await this.client.get("/platform/config/",{version:null});return N(e)}async checkUserExists(e){let{exists:o}=await this.client.get(`/apis/admin/users/exists?external_id=${e}`);return o}async getConversationBySessionId(e,o={}){await this.preflight(),w.info(`Getting conversation for session ${e}`);let{attempts:n=1,retryDelay:s=1e3}=o,r=await this.client.get(`/api/conversations/by_session_id/${e}`,{attempts:n,retryDelay:s,retryOnResponse:i=>i.status===404||i.status>=500,version:"v2"});return Sr(r)}async isConversationSupported(e,o={}){w.info(`Check if conversation for session ${e} is supported`);let{attempts:n=1,retryDelay:s=1e3}=o;return(await this.client.get(`/api/conversations/by_session_id/${e}/active_profile`,{attempts:n,retryDelay:s,retryOnResponse:i=>i.status===404||i.status>=500,version:"v2"})).has_active_profile}async updateConversation(e,o){let n=W(o);o.tags&&(n.tags=o.tags);let s=await this.client.put(`/api/conversations/${e}`,n,{version:"v2"});return Sr(s)}async postMessages(e,o){return(await this.client.post(`/api/conversations/${e}/messages`,o.map(s=>({...W(s),tags:s.tags})),{version:"v2"})).map(s=>Sr(s))}async sendEvent(e,o){let{data:n,...s}=o,r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((i,[a,l])=>({...i,[a]:l}),{});return this.client.post("/api/events",W({...r,...s,data:n,name:e}),{version:"v2"})}async sendEventV1(e,o){let n=Object.entries(this.latestReceivedDeepdeskVersions).reduce((s,[r,i])=>({...s,[r]:i}),{});return this.client.post("/api/events",{event:e,data:W({...o,...n})})}async getEntities(e){return(await this.client.post("/api/entities",{messages:e.filter(n=>n.text)})).entities}async getSummary(e,o={}){return(await this.client.post("/api/summary",{conversation:{messages:e.filter(s=>s.text&&s.source),agent_id:o.agentId,id:o.externalConversationId},prompt_instruction:o.promptInstruction,model:o.model})).summary}async getTemporaryExchangeToken(){return(await this.client.get("/auth/exchange-token",{version:null})).jwt}async exchangeTokenForAccessCookie(e){return this.client.post("/apis/admin/session/jwt/",{jwt:e},{version:null}).catch(o=>{throw w.warn(`Invalid token '${e}'`),o})}async authenticateWithKey(e,o){await this.client.post("/apis/admin/session/api-key/",W(o),{version:null,refreshTokenOn401:!1,headers:{apikey:e}})}async getTextSuggestions(e,o={},n){return n==="sticky-messages"?this.getPinnedMessages(e):(await this.client.post(`/api/conversations/${e}/recommend/${n}`,W(o),{abortLatest:!0})).map(r=>({...N(r),text:r.text||r.url||r.message,source:n,type:n})).filter((r,i,a)=>i===a.findIndex(l=>l.text===r.text))}async isLoggedIn(){return await this.preflight(),this.client.validateToken()}async getAutocompleteSuggestions(e,o){return(await this.client.post(`/api/conversations/${e}/autocomplete`,W(o),{abortLatest:!0})).map(s=>({score:1,source:s.source,sourceText:s.source_text,text:s.label,trainingJobs:s.training_jobs,searchKeywords:s.search_keywords,type:s.source})).filter((s,r,i)=>r===i.findIndex(a=>a.text===s.text))}async getPinnedMessages(e){let o=await this.client.get(`/api/conversations/${e}/sticky-messages`,{abortLatest:!0});return N(o).map(n=>({...n,text:n.message,source:"sticky-messages",type:"pinned-message"}))}async getStyleSuggestions(e){let o=await this.client.post("/api/style-suggestions",W(e),{abortLatest:!0});return N(o)}async search(e){let o=await this.client.post(`/api/profiles/${e.profile}/search`,W(e),{version:"v2"});return N(o)}async knowledgeAssist(e,o,n){let s=await this.client.post(`/api/knowledge-assist/assistants/${n}/search`,W({question:e.question,promptInstruction:e.promptInstruction,chatHistory:o.map(r=>({question:r.question,answer:r.answer.answer}))}),{version:"v2"});return N(s)}async requestLoginByEmail(e){let o=await this.client.post("/apis/admin/session/passwordless/request/",{email:e},{version:null});return N(o)}async requestPasswordlessToken(){let e=await this.client.get("/apis/admin/session/passwordless/request/",{version:null});return N(e.token)}async getCsrfToken(){let{token:e}=await this.client.get("/apis/admin/session/csrf/",{version:null});return e}async verifyLoginToken(e){let o=await this.client.post("/apis/admin/session/passwordless/login/",{token:e},{version:null});return N(o)}handleDeepdeskVersionHeaders(e){e.headers.forEach((o,n)=>{let s=n.toLowerCase(),r=s.match(Ra);if(!o||!r)return;let i=r[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&o&&a!==o&&w.warn(`Overwritten Version header ${s}: ${JSON.stringify(a)} -> ${JSON.stringify(o)}`),this.latestReceivedDeepdeskVersions[i]=o})}};var En=class{constructor(e,o){this.url=e;this.options={timeout:25e3,...o}}eventListeners={};options;timeoutTimer;eventSource;proxyEvent(e){this.eventSource.addEventListener(ci(e),o=>{let{data:n}=o;try{let s=JSON.parse(n);this.emit(e,N(s))}catch{w.warn(`Invalid JSON for ${e}: ${n}`)}})}connect(){clearTimeout(this.timeoutTimer);let e=new EventSource(this.url,{withCredentials:!0});this.eventSource=e;let o=!1;e.onopen=()=>{o=!0},e.onerror=()=>{o&&e.readyState===2&&this.connect()},this.timeoutTimer=setTimeout(()=>{e.close(),this.connect()},this.options.timeout),Object.keys(this.eventListeners).forEach(n=>{this.proxyEvent(n)})}disconnect(){var e;clearTimeout(this.timeoutTimer),this.eventListeners={},(e=this.eventSource)==null||e.close()}emit(e,o){this.eventListeners[e]&&this.eventListeners[e].forEach(n=>n(o))}on(e,o){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(o),this.proxyEvent(e),()=>{this.off(e,o)}}off(e,o){let n;this.eventListeners[e]&&(n=this.eventListeners[e].indexOf(o),n>-1&&this.eventListeners[e].splice(n,1))}};var mh;(e=>{let t;(r=>(r.Started="Started",r.Aborted="Aborted",r.Completed="Completed"))(t=e.AutoflowSessionState||={})})(mh||={});var kn=class{constructor(e,o={}){this.apiUrl=e;this.client=new Ne(e,o)}client;streams={};logger=w;async getCustomMessages(e){let o=await this.client.get(`/sessions/${e}/suggestions`);return N(o.suggestions)}async sendCustomMessage(e,o){let n=await this.client.post(`/sessions/${e}/messages`,W(o));return N(n)}async answerCustomMessage(e,o){await this.client.post(`/sessions/${e}/answers`,W(o))}async getAutoflows(e){let o=await this.client.get(`/sessions/${e}/autoflows`);return N(o.autoflows)}async startAutoflowSession(e){let o=await this.client.post("/autoflow-sessions",W(e));return N(o)}async stopAutoflowSession(e){await this.client.delete(`/autoflow-sessions/${e}`)}openStream(e){return this.streams[e]||(this.streams[e]=new En(`${this.apiUrl}/sessions/${e}/events`),this.streams[e].connect()),this.streams[e]}closeStream(e){this.streams[e]||(this.streams[e].disconnect(),delete this.streams[e])}};var Cr=require("@reduxjs/toolkit");var gu=require("@reduxjs/toolkit");var uu={startTime:null,stopTime:null},mu=(0,gu.createSlice)({name:"handlingTime",initialState:uu,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(O,()=>uu)}}),{handlingTimeStart:fu,handlingTimeStop:_r,handlingTimeReset:hu}=mu.actions,yu=mu.reducer;var vu=(t={})=>{let e={onAuthError:_o(!1),...t};return o=>n=>s=>("error"in s&&s.error.message==="Unauthorized"&&o.dispatch(e.onAuthError),n(s))};var br=require("@reduxjs/toolkit");var xr={list:{keywordMatches:[]},fetchState:"idle",isInitialRequest:null};var Zt=(0,br.createAsyncThunk)("styleSuggestions/getAll",async({text:t},e)=>{var i;let{deepdeskAPI:o}=e.extra,n=e.getState(),{showStyleSuggestions:s}=n.settings,r=(i=n.conversation.current)==null?void 0:i.profileCode;if(!s)return xr.list;if(!r)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:r,message:t})}),fh=(0,br.createSlice)({name:"styleSuggestions",initialState:xr,reducers:{},extraReducers:t=>{t.addCase(Zt.pending,e=>{e.isInitialRequest=e.isInitialRequest===null,e.fetchState="loading"}).addCase(Zt.rejected,e=>{e.fetchState="error"}).addCase(Zt.fulfilled,(e,o)=>{e.fetchState="done",pt(e.list,o.payload)||(e.list=o.payload)}).addCase(Pt,e=>{e.list=xr.list}).addCase(O,()=>xr)}}),Su=fh.reducer;var _u=(t={})=>{let e,o=!0,n={getStyleSuggestions:Zt,debounce:500,...t};return s=>r=>i=>{var u;let a=s.getState().input.text,l=r(i),c=s.getState();if(c.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:p}=c.settings;if(!((u=c.conversation.current)==null?void 0:u.id)||!p)return l;let{text:g}=c.input;return g===a&&!o||(clearTimeout(e),g==="")||(e=setTimeout(()=>{o=!1,s.dispatch(n.getStyleSuggestions({text:g}))},t.debounce)),l}};function hh(t,e){return t.text===e.text&&t.selection.start===e.selection.start&&t.selection.end===e.selection.end}var xu=(t={})=>{let e={getTextSuggestions:Pe,getAutocompleteSuggestions:en,debounce:200,check:ko,...t},o;return n=>s=>r=>{var f;let{input:{userCommitted:i}}=n.getState(),a=s(r),l=n.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:c,showTabCompletion:p}=l.settings,d=(f=l.conversation.current)==null?void 0:f.id,g=r.type===Os.toString();if(!d||!c&&!p)return a;let{input:{userCommitted:u}}=l;return hh(u,i)&&!g||(clearTimeout(o),!e.check(l))||(o=setTimeout(()=>{let h=so(l);h===""?n.dispatch(e.getTextSuggestions("default")):n.dispatch(e.getAutocompleteSuggestions(h))},g?0:e.debounce)),a}};var bu=Zt.fulfilled.toString();function yh(t,e){let o=new Set([...e.keywordMatches.map(s=>s.keyword)]),n=[];return o.forEach(s=>{let r=t.keywordMatches.filter(l=>l.keyword===s),i=e.keywordMatches.filter(l=>l.keyword===s),a=i.length-r.length;a<=0||n.push(...i.slice(0,a))}),n}var Cu=t=>e=>o=>n=>{var c;if(n.type!==bu){o(n);return}let s=e.getState().styleSuggestions.list;o(n);let r=e.getState(),i=r.styleSuggestions.list,a=(c=r.conversation)==null?void 0:c.current;if(s===i)return;let l=yh(s,i);n.type===bu&&l.length>0&&t.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var vh=(0,Cr.combineReducers)({activeSuggestion:xc,answer:dp,auth:Oc,autoflows:_d,conversation:Ha,contentTypes:Gc,customMessages:Rd,passwordlessToken:Md,entities:Qc,knowledgeAssistant:lp,handlingTime:yu,info:Xl,input:Nr.reducer,overlayInput:ae.reducer,settings:Ma,profile:mp,search:tc,summary:np,styleSuggestions:Su,ui:Ec,textSuggestions:fc});function wu(t){return(0,Cr.configureStore)({reducer:vh,middleware:e=>[...e({thunk:{extraArgument:{dynamicThunkObject:t.dynamicThunkObject,deepdeskAPI:t.deepdeskAPI,deepdeskBrokerAPI:t.deepdeskBrokerAPI}},serializableCheck:!1}),vu(),xu({debounce:200}),_u({debounce:500}),Cu(t.deepdeskAPI),...t.middleware?t.middleware:[]],preloadedState:t.preloadedState})}var Sh=t=>{var e;return((e=t==null?void 0:t.type)==null?void 0:e.toLowerCase())??"unknown"},_h=t=>e=>o=>n=>{var a;let s=e.getState(),r=Pr("inlineSuggestions")(s);switch(n.type){case $e.toString():{let l=Ns(n.payload.contentType)(e.getState()),c=l.indexOf(n.payload.suggestion);t.emit("edit-suggestion",{contentType:n.payload.contentType,index:c,suggestions:l});break}case _o.toString():{!n.payload&&t.emit("logout",void 0);break}case ke.toString():{let{start:l,end:c}=s.input.selection;t.emit("select-suggestion",{type:Sh(n.payload.suggestion),...n.payload,replace:n.payload.replace==="selection"?{start:l,end:c}:{start:0,end:c}},{mayApplyChanges:!0});break}case Zn.toString():{let{start:l,end:c}=s.input.selection;t.emit("replace",{...n.payload,replace:n.payload.replace==="selection"?{start:l,end:c}:{start:0,end:c}},{mayApplyChanges:!0});break}case Ko.toString():{let l=e.getState(),{text:c,selection:p}=l.input.userCommitted;t.emit("reset",{text:c,selectionAfter:p},{mayApplyChanges:!0});break}case es.toString():t.emit("select-image",n.payload,{mayApplyChanges:!0}),t.sendEvent("Image attached",{conversationId:s.conversation.current.id,data:{path:n.payload.suggestion.image,title:n.payload.suggestion.title}});break;case Le.fulfilled.toString():n.payload.length>0&&t.sendEvent("entities found",{conversationId:s.conversation.current.id,data:{entities:n.payload}});break;case Qe.fulfilled.toString():t.sendEvent("conversation summarized",{conversationId:s.conversation.current.id,data:{summary:n.payload.summary}});break;case Q.toString():t.sendEvent(n.payload.name,{conversationId:((a=n.payload.options)==null?void 0:a.includeConversationData)&&s.conversation.current.id,data:n.payload.data});break;case Qn.toString():t.handleKeyDown(n.payload);break;case Pt.toString():t.logSendMessage(n.payload);break;case Jn.toString():t.logSendEditSuggestionMessage(n.payload);break;case Yn.toString():t.handleInputChanged(n.payload);break;default:break}let i=o(n);switch(n.type){case Pt.toString():t.handleAfterSendMessage(n.payload);break;case tn.toString():t.onUpdateShowTabHint(n.payload);break;case _r.toString():t.logHandlingTime();break;case ke.toString():{r&&(e.dispatch(He([])),e.dispatch(ze()));break}case He.toString():{r&&n.payload.length>0&&e.dispatch(ut(0));break}default:break}return i},Tu=_h;function ra(t){return t.toISOString().replace("T"," ").replace("Z","")}function Eu(t,e){var s,r,i;let{startTime:o,stopTime:n}=t.handlingTime;if(!o||!n)throw new Error("No startTime and stopTime for handling time metrics");return{conversationId:t.conversation.current.id,clientVersion:e.version,agentId:(s=t.info.agentInfo)==null?void 0:s.agentId,agentName:(r=t.info.agentInfo)==null?void 0:r.agentName,agentEmail:(i=t.info.agentInfo)==null?void 0:i.agentEmail,timeStart:ra(o),timeStop:ra(n)}}function ia(t,e,o){var M,K,L;let{text:n,metrics:{numCharsTyped:s,numCharsPasted:r,numCharsCut:i,numCharsDeleted:a,numPaste:l,agentStartedTypingTimestamp:c,externalTimeTotalSeconds:p,pastes:d,cuts:g,deletions:u,textSuggestions:m,offeredTextSuggestions:f}}=e[t],h=n.length,S=m.reduce((Z,{text:I,searchTerm:j})=>Z+I.length-(j?j.length:0),0),x=c??Date.now(),b=(Date.now()-x)/1e3+(p||0),v=s/b,A=m.reduce((Z,{searchTerm:I})=>Z+(I?I.length:0),0);return{conversationId:e.conversation.current.id,source:"agent",text:n,clientVersion:o.version,pastes:d,cuts:g,deletions:u,lenTextTyped:s+A,lenTextTotal:h,lenTextAssisted:S,lenTextPasted:r,lenTextCut:i,lenTextDeleted:a,timeTotalSeconds:b,charsPerSecond:v,numPastes:l,textSuggestionsV2:m,suggestionsCounters:[{source:"gpt",countOffered:f.filter(Z=>Z.source==="gpt").length}],agentId:(M=e.info.agentInfo)==null?void 0:M.agentId,agentName:(K=e.info.agentInfo)==null?void 0:K.agentName,agentEmail:(L=e.info.agentInfo)==null?void 0:L.agentEmail}}function aa(t,e){var r;let o=t.closest(e);if(o)return o;let n=t.getRootNode().host;if(n instanceof HTMLElement)return aa(n,e);let s=(r=t.ownerDocument.defaultView)==null?void 0:r.frameElement;return s?aa(s,e):null}function ku(t,e){return aa(t,e)}function Iu(t){return typeof t=="object"&&t!==null&&"name"in t&&"message"in t}function xh(t){return typeof t=="object"&&t!==null&&"tagName"in t}function wr(t){return xh(t)&&(xt(t)||ys(t))}var Ru=(t,e)=>({value(){try{let o=sessionStorage.getItem(`dd-${t}`);if(!o)return e;try{return JSON.parse(o)}catch{return e}}catch{return e}},update(o){try{sessionStorage.setItem(`dd-${t}`,JSON.stringify(o))}catch{w.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function bh(t){return t.offsetParent!==null}function Pu(t){if(!bh(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 Tr(t,e,o=100){let n=Pu(t);e({isVisible:n});let s=setInterval(()=>{let r=Pu(t);r!==n&&(n=r,e({isVisible:n}))},o);return()=>{clearTimeout(s)}}var V=require("react/jsx-runtime");var Au=Ru("showTabHint",!0),In=class t{static version="10.10.3";static count=0;deepdeskApi;inputMediator=null;version;broadcastEvents;eventListeners={};unmountHandlers=[];widgetRoot=null;dynamicThunkObject={};isMounted=!1;instanceId;shouldRender=!0;store;constructor({deepdeskUrl:e,brokerUrl:o,version:n=t.version||"unknown",locale:s="en-US",token:r,fetch:i,productName:a,createCustomChannel:l}){let c=e.replace(/\/api$/,"");this.deepdeskApi=new at(c,{token:r,fetch:i}),this.version=n,this.instanceId=t.count++;let p={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[Tu({emit:(d,g,u)=>this.emit(d,g,u),handleAfterSendMessage:d=>this.handleAfterSendMessage(d),handleInputChanged:d=>this.handleInputChanged(d),handleKeyDown:d=>this.handleKeyDown(d),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:d=>this.logSendMessage(d),logSendEditSuggestionMessage:d=>this.logSendEditMessage(d),onUpdateShowTabHint:d=>Au.update(d),sendEvent:(d,g)=>this.deepdeskApi.sendEvent(d,g)})]};o&&Object.assign(p,{deepdeskBrokerAPI:new kn(o)}),this.store=wu(p),this.broadcastEvents=new du({debug:!0,deepdeskUrl:c,eventMap:Dc(this.store),createCustomChannel:l}),this.store.dispatch(Fo),this.store.dispatch(tn(Au.value())),this.store.dispatch(Fo({locale:s,adminUrl:c,productName:a}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){return this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex]??null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(w.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(w.warn("Profile has not been loaded (yet)"),!0):(w.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(_o(null)),this.store.dispatch(Xe()),new Promise(e=>{let o=this.store.subscribe(()=>{let n=this.store.getState();ne(n)&&Rc(n)!=="loading"&&(o(),e())});this.unmountHandlers.push(()=>{o()})})}async isLoggedIn(){return(await this.store.dispatch(Xe())).payload}async setPlatformAgentId(e){try{if((await this.deepdeskApi.client.get("/apis/admin/session/me/",{version:null})).external_id)return;await this.deepdeskApi.client.request("/apis/admin/session/me/",{method:"PATCH",body:JSON.stringify({external_id:e}),version:null})}catch(o){w.warn("Failed to attach user:",o)}}async isConversationSupported(e,o){return(await this.store.dispatch(Lr({sessionId:e,options:o}))).payload}async createConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(Vn(e))).payload}async getConversationBySessionId(e,o){return this.hasConversation()&&this.sessionId()!==e&&this.resetConversation(),(await this.store.dispatch(qn({sessionId:e,options:o}))).payload}async upsertConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(Mr(e))).payload}async postMessages(e){return(await this.store.dispatch(Gn(e))).payload}async updateConversation(e){return(await this.store.dispatch(Wn(e))).payload}resetConversation(){this.store.dispatch(O()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}async getSummary(){let e=await this.store.dispatch(Qe());if(e.error)throw new Error(e.error.message);return e.payload.summary}configure(e){this.store.dispatch(Fo(e))}setVisitorInfo(e){this.store.dispatch($l(e))}async setAgentInfo(e){await this.store.dispatch(Zo(e))}async setAgentSettings(e){await this.store.dispatch(pi(e))}async getAgentSettings(){return(await this.store.dispatch(di())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let e=[];return this.store.dispatch(Os()),e.push(this.refreshWidgetSuggestions()),Promise.all(e).then(()=>{})}notifyInputChanged(e){this.store.dispatch(Yn(e))}notifyKeyDown(e){this.store.dispatch(Qn(e))}notifyPaste(e,o){this.store.dispatch(Za({text:e,selectionText:o}))}notifyCut(e){this.store.dispatch($a(e))}notifyExternalSuggestion(e){this.store.dispatch(ke(e)),this.store.dispatch(ze())}notifyEditSuggestion(e){this.store.dispatch(gc(e.contentType,e.suggestions)),this.store.dispatch($e({contentType:e.contentType,suggestion:typeof e.index=="number"?e.suggestions[e.index]:null}))}handleInputChanged(e){let{overlayCollapsed:o,openOverlayWhenTyping:n}=this.state.ui;o&&n&&this.store.dispatch(yt({collapse:!1})),this.inputMediator&&this.store.dispatch(ja({text:e,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(He([])))}handleKeyDown(e){let{overlayCollapsed:o}=this.state.ui,{textSuggestions:n,selectedSuggestionIndex:s,selection:r}=this.state.input,{inlineSuggestions:i}=this.state.settings,a=n.length>0,l=s!==-1;if(this.store.dispatch(Xa(Xn(e))),e.key!=="Tab"&&!this.settings.showTextSuggestions)return;let c=()=>{o||!a||r&&(e.shiftKey||(this.store.dispatch(qa()),i||this.stageSelectedSuggestion({inputType:"arrow"}),e.preventDefault()))},p=()=>{o||!a||i&&s<=0||r&&(e.shiftKey||(this.store.dispatch(Ga()),e.preventDefault(),!i&&(this.state.input.selectedSuggestionIndex===-1?this.store.dispatch(Ko()):this.stageSelectedSuggestion({inputType:"arrow"}))))};switch(e.key){case"Up":case"ArrowUp":i?p():c();return;case"Down":case"ArrowDown":{i?c():p();return}case"Esc":case"Escape":{i&&l&&this.store.dispatch(ut(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(ut(-1)),this.store.dispatch(Ko()),e.preventDefault()):o||(this.store.dispatch(yt({collapse:!0})),this.store.dispatch(wc(!0)),e.preventDefault());return}case"Tab":{let{userCommitted:d}=this.state.input,g=d.text.substring(0,d.selection.end),{tabCompletionSuggestion:u}=this.state.input;this.store.dispatch(tn(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!i&&this.settings.showTabCompletion&&u&&u.text.startsWith(g)&&(this.store.dispatch(ke({text:u.text,suggestion:u,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch(ze())),e.preventDefault();break}default:}}handleAfterSendMessage(e){this.emit("send-message",e),this.store.dispatch(Qa()),this.store.dispatch(He([]))}handlingTimeStart(){this.state.handlingTime.startTime||(w.info("Start handling time"),this.store.dispatch(fu()))}handlingTimeStop(){this.state.handlingTime.startTime&&(w.info("Stop handling time"),this.store.dispatch(_r()))}logSendMessage(e){let o=ia("input",this.state,{version:this.version});e&&(Object.assign(o,{text:e}),Object.assign(o,{lenTextTotal:e.length})),this.deepdeskApi.sendEventV1("Send Message",o),this.emit("send-message-event",o)}logSendEditMessage(e){let o=ia("overlayInput",this.state,{version:this.version});e&&Object.assign(o,{text:e}),this.store.dispatch(Va(this.state.overlayInput.metrics))}logHandlingTime(){let e=Eu(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",e),this.store.dispatch(hu())}notifySubmit(e={}){this.shouldAbort()||(this.store.dispatch(ze()),this.store.dispatch(Pt(e.text??this.state.input.text)))}stageSelectedSuggestion(e){let o=this.state.input.selectedSuggestionIndex,{textSuggestions:n}=this.state.input;this.store.dispatch(ke({text:n[o].text,suggestion:n[o],eventMetrics:e,replace:"until-selection-end"}))}emit(e,o,n={}){let s=()=>{this.eventListeners[e]&&this.eventListeners[e].forEach(r=>{try{r(o)}catch(i){w.warn(`The following error occurred in deepdeskSDK.on('${e}', handler)`),w.error(i)}})};this.inputMediator&&n.mayApplyChanges?this.inputMediator.applyChanges(s):s()}on(e,o){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(o),()=>{this.off(e,o)}}off(e,o){if(!e&&!o){this.eventListeners={};return}let n;this.eventListeners[e]&&(n=this.eventListeners[e].indexOf(o),n>-1&&this.eventListeners[e].splice(n,1))}setConversationQuery(e){this.dynamicThunkObject.conversationQuery=e}whenConversationLoaded(e){let o=()=>this.loadProfileConfig().then(()=>e());this.hasConversation()&&o();let n=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==n&&(n=this.hasConversation(),n&&o())})}overlayContainerFactory(e,o,n,s){let[r,i]=Mt(o,n);return r.setAttribute("translate","no"),r.dataset.testid=e,s&&r.classList.add(s),this.unmountHandlers.push(()=>{(0,we.unmountComponentAtNode)(r),i(),r.remove()}),r}createInlineContainer(e,o){var i;let n=document.createElement("div");n.style.position="absolute",n.style.top="0px",n.style.left="0px",n.style.height="0px",n.style.width="0px";let s=document.createElement("div");s.style.display="none",s.style.position="absolute",s.style.height="0px",s.style.width="0px",s.style.backgroundColor="red",n.appendChild(s);let r=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;if(r){let[a,l]=Mt(r,{appendTo:document.body,onMoveStart:()=>{s.style.display="none"}});a.dataset.testid=o,a.style.zIndex="2",a.appendChild(n),this.unmountHandlers.push(()=>{(0,we.unmountComponentAtNode)(s),l()})}else document.body.appendChild(n);return s}createContainer(e,o=document.body){let n=window.getComputedStyle(o),s=document.createElement("div");return Lt(s),s.dataset.testid=e,s.style.color=n.color,s.style.fontSize=n.fontSize,s.style.fontFamily=n.fontFamily,s.style.fontVariant=n.fontVariant,s.setAttribute("translate","no"),o.appendChild(s),this.unmountHandlers.push(()=>{(0,we.unmountComponentAtNode)(s),s.remove()}),s}storeMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,o=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(e,o),w.info(`Stored analytics for ${this.conversationId()}`)}catch{}}restoreMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,o=window.sessionStorage.getItem(e);if(!o)return;let n=JSON.parse(o);n.text.trim()===this.state.input.text.trim()?(w.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(Ya(n.metrics))):w.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(e)}catch{}}mount(e,o={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!wr(e))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let{customStyles:n={},showStyleSuggestions:s,showTabCompletion:r,showTextSuggestions:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:c,showSuggestionsAfterPattern:p,isEmbedded:d,detectSubmit:g,insertLink:u,inputMediator:m,closestScrollSelector:f,appendOverlayTo:h,inlineSuggestions:k,floatingMenu:S}=o;this.configure({showStyleSuggestions:s,showTabCompletion:r,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:c,showSuggestionsAfterPattern:p,showTextSuggestions:i,insertLink:u,isEmbedded:d,inlineSuggestions:k,floatingMenu:!!S}),o.automaticHandlingTime&&this.setupHandlingTime(e),Lt(e),this.inputMediator=m||(xt(e)?new We(e):new Xt(e)),this.inputMediator.on("change",({plainText:v})=>{this.notifyInputChanged(v)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(Ja({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",v=>{this.notifyKeyDown(v)}),this.inputMediator.on("paste",({pastedText:v,selectionText:A})=>{this.notifyPaste(v,A)}),this.inputMediator.on("cut",({selectionText:v})=>{this.notifyCut(v)});let x=f&&ku(e,f)||void 0;if(k){let{customStyles:v,appendOverlayTo:A}=o;if(xt(e))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let M=this.createInlineContainer(e,"deepdesk-caret");(0,we.render)((0,V.jsx)(Gt,{store:this.store,customStyles:v,children:(0,V.jsx)(jt,{broadcastEvents:this.broadcastEvents,children:(0,V.jsx)(Dp,{})})}),M),this.inputMediator.on("caret",L=>{this.store.dispatch(He([])),L?(M.style.display="block",M.style.top=`${L.top}px`,M.style.left=`${L.left}px`):M.style.display="none"});let K=this.overlayContainerFactory("floating-menu",x||e,{appendTo:typeof S=="object"&&"appendOverlayTo"in S?S.appendOverlayTo:A},v==null?void 0:v.floatingMenuRootNode);(0,we.render)((0,V.jsx)(Gt,{store:this.store,customStyles:v,children:(0,V.jsx)(jt,{broadcastEvents:this.broadcastEvents,children:(0,V.jsx)(Rp,{onLogIn:()=>this.loginViaPopup().catch(L=>w.warn(L.message))})})}),K)}else{let v=this.overlayContainerFactory("deepdesk-tab-completion",x||e,{appendTo:h,closestScrollElement:x,mirrorOverflow:!0,onRemove:()=>this.unmount()},n==null?void 0:n.rootNode),A=this.overlayContainerFactory("deepdesk-suggestions-overlay",x||e,{appendTo:h},n==null?void 0:n.suggestionsRootNode);(0,we.render)((0,V.jsx)(Gt,{store:this.store,customStyles:n,children:(0,V.jsx)(jt,{broadcastEvents:this.broadcastEvents,children:(0,V.jsx)(md,{inputElement:e})})}),v),(0,we.render)((0,V.jsx)(Gt,{store:this.store,customStyles:n,children:(0,V.jsx)(jt,{broadcastEvents:this.broadcastEvents,children:(0,V.jsx)(Wp,{onLogIn:()=>this.loginViaPopup().catch(M=>w.warn(M.message))})})}),A)}(0,we.render)((0,V.jsx)(Gt,{store:this.store,customStyles:n,children:(0,V.jsx)(jt,{broadcastEvents:this.broadcastEvents,children:(0,V.jsx)(bp,{})})}),this.createContainer("deepdesk-overlays"));let b;this.inputMediator.on("selection",v=>{clearTimeout(b),v===null?b=setTimeout(()=>{v!==null&&this.store.dispatch(Or(v))},500):this.store.dispatch(Or(v))}),this.inputMediator.on("disabled",()=>{var v;(v=this.inputMediator)==null||v.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{g&&this.notifySubmit()}),this.inputMediator.on("blur",()=>this.store.dispatch(vo(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(vo(!0))),this.store.dispatch(za({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.unmountHandlers.push(()=>{this.state.input.text!==""&&(this.store.dispatch(ze()),this.storeMetrics())}),this.whenConversationLoaded(()=>{var v;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((v=this.state.conversation.current)==null?void 0:v.sessionId)}),this.isMounted=!0}unmount(){var e;this.unmountHandlers.forEach(o=>o()),this.unmountHandlers=[],(e=this.inputMediator)==null||e.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(e,o={}){if(this.widgetRoot&&w.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:n,showImages:s,isEmbedded:r}=o;this.widgetRoot=e,this.configure({showImages:s,isEmbedded:r}),(0,we.render)((0,V.jsx)(Gt,{store:this.store,customStyles:n,children:(0,V.jsx)(jt,{broadcastEvents:this.broadcastEvents,children:(0,V.jsx)(au,{onLogIn:()=>this.loginViaPopup().catch(i=>w.warn(i.message))})})}),e),this.whenConversationLoaded(()=>{var i;this.broadcastEvents.setSessionId((i=this.state.conversation.current)==null?void 0:i.sessionId)})}unmountWidget(){this.widgetRoot&&(0,we.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(e){let o=Tr(e,({isVisible:n})=>{n?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),o()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){Iu(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(fn());let e=St(this.state);e&&(await this.store.dispatch(un()),this.store.dispatch(Fo({showSearch:e.search,showAutoflows:e.autoflows,showCustomMessages:e.customMessages,showImageSearch:e.imageSearch,showEntitiesCommand:e.entitiesCommand,showSummaryCommand:e.summarizer,showKnowledgeSearch:!!e.knowledgeAssistant,recommendTextSuggestions:e.recommendTextSuggestions})))}),this.loadProfileConfigPromise)}async loginViaPopup(e){return new Promise((o,n)=>{let s=new MessageChannel,r=s.port1,i=this.state.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 l=!1,c=()=>{p&&!p.closed&&p.close(),window.removeEventListener("message",d),clearInterval(g)};r.onmessage=async u=>{var m,f;if((m=u.data)!=null&&m.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((f=u.data)==null?void 0:f.jwt),await this.isLoggedIn(),this.broadcastEvents.send(sn),l=!0,s.port1.close(),o()}catch(h){console.error(h),n(h)}finally{l=!0,c()}};let p=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");p===null&&n(new Error("Popup blocked by browser"));let d=async u=>{var m;if(u.origin===a.origin)switch((m=u.data)==null?void 0:m.type){case"deepdesk-popup-loaded":{try{let f=JSON.stringify({type:"deepdesk-popup-create-channel"});p==null||p.postMessage(f,a.origin,[s.port2])}catch(f){w.error("Error posting message to popup",f),n(f)}break}case"deepdesk-popup-error":{c(),u.data.message==="Timeout"&&w.warn("Popup timed out. Check if the account's platform url is configured correctly."),n(new Error(u.data.message));break}}};window.addEventListener("message",d);let g=setInterval(()=>{p&&!p.closed||(c(),l||n(new Error("Popup closed by user")))},200);this.unmountHandlers.push(c)})}async checkForTrialMode(e){try{let{account:o}=await this.deepdeskApi.getPlatformConfig();if(!o.isTrial){this.shouldRender=!0;return}if(w.info("Trial is active"),!await this.deepdeskApi.checkUserExists(e))throw new Error("User is not in trial");this.shouldRender=!0}catch(o){let{message:n}=o;w.info(n),this.shouldRender=!1}}async refreshWidgetSuggestions(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:e}=this.state.profile.data;if(!e.widget)return;let o=Ws(this.state);try{o.forEach(({type:n})=>{n==="entities"?this.store.dispatch(Le()):this.store.dispatch(Pe(n))})}catch(n){this.handleError(n)}}};async function Lu(t,e,o={}){let{value:n}=t,{start:s,end:r}=o.replace??{start:0,end:n.length},i=`${n.slice(0,s)}${e}${n.slice(r)}`,a=o.selectionAfter??{start:s+e.length,end:s+e.length},l=()=>{if(o.setValue)return o.setValue(i);t.value=i};return Promise.resolve(l()).then(()=>{t.selectionStart=a.start,t.selectionEnd=a.end,t.blur(),t.focus()})}async function Mu(t,e,o={}){let n=o.replace?Et(t,o.replace.start,o.replace.end):Ao(t),s,r=()=>{if(o.setRange)return o.setRange(n.cloneRange());n.deleteContents(),s=document.createElement("span"),n.insertNode(s),o.insertBRs!==!1?e.split(`
10
10
  `).reverse().forEach((i,a)=>{a>0&&n.insertNode(document.createElement("br")),n.insertNode(document.createTextNode(i))}):n.insertNode(document.createTextNode(e))};return Promise.resolve(r()).then(()=>{try{if(o.selectionAfter!==!1){t.focus();let i=o.selectionAfter?Et(t,o.selectionAfter.start,o.selectionAfter.end):(n.collapse(!1),n),a=window.getSelection();a==null||a.removeAllRanges(),a==null||a.addRange(i)}if(!s)return;s.scrollIntoView&&s.scrollIntoView({block:"nearest",inline:"nearest"})}finally{s&&s.remove()}})}function Ch(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 wh(t){let e=document.createDocumentFragment();return t.split(`
11
11
  `).forEach((o,n)=>{n>0&&e.appendChild(document.createElement("br"));let s={index:0},r=0;for(;s=o.slice(r).match(/(\[([^\]]+)])\(([^)]+)\)/);){let i=document.createElement("a");i.href=s[3],i.setAttribute("target","_blank"),i.setAttribute("rel","noopener noreferrer"),i.appendChild(document.createTextNode(s[2])),e.appendChild(document.createTextNode(o.slice(r,r+s.index))),e.appendChild(i),r=r+s.index+s[0].length}e.appendChild(document.createTextNode(o.slice(r)))}),e}function Nu(t,e){return!t.contains(e)||e===t?null:e.parentNode===t?e:Nu(t,e.parentNode)}async function Ou(t,e,{isBlock:o,isHTML:n}={}){let s;t.dispatchEvent(new InputEvent("beforeinput",{inputType:"insertText",data:e,bubbles:!0,cancelable:!0}));let r=()=>{let i=t.ownerDocument.defaultView??window,a=i.getSelection();if((!a||a.rangeCount===0)&&(t.focus(),a=i.getSelection()),!a||a.rangeCount===0)return;let l=a.getRangeAt(0);if(!l)return;s=document.createElement("span"),l.insertNode(s);let c=n?Ch(e):wh(e);if(o){let p=l.startContainer===t?t.childNodes[l.startOffset]:l.startContainer,d=Nu(t,p)??t.firstChild;t.insertBefore(c,(d==null?void 0:d.nextSibling)??null)}else l.insertNode(c),l.collapse(!1)};return Promise.resolve(r()).then(()=>{if(t.dispatchEvent(new InputEvent("input",{inputType:"insertText",data:e,bubbles:!0,cancelable:!0})),t.focus(),!!s)try{s.scrollIntoView&&s.scrollIntoView({block:"nearest",inline:"nearest"})}finally{s&&s.remove()}})}function Du(t){return t.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}async function Hu(t,e,o){await new at(t).authenticateWithKey(e,o)}async function Bu(t){let o=await new Ne(t).get("/platform/config/",{version:null});return N(o)}async function Th(t){let o=await(t.fetch??window.fetch)(t.url),n=await o.blob();return new File([n],t.name,{type:t.mimeType??o.headers.get("Content-Type")??"image/jpeg"})}async function Fu(t,e){let o=await Th(e),n=new Event("change",{bubbles:!0,cancelable:!0});try{Object.defineProperty(t,"files",{configurable:!0,get:()=>[o]}),t.dispatchEvent(n)}finally{Object.hasOwn(t,"files")&&delete t.files}}0&&(module.exports={Card,ContentEditableInput,DeepdeskAPI,DeepdeskSDK,HTTPClient,InputMediator,InputType,KeyboardHint,Label,Locale,Section,SectionList,Sources,Suggestion,SuggestionList,TextAreaInput,ToggleButton,attachFile,authenticateWithKey,createFullRange,createOverlayContainer,createRangeFromOffsets,escapeHTML,fetchPlatformConfig,formatTextMarkup,getRangeOffsets,getRangeText,insertCKEditor,isHTML,isSupportedInputElement,updateContentEditable,updateTextArea,useStyles,waitForElementVisibilityChange});
package/dist/index.esm.js CHANGED
@@ -6,6 +6,6 @@ Try polyfilling it using "@formatjs/intl-pluralrules"
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
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 gc}from"react/jsx-runtime";var th={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},mc=({className:t,color:e})=>gc("svg",{className:t,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:gc("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:th[e||"pink"]})});var fc={root:"_root_1tvv4_1",text:"_text_1tvv4_18",isLoggedIn:"_isLoggedIn_1tvv4_25",isLoggedOut:"_isLoggedOut_1tvv4_29",icon:"_icon_1tvv4_39",logo:"_logo_1tvv4_44",lock:"_lock_1tvv4_49"};var Tr={};q(Tr,{enUS:()=>oh,nlNL:()=>nh});var oh={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},nh={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};import{useDispatch as ih}from"react-redux";import{jsx as Er,jsxs as hc}from"react/jsx-runtime";var yc=({onLogIn:t})=>{let e=T(Tr),o=C("floatingMenu"),n=C("productName"),s=ih(),r=rh(Z),i=y("FloatingMenu",fc);if(r===null||o===!1)return null;let a=()=>{r===!0?s($(!0)):t()};return hc("button",{className:sh(i.root,{[i.isLoggedIn]:r,[i.isLoggedOut]:!r}),onClick:a,children:[Er("div",{className:i.text,children:e(r?"search":"signin",{productName:n})}),hc("div",{className:i.icon,children:[Er(mc,{className:i.logo,color:"pink"}),r===!1&&Er(uc,{className:i.lock})]})]})};import{useEffect as Ch,useRef as wh}from"react";import{connect as Th,useDispatch as Eh,useSelector as On}from"react-redux";function Mt(t){let{showMidSentenceSuggestions:e,showSuggestionsBeforePattern:o,showSuggestionsAfterPattern:n}=t.settings,{text:s,selection:r}=t.input.userCommitted;return r.start!==r.end?!1:r.end>=s.length?!0:e?o&&new RegExp(o).test(s.substring(r.end))||n&&new RegExp(n).test(s.substring(0,r.end))?!0:o===!1&&n===!1:!1}import{Fragment as _h,useMemo as xh}from"react";import{Interweave as ch}from"interweave";import{useEffect as ph,useMemo as dh,useRef as uh}from"react";import{useDispatch as gh,useSelector as mh}from"react-redux";import{useEffect as ah}from"react";function vc(t,e,o){ah(()=>{let n=t.current;return n?(n.addEventListener(e,o),()=>{n.removeEventListener(e,o)}):()=>{}},[t,e,o])}var Sc={root:"_root_4u430_1",actions:"_actions_4u430_8",badge:"_badge_4u430_15",formattedText:"_formattedText_4u430_19"};import{jsx as Mn,jsxs as Sh}from"react/jsx-runtime";var fh=["search","personal-collection-search","search-autocomplete"];function hh(t,e,o,n={}){let s="";return fh.includes(e)?s=fa(Us(t,o,{stripAgentPart:!0}),n.searchKeywords??[o]):s=Us(t,o,n),n.placeholders===!0&&(s=ha(s)),s}var yh=()=>{},vh=({index:t,selected:e,suggestion:o,onFeedback:n})=>{let s=C("inlineSuggestions"),r=mh(ht),i=gh(),a=y("TextSuggestion",Sc),l=uh(null);ph(()=>{let p=setTimeout(()=>{i(Ii({text:o.text,suggestion:o}))},500);return()=>{clearTimeout(p)}},[o]),vc(l,"click",()=>{i(Me(t)),i(ie({suggestion:o,text:o.text,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"}))});let c=dh(()=>hh(o.text,o.source,r,{stripAgentPart:s,placeholders:!0,searchKeywords:o.searchKeywords}),[s,o.text,o.source,r,o.searchKeywords]);return o.source==="gpt"&&!s?null:Sh("div",{className:a.root,onMouseEnter:()=>i(Me(t)),children:[Mn(D,{ref:l,as:"button","data-testid":"suggestions-overlay-item",selected:e,onClick:yh,children:Mn(ch,{containerTagName:"div",noWrap:!1,tagName:"span",className:a.formattedText,content:c})}),e&&n&&Mn("div",{className:a.actions,children:Mn(fn,{onFeedback:()=>n(o),suggestion:o.text})})]})},_c=vh;import{jsx as xc}from"react/jsx-runtime";var bh=({onFeedback:t,suggestions:e,selectedIndex:o,reverse:n})=>{let s=xh(()=>{let r=e.map((i,a)=>xc(_c,{index:a,selected:a===o,suggestion:i,onFeedback:t},`${i.text}-${i.source}`));return n?r.reverse():r},[e,o,n]);return xc(_h,{children:s})},Nn=bh;var bc={root:"_root_otdbu_1",paper:"_paper_otdbu_11"};import{jsx as Dn}from"react/jsx-runtime";var kh=({textSuggestions:t,selectedIndex:e})=>{let o=wh(null),n=y("InlineSuggestionsOverlay",bc),s=On(Mt),r=Eh(),i=On(Z),a=On(ft),l=On(Tn),c=C("showTextSuggestions");return St(()=>{r(Fe({collapse:!0,skipWhenInputFocus:!0}))}),Ch(()=>{let p=o.current;if(!p||!p.parentElement)return;p.parentElement.style.left="0px";let d=p.getBoundingClientRect();p.parentElement.style.left=`${Math.min(window.innerWidth-4-d.right,0)}px`}),l||!s||!c||t.length===0||i!==!0||a===!1?null:Dn("div",{className:n.root,"data-variant":"inline",children:Dn("div",{ref:o,className:n.paper,children:Dn(re,{children:Dn(Nn,{suggestions:t,selectedIndex:e})})})})},Ih=({input:t})=>({selectedIndex:t.selectedSuggestionIndex,textSuggestions:t.textSuggestions}),Cc=Th(Ih)(kh);import{Provider as Rh}from"react-redux";import{jsx as Hn}from"react/jsx-runtime";var Ph=({children:t})=>{let o=C("locale").replace("-","");return Hn(Ns.Provider,{value:o,children:t})},Ah=({store:t,customStyles:e={},children:o})=>Hn(Rh,{store:t,children:Hn(Ph,{children:Hn(zt.Provider,{value:e,children:o})})}),tt=Ah;import Ar from"classnames";import{useEffect as zh,useRef as Vh,useState as qh}from"react";import{connect as Wh,useDispatch as Gh,useSelector as fo}from"react-redux";import{useState as Lh}from"react";function wc(t,e){let[o,n]=Lh(()=>{if(typeof window>"u")return e;try{let r=window.localStorage.getItem(t);return r?JSON.parse(r):e}catch(r){return w.error(r),e}});return[o,r=>{try{let i=r instanceof Function?r(o):r;n(i),typeof window<"u"&&window.localStorage.setItem(t,JSON.stringify(i))}catch(i){w.error(i)}}]}import Oh from"classnames";import{Fragment as Dh,useCallback as Ir,useMemo as Ec}from"react";var kr={};q(kr,{enUS:()=>Mh,nlNL:()=>Nh});var Mh={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"}]}]},Nh={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 Tc={root:"_root_1vfca_1",anchor:"_anchor_1vfca_6",anchorButton:"_anchorButton_1vfca_11"};import{jsx as Bn,jsxs as kc}from"react/jsx-runtime";var Rr=(t,e,o)=>n=>Bn("button",{className:t.anchorButton,type:"button",value:e,onClick:o,children:n},e),Hh=({className:t,loginUrl:e,isEmbedded:o,onSnooze:n,onLogIn:s})=>{let r=T(kr),i=se(),a=y("Login",Tc),l=C("productName"),c=Ir(h=>{h.preventDefault(),n&&n(parseInt(h.target.value,10))},[]),p=Ir(h=>{h.preventDefault(),i.send(It,!0)},[e]),d=Ec(()=>h=>Bn("a",{onClick:S=>{S.preventDefault(),s()},href:e,className:a.anchor,target:"_blank",rel:"noreferrer",children:h},"login"),[e]),g=Ir(h=>Bn("button",{type:"button",className:a.anchorButton,onClick:p,children:h},"prompt"),[p]),{min:u,hour:m,day:f}=Ec(()=>({min:Rr(a,60*10,c),hour:Rr(a,60*60,c),day:Rr(a,60*60*12,c)}),[]);return kc("div",{className:Oh(t,a.root),children:[r("loginPlease",{login:o?g:d,productName:l}),n&&kc(Dh,{children:[Bn("br",{}),r("snooze",{min:u,hour:m,day:f})]})]})},Fn=Hh;import{useDispatch as Bh}from"react-redux";var Ic={root:"_root_1g8fi_1",text:"_text_1g8fi_19"};import{jsx as Rc,jsxs as Kh}from"react/jsx-runtime";var Fh=({title:t})=>{let e=y("SearchTrigger",Ic),o=Bh();return Kh("button",{type:"button",className:e.root,onClick:()=>o($(!0)),children:[Rc(wt,{}),Rc("span",{className:e.text,children:t})]})},Pc=Fh;var Pr={};q(Pr,{enUS:()=>Uh,nlNL:()=>jh});var Uh={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"}]},jh={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"}]};var Ac={root:"_root_onpov_1",isInline:"_isInline_onpov_14",toggleButton:"_toggleButton_onpov_21",toggleButtonWrapper:"_toggleButtonWrapper_onpov_25",toggleButtonWrapperHidden:"_toggleButtonWrapperHidden_onpov_32",isCollapsed:"_isCollapsed_onpov_36",collapsible:"_collapsible_onpov_36",hints:"_hints_onpov_44",hintsHidden:"_hintsHidden_onpov_51",triggers:"_triggers_onpov_56",triggersRight:"_triggersRight_onpov_71"};import{jsx as z,jsxs as ho}from"react/jsx-runtime";var $h=({textSuggestions:t,selectedIndex:e,onLogIn:o})=>{let n=y("SuggestionsOverlay",Ac),s=T(Pr),r=fo(Mt),i=Ci(),a=Gh(),l=Vh(null),c=C("searchTriggerKey"),p=C("productName"),d=fo(Tn),g=fo(Z),u=fo(ft),[m,f]=qh(null),h=C("showSearch"),E=C("showTextSuggestions"),S=C("adminUrl"),x=C("isEmbedded"),[b,v]=wc("dd-snooze-until-ms",0),R=d||b>Date.now(),A=fo(F=>F.input.text),H=t.filter(F=>F.source!=="gpt").length,P=()=>{R&&v(0),a(fl(!R))},V=F=>{a(W({name:"suggestion feedback",data:{text:F.text,source:"overlay",context:A},options:{includeConversationData:!0}}))},k=F=>{let at=Date.now()+F*1e3;v(at),w.info(`Snooze until: ${new Date(at)}`),a(Fe({collapse:!0}))};return zh(()=>{H===0&&f(null)},[t,H]),St(()=>{a(Fe({collapse:!0,skipWhenInputFocus:!0}))}),g===null||u===!1?null:g===!1?ho("div",{ref:l,className:Ar(n.root,{[n.isCollapsed]:R}),children:[!R&&ho("div",{className:n.triggers,children:[z("div",{style:{flex:1}}),z("div",{className:n.triggersRight,children:z(ut,{className:n.toggleButton,title:s("collapse"),onClick:P,isCollapsed:!1})})]}),z("div",{className:n.toggleButtonWrapper,children:z(ut,{className:n.toggleButton,title:s("open",{productName:p}),onClick:P,isCollapsed:!0})}),z("div",{className:n.collapsible,children:z(Fn,{loginUrl:S,isEmbedded:x,onLogIn:o,onSnooze:k})})]}):!i||!r?null:ho("div",{ref:l,className:Ar(n.root,{[n.isCollapsed]:R}),children:[!R&&ho("div",{className:n.triggers,children:[z("div",{style:{flex:1},children:h&&z("div",{style:{display:"inline-block"},onFocus:()=>{},onMouseOver:()=>f(s(_n()?"searchHintMac":"searchHintWindows",{searchTriggerKey:c.toUpperCase()})),onMouseLeave:()=>f(null),children:z(Pc,{title:s("search")})})}),ho("div",{className:n.triggersRight,onFocus:()=>{},children:[z("div",{className:Ar(!m&&n.hintsHidden,n.hints),children:m}),z(ut,{className:n.toggleButton,title:s("collapse"),onClick:P,isCollapsed:!1})]})]}),z("div",{className:n.toggleButtonWrapper,children:z(ut,{className:n.toggleButton,title:s("open",{productName:p}),onClick:P,isCollapsed:!0})}),H>0&&E&&z("div",{className:n.collapsible,onFocus:()=>{},children:z(re,{children:z(Nn,{onFeedback:V,suggestions:t,selectedIndex:e,reverse:!0})})})]})},Xh=({input:t})=>({selectedIndex:t.selectedSuggestionIndex,textSuggestions:t.textSuggestions}),Lc=Wh(Xh)($h);import jr from"classnames";import{Interweave as Dy}from"interweave";import{useCallback as Hy,useEffect as By,useMemo as Jc,useRef as Fy}from"react";import{connect as Ky}from"react-redux";import{cloneElement as Zh}from"react";var Qh=["div","span","mark","strong","b","i","u","em"];function Lr(t,e,o=0){var r;let n=t[t.length-1],s=typeof n=="object"&&n!==null?(r=n.props)==null?void 0:r.tagName:void 0;if(s==="br")return t.pop(),[...t,...e,n];if(Qh.includes(s)){let i=Array.isArray(n.props.children)?n.props.children:[n.props.children];return[...t.slice(0,t.length-1),Zh(n,{children:Lr(i,e,o+1)})]}return[...t,...e]}function Ue(t){return t.tagName.toLowerCase()==="textarea"}var Mc={root:"_root_81non_1",container:"_container_81non_3",agentText:"_agentText_81non_5",tabText:"_tabText_81non_6",hint:"_hint_81non_6",matchSelection:"_matchSelection_81non_10",focus:"_focus_81non_16",resetIndent:"_resetIndent_81non_20",matchKeyword:"_matchKeyword_81non_24",matchPlaceholder:"_matchPlaceholder_81non_25",hover:"_hover_81non_31",hintText:"_hintText_81non_64",popover:"_popover_81non_72",popoverRoot:"_popoverRoot_81non_77",popoverContentContainer:"_popoverContentContainer_81non_81",popoverContent:"_popoverContent_81non_81",selectionOptions:"_selectionOptions_81non_107",selectionOptionsIsHidden:"_selectionOptionsIsHidden_81non_112",selectionOptionsButton:"_selectionOptionsButton_81non_116",caret:"_caret_81non_132",popoverSuggestionsRoot:"_popoverSuggestionsRoot_81non_136",suggestionsOverlayInputStyles:"_suggestionsOverlayInputStyles_81non_141"};import my from"classnames";import{Matcher as fy}from"interweave";import{useEffect as hy,useMemo as yy}from"react";function Nc(t){return t.replace(/[.*+^${}()|[\]\\]/g,"\\$&")}function Kn(t){return e=>{t.forEach(o=>{typeof o=="function"?o(e):o!=null&&(o.current=e)})}}function Oc(t){return t!=null}import Kc from"classnames";import{createRef as ay,useCallback as Nr,useMemo as ly,useRef as cy,useState as py}from"react";import{useState as Jh,useLayoutEffect as Yh}from"react";var ey=["bottom","height","left","right","top","width"],ty=(t={},e={})=>ey.some(o=>t[o]!==e[o]),Ie=new Map,Dc,Hc=()=>{let t=[],e=[];Ie.forEach((o,n)=>{if(n instanceof Element&&!n.isConnected){e.push(n);return}let s=n.getBoundingClientRect();ty(s,o.rect)&&(o.rect=s,t.push(o))}),e.forEach(o=>{Ie.delete(o)}),t.forEach(o=>{o.callbacks.forEach(n=>n(o.rect))}),Dc=window.requestAnimationFrame(Hc)};function oy(t,e){return{observe(){let o=Ie.size===0;if(Ie.has(t)){let n=Ie.get(t);n.callbacks.push(e),n.rect&&e(n.rect)}else Ie.set(t,{rect:void 0,hasRectChanged:!1,callbacks:[e]});o&&Hc()},unobserve(){let o=Ie.get(t);if(o){let n=o.callbacks.indexOf(e);n>=0&&o.callbacks.splice(n,1),o.callbacks.length||Ie.delete(t),Ie.size||cancelAnimationFrame(Dc)}}}}function Mr(t){let[e,o]=Jh(null);return Yh(()=>{if(!t.current)return;let n=oy(t.current,s=>{o(s)});return n.observe(),()=>{n.unobserve()}},[t]),e}import{useContext as ny,useLayoutEffect as sy,useState as ry}from"react";import{createPortal as iy}from"react-dom";var Bc={root:"_root_1jq08_1"};var Fc=({children:t})=>{let[e,o]=ry(null),n=ny(zt);return sy(()=>{let s=document.createElement("div");return Xe(s),s.classList.add(Bc.root),n!=null&&n.portalRootNode&&s.classList.add(n==null?void 0:n.portalRootNode),document.body.appendChild(s),o(s),()=>{s.isConnected&&document.body.removeChild(s)}},[]),e?iy(t,e):null};var he={ref:"_ref_1rcyi_1",root:"_root_1rcyi_7",positionAbove:"_positionAbove_1rcyi_13",positionBelow:"_positionBelow_1rcyi_17",positionLeft:"_positionLeft_1rcyi_21",positionRight:"_positionRight_1rcyi_25",alignStart:"_alignStart_1rcyi_29",alignCenter:"_alignCenter_1rcyi_34",alignEnd:"_alignEnd_1rcyi_40"};import{jsx as Or}from"react/jsx-runtime";var Un=(t=!1)=>{let[e,o]=py(t),n=Nr(()=>o(!0),[]),s=Nr(()=>o(!1),[]),r=Nr(()=>o(a=>!a),[]),i=cy(null);return{opened:e,open:n,close:s,toggle:r,triggerRef:i}};function Dr(t,e=null,o=0){if(!t)return{display:"none"};let n=e?t.top-e.top<0||t.top<e.top-o?e.top-o:t.top+t.height>e.top+e.height+o?e.top+e.height+o-t.height:t.top:t.top,s=e?t.left<e.left-o?e.left-o:t.left+t.width>e.left+e.width+o?e.left+e.width+o-t.width:t.left:t.left;return{top:n,left:s,height:t.height,width:t.width}}var jn=({className:t,triggerRef:e,boundaryRef:o=ay(),position:n="above",align:s="center",children:r,toStyle:i=Dr,...a})=>{let l=Mr(e),c=Mr(o),p=ly(()=>i(l,c,0),[l,c]);return Or(Fc,{children:Or("div",{className:Kc(he.ref,{[he.positionAbove]:n==="above",[he.positionBelow]:n==="below",[he.positionLeft]:n==="left",[he.positionRight]:n==="right",[he.alignStart]:s==="start",[he.alignCenter]:s==="center",[he.alignEnd]:s==="end"}),style:p,...a,role:"dialog",children:Or("div",{className:Kc(t,he.root),children:r})})})};import dy from"classnames";import{forwardRef as uy,useRef as gy}from"react";import{jsx as Uc}from"react/jsx-runtime";var zn=uy(({className:t,children:e,...o},n)=>{let s=gy(null),r=y("TabCompletion",xe);return Uc("div",{ref:Kn([s,n]),className:dy(t,r.popoverContentContainer),...o,children:Uc("div",{className:r.popoverContent,children:e})})});import{jsx as yo,jsxs as _y}from"react/jsx-runtime";var vy=t=>e=>{let o=Dr(e);return"top"in o&&(o.width=t.width-(e.left-t.left)-10),o},Sy=({inputElement:t,boundaryRef:e,inputStyle:o,children:n,suggestion:s})=>{let r=y("TabCompletion",xe),i=Un(),a=yy(()=>vy(t.getBoundingClientRect()),[t]),[l,c]=ln(t);return hy(()=>{c?i.open():i.close()},[c]),_y("span",{children:[yo("mark",{ref:Kn([l,i.triggerRef]),className:my(r.matchKeyword,{[r.hover]:c}),"aria-haspopup":"dialog","aria-expanded":i.opened?"true":"false",children:n}),i.opened&&yo(jn,{className:r.popover,triggerRef:i.triggerRef,boundaryRef:e,position:"below",align:"start",toStyle:a,children:yo(zn,{style:o,children:yo("div",{className:r.hintText,children:s})})})]})},Vn=class extends fy{keywordMatches=[];preparedKeywordMatches=[];usedKeywordMatches=new Set;onBeforeParse(e,o){return o.keywordMatches&&o.keywordMatches!==this.keywordMatches&&(this.preparedKeywordMatches=o.keywordMatches.map(n=>({...n,keywordRegex:new RegExp(`\\b${Nc(n.keyword)}\\b`,"i")})),this.keywordMatches=o.keywordMatches),this.usedKeywordMatches.clear(),e}match(e){let o=this.preparedKeywordMatches.map(s=>{if(this.usedKeywordMatches.has(s))return null;let r=e.match(s.keywordRegex);if(!r)return null;let i=e.charAt(r.index-1),a=e.charAt(r.index+s.keyword.length);return i==="{"&&a==="}"?null:{index:r.index,length:r[0].length,match:r[0],matchString:r[0],suggestion:s.suggestion,preparedKeywordMatch:s,valid:!0}}).filter(Oc);if(o.length===0)return null;let n=o.reduce((s,r)=>r.index<s.index?r:s);return this.usedKeywordMatches.add(n.preparedKeywordMatch),n}replaceWith(e,o){return yo(Sy,{inputElement:o.inputElement,suggestion:o.suggestion,inputStyle:o.inputStyle,boundaryRef:o.boundaryRef,children:e},`keyword_${o.matchString}_${o.key}`)}asTag(){return"mark"}};import Ur from"classnames";import{Matcher as Ry}from"interweave";import{createRef as Py,forwardRef as Ay,useCallback as Ly,useEffect as Xc,useRef as Zc,useState as Qc}from"react";import{useDispatch as My}from"react-redux";import{jsx as jc}from"react/jsx-runtime";var zc=()=>jc("svg",{width:"1.3em",height:"1.3em",focusable:"false","aria-hidden":"true",viewBox:"0 0 24 24","data-testid":"InsertLinkIcon",tabIndex:-1,children:jc("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 xy,useEffect as qc,useState as Wc}from"react";import{useDispatch as by,useSelector as Gc}from"react-redux";import Cy from"lodash.debounce";var Vc={root:"_root_1muu8_1",content:"_content_1muu8_7"};function qn(t,e,o){var s;let n=((s=t.imageSizes)==null?void 0:s[e])||t.image||o;if(!n)return null;try{return new URL(n).toString()}catch{return null}}function Hr(t){return t.replace("https://www.","").replace("https://","")}import{jsx as ot,jsxs as Br}from"react/jsx-runtime";var wy=3,Ty=t=>({image:t.image||"",text:t.text,id:t.id,title:t.title}),Ey=({onSelectLink:t,onDismiss:e,placeholder:o,visitUrlText:n,linkCount:s=wy})=>{let r=y("LinkSearch",Vc),[i,a]=Wc(""),l=by(),c=Gc(Cn("url")),p=Gc(Ua("URL",Ty)),[d,g]=Wc(p.length-1),u=C("fallbackImage"),m=S=>{let x=S.target;a(x.value)},f=(S,x)=>{S.stopPropagation(),S.preventDefault(),window.open(x,"_blank")},h=S=>{var v;let x=d-1<0?p.length-1:d-1,b=d+1===p.length?0:d+1;S.code==="Escape"&&(a(""),e()),S.code==="ArrowUp"&&g(x),S.code==="ArrowDown"&&g(b),S.code==="Enter"&&t(((v=p[d])==null?void 0:v.text)||i)},E=xy(Cy(S=>{l(Je({query:S,type:"URL",tags:["link-search"]}))},300),[]);return qc(()=>{i&&E(i)},[i]),qc(()=>()=>{l(vn())},[]),Br("div",{className:r.root,children:[ot(re,{withDivider:!0,children:(i?p:c).slice(0,s).map((S,x)=>ot(D,{selected:d===x,onClick:()=>t(S.text),"data-testid":"linksearch-suggestion",children:Br(B,{children:[ot(B.Image,{src:qn(S,"small",u||void 0),title:S.title||S.text}),Br(B.Content,{className:r.content,cropText:!0,children:[ot(B.Title,{children:S.title||Hr(S.text)}),S.title&&Hr(S.text)]}),ot(D.Actions,{children:ot(D.ActionButton,{label:n,onClick:b=>f(b,S.text)})})]})},S.text))}),ot(ao,{value:i,onChange:m,autoFocus:!0,placeholder:o,onKeyUp:h})]})},$c=Ey;var Fr={};q(Fr,{enUS:()=>ky,nlNL:()=>Iy});var ky={insertLink:[{type:0,value:"Insert link"}],linkInputPlaceholder:[{type:0,value:"Search, type or paste link"}],visitUrl:[{type:0,value:"Visit"}]},Iy={insertLink:[{type:0,value:"Voeg link toe"}],linkInputPlaceholder:[{type:0,value:"Zoek, typ of plak link"}],visitUrl:[{type:0,value:"Bekijk"}]};import{jsx as ye,jsxs as Kr}from"react/jsx-runtime";var Ny=Ay((t,e)=>{let o=y("TabCompletion",xe);return ye("mark",{ref:e,className:Ur(o.matchSelection)},"selection-start")}),Oy=({startRef:t,boundaryRef:e,inputStyle:o,inputElement:n,children:s})=>{let r=T(Fr),i=y("TabCompletion",xe),a=Zc(null),l=Zc(null),[c,p]=Qc(null),d=My(),g=Un(document.activeElement===n),[u]=Qc(()=>document.createRange());g.triggerRef.current=u,Xc(()=>()=>u.detach(),[]),Xc(()=>{let f=t.current,h=a.current;!f||!h||(u.setStart(f,0),u.setEnd(h,0))},[t.current,a.current]),St(()=>{g.close()});let m=Ly(f=>{let h=u.toString(),E=/^http(s?):\/\//.test(f)?f:`https://${f}`;d(jo({text:`[${h}](${E})`,replace:"selection"}))},[]);return Kr("span",{children:[ye("mark",{ref:a,className:Ur(i.matchSelection),"aria-haspopup":"dialog","aria-expanded":g.opened?"true":"false",children:s}),g.opened&&ye(jn,{className:i.popoverRoot,triggerRef:g.triggerRef,boundaryRef:e,position:"above",align:"start",children:Kr(zn,{style:o,ref:l,children:[ye("div",{className:Ur(i.selectionOptions,{[i.selectionOptionsIsHidden]:c!==null}),children:Kr("button",{type:"button",tabIndex:c===null?-1:void 0,className:i.selectionOptionsButton,onClick:()=>p("insertLink"),children:[ye(zc,{}),ye("span",{children:"\xA0"}),ye("span",{children:r("insertLink")})]})}),c==="insertLink"&&ye($c,{placeholder:r("linkInputPlaceholder"),visitUrlText:r("visitUrl"),onSelectLink:m,onDismiss:()=>{p(null),g.close()}})]})})]},"selection-end")},Wn=class extends Ry{charCount=0;foundIndex=0;startRef=null;props;onBeforeParse(e,o){return this.props=o,this.charCount=0,this.startRef=Py(),this.foundIndex=0,e}match(e){if(!this.props||this.props.selection===null||this.foundIndex===2)return null;let[o,n]=this.props.selection;if(o===n)return null;let s=this.foundIndex===0?o:n,r=s>=this.charCount&&s<=this.charCount+e.length?{index:s-this.charCount,length:0,match:"",valid:!0}:null;r&&this.foundIndex++;let i=this.foundIndex===1;return r&&i?this.charCount+=s-this.charCount:this.charCount+=e.length,r?{isStart:i,...r}:null}replaceWith(e,o){return o.isStart?ye(Ny,{ref:this.startRef}):ye(Oy,{inputElement:o.inputElement,startRef:this.startRef,boundaryRef:o.boundaryRef,inputStyle:o.inputStyle})}asTag(){return"mark"}};import{useSelector as Uy}from"react-redux";import{jsx as Nt,jsxs as Vy}from"react/jsx-runtime";var jy=({enabled:t,content:e,tabText:o,showTabHint:n,showTabCompletion:s,showStyleSuggestions:r,keywordMatches:i,inputElement:a,source:l})=>{let c=y("TabCompletion",Mc),p=C("insertLink"),d=C("showMidSentenceSuggestions"),g=C("inlineSuggestions"),u=pn(a),m=Fy(null),f=Uy(Z);By(()=>{Ue(a)&&u&&dn(a,u)},[u]);let h=Hy(x=>{if(!s||!o)return x;let b=[Nt("span",{className:c.resetIndent,children:"\u200B"},"u200B"),Nt("span",{"data-testid":"tab-completion",className:jr(c.tabText,c.resetIndent),"data-source":l,children:o},"tabText")];return n&&b.push(Nt("span",{className:jr(c.hint,c.resetIndent),children:Nt(gs,{keyCode:"tab"},"tabHint")})),Lr(x,b)},[s,o,n]),E=Jc(()=>{let x=[];return p&&x.push(new Wn("selection")),x.push(new vt("placeholders")),r&&x.push(new Vn("keywords")),x},[g,p,r]),S=Jc(()=>{let x=window.getComputedStyle(a);return{"--dd-color":x.color,"--dd-font-size":x.fontSize,"--dd-font-family":x.fontFamily,"--dd-font-variant":x.fontVariant}},[]);return!t||!f?null:Vy("div",{ref:x=>{x!=null&&x.parentElement&&(m.current=x==null?void 0:x.parentElement)},className:c.root,style:S,children:[Nt(Dy,{tagName:"span",containerTagName:"div",className:jr(c.container,c.agentText),disableLineBreaks:Ue(a),content:e||"\u200B",onAfterParse:h,matchers:E,selection:u,keywordMatches:i,inputElement:a,inputStyle:S,boundaryRef:m,inlineSuggestionsOnlyAtEnd:!d}),Nt("br",{})]})},zy=({input:t,ui:e,settings:o,styleSuggestions:n,conversation:s})=>{var f;let{tabCompletionSuggestion:r}=t,i=(r==null?void 0:r.text)||"",a=(r==null?void 0:r.source)||"",l=t.html??Qt(t.text),c=i.indexOf(t.text)===0?i.slice(t.text.length):"",{showTabHint:p}=e,{isSupported:d}=s,{showTabCompletion:g,visible:u,showStyleSuggestions:m}=o;return{showTabHint:p,showStyleSuggestions:m,showTabCompletion:g,content:l,tabText:c,source:a,keywordMatches:((f=n.list)==null?void 0:f.keywordMatches)??[],enabled:u&&d!==!1}},Yc=Ky(zy)(jy);import Tv from"classnames";import{useEffect as Ev}from"react";import{useDispatch as kv,useSelector as te}from"react-redux";import{createAsyncThunk as vo,createSlice as qy}from"@reduxjs/toolkit";var ep={list:[],fetchState:"idle",isInitialRequest:null},op=t=>t.autoflows.list||[],tp=t=>e=>{var o;return(o=e.list)==null?void 0:o.find(n=>n.triggerPayload===t)},Re=vo("autoflows/getAll",async(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");return o.getAutoflows(t)}),zr=vo("autoflows/start",async(t,e)=>{let{dispatch:o}=e,{deepdeskBrokerAPI:n}=e.extra;if(!n)throw new Error("Deepdesk Broker not initialized");await n.startAutoflowSession(t),await o(Re(t.platformSessionId))}),Vr=vo("autoflows/stop",async(t,e)=>{let{dispatch:o}=e,{deepdeskBrokerAPI:n}=e.extra;if(!n)throw new Error("Deepdesk Broker not initialized");await n.stopAutoflowSession(t.platformSessionId),await o(Re(t.platformSessionId))}),Wy=qy({name:"autoflows",initialState:ep,reducers:{},extraReducers:t=>{t.addCase(zr.pending,(e,o)=>{let n=tp(o.meta.arg.triggerPayload)(e);n.state="Started",n.isBusy=!0}),t.addCase(Vr.pending,(e,o)=>{let n=tp(o.meta.arg.triggerPayload)(e);n.state="Aborted",n.isBusy=!0}),t.addCase(Re.pending,e=>{e.isInitialRequest=e.isInitialRequest===null,e.fetchState="loading"}),t.addCase(Re.rejected,e=>{e.fetchState="error"}),t.addCase(Re.fulfilled,(e,o)=>{e.list=o.payload,e.fetchState="done"}),t.addCase(M,()=>ep)}}),np=vo("autoflows/openStream",(t,e)=>{let{dispatch:o}=e,{deepdeskBrokerAPI:n}=e.extra;if(!n)throw new Error("Deepdesk Broker not initialized");let s=n.openStream(t);s.on("sessionAborted",()=>{o(Re(t))}),s.on("sessionCompleted",()=>{o(Re(t))})}),sp=vo("autoflows/closeStream",(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");o.closeStream(t)}),rp=Wy.reducer;import{createAsyncThunk as _o,createSlice as Gy}from"@reduxjs/toolkit";var ip={list:[],fetchState:"idle",isInitialRequest:null,sentSuggestions:[],errorSuggestions:[],answeredSuggestions:[]},ap=t=>t.customMessages.list,lp=t=>e=>!!e.customMessages.sentSuggestions.find(o=>o===t),cp=t=>e=>!!e.customMessages.answeredSuggestions.find(o=>o===t),pp=t=>e=>!!e.customMessages.errorSuggestions.find(o=>o===t),So=_o("customMessages/getAll",async(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");return o.getCustomMessages(t)}),Gn=_o("customMessages/send",async(t,e)=>{let{platformSessionId:o,suggestion:n}=t,{deepdeskBrokerAPI:s}=e.extra;if(!s)throw new Error("Deepdesk Broker not initialized");await s.sendCustomMessage(o,n)}),$n=_o("customMessages/answer",async(t,e)=>{let{platformSessionId:o,reply:n}=t,{deepdeskBrokerAPI:s}=e.extra;if(!s)throw new Error("Deepdesk Broker not initialized");await s.answerCustomMessage(o,n)}),dp=Gy({name:"customMessages",initialState:ip,reducers:{onCustomMessage(t,e){Array.isArray(e.payload)?t.list=e.payload:t.list=[e.payload]}},extraReducers:t=>{t.addCase(So.pending,e=>{e.isInitialRequest=e.isInitialRequest===null,e.fetchState="loading"}).addCase(So.rejected,e=>{e.fetchState="error"}).addCase(So.fulfilled,(e,o)=>{e.fetchState="done",e.list=o.payload||[]}).addCase(Gn.pending,(e,o)=>{e.sentSuggestions.push(o.meta.arg.suggestion.text),e.errorSuggestions=e.errorSuggestions.filter(n=>o.meta.arg.suggestion.text!==n)}).addCase(Gn.rejected,(e,o)=>{let n=e.sentSuggestions.indexOf(o.meta.arg.suggestion.text);e.errorSuggestions.push(...e.sentSuggestions.splice(n,1))}).addCase($n.pending,(e,o)=>{e.sentSuggestions.push(o.meta.arg.suggestion.text),e.answeredSuggestions.push(o.meta.arg.suggestion.text)}).addCase($n.rejected,(e,o)=>{let n=e.answeredSuggestions.indexOf(o.meta.arg.suggestion.text);e.errorSuggestions.push(...e.sentSuggestions.splice(n,1)),e.answeredSuggestions.splice(n,1)}).addCase(M,()=>ip)}}),up=_o("customMessages/openStream",(t,e)=>{let{dispatch:o}=e,{deepdeskBrokerAPI:n}=e.extra;if(!n)throw new Error("Deepdesk Broker not initialized");n.openStream(t).on("customMessageSuggestion",r=>{o(dp.actions.onCustomMessage(r))})}),gp=_o("customMessages/closeStream",(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");o.closeStream(t)}),mp=dp.reducer;import{createAsyncThunk as fp,createSlice as $y}from"@reduxjs/toolkit";var Xy={token:null,accountUrl:null,interval:null},hp=t=>e=>{let{passwordlessToken:{token:o,accountUrl:n}}=e;return o&&n?`${n}/apis/admin/session/passwordless/login/?token=${o}&redirect=${t}`:null},qr=fp("passwordlessToken/getTemporaryPasswordlessToken",async(t,e)=>{let{deepdeskAPI:o}=e.extra,n=await o.requestPasswordlessToken();return{accountUrl:o.client.baseUrl,token:n}}),Wr=fp("passwordlessToken/pollPasswordlessToken",(t={},e)=>{let{interval:o=1e3*60*10}=t,{dispatch:n}=e;return n(qr()),setInterval(()=>n(qr()),o)}),yp=$y({name:"passwordlessToken",initialState:Xy,reducers:{stopPollPasswordlessToken(t){t.interval&&clearInterval(t.interval),t.interval=null}},extraReducers:t=>{t.addCase(qr.fulfilled,(e,o)=>{e.token=o.payload.token,e.accountUrl=o.payload.accountUrl}),t.addCase(Wr.fulfilled,(e,o)=>{e.interval=o.payload})}}),{stopPollPasswordlessToken:vp}=yp.actions,Sp=yp.reducer;function _p(t){let{customMessages:e,autoflows:o}=t;return o.fetchState==="loading"&&o.isInitialRequest===!0||e.fetchState==="loading"&&e.isInitialRequest===!0}import{Fragment as rv}from"react";import{connect as iv}from"react-redux";import ov from"classnames";import{Fragment as nv}from"react";import Zy from"classnames";var xp={root:"_root_838fd_1"};import{jsx as Jy}from"react/jsx-runtime";var Qy=({className:t,children:e})=>{let o=y("Unicode",xp);return Jy("span",{className:Zy(t,o.root),children:e})},bp=Qy;var Cp={isDisabled:"_isDisabled_1rmfm_1",buttonStart:"_buttonStart_1rmfm_5",root:"_root_1rmfm_8",buttonStop:"_buttonStop_1rmfm_8",stateBadge:"_stateBadge_1rmfm_19",isCompleted:"_isCompleted_1rmfm_26",isStarted:"_isStarted_1rmfm_30",isAborted:"_isAborted_1rmfm_34"};var Gr={};q(Gr,{enUS:()=>Yy,nlNL:()=>ev});var Yy={start:[{type:0,value:"Start"}],stop:[{type:0,value:"Stop"}],aborted:[{type:0,value:"Stopped"}],completed:[{type:0,value:"Completed"}],Aborted:[{type:0,value:"Stopped"}],Started:[{type:0,value:"Running"}],Completed:[{type:0,value:"Completed"}]},ev={start:[{type:0,value:"Start"}],stop:[{type:0,value:"Stop"}],aborted:[{type:0,value:"Stopped"}],completed:[{type:0,value:"Completed"}],Aborted:[{type:0,value:"Stopped"}],Started:[{type:0,value:"Running"}],Completed:[{type:0,value:"Completed"}]};import{jsx as nt,jsxs as Xn}from"react/jsx-runtime";var sv=({disabled:t,state:e,displayName:o,description:n,onStartAutoflow:s,onStopAutoflow:r})=>{let i=y("Autoflow",Cp),a=T(Gr),l=e==="Started"?"stop":"start",c=l==="start"?"\u25B6":l==="stop"?"\u25FC":"";return Xn(D,{className:ov(i.root,{[i.isDisabled]:t,[i.isCompleted]:e==="Completed",[i.isAborted]:e==="Aborted",[i.isStarted]:e==="Started"}),children:[nt(B,{children:Xn(B.Content,{children:[Xn(B.Title,{children:[e&&nt("span",{className:i.stateBadge,children:a(e)}),o]}),nt("span",{children:n})]})}),nt(D.Actions,{fixed:e==="Started",children:nt(D.ActionButton,{primary:!0,className:l==="start"?i.buttonStart:i.buttonStop,onClick:e==="Started"?r:s,disabled:t,label:Xn(nv,{children:[nt(bp,{children:c})," ",nt("span",{children:a(l)})]})})})]})},wp=sv;import{jsx as Tp}from"react/jsx-runtime";var av=(t,e)=>{let o=e.filter(n=>n.state==="Started");return o.length>0?o.indexOf(t)===-1:!1},lv=({autoflows:t,onStartAutoflow:e,onStopAutoflow:o,platformSessionId:n})=>Tp(rv,{children:t.map(s=>Tp(wp,{displayName:s.displayName,description:s.description,disabled:s.isBusy||av(s,t),state:s.state,onStartAutoflow:()=>e({platformSessionId:n,triggerPayload:s.triggerPayload}),onStopAutoflow:()=>o({platformSessionId:n,triggerPayload:s.triggerPayload})},s.displayName))}),cv=({autoflows:t,conversation:e})=>{var o;return{autoflows:t.list,platformSessionId:(o=e.current)==null?void 0:o.sessionId}},pv={onStartAutoflow:zr,onStopAutoflow:Vr},Ep=iv(cv,pv)(lv);import{useEffect as dv,useState as uv}from"react";import{useDispatch as gv}from"react-redux";import Rp from"classnames";import{jsx as kp}from"react/jsx-runtime";var $r=()=>kp("svg",{width:"1em",height:"1em",viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",children:kp("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 Ip={root:"_root_rjdyr_1",entity:"_entity_rjdyr_10",entityText:"_entityText_rjdyr_46",iconWrapper:"_iconWrapper_rjdyr_53",icon:"_icon_rjdyr_53",iconClicked:"_iconClicked_rjdyr_67"};import{jsx as Ot,jsxs as Pp}from"react/jsx-runtime";var mv=({entities:t})=>{let e=y("EntitiesWidgetList",Ip),[o,n]=uv(void 0),s=gv(),r=()=>{n(void 0)},i=a=>{t&&(n(t.indexOf(a)),co(a.text),s(W({name:"entity copied",data:{entity:a,type:"copy"}})))};return dv(()=>{let a=setTimeout(r,500);return()=>{clearTimeout(a)}},[o]),!t||t.length===0?null:Ot("div",{className:e.root,"data-testid":"widget-entities-list",children:t.map((a,l)=>Pp("button",{title:a.text,className:e.entity,type:"button",onClick:()=>i(a),children:[Ot("span",{className:e.entityText,children:a.text}),Pp("span",{className:e.iconWrapper,children:[Ot("span",{className:Rp(e.icon),children:Ot($r,{})}),Ot("span",{className:Rp(e.icon,o===l&&e.iconClicked),children:Ot($r,{})})]})]},a.text))})},Ap=mv;import fv from"classnames";import{useCallback as Lp}from"react";import{useDispatch as hv,useSelector as Zn}from"react-redux";var Pe={root:"_root_1e6ej_1",title:"_title_1e6ej_8",isUsed:"_isUsed_1e6ej_13",quickReplies:"_quickReplies_1e6ej_22",quickReply:"_quickReply_1e6ej_29",hasError:"_hasError_1e6ej_39",label:"_label_1e6ej_43",errorIcon:"_errorIcon_1e6ej_48"};import{jsx as je,jsxs as Qn}from"react/jsx-runtime";var yv=({suggestion:t})=>{let e=T(Qe),o=hv(),n=Zn(lp(t.text)),s=Zn(cp(t.text)),r=Zn(pp(t.text)),i=Zn(No),{replyOptions:a}=t,l=Lp(p=>{p.preventDefault(),p.stopPropagation(),!(n||!i)&&o(Gn({platformSessionId:i,suggestion:t}))},[t,n,o,i]),c=Lp(p=>{if(p.preventDefault(),p.stopPropagation(),!i||!a)return;let d=parseInt(p.target.dataset.index,10),g=a[d];o($n({platformSessionId:i,reply:g,suggestion:t}))},[t,n,o,i]);return Qn(D,{onClick:l,className:fv(Pe.root,{[Pe.isUsed]:n,[Pe.hasError]:r}),children:[je(B,{children:Qn(B.Content,{children:[Qn(B.Title,{className:Pe.title,children:[t.text," ",je(ms,{className:Pe.label,children:"analyse tool"})," ",r&&je("span",{className:Pe.errorIcon,role:"img","aria-label":e("sendingError"),title:e("sendingError"),children:"!"})]}),a&&a.length>0&&je("ul",{className:Pe.quickReplies,children:a.map(p=>je("li",{className:Pe.quickReply,children:p.title},p.title))})]})}),Qn(D.Actions,{fixed:r||n,children:[a&&a.length>0&&je(D.DropdownButton,{label:e("answer"),disabled:s,children:a.map((p,d)=>je(D.DropdownItem,{index:d,label:p.title,onClick:c},p.title))}),je(D.ActionButton,{primary:!0,disabled:n,onClick:l,label:e(n?"suggestionSent":r?"tryAgain":"sendSuggestion")})]})]})},Mp=yv;import{jsx as Np}from"react/jsx-runtime";var Op=()=>Np("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:Np("path",{d:"M17 13.5v6H5v-12h6m3-3h6v6m0-6-9 9",stroke:"currentColor",strokeWidth:"1.5",fill:"none",fillRule:"evenodd",strokeLinecap:"round",strokeLinejoin:"round"})});import{useSelector as _v}from"react-redux";import{useCallback as vv}from"react";import{jsx as st,jsxs as Jn}from"react/jsx-runtime";var Sv=({suggestion:t,lines:e,onEdit:o,onUse:n})=>{var g;let s=t.text||t.url||t.message,r=Sn(s),i=T(Qe),a=C("showImages"),l=C("fallbackImage"),c=u=>{u.preventDefault(),u.stopPropagation(),n(s)},p=u=>{u.preventDefault(),u.stopPropagation(),o(t)},d=vv(u=>{window.open(r,"_blank"),u.stopPropagation(),u.preventDefault()},[r]);return Jn(D,{onClick:c,"data-testid":"edit-suggestion",children:[Jn(B,{children:[a&&t.image&&st(B.Image,{src:qn(t,"small",l||void 0),title:t.title}),Jn(B.Content,{children:[t.title&&st(B.Title,{"data-testid":"widget-suggestion-title",children:t.title}),t.searchKeywords&&((g=t.searchKeywords)==null?void 0:g.length)>0&&st(D.Labels,{labels:t.searchKeywords}),st(B.Content,{cropText:e==="single",lineClamp:e==="multiple",children:s})]})]}),Jn(D.Actions,{children:[r&&st(D.ActionButton,{onClick:d,label:i("visitUrl")}),st(D.ActionButton,{primary:!0,onClick:p,label:i("preview")}),st(D.ActionButton,{primary:!0,onClick:c,label:i("useSuggestion")})]})]})},Dp=Sv;import{Fragment as bv,jsx as Hp}from"react/jsx-runtime";var xv=({contentType:t,lines:e,suggestions:o})=>{let n=se(),s=_v(Be),r=a=>{n.send(cr,{state:s,suggestion:a,contentType:t})},i=(a,l)=>{n.send(Te,{text:a,suggestion:{...l,source:l.source,sourceText:l.text}})};return Hp(bv,{children:o.map(a=>Hp(Dp,{suggestion:a,lines:e,onEdit:l=>r(l),onUse:l=>i(l,a)},a.text||a.url||a.message))})},Bp=xv;var Xr={};q(Xr,{enUS:()=>Cv,nlNL:()=>wv});var Cv={waiting:[{type:0,value:"Loading\u2026"}],notSupported:[{type:0,value:"This conversation is not supported"}],noResults:[{type:0,value:"No results found\u2026"}],titleAutoflows:[{type:0,value:"Autoflows"}],titleCustomMessages:[{type:0,value:"Quick replies"}],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"}]},wv={waiting:[{type:0,value:"Laden\u2026"}],notSupported:[{type:0,value:"Dit gesprek wordt niet ondersteund"}],noResults:[{type:0,value:"Geen resultaten gevonden\u2026"}],titleAutoflows:[{type:0,value:"Autoflows"}],titleCustomMessages:[{type:0,value:"Quick replies"}],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"}]};var Fp={root:"_root_x0pwe_1",loginText:"_loginText_x0pwe_7",stateText:"_stateText_x0pwe_8",sectionList:"_sectionList_x0pwe_20",shortcutList:"_shortcutList_x0pwe_24",shortcut:"_shortcut_x0pwe_24",link:"_link_x0pwe_52"};import{jsx as Kp}from"react/jsx-runtime";var Up=()=>Kp("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:Kp("path",{d:"M543-340q16.595 0 28.798-12.202Q584-364.405 584-381t-12.202-28.798Q559.595-422 543-422t-28.798 12.202Q502-397.595 502-381t12.202 28.798Q526.405-340 543-340Zm-25-126h47q2-29 8.5-43t32.5-39q27-26 37.5-45.395Q654-612.79 654-639q0-45.882-31.5-74.941Q591-743 540-743q-38 0-68 20.5T428-665l45 19q11-25 27.5-38t39.5-13q29.778 0 48.389 17Q607-663 607-637q0 20-9 35t-32 32q-32 29-40 46.5t-8 57.5ZM260-200q-24 0-42-18t-18-42v-560q0-24 18-42t42-18h560q24 0 42 18t18 42v560q0 24-18 42t-42 18H260Zm0-60h560v-560H260v560ZM140-80q-24 0-42-18t-18-42v-620h60v620h620v60H140Zm120-740v560-560Z"})});import{jsx as jp}from"react/jsx-runtime";var zp=()=>jp("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:jp("path",{d:"M319-250h322v-60H319v60Zm0-170h322v-60H319v60ZM220-80q-24 0-42-18t-18-42v-680q0-24 18-42t42-18h361l219 219v521q0 24-18 42t-42 18H220Zm331-554v-186H220v680h520v-494H551ZM220-820v186-186 680-680Z"})});import{jsx as N,jsxs as Dt}from"react/jsx-runtime";var Yn=(t,e)=>{let o=te(Z);Ev(()=>o?e.every(n=>!!n)?t():()=>{}:()=>{},[...e,o])},Iv=({onLogIn:t})=>{let e=T(Xr),o=kv(),n=C("isEmbedded"),s=y("Widget",Fp),r=C("showAutoflows"),i=C("showCustomMessages"),a=C("showSummaryCommand"),l=C("showKnowledgeSearch"),c=C("showSearch"),p=te(Ke),d=te(Pn),g=te(op),u=te(kn),m=te(ap),f=te(Oo),h=te(ft),E=te(Z),S=te(No),x=te(_p),b=te(Be),v=se(),R=te(ol),A=te(hp("/admin/")),H=C("adminUrl"),P=C("productName");if(Yn(()=>(o(So(S)),o(up(S)),()=>{o(gp(S))}),[o,h,i,S]),Yn(()=>(o(Re(S)),o(np(S)),()=>{o(sp(S))}),[o,h,r,S]),Yn(()=>{d.forEach(({type:k})=>{o(k==="entities"?pe():ce(k))})},[o,h,f,p]),Yn(()=>(o(Wr()),()=>{o(vp())}),[o]),h===!1)return N("div",{className:s.stateText,children:N("div",{children:N("p",{children:e("notSupported")})})},"supported");if(E===!1)return N("div",{className:s.loginText,children:N("div",{children:N(Fn,{isEmbedded:n,loginUrl:H,onLogIn:t})})},"login");if(!p||!S||E===null||R||x)return N("div",{className:s.stateText,children:N("div",{children:N("p",{children:e("waiting")})})},"waiting");let V=c||a||l||A;return N("div",{className:Tv(s.root),"data-testid":"widget",children:Dt(hs,{className:s.sectionList,children:[V&&N(Ve,{title:e("actions"),type:"shortcuts",children:Dt("div",{className:s.shortcutList,children:[c&&Dt("button",{className:s.shortcut,"data-testid":"shortcut-search",onClick:()=>v.send("ShowCommandPalette",{isOpen:!0}),children:[N(wt,{}),e("linkSearch")]}),a&&Dt("button",{className:s.shortcut,"data-testid":"shortcut-summary",onClick:()=>v.send("ShowCommandPalette",{isOpen:!0,page:"summary"}),children:[N(zp,{}),e("linkSummary")]}),l&&Dt("button",{className:s.shortcut,"data-testid":"shortcut-knowledge-assist",onClick:()=>v.send("ShowCommandPalette",{isOpen:!0,page:"knowledgeAssist"}),children:[N(Up,{}),e("linkKnowledgeSearch")]}),A&&Dt("a",{className:s.shortcut,target:"_blank",href:A,"data-testid":"shortcut-studio-login",rel:"noreferrer",children:[N(Op,{}),e("linkStudioLogin",{productName:P})]})]})}),i&&m.length>0&&N(Ve,{type:"custom-messages","data-testid":"custom-messages",children:N(re,{withDivider:!0,children:m.map(k=>N(Mp,{suggestion:k},k.text))})}),r&&g.length>0&&N(Ve,{type:"autoflows",title:e("titleAutoflows"),"data-testid":"autoflows",children:N(re,{withDivider:!0,children:N(Ep,{})})}),d.map(({type:k,title:F,amount:at,lines:Ut})=>{var jt;switch(k){case"entities":return u&&u.length>0&&N(Ve,{type:k,title:F,"data-testid":`type-${k}`,children:N(Ap,{entities:u})},k);default:return((jt=b[k])==null?void 0:jt.fetchState)==="done"&&b[k].suggestions.length>0&&N(Ve,{type:k,title:F,"data-testid":`type-${k}`,children:N(re,{withDivider:!0,children:N(Bp,{lines:Ut,contentType:k,suggestions:b[k].suggestions.slice(0,at)||[]})})},k)}})]})})},Vp=Iv;function bo(t){let e=new Range;return e.selectNodeContents(t),e}function qp(t,e,o){try{return rt(t,e,o),!0}catch{return!1}}function es(t){return"tagName"in t&&(t.tagName==="DIV"||t.tagName==="P")}function ts(t){return"tagName"in t&&t.tagName==="BR"}var xo=/[\u200B-\u200D\uFEFF]/g;function rt(t,e,o){let n=new Range;if(t.firstChild===null&&e===0&&o===0)return n.selectNodeContents(t),n;let s=0,r=!1;function i(l,c){let p=-1,d=/[\u200B-\u200D\uFEFF]/;if(!d.test(l))return c;for(let g=0;g<=l.length;g++)if(d.test(l[g])||p++,p===c)return g;throw new Error("Offset out of range")}function a(l){switch(l.nodeType){case Node.TEXT_NODE:{let c=l.textContent,p=c.replace(xo,""),d=s+p.length,g=e>=s&&e<=d,u=o>=s&&o<=d;if(g){let m=i(c,e-s);m===0&&!u?n.setStartBefore(l):n.setStart(l,m)}u&&(n.setEnd(l,i(c,o-s)),r=!0),s=d;break}case Node.ELEMENT_NODE:{if(ts(l)&&(s===e&&n.setStartBefore(l),s++,s===o)){n.setEndAfter(l),r=!0;return}for(let p=0;p<l.childNodes.length&&(a(l.childNodes[p]),!r);p++);let c=l.lastChild;es(l)&&c&&!es(c)&&!ts(c)&&s++;break}default:break}}if(a(t),n.startContainer===document)throw new Error("Offsets out of bound");return n}function os(t,e){if(!t.contains(e.startContainer)||!t.contains(e.endContainer))throw new Error("Range not within root element");let{startContainer:o,startOffset:n,endContainer:s,endOffset:r,collapsed:i}=e,a,l,c=0;function p(d){let g=d===o,u=d===s;switch(d.nodeType){case Node.TEXT_NODE:{let m=d.textContent;g&&(a=c+m.substring(0,n).replace(xo,"").length),u&&(l=c+m.substring(0,r).replace(xo,"").length),c+=m.replace(xo,"").length;break}case Node.ELEMENT_NODE:{let m=d.nextSibling===null;ts(d)&&!m&&c++;for(let f=0;f<d.childNodes.length;f++){let h=g&&f===n,E=u&&f===r;if(h&&(a=c),E&&(l=c),l!==void 0||((!h||!i)&&p(d.childNodes[f]),u&&f===r-1&&(l=c),l!==void 0))break}!u&&es(d)&&!m&&c++,u&&(l=c);break}default:break}}if(p(t),l===void 0)throw new Error("Could not determine start and end");return{start:a??l,end:l}}function ns(t,e){if(!t.contains(e.startContainer)||!t.contains(e.endContainer))throw new Error("Range not within root element");let{startContainer:o,startOffset:n,endContainer:s,endOffset:r}=e,i=-1,a="";function l(c){let p=c===o,d=c===s;switch(p&&i++,c.nodeType){case Node.TEXT_NODE:{if(i!==0)return;let g=p?n:0,u=d?r:void 0,m=c.textContent.replace(xo,"");g===0&&u===void 0?a+=m:a+=m.substring(g,u);break}case Node.ELEMENT_NODE:{let g=c.nextSibling===null;i===0&&ts(c)&&!g&&(a+=`
8
8
  `);for(let u=p?n:0;u<(d?Math.min(r,c.childNodes.length):c.childNodes.length)&&(l(c.childNodes[u]),i!==1);u++);!d&&i===0&&es(c)&&!g&&(a+=`
9
- `);break}default:break}d&&i++}return l(t),a}function Wp(t){return t.top!==0||t.left!==0||t.height!==0||t.width!==0}var Ht=class extends Ne{observer;lastKnownSelection=null;getRootNode(){return this.element.getRootNode()}getText(){let e=new Range;return e.selectNodeContents(this.element),ns(this.element,e)}getHTML(){return this.element.innerHTML||""}getRange(){var r;let e=this.getRootNode();if(e.activeElement!==this.element)return null;let o="getSelection"in e?e.getSelection():window.getSelection();if(!o)return null;let n="getComposedRanges"in o&&e instanceof ShadowRoot?(r=o.getComposedRanges(e))==null?void 0:r[0]:o.rangeCount>0?o.getRangeAt(0):null;if(!n)return null;let s=this.element.ownerDocument.createRange();return s.setStart(n==null?void 0:n.startContainer,n==null?void 0:n.startOffset),s.setEnd(n==null?void 0:n.endContainer,n==null?void 0:n.endOffset),!s||!this.element.contains(s.startContainer)||!this.element.contains(s.endContainer)?null:s}getCaretPosition(){let e=this.getRange();if(!e||!e.collapsed||!("getBoundingClientRect"in e))return null;let o=e.getBoundingClientRect();return!Wp(o)&&(e.insertNode(this.element.ownerDocument.createTextNode("\u2060")),o=e.getBoundingClientRect(),e.deleteContents(),!Wp(o))?null:{top:o.top+o.height,left:o.left}}getSelection(){let e=this.getRange();if(e)return os(this.element,e);let o=this.lastKnownSelection;if(o&&qp(this.element,o.start,o.end))return o;let n=bo(this.element);return n.collapse(!1),os(this.element,n)}getSelectedText(){let{start:e,end:o}=this.getSelection();return ns(this.element,rt(this.element,e,o))}applyChanges(e){var s;if(!this.isActive)return;this.isSettingValue=!0;let o=this.getText(),n=e(this.element);return(s=this.observer)==null||s.takeRecords(),Promise.resolve(n).then(()=>{this.currentText=this.getText(),o!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(){super.listen(),this.observer=new MutationObserver(()=>{setTimeout(()=>{this.triggerChange()},0)}),this.observer.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0});let e=this.element.isContentEditable,o=new MutationObserver(()=>{this.element.isContentEditable!==e&&(e=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>o.disconnect())}dispose(){super.dispose(),this.observer&&this.observer.disconnect()}};function Gp(t,e,o){let n=`deepdesk-iframe-${t}`,s=document.getElementById(n);if(s)return s;let r=document.createElement("iframe"),i=new URL(e);return Object.entries(o).forEach(([a,l])=>{i.searchParams.append(a,l)}),r.style.position="absolute",r.style.left="-999em",r.style.width="0px",r.style.height="0px",r.tabIndex=-1,r.id=n,r.title=`iframe-${t}`,r.src=i.toString(),window.document.body.appendChild(r),r}var Zr=class{constructor(e){this.name=e;this.broadcastChannel=new BroadcastChannel(e)}broadcastChannel;disposeHandlers=[];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()}},Qr=class{constructor(e,o,n){this.name=e;this.targetOrigin=o;this.options=n;this.iframe=Gp(e,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}iframe;disposeHandlers=[];onMessage(e){window.addEventListener("message",e),this.disposeHandlers.push(()=>{window.removeEventListener("message",e)})}postMessage(e){var o;(o=this.iframe.contentWindow)==null||o.postMessage(JSON.stringify(e),this.targetOrigin)}close(){var e;this.disposeHandlers.forEach(o=>o()),(e=this.iframe)==null||e.remove()}},Jr=class{constructor(e){this.params=e;this.deepdeskUrl=e.deepdeskUrl,this.eventMap=e.eventMap,this.sessionId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}sessionId;deepdeskUrl;channel;defaultChannel;eventMap;get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setSessionId(e){this.sessionId!==e&&(this.cleanup(),w.info("Set sessionId",e),this.sessionId=e,this.channel=this.createChannel(e))}createChannel(e){let o=this.params.createCustomChannel?this.params.createCustomChannel(e):this.isCrossOrigin?new Qr(e,this.deepdeskUrl,{debug:!0}):new Zr(e),n=s=>{var i,a;if(s.origin!==this.deepdeskUrl)return;let r=typeof s.data=="string"?JSON.parse(s.data):s.data;r.type==="event"&&r.channel===e&&(w.info("Received broadcast event",this.sessionId,s),(a=(i=this.eventMap)[r.name])==null||a.call(i,r.payload))};return o.onMessage(n),o}send(e,o){var r,i;w.info("Broadcast event",{sessionId:this.sessionId,name:e,payload:o});let n={type:"event",name:e,payload:o};(i=(r=this.eventMap)[e])==null||i.call(r,o);let s=this.sessionId==="deepdesk-general"?this.defaultChannel:this.channel;s==null||s.postMessage({...n,channel:this.sessionId})}cleanup(e=!1){var o,n;(o=this.channel)==null||o.close(),delete this.channel,e&&((n=this.defaultChannel)==null||n.close(),delete this.defaultChannel)}},$p=Jr;var Bt=class extends Error{constructor(o,n){super(o);this.body=n}name="CustomError"};var Yr=t=>new Promise(e=>{setTimeout(e,t)});var Ft=class extends Bt{name="ClientError"},ei=class extends Bt{name="ServerError"},ve=class t{constructor(e="",o={}){this.baseUrl=e;this.options=o;o.fetch&&(this.fetch=o.fetch)}latestRequestByUrl={};csrfToken;fetch=window.fetch.bind(window);static refreshingToken=null;patchFetch(e){this.fetch=e(this.fetch)}setCsrfToken(e){this.csrfToken=e}request(e,o={}){return new Promise((n,s)=>{let r={isAborted:!1,reject:s},i=`${this.baseUrl}${e}`,a=this.fetch,{abortLatest:l=!1,attempts:c=1,retryDelay:p=500,refreshTokenOn401:d=!0,retryOnError:g=b=>b instanceof TypeError,retryOnResponse:u=b=>b.status>=500,version:m="v1",...f}=o,h={credentials:"include",...f,headers:{"Content-Type":"application/json",...f.headers}};o.method!==void 0&&o.method!=="GET"&&this.csrfToken&&(h.headers={...h.headers,"X-CSRFToken":this.csrfToken}),typeof m=="string"&&(h.headers={...h.headers,"X-Deepdesk-API-Version":m});let E=c,S=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[i]&&l&&(this.latestRequestByUrl[i].isAborted=!0,this.latestRequestByUrl[i].reject(new Error("Aborted"))),this.latestRequestByUrl[i]=r;let x=async()=>(E--,a(i,h).then(async b=>u(b)&&!r.isAborted&&E>0?(await Yr(p),x()):b.status===401&&d===!0&&S===!1?(S=!0,await this.refreshToken(),x()):b).catch(async b=>{if(g(b)&&!r.isAborted&&E>0)return await Yr(p),x();throw b}));x().then(b=>b.json().catch(()=>null).then(v=>{b.status>=500?s(new ei("Server Error",v)):b.status===401?s(new Ft("Unauthorized",v)):b.status===403?s(new Ft("Forbidden",v)):b.status===404?s(new Ft("Not Found",v)):b.status>=400&&s(new Ft("Bad Request",v)),delete this.latestRequestByUrl[i],n(v)})).catch(b=>{s(b)})})}async validateToken(){let{has_valid_access_token:e}=await this.get("/auth/validate");if(!e)return!1;let{is_logged_in:o}=await this.get("/apis/admin/session/validate/",{version:null});return!!o}refreshToken(){return t.refreshingToken||(t.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{t.refreshingToken=null},1e3*60)})),t.refreshingToken}get(e,o){return this.request(e,o)}post(e,o,n){return this.request(e,{method:"POST",body:JSON.stringify(o),...n})}patch(e,o,n){return this.request(e,{method:"PATCH",body:JSON.stringify(o),...n})}put(e,o,n){return this.request(e,{method:"PUT",body:JSON.stringify(o),...n})}delete(e,o){return this.request(e,{method:"DELETE",...o})}};var Rv;(e=>{let t;(l=>(l.SEND_MESSAGE="Send Message",l.HANDLING_TIME="Handling Time",l.START_AUTOFLOW="Start Autoflow",l.ABORT_AUTOFLOW="Abort Autoflow",l.ADD_TO_PERSONAL_COLLECTION="Add to personal collection",l.DELETE_FROM_PERSONAL_COLLECTION="Delete from personal collection"))(t=e.EventType||={})})(Rv||={});function ss(t){return{...L(t),tags:t.tags}}var ze=class t{constructor(e,o={}){this.options=o;this.client=new ve(e,{fetch:o.fetch}),this.client.patchFetch(n=>async(s,r)=>{let i=await n(s,r);return this.handleDeepdeskVersionHeaders(i),i})}latestReceivedDeepdeskVersions={};client;shouldFetchCsrfToken=!0;static exchangeTokenPromise=null;async preflight(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let e=await this.getCsrfToken();this.client.setCsrfToken(e)}return this.options.token?(t.exchangeTokenPromise||(t.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),t.exchangeTokenPromise):Promise.resolve()}async createConversation(e){await this.preflight(),w.info(`Creating conversation for session ${e.sessionId} and agent ${e.agentId}`);let o=await this.client.post("/api/conversations",{...U(e),tags:e.tags},{version:"v2"});return ss(o)}async getProfile(e){let o=await this.client.get(`/apis/admin/profiles/${e}/`,{version:null});return L(o)}async getKnowledgeAssistant(e){let o=await this.client.get(`/apis/admin/knowledge-assist/assistants/${e}/`,{version:null});return L(o)}async getContentTypes(){let e=await this.client.get("/apis/admin/content-types/",{version:null});return L(e)}async getPlatformConfig(){let{config:e}=await this.client.get("/platform/config/",{version:null});return L(e)}async checkUserExists(e){let{exists:o}=await this.client.get(`/apis/admin/users/exists?external_id=${e}`);return o}async getConversationBySessionId(e,o={}){await this.preflight(),w.info(`Getting conversation for session ${e}`);let{attempts:n=1,retryDelay:s=1e3}=o,r=await this.client.get(`/api/conversations/by_session_id/${e}`,{attempts:n,retryDelay:s,retryOnResponse:i=>i.status===404||i.status>=500,version:"v2"});return ss(r)}async isConversationSupported(e,o={}){w.info(`Check if conversation for session ${e} is supported`);let{attempts:n=1,retryDelay:s=1e3}=o;return(await this.client.get(`/api/conversations/by_session_id/${e}/active_profile`,{attempts:n,retryDelay:s,retryOnResponse:i=>i.status===404||i.status>=500,version:"v2"})).has_active_profile}async updateConversation(e,o){let n=U(o);o.tags&&(n.tags=o.tags);let s=await this.client.put(`/api/conversations/${e}`,n,{version:"v2"});return ss(s)}async postMessages(e,o){return(await this.client.post(`/api/conversations/${e}/messages`,o.map(s=>({...U(s),tags:s.tags})),{version:"v2"})).map(s=>ss(s))}async sendEvent(e,o){let{data:n,...s}=o,r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((i,[a,l])=>({...i,[a]:l}),{});return this.client.post("/api/events",U({...r,...s,data:n,name:e}),{version:"v2"})}async sendEventV1(e,o){let n=Object.entries(this.latestReceivedDeepdeskVersions).reduce((s,[r,i])=>({...s,[r]:i}),{});return this.client.post("/api/events",{event:e,data:U({...o,...n})})}async getEntities(e){return(await this.client.post("/api/entities",{messages:e.filter(n=>n.text)})).entities}async getSummary(e,o={}){return(await this.client.post("/api/summary",{conversation:{messages:e.filter(s=>s.text&&s.source),agent_id:o.agentId,id:o.externalConversationId},prompt_instruction:o.promptInstruction,model:o.model})).summary}async getTemporaryExchangeToken(){return(await this.client.get("/auth/exchange-token",{version:null})).jwt}async exchangeTokenForAccessCookie(e){return this.client.post("/apis/admin/session/jwt/",{jwt:e},{version:null}).catch(o=>{throw w.warn(`Invalid token '${e}'`),o})}async authenticateWithKey(e,o){await this.client.post("/apis/admin/session/api-key/",U(o),{version:null,refreshTokenOn401:!1,headers:{apikey:e}})}async getTextSuggestions(e,o={},n){return n==="sticky-messages"?this.getPinnedMessages(e):(await this.client.post(`/api/conversations/${e}/recommend/${n}`,U(o),{abortLatest:!0})).map(r=>({...L(r),text:r.text||r.url||r.message,source:n,type:n})).filter((r,i,a)=>i===a.findIndex(l=>l.text===r.text))}async isLoggedIn(){return await this.preflight(),this.client.validateToken()}async getAutocompleteSuggestions(e,o){return(await this.client.post(`/api/conversations/${e}/autocomplete`,U(o),{abortLatest:!0})).map(s=>({score:1,source:s.source,sourceText:s.source_text,text:s.label,trainingJobs:s.training_jobs,searchKeywords:s.search_keywords,type:s.source})).filter((s,r,i)=>r===i.findIndex(a=>a.text===s.text))}async getPinnedMessages(e){let o=await this.client.get(`/api/conversations/${e}/sticky-messages`,{abortLatest:!0});return L(o).map(n=>({...n,text:n.message,source:"sticky-messages",type:"pinned-message"}))}async getStyleSuggestions(e){let o=await this.client.post("/api/style-suggestions",U(e),{abortLatest:!0});return L(o)}async search(e){let o=await this.client.post(`/api/profiles/${e.profile}/search`,U(e),{version:"v2"});return L(o)}async knowledgeAssist(e,o,n){let s=await this.client.post(`/api/knowledge-assist/assistants/${n}/search`,U({question:e.question,promptInstruction:e.promptInstruction,chatHistory:o.map(r=>({question:r.question,answer:r.answer.answer}))}),{version:"v2"});return L(s)}async requestLoginByEmail(e){let o=await this.client.post("/apis/admin/session/passwordless/request/",{email:e},{version:null});return L(o)}async requestPasswordlessToken(){let e=await this.client.get("/apis/admin/session/passwordless/request/",{version:null});return L(e.token)}async getCsrfToken(){let{token:e}=await this.client.get("/apis/admin/session/csrf/",{version:null});return e}async verifyLoginToken(e){let o=await this.client.post("/apis/admin/session/passwordless/login/",{token:e},{version:null});return L(o)}handleDeepdeskVersionHeaders(e){e.headers.forEach((o,n)=>{let s=n.toLowerCase(),r=s.match(fi);if(!o||!r)return;let i=r[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&o&&a!==o&&w.warn(`Overwritten Version header ${s}: ${JSON.stringify(a)} -> ${JSON.stringify(o)}`),this.latestReceivedDeepdeskVersions[i]=o})}};var Co=class{constructor(e,o){this.url=e;this.options={timeout:25e3,...o}}eventListeners={};options;timeoutTimer;eventSource;proxyEvent(e){this.eventSource.addEventListener(er(e),o=>{let{data:n}=o;try{let s=JSON.parse(n);this.emit(e,L(s))}catch{w.warn(`Invalid JSON for ${e}: ${n}`)}})}connect(){clearTimeout(this.timeoutTimer);let e=new EventSource(this.url,{withCredentials:!0});this.eventSource=e;let o=!1;e.onopen=()=>{o=!0},e.onerror=()=>{o&&e.readyState===2&&this.connect()},this.timeoutTimer=setTimeout(()=>{e.close(),this.connect()},this.options.timeout),Object.keys(this.eventListeners).forEach(n=>{this.proxyEvent(n)})}disconnect(){var e;clearTimeout(this.timeoutTimer),this.eventListeners={},(e=this.eventSource)==null||e.close()}emit(e,o){this.eventListeners[e]&&this.eventListeners[e].forEach(n=>n(o))}on(e,o){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(o),this.proxyEvent(e),()=>{this.off(e,o)}}off(e,o){let n;this.eventListeners[e]&&(n=this.eventListeners[e].indexOf(o),n>-1&&this.eventListeners[e].splice(n,1))}};var Pv;(e=>{let t;(r=>(r.Started="Started",r.Aborted="Aborted",r.Completed="Completed"))(t=e.AutoflowSessionState||={})})(Pv||={});var wo=class{constructor(e,o={}){this.apiUrl=e;this.client=new ve(e,o)}client;streams={};logger=w;async getCustomMessages(e){let o=await this.client.get(`/sessions/${e}/suggestions`);return L(o.suggestions)}async sendCustomMessage(e,o){let n=await this.client.post(`/sessions/${e}/messages`,U(o));return L(n)}async answerCustomMessage(e,o){await this.client.post(`/sessions/${e}/answers`,U(o))}async getAutoflows(e){let o=await this.client.get(`/sessions/${e}/autoflows`);return L(o.autoflows)}async startAutoflowSession(e){let o=await this.client.post("/autoflow-sessions",U(e));return L(o)}async stopAutoflowSession(e){await this.client.delete(`/autoflow-sessions/${e}`)}openStream(e){return this.streams[e]||(this.streams[e]=new Co(`${this.apiUrl}/sessions/${e}/events`),this.streams[e].connect()),this.streams[e]}closeStream(e){this.streams[e]||(this.streams[e].disconnect(),delete this.streams[e])}};import{combineReducers as Hv,configureStore as Bv}from"@reduxjs/toolkit";import{createSlice as Av}from"@reduxjs/toolkit";var Xp={startTime:null,stopTime:null},Zp=Av({name:"handlingTime",initialState:Xp,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(M,()=>Xp)}}),{handlingTimeStart:Qp,handlingTimeStop:rs,handlingTimeReset:Jp}=Zp.actions,Yp=Zp.reducer;var ed=(t={})=>{let e={onAuthError:kt(!1),...t};return o=>n=>s=>("error"in s&&s.error.message==="Unauthorized"&&o.dispatch(e.onAuthError),n(s))};import{createAsyncThunk as Lv,createSlice as Mv}from"@reduxjs/toolkit";var is={list:{keywordMatches:[]},fetchState:"idle",isInitialRequest:null};var it=Lv("styleSuggestions/getAll",async({text:t},e)=>{var i;let{deepdeskAPI:o}=e.extra,n=e.getState(),{showStyleSuggestions:s}=n.settings,r=(i=n.conversation.current)==null?void 0:i.profileCode;if(!s)return is.list;if(!r)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:r,message:t})}),Nv=Mv({name:"styleSuggestions",initialState:is,reducers:{},extraReducers:t=>{t.addCase(it.pending,e=>{e.isInitialRequest=e.isInitialRequest===null,e.fetchState="loading"}).addCase(it.rejected,e=>{e.fetchState="error"}).addCase(it.fulfilled,(e,o)=>{e.fetchState="done",Ae(e.list,o.payload)||(e.list=o.payload)}).addCase(Ge,e=>{e.list=is.list}).addCase(M,()=>is)}}),td=Nv.reducer;var od=(t={})=>{let e,o=!0,n={getStyleSuggestions:it,debounce:500,...t};return s=>r=>i=>{var u;let a=s.getState().input.text,l=r(i),c=s.getState();if(c.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:p}=c.settings;if(!((u=c.conversation.current)==null?void 0:u.id)||!p)return l;let{text:g}=c.input;return g===a&&!o||(clearTimeout(e),g==="")||(e=setTimeout(()=>{o=!1,s.dispatch(n.getStyleSuggestions({text:g}))},t.debounce)),l}};function Ov(t,e){return t.text===e.text&&t.selection.start===e.selection.start&&t.selection.end===e.selection.end}var nd=(t={})=>{let e={getTextSuggestions:ce,getAutocompleteSuggestions:no,debounce:200,check:Mt,...t},o;return n=>s=>r=>{var f;let{input:{userCommitted:i}}=n.getState(),a=s(r),l=n.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:c,showTabCompletion:p}=l.settings,d=(f=l.conversation.current)==null?void 0:f.id,g=r.type===wn.toString();if(!d||!c&&!p)return a;let{input:{userCommitted:u}}=l;return Ov(u,i)&&!g||(clearTimeout(o),!e.check(l))||(o=setTimeout(()=>{let h=ht(l);h===""?n.dispatch(e.getTextSuggestions("default")):n.dispatch(e.getAutocompleteSuggestions(h))},g?0:e.debounce)),a}};var sd=it.fulfilled.toString();function Dv(t,e){let o=new Set([...e.keywordMatches.map(s=>s.keyword)]),n=[];return o.forEach(s=>{let r=t.keywordMatches.filter(l=>l.keyword===s),i=e.keywordMatches.filter(l=>l.keyword===s),a=i.length-r.length;a<=0||n.push(...i.slice(0,a))}),n}var rd=t=>e=>o=>n=>{var c;if(n.type!==sd){o(n);return}let s=e.getState().styleSuggestions.list;o(n);let r=e.getState(),i=r.styleSuggestions.list,a=(c=r.conversation)==null?void 0:c.current;if(s===i)return;let l=Dv(s,i);n.type===sd&&l.length>0&&t.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var Fv=Hv({activeSuggestion:ul,answer:tc,auth:Tl,autoflows:rp,conversation:xi,contentTypes:Dl,customMessages:mp,passwordlessToken:Sp,entities:Fl,knowledgeAssistant:Jl,handlingTime:Yp,info:Ha,input:ws.reducer,overlayInput:Q.reducer,settings:yi,profile:ic,search:za,summary:Wl,styleSuggestions:td,ui:hl,textSuggestions:al});function id(t){return Bv({reducer:Fv,middleware:e=>[...e({thunk:{extraArgument:{dynamicThunkObject:t.dynamicThunkObject,deepdeskAPI:t.deepdeskAPI,deepdeskBrokerAPI:t.deepdeskBrokerAPI}},serializableCheck:!1}),ed(),nd({debounce:200}),od({debounce:500}),rd(t.deepdeskAPI),...t.middleware?t.middleware:[]],preloadedState:t.preloadedState})}var Kv=t=>{var e;return((e=t==null?void 0:t.type)==null?void 0:e.toLowerCase())??"unknown"},Uv=t=>e=>o=>n=>{var a;let s=e.getState(),r=_s("inlineSuggestions")(s);switch(n.type){case Ce.toString():{let l=Cn(n.payload.contentType)(e.getState()),c=l.indexOf(n.payload.suggestion);t.emit("edit-suggestion",{contentType:n.payload.contentType,index:c,suggestions:l});break}case kt.toString():{!n.payload&&t.emit("logout",void 0);break}case ie.toString():{let{start:l,end:c}=s.input.selection;t.emit("select-suggestion",{type:Kv(n.payload.suggestion),...n.payload,replace:n.payload.replace==="selection"?{start:l,end:c}:{start:0,end:c}},{mayApplyChanges:!0});break}case jo.toString():{let{start:l,end:c}=s.input.selection;t.emit("replace",{...n.payload,replace:n.payload.replace==="selection"?{start:l,end:c}:{start:0,end:c}},{mayApplyChanges:!0});break}case Wt.toString():{let l=e.getState(),{text:c,selection:p}=l.input.userCommitted;t.emit("reset",{text:c,selectionAfter:p},{mayApplyChanges:!0});break}case Wo.toString():t.emit("select-image",n.payload,{mayApplyChanges:!0}),t.sendEvent("Image attached",{conversationId:s.conversation.current.id,data:{path:n.payload.suggestion.image,title:n.payload.suggestion.title}});break;case pe.fulfilled.toString():n.payload.length>0&&t.sendEvent("entities found",{conversationId:s.conversation.current.id,data:{entities:n.payload}});break;case Ee.fulfilled.toString():t.sendEvent("conversation summarized",{conversationId:s.conversation.current.id,data:{summary:n.payload.summary}});break;case W.toString():t.sendEvent(n.payload.name,{conversationId:((a=n.payload.options)==null?void 0:a.includeConversationData)&&s.conversation.current.id,data:n.payload.data});break;case zo.toString():t.handleKeyDown(n.payload);break;case Ge.toString():t.logSendMessage(n.payload);break;case Vo.toString():t.logSendEditSuggestionMessage(n.payload);break;case qo.toString():t.handleInputChanged(n.payload);break;default:break}let i=o(n);switch(n.type){case Ge.toString():t.handleAfterSendMessage(n.payload);break;case so.toString():t.onUpdateShowTabHint(n.payload);break;case rs.toString():t.logHandlingTime();break;case ie.toString():{r&&(e.dispatch(ge([])),e.dispatch(_e()));break}case ge.toString():{r&&n.payload.length>0&&e.dispatch(Me(0));break}default:break}return i},ad=Uv;function ti(t){return t.toISOString().replace("T"," ").replace("Z","")}function ld(t,e){var s,r,i;let{startTime:o,stopTime:n}=t.handlingTime;if(!o||!n)throw new Error("No startTime and stopTime for handling time metrics");return{conversationId:t.conversation.current.id,clientVersion:e.version,agentId:(s=t.info.agentInfo)==null?void 0:s.agentId,agentName:(r=t.info.agentInfo)==null?void 0:r.agentName,agentEmail:(i=t.info.agentInfo)==null?void 0:i.agentEmail,timeStart:ti(o),timeStop:ti(n)}}function oi(t,e,o){var A,H,P;let{text:n,metrics:{numCharsTyped:s,numCharsPasted:r,numCharsCut:i,numCharsDeleted:a,numPaste:l,agentStartedTypingTimestamp:c,externalTimeTotalSeconds:p,pastes:d,cuts:g,deletions:u,textSuggestions:m,offeredTextSuggestions:f}}=e[t],h=n.length,S=m.reduce((V,{text:k,searchTerm:F})=>V+k.length-(F?F.length:0),0),x=c??Date.now(),b=(Date.now()-x)/1e3+(p||0),v=s/b,R=m.reduce((V,{searchTerm:k})=>V+(k?k.length:0),0);return{conversationId:e.conversation.current.id,source:"agent",text:n,clientVersion:o.version,pastes:d,cuts:g,deletions:u,lenTextTyped:s+R,lenTextTotal:h,lenTextAssisted:S,lenTextPasted:r,lenTextCut:i,lenTextDeleted:a,timeTotalSeconds:b,charsPerSecond:v,numPastes:l,textSuggestionsV2:m,suggestionsCounters:[{source:"gpt",countOffered:f.filter(V=>V.source==="gpt").length}],agentId:(A=e.info.agentInfo)==null?void 0:A.agentId,agentName:(H=e.info.agentInfo)==null?void 0:H.agentName,agentEmail:(P=e.info.agentInfo)==null?void 0:P.agentEmail}}function ni(t,e){var r;let o=t.closest(e);if(o)return o;let n=t.getRootNode().host;if(n instanceof HTMLElement)return ni(n,e);let s=(r=t.ownerDocument.defaultView)==null?void 0:r.frameElement;return s?ni(s,e):null}function cd(t,e){return ni(t,e)}function pd(t){return typeof t=="object"&&t!==null&&"name"in t&&"message"in t}function jv(t){return typeof t=="object"&&t!==null&&"tagName"in t}function si(t){return jv(t)&&(Ue(t)||cn(t))}var dd=(t,e)=>({value(){try{let o=sessionStorage.getItem(`dd-${t}`);if(!o)return e;try{return JSON.parse(o)}catch{return e}}catch{return e}},update(o){try{sessionStorage.setItem(`dd-${t}`,JSON.stringify(o))}catch{w.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function zv(t){return t.offsetParent!==null}function ud(t){if(!zv(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 ri(t,e,o=100){let n=ud(t);e({isVisible:n});let s=setInterval(()=>{let r=ud(t);r!==n&&(n=r,e({isVisible:n}))},o);return()=>{clearTimeout(s)}}import{jsx as j}from"react/jsx-runtime";var gd=dd("showTabHint",!0),ls=class t{static version="10.10.3-beta.6";static count=0;deepdeskApi;inputMediator=null;version;broadcastEvents;eventListeners={};unmountHandlers=[];widgetRoot=null;dynamicThunkObject={};isMounted=!1;instanceId;shouldRender=!0;store;constructor({deepdeskUrl:e,brokerUrl:o,version:n=t.version||"unknown",locale:s="en-US",token:r,fetch:i,productName:a,createCustomChannel:l}){let c=e.replace(/\/api$/,"");this.deepdeskApi=new ze(c,{token:r,fetch:i}),this.version=n,this.instanceId=t.count++;let p={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[ad({emit:(d,g,u)=>this.emit(d,g,u),handleAfterSendMessage:d=>this.handleAfterSendMessage(d),handleInputChanged:d=>this.handleInputChanged(d),handleKeyDown:d=>this.handleKeyDown(d),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:d=>this.logSendMessage(d),logSendEditSuggestionMessage:d=>this.logSendEditMessage(d),onUpdateShowTabHint:d=>gd.update(d),sendEvent:(d,g)=>this.deepdeskApi.sendEvent(d,g)})]};o&&Object.assign(p,{deepdeskBrokerAPI:new wo(o)}),this.store=id(p),this.broadcastEvents=new $p({debug:!0,deepdeskUrl:c,eventMap:El(this.store),createCustomChannel:l}),this.store.dispatch(qt),this.store.dispatch(so(gd.value())),this.store.dispatch(qt({locale:s,adminUrl:c,productName:a}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){return this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex]??null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(w.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(w.warn("Profile has not been loaded (yet)"),!0):(w.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(kt(null)),this.store.dispatch(we()),new Promise(e=>{let o=this.store.subscribe(()=>{let n=this.store.getState();Z(n)&&Sl(n)!=="loading"&&(o(),e())});this.unmountHandlers.push(()=>{o()})})}async isLoggedIn(){return(await this.store.dispatch(we())).payload}async setPlatformAgentId(e){try{if((await this.deepdeskApi.client.get("/apis/admin/session/me/",{version:null})).external_id)return;await this.deepdeskApi.client.request("/apis/admin/session/me/",{method:"PATCH",body:JSON.stringify({external_id:e}),version:null})}catch(o){w.warn("Failed to attach user:",o)}}async isConversationSupported(e,o){return(await this.store.dispatch(bs({sessionId:e,options:o}))).payload}async createConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(Do(e))).payload}async getConversationBySessionId(e,o){return this.hasConversation()&&this.sessionId()!==e&&this.resetConversation(),(await this.store.dispatch(Ho({sessionId:e,options:o}))).payload}async upsertConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(Cs(e))).payload}async postMessages(e){return(await this.store.dispatch(Fo(e))).payload}async updateConversation(e){return(await this.store.dispatch(Bo(e))).payload}resetConversation(){this.store.dispatch(M()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}async getSummary(){let e=await this.store.dispatch(Ee());if(e.error)throw new Error(e.error.message);return e.payload.summary}configure(e){this.store.dispatch(qt(e))}setVisitorInfo(e){this.store.dispatch(Da(e))}async setAgentInfo(e){await this.store.dispatch(eo(e))}async setAgentSettings(e){await this.store.dispatch(or(e))}async getAgentSettings(){return(await this.store.dispatch(nr())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let e=[];return this.store.dispatch(wn()),e.push(this.refreshWidgetSuggestions()),Promise.all(e).then(()=>{})}notifyInputChanged(e){this.store.dispatch(qo(e))}notifyKeyDown(e){this.store.dispatch(zo(e))}notifyPaste(e,o){this.store.dispatch(Li({text:e,selectionText:o}))}notifyCut(e){this.store.dispatch(Pi(e))}notifyExternalSuggestion(e){this.store.dispatch(ie(e)),this.store.dispatch(_e())}notifyEditSuggestion(e){this.store.dispatch(rl(e.contentType,e.suggestions)),this.store.dispatch(Ce({contentType:e.contentType,suggestion:typeof e.index=="number"?e.suggestions[e.index]:null}))}handleInputChanged(e){let{overlayCollapsed:o,openOverlayWhenTyping:n}=this.state.ui;o&&n&&this.store.dispatch(Fe({collapse:!1})),this.inputMediator&&this.store.dispatch(wi({text:e,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(ge([])))}handleKeyDown(e){let{overlayCollapsed:o}=this.state.ui,{textSuggestions:n,selectedSuggestionIndex:s,selection:r}=this.state.input,{inlineSuggestions:i}=this.state.settings,a=n.length>0,l=s!==-1;if(this.store.dispatch(Ai(Uo(e))),e.key!=="Tab"&&!this.settings.showTextSuggestions)return;let c=()=>{o||!a||r&&(e.shiftKey||(this.store.dispatch(ki()),i||this.stageSelectedSuggestion({inputType:"arrow"}),e.preventDefault()))},p=()=>{o||!a||i&&s<=0||r&&(e.shiftKey||(this.store.dispatch(Ri()),e.preventDefault(),!i&&(this.state.input.selectedSuggestionIndex===-1?this.store.dispatch(Wt()):this.stageSelectedSuggestion({inputType:"arrow"}))))};switch(e.key){case"Up":case"ArrowUp":i?p():c();return;case"Down":case"ArrowDown":{i?c():p();return}case"Esc":case"Escape":{i&&l&&this.store.dispatch(Me(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(Me(-1)),this.store.dispatch(Wt()),e.preventDefault()):o||(this.store.dispatch(Fe({collapse:!0})),this.store.dispatch(ml(!0)),e.preventDefault());return}case"Tab":{let{userCommitted:d}=this.state.input,g=d.text.substring(0,d.selection.end),{tabCompletionSuggestion:u}=this.state.input;this.store.dispatch(so(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!i&&this.settings.showTabCompletion&&u&&u.text.startsWith(g)&&(this.store.dispatch(ie({text:u.text,suggestion:u,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch(_e())),e.preventDefault();break}default:}}handleAfterSendMessage(e){this.emit("send-message",e),this.store.dispatch(Mi()),this.store.dispatch(ge([]))}handlingTimeStart(){this.state.handlingTime.startTime||(w.info("Start handling time"),this.store.dispatch(Qp()))}handlingTimeStop(){this.state.handlingTime.startTime&&(w.info("Stop handling time"),this.store.dispatch(rs()))}logSendMessage(e){let o=oi("input",this.state,{version:this.version});e&&(Object.assign(o,{text:e}),Object.assign(o,{lenTextTotal:e.length})),this.deepdeskApi.sendEventV1("Send Message",o),this.emit("send-message-event",o)}logSendEditMessage(e){let o=oi("overlayInput",this.state,{version:this.version});e&&Object.assign(o,{text:e}),this.store.dispatch(Ei(this.state.overlayInput.metrics))}logHandlingTime(){let e=ld(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",e),this.store.dispatch(Jp())}notifySubmit(e={}){this.shouldAbort()||(this.store.dispatch(_e()),this.store.dispatch(Ge(e.text??this.state.input.text)))}stageSelectedSuggestion(e){let o=this.state.input.selectedSuggestionIndex,{textSuggestions:n}=this.state.input;this.store.dispatch(ie({text:n[o].text,suggestion:n[o],eventMetrics:e,replace:"until-selection-end"}))}emit(e,o,n={}){let s=()=>{this.eventListeners[e]&&this.eventListeners[e].forEach(r=>{try{r(o)}catch(i){w.warn(`The following error occurred in deepdeskSDK.on('${e}', handler)`),w.error(i)}})};this.inputMediator&&n.mayApplyChanges?this.inputMediator.applyChanges(s):s()}on(e,o){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(o),()=>{this.off(e,o)}}off(e,o){if(!e&&!o){this.eventListeners={};return}let n;this.eventListeners[e]&&(n=this.eventListeners[e].indexOf(o),n>-1&&this.eventListeners[e].splice(n,1))}setConversationQuery(e){this.dynamicThunkObject.conversationQuery=e}whenConversationLoaded(e){let o=()=>this.loadProfileConfig().then(()=>e());this.hasConversation()&&o();let n=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==n&&(n=this.hasConversation(),n&&o())})}overlayContainerFactory(e,o,n,s){let[r,i]=xt(o,n);return r.setAttribute("translate","no"),r.dataset.testid=e,s&&r.classList.add(s),this.unmountHandlers.push(()=>{as(r),i(),r.remove()}),r}createInlineContainer(e,o){var i;let n=document.createElement("div");n.style.position="absolute",n.style.top="0px",n.style.left="0px",n.style.height="0px",n.style.width="0px";let s=document.createElement("div");s.style.display="none",s.style.position="absolute",s.style.height="0px",s.style.width="0px",s.style.backgroundColor="red",n.appendChild(s);let r=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;if(r){let[a,l]=xt(r,{appendTo:document.body,onMoveStart:()=>{s.style.display="none"}});a.dataset.testid=o,a.style.zIndex="2",a.appendChild(n),this.unmountHandlers.push(()=>{as(s),l()})}else document.body.appendChild(n);return s}createContainer(e,o=document.body){let n=window.getComputedStyle(o),s=document.createElement("div");return Xe(s),s.dataset.testid=e,s.style.color=n.color,s.style.fontSize=n.fontSize,s.style.fontFamily=n.fontFamily,s.style.fontVariant=n.fontVariant,s.setAttribute("translate","no"),o.appendChild(s),this.unmountHandlers.push(()=>{as(s),s.remove()}),s}storeMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,o=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(e,o),w.info(`Stored analytics for ${this.conversationId()}`)}catch{}}restoreMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,o=window.sessionStorage.getItem(e);if(!o)return;let n=JSON.parse(o);n.text.trim()===this.state.input.text.trim()?(w.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(Oi(n.metrics))):w.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(e)}catch{}}mount(e,o={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!si(e))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let{customStyles:n={},showStyleSuggestions:s,showTabCompletion:r,showTextSuggestions:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:c,showSuggestionsAfterPattern:p,isEmbedded:d,detectSubmit:g,insertLink:u,inputMediator:m,closestScrollSelector:f,appendOverlayTo:h,inlineSuggestions:E,floatingMenu:S}=o;this.configure({showStyleSuggestions:s,showTabCompletion:r,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:c,showSuggestionsAfterPattern:p,showTextSuggestions:i,insertLink:u,isEmbedded:d,inlineSuggestions:E,floatingMenu:!!S}),o.automaticHandlingTime&&this.setupHandlingTime(e),Xe(e),this.inputMediator=m||(Ue(e)?new Oe(e):new Ht(e)),this.inputMediator.on("change",({plainText:v})=>{this.notifyInputChanged(v)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(Ni({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",v=>{this.notifyKeyDown(v)}),this.inputMediator.on("paste",({pastedText:v,selectionText:R})=>{this.notifyPaste(v,R)}),this.inputMediator.on("cut",({selectionText:v})=>{this.notifyCut(v)});let x=f&&cd(e,f)||void 0;if(E){let{customStyles:v,appendOverlayTo:R}=o;if(Ue(e))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let A=this.createInlineContainer(e,"deepdesk-caret");Kt(j(tt,{store:this.store,customStyles:v,children:j(et,{broadcastEvents:this.broadcastEvents,children:j(Cc,{})})}),A),this.inputMediator.on("caret",P=>{this.store.dispatch(ge([])),P?(A.style.display="block",A.style.top=`${P.top}px`,A.style.left=`${P.left}px`):A.style.display="none"});let H=this.overlayContainerFactory("floating-menu",x||e,{appendTo:typeof S=="object"&&"appendOverlayTo"in S?S.appendOverlayTo:R},v==null?void 0:v.floatingMenuRootNode);Kt(j(tt,{store:this.store,customStyles:v,children:j(et,{broadcastEvents:this.broadcastEvents,children:j(yc,{onLogIn:()=>this.loginViaPopup().catch(P=>w.warn(P.message))})})}),H)}else{let v=this.overlayContainerFactory("deepdesk-tab-completion",x||e,{appendTo:h,closestScrollElement:x,mirrorOverflow:!0,onRemove:()=>this.unmount()},n==null?void 0:n.rootNode),R=this.overlayContainerFactory("deepdesk-suggestions-overlay",x||e,{appendTo:h},n==null?void 0:n.suggestionsRootNode);Kt(j(tt,{store:this.store,customStyles:n,children:j(et,{broadcastEvents:this.broadcastEvents,children:j(Yc,{inputElement:e})})}),v),Kt(j(tt,{store:this.store,customStyles:n,children:j(et,{broadcastEvents:this.broadcastEvents,children:j(Lc,{onLogIn:()=>this.loginViaPopup().catch(A=>w.warn(A.message))})})}),R)}Kt(j(tt,{store:this.store,customStyles:n,children:j(et,{broadcastEvents:this.broadcastEvents,children:j(dc,{})})}),this.createContainer("deepdesk-overlays"));let b;this.inputMediator.on("selection",v=>{clearTimeout(b),v===null?b=setTimeout(()=>{v!==null&&this.store.dispatch(Ts(v))},500):this.store.dispatch(Ts(v))}),this.inputMediator.on("disabled",()=>{var v;(v=this.inputMediator)==null||v.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{g&&this.notifySubmit()}),this.inputMediator.on("blur",()=>this.store.dispatch(Et(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(Et(!0))),this.store.dispatch(Ti({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.unmountHandlers.push(()=>{this.state.input.text!==""&&(this.store.dispatch(_e()),this.storeMetrics())}),this.whenConversationLoaded(()=>{var v;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((v=this.state.conversation.current)==null?void 0:v.sessionId)}),this.isMounted=!0}unmount(){var e;this.unmountHandlers.forEach(o=>o()),this.unmountHandlers=[],(e=this.inputMediator)==null||e.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(e,o={}){if(this.widgetRoot&&w.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:n,showImages:s,isEmbedded:r}=o;this.widgetRoot=e,this.configure({showImages:s,isEmbedded:r}),Kt(j(tt,{store:this.store,customStyles:n,children:j(et,{broadcastEvents:this.broadcastEvents,children:j(Vp,{onLogIn:()=>this.loginViaPopup().catch(i=>w.warn(i.message))})})}),e),this.whenConversationLoaded(()=>{var i;this.broadcastEvents.setSessionId((i=this.state.conversation.current)==null?void 0:i.sessionId)})}unmountWidget(){this.widgetRoot&&as(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(e){let o=ri(e,({isVisible:n})=>{n?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),o()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){pd(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(go());let e=Ke(this.state);e&&(await this.store.dispatch(uo()),this.store.dispatch(qt({showSearch:e.search,showAutoflows:e.autoflows,showCustomMessages:e.customMessages,showImageSearch:e.imageSearch,showEntitiesCommand:e.entitiesCommand,showSummaryCommand:e.summarizer,showKnowledgeSearch:!!e.knowledgeAssistant,recommendTextSuggestions:e.recommendTextSuggestions})))}),this.loadProfileConfigPromise)}async loginViaPopup(e){return new Promise((o,n)=>{let s=new MessageChannel,r=s.port1,i=this.state.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 l=!1,c=()=>{p&&!p.closed&&p.close(),window.removeEventListener("message",d),clearInterval(g)};r.onmessage=async u=>{var m,f;if((m=u.data)!=null&&m.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((f=u.data)==null?void 0:f.jwt),await this.isLoggedIn(),this.broadcastEvents.send(io),l=!0,s.port1.close(),o()}catch(h){console.error(h),n(h)}finally{l=!0,c()}};let p=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");p===null&&n(new Error("Popup blocked by browser"));let d=async u=>{var m;if(u.origin===a.origin)switch((m=u.data)==null?void 0:m.type){case"deepdesk-popup-loaded":{try{let f=JSON.stringify({type:"deepdesk-popup-create-channel"});p==null||p.postMessage(f,a.origin,[s.port2])}catch(f){w.error("Error posting message to popup",f),n(f)}break}case"deepdesk-popup-error":{c(),u.data.message==="Timeout"&&w.warn("Popup timed out. Check if the account's platform url is configured correctly."),n(new Error(u.data.message));break}}};window.addEventListener("message",d);let g=setInterval(()=>{p&&!p.closed||(c(),l||n(new Error("Popup closed by user")))},200);this.unmountHandlers.push(c)})}async checkForTrialMode(e){try{let{account:o}=await this.deepdeskApi.getPlatformConfig();if(!o.isTrial){this.shouldRender=!0;return}if(w.info("Trial is active"),!await this.deepdeskApi.checkUserExists(e))throw new Error("User is not in trial");this.shouldRender=!0}catch(o){let{message:n}=o;w.info(n),this.shouldRender=!1}}async refreshWidgetSuggestions(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:e}=this.state.profile.data;if(!e.widget)return;let o=Pn(this.state);try{o.forEach(({type:n})=>{n==="entities"?this.store.dispatch(pe()):this.store.dispatch(ce(n))})}catch(n){this.handleError(n)}}};async function Vv(t,e,o={}){let{value:n}=t,{start:s,end:r}=o.replace??{start:0,end:n.length},i=`${n.slice(0,s)}${e}${n.slice(r)}`,a=o.selectionAfter??{start:s+e.length,end:s+e.length},l=()=>{if(o.setValue)return o.setValue(i);t.value=i};return Promise.resolve(l()).then(()=>{t.selectionStart=a.start,t.selectionEnd=a.end,t.blur(),t.focus()})}async function qv(t,e,o={}){let n=o.replace?rt(t,o.replace.start,o.replace.end):bo(t),s,r=()=>{if(o.setRange)return o.setRange(n.cloneRange());n.deleteContents(),s=document.createElement("span"),n.insertNode(s),o.insertBRs!==!1?e.split(`
9
+ `);break}default:break}d&&i++}return l(t),a}function Wp(t){return t.top!==0||t.left!==0||t.height!==0||t.width!==0}var Ht=class extends Ne{observer;lastKnownSelection=null;getRootNode(){return this.element.getRootNode()}getText(){let e=new Range;return e.selectNodeContents(this.element),ns(this.element,e)}getHTML(){return this.element.innerHTML||""}getRange(){var r;let e=this.getRootNode();if(e.activeElement!==this.element)return null;let o="getSelection"in e?e.getSelection():window.getSelection();if(!o)return null;let n="getComposedRanges"in o&&e instanceof ShadowRoot?(r=o.getComposedRanges(e))==null?void 0:r[0]:o.rangeCount>0?o.getRangeAt(0):null;if(!n)return null;let s=this.element.ownerDocument.createRange();return s.setStart(n==null?void 0:n.startContainer,n==null?void 0:n.startOffset),s.setEnd(n==null?void 0:n.endContainer,n==null?void 0:n.endOffset),!s||!this.element.contains(s.startContainer)||!this.element.contains(s.endContainer)?null:s}getCaretPosition(){let e=this.getRange();if(!e||!e.collapsed||!("getBoundingClientRect"in e))return null;let o=e.getBoundingClientRect();return!Wp(o)&&(e.insertNode(this.element.ownerDocument.createTextNode("\u2060")),o=e.getBoundingClientRect(),e.deleteContents(),!Wp(o))?null:{top:o.top+o.height,left:o.left}}getSelection(){let e=this.getRange();if(e)return os(this.element,e);let o=this.lastKnownSelection;if(o&&qp(this.element,o.start,o.end))return o;let n=bo(this.element);return n.collapse(!1),os(this.element,n)}getSelectedText(){let{start:e,end:o}=this.getSelection();return ns(this.element,rt(this.element,e,o))}applyChanges(e){var s;if(!this.isActive)return;this.isSettingValue=!0;let o=this.getText(),n=e(this.element);return(s=this.observer)==null||s.takeRecords(),Promise.resolve(n).then(()=>{this.currentText=this.getText(),o!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(){super.listen(),this.observer=new MutationObserver(()=>{setTimeout(()=>{this.triggerChange()},0)}),this.observer.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0});let e=this.element.isContentEditable,o=new MutationObserver(()=>{this.element.isContentEditable!==e&&(e=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>o.disconnect())}dispose(){super.dispose(),this.observer&&this.observer.disconnect()}};function Gp(t,e,o){let n=`deepdesk-iframe-${t}`,s=document.getElementById(n);if(s)return s;let r=document.createElement("iframe"),i=new URL(e);return Object.entries(o).forEach(([a,l])=>{i.searchParams.append(a,l)}),r.style.position="absolute",r.style.left="-999em",r.style.width="0px",r.style.height="0px",r.tabIndex=-1,r.id=n,r.title=`iframe-${t}`,r.src=i.toString(),window.document.body.appendChild(r),r}var Zr=class{constructor(e){this.name=e;this.broadcastChannel=new BroadcastChannel(e)}broadcastChannel;disposeHandlers=[];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()}},Qr=class{constructor(e,o,n){this.name=e;this.targetOrigin=o;this.options=n;this.iframe=Gp(e,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}iframe;disposeHandlers=[];onMessage(e){window.addEventListener("message",e),this.disposeHandlers.push(()=>{window.removeEventListener("message",e)})}postMessage(e){var o;(o=this.iframe.contentWindow)==null||o.postMessage(JSON.stringify(e),this.targetOrigin)}close(){var e;this.disposeHandlers.forEach(o=>o()),(e=this.iframe)==null||e.remove()}},Jr=class{constructor(e){this.params=e;this.deepdeskUrl=e.deepdeskUrl,this.eventMap=e.eventMap,this.sessionId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}sessionId;deepdeskUrl;channel;defaultChannel;eventMap;get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setSessionId(e){this.sessionId!==e&&(this.cleanup(),w.info("Set sessionId",e),this.sessionId=e,this.channel=this.createChannel(e))}createChannel(e){let o=this.params.createCustomChannel?this.params.createCustomChannel(e):this.isCrossOrigin?new Qr(e,this.deepdeskUrl,{debug:!0}):new Zr(e),n=s=>{var i,a;if(s.origin!==this.deepdeskUrl)return;let r=typeof s.data=="string"?JSON.parse(s.data):s.data;r.type==="event"&&r.channel===e&&(w.info("Received broadcast event",this.sessionId,s),(a=(i=this.eventMap)[r.name])==null||a.call(i,r.payload))};return o.onMessage(n),o}send(e,o){var r,i;w.info("Broadcast event",{sessionId:this.sessionId,name:e,payload:o});let n={type:"event",name:e,payload:o};(i=(r=this.eventMap)[e])==null||i.call(r,o);let s=this.sessionId==="deepdesk-general"?this.defaultChannel:this.channel;s==null||s.postMessage({...n,channel:this.sessionId})}cleanup(e=!1){var o,n;(o=this.channel)==null||o.close(),delete this.channel,e&&((n=this.defaultChannel)==null||n.close(),delete this.defaultChannel)}},$p=Jr;var Bt=class extends Error{constructor(o,n){super(o);this.body=n}name="CustomError"};var Yr=t=>new Promise(e=>{setTimeout(e,t)});var Ft=class extends Bt{name="ClientError"},ei=class extends Bt{name="ServerError"},ve=class t{constructor(e="",o={}){this.baseUrl=e;this.options=o;o.fetch&&(this.fetch=o.fetch)}latestRequestByUrl={};csrfToken;fetch=window.fetch.bind(window);static refreshingToken=null;patchFetch(e){this.fetch=e(this.fetch)}setCsrfToken(e){this.csrfToken=e}request(e,o={}){return new Promise((n,s)=>{let r={isAborted:!1,reject:s},i=`${this.baseUrl}${e}`,a=this.fetch,{abortLatest:l=!1,attempts:c=1,retryDelay:p=500,refreshTokenOn401:d=!0,retryOnError:g=b=>b instanceof TypeError,retryOnResponse:u=b=>b.status>=500,version:m="v1",...f}=o,h={credentials:"include",...f,headers:{"Content-Type":"application/json",...f.headers}};o.method!==void 0&&o.method!=="GET"&&this.csrfToken&&(h.headers={...h.headers,"X-CSRFToken":this.csrfToken}),typeof m=="string"&&(h.headers={...h.headers,"X-Deepdesk-API-Version":m});let E=c,S=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[i]&&l&&(this.latestRequestByUrl[i].isAborted=!0,this.latestRequestByUrl[i].reject(new Error("Aborted"))),this.latestRequestByUrl[i]=r;let x=async()=>(E--,a(i,h).then(async b=>u(b)&&!r.isAborted&&E>0?(await Yr(p),x()):b.status===401&&d===!0&&S===!1?(S=!0,await this.refreshToken(),x()):b).catch(async b=>{if(g(b)&&!r.isAborted&&E>0)return await Yr(p),x();throw b}));x().then(b=>b.json().catch(()=>null).then(v=>{b.status>=500?s(new ei("Server Error",v)):b.status===401?s(new Ft("Unauthorized",v)):b.status===403?s(new Ft("Forbidden",v)):b.status===404?s(new Ft("Not Found",v)):b.status>=400&&s(new Ft("Bad Request",v)),delete this.latestRequestByUrl[i],n(v)})).catch(b=>{s(b)})})}async validateToken(){let{has_valid_access_token:e}=await this.get("/auth/validate");if(!e)return!1;let{is_logged_in:o}=await this.get("/apis/admin/session/validate/",{version:null});return!!o}refreshToken(){return t.refreshingToken||(t.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{t.refreshingToken=null},1e3*60)})),t.refreshingToken}get(e,o){return this.request(e,o)}post(e,o,n){return this.request(e,{method:"POST",body:JSON.stringify(o),...n})}patch(e,o,n){return this.request(e,{method:"PATCH",body:JSON.stringify(o),...n})}put(e,o,n){return this.request(e,{method:"PUT",body:JSON.stringify(o),...n})}delete(e,o){return this.request(e,{method:"DELETE",...o})}};var Rv;(e=>{let t;(l=>(l.SEND_MESSAGE="Send Message",l.HANDLING_TIME="Handling Time",l.START_AUTOFLOW="Start Autoflow",l.ABORT_AUTOFLOW="Abort Autoflow",l.ADD_TO_PERSONAL_COLLECTION="Add to personal collection",l.DELETE_FROM_PERSONAL_COLLECTION="Delete from personal collection"))(t=e.EventType||={})})(Rv||={});function ss(t){return{...L(t),tags:t.tags}}var ze=class t{constructor(e,o={}){this.options=o;this.client=new ve(e,{fetch:o.fetch}),this.client.patchFetch(n=>async(s,r)=>{let i=await n(s,r);return this.handleDeepdeskVersionHeaders(i),i})}latestReceivedDeepdeskVersions={};client;shouldFetchCsrfToken=!0;static exchangeTokenPromise=null;async preflight(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let e=await this.getCsrfToken();this.client.setCsrfToken(e)}return this.options.token?(t.exchangeTokenPromise||(t.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),t.exchangeTokenPromise):Promise.resolve()}async createConversation(e){await this.preflight(),w.info(`Creating conversation for session ${e.sessionId} and agent ${e.agentId}`);let o=await this.client.post("/api/conversations",{...U(e),tags:e.tags},{version:"v2"});return ss(o)}async getProfile(e){let o=await this.client.get(`/apis/admin/profiles/${e}/`,{version:null});return L(o)}async getKnowledgeAssistant(e){let o=await this.client.get(`/apis/admin/knowledge-assist/assistants/${e}/`,{version:null});return L(o)}async getContentTypes(){let e=await this.client.get("/apis/admin/content-types/",{version:null});return L(e)}async getPlatformConfig(){let{config:e}=await this.client.get("/platform/config/",{version:null});return L(e)}async checkUserExists(e){let{exists:o}=await this.client.get(`/apis/admin/users/exists?external_id=${e}`);return o}async getConversationBySessionId(e,o={}){await this.preflight(),w.info(`Getting conversation for session ${e}`);let{attempts:n=1,retryDelay:s=1e3}=o,r=await this.client.get(`/api/conversations/by_session_id/${e}`,{attempts:n,retryDelay:s,retryOnResponse:i=>i.status===404||i.status>=500,version:"v2"});return ss(r)}async isConversationSupported(e,o={}){w.info(`Check if conversation for session ${e} is supported`);let{attempts:n=1,retryDelay:s=1e3}=o;return(await this.client.get(`/api/conversations/by_session_id/${e}/active_profile`,{attempts:n,retryDelay:s,retryOnResponse:i=>i.status===404||i.status>=500,version:"v2"})).has_active_profile}async updateConversation(e,o){let n=U(o);o.tags&&(n.tags=o.tags);let s=await this.client.put(`/api/conversations/${e}`,n,{version:"v2"});return ss(s)}async postMessages(e,o){return(await this.client.post(`/api/conversations/${e}/messages`,o.map(s=>({...U(s),tags:s.tags})),{version:"v2"})).map(s=>ss(s))}async sendEvent(e,o){let{data:n,...s}=o,r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((i,[a,l])=>({...i,[a]:l}),{});return this.client.post("/api/events",U({...r,...s,data:n,name:e}),{version:"v2"})}async sendEventV1(e,o){let n=Object.entries(this.latestReceivedDeepdeskVersions).reduce((s,[r,i])=>({...s,[r]:i}),{});return this.client.post("/api/events",{event:e,data:U({...o,...n})})}async getEntities(e){return(await this.client.post("/api/entities",{messages:e.filter(n=>n.text)})).entities}async getSummary(e,o={}){return(await this.client.post("/api/summary",{conversation:{messages:e.filter(s=>s.text&&s.source),agent_id:o.agentId,id:o.externalConversationId},prompt_instruction:o.promptInstruction,model:o.model})).summary}async getTemporaryExchangeToken(){return(await this.client.get("/auth/exchange-token",{version:null})).jwt}async exchangeTokenForAccessCookie(e){return this.client.post("/apis/admin/session/jwt/",{jwt:e},{version:null}).catch(o=>{throw w.warn(`Invalid token '${e}'`),o})}async authenticateWithKey(e,o){await this.client.post("/apis/admin/session/api-key/",U(o),{version:null,refreshTokenOn401:!1,headers:{apikey:e}})}async getTextSuggestions(e,o={},n){return n==="sticky-messages"?this.getPinnedMessages(e):(await this.client.post(`/api/conversations/${e}/recommend/${n}`,U(o),{abortLatest:!0})).map(r=>({...L(r),text:r.text||r.url||r.message,source:n,type:n})).filter((r,i,a)=>i===a.findIndex(l=>l.text===r.text))}async isLoggedIn(){return await this.preflight(),this.client.validateToken()}async getAutocompleteSuggestions(e,o){return(await this.client.post(`/api/conversations/${e}/autocomplete`,U(o),{abortLatest:!0})).map(s=>({score:1,source:s.source,sourceText:s.source_text,text:s.label,trainingJobs:s.training_jobs,searchKeywords:s.search_keywords,type:s.source})).filter((s,r,i)=>r===i.findIndex(a=>a.text===s.text))}async getPinnedMessages(e){let o=await this.client.get(`/api/conversations/${e}/sticky-messages`,{abortLatest:!0});return L(o).map(n=>({...n,text:n.message,source:"sticky-messages",type:"pinned-message"}))}async getStyleSuggestions(e){let o=await this.client.post("/api/style-suggestions",U(e),{abortLatest:!0});return L(o)}async search(e){let o=await this.client.post(`/api/profiles/${e.profile}/search`,U(e),{version:"v2"});return L(o)}async knowledgeAssist(e,o,n){let s=await this.client.post(`/api/knowledge-assist/assistants/${n}/search`,U({question:e.question,promptInstruction:e.promptInstruction,chatHistory:o.map(r=>({question:r.question,answer:r.answer.answer}))}),{version:"v2"});return L(s)}async requestLoginByEmail(e){let o=await this.client.post("/apis/admin/session/passwordless/request/",{email:e},{version:null});return L(o)}async requestPasswordlessToken(){let e=await this.client.get("/apis/admin/session/passwordless/request/",{version:null});return L(e.token)}async getCsrfToken(){let{token:e}=await this.client.get("/apis/admin/session/csrf/",{version:null});return e}async verifyLoginToken(e){let o=await this.client.post("/apis/admin/session/passwordless/login/",{token:e},{version:null});return L(o)}handleDeepdeskVersionHeaders(e){e.headers.forEach((o,n)=>{let s=n.toLowerCase(),r=s.match(fi);if(!o||!r)return;let i=r[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&o&&a!==o&&w.warn(`Overwritten Version header ${s}: ${JSON.stringify(a)} -> ${JSON.stringify(o)}`),this.latestReceivedDeepdeskVersions[i]=o})}};var Co=class{constructor(e,o){this.url=e;this.options={timeout:25e3,...o}}eventListeners={};options;timeoutTimer;eventSource;proxyEvent(e){this.eventSource.addEventListener(er(e),o=>{let{data:n}=o;try{let s=JSON.parse(n);this.emit(e,L(s))}catch{w.warn(`Invalid JSON for ${e}: ${n}`)}})}connect(){clearTimeout(this.timeoutTimer);let e=new EventSource(this.url,{withCredentials:!0});this.eventSource=e;let o=!1;e.onopen=()=>{o=!0},e.onerror=()=>{o&&e.readyState===2&&this.connect()},this.timeoutTimer=setTimeout(()=>{e.close(),this.connect()},this.options.timeout),Object.keys(this.eventListeners).forEach(n=>{this.proxyEvent(n)})}disconnect(){var e;clearTimeout(this.timeoutTimer),this.eventListeners={},(e=this.eventSource)==null||e.close()}emit(e,o){this.eventListeners[e]&&this.eventListeners[e].forEach(n=>n(o))}on(e,o){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(o),this.proxyEvent(e),()=>{this.off(e,o)}}off(e,o){let n;this.eventListeners[e]&&(n=this.eventListeners[e].indexOf(o),n>-1&&this.eventListeners[e].splice(n,1))}};var Pv;(e=>{let t;(r=>(r.Started="Started",r.Aborted="Aborted",r.Completed="Completed"))(t=e.AutoflowSessionState||={})})(Pv||={});var wo=class{constructor(e,o={}){this.apiUrl=e;this.client=new ve(e,o)}client;streams={};logger=w;async getCustomMessages(e){let o=await this.client.get(`/sessions/${e}/suggestions`);return L(o.suggestions)}async sendCustomMessage(e,o){let n=await this.client.post(`/sessions/${e}/messages`,U(o));return L(n)}async answerCustomMessage(e,o){await this.client.post(`/sessions/${e}/answers`,U(o))}async getAutoflows(e){let o=await this.client.get(`/sessions/${e}/autoflows`);return L(o.autoflows)}async startAutoflowSession(e){let o=await this.client.post("/autoflow-sessions",U(e));return L(o)}async stopAutoflowSession(e){await this.client.delete(`/autoflow-sessions/${e}`)}openStream(e){return this.streams[e]||(this.streams[e]=new Co(`${this.apiUrl}/sessions/${e}/events`),this.streams[e].connect()),this.streams[e]}closeStream(e){this.streams[e]||(this.streams[e].disconnect(),delete this.streams[e])}};import{combineReducers as Hv,configureStore as Bv}from"@reduxjs/toolkit";import{createSlice as Av}from"@reduxjs/toolkit";var Xp={startTime:null,stopTime:null},Zp=Av({name:"handlingTime",initialState:Xp,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(M,()=>Xp)}}),{handlingTimeStart:Qp,handlingTimeStop:rs,handlingTimeReset:Jp}=Zp.actions,Yp=Zp.reducer;var ed=(t={})=>{let e={onAuthError:kt(!1),...t};return o=>n=>s=>("error"in s&&s.error.message==="Unauthorized"&&o.dispatch(e.onAuthError),n(s))};import{createAsyncThunk as Lv,createSlice as Mv}from"@reduxjs/toolkit";var is={list:{keywordMatches:[]},fetchState:"idle",isInitialRequest:null};var it=Lv("styleSuggestions/getAll",async({text:t},e)=>{var i;let{deepdeskAPI:o}=e.extra,n=e.getState(),{showStyleSuggestions:s}=n.settings,r=(i=n.conversation.current)==null?void 0:i.profileCode;if(!s)return is.list;if(!r)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:r,message:t})}),Nv=Mv({name:"styleSuggestions",initialState:is,reducers:{},extraReducers:t=>{t.addCase(it.pending,e=>{e.isInitialRequest=e.isInitialRequest===null,e.fetchState="loading"}).addCase(it.rejected,e=>{e.fetchState="error"}).addCase(it.fulfilled,(e,o)=>{e.fetchState="done",Ae(e.list,o.payload)||(e.list=o.payload)}).addCase(Ge,e=>{e.list=is.list}).addCase(M,()=>is)}}),td=Nv.reducer;var od=(t={})=>{let e,o=!0,n={getStyleSuggestions:it,debounce:500,...t};return s=>r=>i=>{var u;let a=s.getState().input.text,l=r(i),c=s.getState();if(c.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:p}=c.settings;if(!((u=c.conversation.current)==null?void 0:u.id)||!p)return l;let{text:g}=c.input;return g===a&&!o||(clearTimeout(e),g==="")||(e=setTimeout(()=>{o=!1,s.dispatch(n.getStyleSuggestions({text:g}))},t.debounce)),l}};function Ov(t,e){return t.text===e.text&&t.selection.start===e.selection.start&&t.selection.end===e.selection.end}var nd=(t={})=>{let e={getTextSuggestions:ce,getAutocompleteSuggestions:no,debounce:200,check:Mt,...t},o;return n=>s=>r=>{var f;let{input:{userCommitted:i}}=n.getState(),a=s(r),l=n.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:c,showTabCompletion:p}=l.settings,d=(f=l.conversation.current)==null?void 0:f.id,g=r.type===wn.toString();if(!d||!c&&!p)return a;let{input:{userCommitted:u}}=l;return Ov(u,i)&&!g||(clearTimeout(o),!e.check(l))||(o=setTimeout(()=>{let h=ht(l);h===""?n.dispatch(e.getTextSuggestions("default")):n.dispatch(e.getAutocompleteSuggestions(h))},g?0:e.debounce)),a}};var sd=it.fulfilled.toString();function Dv(t,e){let o=new Set([...e.keywordMatches.map(s=>s.keyword)]),n=[];return o.forEach(s=>{let r=t.keywordMatches.filter(l=>l.keyword===s),i=e.keywordMatches.filter(l=>l.keyword===s),a=i.length-r.length;a<=0||n.push(...i.slice(0,a))}),n}var rd=t=>e=>o=>n=>{var c;if(n.type!==sd){o(n);return}let s=e.getState().styleSuggestions.list;o(n);let r=e.getState(),i=r.styleSuggestions.list,a=(c=r.conversation)==null?void 0:c.current;if(s===i)return;let l=Dv(s,i);n.type===sd&&l.length>0&&t.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var Fv=Hv({activeSuggestion:ul,answer:tc,auth:Tl,autoflows:rp,conversation:xi,contentTypes:Dl,customMessages:mp,passwordlessToken:Sp,entities:Fl,knowledgeAssistant:Jl,handlingTime:Yp,info:Ha,input:ws.reducer,overlayInput:Q.reducer,settings:yi,profile:ic,search:za,summary:Wl,styleSuggestions:td,ui:hl,textSuggestions:al});function id(t){return Bv({reducer:Fv,middleware:e=>[...e({thunk:{extraArgument:{dynamicThunkObject:t.dynamicThunkObject,deepdeskAPI:t.deepdeskAPI,deepdeskBrokerAPI:t.deepdeskBrokerAPI}},serializableCheck:!1}),ed(),nd({debounce:200}),od({debounce:500}),rd(t.deepdeskAPI),...t.middleware?t.middleware:[]],preloadedState:t.preloadedState})}var Kv=t=>{var e;return((e=t==null?void 0:t.type)==null?void 0:e.toLowerCase())??"unknown"},Uv=t=>e=>o=>n=>{var a;let s=e.getState(),r=_s("inlineSuggestions")(s);switch(n.type){case Ce.toString():{let l=Cn(n.payload.contentType)(e.getState()),c=l.indexOf(n.payload.suggestion);t.emit("edit-suggestion",{contentType:n.payload.contentType,index:c,suggestions:l});break}case kt.toString():{!n.payload&&t.emit("logout",void 0);break}case ie.toString():{let{start:l,end:c}=s.input.selection;t.emit("select-suggestion",{type:Kv(n.payload.suggestion),...n.payload,replace:n.payload.replace==="selection"?{start:l,end:c}:{start:0,end:c}},{mayApplyChanges:!0});break}case jo.toString():{let{start:l,end:c}=s.input.selection;t.emit("replace",{...n.payload,replace:n.payload.replace==="selection"?{start:l,end:c}:{start:0,end:c}},{mayApplyChanges:!0});break}case Wt.toString():{let l=e.getState(),{text:c,selection:p}=l.input.userCommitted;t.emit("reset",{text:c,selectionAfter:p},{mayApplyChanges:!0});break}case Wo.toString():t.emit("select-image",n.payload,{mayApplyChanges:!0}),t.sendEvent("Image attached",{conversationId:s.conversation.current.id,data:{path:n.payload.suggestion.image,title:n.payload.suggestion.title}});break;case pe.fulfilled.toString():n.payload.length>0&&t.sendEvent("entities found",{conversationId:s.conversation.current.id,data:{entities:n.payload}});break;case Ee.fulfilled.toString():t.sendEvent("conversation summarized",{conversationId:s.conversation.current.id,data:{summary:n.payload.summary}});break;case W.toString():t.sendEvent(n.payload.name,{conversationId:((a=n.payload.options)==null?void 0:a.includeConversationData)&&s.conversation.current.id,data:n.payload.data});break;case zo.toString():t.handleKeyDown(n.payload);break;case Ge.toString():t.logSendMessage(n.payload);break;case Vo.toString():t.logSendEditSuggestionMessage(n.payload);break;case qo.toString():t.handleInputChanged(n.payload);break;default:break}let i=o(n);switch(n.type){case Ge.toString():t.handleAfterSendMessage(n.payload);break;case so.toString():t.onUpdateShowTabHint(n.payload);break;case rs.toString():t.logHandlingTime();break;case ie.toString():{r&&(e.dispatch(ge([])),e.dispatch(_e()));break}case ge.toString():{r&&n.payload.length>0&&e.dispatch(Me(0));break}default:break}return i},ad=Uv;function ti(t){return t.toISOString().replace("T"," ").replace("Z","")}function ld(t,e){var s,r,i;let{startTime:o,stopTime:n}=t.handlingTime;if(!o||!n)throw new Error("No startTime and stopTime for handling time metrics");return{conversationId:t.conversation.current.id,clientVersion:e.version,agentId:(s=t.info.agentInfo)==null?void 0:s.agentId,agentName:(r=t.info.agentInfo)==null?void 0:r.agentName,agentEmail:(i=t.info.agentInfo)==null?void 0:i.agentEmail,timeStart:ti(o),timeStop:ti(n)}}function oi(t,e,o){var A,H,P;let{text:n,metrics:{numCharsTyped:s,numCharsPasted:r,numCharsCut:i,numCharsDeleted:a,numPaste:l,agentStartedTypingTimestamp:c,externalTimeTotalSeconds:p,pastes:d,cuts:g,deletions:u,textSuggestions:m,offeredTextSuggestions:f}}=e[t],h=n.length,S=m.reduce((V,{text:k,searchTerm:F})=>V+k.length-(F?F.length:0),0),x=c??Date.now(),b=(Date.now()-x)/1e3+(p||0),v=s/b,R=m.reduce((V,{searchTerm:k})=>V+(k?k.length:0),0);return{conversationId:e.conversation.current.id,source:"agent",text:n,clientVersion:o.version,pastes:d,cuts:g,deletions:u,lenTextTyped:s+R,lenTextTotal:h,lenTextAssisted:S,lenTextPasted:r,lenTextCut:i,lenTextDeleted:a,timeTotalSeconds:b,charsPerSecond:v,numPastes:l,textSuggestionsV2:m,suggestionsCounters:[{source:"gpt",countOffered:f.filter(V=>V.source==="gpt").length}],agentId:(A=e.info.agentInfo)==null?void 0:A.agentId,agentName:(H=e.info.agentInfo)==null?void 0:H.agentName,agentEmail:(P=e.info.agentInfo)==null?void 0:P.agentEmail}}function ni(t,e){var r;let o=t.closest(e);if(o)return o;let n=t.getRootNode().host;if(n instanceof HTMLElement)return ni(n,e);let s=(r=t.ownerDocument.defaultView)==null?void 0:r.frameElement;return s?ni(s,e):null}function cd(t,e){return ni(t,e)}function pd(t){return typeof t=="object"&&t!==null&&"name"in t&&"message"in t}function jv(t){return typeof t=="object"&&t!==null&&"tagName"in t}function si(t){return jv(t)&&(Ue(t)||cn(t))}var dd=(t,e)=>({value(){try{let o=sessionStorage.getItem(`dd-${t}`);if(!o)return e;try{return JSON.parse(o)}catch{return e}}catch{return e}},update(o){try{sessionStorage.setItem(`dd-${t}`,JSON.stringify(o))}catch{w.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function zv(t){return t.offsetParent!==null}function ud(t){if(!zv(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 ri(t,e,o=100){let n=ud(t);e({isVisible:n});let s=setInterval(()=>{let r=ud(t);r!==n&&(n=r,e({isVisible:n}))},o);return()=>{clearTimeout(s)}}import{jsx as j}from"react/jsx-runtime";var gd=dd("showTabHint",!0),ls=class t{static version="10.10.3";static count=0;deepdeskApi;inputMediator=null;version;broadcastEvents;eventListeners={};unmountHandlers=[];widgetRoot=null;dynamicThunkObject={};isMounted=!1;instanceId;shouldRender=!0;store;constructor({deepdeskUrl:e,brokerUrl:o,version:n=t.version||"unknown",locale:s="en-US",token:r,fetch:i,productName:a,createCustomChannel:l}){let c=e.replace(/\/api$/,"");this.deepdeskApi=new ze(c,{token:r,fetch:i}),this.version=n,this.instanceId=t.count++;let p={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[ad({emit:(d,g,u)=>this.emit(d,g,u),handleAfterSendMessage:d=>this.handleAfterSendMessage(d),handleInputChanged:d=>this.handleInputChanged(d),handleKeyDown:d=>this.handleKeyDown(d),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:d=>this.logSendMessage(d),logSendEditSuggestionMessage:d=>this.logSendEditMessage(d),onUpdateShowTabHint:d=>gd.update(d),sendEvent:(d,g)=>this.deepdeskApi.sendEvent(d,g)})]};o&&Object.assign(p,{deepdeskBrokerAPI:new wo(o)}),this.store=id(p),this.broadcastEvents=new $p({debug:!0,deepdeskUrl:c,eventMap:El(this.store),createCustomChannel:l}),this.store.dispatch(qt),this.store.dispatch(so(gd.value())),this.store.dispatch(qt({locale:s,adminUrl:c,productName:a}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){return this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex]??null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(w.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(w.warn("Profile has not been loaded (yet)"),!0):(w.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(kt(null)),this.store.dispatch(we()),new Promise(e=>{let o=this.store.subscribe(()=>{let n=this.store.getState();Z(n)&&Sl(n)!=="loading"&&(o(),e())});this.unmountHandlers.push(()=>{o()})})}async isLoggedIn(){return(await this.store.dispatch(we())).payload}async setPlatformAgentId(e){try{if((await this.deepdeskApi.client.get("/apis/admin/session/me/",{version:null})).external_id)return;await this.deepdeskApi.client.request("/apis/admin/session/me/",{method:"PATCH",body:JSON.stringify({external_id:e}),version:null})}catch(o){w.warn("Failed to attach user:",o)}}async isConversationSupported(e,o){return(await this.store.dispatch(bs({sessionId:e,options:o}))).payload}async createConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(Do(e))).payload}async getConversationBySessionId(e,o){return this.hasConversation()&&this.sessionId()!==e&&this.resetConversation(),(await this.store.dispatch(Ho({sessionId:e,options:o}))).payload}async upsertConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(Cs(e))).payload}async postMessages(e){return(await this.store.dispatch(Fo(e))).payload}async updateConversation(e){return(await this.store.dispatch(Bo(e))).payload}resetConversation(){this.store.dispatch(M()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}async getSummary(){let e=await this.store.dispatch(Ee());if(e.error)throw new Error(e.error.message);return e.payload.summary}configure(e){this.store.dispatch(qt(e))}setVisitorInfo(e){this.store.dispatch(Da(e))}async setAgentInfo(e){await this.store.dispatch(eo(e))}async setAgentSettings(e){await this.store.dispatch(or(e))}async getAgentSettings(){return(await this.store.dispatch(nr())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let e=[];return this.store.dispatch(wn()),e.push(this.refreshWidgetSuggestions()),Promise.all(e).then(()=>{})}notifyInputChanged(e){this.store.dispatch(qo(e))}notifyKeyDown(e){this.store.dispatch(zo(e))}notifyPaste(e,o){this.store.dispatch(Li({text:e,selectionText:o}))}notifyCut(e){this.store.dispatch(Pi(e))}notifyExternalSuggestion(e){this.store.dispatch(ie(e)),this.store.dispatch(_e())}notifyEditSuggestion(e){this.store.dispatch(rl(e.contentType,e.suggestions)),this.store.dispatch(Ce({contentType:e.contentType,suggestion:typeof e.index=="number"?e.suggestions[e.index]:null}))}handleInputChanged(e){let{overlayCollapsed:o,openOverlayWhenTyping:n}=this.state.ui;o&&n&&this.store.dispatch(Fe({collapse:!1})),this.inputMediator&&this.store.dispatch(wi({text:e,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(ge([])))}handleKeyDown(e){let{overlayCollapsed:o}=this.state.ui,{textSuggestions:n,selectedSuggestionIndex:s,selection:r}=this.state.input,{inlineSuggestions:i}=this.state.settings,a=n.length>0,l=s!==-1;if(this.store.dispatch(Ai(Uo(e))),e.key!=="Tab"&&!this.settings.showTextSuggestions)return;let c=()=>{o||!a||r&&(e.shiftKey||(this.store.dispatch(ki()),i||this.stageSelectedSuggestion({inputType:"arrow"}),e.preventDefault()))},p=()=>{o||!a||i&&s<=0||r&&(e.shiftKey||(this.store.dispatch(Ri()),e.preventDefault(),!i&&(this.state.input.selectedSuggestionIndex===-1?this.store.dispatch(Wt()):this.stageSelectedSuggestion({inputType:"arrow"}))))};switch(e.key){case"Up":case"ArrowUp":i?p():c();return;case"Down":case"ArrowDown":{i?c():p();return}case"Esc":case"Escape":{i&&l&&this.store.dispatch(Me(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(Me(-1)),this.store.dispatch(Wt()),e.preventDefault()):o||(this.store.dispatch(Fe({collapse:!0})),this.store.dispatch(ml(!0)),e.preventDefault());return}case"Tab":{let{userCommitted:d}=this.state.input,g=d.text.substring(0,d.selection.end),{tabCompletionSuggestion:u}=this.state.input;this.store.dispatch(so(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!i&&this.settings.showTabCompletion&&u&&u.text.startsWith(g)&&(this.store.dispatch(ie({text:u.text,suggestion:u,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch(_e())),e.preventDefault();break}default:}}handleAfterSendMessage(e){this.emit("send-message",e),this.store.dispatch(Mi()),this.store.dispatch(ge([]))}handlingTimeStart(){this.state.handlingTime.startTime||(w.info("Start handling time"),this.store.dispatch(Qp()))}handlingTimeStop(){this.state.handlingTime.startTime&&(w.info("Stop handling time"),this.store.dispatch(rs()))}logSendMessage(e){let o=oi("input",this.state,{version:this.version});e&&(Object.assign(o,{text:e}),Object.assign(o,{lenTextTotal:e.length})),this.deepdeskApi.sendEventV1("Send Message",o),this.emit("send-message-event",o)}logSendEditMessage(e){let o=oi("overlayInput",this.state,{version:this.version});e&&Object.assign(o,{text:e}),this.store.dispatch(Ei(this.state.overlayInput.metrics))}logHandlingTime(){let e=ld(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",e),this.store.dispatch(Jp())}notifySubmit(e={}){this.shouldAbort()||(this.store.dispatch(_e()),this.store.dispatch(Ge(e.text??this.state.input.text)))}stageSelectedSuggestion(e){let o=this.state.input.selectedSuggestionIndex,{textSuggestions:n}=this.state.input;this.store.dispatch(ie({text:n[o].text,suggestion:n[o],eventMetrics:e,replace:"until-selection-end"}))}emit(e,o,n={}){let s=()=>{this.eventListeners[e]&&this.eventListeners[e].forEach(r=>{try{r(o)}catch(i){w.warn(`The following error occurred in deepdeskSDK.on('${e}', handler)`),w.error(i)}})};this.inputMediator&&n.mayApplyChanges?this.inputMediator.applyChanges(s):s()}on(e,o){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(o),()=>{this.off(e,o)}}off(e,o){if(!e&&!o){this.eventListeners={};return}let n;this.eventListeners[e]&&(n=this.eventListeners[e].indexOf(o),n>-1&&this.eventListeners[e].splice(n,1))}setConversationQuery(e){this.dynamicThunkObject.conversationQuery=e}whenConversationLoaded(e){let o=()=>this.loadProfileConfig().then(()=>e());this.hasConversation()&&o();let n=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==n&&(n=this.hasConversation(),n&&o())})}overlayContainerFactory(e,o,n,s){let[r,i]=xt(o,n);return r.setAttribute("translate","no"),r.dataset.testid=e,s&&r.classList.add(s),this.unmountHandlers.push(()=>{as(r),i(),r.remove()}),r}createInlineContainer(e,o){var i;let n=document.createElement("div");n.style.position="absolute",n.style.top="0px",n.style.left="0px",n.style.height="0px",n.style.width="0px";let s=document.createElement("div");s.style.display="none",s.style.position="absolute",s.style.height="0px",s.style.width="0px",s.style.backgroundColor="red",n.appendChild(s);let r=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;if(r){let[a,l]=xt(r,{appendTo:document.body,onMoveStart:()=>{s.style.display="none"}});a.dataset.testid=o,a.style.zIndex="2",a.appendChild(n),this.unmountHandlers.push(()=>{as(s),l()})}else document.body.appendChild(n);return s}createContainer(e,o=document.body){let n=window.getComputedStyle(o),s=document.createElement("div");return Xe(s),s.dataset.testid=e,s.style.color=n.color,s.style.fontSize=n.fontSize,s.style.fontFamily=n.fontFamily,s.style.fontVariant=n.fontVariant,s.setAttribute("translate","no"),o.appendChild(s),this.unmountHandlers.push(()=>{as(s),s.remove()}),s}storeMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,o=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(e,o),w.info(`Stored analytics for ${this.conversationId()}`)}catch{}}restoreMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,o=window.sessionStorage.getItem(e);if(!o)return;let n=JSON.parse(o);n.text.trim()===this.state.input.text.trim()?(w.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(Oi(n.metrics))):w.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(e)}catch{}}mount(e,o={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!si(e))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let{customStyles:n={},showStyleSuggestions:s,showTabCompletion:r,showTextSuggestions:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:c,showSuggestionsAfterPattern:p,isEmbedded:d,detectSubmit:g,insertLink:u,inputMediator:m,closestScrollSelector:f,appendOverlayTo:h,inlineSuggestions:E,floatingMenu:S}=o;this.configure({showStyleSuggestions:s,showTabCompletion:r,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:c,showSuggestionsAfterPattern:p,showTextSuggestions:i,insertLink:u,isEmbedded:d,inlineSuggestions:E,floatingMenu:!!S}),o.automaticHandlingTime&&this.setupHandlingTime(e),Xe(e),this.inputMediator=m||(Ue(e)?new Oe(e):new Ht(e)),this.inputMediator.on("change",({plainText:v})=>{this.notifyInputChanged(v)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(Ni({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",v=>{this.notifyKeyDown(v)}),this.inputMediator.on("paste",({pastedText:v,selectionText:R})=>{this.notifyPaste(v,R)}),this.inputMediator.on("cut",({selectionText:v})=>{this.notifyCut(v)});let x=f&&cd(e,f)||void 0;if(E){let{customStyles:v,appendOverlayTo:R}=o;if(Ue(e))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let A=this.createInlineContainer(e,"deepdesk-caret");Kt(j(tt,{store:this.store,customStyles:v,children:j(et,{broadcastEvents:this.broadcastEvents,children:j(Cc,{})})}),A),this.inputMediator.on("caret",P=>{this.store.dispatch(ge([])),P?(A.style.display="block",A.style.top=`${P.top}px`,A.style.left=`${P.left}px`):A.style.display="none"});let H=this.overlayContainerFactory("floating-menu",x||e,{appendTo:typeof S=="object"&&"appendOverlayTo"in S?S.appendOverlayTo:R},v==null?void 0:v.floatingMenuRootNode);Kt(j(tt,{store:this.store,customStyles:v,children:j(et,{broadcastEvents:this.broadcastEvents,children:j(yc,{onLogIn:()=>this.loginViaPopup().catch(P=>w.warn(P.message))})})}),H)}else{let v=this.overlayContainerFactory("deepdesk-tab-completion",x||e,{appendTo:h,closestScrollElement:x,mirrorOverflow:!0,onRemove:()=>this.unmount()},n==null?void 0:n.rootNode),R=this.overlayContainerFactory("deepdesk-suggestions-overlay",x||e,{appendTo:h},n==null?void 0:n.suggestionsRootNode);Kt(j(tt,{store:this.store,customStyles:n,children:j(et,{broadcastEvents:this.broadcastEvents,children:j(Yc,{inputElement:e})})}),v),Kt(j(tt,{store:this.store,customStyles:n,children:j(et,{broadcastEvents:this.broadcastEvents,children:j(Lc,{onLogIn:()=>this.loginViaPopup().catch(A=>w.warn(A.message))})})}),R)}Kt(j(tt,{store:this.store,customStyles:n,children:j(et,{broadcastEvents:this.broadcastEvents,children:j(dc,{})})}),this.createContainer("deepdesk-overlays"));let b;this.inputMediator.on("selection",v=>{clearTimeout(b),v===null?b=setTimeout(()=>{v!==null&&this.store.dispatch(Ts(v))},500):this.store.dispatch(Ts(v))}),this.inputMediator.on("disabled",()=>{var v;(v=this.inputMediator)==null||v.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{g&&this.notifySubmit()}),this.inputMediator.on("blur",()=>this.store.dispatch(Et(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(Et(!0))),this.store.dispatch(Ti({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.unmountHandlers.push(()=>{this.state.input.text!==""&&(this.store.dispatch(_e()),this.storeMetrics())}),this.whenConversationLoaded(()=>{var v;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((v=this.state.conversation.current)==null?void 0:v.sessionId)}),this.isMounted=!0}unmount(){var e;this.unmountHandlers.forEach(o=>o()),this.unmountHandlers=[],(e=this.inputMediator)==null||e.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(e,o={}){if(this.widgetRoot&&w.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:n,showImages:s,isEmbedded:r}=o;this.widgetRoot=e,this.configure({showImages:s,isEmbedded:r}),Kt(j(tt,{store:this.store,customStyles:n,children:j(et,{broadcastEvents:this.broadcastEvents,children:j(Vp,{onLogIn:()=>this.loginViaPopup().catch(i=>w.warn(i.message))})})}),e),this.whenConversationLoaded(()=>{var i;this.broadcastEvents.setSessionId((i=this.state.conversation.current)==null?void 0:i.sessionId)})}unmountWidget(){this.widgetRoot&&as(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(e){let o=ri(e,({isVisible:n})=>{n?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),o()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){pd(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(go());let e=Ke(this.state);e&&(await this.store.dispatch(uo()),this.store.dispatch(qt({showSearch:e.search,showAutoflows:e.autoflows,showCustomMessages:e.customMessages,showImageSearch:e.imageSearch,showEntitiesCommand:e.entitiesCommand,showSummaryCommand:e.summarizer,showKnowledgeSearch:!!e.knowledgeAssistant,recommendTextSuggestions:e.recommendTextSuggestions})))}),this.loadProfileConfigPromise)}async loginViaPopup(e){return new Promise((o,n)=>{let s=new MessageChannel,r=s.port1,i=this.state.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 l=!1,c=()=>{p&&!p.closed&&p.close(),window.removeEventListener("message",d),clearInterval(g)};r.onmessage=async u=>{var m,f;if((m=u.data)!=null&&m.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((f=u.data)==null?void 0:f.jwt),await this.isLoggedIn(),this.broadcastEvents.send(io),l=!0,s.port1.close(),o()}catch(h){console.error(h),n(h)}finally{l=!0,c()}};let p=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");p===null&&n(new Error("Popup blocked by browser"));let d=async u=>{var m;if(u.origin===a.origin)switch((m=u.data)==null?void 0:m.type){case"deepdesk-popup-loaded":{try{let f=JSON.stringify({type:"deepdesk-popup-create-channel"});p==null||p.postMessage(f,a.origin,[s.port2])}catch(f){w.error("Error posting message to popup",f),n(f)}break}case"deepdesk-popup-error":{c(),u.data.message==="Timeout"&&w.warn("Popup timed out. Check if the account's platform url is configured correctly."),n(new Error(u.data.message));break}}};window.addEventListener("message",d);let g=setInterval(()=>{p&&!p.closed||(c(),l||n(new Error("Popup closed by user")))},200);this.unmountHandlers.push(c)})}async checkForTrialMode(e){try{let{account:o}=await this.deepdeskApi.getPlatformConfig();if(!o.isTrial){this.shouldRender=!0;return}if(w.info("Trial is active"),!await this.deepdeskApi.checkUserExists(e))throw new Error("User is not in trial");this.shouldRender=!0}catch(o){let{message:n}=o;w.info(n),this.shouldRender=!1}}async refreshWidgetSuggestions(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:e}=this.state.profile.data;if(!e.widget)return;let o=Pn(this.state);try{o.forEach(({type:n})=>{n==="entities"?this.store.dispatch(pe()):this.store.dispatch(ce(n))})}catch(n){this.handleError(n)}}};async function Vv(t,e,o={}){let{value:n}=t,{start:s,end:r}=o.replace??{start:0,end:n.length},i=`${n.slice(0,s)}${e}${n.slice(r)}`,a=o.selectionAfter??{start:s+e.length,end:s+e.length},l=()=>{if(o.setValue)return o.setValue(i);t.value=i};return Promise.resolve(l()).then(()=>{t.selectionStart=a.start,t.selectionEnd=a.end,t.blur(),t.focus()})}async function qv(t,e,o={}){let n=o.replace?rt(t,o.replace.start,o.replace.end):bo(t),s,r=()=>{if(o.setRange)return o.setRange(n.cloneRange());n.deleteContents(),s=document.createElement("span"),n.insertNode(s),o.insertBRs!==!1?e.split(`
10
10
  `).reverse().forEach((i,a)=>{a>0&&n.insertNode(document.createElement("br")),n.insertNode(document.createTextNode(i))}):n.insertNode(document.createTextNode(e))};return Promise.resolve(r()).then(()=>{try{if(o.selectionAfter!==!1){t.focus();let i=o.selectionAfter?rt(t,o.selectionAfter.start,o.selectionAfter.end):(n.collapse(!1),n),a=window.getSelection();a==null||a.removeAllRanges(),a==null||a.addRange(i)}if(!s)return;s.scrollIntoView&&s.scrollIntoView({block:"nearest",inline:"nearest"})}finally{s&&s.remove()}})}function Wv(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 Gv(t){let e=document.createDocumentFragment();return t.split(`
11
11
  `).forEach((o,n)=>{n>0&&e.appendChild(document.createElement("br"));let s={index:0},r=0;for(;s=o.slice(r).match(/(\[([^\]]+)])\(([^)]+)\)/);){let i=document.createElement("a");i.href=s[3],i.setAttribute("target","_blank"),i.setAttribute("rel","noopener noreferrer"),i.appendChild(document.createTextNode(s[2])),e.appendChild(document.createTextNode(o.slice(r,r+s.index))),e.appendChild(i),r=r+s.index+s[0].length}e.appendChild(document.createTextNode(o.slice(r)))}),e}function md(t,e){return!t.contains(e)||e===t?null:e.parentNode===t?e:md(t,e.parentNode)}async function $v(t,e,{isBlock:o,isHTML:n}={}){let s;t.dispatchEvent(new InputEvent("beforeinput",{inputType:"insertText",data:e,bubbles:!0,cancelable:!0}));let r=()=>{let i=t.ownerDocument.defaultView??window,a=i.getSelection();if((!a||a.rangeCount===0)&&(t.focus(),a=i.getSelection()),!a||a.rangeCount===0)return;let l=a.getRangeAt(0);if(!l)return;s=document.createElement("span"),l.insertNode(s);let c=n?Wv(e):Gv(e);if(o){let p=l.startContainer===t?t.childNodes[l.startOffset]:l.startContainer,d=md(t,p)??t.firstChild;t.insertBefore(c,(d==null?void 0:d.nextSibling)??null)}else l.insertNode(c),l.collapse(!1)};return Promise.resolve(r()).then(()=>{if(t.dispatchEvent(new InputEvent("input",{inputType:"insertText",data:e,bubbles:!0,cancelable:!0})),t.focus(),!!s)try{s.scrollIntoView&&s.scrollIntoView({block:"nearest",inline:"nearest"})}finally{s&&s.remove()}})}function Xv(t){return t.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}async function Zv(t,e,o){await new ze(t).authenticateWithKey(e,o)}async function Qv(t){let o=await new ve(t).get("/platform/config/",{version:null});return L(o)}async function Jv(t){let o=await(t.fetch??window.fetch)(t.url),n=await o.blob();return new File([n],t.name,{type:t.mimeType??o.headers.get("Content-Type")??"image/jpeg"})}async function Yv(t,e){let o=await Jv(e),n=new Event("change",{bubbles:!0,cancelable:!0});try{Object.defineProperty(t,"files",{configurable:!0,get:()=>[o]}),t.dispatchEvent(n)}finally{Object.hasOwn(t,"files")&&delete t.files}}export{B as Card,Ht as ContentEditableInput,ze as DeepdeskAPI,ls as DeepdeskSDK,ve as HTTPClient,Ne as InputMediator,qe as InputType,gs as KeyboardHint,ms as Label,Mo as Locale,Ve as Section,hs as SectionList,ue as Sources,D as Suggestion,re as SuggestionList,Oe as TextAreaInput,ut as ToggleButton,Yv as attachFile,Zv as authenticateWithKey,bo as createFullRange,xt as createOverlayContainer,rt as createRangeFromOffsets,Qt as escapeHTML,Qv as fetchPlatformConfig,Xv as formatTextMarkup,os as getRangeOffsets,ns as getRangeText,$v as insertCKEditor,bt as isHTML,si as isSupportedInputElement,qv as updateContentEditable,Vv as updateTextArea,y as useStyles,ri as waitForElementVisibilityChange};
@@ -22,7 +22,7 @@ Try polyfilling it using "@formatjs/intl-pluralrules"
22
22
  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
23
23
  c32.4,32.4,47.8,70,47.8,115.2v70h11.9c9.4,0,17.9,3.4,24.7,10.2C462.1,250,465.5,257.7,465.5,267.9z`})})});var Jg=S(b()),yL={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},N1=({className:e,color:t})=>(0,Jg.jsx)("svg",{className:e,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:(0,Jg.jsx)("path",{d:"M172.03 0.0199966H0V86.03C47.5 86.03 86 124.54 86 172.04C86 124.54 124.51 86.03 172.01 86.03C219.51 86.03 258.03 124.54 258.03 172.04C258.03 219.54 219.52 258.05 172.01 258.05C124.5 258.05 86 219.54 86 172.04C86 219.54 47.5 258.05 0 258.05V344.06H172.03C267.04 344.06 344.06 267.04 344.06 172.03C344.06 77.02 267.04 0 172.03 0V0.0199966Z",fill:yL[t||"pink"]})});var M1={root:"_root_1tvv4_1",text:"_text_1tvv4_18",isLoggedIn:"_isLoggedIn_1tvv4_25",isLoggedOut:"_isLoggedOut_1tvv4_29",icon:"_icon_1tvv4_39",logo:"_logo_1tvv4_44",lock:"_lock_1tvv4_49"};var eh={};Pe(eh,{enUS:()=>vL,nlNL:()=>SL});var vL={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},SL={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};var xo=S(b()),F1=({onLogIn:e})=>{let t=H(eh),n=M("floatingMenu"),r=M("productName"),o=U(),i=R(Ge),s=P("FloatingMenu",M1);if(i===null||n===!1)return null;let a=()=>{i===!0?o($e(!0)):e()};return(0,xo.jsxs)("button",{className:(0,D1.default)(s.root,{[s.isLoggedIn]:i,[s.isLoggedOut]:!i}),onClick:a,children:[(0,xo.jsx)("div",{className:s.text,children:t(i?"search":"signin",{productName:r})}),(0,xo.jsxs)("div",{className:s.icon,children:[(0,xo.jsx)(N1,{className:s.logo,color:"pink"}),i===!1&&(0,xo.jsx)(O1,{className:s.lock})]})]})};var dd=S(O());function ji(e){let{showMidSentenceSuggestions:t,showSuggestionsBeforePattern:n,showSuggestionsAfterPattern:r}=e.settings,{text:o,selection:i}=e.input.userCommitted;return i.start!==i.end?!1:i.end>=o.length?!0:t?n&&new RegExp(n).test(o.substring(i.end))||r&&new RegExp(r).test(o.substring(0,i.end))?!0:n===!1&&r===!1:!1}var ud=S(O());var Hi=S(O());var j1=S(O());function H1(e,t,n){(0,j1.useEffect)(()=>{let r=e.current;return r?(r.addEventListener(t,n),()=>{r.removeEventListener(t,n)}):()=>{}},[e,t,n])}var B1={root:"_root_4u430_1",actions:"_actions_4u430_8",badge:"_badge_4u430_15",formattedText:"_formattedText_4u430_19"};var _o=S(b()),_L=["search","personal-collection-search","search-autocomplete"];function wL(e,t,n,r={}){let o="";return _L.includes(t)?o=B_(kg(e,n,{stripAgentPart:!0}),r.searchKeywords??[n]):o=kg(e,n,r),r.placeholders===!0&&(o=z_(o)),o}var bL=()=>{},EL=({index:e,selected:t,suggestion:n,onFeedback:r})=>{let o=M("inlineSuggestions"),i=R(xi),s=U(),a=P("TextSuggestion",B1),l=(0,Hi.useRef)(null);(0,Hi.useEffect)(()=>{let c=setTimeout(()=>{s(e_({text:n.text,suggestion:n}))},500);return()=>{clearTimeout(c)}},[n]),H1(l,"click",()=>{s(vr(e)),s(Bt({suggestion:n,text:n.text,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"}))});let u=(0,Hi.useMemo)(()=>wL(n.text,n.source,i,{stripAgentPart:o,placeholders:!0,searchKeywords:n.searchKeywords}),[o,n.text,n.source,i,n.searchKeywords]);return n.source==="gpt"&&!o?null:(0,_o.jsxs)("div",{className:a.root,onMouseEnter:()=>s(vr(e)),children:[(0,_o.jsx)(oe,{ref:l,as:"button","data-testid":"suggestions-overlay-item",selected:t,onClick:bL,children:(0,_o.jsx)(Cn,{containerTagName:"div",noWrap:!1,tagName:"span",className:a.formattedText,content:u})}),t&&r&&(0,_o.jsx)("div",{className:a.actions,children:(0,_o.jsx)(Gc,{onFeedback:()=>r(n),suggestion:n.text})})]})},z1=EL;var th=S(b()),CL=({onFeedback:e,suggestions:t,selectedIndex:n,reverse:r})=>{let o=(0,ud.useMemo)(()=>{let i=t.map((s,a)=>(0,th.jsx)(z1,{index:a,selected:a===n,suggestion:s,onFeedback:e},`${s.text}-${s.source}`));return r?i.reverse():i},[t,n,r]);return(0,th.jsx)(ud.Fragment,{children:o})},cd=CL;var U1={root:"_root_otdbu_1",paper:"_paper_otdbu_11"};var Fa=S(b()),TL=({textSuggestions:e,selectedIndex:t})=>{let n=(0,dd.useRef)(null),r=P("InlineSuggestionsOverlay",U1),o=R(ji),i=U(),s=R(Ge),a=R(Si),l=R(od),u=M("showTextSuggestions");return Ti(()=>{i(Er({collapse:!0,skipWhenInputFocus:!0}))}),(0,dd.useEffect)(()=>{let c=n.current;if(!c||!c.parentElement)return;c.parentElement.style.left="0px";let p=c.getBoundingClientRect();c.parentElement.style.left=`${Math.min(window.innerWidth-4-p.right,0)}px`}),l||!o||!u||e.length===0||s!==!0||a===!1?null:(0,Fa.jsx)("div",{className:r.root,"data-variant":"inline",children:(0,Fa.jsx)("div",{ref:n,className:r.paper,children:(0,Fa.jsx)(xt,{children:(0,Fa.jsx)(cd,{suggestions:e,selectedIndex:t})})})})},kL=({input:e})=>({selectedIndex:e.selectedSuggestionIndex,textSuggestions:e.textSuggestions}),K1=xn(kL)(TL);var ja=S(b()),PL=({children:e})=>{let n=M("locale").replace("-","");return(0,ja.jsx)(cg.Provider,{value:n,children:e})},IL=({store:e,customStyles:t={},children:n})=>(0,ja.jsx)(Wm,{store:e,children:(0,ja.jsx)(PL,{children:(0,ja.jsx)(Xi.Provider,{value:t,children:n})})}),wo=IL;var fd=S(q()),Bi=S(O());var V1=S(O());function W1(e,t){let[n,r]=(0,V1.useState)(()=>{if(typeof window>"u")return t;try{let i=window.localStorage.getItem(e);return i?JSON.parse(i):t}catch(i){return j.error(i),t}});return[n,i=>{try{let s=i instanceof Function?i(n):i;r(s),typeof window<"u"&&window.localStorage.setItem(e,JSON.stringify(s))}catch(s){j.error(s)}}]}var q1=S(q()),Mn=S(O());var nh={};Pe(nh,{enUS:()=>RL,nlNL:()=>LL});var RL={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"}]}]},LL={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 $1={root:"_root_1vfca_1",anchor:"_anchor_1vfca_6",anchorButton:"_anchorButton_1vfca_11"};var kr=S(b()),rh=(e,t,n)=>r=>(0,kr.jsx)("button",{className:e.anchorButton,type:"button",value:t,onClick:n,children:r},t),AL=({className:e,loginUrl:t,isEmbedded:n,onSnooze:r,onLogIn:o})=>{let i=H(nh),s=Lt(),a=P("Login",$1),l=M("productName"),u=(0,Mn.useCallback)(m=>{m.preventDefault(),r&&r(parseInt(m.target.value,10))},[]),c=(0,Mn.useCallback)(m=>{m.preventDefault(),s.send(Ni,!0)},[t]),p=(0,Mn.useMemo)(()=>m=>(0,kr.jsx)("a",{onClick:g=>{g.preventDefault(),o()},href:t,className:a.anchor,target:"_blank",rel:"noreferrer",children:m},"login"),[t]),d=(0,Mn.useCallback)(m=>(0,kr.jsx)("button",{type:"button",className:a.anchorButton,onClick:c,children:m},"prompt"),[c]),{min:f,hour:y,day:v}=(0,Mn.useMemo)(()=>({min:rh(a,60*10,u),hour:rh(a,60*60,u),day:rh(a,60*60*12,u)}),[]);return(0,kr.jsxs)("div",{className:(0,q1.default)(e,a.root),children:[i("loginPlease",{login:n?d:p,productName:l}),r&&(0,kr.jsxs)(Mn.Fragment,{children:[(0,kr.jsx)("br",{}),i("snooze",{min:f,hour:y,day:v})]})]})},pd=AL;var G1={root:"_root_1g8fi_1",text:"_text_1g8fi_19"};var Ha=S(b()),OL=({title:e})=>{let t=P("SearchTrigger",G1),n=U();return(0,Ha.jsxs)("button",{type:"button",className:t.root,onClick:()=>n($e(!0)),children:[(0,Ha.jsx)(Ri,{}),(0,Ha.jsx)("span",{className:t.text,children:e})]})},X1=OL;var oh={};Pe(oh,{enUS:()=>NL,nlNL:()=>ML});var NL={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"}]},ML={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"}]};var Q1={root:"_root_onpov_1",isInline:"_isInline_onpov_14",toggleButton:"_toggleButton_onpov_21",toggleButtonWrapper:"_toggleButtonWrapper_onpov_25",toggleButtonWrapperHidden:"_toggleButtonWrapperHidden_onpov_32",isCollapsed:"_isCollapsed_onpov_36",collapsible:"_collapsible_onpov_36",hints:"_hints_onpov_44",hintsHidden:"_hintsHidden_onpov_51",triggers:"_triggers_onpov_56",triggersRight:"_triggersRight_onpov_71"};var ue=S(b()),DL=({textSuggestions:e,selectedIndex:t,onLogIn:n})=>{let r=P("SuggestionsOverlay",Q1),o=H(oh),i=R(ji),s=Xx(),a=U(),l=(0,Bi.useRef)(null),u=M("searchTriggerKey"),c=M("productName"),p=R(od),d=R(Ge),f=R(Si),[y,v]=(0,Bi.useState)(null),m=M("showSearch"),h=M("showTextSuggestions"),g=M("adminUrl"),x=M("isEmbedded"),[_,w]=W1("dd-snooze-until-ms",0),E=p||_>Date.now(),C=R(B=>B.input.text),I=e.filter(B=>B.source!=="gpt").length,k=()=>{E&&w(0),a(Ow(!E))},K=B=>{a(Be({name:"suggestion feedback",data:{text:B.text,source:"overlay",context:C},options:{includeConversationData:!0}}))},N=B=>{let be=Date.now()+B*1e3;w(be),j.info(`Snooze until: ${new Date(be)}`),a(Er({collapse:!0}))};return(0,Bi.useEffect)(()=>{I===0&&v(null)},[e,I]),Ti(()=>{a(Er({collapse:!0,skipWhenInputFocus:!0}))}),d===null||f===!1?null:d===!1?(0,ue.jsxs)("div",{ref:l,className:(0,fd.default)(r.root,{[r.isCollapsed]:E}),children:[!E&&(0,ue.jsxs)("div",{className:r.triggers,children:[(0,ue.jsx)("div",{style:{flex:1}}),(0,ue.jsx)("div",{className:r.triggersRight,children:(0,ue.jsx)(Hr,{className:r.toggleButton,title:o("collapse"),onClick:k,isCollapsed:!1})})]}),(0,ue.jsx)("div",{className:r.toggleButtonWrapper,children:(0,ue.jsx)(Hr,{className:r.toggleButton,title:o("open",{productName:c}),onClick:k,isCollapsed:!0})}),(0,ue.jsx)("div",{className:r.collapsible,children:(0,ue.jsx)(pd,{loginUrl:g,isEmbedded:x,onLogIn:n,onSnooze:N})})]}):!s||!i?null:(0,ue.jsxs)("div",{ref:l,className:(0,fd.default)(r.root,{[r.isCollapsed]:E}),children:[!E&&(0,ue.jsxs)("div",{className:r.triggers,children:[(0,ue.jsx)("div",{style:{flex:1},children:m&&(0,ue.jsx)("div",{style:{display:"inline-block"},onFocus:()=>{},onMouseOver:()=>v(o(Jc()?"searchHintMac":"searchHintWindows",{searchTriggerKey:u.toUpperCase()})),onMouseLeave:()=>v(null),children:(0,ue.jsx)(X1,{title:o("search")})})}),(0,ue.jsxs)("div",{className:r.triggersRight,onFocus:()=>{},children:[(0,ue.jsx)("div",{className:(0,fd.default)(!y&&r.hintsHidden,r.hints),children:y}),(0,ue.jsx)(Hr,{className:r.toggleButton,title:o("collapse"),onClick:k,isCollapsed:!1})]})]}),(0,ue.jsx)("div",{className:r.toggleButtonWrapper,children:(0,ue.jsx)(Hr,{className:r.toggleButton,title:o("open",{productName:c}),onClick:k,isCollapsed:!0})}),I>0&&h&&(0,ue.jsx)("div",{className:r.collapsible,onFocus:()=>{},children:(0,ue.jsx)(xt,{children:(0,ue.jsx)(cd,{onFeedback:K,suggestions:e,selectedIndex:t,reverse:!0})})})]})},FL=({input:e})=>({selectedIndex:e.selectedSuggestionIndex,textSuggestions:e.textSuggestions}),Y1=xn(FL)(DL);var Td=S(q());var jn=S(O());var Z1=S(O()),jL=["div","span","mark","strong","b","i","u","em"];function ih(e,t,n=0){var i;let r=e[e.length-1],o=typeof r=="object"&&r!==null?(i=r.props)==null?void 0:i.tagName:void 0;if(o==="br")return e.pop(),[...e,...t,r];if(jL.includes(o)){let s=Array.isArray(r.props.children)?r.props.children:[r.props.children];return[...e.slice(0,e.length-1),(0,Z1.cloneElement)(r,{children:ih(s,t,n+1)})]}return[...e,...t]}function Pr(e){return e.tagName.toLowerCase()==="textarea"}var J1={root:"_root_81non_1",container:"_container_81non_3",agentText:"_agentText_81non_5",tabText:"_tabText_81non_6",hint:"_hint_81non_6",matchSelection:"_matchSelection_81non_10",focus:"_focus_81non_16",resetIndent:"_resetIndent_81non_20",matchKeyword:"_matchKeyword_81non_24",matchPlaceholder:"_matchPlaceholder_81non_25",hover:"_hover_81non_31",hintText:"_hintText_81non_64",popover:"_popover_81non_72",popoverRoot:"_popoverRoot_81non_77",popoverContentContainer:"_popoverContentContainer_81non_81",popoverContent:"_popoverContent_81non_81",selectionOptions:"_selectionOptions_81non_107",selectionOptionsIsHidden:"_selectionOptionsIsHidden_81non_112",selectionOptionsButton:"_selectionOptionsButton_81non_116",caret:"_caret_81non_132",popoverSuggestionsRoot:"_popoverSuggestionsRoot_81non_136",suggestionsOverlayInputStyles:"_suggestionsOverlayInputStyles_81non_141"};var lb=S(q());var wd=S(O());function eb(e){return e.replace(/[.*+^${}()|[\]\\]/g,"\\$&")}function md(e){return t=>{e.forEach(n=>{typeof n=="function"?n(t):n!=null&&(n.current=t)})}}function tb(e){return e!=null}var ah=S(q()),At=S(O());var gd=S(O()),HL=["bottom","height","left","right","top","width"],BL=(e={},t={})=>HL.some(n=>e[n]!==t[n]),Dn=new Map,nb,rb=()=>{let e=[],t=[];Dn.forEach((n,r)=>{if(r instanceof Element&&!r.isConnected){t.push(r);return}let o=r.getBoundingClientRect();BL(o,n.rect)&&(n.rect=o,e.push(n))}),t.forEach(n=>{Dn.delete(n)}),e.forEach(n=>{n.callbacks.forEach(r=>r(n.rect))}),nb=window.requestAnimationFrame(rb)};function zL(e,t){return{observe(){let n=Dn.size===0;if(Dn.has(e)){let r=Dn.get(e);r.callbacks.push(t),r.rect&&t(r.rect)}else Dn.set(e,{rect:void 0,hasRectChanged:!1,callbacks:[t]});n&&rb()},unobserve(){let n=Dn.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||Dn.delete(e),Dn.size||cancelAnimationFrame(nb)}}}}function sh(e){let[t,n]=(0,gd.useState)(null);return(0,gd.useLayoutEffect)(()=>{if(!e.current)return;let r=zL(e.current,o=>{n(o)});return r.observe(),()=>{r.unobserve()}},[e]),t}var zi=S(O()),ib=S(wu());var ob={root:"_root_1jq08_1"};var sb=({children:e})=>{let[t,n]=(0,zi.useState)(null),r=(0,zi.useContext)(Xi);return(0,zi.useLayoutEffect)(()=>{let o=document.createElement("div");return ao(o),o.classList.add(ob.root),r!=null&&r.portalRootNode&&o.classList.add(r==null?void 0:r.portalRootNode),document.body.appendChild(o),n(o),()=>{o.isConnected&&document.body.removeChild(o)}},[]),t?(0,ib.createPortal)(e,t):null};var ln={ref:"_ref_1rcyi_1",root:"_root_1rcyi_7",positionAbove:"_positionAbove_1rcyi_13",positionBelow:"_positionBelow_1rcyi_17",positionLeft:"_positionLeft_1rcyi_21",positionRight:"_positionRight_1rcyi_25",alignStart:"_alignStart_1rcyi_29",alignCenter:"_alignCenter_1rcyi_34",alignEnd:"_alignEnd_1rcyi_40"};var hd=S(b()),yd=(e=!1)=>{let[t,n]=(0,At.useState)(e),r=(0,At.useCallback)(()=>n(!0),[]),o=(0,At.useCallback)(()=>n(!1),[]),i=(0,At.useCallback)(()=>n(a=>!a),[]),s=(0,At.useRef)(null);return{opened:t,open:r,close:o,toggle:i,triggerRef:s}};function lh(e,t=null,n=0){if(!e)return{display:"none"};let r=t?e.top-t.top<0||e.top<t.top-n?t.top-n:e.top+e.height>t.top+t.height+n?t.top+t.height+n-e.height:e.top:e.top,o=t?e.left<t.left-n?t.left-n:e.left+e.width>t.left+t.width+n?t.left+t.width+n-e.width:e.left:e.left;return{top:r,left:o,height:e.height,width:e.width}}var vd=({className:e,triggerRef:t,boundaryRef:n=(0,At.createRef)(),position:r="above",align:o="center",children:i,toStyle:s=lh,...a})=>{let l=sh(t),u=sh(n),c=(0,At.useMemo)(()=>s(l,u,0),[l,u]);return(0,hd.jsx)(sb,{children:(0,hd.jsx)("div",{className:(0,ah.default)(ln.ref,{[ln.positionAbove]:r==="above",[ln.positionBelow]:r==="below",[ln.positionLeft]:r==="left",[ln.positionRight]:r==="right",[ln.alignStart]:o==="start",[ln.alignCenter]:o==="center",[ln.alignEnd]:o==="end"}),style:c,...a,role:"dialog",children:(0,hd.jsx)("div",{className:(0,ah.default)(e,ln.root),children:i})})})};var ab=S(q()),Sd=S(O());var uh=S(b()),xd=(0,Sd.forwardRef)(({className:e,children:t,...n},r)=>{let o=(0,Sd.useRef)(null),i=P("TabCompletion",Tn);return(0,uh.jsx)("div",{ref:md([o,r]),className:(0,ab.default)(e,i.popoverContentContainer),...n,children:(0,uh.jsx)("div",{className:i.popoverContent,children:t})})});var Ir=S(b()),UL=e=>t=>{let n=lh(t);return"top"in n&&(n.width=e.width-(t.left-e.left)-10),n},KL=({inputElement:e,boundaryRef:t,inputStyle:n,children:r,suggestion:o})=>{let i=P("TabCompletion",Tn),s=yd(),a=(0,wd.useMemo)(()=>UL(e.getBoundingClientRect()),[e]),[l,u]=Bc(e);return(0,wd.useEffect)(()=>{u?s.open():s.close()},[u]),(0,Ir.jsxs)("span",{children:[(0,Ir.jsx)("mark",{ref:md([l,s.triggerRef]),className:(0,lb.default)(i.matchKeyword,{[i.hover]:u}),"aria-haspopup":"dialog","aria-expanded":s.opened?"true":"false",children:r}),s.opened&&(0,Ir.jsx)(vd,{className:i.popover,triggerRef:s.triggerRef,boundaryRef:t,position:"below",align:"start",toStyle:a,children:(0,Ir.jsx)(xd,{style:n,children:(0,Ir.jsx)("div",{className:i.hintText,children:o})})})]})},_d=class extends bn{keywordMatches=[];preparedKeywordMatches=[];usedKeywordMatches=new Set;onBeforeParse(t,n){return n.keywordMatches&&n.keywordMatches!==this.keywordMatches&&(this.preparedKeywordMatches=n.keywordMatches.map(r=>({...r,keywordRegex:new RegExp(`\\b${eb(r.keyword)}\\b`,"i")})),this.keywordMatches=n.keywordMatches),this.usedKeywordMatches.clear(),t}match(t){let n=this.preparedKeywordMatches.map(o=>{if(this.usedKeywordMatches.has(o))return null;let i=t.match(o.keywordRegex);if(!i)return null;let s=t.charAt(i.index-1),a=t.charAt(i.index+o.keyword.length);return s==="{"&&a==="}"?null:{index:i.index,length:i[0].length,match:i[0],matchString:i[0],suggestion:o.suggestion,preparedKeywordMatch:o,valid:!0}}).filter(tb);if(n.length===0)return null;let r=n.reduce((o,i)=>i.index<o.index?i:o);return this.usedKeywordMatches.add(r.preparedKeywordMatch),r}replaceWith(t,n){return(0,Ir.jsx)(KL,{inputElement:n.inputElement,suggestion:n.suggestion,inputStyle:n.inputStyle,boundaryRef:n.boundaryRef,children:t},`keyword_${n.matchString}_${n.key}`)}asTag(){return"mark"}};var Ed=S(q());var Ye=S(O());var ch=S(b()),ub=()=>(0,ch.jsx)("svg",{width:"1.3em",height:"1.3em",focusable:"false","aria-hidden":"true",viewBox:"0 0 24 24","data-testid":"InsertLinkIcon",tabIndex:-1,children:(0,ch.jsx)("path",{fill:"currentColor",d:"M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76 0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71 0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71 0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76 0 5-2.24 5-5s-2.24-5-5-5z"})});var Rr=S(O());var db=S(Gg());var cb={root:"_root_1muu8_1",content:"_content_1muu8_7"};function bd(e,t,n){var o;let r=((o=e.imageSizes)==null?void 0:o[t])||e.image||n;if(!r)return null;try{return new URL(r).toString()}catch{return null}}function dh(e){return e.replace("https://www.","").replace("https://","")}var Ot=S(b()),VL=3,WL=e=>({image:e.image||"",text:e.text,id:e.id,title:e.title}),$L=({onSelectLink:e,onDismiss:t,placeholder:n,visitUrlText:r,linkCount:o=VL})=>{let i=P("LinkSearch",cb),[s,a]=(0,Rr.useState)(""),l=U(),u=R(nd("url")),c=R(uw("URL",WL)),[p,d]=(0,Rr.useState)(c.length-1),f=M("fallbackImage"),y=g=>{let x=g.target;a(x.value)},v=(g,x)=>{g.stopPropagation(),g.preventDefault(),window.open(x,"_blank")},m=g=>{var w;let x=p-1<0?c.length-1:p-1,_=p+1===c.length?0:p+1;g.code==="Escape"&&(a(""),t()),g.code==="ArrowUp"&&d(x),g.code==="ArrowDown"&&d(_),g.code==="Enter"&&e(((w=c[p])==null?void 0:w.text)||s)},h=(0,Rr.useCallback)((0,db.default)(g=>{l(go({query:g,type:"URL",tags:["link-search"]}))},300),[]);return(0,Rr.useEffect)(()=>{s&&h(s)},[s]),(0,Rr.useEffect)(()=>()=>{l(Yc())},[]),(0,Ot.jsxs)("div",{className:i.root,children:[(0,Ot.jsx)(xt,{withDivider:!0,children:(s?c:u).slice(0,o).map((g,x)=>(0,Ot.jsx)(oe,{selected:p===x,onClick:()=>e(g.text),"data-testid":"linksearch-suggestion",children:(0,Ot.jsxs)(ge,{children:[(0,Ot.jsx)(ge.Image,{src:bd(g,"small",f||void 0),title:g.title||g.text}),(0,Ot.jsxs)(ge.Content,{className:i.content,cropText:!0,children:[(0,Ot.jsx)(ge.Title,{children:g.title||dh(g.text)}),g.title&&dh(g.text)]}),(0,Ot.jsx)(oe.Actions,{children:(0,Ot.jsx)(oe.ActionButton,{label:r,onClick:_=>v(_,g.text)})})]})},g.text))}),(0,Ot.jsx)(Ia,{value:s,onChange:y,autoFocus:!0,placeholder:n,onKeyUp:m})]})},pb=$L;var ph={};Pe(ph,{enUS:()=>qL,nlNL:()=>GL});var qL={insertLink:[{type:0,value:"Insert link"}],linkInputPlaceholder:[{type:0,value:"Search, type or paste link"}],visitUrl:[{type:0,value:"Visit"}]},GL={insertLink:[{type:0,value:"Voeg link toe"}],linkInputPlaceholder:[{type:0,value:"Zoek, typ of plak link"}],visitUrl:[{type:0,value:"Bekijk"}]};var Qe=S(b()),XL=(0,Ye.forwardRef)((e,t)=>{let n=P("TabCompletion",Tn);return(0,Qe.jsx)("mark",{ref:t,className:(0,Ed.default)(n.matchSelection)},"selection-start")}),QL=({startRef:e,boundaryRef:t,inputStyle:n,inputElement:r,children:o})=>{let i=H(ph),s=P("TabCompletion",Tn),a=(0,Ye.useRef)(null),l=(0,Ye.useRef)(null),[u,c]=(0,Ye.useState)(null),p=U(),d=yd(document.activeElement===r),[f]=(0,Ye.useState)(()=>document.createRange());d.triggerRef.current=f,(0,Ye.useEffect)(()=>()=>f.detach(),[]),(0,Ye.useEffect)(()=>{let v=e.current,m=a.current;!v||!m||(f.setStart(v,0),f.setEnd(m,0))},[e.current,a.current]),Ti(()=>{d.close()});let y=(0,Ye.useCallback)(v=>{let m=f.toString(),h=/^http(s?):\/\//.test(v)?v:`https://${v}`;p(fc({text:`[${m}](${h})`,replace:"selection"}))},[]);return(0,Qe.jsxs)("span",{children:[(0,Qe.jsx)("mark",{ref:a,className:(0,Ed.default)(s.matchSelection),"aria-haspopup":"dialog","aria-expanded":d.opened?"true":"false",children:o}),d.opened&&(0,Qe.jsx)(vd,{className:s.popoverRoot,triggerRef:d.triggerRef,boundaryRef:t,position:"above",align:"start",children:(0,Qe.jsxs)(xd,{style:n,ref:l,children:[(0,Qe.jsx)("div",{className:(0,Ed.default)(s.selectionOptions,{[s.selectionOptionsIsHidden]:u!==null}),children:(0,Qe.jsxs)("button",{type:"button",tabIndex:u===null?-1:void 0,className:s.selectionOptionsButton,onClick:()=>c("insertLink"),children:[(0,Qe.jsx)(ub,{}),(0,Qe.jsx)("span",{children:"\xA0"}),(0,Qe.jsx)("span",{children:i("insertLink")})]})}),u==="insertLink"&&(0,Qe.jsx)(pb,{placeholder:i("linkInputPlaceholder"),visitUrlText:i("visitUrl"),onSelectLink:y,onDismiss:()=>{c(null),d.close()}})]})})]},"selection-end")},Cd=class extends bn{charCount=0;foundIndex=0;startRef=null;props;onBeforeParse(t,n){return this.props=n,this.charCount=0,this.startRef=(0,Ye.createRef)(),this.foundIndex=0,t}match(t){if(!this.props||this.props.selection===null||this.foundIndex===2)return null;let[n,r]=this.props.selection;if(n===r)return null;let o=this.foundIndex===0?n:r,i=o>=this.charCount&&o<=this.charCount+t.length?{index:o-this.charCount,length:0,match:"",valid:!0}:null;i&&this.foundIndex++;let s=this.foundIndex===1;return i&&s?this.charCount+=o-this.charCount:this.charCount+=t.length,i?{isStart:s,...i}:null}replaceWith(t,n){return n.isStart?(0,Qe.jsx)(XL,{ref:this.startRef}):(0,Qe.jsx)(QL,{inputElement:n.inputElement,startRef:this.startRef,boundaryRef:n.boundaryRef,inputStyle:n.inputStyle})}asTag(){return"mark"}};var Fn=S(b()),YL=({enabled:e,content:t,tabText:n,showTabHint:r,showTabCompletion:o,showStyleSuggestions:i,keywordMatches:s,inputElement:a,source:l})=>{let u=P("TabCompletion",J1),c=M("insertLink"),p=M("showMidSentenceSuggestions"),d=M("inlineSuggestions"),f=Uc(a),y=(0,jn.useRef)(null),v=R(Ge);(0,jn.useEffect)(()=>{Pr(a)&&f&&Kc(a,f)},[f]);let m=(0,jn.useCallback)(x=>{if(!o||!n)return x;let _=[(0,Fn.jsx)("span",{className:u.resetIndent,children:"\u200B"},"u200B"),(0,Fn.jsx)("span",{"data-testid":"tab-completion",className:(0,Td.default)(u.tabText,u.resetIndent),"data-source":l,children:n},"tabText")];return r&&_.push((0,Fn.jsx)("span",{className:(0,Td.default)(u.hint,u.resetIndent),children:(0,Fn.jsx)(sl,{keyCode:"tab"},"tabHint")})),ih(x,_)},[o,n,r]),h=(0,jn.useMemo)(()=>{let x=[];return c&&x.push(new Cd("selection")),x.push(new Ei("placeholders")),i&&x.push(new _d("keywords")),x},[d,c,i]),g=(0,jn.useMemo)(()=>{let x=window.getComputedStyle(a);return{"--dd-color":x.color,"--dd-font-size":x.fontSize,"--dd-font-family":x.fontFamily,"--dd-font-variant":x.fontVariant}},[]);return!e||!v?null:(0,Fn.jsxs)("div",{ref:x=>{x!=null&&x.parentElement&&(y.current=x==null?void 0:x.parentElement)},className:u.root,style:g,children:[(0,Fn.jsx)(Cn,{tagName:"span",containerTagName:"div",className:(0,Td.default)(u.container,u.agentText),disableLineBreaks:Pr(a),content:t||"\u200B",onAfterParse:m,matchers:h,selection:f,keywordMatches:s,inputElement:a,inputStyle:g,boundaryRef:y,inlineSuggestionsOnlyAtEnd:!p}),(0,Fn.jsx)("br",{})]})},ZL=({input:e,ui:t,settings:n,styleSuggestions:r,conversation:o})=>{var v;let{tabCompletionSuggestion:i}=e,s=(i==null?void 0:i.text)||"",a=(i==null?void 0:i.source)||"",l=e.html??Pi(e.text),u=s.indexOf(e.text)===0?s.slice(e.text.length):"",{showTabHint:c}=t,{isSupported:p}=o,{showTabCompletion:d,visible:f,showStyleSuggestions:y}=n;return{showTabHint:c,showStyleSuggestions:y,showTabCompletion:d,content:l,tabText:u,source:a,keywordMatches:((v=r.list)==null?void 0:v.keywordMatches)??[],enabled:f&&p!==!1}},fb=xn(ZL)(YL);var tE=S(q()),nE=S(O());var mb={list:[],fetchState:"idle",isInitialRequest:null},hb=e=>e.autoflows.list||[],gb=e=>t=>{var n;return(n=t.list)==null?void 0:n.find(r=>r.triggerPayload===e)},Hn=D("autoflows/getAll",async(e,t)=>{let{deepdeskBrokerAPI:n}=t.extra;if(!n)throw new Error("Deepdesk Broker not initialized");return n.getAutoflows(e)}),fh=D("autoflows/start",async(e,t)=>{let{dispatch:n}=t,{deepdeskBrokerAPI:r}=t.extra;if(!r)throw new Error("Deepdesk Broker not initialized");await r.startAutoflowSession(e),await n(Hn(e.platformSessionId))}),mh=D("autoflows/stop",async(e,t)=>{let{dispatch:n}=t,{deepdeskBrokerAPI:r}=t.extra;if(!r)throw new Error("Deepdesk Broker not initialized");await r.stopAutoflowSession(e.platformSessionId),await n(Hn(e.platformSessionId))}),JL=z({name:"autoflows",initialState:mb,reducers:{},extraReducers:e=>{e.addCase(fh.pending,(t,n)=>{let r=gb(n.meta.arg.triggerPayload)(t);r.state="Started",r.isBusy=!0}),e.addCase(mh.pending,(t,n)=>{let r=gb(n.meta.arg.triggerPayload)(t);r.state="Aborted",r.isBusy=!0}),e.addCase(Hn.pending,t=>{t.isInitialRequest=t.isInitialRequest===null,t.fetchState="loading"}),e.addCase(Hn.rejected,t=>{t.fetchState="error"}),e.addCase(Hn.fulfilled,(t,n)=>{t.list=n.payload,t.fetchState="done"}),e.addCase(te,()=>mb)}}),yb=D("autoflows/openStream",(e,t)=>{let{dispatch:n}=t,{deepdeskBrokerAPI:r}=t.extra;if(!r)throw new Error("Deepdesk Broker not initialized");let o=r.openStream(e);o.on("sessionAborted",()=>{n(Hn(e))}),o.on("sessionCompleted",()=>{n(Hn(e))})}),vb=D("autoflows/closeStream",(e,t)=>{let{deepdeskBrokerAPI:n}=t.extra;if(!n)throw new Error("Deepdesk Broker not initialized");n.closeStream(e)}),Sb=JL.reducer;var xb={list:[],fetchState:"idle",isInitialRequest:null,sentSuggestions:[],errorSuggestions:[],answeredSuggestions:[]},_b=e=>e.customMessages.list,wb=e=>t=>!!t.customMessages.sentSuggestions.find(n=>n===e),bb=e=>t=>!!t.customMessages.answeredSuggestions.find(n=>n===e),Eb=e=>t=>!!t.customMessages.errorSuggestions.find(n=>n===e),Ba=D("customMessages/getAll",async(e,t)=>{let{deepdeskBrokerAPI:n}=t.extra;if(!n)throw new Error("Deepdesk Broker not initialized");return n.getCustomMessages(e)}),kd=D("customMessages/send",async(e,t)=>{let{platformSessionId:n,suggestion:r}=e,{deepdeskBrokerAPI:o}=t.extra;if(!o)throw new Error("Deepdesk Broker not initialized");await o.sendCustomMessage(n,r)}),Pd=D("customMessages/answer",async(e,t)=>{let{platformSessionId:n,reply:r}=e,{deepdeskBrokerAPI:o}=t.extra;if(!o)throw new Error("Deepdesk Broker not initialized");await o.answerCustomMessage(n,r)}),Cb=z({name:"customMessages",initialState:xb,reducers:{onCustomMessage(e,t){Array.isArray(t.payload)?e.list=t.payload:e.list=[t.payload]}},extraReducers:e=>{e.addCase(Ba.pending,t=>{t.isInitialRequest=t.isInitialRequest===null,t.fetchState="loading"}).addCase(Ba.rejected,t=>{t.fetchState="error"}).addCase(Ba.fulfilled,(t,n)=>{t.fetchState="done",t.list=n.payload||[]}).addCase(kd.pending,(t,n)=>{t.sentSuggestions.push(n.meta.arg.suggestion.text),t.errorSuggestions=t.errorSuggestions.filter(r=>n.meta.arg.suggestion.text!==r)}).addCase(kd.rejected,(t,n)=>{let r=t.sentSuggestions.indexOf(n.meta.arg.suggestion.text);t.errorSuggestions.push(...t.sentSuggestions.splice(r,1))}).addCase(Pd.pending,(t,n)=>{t.sentSuggestions.push(n.meta.arg.suggestion.text),t.answeredSuggestions.push(n.meta.arg.suggestion.text)}).addCase(Pd.rejected,(t,n)=>{let r=t.answeredSuggestions.indexOf(n.meta.arg.suggestion.text);t.errorSuggestions.push(...t.sentSuggestions.splice(r,1)),t.answeredSuggestions.splice(r,1)}).addCase(te,()=>xb)}}),Tb=D("customMessages/openStream",(e,t)=>{let{dispatch:n}=t,{deepdeskBrokerAPI:r}=t.extra;if(!r)throw new Error("Deepdesk Broker not initialized");r.openStream(e).on("customMessageSuggestion",i=>{n(Cb.actions.onCustomMessage(i))})}),kb=D("customMessages/closeStream",(e,t)=>{let{deepdeskBrokerAPI:n}=t.extra;if(!n)throw new Error("Deepdesk Broker not initialized");n.closeStream(e)}),Pb=Cb.reducer;var eA={token:null,accountUrl:null,interval:null},Ib=e=>t=>{let{passwordlessToken:{token:n,accountUrl:r}}=t;return n&&r?`${r}/apis/admin/session/passwordless/login/?token=${n}&redirect=${e}`:null},gh=D("passwordlessToken/getTemporaryPasswordlessToken",async(e,t)=>{let{deepdeskAPI:n}=t.extra,r=await n.requestPasswordlessToken();return{accountUrl:n.client.baseUrl,token:r}}),hh=D("passwordlessToken/pollPasswordlessToken",(e={},t)=>{let{interval:n=1e3*60*10}=e,{dispatch:r}=t;return r(gh()),setInterval(()=>r(gh()),n)}),Rb=z({name:"passwordlessToken",initialState:eA,reducers:{stopPollPasswordlessToken(e){e.interval&&clearInterval(e.interval),e.interval=null}},extraReducers:e=>{e.addCase(gh.fulfilled,(t,n)=>{t.token=n.payload.token,t.accountUrl=n.payload.accountUrl}),e.addCase(hh.fulfilled,(t,n)=>{t.interval=n.payload})}}),{stopPollPasswordlessToken:Lb}=Rb.actions,Ab=Rb.reducer;function Ob(e){let{customMessages:t,autoflows:n}=e;return n.fetchState==="loading"&&n.isInitialRequest===!0||t.fetchState==="loading"&&t.isInitialRequest===!0}var Ub=S(O());var Hb=S(q()),Bb=S(O());var Mb=S(q());var Nb={root:"_root_838fd_1"};var Fb=S(b()),tA=({className:e,children:t})=>{let n=P("Unicode",Nb);return(0,Fb.jsx)("span",{className:(0,Mb.default)(e,n.root),children:t})},Db=tA;var jb={isDisabled:"_isDisabled_1rmfm_1",buttonStart:"_buttonStart_1rmfm_5",root:"_root_1rmfm_8",buttonStop:"_buttonStop_1rmfm_8",stateBadge:"_stateBadge_1rmfm_19",isCompleted:"_isCompleted_1rmfm_26",isStarted:"_isStarted_1rmfm_30",isAborted:"_isAborted_1rmfm_34"};var yh={};Pe(yh,{enUS:()=>nA,nlNL:()=>rA});var nA={start:[{type:0,value:"Start"}],stop:[{type:0,value:"Stop"}],aborted:[{type:0,value:"Stopped"}],completed:[{type:0,value:"Completed"}],Aborted:[{type:0,value:"Stopped"}],Started:[{type:0,value:"Running"}],Completed:[{type:0,value:"Completed"}]},rA={start:[{type:0,value:"Start"}],stop:[{type:0,value:"Stop"}],aborted:[{type:0,value:"Stopped"}],completed:[{type:0,value:"Completed"}],Aborted:[{type:0,value:"Stopped"}],Started:[{type:0,value:"Running"}],Completed:[{type:0,value:"Completed"}]};var ft=S(b()),iA=({disabled:e,state:t,displayName:n,description:r,onStartAutoflow:o,onStopAutoflow:i})=>{let s=P("Autoflow",jb),a=H(yh),l=t==="Started"?"stop":"start",u=l==="start"?"\u25B6":l==="stop"?"\u25FC":"";return(0,ft.jsxs)(oe,{className:(0,Hb.default)(s.root,{[s.isDisabled]:e,[s.isCompleted]:t==="Completed",[s.isAborted]:t==="Aborted",[s.isStarted]:t==="Started"}),children:[(0,ft.jsx)(ge,{children:(0,ft.jsxs)(ge.Content,{children:[(0,ft.jsxs)(ge.Title,{children:[t&&(0,ft.jsx)("span",{className:s.stateBadge,children:a(t)}),n]}),(0,ft.jsx)("span",{children:r})]})}),(0,ft.jsx)(oe.Actions,{fixed:t==="Started",children:(0,ft.jsx)(oe.ActionButton,{primary:!0,className:l==="start"?s.buttonStart:s.buttonStop,onClick:t==="Started"?i:o,disabled:e,label:(0,ft.jsxs)(Bb.Fragment,{children:[(0,ft.jsx)(Db,{children:u})," ",(0,ft.jsx)("span",{children:a(l)})]})})})]})},zb=iA;var vh=S(b()),sA=(e,t)=>{let n=t.filter(r=>r.state==="Started");return n.length>0?n.indexOf(e)===-1:!1},aA=({autoflows:e,onStartAutoflow:t,onStopAutoflow:n,platformSessionId:r})=>(0,vh.jsx)(Ub.Fragment,{children:e.map(o=>(0,vh.jsx)(zb,{displayName:o.displayName,description:o.description,disabled:o.isBusy||sA(o,e),state:o.state,onStartAutoflow:()=>t({platformSessionId:r,triggerPayload:o.triggerPayload}),onStopAutoflow:()=>n({platformSessionId:r,triggerPayload:o.triggerPayload})},o.displayName))}),lA=({autoflows:e,conversation:t})=>{var n;return{autoflows:e.list,platformSessionId:(n=t.current)==null?void 0:n.sessionId}},uA={onStartAutoflow:fh,onStopAutoflow:mh},Kb=xn(lA,uA)(aA);var Id=S(O());var _h=S(q());var Sh=S(b()),xh=()=>(0,Sh.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",children:(0,Sh.jsx)("path",{d:"M502.6 70.63l-61.25-61.25C435.4 3.371 427.2 0 418.7 0H255.1c-35.35 0-64 28.66-64 64l.0195 256C192 355.4 220.7 384 256 384h192c35.2 0 64-28.8 64-64V93.25C512 84.77 508.6 76.63 502.6 70.63zM464 320c0 8.836-7.164 16-16 16H255.1c-8.838 0-16-7.164-16-16L239.1 64.13c0-8.836 7.164-16 16-16h128L384 96c0 17.67 14.33 32 32 32h47.1V320zM272 448c0 8.836-7.164 16-16 16H63.1c-8.838 0-16-7.164-16-16L47.98 192.1c0-8.836 7.164-16 16-16H160V128H63.99c-35.35 0-64 28.65-64 64l.0098 256C.002 483.3 28.66 512 64 512h192c35.2 0 64-28.8 64-64v-32h-47.1L272 448z"})});var Vb={root:"_root_rjdyr_1",entity:"_entity_rjdyr_10",entityText:"_entityText_rjdyr_46",iconWrapper:"_iconWrapper_rjdyr_53",icon:"_icon_rjdyr_53",iconClicked:"_iconClicked_rjdyr_67"};var un=S(b()),cA=({entities:e})=>{let t=P("EntitiesWidgetList",Vb),[n,r]=(0,Id.useState)(void 0),o=U(),i=()=>{r(void 0)},s=a=>{e&&(r(e.indexOf(a)),La(a.text),o(Be({name:"entity copied",data:{entity:a,type:"copy"}})))};return(0,Id.useEffect)(()=>{let a=setTimeout(i,500);return()=>{clearTimeout(a)}},[n]),!e||e.length===0?null:(0,un.jsx)("div",{className:t.root,"data-testid":"widget-entities-list",children:e.map((a,l)=>(0,un.jsxs)("button",{title:a.text,className:t.entity,type:"button",onClick:()=>s(a),children:[(0,un.jsx)("span",{className:t.entityText,children:a.text}),(0,un.jsxs)("span",{className:t.iconWrapper,children:[(0,un.jsx)("span",{className:(0,_h.default)(t.icon),children:(0,un.jsx)(xh,{})}),(0,un.jsx)("span",{className:(0,_h.default)(t.icon,n===l&&t.iconClicked),children:(0,un.jsx)(xh,{})})]})]},a.text))})},Wb=cA;var $b=S(q()),wh=S(O());var Bn={root:"_root_1e6ej_1",title:"_title_1e6ej_8",isUsed:"_isUsed_1e6ej_13",quickReplies:"_quickReplies_1e6ej_22",quickReply:"_quickReply_1e6ej_29",hasError:"_hasError_1e6ej_39",label:"_label_1e6ej_43",errorIcon:"_errorIcon_1e6ej_48"};var st=S(b()),dA=({suggestion:e})=>{let t=H(fo),n=U(),r=R(wb(e.text)),o=R(bb(e.text)),i=R(Eb(e.text)),s=R(ic),{replyOptions:a}=e,l=(0,wh.useCallback)(c=>{c.preventDefault(),c.stopPropagation(),!(r||!s)&&n(kd({platformSessionId:s,suggestion:e}))},[e,r,n,s]),u=(0,wh.useCallback)(c=>{if(c.preventDefault(),c.stopPropagation(),!s||!a)return;let p=parseInt(c.target.dataset.index,10),d=a[p];n(Pd({platformSessionId:s,reply:d,suggestion:e}))},[e,r,n,s]);return(0,st.jsxs)(oe,{onClick:l,className:(0,$b.default)(Bn.root,{[Bn.isUsed]:r,[Bn.hasError]:i}),children:[(0,st.jsx)(ge,{children:(0,st.jsxs)(ge.Content,{children:[(0,st.jsxs)(ge.Title,{className:Bn.title,children:[e.text," ",(0,st.jsx)(al,{className:Bn.label,children:"analyse tool"})," ",i&&(0,st.jsx)("span",{className:Bn.errorIcon,role:"img","aria-label":t("sendingError"),title:t("sendingError"),children:"!"})]}),a&&a.length>0&&(0,st.jsx)("ul",{className:Bn.quickReplies,children:a.map(c=>(0,st.jsx)("li",{className:Bn.quickReply,children:c.title},c.title))})]})}),(0,st.jsxs)(oe.Actions,{fixed:i||r,children:[a&&a.length>0&&(0,st.jsx)(oe.DropdownButton,{label:t("answer"),disabled:o,children:a.map((c,p)=>(0,st.jsx)(oe.DropdownItem,{index:p,label:c.title,onClick:u},c.title))}),(0,st.jsx)(oe.ActionButton,{primary:!0,disabled:r,onClick:l,label:t(r?"suggestionSent":i?"tryAgain":"sendSuggestion")})]})]})},qb=dA;var bh=S(b()),Gb=()=>(0,bh.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,bh.jsx)("path",{d:"M17 13.5v6H5v-12h6m3-3h6v6m0-6-9 9",stroke:"currentColor",strokeWidth:"1.5",fill:"none",fillRule:"evenodd",strokeLinecap:"round",strokeLinejoin:"round"})});var Xb=S(O());var mt=S(b()),pA=({suggestion:e,lines:t,onEdit:n,onUse:r})=>{var d;let o=e.text||e.url||e.message,i=Zc(o),s=H(fo),a=M("showImages"),l=M("fallbackImage"),u=f=>{f.preventDefault(),f.stopPropagation(),r(o)},c=f=>{f.preventDefault(),f.stopPropagation(),n(e)},p=(0,Xb.useCallback)(f=>{window.open(i,"_blank"),f.stopPropagation(),f.preventDefault()},[i]);return(0,mt.jsxs)(oe,{onClick:u,"data-testid":"edit-suggestion",children:[(0,mt.jsxs)(ge,{children:[a&&e.image&&(0,mt.jsx)(ge.Image,{src:bd(e,"small",l||void 0),title:e.title}),(0,mt.jsxs)(ge.Content,{children:[e.title&&(0,mt.jsx)(ge.Title,{"data-testid":"widget-suggestion-title",children:e.title}),e.searchKeywords&&((d=e.searchKeywords)==null?void 0:d.length)>0&&(0,mt.jsx)(oe.Labels,{labels:e.searchKeywords}),(0,mt.jsx)(ge.Content,{cropText:t==="single",lineClamp:t==="multiple",children:o})]})]}),(0,mt.jsxs)(oe.Actions,{children:[i&&(0,mt.jsx)(oe.ActionButton,{onClick:p,label:s("visitUrl")}),(0,mt.jsx)(oe.ActionButton,{primary:!0,onClick:c,label:s("preview")}),(0,mt.jsx)(oe.ActionButton,{primary:!0,onClick:u,label:s("useSuggestion")})]})]})},Qb=pA;var za=S(b()),fA=({contentType:e,lines:t,suggestions:n})=>{let r=Lt(),o=R(br),i=a=>{r.send(Ug,{state:o,suggestion:a,contentType:e})},s=(a,l)=>{r.send(An,{text:a,suggestion:{...l,source:l.source,sourceText:l.text}})};return(0,za.jsx)(za.Fragment,{children:n.map(a=>(0,za.jsx)(Qb,{suggestion:a,lines:t,onEdit:l=>i(l),onUse:l=>s(l,a)},a.text||a.url||a.message))})},Yb=fA;var Eh={};Pe(Eh,{enUS:()=>mA,nlNL:()=>gA});var mA={waiting:[{type:0,value:"Loading\u2026"}],notSupported:[{type:0,value:"This conversation is not supported"}],noResults:[{type:0,value:"No results found\u2026"}],titleAutoflows:[{type:0,value:"Autoflows"}],titleCustomMessages:[{type:0,value:"Quick replies"}],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"}]},gA={waiting:[{type:0,value:"Laden\u2026"}],notSupported:[{type:0,value:"Dit gesprek wordt niet ondersteund"}],noResults:[{type:0,value:"Geen resultaten gevonden\u2026"}],titleAutoflows:[{type:0,value:"Autoflows"}],titleCustomMessages:[{type:0,value:"Quick replies"}],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"}]};var Zb={root:"_root_x0pwe_1",loginText:"_loginText_x0pwe_7",stateText:"_stateText_x0pwe_8",sectionList:"_sectionList_x0pwe_20",shortcutList:"_shortcutList_x0pwe_24",shortcut:"_shortcut_x0pwe_24",link:"_link_x0pwe_52"};var Ch=S(b()),Jb=()=>(0,Ch.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:(0,Ch.jsx)("path",{d:"M543-340q16.595 0 28.798-12.202Q584-364.405 584-381t-12.202-28.798Q559.595-422 543-422t-28.798 12.202Q502-397.595 502-381t12.202 28.798Q526.405-340 543-340Zm-25-126h47q2-29 8.5-43t32.5-39q27-26 37.5-45.395Q654-612.79 654-639q0-45.882-31.5-74.941Q591-743 540-743q-38 0-68 20.5T428-665l45 19q11-25 27.5-38t39.5-13q29.778 0 48.389 17Q607-663 607-637q0 20-9 35t-32 32q-32 29-40 46.5t-8 57.5ZM260-200q-24 0-42-18t-18-42v-560q0-24 18-42t42-18h560q24 0 42 18t18 42v560q0 24-18 42t-42 18H260Zm0-60h560v-560H260v560ZM140-80q-24 0-42-18t-18-42v-620h60v620h620v60H140Zm120-740v560-560Z"})});var Th=S(b()),eE=()=>(0,Th.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:(0,Th.jsx)("path",{d:"M319-250h322v-60H319v60Zm0-170h322v-60H319v60ZM220-80q-24 0-42-18t-18-42v-680q0-24 18-42t42-18h361l219 219v521q0 24-18 42t-42 18H220Zm331-554v-186H220v680h520v-494H551ZM220-820v186-186 680-680Z"})});var V=S(b()),Rd=(e,t)=>{let n=R(Ge);(0,nE.useEffect)(()=>n?t.every(r=>!!r)?e():()=>{}:()=>{},[...t,n])},hA=({onLogIn:e})=>{let t=H(Eh),n=U(),r=M("isEmbedded"),o=P("Widget",Zb),i=M("showAutoflows"),s=M("showCustomMessages"),a=M("showSummaryCommand"),l=M("showKnowledgeSearch"),u=M("showSearch"),c=R(Tr),p=R(ad),d=R(hb),f=R(sd),y=R(_b),v=R(sc),m=R(Si),h=R(Ge),g=R(ic),x=R(Ob),_=R(br),w=Lt(),E=R(xw),C=R(Ib("/admin/")),I=M("adminUrl"),k=M("productName");if(Rd(()=>(n(Ba(g)),n(Tb(g)),()=>{n(kb(g))}),[n,m,s,g]),Rd(()=>(n(Hn(g)),n(yb(g)),()=>{n(vb(g))}),[n,m,i,g]),Rd(()=>{p.forEach(({type:N})=>{n(N==="entities"?$t():Vt(N))})},[n,m,v,c]),Rd(()=>(n(hh()),()=>{n(Lb())}),[n]),m===!1)return(0,V.jsx)("div",{className:o.stateText,children:(0,V.jsx)("div",{children:(0,V.jsx)("p",{children:t("notSupported")})})},"supported");if(h===!1)return(0,V.jsx)("div",{className:o.loginText,children:(0,V.jsx)("div",{children:(0,V.jsx)(pd,{isEmbedded:r,loginUrl:I,onLogIn:e})})},"login");if(!c||!g||h===null||E||x)return(0,V.jsx)("div",{className:o.stateText,children:(0,V.jsx)("div",{children:(0,V.jsx)("p",{children:t("waiting")})})},"waiting");let K=u||a||l||C;return(0,V.jsx)("div",{className:(0,tE.default)(o.root),"data-testid":"widget",children:(0,V.jsxs)(ll,{className:o.sectionList,children:[K&&(0,V.jsx)(Kn,{title:t("actions"),type:"shortcuts",children:(0,V.jsxs)("div",{className:o.shortcutList,children:[u&&(0,V.jsxs)("button",{className:o.shortcut,"data-testid":"shortcut-search",onClick:()=>w.send("ShowCommandPalette",{isOpen:!0}),children:[(0,V.jsx)(Ri,{}),t("linkSearch")]}),a&&(0,V.jsxs)("button",{className:o.shortcut,"data-testid":"shortcut-summary",onClick:()=>w.send("ShowCommandPalette",{isOpen:!0,page:"summary"}),children:[(0,V.jsx)(eE,{}),t("linkSummary")]}),l&&(0,V.jsxs)("button",{className:o.shortcut,"data-testid":"shortcut-knowledge-assist",onClick:()=>w.send("ShowCommandPalette",{isOpen:!0,page:"knowledgeAssist"}),children:[(0,V.jsx)(Jb,{}),t("linkKnowledgeSearch")]}),C&&(0,V.jsxs)("a",{className:o.shortcut,target:"_blank",href:C,"data-testid":"shortcut-studio-login",rel:"noreferrer",children:[(0,V.jsx)(Gb,{}),t("linkStudioLogin",{productName:k})]})]})}),s&&y.length>0&&(0,V.jsx)(Kn,{type:"custom-messages","data-testid":"custom-messages",children:(0,V.jsx)(xt,{withDivider:!0,children:y.map(N=>(0,V.jsx)(qb,{suggestion:N},N.text))})}),i&&d.length>0&&(0,V.jsx)(Kn,{type:"autoflows",title:t("titleAutoflows"),"data-testid":"autoflows",children:(0,V.jsx)(xt,{withDivider:!0,children:(0,V.jsx)(Kb,{})})}),p.map(({type:N,title:B,amount:be,lines:Ar})=>{var Ze;switch(N){case"entities":return f&&f.length>0&&(0,V.jsx)(Kn,{type:N,title:B,"data-testid":`type-${N}`,children:(0,V.jsx)(Wb,{entities:f})},N);default:return((Ze=_[N])==null?void 0:Ze.fetchState)==="done"&&_[N].suggestions.length>0&&(0,V.jsx)(Kn,{type:N,title:B,"data-testid":`type-${N}`,children:(0,V.jsx)(xt,{withDivider:!0,children:(0,V.jsx)(Yb,{lines:Ar,contentType:N,suggestions:_[N].suggestions.slice(0,be)||[]})})},N)}})]})})},rE=hA;function Ui(e){let t=new Range;return t.selectNodeContents(e),t}function oE(e,t,n){try{return Lr(e,t,n),!0}catch{return!1}}function Ld(e){return"tagName"in e&&(e.tagName==="DIV"||e.tagName==="P")}function Ad(e){return"tagName"in e&&e.tagName==="BR"}var Ua=/[\u200B-\u200D\uFEFF]/g;function Lr(e,t,n){let r=new Range;if(e.firstChild===null&&t===0&&n===0)return r.selectNodeContents(e),r;let o=0,i=!1;function s(l,u){let c=-1,p=/[\u200B-\u200D\uFEFF]/;if(!p.test(l))return u;for(let d=0;d<=l.length;d++)if(p.test(l[d])||c++,c===u)return d;throw new Error("Offset out of range")}function a(l){switch(l.nodeType){case Node.TEXT_NODE:{let u=l.textContent,c=u.replace(Ua,""),p=o+c.length,d=t>=o&&t<=p,f=n>=o&&n<=p;if(d){let y=s(u,t-o);y===0&&!f?r.setStartBefore(l):r.setStart(l,y)}f&&(r.setEnd(l,s(u,n-o)),i=!0),o=p;break}case Node.ELEMENT_NODE:{if(Ad(l)&&(o===t&&r.setStartBefore(l),o++,o===n)){r.setEndAfter(l),i=!0;return}for(let c=0;c<l.childNodes.length&&(a(l.childNodes[c]),!i);c++);let u=l.lastChild;Ld(l)&&u&&!Ld(u)&&!Ad(u)&&o++;break}default:break}}if(a(e),r.startContainer===document)throw new Error("Offsets out of bound");return r}function Ka(e,t){if(!e.contains(t.startContainer)||!e.contains(t.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:r,endContainer:o,endOffset:i,collapsed:s}=t,a,l,u=0;function c(p){let d=p===n,f=p===o;switch(p.nodeType){case Node.TEXT_NODE:{let y=p.textContent;d&&(a=u+y.substring(0,r).replace(Ua,"").length),f&&(l=u+y.substring(0,i).replace(Ua,"").length),u+=y.replace(Ua,"").length;break}case Node.ELEMENT_NODE:{let y=p.nextSibling===null;Ad(p)&&!y&&u++;for(let v=0;v<p.childNodes.length;v++){let m=d&&v===r,h=f&&v===i;if(m&&(a=u),h&&(l=u),l!==void 0||((!m||!s)&&c(p.childNodes[v]),f&&v===i-1&&(l=u),l!==void 0))break}!f&&Ld(p)&&!y&&u++,f&&(l=u);break}default:break}}if(c(e),l===void 0)throw new Error("Could not determine start and end");return{start:a??l,end:l}}function Va(e,t){if(!e.contains(t.startContainer)||!e.contains(t.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:r,endContainer:o,endOffset:i}=t,s=-1,a="";function l(u){let c=u===n,p=u===o;switch(c&&s++,u.nodeType){case Node.TEXT_NODE:{if(s!==0)return;let d=c?r:0,f=p?i:void 0,y=u.textContent.replace(Ua,"");d===0&&f===void 0?a+=y:a+=y.substring(d,f);break}case Node.ELEMENT_NODE:{let d=u.nextSibling===null;s===0&&Ad(u)&&!d&&(a+=`
24
24
  `);for(let f=c?r:0;f<(p?Math.min(i,u.childNodes.length):u.childNodes.length)&&(l(u.childNodes[f]),s!==1);f++);!p&&s===0&&Ld(u)&&!d&&(a+=`
25
- `);break}default:break}p&&s++}return l(e),a}function iE(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var bo=class extends kn{observer;lastKnownSelection=null;getRootNode(){return this.element.getRootNode()}getText(){let t=new Range;return t.selectNodeContents(this.element),Va(this.element,t)}getHTML(){return this.element.innerHTML||""}getRange(){var i;let t=this.getRootNode();if(t.activeElement!==this.element)return null;let n="getSelection"in t?t.getSelection():window.getSelection();if(!n)return null;let r="getComposedRanges"in n&&t instanceof ShadowRoot?(i=n.getComposedRanges(t))==null?void 0:i[0]:n.rangeCount>0?n.getRangeAt(0):null;if(!r)return null;let o=this.element.ownerDocument.createRange();return o.setStart(r==null?void 0:r.startContainer,r==null?void 0:r.startOffset),o.setEnd(r==null?void 0:r.endContainer,r==null?void 0:r.endOffset),!o||!this.element.contains(o.startContainer)||!this.element.contains(o.endContainer)?null:o}getCaretPosition(){let t=this.getRange();if(!t||!t.collapsed||!("getBoundingClientRect"in t))return null;let n=t.getBoundingClientRect();return!iE(n)&&(t.insertNode(this.element.ownerDocument.createTextNode("\u2060")),n=t.getBoundingClientRect(),t.deleteContents(),!iE(n))?null:{top:n.top+n.height,left:n.left}}getSelection(){let t=this.getRange();if(t)return Ka(this.element,t);let n=this.lastKnownSelection;if(n&&oE(this.element,n.start,n.end))return n;let r=Ui(this.element);return r.collapse(!1),Ka(this.element,r)}getSelectedText(){let{start:t,end:n}=this.getSelection();return Va(this.element,Lr(this.element,t,n))}applyChanges(t){var o;if(!this.isActive)return;this.isSettingValue=!0;let n=this.getText(),r=t(this.element);return(o=this.observer)==null||o.takeRecords(),Promise.resolve(r).then(()=>{this.currentText=this.getText(),n!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(){super.listen(),this.observer=new MutationObserver(()=>{setTimeout(()=>{this.triggerChange()},0)}),this.observer.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0});let t=this.element.isContentEditable,n=new MutationObserver(()=>{this.element.isContentEditable!==t&&(t=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});n.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>n.disconnect())}dispose(){super.dispose(),this.observer&&this.observer.disconnect()}};function sE(e,t,n){let r=`deepdesk-iframe-${e}`,o=document.getElementById(r);if(o)return o;let i=document.createElement("iframe"),s=new URL(t);return Object.entries(n).forEach(([a,l])=>{s.searchParams.append(a,l)}),i.style.position="absolute",i.style.left="-999em",i.style.width="0px",i.style.height="0px",i.tabIndex=-1,i.id=r,i.title=`iframe-${e}`,i.src=s.toString(),window.document.body.appendChild(i),i}var kh=class{constructor(t){this.name=t;this.broadcastChannel=new BroadcastChannel(t)}broadcastChannel;disposeHandlers=[];onMessage(t){this.broadcastChannel.addEventListener("message",t),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",t)})}postMessage(t){this.broadcastChannel.postMessage(JSON.stringify(t))}close(){this.disposeHandlers.forEach(t=>t()),this.broadcastChannel.close()}},Ph=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.iframe=sE(t,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}iframe;disposeHandlers=[];onMessage(t){window.addEventListener("message",t),this.disposeHandlers.push(()=>{window.removeEventListener("message",t)})}postMessage(t){var n;(n=this.iframe.contentWindow)==null||n.postMessage(JSON.stringify(t),this.targetOrigin)}close(){var t;this.disposeHandlers.forEach(n=>n()),(t=this.iframe)==null||t.remove()}},Ih=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.eventMap,this.sessionId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}sessionId;deepdeskUrl;channel;defaultChannel;eventMap;get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setSessionId(t){this.sessionId!==t&&(this.cleanup(),j.info("Set sessionId",t),this.sessionId=t,this.channel=this.createChannel(t))}createChannel(t){let n=this.params.createCustomChannel?this.params.createCustomChannel(t):this.isCrossOrigin?new Ph(t,this.deepdeskUrl,{debug:!0}):new kh(t),r=o=>{var s,a;if(o.origin!==this.deepdeskUrl)return;let i=typeof o.data=="string"?JSON.parse(o.data):o.data;i.type==="event"&&i.channel===t&&(j.info("Received broadcast event",this.sessionId,o),(a=(s=this.eventMap)[i.name])==null||a.call(s,i.payload))};return n.onMessage(r),n}send(t,n){var i,s;j.info("Broadcast event",{sessionId:this.sessionId,name:t,payload:n});let r={type:"event",name:t,payload:n};(s=(i=this.eventMap)[t])==null||s.call(i,n);let o=this.sessionId==="deepdesk-general"?this.defaultChannel:this.channel;o==null||o.postMessage({...r,channel:this.sessionId})}cleanup(t=!1){var n,r;(n=this.channel)==null||n.close(),delete this.channel,t&&((r=this.defaultChannel)==null||r.close(),delete this.defaultChannel)}},aE=Ih;var Ki=class extends Error{constructor(n,r){super(n);this.body=r}name="CustomError"};var Rh=e=>new Promise(t=>{setTimeout(t,e)});var Vi=class extends Ki{name="ClientError"},Lh=class extends Ki{name="ServerError"},Gt=class e{constructor(t="",n={}){this.baseUrl=t;this.options=n;n.fetch&&(this.fetch=n.fetch)}latestRequestByUrl={};csrfToken;fetch=window.fetch.bind(window);static refreshingToken=null;patchFetch(t){this.fetch=t(this.fetch)}setCsrfToken(t){this.csrfToken=t}request(t,n={}){return new Promise((r,o)=>{let i={isAborted:!1,reject:o},s=`${this.baseUrl}${t}`,a=this.fetch,{abortLatest:l=!1,attempts:u=1,retryDelay:c=500,refreshTokenOn401:p=!0,retryOnError:d=_=>_ instanceof TypeError,retryOnResponse:f=_=>_.status>=500,version:y="v1",...v}=n,m={credentials:"include",...v,headers:{"Content-Type":"application/json",...v.headers}};n.method!==void 0&&n.method!=="GET"&&this.csrfToken&&(m.headers={...m.headers,"X-CSRFToken":this.csrfToken}),typeof y=="string"&&(m.headers={...m.headers,"X-Deepdesk-API-Version":y});let h=u,g=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[s]&&l&&(this.latestRequestByUrl[s].isAborted=!0,this.latestRequestByUrl[s].reject(new Error("Aborted"))),this.latestRequestByUrl[s]=i;let x=async()=>(h--,a(s,m).then(async _=>f(_)&&!i.isAborted&&h>0?(await Rh(c),x()):_.status===401&&p===!0&&g===!1?(g=!0,await this.refreshToken(),x()):_).catch(async _=>{if(d(_)&&!i.isAborted&&h>0)return await Rh(c),x();throw _}));x().then(_=>_.json().catch(()=>null).then(w=>{_.status>=500?o(new Lh("Server Error",w)):_.status===401?o(new Vi("Unauthorized",w)):_.status===403?o(new Vi("Forbidden",w)):_.status===404?o(new Vi("Not Found",w)):_.status>=400&&o(new Vi("Bad Request",w)),delete this.latestRequestByUrl[s],r(w)})).catch(_=>{o(_)})})}async validateToken(){let{has_valid_access_token:t}=await this.get("/auth/validate");if(!t)return!1;let{is_logged_in:n}=await this.get("/apis/admin/session/validate/",{version:null});return!!n}refreshToken(){return e.refreshingToken||(e.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{e.refreshingToken=null},1e3*60)})),e.refreshingToken}get(t,n){return this.request(t,n)}post(t,n,r){return this.request(t,{method:"POST",body:JSON.stringify(n),...r})}patch(t,n,r){return this.request(t,{method:"PATCH",body:JSON.stringify(n),...r})}put(t,n,r){return this.request(t,{method:"PUT",body:JSON.stringify(n),...r})}delete(t,n){return this.request(t,{method:"DELETE",...n})}};var yA;(t=>{let e;(l=>(l.SEND_MESSAGE="Send Message",l.HANDLING_TIME="Handling Time",l.START_AUTOFLOW="Start Autoflow",l.ABORT_AUTOFLOW="Abort Autoflow",l.ADD_TO_PERSONAL_COLLECTION="Add to personal collection",l.DELETE_FROM_PERSONAL_COLLECTION="Delete from personal collection"))(e=t.EventType||={})})(yA||={});function Od(e){return{...Z(e),tags:e.tags}}var zn=class e{constructor(t,n={}){this.options=n;this.client=new Gt(t,{fetch:n.fetch}),this.client.patchFetch(r=>async(o,i)=>{let s=await r(o,i);return this.handleDeepdeskVersionHeaders(s),s})}latestReceivedDeepdeskVersions={};client;shouldFetchCsrfToken=!0;static exchangeTokenPromise=null;async preflight(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=await this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(e.exchangeTokenPromise||(e.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),e.exchangeTokenPromise):Promise.resolve()}async createConversation(t){await this.preflight(),j.info(`Creating conversation for session ${t.sessionId} and agent ${t.agentId}`);let n=await this.client.post("/api/conversations",{...ke(t),tags:t.tags},{version:"v2"});return Od(n)}async getProfile(t){let n=await this.client.get(`/apis/admin/profiles/${t}/`,{version:null});return Z(n)}async getKnowledgeAssistant(t){let n=await this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{version:null});return Z(n)}async getContentTypes(){let t=await this.client.get("/apis/admin/content-types/",{version:null});return Z(t)}async getPlatformConfig(){let{config:t}=await this.client.get("/platform/config/",{version:null});return Z(t)}async checkUserExists(t){let{exists:n}=await this.client.get(`/apis/admin/users/exists?external_id=${t}`);return n}async getConversationBySessionId(t,n={}){await this.preflight(),j.info(`Getting conversation for session ${t}`);let{attempts:r=1,retryDelay:o=1e3}=n,i=await this.client.get(`/api/conversations/by_session_id/${t}`,{attempts:r,retryDelay:o,retryOnResponse:s=>s.status===404||s.status>=500,version:"v2"});return Od(i)}async isConversationSupported(t,n={}){j.info(`Check if conversation for session ${t} is supported`);let{attempts:r=1,retryDelay:o=1e3}=n;return(await this.client.get(`/api/conversations/by_session_id/${t}/active_profile`,{attempts:r,retryDelay:o,retryOnResponse:s=>s.status===404||s.status>=500,version:"v2"})).has_active_profile}async updateConversation(t,n){let r=ke(n);n.tags&&(r.tags=n.tags);let o=await this.client.put(`/api/conversations/${t}`,r,{version:"v2"});return Od(o)}async postMessages(t,n){return(await this.client.post(`/api/conversations/${t}/messages`,n.map(o=>({...ke(o),tags:o.tags})),{version:"v2"})).map(o=>Od(o))}async sendEvent(t,n){let{data:r,...o}=n,i=Object.entries(this.latestReceivedDeepdeskVersions).reduce((s,[a,l])=>({...s,[a]:l}),{});return this.client.post("/api/events",ke({...i,...o,data:r,name:t}),{version:"v2"})}async sendEventV1(t,n){let r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((o,[i,s])=>({...o,[i]:s}),{});return this.client.post("/api/events",{event:t,data:ke({...n,...r})})}async getEntities(t){return(await this.client.post("/api/entities",{messages:t.filter(r=>r.text)})).entities}async getSummary(t,n={}){return(await this.client.post("/api/summary",{conversation:{messages:t.filter(o=>o.text&&o.source),agent_id:n.agentId,id:n.externalConversationId},prompt_instruction:n.promptInstruction,model:n.model})).summary}async getTemporaryExchangeToken(){return(await this.client.get("/auth/exchange-token",{version:null})).jwt}async exchangeTokenForAccessCookie(t){return this.client.post("/apis/admin/session/jwt/",{jwt:t},{version:null}).catch(n=>{throw j.warn(`Invalid token '${t}'`),n})}async authenticateWithKey(t,n){await this.client.post("/apis/admin/session/api-key/",ke(n),{version:null,refreshTokenOn401:!1,headers:{apikey:t}})}async getTextSuggestions(t,n={},r){return r==="sticky-messages"?this.getPinnedMessages(t):(await this.client.post(`/api/conversations/${t}/recommend/${r}`,ke(n),{abortLatest:!0})).map(i=>({...Z(i),text:i.text||i.url||i.message,source:r,type:r})).filter((i,s,a)=>s===a.findIndex(l=>l.text===i.text))}async isLoggedIn(){return await this.preflight(),this.client.validateToken()}async getAutocompleteSuggestions(t,n){return(await this.client.post(`/api/conversations/${t}/autocomplete`,ke(n),{abortLatest:!0})).map(o=>({score:1,source:o.source,sourceText:o.source_text,text:o.label,trainingJobs:o.training_jobs,searchKeywords:o.search_keywords,type:o.source})).filter((o,i,s)=>i===s.findIndex(a=>a.text===o.text))}async getPinnedMessages(t){let n=await this.client.get(`/api/conversations/${t}/sticky-messages`,{abortLatest:!0});return Z(n).map(r=>({...r,text:r.message,source:"sticky-messages",type:"pinned-message"}))}async getStyleSuggestions(t){let n=await this.client.post("/api/style-suggestions",ke(t),{abortLatest:!0});return Z(n)}async search(t){let n=await this.client.post(`/api/profiles/${t.profile}/search`,ke(t),{version:"v2"});return Z(n)}async knowledgeAssist(t,n,r){let o=await this.client.post(`/api/knowledge-assist/assistants/${r}/search`,ke({question:t.question,promptInstruction:t.promptInstruction,chatHistory:n.map(i=>({question:i.question,answer:i.answer.answer}))}),{version:"v2"});return Z(o)}async requestLoginByEmail(t){let n=await this.client.post("/apis/admin/session/passwordless/request/",{email:t},{version:null});return Z(n)}async requestPasswordlessToken(){let t=await this.client.get("/apis/admin/session/passwordless/request/",{version:null});return Z(t.token)}async getCsrfToken(){let{token:t}=await this.client.get("/apis/admin/session/csrf/",{version:null});return t}async verifyLoginToken(t){let n=await this.client.post("/apis/admin/session/passwordless/login/",{token:t},{version:null});return Z(n)}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),i=o.match(Cy);if(!n||!i)return;let s=i[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[s];a&&n&&a!==n&&j.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[s]=n})}};var Wa=class{constructor(t,n){this.url=t;this.options={timeout:25e3,...n}}eventListeners={};options;timeoutTimer;eventSource;proxyEvent(t){this.eventSource.addEventListener(Mg(t),n=>{let{data:r}=n;try{let o=JSON.parse(r);this.emit(t,Z(o))}catch{j.warn(`Invalid JSON for ${t}: ${r}`)}})}connect(){clearTimeout(this.timeoutTimer);let t=new EventSource(this.url,{withCredentials:!0});this.eventSource=t;let n=!1;t.onopen=()=>{n=!0},t.onerror=()=>{n&&t.readyState===2&&this.connect()},this.timeoutTimer=setTimeout(()=>{t.close(),this.connect()},this.options.timeout),Object.keys(this.eventListeners).forEach(r=>{this.proxyEvent(r)})}disconnect(){var t;clearTimeout(this.timeoutTimer),this.eventListeners={},(t=this.eventSource)==null||t.close()}emit(t,n){this.eventListeners[t]&&this.eventListeners[t].forEach(r=>r(n))}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),this.proxyEvent(t),()=>{this.off(t,n)}}off(t,n){let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}};var vA;(t=>{let e;(i=>(i.Started="Started",i.Aborted="Aborted",i.Completed="Completed"))(e=t.AutoflowSessionState||={})})(vA||={});var $a=class{constructor(t,n={}){this.apiUrl=t;this.client=new Gt(t,n)}client;streams={};logger=j;async getCustomMessages(t){let n=await this.client.get(`/sessions/${t}/suggestions`);return Z(n.suggestions)}async sendCustomMessage(t,n){let r=await this.client.post(`/sessions/${t}/messages`,ke(n));return Z(r)}async answerCustomMessage(t,n){await this.client.post(`/sessions/${t}/answers`,ke(n))}async getAutoflows(t){let n=await this.client.get(`/sessions/${t}/autoflows`);return Z(n.autoflows)}async startAutoflowSession(t){let n=await this.client.post("/autoflow-sessions",ke(t));return Z(n)}async stopAutoflowSession(t){await this.client.delete(`/autoflow-sessions/${t}`)}openStream(t){return this.streams[t]||(this.streams[t]=new Wa(`${this.apiUrl}/sessions/${t}/events`),this.streams[t].connect()),this.streams[t]}closeStream(t){this.streams[t]||(this.streams[t].disconnect(),delete this.streams[t])}};var lE={startTime:null,stopTime:null},uE=z({name:"handlingTime",initialState:lE,reducers:{handlingTimeStart(e){if(e.startTime&&!e.stopTime)throw new Error("Timing already started");e.startTime=new Date,e.stopTime=null},handlingTimeStop(e){if(!e.startTime)throw new Error("Timing not started");e.stopTime=new Date},handlingTimeReset(e){e.startTime=null,e.stopTime=null}},extraReducers:e=>{e.addCase(te,()=>lE)}}),{handlingTimeStart:cE,handlingTimeStop:Nd,handlingTimeReset:dE}=uE.actions,pE=uE.reducer;var fE=(e={})=>{let t={onAuthError:Oi(!1),...e};return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var Md={list:{keywordMatches:[]},fetchState:"idle",isInitialRequest:null};var Eo=D("styleSuggestions/getAll",async({text:e},t)=>{var s;let{deepdeskAPI:n}=t.extra,r=t.getState(),{showStyleSuggestions:o}=r.settings,i=(s=r.conversation.current)==null?void 0:s.profileCode;if(!o)return Md.list;if(!i)throw new Error("No current conversation to fetch pinned messages");return n.getStyleSuggestions({profileCode:i,message:e})}),SA=z({name:"styleSuggestions",initialState:Md,reducers:{},extraReducers:e=>{e.addCase(Eo.pending,t=>{t.isInitialRequest=t.isInitialRequest===null,t.fetchState="loading"}).addCase(Eo.rejected,t=>{t.fetchState="error"}).addCase(Eo.fulfilled,(t,n)=>{t.fetchState="done",hr(t.list,n.payload)||(t.list=n.payload)}).addCase(no,t=>{t.list=Md.list}).addCase(te,()=>Md)}}),mE=SA.reducer;var gE=(e={})=>{let t,n=!0,r={getStyleSuggestions:Eo,debounce:500,...e};return o=>i=>s=>{var f;let a=o.getState().input.text,l=i(s),u=o.getState();if(u.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:c}=u.settings;if(!((f=u.conversation.current)==null?void 0:f.id)||!c)return l;let{text:d}=u.input;return d===a&&!n||(clearTimeout(t),d==="")||(t=setTimeout(()=>{n=!1,o.dispatch(r.getStyleSuggestions({text:d}))},e.debounce)),l}};function xA(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var hE=(e={})=>{let t={getTextSuggestions:Vt,getAutocompleteSuggestions:Ea,debounce:200,check:ji,...e},n;return r=>o=>i=>{var v;let{input:{userCommitted:s}}=r.getState(),a=o(i),l=r.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:u,showTabCompletion:c}=l.settings,p=(v=l.conversation.current)==null?void 0:v.id,d=i.type===rd.toString();if(!p||!u&&!c)return a;let{input:{userCommitted:f}}=l;return xA(f,s)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let m=xi(l);m===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(m))},d?0:t.debounce)),a}};var yE=Eo.fulfilled.toString();function _A(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let i=e.keywordMatches.filter(l=>l.keyword===o),s=t.keywordMatches.filter(l=>l.keyword===o),a=s.length-i.length;a<=0||r.push(...s.slice(0,a))}),r}var vE=e=>t=>n=>r=>{var u;if(r.type!==yE){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let i=t.getState(),s=i.styleSuggestions.list,a=(u=i.conversation)==null?void 0:u.current;if(o===s)return;let l=_A(o,s);r.type===yE&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var wA=Iu({activeSuggestion:Rw,answer:w1,auth:Kw,autoflows:Sb,conversation:qx,contentTypes:o1,customMessages:Pb,passwordlessToken:Ab,entities:l1,knowledgeAssistant:S1,handlingTime:pE,info:iw,input:Jm.reducer,overlayInput:rt.reducer,settings:jx,profile:C1,search:dw,summary:m1,styleSuggestions:mE,ui:Nw,textSuggestions:Cw});function SE(e){return V0({reducer:wA,middleware:t=>[...t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI,deepdeskBrokerAPI:e.deepdeskBrokerAPI}},serializableCheck:!1}),fE(),hE({debounce:200}),gE({debounce:500}),vE(e.deepdeskAPI),...e.middleware?e.middleware:[]],preloadedState:e.preloadedState})}var bA=e=>{var t;return((t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())??"unknown"},EA=e=>t=>n=>r=>{var a;let o=t.getState(),i=qm("inlineSuggestions")(o);switch(r.type){case Rn.toString():{let l=nd(r.payload.contentType)(t.getState()),u=l.indexOf(r.payload.suggestion);e.emit("edit-suggestion",{contentType:r.payload.contentType,index:u,suggestions:l});break}case Oi.toString():{!r.payload&&e.emit("logout",void 0);break}case Bt.toString():{let{start:l,end:u}=o.input.selection;e.emit("select-suggestion",{type:bA(r.payload.suggestion),...r.payload,replace:r.payload.replace==="selection"?{start:l,end:u}:{start:0,end:u}},{mayApplyChanges:!0});break}case fc.toString():{let{start:l,end:u}=o.input.selection;e.emit("replace",{...r.payload,replace:r.payload.replace==="selection"?{start:l,end:u}:{start:0,end:u}},{mayApplyChanges:!0});break}case sa.toString():{let l=t.getState(),{text:u,selection:c}=l.input.userCommitted;e.emit("reset",{text:u,selectionAfter:c},{mayApplyChanges:!0});break}case yc.toString():e.emit("select-image",r.payload,{mayApplyChanges:!0}),e.sendEvent("Image attached",{conversationId:o.conversation.current.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case $t.fulfilled.toString():r.payload.length>0&&e.sendEvent("entities found",{conversationId:o.conversation.current.id,data:{entities:r.payload}});break;case On.fulfilled.toString():e.sendEvent("conversation summarized",{conversationId:o.conversation.current.id,data:{summary:r.payload.summary}});break;case Be.toString():e.sendEvent(r.payload.name,{conversationId:((a=r.payload.options)==null?void 0:a.includeConversationData)&&o.conversation.current.id,data:r.payload.data});break;case mc.toString():e.handleKeyDown(r.payload);break;case no.toString():e.logSendMessage(r.payload);break;case gc.toString():e.logSendEditSuggestionMessage(r.payload);break;case hc.toString():e.handleInputChanged(r.payload);break;default:break}let s=n(r);switch(r.type){case no.toString():e.handleAfterSendMessage(r.payload);break;case Ca.toString():e.onUpdateShowTabHint(r.payload);break;case Nd.toString():e.logHandlingTime();break;case Bt.toString():{i&&(t.dispatch(on([])),t.dispatch(wn()));break}case on.toString():{i&&r.payload.length>0&&t.dispatch(vr(0));break}default:break}return s},xE=EA;function Ah(e){return e.toISOString().replace("T"," ").replace("Z","")}function _E(e,t){var o,i,s;let{startTime:n,stopTime:r}=e.handlingTime;if(!n||!r)throw new Error("No startTime and stopTime for handling time metrics");return{conversationId:e.conversation.current.id,clientVersion:t.version,agentId:(o=e.info.agentInfo)==null?void 0:o.agentId,agentName:(i=e.info.agentInfo)==null?void 0:i.agentName,agentEmail:(s=e.info.agentInfo)==null?void 0:s.agentEmail,timeStart:Ah(n),timeStop:Ah(r)}}function Oh(e,t,n){var C,I,k;let{text:r,metrics:{numCharsTyped:o,numCharsPasted:i,numCharsCut:s,numCharsDeleted:a,numPaste:l,agentStartedTypingTimestamp:u,externalTimeTotalSeconds:c,pastes:p,cuts:d,deletions:f,textSuggestions:y,offeredTextSuggestions:v}}=t[e],m=r.length,g=y.reduce((K,{text:N,searchTerm:B})=>K+N.length-(B?B.length:0),0),x=u??Date.now(),_=(Date.now()-x)/1e3+(c||0),w=o/_,E=y.reduce((K,{searchTerm:N})=>K+(N?N.length:0),0);return{conversationId:t.conversation.current.id,source:"agent",text:r,clientVersion:n.version,pastes:p,cuts:d,deletions:f,lenTextTyped:o+E,lenTextTotal:m,lenTextAssisted:g,lenTextPasted:i,lenTextCut:s,lenTextDeleted:a,timeTotalSeconds:_,charsPerSecond:w,numPastes:l,textSuggestionsV2:y,suggestionsCounters:[{source:"gpt",countOffered:v.filter(K=>K.source==="gpt").length}],agentId:(C=t.info.agentInfo)==null?void 0:C.agentId,agentName:(I=t.info.agentInfo)==null?void 0:I.agentName,agentEmail:(k=t.info.agentInfo)==null?void 0:k.agentEmail}}function Nh(e,t){var i;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return Nh(r,t);let o=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;return o?Nh(o,t):null}function wE(e,t){return Nh(e,t)}function bE(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function CA(e){return typeof e=="object"&&e!==null&&"tagName"in e}function Dd(e){return CA(e)&&(Pr(e)||zc(e))}var EE=(e,t)=>({value(){try{let n=sessionStorage.getItem(`dd-${e}`);if(!n)return t;try{return JSON.parse(n)}catch{return t}}catch{return t}},update(n){try{sessionStorage.setItem(`dd-${e}`,JSON.stringify(n))}catch{j.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function TA(e){return e.offsetParent!==null}function CE(e){if(!TA(e))return!1;let t=e.getBoundingClientRect();return t.top>=0&&t.left>=0&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&t.right<=(window.innerWidth||document.documentElement.clientWidth)}function Fd(e,t,n=100){let r=CE(e);t({isVisible:r});let o=setInterval(()=>{let i=CE(e);i!==r&&(r=i,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var we=S(b());var TE=EE("showTabHint",!0),qa=class e{static version="10.10.3-beta.6";static count=0;deepdeskApi;inputMediator=null;version;broadcastEvents;eventListeners={};unmountHandlers=[];widgetRoot=null;dynamicThunkObject={};isMounted=!1;instanceId;shouldRender=!0;store;constructor({deepdeskUrl:t,brokerUrl:n,version:r=e.version||"unknown",locale:o="en-US",token:i,fetch:s,productName:a,createCustomChannel:l}){let u=t.replace(/\/api$/,"");this.deepdeskApi=new zn(u,{token:i,fetch:s}),this.version=r,this.instanceId=e.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[xE({emit:(p,d,f)=>this.emit(p,d,f),handleAfterSendMessage:p=>this.handleAfterSendMessage(p),handleInputChanged:p=>this.handleInputChanged(p),handleKeyDown:p=>this.handleKeyDown(p),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:p=>this.logSendMessage(p),logSendEditSuggestionMessage:p=>this.logSendEditMessage(p),onUpdateShowTabHint:p=>TE.update(p),sendEvent:(p,d)=>this.deepdeskApi.sendEvent(p,d)})]};n&&Object.assign(c,{deepdeskBrokerAPI:new $a(n)}),this.store=SE(c),this.broadcastEvents=new aE({debug:!0,deepdeskUrl:u,eventMap:Vw(this.store),createCustomChannel:l}),this.store.dispatch(oa),this.store.dispatch(Ca(TE.value())),this.store.dispatch(oa({locale:o,adminUrl:u,productName:a}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){return this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex]??null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(j.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(j.warn("Profile has not been loaded (yet)"),!0):(j.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(Oi(null)),this.store.dispatch(Ln()),new Promise(t=>{let n=this.store.subscribe(()=>{let r=this.store.getState();Ge(r)&&Fw(r)!=="loading"&&(n(),t())});this.unmountHandlers.push(()=>{n()})})}async isLoggedIn(){return(await this.store.dispatch(Ln())).payload}async setPlatformAgentId(t){try{if((await this.deepdeskApi.client.get("/apis/admin/session/me/",{version:null})).external_id)return;await this.deepdeskApi.client.request("/apis/admin/session/me/",{method:"PATCH",body:JSON.stringify({external_id:t}),version:null})}catch(n){j.warn("Failed to attach user:",n)}}async isConversationSupported(t,n){return(await this.store.dispatch(Ym({sessionId:t,options:n}))).payload}async createConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(ac(t))).payload}async getConversationBySessionId(t,n){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(await this.store.dispatch(lc({sessionId:t,options:n}))).payload}async upsertConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(Zm(t))).payload}async postMessages(t){return(await this.store.dispatch(cc(t))).payload}async updateConversation(t){return(await this.store.dispatch(uc(t))).payload}resetConversation(){this.store.dispatch(te()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}async getSummary(){let t=await this.store.dispatch(On());if(t.error)throw new Error(t.error.message);return t.payload.summary}configure(t){this.store.dispatch(oa(t))}setVisitorInfo(t){this.store.dispatch(ow(t))}async setAgentInfo(t){await this.store.dispatch(xa(t))}async setAgentSettings(t){await this.store.dispatch(Dg(t))}async getAgentSettings(){return(await this.store.dispatch(Fg())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let t=[];return this.store.dispatch(rd()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})}notifyInputChanged(t){this.store.dispatch(hc(t))}notifyKeyDown(t){this.store.dispatch(mc(t))}notifyPaste(t,n){this.store.dispatch(o_({text:t,selectionText:n}))}notifyCut(t){this.store.dispatch(n_(t))}notifyExternalSuggestion(t){this.store.dispatch(Bt(t)),this.store.dispatch(wn())}notifyEditSuggestion(t){this.store.dispatch(bw(t.contentType,t.suggestions)),this.store.dispatch(Rn({contentType:t.contentType,suggestion:typeof t.index=="number"?t.suggestions[t.index]:null}))}handleInputChanged(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui;n&&r&&this.store.dispatch(Er({collapse:!1})),this.inputMediator&&this.store.dispatch(Qx({text:t,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(on([])))}handleKeyDown(t){let{overlayCollapsed:n}=this.state.ui,{textSuggestions:r,selectedSuggestionIndex:o,selection:i}=this.state.input,{inlineSuggestions:s}=this.state.settings,a=r.length>0,l=o!==-1;if(this.store.dispatch(r_(pc(t))),t.key!=="Tab"&&!this.settings.showTextSuggestions)return;let u=()=>{n||!a||i&&(t.shiftKey||(this.store.dispatch(Jx()),s||this.stageSelectedSuggestion({inputType:"arrow"}),t.preventDefault()))},c=()=>{n||!a||s&&o<=0||i&&(t.shiftKey||(this.store.dispatch(t_()),t.preventDefault(),!s&&(this.state.input.selectedSuggestionIndex===-1?this.store.dispatch(sa()):this.stageSelectedSuggestion({inputType:"arrow"}))))};switch(t.key){case"Up":case"ArrowUp":s?c():u();return;case"Down":case"ArrowDown":{s?u():c();return}case"Esc":case"Escape":{s&&l&&this.store.dispatch(vr(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(vr(-1)),this.store.dispatch(sa()),t.preventDefault()):n||(this.store.dispatch(Er({collapse:!0})),this.store.dispatch(Aw(!0)),t.preventDefault());return}case"Tab":{let{userCommitted:p}=this.state.input,d=p.text.substring(0,p.selection.end),{tabCompletionSuggestion:f}=this.state.input;this.store.dispatch(Ca(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!s&&this.settings.showTabCompletion&&f&&f.text.startsWith(d)&&(this.store.dispatch(Bt({text:f.text,suggestion:f,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch(wn())),t.preventDefault();break}default:}}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(i_()),this.store.dispatch(on([]))}handlingTimeStart(){this.state.handlingTime.startTime||(j.info("Start handling time"),this.store.dispatch(cE()))}handlingTimeStop(){this.state.handlingTime.startTime&&(j.info("Stop handling time"),this.store.dispatch(Nd()))}logSendMessage(t){let n=Oh("input",this.state,{version:this.version});t&&(Object.assign(n,{text:t}),Object.assign(n,{lenTextTotal:t.length})),this.deepdeskApi.sendEventV1("Send Message",n),this.emit("send-message-event",n)}logSendEditMessage(t){let n=Oh("overlayInput",this.state,{version:this.version});t&&Object.assign(n,{text:t}),this.store.dispatch(Zx(this.state.overlayInput.metrics))}logHandlingTime(){let t=_E(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch(dE())}notifySubmit(t={}){this.shouldAbort()||(this.store.dispatch(wn()),this.store.dispatch(no(t.text??this.state.input.text)))}stageSelectedSuggestion(t){let n=this.state.input.selectedSuggestionIndex,{textSuggestions:r}=this.state.input;this.store.dispatch(Bt({text:r[n].text,suggestion:r[n],eventMetrics:t,replace:"until-selection-end"}))}emit(t,n,r={}){let o=()=>{this.eventListeners[t]&&this.eventListeners[t].forEach(i=>{try{i(n)}catch(s){j.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),j.error(s)}})};this.inputMediator&&r.mayApplyChanges?this.inputMediator.applyChanges(o):o()}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),()=>{this.off(t,n)}}off(t,n){if(!t&&!n){this.eventListeners={};return}let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}setConversationQuery(t){this.dynamicThunkObject.conversationQuery=t}whenConversationLoaded(t){let n=()=>this.loadProfileConfig().then(()=>t());this.hasConversation()&&n();let r=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==r&&(r=this.hasConversation(),r&&n())})}overlayContainerFactory(t,n,r,o){let[i,s]=lo(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),this.unmountHandlers.push(()=>{(0,Nt.unmountComponentAtNode)(i),s(),i.remove()}),i}createInlineContainer(t,n){var s;let r=document.createElement("div");r.style.position="absolute",r.style.top="0px",r.style.left="0px",r.style.height="0px",r.style.width="0px";let o=document.createElement("div");o.style.display="none",o.style.position="absolute",o.style.height="0px",o.style.width="0px",o.style.backgroundColor="red",r.appendChild(o);let i=(s=t.ownerDocument.defaultView)==null?void 0:s.frameElement;if(i){let[a,l]=lo(i,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});a.dataset.testid=n,a.style.zIndex="2",a.appendChild(r),this.unmountHandlers.push(()=>{(0,Nt.unmountComponentAtNode)(o),l()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return ao(o),o.dataset.testid=t,o.style.color=r.color,o.style.fontSize=r.fontSize,o.style.fontFamily=r.fontFamily,o.style.fontVariant=r.fontVariant,o.setAttribute("translate","no"),n.appendChild(o),this.unmountHandlers.push(()=>{(0,Nt.unmountComponentAtNode)(o),o.remove()}),o}storeMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(t,n),j.info(`Stored analytics for ${this.conversationId()}`)}catch{}}restoreMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=window.sessionStorage.getItem(t);if(!n)return;let r=JSON.parse(n);r.text.trim()===this.state.input.text.trim()?(j.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(a_(r.metrics))):j.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(t)}catch{}}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!Dd(t))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let{customStyles:r={},showStyleSuggestions:o,showTabCompletion:i,showTextSuggestions:s,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,isEmbedded:p,detectSubmit:d,insertLink:f,inputMediator:y,closestScrollSelector:v,appendOverlayTo:m,inlineSuggestions:h,floatingMenu:g}=n;this.configure({showStyleSuggestions:o,showTabCompletion:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,showTextSuggestions:s,insertLink:f,isEmbedded:p,inlineSuggestions:h,floatingMenu:!!g}),n.automaticHandlingTime&&this.setupHandlingTime(t),ao(t),this.inputMediator=y||(Pr(t)?new Pn(t):new bo(t)),this.inputMediator.on("change",({plainText:w})=>{this.notifyInputChanged(w)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(s_({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",w=>{this.notifyKeyDown(w)}),this.inputMediator.on("paste",({pastedText:w,selectionText:E})=>{this.notifyPaste(w,E)}),this.inputMediator.on("cut",({selectionText:w})=>{this.notifyCut(w)});let x=v&&wE(t,v)||void 0;if(h){let{customStyles:w,appendOverlayTo:E}=n;if(Pr(t))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let C=this.createInlineContainer(t,"deepdesk-caret");(0,Nt.render)((0,we.jsx)(wo,{store:this.store,customStyles:w,children:(0,we.jsx)(yo,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(K1,{})})}),C),this.inputMediator.on("caret",k=>{this.store.dispatch(on([])),k?(C.style.display="block",C.style.top=`${k.top}px`,C.style.left=`${k.left}px`):C.style.display="none"});let I=this.overlayContainerFactory("floating-menu",x||t,{appendTo:typeof g=="object"&&"appendOverlayTo"in g?g.appendOverlayTo:E},w==null?void 0:w.floatingMenuRootNode);(0,Nt.render)((0,we.jsx)(wo,{store:this.store,customStyles:w,children:(0,we.jsx)(yo,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(F1,{onLogIn:()=>this.loginViaPopup().catch(k=>j.warn(k.message))})})}),I)}else{let w=this.overlayContainerFactory("deepdesk-tab-completion",x||t,{appendTo:m,closestScrollElement:x,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),E=this.overlayContainerFactory("deepdesk-suggestions-overlay",x||t,{appendTo:m},r==null?void 0:r.suggestionsRootNode);(0,Nt.render)((0,we.jsx)(wo,{store:this.store,customStyles:r,children:(0,we.jsx)(yo,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(fb,{inputElement:t})})}),w),(0,Nt.render)((0,we.jsx)(wo,{store:this.store,customStyles:r,children:(0,we.jsx)(yo,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(Y1,{onLogIn:()=>this.loginViaPopup().catch(C=>j.warn(C.message))})})}),E)}(0,Nt.render)((0,we.jsx)(wo,{store:this.store,customStyles:r,children:(0,we.jsx)(yo,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(A1,{})})}),this.createContainer("deepdesk-overlays"));let _;this.inputMediator.on("selection",w=>{clearTimeout(_),w===null?_=setTimeout(()=>{w!==null&&this.store.dispatch(eg(w))},500):this.store.dispatch(eg(w))}),this.inputMediator.on("disabled",()=>{var w;(w=this.inputMediator)==null||w.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{d&&this.notifySubmit()}),this.inputMediator.on("blur",()=>this.store.dispatch(Ai(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(Ai(!0))),this.store.dispatch(Yx({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.unmountHandlers.push(()=>{this.state.input.text!==""&&(this.store.dispatch(wn()),this.storeMetrics())}),this.whenConversationLoaded(()=>{var w;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((w=this.state.conversation.current)==null?void 0:w.sessionId)}),this.isMounted=!0}unmount(){var t;this.unmountHandlers.forEach(n=>n()),this.unmountHandlers=[],(t=this.inputMediator)==null||t.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(t,n={}){if(this.widgetRoot&&j.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:i}=n;this.widgetRoot=t,this.configure({showImages:o,isEmbedded:i}),(0,Nt.render)((0,we.jsx)(wo,{store:this.store,customStyles:r,children:(0,we.jsx)(yo,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(rE,{onLogIn:()=>this.loginViaPopup().catch(s=>j.warn(s.message))})})}),t),this.whenConversationLoaded(()=>{var s;this.broadcastEvents.setSessionId((s=this.state.conversation.current)==null?void 0:s.sessionId)})}unmountWidget(){this.widgetRoot&&(0,Nt.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(t){let n=Fd(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){bE(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(Da());let t=Tr(this.state);t&&(await this.store.dispatch(Na()),this.store.dispatch(oa({showSearch:t.search,showAutoflows:t.autoflows,showCustomMessages:t.customMessages,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:t.summarizer,showKnowledgeSearch:!!t.knowledgeAssistant,recommendTextSuggestions:t.recommendTextSuggestions})))}),this.loadProfileConfigPromise)}async loginViaPopup(t){return new Promise((n,r)=>{let o=new MessageChannel,i=o.port1,s=this.state.settings.adminUrl,a=new URL(t!=null&&t.url?t==null?void 0:t.url:`${s}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let l=!1,u=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",p),clearInterval(d)};i.onmessage=async f=>{var y,v;if((y=f.data)!=null&&y.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((v=f.data)==null?void 0:v.jwt),await this.isLoggedIn(),this.broadcastEvents.send(Pa),l=!0,o.port1.close(),n()}catch(m){console.error(m),r(m)}finally{l=!0,u()}};let c=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");c===null&&r(new Error("Popup blocked by browser"));let p=async f=>{var y;if(f.origin===a.origin)switch((y=f.data)==null?void 0:y.type){case"deepdesk-popup-loaded":{try{let v=JSON.stringify({type:"deepdesk-popup-create-channel"});c==null||c.postMessage(v,a.origin,[o.port2])}catch(v){j.error("Error posting message to popup",v),r(v)}break}case"deepdesk-popup-error":{u(),f.data.message==="Timeout"&&j.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(f.data.message));break}}};window.addEventListener("message",p);let d=setInterval(()=>{c&&!c.closed||(u(),l||r(new Error("Popup closed by user")))},200);this.unmountHandlers.push(u)})}async checkForTrialMode(t){try{let{account:n}=await this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(j.info("Trial is active"),!await this.deepdeskApi.checkUserExists(t))throw new Error("User is not in trial");this.shouldRender=!0}catch(n){let{message:r}=n;j.info(r),this.shouldRender=!1}}async refreshWidgetSuggestions(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=ad(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch($t()):this.store.dispatch(Vt(r))})}catch(r){this.handleError(r)}}};async function kE(e,t,n={}){let{value:r}=e,{start:o,end:i}=n.replace??{start:0,end:r.length},s=`${r.slice(0,o)}${t}${r.slice(i)}`,a=n.selectionAfter??{start:o+t.length,end:o+t.length},l=()=>{if(n.setValue)return n.setValue(s);e.value=s};return Promise.resolve(l()).then(()=>{e.selectionStart=a.start,e.selectionEnd=a.end,e.blur(),e.focus()})}async function PE(e,t,n={}){let r=n.replace?Lr(e,n.replace.start,n.replace.end):Ui(e),o,i=()=>{if(n.setRange)return n.setRange(r.cloneRange());r.deleteContents(),o=document.createElement("span"),r.insertNode(o),n.insertBRs!==!1?t.split(`
25
+ `);break}default:break}p&&s++}return l(e),a}function iE(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var bo=class extends kn{observer;lastKnownSelection=null;getRootNode(){return this.element.getRootNode()}getText(){let t=new Range;return t.selectNodeContents(this.element),Va(this.element,t)}getHTML(){return this.element.innerHTML||""}getRange(){var i;let t=this.getRootNode();if(t.activeElement!==this.element)return null;let n="getSelection"in t?t.getSelection():window.getSelection();if(!n)return null;let r="getComposedRanges"in n&&t instanceof ShadowRoot?(i=n.getComposedRanges(t))==null?void 0:i[0]:n.rangeCount>0?n.getRangeAt(0):null;if(!r)return null;let o=this.element.ownerDocument.createRange();return o.setStart(r==null?void 0:r.startContainer,r==null?void 0:r.startOffset),o.setEnd(r==null?void 0:r.endContainer,r==null?void 0:r.endOffset),!o||!this.element.contains(o.startContainer)||!this.element.contains(o.endContainer)?null:o}getCaretPosition(){let t=this.getRange();if(!t||!t.collapsed||!("getBoundingClientRect"in t))return null;let n=t.getBoundingClientRect();return!iE(n)&&(t.insertNode(this.element.ownerDocument.createTextNode("\u2060")),n=t.getBoundingClientRect(),t.deleteContents(),!iE(n))?null:{top:n.top+n.height,left:n.left}}getSelection(){let t=this.getRange();if(t)return Ka(this.element,t);let n=this.lastKnownSelection;if(n&&oE(this.element,n.start,n.end))return n;let r=Ui(this.element);return r.collapse(!1),Ka(this.element,r)}getSelectedText(){let{start:t,end:n}=this.getSelection();return Va(this.element,Lr(this.element,t,n))}applyChanges(t){var o;if(!this.isActive)return;this.isSettingValue=!0;let n=this.getText(),r=t(this.element);return(o=this.observer)==null||o.takeRecords(),Promise.resolve(r).then(()=>{this.currentText=this.getText(),n!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(){super.listen(),this.observer=new MutationObserver(()=>{setTimeout(()=>{this.triggerChange()},0)}),this.observer.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0});let t=this.element.isContentEditable,n=new MutationObserver(()=>{this.element.isContentEditable!==t&&(t=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});n.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>n.disconnect())}dispose(){super.dispose(),this.observer&&this.observer.disconnect()}};function sE(e,t,n){let r=`deepdesk-iframe-${e}`,o=document.getElementById(r);if(o)return o;let i=document.createElement("iframe"),s=new URL(t);return Object.entries(n).forEach(([a,l])=>{s.searchParams.append(a,l)}),i.style.position="absolute",i.style.left="-999em",i.style.width="0px",i.style.height="0px",i.tabIndex=-1,i.id=r,i.title=`iframe-${e}`,i.src=s.toString(),window.document.body.appendChild(i),i}var kh=class{constructor(t){this.name=t;this.broadcastChannel=new BroadcastChannel(t)}broadcastChannel;disposeHandlers=[];onMessage(t){this.broadcastChannel.addEventListener("message",t),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",t)})}postMessage(t){this.broadcastChannel.postMessage(JSON.stringify(t))}close(){this.disposeHandlers.forEach(t=>t()),this.broadcastChannel.close()}},Ph=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.iframe=sE(t,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}iframe;disposeHandlers=[];onMessage(t){window.addEventListener("message",t),this.disposeHandlers.push(()=>{window.removeEventListener("message",t)})}postMessage(t){var n;(n=this.iframe.contentWindow)==null||n.postMessage(JSON.stringify(t),this.targetOrigin)}close(){var t;this.disposeHandlers.forEach(n=>n()),(t=this.iframe)==null||t.remove()}},Ih=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.eventMap,this.sessionId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}sessionId;deepdeskUrl;channel;defaultChannel;eventMap;get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setSessionId(t){this.sessionId!==t&&(this.cleanup(),j.info("Set sessionId",t),this.sessionId=t,this.channel=this.createChannel(t))}createChannel(t){let n=this.params.createCustomChannel?this.params.createCustomChannel(t):this.isCrossOrigin?new Ph(t,this.deepdeskUrl,{debug:!0}):new kh(t),r=o=>{var s,a;if(o.origin!==this.deepdeskUrl)return;let i=typeof o.data=="string"?JSON.parse(o.data):o.data;i.type==="event"&&i.channel===t&&(j.info("Received broadcast event",this.sessionId,o),(a=(s=this.eventMap)[i.name])==null||a.call(s,i.payload))};return n.onMessage(r),n}send(t,n){var i,s;j.info("Broadcast event",{sessionId:this.sessionId,name:t,payload:n});let r={type:"event",name:t,payload:n};(s=(i=this.eventMap)[t])==null||s.call(i,n);let o=this.sessionId==="deepdesk-general"?this.defaultChannel:this.channel;o==null||o.postMessage({...r,channel:this.sessionId})}cleanup(t=!1){var n,r;(n=this.channel)==null||n.close(),delete this.channel,t&&((r=this.defaultChannel)==null||r.close(),delete this.defaultChannel)}},aE=Ih;var Ki=class extends Error{constructor(n,r){super(n);this.body=r}name="CustomError"};var Rh=e=>new Promise(t=>{setTimeout(t,e)});var Vi=class extends Ki{name="ClientError"},Lh=class extends Ki{name="ServerError"},Gt=class e{constructor(t="",n={}){this.baseUrl=t;this.options=n;n.fetch&&(this.fetch=n.fetch)}latestRequestByUrl={};csrfToken;fetch=window.fetch.bind(window);static refreshingToken=null;patchFetch(t){this.fetch=t(this.fetch)}setCsrfToken(t){this.csrfToken=t}request(t,n={}){return new Promise((r,o)=>{let i={isAborted:!1,reject:o},s=`${this.baseUrl}${t}`,a=this.fetch,{abortLatest:l=!1,attempts:u=1,retryDelay:c=500,refreshTokenOn401:p=!0,retryOnError:d=_=>_ instanceof TypeError,retryOnResponse:f=_=>_.status>=500,version:y="v1",...v}=n,m={credentials:"include",...v,headers:{"Content-Type":"application/json",...v.headers}};n.method!==void 0&&n.method!=="GET"&&this.csrfToken&&(m.headers={...m.headers,"X-CSRFToken":this.csrfToken}),typeof y=="string"&&(m.headers={...m.headers,"X-Deepdesk-API-Version":y});let h=u,g=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[s]&&l&&(this.latestRequestByUrl[s].isAborted=!0,this.latestRequestByUrl[s].reject(new Error("Aborted"))),this.latestRequestByUrl[s]=i;let x=async()=>(h--,a(s,m).then(async _=>f(_)&&!i.isAborted&&h>0?(await Rh(c),x()):_.status===401&&p===!0&&g===!1?(g=!0,await this.refreshToken(),x()):_).catch(async _=>{if(d(_)&&!i.isAborted&&h>0)return await Rh(c),x();throw _}));x().then(_=>_.json().catch(()=>null).then(w=>{_.status>=500?o(new Lh("Server Error",w)):_.status===401?o(new Vi("Unauthorized",w)):_.status===403?o(new Vi("Forbidden",w)):_.status===404?o(new Vi("Not Found",w)):_.status>=400&&o(new Vi("Bad Request",w)),delete this.latestRequestByUrl[s],r(w)})).catch(_=>{o(_)})})}async validateToken(){let{has_valid_access_token:t}=await this.get("/auth/validate");if(!t)return!1;let{is_logged_in:n}=await this.get("/apis/admin/session/validate/",{version:null});return!!n}refreshToken(){return e.refreshingToken||(e.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{e.refreshingToken=null},1e3*60)})),e.refreshingToken}get(t,n){return this.request(t,n)}post(t,n,r){return this.request(t,{method:"POST",body:JSON.stringify(n),...r})}patch(t,n,r){return this.request(t,{method:"PATCH",body:JSON.stringify(n),...r})}put(t,n,r){return this.request(t,{method:"PUT",body:JSON.stringify(n),...r})}delete(t,n){return this.request(t,{method:"DELETE",...n})}};var yA;(t=>{let e;(l=>(l.SEND_MESSAGE="Send Message",l.HANDLING_TIME="Handling Time",l.START_AUTOFLOW="Start Autoflow",l.ABORT_AUTOFLOW="Abort Autoflow",l.ADD_TO_PERSONAL_COLLECTION="Add to personal collection",l.DELETE_FROM_PERSONAL_COLLECTION="Delete from personal collection"))(e=t.EventType||={})})(yA||={});function Od(e){return{...Z(e),tags:e.tags}}var zn=class e{constructor(t,n={}){this.options=n;this.client=new Gt(t,{fetch:n.fetch}),this.client.patchFetch(r=>async(o,i)=>{let s=await r(o,i);return this.handleDeepdeskVersionHeaders(s),s})}latestReceivedDeepdeskVersions={};client;shouldFetchCsrfToken=!0;static exchangeTokenPromise=null;async preflight(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=await this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(e.exchangeTokenPromise||(e.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),e.exchangeTokenPromise):Promise.resolve()}async createConversation(t){await this.preflight(),j.info(`Creating conversation for session ${t.sessionId} and agent ${t.agentId}`);let n=await this.client.post("/api/conversations",{...ke(t),tags:t.tags},{version:"v2"});return Od(n)}async getProfile(t){let n=await this.client.get(`/apis/admin/profiles/${t}/`,{version:null});return Z(n)}async getKnowledgeAssistant(t){let n=await this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{version:null});return Z(n)}async getContentTypes(){let t=await this.client.get("/apis/admin/content-types/",{version:null});return Z(t)}async getPlatformConfig(){let{config:t}=await this.client.get("/platform/config/",{version:null});return Z(t)}async checkUserExists(t){let{exists:n}=await this.client.get(`/apis/admin/users/exists?external_id=${t}`);return n}async getConversationBySessionId(t,n={}){await this.preflight(),j.info(`Getting conversation for session ${t}`);let{attempts:r=1,retryDelay:o=1e3}=n,i=await this.client.get(`/api/conversations/by_session_id/${t}`,{attempts:r,retryDelay:o,retryOnResponse:s=>s.status===404||s.status>=500,version:"v2"});return Od(i)}async isConversationSupported(t,n={}){j.info(`Check if conversation for session ${t} is supported`);let{attempts:r=1,retryDelay:o=1e3}=n;return(await this.client.get(`/api/conversations/by_session_id/${t}/active_profile`,{attempts:r,retryDelay:o,retryOnResponse:s=>s.status===404||s.status>=500,version:"v2"})).has_active_profile}async updateConversation(t,n){let r=ke(n);n.tags&&(r.tags=n.tags);let o=await this.client.put(`/api/conversations/${t}`,r,{version:"v2"});return Od(o)}async postMessages(t,n){return(await this.client.post(`/api/conversations/${t}/messages`,n.map(o=>({...ke(o),tags:o.tags})),{version:"v2"})).map(o=>Od(o))}async sendEvent(t,n){let{data:r,...o}=n,i=Object.entries(this.latestReceivedDeepdeskVersions).reduce((s,[a,l])=>({...s,[a]:l}),{});return this.client.post("/api/events",ke({...i,...o,data:r,name:t}),{version:"v2"})}async sendEventV1(t,n){let r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((o,[i,s])=>({...o,[i]:s}),{});return this.client.post("/api/events",{event:t,data:ke({...n,...r})})}async getEntities(t){return(await this.client.post("/api/entities",{messages:t.filter(r=>r.text)})).entities}async getSummary(t,n={}){return(await this.client.post("/api/summary",{conversation:{messages:t.filter(o=>o.text&&o.source),agent_id:n.agentId,id:n.externalConversationId},prompt_instruction:n.promptInstruction,model:n.model})).summary}async getTemporaryExchangeToken(){return(await this.client.get("/auth/exchange-token",{version:null})).jwt}async exchangeTokenForAccessCookie(t){return this.client.post("/apis/admin/session/jwt/",{jwt:t},{version:null}).catch(n=>{throw j.warn(`Invalid token '${t}'`),n})}async authenticateWithKey(t,n){await this.client.post("/apis/admin/session/api-key/",ke(n),{version:null,refreshTokenOn401:!1,headers:{apikey:t}})}async getTextSuggestions(t,n={},r){return r==="sticky-messages"?this.getPinnedMessages(t):(await this.client.post(`/api/conversations/${t}/recommend/${r}`,ke(n),{abortLatest:!0})).map(i=>({...Z(i),text:i.text||i.url||i.message,source:r,type:r})).filter((i,s,a)=>s===a.findIndex(l=>l.text===i.text))}async isLoggedIn(){return await this.preflight(),this.client.validateToken()}async getAutocompleteSuggestions(t,n){return(await this.client.post(`/api/conversations/${t}/autocomplete`,ke(n),{abortLatest:!0})).map(o=>({score:1,source:o.source,sourceText:o.source_text,text:o.label,trainingJobs:o.training_jobs,searchKeywords:o.search_keywords,type:o.source})).filter((o,i,s)=>i===s.findIndex(a=>a.text===o.text))}async getPinnedMessages(t){let n=await this.client.get(`/api/conversations/${t}/sticky-messages`,{abortLatest:!0});return Z(n).map(r=>({...r,text:r.message,source:"sticky-messages",type:"pinned-message"}))}async getStyleSuggestions(t){let n=await this.client.post("/api/style-suggestions",ke(t),{abortLatest:!0});return Z(n)}async search(t){let n=await this.client.post(`/api/profiles/${t.profile}/search`,ke(t),{version:"v2"});return Z(n)}async knowledgeAssist(t,n,r){let o=await this.client.post(`/api/knowledge-assist/assistants/${r}/search`,ke({question:t.question,promptInstruction:t.promptInstruction,chatHistory:n.map(i=>({question:i.question,answer:i.answer.answer}))}),{version:"v2"});return Z(o)}async requestLoginByEmail(t){let n=await this.client.post("/apis/admin/session/passwordless/request/",{email:t},{version:null});return Z(n)}async requestPasswordlessToken(){let t=await this.client.get("/apis/admin/session/passwordless/request/",{version:null});return Z(t.token)}async getCsrfToken(){let{token:t}=await this.client.get("/apis/admin/session/csrf/",{version:null});return t}async verifyLoginToken(t){let n=await this.client.post("/apis/admin/session/passwordless/login/",{token:t},{version:null});return Z(n)}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),i=o.match(Cy);if(!n||!i)return;let s=i[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[s];a&&n&&a!==n&&j.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[s]=n})}};var Wa=class{constructor(t,n){this.url=t;this.options={timeout:25e3,...n}}eventListeners={};options;timeoutTimer;eventSource;proxyEvent(t){this.eventSource.addEventListener(Mg(t),n=>{let{data:r}=n;try{let o=JSON.parse(r);this.emit(t,Z(o))}catch{j.warn(`Invalid JSON for ${t}: ${r}`)}})}connect(){clearTimeout(this.timeoutTimer);let t=new EventSource(this.url,{withCredentials:!0});this.eventSource=t;let n=!1;t.onopen=()=>{n=!0},t.onerror=()=>{n&&t.readyState===2&&this.connect()},this.timeoutTimer=setTimeout(()=>{t.close(),this.connect()},this.options.timeout),Object.keys(this.eventListeners).forEach(r=>{this.proxyEvent(r)})}disconnect(){var t;clearTimeout(this.timeoutTimer),this.eventListeners={},(t=this.eventSource)==null||t.close()}emit(t,n){this.eventListeners[t]&&this.eventListeners[t].forEach(r=>r(n))}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),this.proxyEvent(t),()=>{this.off(t,n)}}off(t,n){let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}};var vA;(t=>{let e;(i=>(i.Started="Started",i.Aborted="Aborted",i.Completed="Completed"))(e=t.AutoflowSessionState||={})})(vA||={});var $a=class{constructor(t,n={}){this.apiUrl=t;this.client=new Gt(t,n)}client;streams={};logger=j;async getCustomMessages(t){let n=await this.client.get(`/sessions/${t}/suggestions`);return Z(n.suggestions)}async sendCustomMessage(t,n){let r=await this.client.post(`/sessions/${t}/messages`,ke(n));return Z(r)}async answerCustomMessage(t,n){await this.client.post(`/sessions/${t}/answers`,ke(n))}async getAutoflows(t){let n=await this.client.get(`/sessions/${t}/autoflows`);return Z(n.autoflows)}async startAutoflowSession(t){let n=await this.client.post("/autoflow-sessions",ke(t));return Z(n)}async stopAutoflowSession(t){await this.client.delete(`/autoflow-sessions/${t}`)}openStream(t){return this.streams[t]||(this.streams[t]=new Wa(`${this.apiUrl}/sessions/${t}/events`),this.streams[t].connect()),this.streams[t]}closeStream(t){this.streams[t]||(this.streams[t].disconnect(),delete this.streams[t])}};var lE={startTime:null,stopTime:null},uE=z({name:"handlingTime",initialState:lE,reducers:{handlingTimeStart(e){if(e.startTime&&!e.stopTime)throw new Error("Timing already started");e.startTime=new Date,e.stopTime=null},handlingTimeStop(e){if(!e.startTime)throw new Error("Timing not started");e.stopTime=new Date},handlingTimeReset(e){e.startTime=null,e.stopTime=null}},extraReducers:e=>{e.addCase(te,()=>lE)}}),{handlingTimeStart:cE,handlingTimeStop:Nd,handlingTimeReset:dE}=uE.actions,pE=uE.reducer;var fE=(e={})=>{let t={onAuthError:Oi(!1),...e};return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var Md={list:{keywordMatches:[]},fetchState:"idle",isInitialRequest:null};var Eo=D("styleSuggestions/getAll",async({text:e},t)=>{var s;let{deepdeskAPI:n}=t.extra,r=t.getState(),{showStyleSuggestions:o}=r.settings,i=(s=r.conversation.current)==null?void 0:s.profileCode;if(!o)return Md.list;if(!i)throw new Error("No current conversation to fetch pinned messages");return n.getStyleSuggestions({profileCode:i,message:e})}),SA=z({name:"styleSuggestions",initialState:Md,reducers:{},extraReducers:e=>{e.addCase(Eo.pending,t=>{t.isInitialRequest=t.isInitialRequest===null,t.fetchState="loading"}).addCase(Eo.rejected,t=>{t.fetchState="error"}).addCase(Eo.fulfilled,(t,n)=>{t.fetchState="done",hr(t.list,n.payload)||(t.list=n.payload)}).addCase(no,t=>{t.list=Md.list}).addCase(te,()=>Md)}}),mE=SA.reducer;var gE=(e={})=>{let t,n=!0,r={getStyleSuggestions:Eo,debounce:500,...e};return o=>i=>s=>{var f;let a=o.getState().input.text,l=i(s),u=o.getState();if(u.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:c}=u.settings;if(!((f=u.conversation.current)==null?void 0:f.id)||!c)return l;let{text:d}=u.input;return d===a&&!n||(clearTimeout(t),d==="")||(t=setTimeout(()=>{n=!1,o.dispatch(r.getStyleSuggestions({text:d}))},e.debounce)),l}};function xA(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var hE=(e={})=>{let t={getTextSuggestions:Vt,getAutocompleteSuggestions:Ea,debounce:200,check:ji,...e},n;return r=>o=>i=>{var v;let{input:{userCommitted:s}}=r.getState(),a=o(i),l=r.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:u,showTabCompletion:c}=l.settings,p=(v=l.conversation.current)==null?void 0:v.id,d=i.type===rd.toString();if(!p||!u&&!c)return a;let{input:{userCommitted:f}}=l;return xA(f,s)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let m=xi(l);m===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(m))},d?0:t.debounce)),a}};var yE=Eo.fulfilled.toString();function _A(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let i=e.keywordMatches.filter(l=>l.keyword===o),s=t.keywordMatches.filter(l=>l.keyword===o),a=s.length-i.length;a<=0||r.push(...s.slice(0,a))}),r}var vE=e=>t=>n=>r=>{var u;if(r.type!==yE){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let i=t.getState(),s=i.styleSuggestions.list,a=(u=i.conversation)==null?void 0:u.current;if(o===s)return;let l=_A(o,s);r.type===yE&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var wA=Iu({activeSuggestion:Rw,answer:w1,auth:Kw,autoflows:Sb,conversation:qx,contentTypes:o1,customMessages:Pb,passwordlessToken:Ab,entities:l1,knowledgeAssistant:S1,handlingTime:pE,info:iw,input:Jm.reducer,overlayInput:rt.reducer,settings:jx,profile:C1,search:dw,summary:m1,styleSuggestions:mE,ui:Nw,textSuggestions:Cw});function SE(e){return V0({reducer:wA,middleware:t=>[...t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI,deepdeskBrokerAPI:e.deepdeskBrokerAPI}},serializableCheck:!1}),fE(),hE({debounce:200}),gE({debounce:500}),vE(e.deepdeskAPI),...e.middleware?e.middleware:[]],preloadedState:e.preloadedState})}var bA=e=>{var t;return((t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())??"unknown"},EA=e=>t=>n=>r=>{var a;let o=t.getState(),i=qm("inlineSuggestions")(o);switch(r.type){case Rn.toString():{let l=nd(r.payload.contentType)(t.getState()),u=l.indexOf(r.payload.suggestion);e.emit("edit-suggestion",{contentType:r.payload.contentType,index:u,suggestions:l});break}case Oi.toString():{!r.payload&&e.emit("logout",void 0);break}case Bt.toString():{let{start:l,end:u}=o.input.selection;e.emit("select-suggestion",{type:bA(r.payload.suggestion),...r.payload,replace:r.payload.replace==="selection"?{start:l,end:u}:{start:0,end:u}},{mayApplyChanges:!0});break}case fc.toString():{let{start:l,end:u}=o.input.selection;e.emit("replace",{...r.payload,replace:r.payload.replace==="selection"?{start:l,end:u}:{start:0,end:u}},{mayApplyChanges:!0});break}case sa.toString():{let l=t.getState(),{text:u,selection:c}=l.input.userCommitted;e.emit("reset",{text:u,selectionAfter:c},{mayApplyChanges:!0});break}case yc.toString():e.emit("select-image",r.payload,{mayApplyChanges:!0}),e.sendEvent("Image attached",{conversationId:o.conversation.current.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case $t.fulfilled.toString():r.payload.length>0&&e.sendEvent("entities found",{conversationId:o.conversation.current.id,data:{entities:r.payload}});break;case On.fulfilled.toString():e.sendEvent("conversation summarized",{conversationId:o.conversation.current.id,data:{summary:r.payload.summary}});break;case Be.toString():e.sendEvent(r.payload.name,{conversationId:((a=r.payload.options)==null?void 0:a.includeConversationData)&&o.conversation.current.id,data:r.payload.data});break;case mc.toString():e.handleKeyDown(r.payload);break;case no.toString():e.logSendMessage(r.payload);break;case gc.toString():e.logSendEditSuggestionMessage(r.payload);break;case hc.toString():e.handleInputChanged(r.payload);break;default:break}let s=n(r);switch(r.type){case no.toString():e.handleAfterSendMessage(r.payload);break;case Ca.toString():e.onUpdateShowTabHint(r.payload);break;case Nd.toString():e.logHandlingTime();break;case Bt.toString():{i&&(t.dispatch(on([])),t.dispatch(wn()));break}case on.toString():{i&&r.payload.length>0&&t.dispatch(vr(0));break}default:break}return s},xE=EA;function Ah(e){return e.toISOString().replace("T"," ").replace("Z","")}function _E(e,t){var o,i,s;let{startTime:n,stopTime:r}=e.handlingTime;if(!n||!r)throw new Error("No startTime and stopTime for handling time metrics");return{conversationId:e.conversation.current.id,clientVersion:t.version,agentId:(o=e.info.agentInfo)==null?void 0:o.agentId,agentName:(i=e.info.agentInfo)==null?void 0:i.agentName,agentEmail:(s=e.info.agentInfo)==null?void 0:s.agentEmail,timeStart:Ah(n),timeStop:Ah(r)}}function Oh(e,t,n){var C,I,k;let{text:r,metrics:{numCharsTyped:o,numCharsPasted:i,numCharsCut:s,numCharsDeleted:a,numPaste:l,agentStartedTypingTimestamp:u,externalTimeTotalSeconds:c,pastes:p,cuts:d,deletions:f,textSuggestions:y,offeredTextSuggestions:v}}=t[e],m=r.length,g=y.reduce((K,{text:N,searchTerm:B})=>K+N.length-(B?B.length:0),0),x=u??Date.now(),_=(Date.now()-x)/1e3+(c||0),w=o/_,E=y.reduce((K,{searchTerm:N})=>K+(N?N.length:0),0);return{conversationId:t.conversation.current.id,source:"agent",text:r,clientVersion:n.version,pastes:p,cuts:d,deletions:f,lenTextTyped:o+E,lenTextTotal:m,lenTextAssisted:g,lenTextPasted:i,lenTextCut:s,lenTextDeleted:a,timeTotalSeconds:_,charsPerSecond:w,numPastes:l,textSuggestionsV2:y,suggestionsCounters:[{source:"gpt",countOffered:v.filter(K=>K.source==="gpt").length}],agentId:(C=t.info.agentInfo)==null?void 0:C.agentId,agentName:(I=t.info.agentInfo)==null?void 0:I.agentName,agentEmail:(k=t.info.agentInfo)==null?void 0:k.agentEmail}}function Nh(e,t){var i;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return Nh(r,t);let o=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;return o?Nh(o,t):null}function wE(e,t){return Nh(e,t)}function bE(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function CA(e){return typeof e=="object"&&e!==null&&"tagName"in e}function Dd(e){return CA(e)&&(Pr(e)||zc(e))}var EE=(e,t)=>({value(){try{let n=sessionStorage.getItem(`dd-${e}`);if(!n)return t;try{return JSON.parse(n)}catch{return t}}catch{return t}},update(n){try{sessionStorage.setItem(`dd-${e}`,JSON.stringify(n))}catch{j.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function TA(e){return e.offsetParent!==null}function CE(e){if(!TA(e))return!1;let t=e.getBoundingClientRect();return t.top>=0&&t.left>=0&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&t.right<=(window.innerWidth||document.documentElement.clientWidth)}function Fd(e,t,n=100){let r=CE(e);t({isVisible:r});let o=setInterval(()=>{let i=CE(e);i!==r&&(r=i,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var we=S(b());var TE=EE("showTabHint",!0),qa=class e{static version="10.10.3";static count=0;deepdeskApi;inputMediator=null;version;broadcastEvents;eventListeners={};unmountHandlers=[];widgetRoot=null;dynamicThunkObject={};isMounted=!1;instanceId;shouldRender=!0;store;constructor({deepdeskUrl:t,brokerUrl:n,version:r=e.version||"unknown",locale:o="en-US",token:i,fetch:s,productName:a,createCustomChannel:l}){let u=t.replace(/\/api$/,"");this.deepdeskApi=new zn(u,{token:i,fetch:s}),this.version=r,this.instanceId=e.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[xE({emit:(p,d,f)=>this.emit(p,d,f),handleAfterSendMessage:p=>this.handleAfterSendMessage(p),handleInputChanged:p=>this.handleInputChanged(p),handleKeyDown:p=>this.handleKeyDown(p),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:p=>this.logSendMessage(p),logSendEditSuggestionMessage:p=>this.logSendEditMessage(p),onUpdateShowTabHint:p=>TE.update(p),sendEvent:(p,d)=>this.deepdeskApi.sendEvent(p,d)})]};n&&Object.assign(c,{deepdeskBrokerAPI:new $a(n)}),this.store=SE(c),this.broadcastEvents=new aE({debug:!0,deepdeskUrl:u,eventMap:Vw(this.store),createCustomChannel:l}),this.store.dispatch(oa),this.store.dispatch(Ca(TE.value())),this.store.dispatch(oa({locale:o,adminUrl:u,productName:a}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){return this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex]??null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(j.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(j.warn("Profile has not been loaded (yet)"),!0):(j.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(Oi(null)),this.store.dispatch(Ln()),new Promise(t=>{let n=this.store.subscribe(()=>{let r=this.store.getState();Ge(r)&&Fw(r)!=="loading"&&(n(),t())});this.unmountHandlers.push(()=>{n()})})}async isLoggedIn(){return(await this.store.dispatch(Ln())).payload}async setPlatformAgentId(t){try{if((await this.deepdeskApi.client.get("/apis/admin/session/me/",{version:null})).external_id)return;await this.deepdeskApi.client.request("/apis/admin/session/me/",{method:"PATCH",body:JSON.stringify({external_id:t}),version:null})}catch(n){j.warn("Failed to attach user:",n)}}async isConversationSupported(t,n){return(await this.store.dispatch(Ym({sessionId:t,options:n}))).payload}async createConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(ac(t))).payload}async getConversationBySessionId(t,n){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(await this.store.dispatch(lc({sessionId:t,options:n}))).payload}async upsertConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(Zm(t))).payload}async postMessages(t){return(await this.store.dispatch(cc(t))).payload}async updateConversation(t){return(await this.store.dispatch(uc(t))).payload}resetConversation(){this.store.dispatch(te()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}async getSummary(){let t=await this.store.dispatch(On());if(t.error)throw new Error(t.error.message);return t.payload.summary}configure(t){this.store.dispatch(oa(t))}setVisitorInfo(t){this.store.dispatch(ow(t))}async setAgentInfo(t){await this.store.dispatch(xa(t))}async setAgentSettings(t){await this.store.dispatch(Dg(t))}async getAgentSettings(){return(await this.store.dispatch(Fg())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let t=[];return this.store.dispatch(rd()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})}notifyInputChanged(t){this.store.dispatch(hc(t))}notifyKeyDown(t){this.store.dispatch(mc(t))}notifyPaste(t,n){this.store.dispatch(o_({text:t,selectionText:n}))}notifyCut(t){this.store.dispatch(n_(t))}notifyExternalSuggestion(t){this.store.dispatch(Bt(t)),this.store.dispatch(wn())}notifyEditSuggestion(t){this.store.dispatch(bw(t.contentType,t.suggestions)),this.store.dispatch(Rn({contentType:t.contentType,suggestion:typeof t.index=="number"?t.suggestions[t.index]:null}))}handleInputChanged(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui;n&&r&&this.store.dispatch(Er({collapse:!1})),this.inputMediator&&this.store.dispatch(Qx({text:t,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(on([])))}handleKeyDown(t){let{overlayCollapsed:n}=this.state.ui,{textSuggestions:r,selectedSuggestionIndex:o,selection:i}=this.state.input,{inlineSuggestions:s}=this.state.settings,a=r.length>0,l=o!==-1;if(this.store.dispatch(r_(pc(t))),t.key!=="Tab"&&!this.settings.showTextSuggestions)return;let u=()=>{n||!a||i&&(t.shiftKey||(this.store.dispatch(Jx()),s||this.stageSelectedSuggestion({inputType:"arrow"}),t.preventDefault()))},c=()=>{n||!a||s&&o<=0||i&&(t.shiftKey||(this.store.dispatch(t_()),t.preventDefault(),!s&&(this.state.input.selectedSuggestionIndex===-1?this.store.dispatch(sa()):this.stageSelectedSuggestion({inputType:"arrow"}))))};switch(t.key){case"Up":case"ArrowUp":s?c():u();return;case"Down":case"ArrowDown":{s?u():c();return}case"Esc":case"Escape":{s&&l&&this.store.dispatch(vr(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(vr(-1)),this.store.dispatch(sa()),t.preventDefault()):n||(this.store.dispatch(Er({collapse:!0})),this.store.dispatch(Aw(!0)),t.preventDefault());return}case"Tab":{let{userCommitted:p}=this.state.input,d=p.text.substring(0,p.selection.end),{tabCompletionSuggestion:f}=this.state.input;this.store.dispatch(Ca(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!s&&this.settings.showTabCompletion&&f&&f.text.startsWith(d)&&(this.store.dispatch(Bt({text:f.text,suggestion:f,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch(wn())),t.preventDefault();break}default:}}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(i_()),this.store.dispatch(on([]))}handlingTimeStart(){this.state.handlingTime.startTime||(j.info("Start handling time"),this.store.dispatch(cE()))}handlingTimeStop(){this.state.handlingTime.startTime&&(j.info("Stop handling time"),this.store.dispatch(Nd()))}logSendMessage(t){let n=Oh("input",this.state,{version:this.version});t&&(Object.assign(n,{text:t}),Object.assign(n,{lenTextTotal:t.length})),this.deepdeskApi.sendEventV1("Send Message",n),this.emit("send-message-event",n)}logSendEditMessage(t){let n=Oh("overlayInput",this.state,{version:this.version});t&&Object.assign(n,{text:t}),this.store.dispatch(Zx(this.state.overlayInput.metrics))}logHandlingTime(){let t=_E(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch(dE())}notifySubmit(t={}){this.shouldAbort()||(this.store.dispatch(wn()),this.store.dispatch(no(t.text??this.state.input.text)))}stageSelectedSuggestion(t){let n=this.state.input.selectedSuggestionIndex,{textSuggestions:r}=this.state.input;this.store.dispatch(Bt({text:r[n].text,suggestion:r[n],eventMetrics:t,replace:"until-selection-end"}))}emit(t,n,r={}){let o=()=>{this.eventListeners[t]&&this.eventListeners[t].forEach(i=>{try{i(n)}catch(s){j.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),j.error(s)}})};this.inputMediator&&r.mayApplyChanges?this.inputMediator.applyChanges(o):o()}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),()=>{this.off(t,n)}}off(t,n){if(!t&&!n){this.eventListeners={};return}let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}setConversationQuery(t){this.dynamicThunkObject.conversationQuery=t}whenConversationLoaded(t){let n=()=>this.loadProfileConfig().then(()=>t());this.hasConversation()&&n();let r=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==r&&(r=this.hasConversation(),r&&n())})}overlayContainerFactory(t,n,r,o){let[i,s]=lo(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),this.unmountHandlers.push(()=>{(0,Nt.unmountComponentAtNode)(i),s(),i.remove()}),i}createInlineContainer(t,n){var s;let r=document.createElement("div");r.style.position="absolute",r.style.top="0px",r.style.left="0px",r.style.height="0px",r.style.width="0px";let o=document.createElement("div");o.style.display="none",o.style.position="absolute",o.style.height="0px",o.style.width="0px",o.style.backgroundColor="red",r.appendChild(o);let i=(s=t.ownerDocument.defaultView)==null?void 0:s.frameElement;if(i){let[a,l]=lo(i,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});a.dataset.testid=n,a.style.zIndex="2",a.appendChild(r),this.unmountHandlers.push(()=>{(0,Nt.unmountComponentAtNode)(o),l()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return ao(o),o.dataset.testid=t,o.style.color=r.color,o.style.fontSize=r.fontSize,o.style.fontFamily=r.fontFamily,o.style.fontVariant=r.fontVariant,o.setAttribute("translate","no"),n.appendChild(o),this.unmountHandlers.push(()=>{(0,Nt.unmountComponentAtNode)(o),o.remove()}),o}storeMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(t,n),j.info(`Stored analytics for ${this.conversationId()}`)}catch{}}restoreMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=window.sessionStorage.getItem(t);if(!n)return;let r=JSON.parse(n);r.text.trim()===this.state.input.text.trim()?(j.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(a_(r.metrics))):j.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(t)}catch{}}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!Dd(t))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let{customStyles:r={},showStyleSuggestions:o,showTabCompletion:i,showTextSuggestions:s,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,isEmbedded:p,detectSubmit:d,insertLink:f,inputMediator:y,closestScrollSelector:v,appendOverlayTo:m,inlineSuggestions:h,floatingMenu:g}=n;this.configure({showStyleSuggestions:o,showTabCompletion:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,showTextSuggestions:s,insertLink:f,isEmbedded:p,inlineSuggestions:h,floatingMenu:!!g}),n.automaticHandlingTime&&this.setupHandlingTime(t),ao(t),this.inputMediator=y||(Pr(t)?new Pn(t):new bo(t)),this.inputMediator.on("change",({plainText:w})=>{this.notifyInputChanged(w)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(s_({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",w=>{this.notifyKeyDown(w)}),this.inputMediator.on("paste",({pastedText:w,selectionText:E})=>{this.notifyPaste(w,E)}),this.inputMediator.on("cut",({selectionText:w})=>{this.notifyCut(w)});let x=v&&wE(t,v)||void 0;if(h){let{customStyles:w,appendOverlayTo:E}=n;if(Pr(t))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let C=this.createInlineContainer(t,"deepdesk-caret");(0,Nt.render)((0,we.jsx)(wo,{store:this.store,customStyles:w,children:(0,we.jsx)(yo,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(K1,{})})}),C),this.inputMediator.on("caret",k=>{this.store.dispatch(on([])),k?(C.style.display="block",C.style.top=`${k.top}px`,C.style.left=`${k.left}px`):C.style.display="none"});let I=this.overlayContainerFactory("floating-menu",x||t,{appendTo:typeof g=="object"&&"appendOverlayTo"in g?g.appendOverlayTo:E},w==null?void 0:w.floatingMenuRootNode);(0,Nt.render)((0,we.jsx)(wo,{store:this.store,customStyles:w,children:(0,we.jsx)(yo,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(F1,{onLogIn:()=>this.loginViaPopup().catch(k=>j.warn(k.message))})})}),I)}else{let w=this.overlayContainerFactory("deepdesk-tab-completion",x||t,{appendTo:m,closestScrollElement:x,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),E=this.overlayContainerFactory("deepdesk-suggestions-overlay",x||t,{appendTo:m},r==null?void 0:r.suggestionsRootNode);(0,Nt.render)((0,we.jsx)(wo,{store:this.store,customStyles:r,children:(0,we.jsx)(yo,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(fb,{inputElement:t})})}),w),(0,Nt.render)((0,we.jsx)(wo,{store:this.store,customStyles:r,children:(0,we.jsx)(yo,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(Y1,{onLogIn:()=>this.loginViaPopup().catch(C=>j.warn(C.message))})})}),E)}(0,Nt.render)((0,we.jsx)(wo,{store:this.store,customStyles:r,children:(0,we.jsx)(yo,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(A1,{})})}),this.createContainer("deepdesk-overlays"));let _;this.inputMediator.on("selection",w=>{clearTimeout(_),w===null?_=setTimeout(()=>{w!==null&&this.store.dispatch(eg(w))},500):this.store.dispatch(eg(w))}),this.inputMediator.on("disabled",()=>{var w;(w=this.inputMediator)==null||w.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{d&&this.notifySubmit()}),this.inputMediator.on("blur",()=>this.store.dispatch(Ai(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(Ai(!0))),this.store.dispatch(Yx({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.unmountHandlers.push(()=>{this.state.input.text!==""&&(this.store.dispatch(wn()),this.storeMetrics())}),this.whenConversationLoaded(()=>{var w;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((w=this.state.conversation.current)==null?void 0:w.sessionId)}),this.isMounted=!0}unmount(){var t;this.unmountHandlers.forEach(n=>n()),this.unmountHandlers=[],(t=this.inputMediator)==null||t.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(t,n={}){if(this.widgetRoot&&j.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:i}=n;this.widgetRoot=t,this.configure({showImages:o,isEmbedded:i}),(0,Nt.render)((0,we.jsx)(wo,{store:this.store,customStyles:r,children:(0,we.jsx)(yo,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(rE,{onLogIn:()=>this.loginViaPopup().catch(s=>j.warn(s.message))})})}),t),this.whenConversationLoaded(()=>{var s;this.broadcastEvents.setSessionId((s=this.state.conversation.current)==null?void 0:s.sessionId)})}unmountWidget(){this.widgetRoot&&(0,Nt.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(t){let n=Fd(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){bE(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(Da());let t=Tr(this.state);t&&(await this.store.dispatch(Na()),this.store.dispatch(oa({showSearch:t.search,showAutoflows:t.autoflows,showCustomMessages:t.customMessages,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:t.summarizer,showKnowledgeSearch:!!t.knowledgeAssistant,recommendTextSuggestions:t.recommendTextSuggestions})))}),this.loadProfileConfigPromise)}async loginViaPopup(t){return new Promise((n,r)=>{let o=new MessageChannel,i=o.port1,s=this.state.settings.adminUrl,a=new URL(t!=null&&t.url?t==null?void 0:t.url:`${s}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let l=!1,u=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",p),clearInterval(d)};i.onmessage=async f=>{var y,v;if((y=f.data)!=null&&y.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((v=f.data)==null?void 0:v.jwt),await this.isLoggedIn(),this.broadcastEvents.send(Pa),l=!0,o.port1.close(),n()}catch(m){console.error(m),r(m)}finally{l=!0,u()}};let c=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");c===null&&r(new Error("Popup blocked by browser"));let p=async f=>{var y;if(f.origin===a.origin)switch((y=f.data)==null?void 0:y.type){case"deepdesk-popup-loaded":{try{let v=JSON.stringify({type:"deepdesk-popup-create-channel"});c==null||c.postMessage(v,a.origin,[o.port2])}catch(v){j.error("Error posting message to popup",v),r(v)}break}case"deepdesk-popup-error":{u(),f.data.message==="Timeout"&&j.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(f.data.message));break}}};window.addEventListener("message",p);let d=setInterval(()=>{c&&!c.closed||(u(),l||r(new Error("Popup closed by user")))},200);this.unmountHandlers.push(u)})}async checkForTrialMode(t){try{let{account:n}=await this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(j.info("Trial is active"),!await this.deepdeskApi.checkUserExists(t))throw new Error("User is not in trial");this.shouldRender=!0}catch(n){let{message:r}=n;j.info(r),this.shouldRender=!1}}async refreshWidgetSuggestions(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=ad(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch($t()):this.store.dispatch(Vt(r))})}catch(r){this.handleError(r)}}};async function kE(e,t,n={}){let{value:r}=e,{start:o,end:i}=n.replace??{start:0,end:r.length},s=`${r.slice(0,o)}${t}${r.slice(i)}`,a=n.selectionAfter??{start:o+t.length,end:o+t.length},l=()=>{if(n.setValue)return n.setValue(s);e.value=s};return Promise.resolve(l()).then(()=>{e.selectionStart=a.start,e.selectionEnd=a.end,e.blur(),e.focus()})}async function PE(e,t,n={}){let r=n.replace?Lr(e,n.replace.start,n.replace.end):Ui(e),o,i=()=>{if(n.setRange)return n.setRange(r.cloneRange());r.deleteContents(),o=document.createElement("span"),r.insertNode(o),n.insertBRs!==!1?t.split(`
26
26
  `).reverse().forEach((s,a)=>{a>0&&r.insertNode(document.createElement("br")),r.insertNode(document.createTextNode(s))}):r.insertNode(document.createTextNode(t))};return Promise.resolve(i()).then(()=>{try{if(n.selectionAfter!==!1){e.focus();let s=n.selectionAfter?Lr(e,n.selectionAfter.start,n.selectionAfter.end):(r.collapse(!1),r),a=window.getSelection();a==null||a.removeAllRanges(),a==null||a.addRange(s)}if(!o)return;o.scrollIntoView&&o.scrollIntoView({block:"nearest",inline:"nearest"})}finally{o&&o.remove()}})}function kA(e){let t=document.createElement("template");return t.innerHTML=e.replace(/(\[([^\]]+)])\(([^)]+)\)/g,'<a href="$3" target="_blank" rel="noopener noreferrer">$2</a>'),t.content}function PA(e){let t=document.createDocumentFragment();return e.split(`
27
27
  `).forEach((n,r)=>{r>0&&t.appendChild(document.createElement("br"));let o={index:0},i=0;for(;o=n.slice(i).match(/(\[([^\]]+)])\(([^)]+)\)/);){let s=document.createElement("a");s.href=o[3],s.setAttribute("target","_blank"),s.setAttribute("rel","noopener noreferrer"),s.appendChild(document.createTextNode(o[2])),t.appendChild(document.createTextNode(n.slice(i,i+o.index))),t.appendChild(s),i=i+o.index+o[0].length}t.appendChild(document.createTextNode(n.slice(i)))}),t}function IE(e,t){return!e.contains(t)||t===e?null:t.parentNode===e?t:IE(e,t.parentNode)}async function RE(e,t,{isBlock:n,isHTML:r}={}){let o;e.dispatchEvent(new InputEvent("beforeinput",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0}));let i=()=>{let s=e.ownerDocument.defaultView??window,a=s.getSelection();if((!a||a.rangeCount===0)&&(e.focus(),a=s.getSelection()),!a||a.rangeCount===0)return;let l=a.getRangeAt(0);if(!l)return;o=document.createElement("span"),l.insertNode(o);let u=r?kA(t):PA(t);if(n){let c=l.startContainer===e?e.childNodes[l.startOffset]:l.startContainer,p=IE(e,c)??e.firstChild;e.insertBefore(u,(p==null?void 0:p.nextSibling)??null)}else l.insertNode(u),l.collapse(!1)};return Promise.resolve(i()).then(()=>{if(e.dispatchEvent(new InputEvent("input",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0})),e.focus(),!!o)try{o.scrollIntoView&&o.scrollIntoView({block:"nearest",inline:"nearest"})}finally{o&&o.remove()}})}function LE(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}async function AE(e,t,n){await new zn(e).authenticateWithKey(t,n)}async function OE(e){let n=await new Gt(e).get("/platform/config/",{version:null});return Z(n)}async function IA(e){let n=await(e.fetch??window.fetch)(e.url),r=await n.blob();return new File([r],e.name,{type:e.mimeType??n.headers.get("Content-Type")??"image/jpeg"})}async function NE(e,t){let n=await IA(t),r=new Event("change",{bubbles:!0,cancelable:!0});try{Object.defineProperty(e,"files",{configurable:!0,get:()=>[n]}),e.dispatchEvent(r)}finally{Object.hasOwn(e,"files")&&delete e.files}}return zE(RA);})();
28
28
  /*! Bundled license information:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deepdesk/deepdesk-sdk",
3
- "version": "10.10.3-beta.6",
3
+ "version": "10.10.3",
4
4
  "description": "Deepdesk SDK",
5
5
  "author": "Lukas Batteau",
6
6
  "license": "ISC",