@deepdesk/deepdesk-sdk 10.10.3-beta.4 → 10.10.3-beta.6
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 +3 -3
- package/dist/index.esm.js +3 -3
- package/dist/index.iife.js +3 -3
- package/package.json +1 -1
package/dist/index.iife.js
CHANGED
|
@@ -20,11 +20,11 @@ Try polyfilling it using "@formatjs/intl-pluralrules"
|
|
|
20
20
|
c-17.9,17.9-27.3,40.1-27.3,65.7C163.4,163,163.4,233,163.4,233z M465.5,267.9V477c0,9.4-3.4,17.9-10.2,24.7
|
|
21
21
|
c-6.8,6.8-15.4,10.2-24.7,10.2h-349c-9.4,0-17.9-3.4-24.7-10.2c-6.8-6.8-10.2-15.4-10.2-24.7V267.9c0-9.4,3.4-17.9,10.2-24.7
|
|
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
|
-
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("productName"),r=U(),o=R(Ge),i=P("FloatingMenu",M1);if(o===null)return null;let s=()=>{o===!0?r($e(!0)):e()};return(0,xo.jsxs)("button",{className:(0,D1.default)(i.root,{[i.isLoggedIn]:o,[i.isLoggedOut]:!o}),onClick:s,children:[(0,xo.jsx)("div",{className:i.text,children:t(o?"search":"signin",{productName:n})}),(0,xo.jsxs)("div",{className:i.icon,children:[(0,xo.jsx)(N1,{className:i.logo,color:"pink"}),o===!1&&(0,xo.jsx)(O1,{className:i.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+=`
|
|
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.4";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-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(`
|
|
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
|
-
`).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=IE(e,
|
|
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:
|
|
29
29
|
|
|
30
30
|
classnames/index.js:
|