@deepdesk/deepdesk-sdk 10.12.1-beta.8 → 10.12.1-beta.9
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 +1 -1
- package/dist/index.esm.js +1 -1
- package/dist/index.iife.js +9 -9
- package/package.json +1 -1
package/dist/index.esm.js
CHANGED
|
@@ -6,6 +6,6 @@ Try polyfilling it using "@formatjs/intl-pluralrules"
|
|
|
6
6
|
c6.8-6.8,15.4-10.2,24.7-10.2h11.9v-70c0-44.4,16.2-82.8,47.8-115.2S212.1,0,256.4,0s82.8,16.2,115.2,47.8
|
|
7
7
|
c32.4,32.4,47.8,70,47.8,115.2v70h11.9c9.4,0,17.9,3.4,24.7,10.2C462.1,250,465.5,257.7,465.5,267.9z`})})});import{jsx as dl}from"react/jsx-runtime";var Nm={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},pl=({className:t,color:e})=>dl("svg",{className:t,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:dl("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:Nm[e||"pink"]})});var ul={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 Vs={};Z(Vs,{enUS:()=>Dm,nlNL:()=>Hm});var Dm={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},Hm={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};import{useDispatch as Km}from"react-redux";import{jsx as qs,jsxs as gl}from"react/jsx-runtime";var ml=({onLogIn:t})=>{let e=E(Vs),o=b("floatingMenu"),n=b("productName"),s=Km(),r=Bm(G),i=h("FloatingMenu",ul);if(r===null||o===!1)return null;let a=()=>{r===!0?s(Y(!0)):t()};return gl("button",{className:Fm(i.root,{[i.isLoggedIn]:r,[i.isLoggedOut]:!r}),onClick:a,children:[qs("div",{className:i.text,children:e(r?"search":"signin",{productName:n})}),gl("div",{className:i.icon,children:[qs(pl,{className:i.logo,color:"pink"}),r===!1&&qs(cl,{className:i.lock})]})]})};import{useEffect as af,useRef as lf}from"react";import{connect as cf,useDispatch as df,useSelector as sn}from"react-redux";import{useEffect as Um}from"react";function vt(t){Um(()=>{let e=o=>{o.isWithinRoot||t(o)};return document.body.addEventListener("mouseup",e),()=>{document.body.removeEventListener("mouseup",e)}},[t])}function Ge(t){t.addEventListener("mouseup",e=>{e.isWithinRoot=!0},!0)}function St(t){let{showMidSentenceSuggestions:e,showSuggestionsBeforePattern:o,showSuggestionsAfterPattern:n}=t.settings,{text:s,selection:r}=t.input.userCommitted;return r.start!==r.end?!1:r.end>=s.length?!0:e?o&&new RegExp(o).test(s.substring(r.end))||n&&new RegExp(n).test(s.substring(0,r.end))?!0:o===!1&&n===!1:!1}import{createSlice as zm}from"@reduxjs/toolkit";var jm={showTabHint:!1,inputHasFocus:!1,overlayCollapsed:!1,openOverlayWhenTyping:!1,overlayCollapsedUserOverwrite:!1};var tn=({ui:t})=>t.overlayCollapsed;var fl=zm({name:"ui",initialState:jm,reducers:{setShowTabHint(t,e){t.showTabHint=e.payload},setInputHasFocus(t,e){t.overlayCollapsedUserOverwrite!==!0&&(e.payload===!0&&(t.overlayCollapsed=!1),t.inputHasFocus=e.payload)},setOverlayCollapsed(t,e){e.payload.collapse===!1&&(t.openOverlayWhenTyping=!1),!(e.payload.skipWhenInputFocus&&t.inputHasFocus)&&(t.overlayCollapsed=e.payload.collapse)},setOpenOverlayWhenTyping(t,e){t.openOverlayWhenTyping=e.payload},setOverlayCollapsedUserOverwrite(t,e){t.overlayCollapsedUserOverwrite=e.payload,t.overlayCollapsed=e.payload}}}),{setShowTabHint:Jt,setInputHasFocus:$s,setOverlayCollapsed:Ne,setOpenOverlayWhenTyping:hl,setOverlayCollapsedUserOverwrite:yl}=fl.actions,vl=fl.reducer;import{Fragment as nf,useMemo as sf}from"react";import{Interweave as $m}from"interweave";import{useEffect as Wm,useMemo as Gm,useRef as Xm}from"react";import{useDispatch as Zm,useSelector as Qm}from"react-redux";import{useEffect as Vm}from"react";function Sl(t,e,o){Vm(()=>{let n=t.current;return n?(n.addEventListener(e,o),()=>{n.removeEventListener(e,o)}):()=>{}},[t,e,o])}var _l={root:"_root_4u430_1",actions:"_actions_4u430_8",badge:"_badge_4u430_15",formattedText:"_formattedText_4u430_19"};import{jsx as on,jsxs as of}from"react/jsx-runtime";var Jm=["search","personal-collection-search","search-autocomplete"];function Ym(t,e,o,n={}){let s="";return Jm.includes(e)?s=ta(bs(t,o,{stripAgentPart:!0}),n.searchKeywords??[o]):s=bs(t,o,n),n.placeholders===!0&&(s=oa(s)),s}var ef=()=>{},tf=({index:t,selected:e,suggestion:o,onFeedback:n})=>{let s=b("inlineSuggestions"),r=Qm(ct),i=Zm(),a=h("TextSuggestion",_l),l=Xm(null);Wm(()=>{let d=setTimeout(()=>{i(ai({text:o.text,suggestion:o}))},500);return()=>{clearTimeout(d)}},[o]),Sl(l,"click",()=>{i(Ae(t)),i(se({suggestion:o,text:o.text,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"}))});let c=Gm(()=>Ym(o.text,o.source,r,{stripAgentPart:s,placeholders:!0,searchKeywords:o.searchKeywords}),[s,o.text,o.source,r,o.searchKeywords]);return o.source==="gpt"&&!s?null:of("div",{className:a.root,onMouseEnter:()=>i(Ae(t)),children:[on(L,{ref:l,as:"button","data-testid":"suggestions-overlay-item",selected:e,onClick:ef,children:on($m,{containerTagName:"div",noWrap:!1,tagName:"span",className:a.formattedText,content:c})}),e&&n&&on("div",{className:a.actions,children:on(Wo,{onFeedback:()=>n(o),suggestion:o.text})})]})},xl=tf;import{jsx as bl}from"react/jsx-runtime";var rf=({onFeedback:t,suggestions:e,selectedIndex:o,reverse:n})=>{let s=sf(()=>{let r=e.map((i,a)=>bl(xl,{index:a,selected:a===o,suggestion:i,onFeedback:t},`${i.text}-${i.source}`));return n?r.reverse():r},[e,o,n]);return bl(nf,{children:s})},nn=rf;var wl={root:"_root_otdbu_1",paper:"_paper_otdbu_11"};import{jsx as rn}from"react/jsx-runtime";var pf=({textSuggestions:t,selectedIndex:e})=>{let o=lf(null),n=h("InlineSuggestionsOverlay",wl),s=sn(St),r=df(),i=sn(G),a=sn(at),l=sn(tn),c=b("showTextSuggestions");return vt(()=>{setTimeout(()=>{r(Ne({collapse:!0,skipWhenInputFocus:!0}))})}),af(()=>{let d=o.current;if(!d||!d.parentElement)return;d.parentElement.style.left="0px";let p=d.getBoundingClientRect();d.parentElement.style.left=`${Math.min(window.innerWidth-4-p.right,0)}px`}),l||!s||!c||t.length===0||i!==!0||a===!1?null:rn("div",{className:n.root,"data-variant":"inline",children:rn("div",{ref:o,className:n.paper,children:rn(te,{children:rn(nn,{suggestions:t,selectedIndex:e})})})})},uf=({input:t})=>({selectedIndex:t.selectedSuggestionIndex,textSuggestions:t.textSuggestions}),Cl=cf(uf)(pf);import{Provider as gf}from"react-redux";import{jsx as an}from"react/jsx-runtime";var mf=({children:t})=>{let o=b("locale").replace("-","");return an(fs.Provider,{value:o,children:t})},ff=({store:t,customStyles:e={},children:o})=>an(gf,{store:t,children:an(mf,{children:an(Pt.Provider,{value:e,children:o})})}),Xe=ff;import Qs from"classnames";import{useEffect as kf,useRef as If,useState as Rf}from"react";import{connect as Pf,useDispatch as Af,useSelector as Yt}from"react-redux";import{useState as hf}from"react";function Tl(t,e){let[o,n]=hf(()=>{if(typeof window>"u")return e;try{let r=window.localStorage.getItem(t);return r?JSON.parse(r):e}catch(r){return C.error(r),e}});return[o,r=>{try{let i=r instanceof Function?r(o):r;n(i),typeof window<"u"&&window.localStorage.setItem(t,JSON.stringify(i))}catch(i){C.error(i)}}]}var El=()=>/Mac/i.test(navigator.platform);import Sf from"classnames";import{Fragment as _f,useCallback as Gs,useMemo as Il}from"react";var Ws={};Z(Ws,{enUS:()=>yf,nlNL:()=>vf});var yf={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"}]}]},vf={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 kl={root:"_root_1vfca_1",anchor:"_anchor_1vfca_6",anchorButton:"_anchorButton_1vfca_11"};import{jsx as ln,jsxs as Rl}from"react/jsx-runtime";var Xs=(t,e,o)=>n=>ln("button",{className:t.anchorButton,type:"button",value:e,onClick:o,children:n},e),xf=({className:t,loginUrl:e,isEmbedded:o,onSnooze:n,onLogIn:s})=>{let r=E(Ws),i=de(),a=h("Login",kl),l=b("productName"),c=Gs(v=>{v.preventDefault(),n&&n(parseInt(v.target.value,10))},[]),d=Gs(v=>{v.preventDefault(),i.send(dt,!0)},[e]),p=Il(()=>v=>ln("a",{onClick:_=>{_.preventDefault(),s()},href:e,className:a.anchor,target:"_blank",rel:"noreferrer",children:v},"login"),[e]),g=Gs(v=>ln("button",{type:"button",className:a.anchorButton,onClick:d,children:v},"prompt"),[d]),{min:u,hour:f,day:m}=Il(()=>({min:Xs(a,60*10,c),hour:Xs(a,60*60,c),day:Xs(a,60*60*12,c)}),[]);return Rl("div",{className:Sf(t,a.root),children:[r("loginPlease",{login:o?g:p,productName:l}),n&&Rl(_f,{children:[ln("br",{}),r("snooze",{min:u,hour:f,day:m})]})]})},cn=xf;import{useDispatch as bf}from"react-redux";var Pl={root:"_root_1g8fi_1",text:"_text_1g8fi_19"};import{jsx as Al,jsxs as Cf}from"react/jsx-runtime";var wf=({title:t})=>{let e=h("SearchTrigger",Pl),o=bf();return Cf("button",{type:"button",className:e.root,onClick:()=>o(Y(!0)),children:[Al(ut,{}),Al("span",{className:e.text,children:t})]})},Ll=wf;var Zs={};Z(Zs,{enUS:()=>Tf,nlNL:()=>Ef});var Tf={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"}]},Ef={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 Ml={root:"_root_onpov_1",isInline:"_isInline_onpov_14",toggleButton:"_toggleButton_onpov_21",toggleButtonWrapper:"_toggleButtonWrapper_onpov_25",toggleButtonWrapperHidden:"_toggleButtonWrapperHidden_onpov_32",isCollapsed:"_isCollapsed_onpov_36",collapsible:"_collapsible_onpov_36",hints:"_hints_onpov_44",hintsHidden:"_hintsHidden_onpov_51",triggers:"_triggers_onpov_56",triggersRight:"_triggersRight_onpov_71"};import{jsx as j,jsxs as eo}from"react/jsx-runtime";var Lf=({textSuggestions:t,selectedIndex:e,onLogIn:o})=>{let n=h("SuggestionsOverlay",Ml),s=E(Zs),r=Yt(St),i=ni(),a=Af(),l=If(null),c=b("searchTriggerKey"),d=b("productName"),p=Yt(tn),g=Yt(G),u=Yt(at),[f,m]=Rf(null),v=b("showSearch"),T=b("showTextSuggestions"),_=b("adminUrl"),y=b("isEmbedded"),[x,S]=Tl("dd-snooze-until-ms",0),O=p||x>Date.now(),F=Yt(k=>k.input.text),K=t.filter(k=>k.source!=="gpt").length,H=()=>{O&&S(0),a(yl(!O))},I=k=>{a($({name:"suggestion feedback",data:{text:k.text,source:"overlay",context:F},options:{includeConversationData:!0}}))},A=k=>{let V=Date.now()+k*1e3;S(V),C.info(`Snooze until: ${new Date(V)}`),a(Ne({collapse:!0}))};return kf(()=>{K===0&&m(null)},[t,K]),vt(()=>{a(Ne({collapse:!0,skipWhenInputFocus:!0}))}),g===null||u===!1?null:g===!1?eo("div",{ref:l,className:Qs(n.root,{[n.isCollapsed]:O}),children:[!O&&eo("div",{className:n.triggers,children:[j("div",{style:{flex:1}}),j("div",{className:n.triggersRight,children:j(nt,{className:n.toggleButton,title:s("collapse"),onClick:H,isCollapsed:!1})})]}),j("div",{className:n.toggleButtonWrapper,children:j(nt,{className:n.toggleButton,title:s("open",{productName:d}),onClick:H,isCollapsed:!0})}),j("div",{className:n.collapsible,children:j(cn,{loginUrl:_,isEmbedded:y,onLogIn:o,onSnooze:A})})]}):!i||!r?null:eo("div",{ref:l,className:Qs(n.root,{[n.isCollapsed]:O}),children:[!O&&eo("div",{className:n.triggers,children:[j("div",{style:{flex:1},children:v&&j("div",{style:{display:"inline-block"},onFocus:()=>{},onMouseOver:()=>m(s(El()?"searchHintMac":"searchHintWindows",{searchTriggerKey:c.toUpperCase()})),onMouseLeave:()=>m(null),children:j(Ll,{title:s("search")})})}),eo("div",{className:n.triggersRight,onFocus:()=>{},children:[j("div",{className:Qs(!f&&n.hintsHidden,n.hints),children:f}),j(nt,{className:n.toggleButton,title:s("collapse"),onClick:H,isCollapsed:!1})]})]}),j("div",{className:n.toggleButtonWrapper,children:j(nt,{className:n.toggleButton,title:s("open",{productName:d}),onClick:H,isCollapsed:!0})}),K>0&&T&&j("div",{className:n.collapsible,onFocus:()=>{},children:j(te,{children:j(nn,{onFeedback:I,suggestions:t,selectedIndex:e,reverse:!0})})})]})},Mf=({input:t})=>({selectedIndex:t.selectedSuggestionIndex,textSuggestions:t.textSuggestions}),Ol=Pf(Mf)(Lf);import lr from"classnames";import{Interweave as Ph}from"interweave";import{useCallback as Ah,useEffect as Lh,useMemo as rc,useRef as Mh}from"react";import{connect as Oh}from"react-redux";import{useEffect as Of,useRef as Nf,useState as Df}from"react";function dn(t){return t.contentEditable==="true"}function Hf(t){let e=0,o=0,n=window.getSelection();if(n.rangeCount!==0){let s=n.getRangeAt(0),r=s.cloneRange();r.selectNodeContents(t),r.setEnd(s.endContainer,s.endOffset),o=r.toString().length,r.selectNodeContents(t),r.setEnd(s.startContainer,s.startOffset),e=r.toString().length}return{selectionStart:e,selectionEnd:o}}function Nl(t){let{selectionStart:e,selectionEnd:o}=dn(t)?Hf(t):t;return[e,o]}function Dl(t){let[,e]=Df(),o=Nf(null);return o.current=Nl(t),Of(()=>{let n=()=>{let[s,r]=o.current??[],i=Nl(t);(!i||s!==i[0]||r!==i[1])&&(o.current=i,e({}))};return t.addEventListener("keyup",n),t.addEventListener("click",n),t.addEventListener("focus",n),document.addEventListener("selectionchange",n),()=>{t.removeEventListener("keyup",n),t.removeEventListener("click",n),t.removeEventListener("focus",n),document.removeEventListener("selectionchange",n)}},[t]),o.current}function Hl(t,e){if(!e)return;let o=t,{value:n}=o,[s,r]=e,i=n.match(fo);if(!i||i.length===0)return;let a=0;i.find(l=>{let c=n.indexOf(l,a);return s>c&&r<c+l.length?(o.selectionStart=c,o.selectionEnd=c+l.length,!0):(a=c+l.length,!1)})}import{cloneElement as Ff}from"react";var Bf=["div","span","mark","strong","b","i","u","em"];function Js(t,e,o=0){var r;let n=t[t.length-1],s=typeof n=="object"&&n!==null?(r=n.props)==null?void 0:r.tagName:void 0;if(s==="br")return t.pop(),[...t,...e,n];if(Bf.includes(s)){let i=Array.isArray(n.props.children)?n.props.children:[n.props.children];return[...t.slice(0,t.length-1),Ff(n,{children:Js(i,e,o+1)})]}return[...t,...e]}function De(t){return t.tagName.toLowerCase()==="textarea"}var Fl={root:"_root_81non_1",container:"_container_81non_3",agentText:"_agentText_81non_5",tabText:"_tabText_81non_6",hint:"_hint_81non_6",matchSelection:"_matchSelection_81non_10",focus:"_focus_81non_16",resetIndent:"_resetIndent_81non_20",matchKeyword:"_matchKeyword_81non_24",matchPlaceholder:"_matchPlaceholder_81non_25",hover:"_hover_81non_31",hintText:"_hintText_81non_64",popover:"_popover_81non_72",popoverRoot:"_popoverRoot_81non_77",popoverContentContainer:"_popoverContentContainer_81non_81",popoverContent:"_popoverContent_81non_81",selectionOptions:"_selectionOptions_81non_107",selectionOptionsIsHidden:"_selectionOptionsIsHidden_81non_112",selectionOptionsButton:"_selectionOptionsButton_81non_116",caret:"_caret_81non_132",popoverSuggestionsRoot:"_popoverSuggestionsRoot_81non_136",suggestionsOverlayInputStyles:"_suggestionsOverlayInputStyles_81non_141"};import rh from"classnames";import{Matcher as ih}from"interweave";import{useEffect as ah,useMemo as lh}from"react";import{useEffect as Kf,useRef as Uf,useState as zf}from"react";function Bl(t,e){let o;return[(...n)=>{window.cancelAnimationFrame(o);let s=e?e(...n):n;o=window.requestAnimationFrame(()=>{t(...s)})},()=>window.cancelAnimationFrame(o)]}function pn(t){let e=Uf(null),[o,n]=zf(!1);return Kf(()=>{let s=!1,r=parseFloat(window.getComputedStyle(document.body).zoom??"1"),[i,a]=Bl((d,p)=>{let g=e.current;if(!g)return;let u=d/r,f=p/r,m=g.getBoundingClientRect(),v=u>m.x&&u<m.x+m.width&&f>m.y&&f<m.y+m.height;v&&!s?(s=!0,n(!0)):!v&&s&&(s=!1,n(!1))},({clientX:d,clientY:p})=>[d,p]),[l,c]=Bl(()=>{s=!1,n(!1)});return t.addEventListener("mousemove",i),t.addEventListener("mouseleave",l),()=>{a(),c(),t.removeEventListener("mousemove",i),t.removeEventListener("mouseleave",l)}},[e]),[e,o]}function Kl(t){return t.replace(/[.*+^${}()|[\]\\]/g,"\\$&")}function un(t){return e=>{t.forEach(o=>{typeof o=="function"?o(e):o!=null&&(o.current=e)})}}function Ul(t){return t!=null}import $l from"classnames";import{createRef as Jf,useCallback as er,useMemo as Yf,useRef as eh,useState as th}from"react";import{useState as jf,useLayoutEffect as Vf}from"react";var qf=["bottom","height","left","right","top","width"],$f=(t={},e={})=>qf.some(o=>t[o]!==e[o]),be=new Map,zl,jl=()=>{let t=[],e=[];be.forEach((o,n)=>{if(n instanceof Element&&!n.isConnected){e.push(n);return}let s=n.getBoundingClientRect();$f(s,o.rect)&&(o.rect=s,t.push(o))}),e.forEach(o=>{be.delete(o)}),t.forEach(o=>{o.callbacks.forEach(n=>n(o.rect))}),zl=window.requestAnimationFrame(jl)};function Wf(t,e){return{observe(){let o=be.size===0;if(be.has(t)){let n=be.get(t);n.callbacks.push(e),n.rect&&e(n.rect)}else be.set(t,{rect:void 0,hasRectChanged:!1,callbacks:[e]});o&&jl()},unobserve(){let o=be.get(t);if(o){let n=o.callbacks.indexOf(e);n>=0&&o.callbacks.splice(n,1),o.callbacks.length||be.delete(t),be.size||cancelAnimationFrame(zl)}}}}function Ys(t){let[e,o]=jf(null);return Vf(()=>{if(!t.current)return;let n=Wf(t.current,s=>{o(s)});return n.observe(),()=>{n.unobserve()}},[t]),e}import{useContext as Gf,useLayoutEffect as Xf,useState as Zf}from"react";import{createPortal as Qf}from"react-dom";var Vl={root:"_root_1jq08_1"};var ql=({children:t})=>{let[e,o]=Zf(null),n=Gf(Pt);return Xf(()=>{let s=document.createElement("div");return Ge(s),s.classList.add(Vl.root),n!=null&&n.portalRootNode&&s.classList.add(n==null?void 0:n.portalRootNode),document.body.appendChild(s),o(s),()=>{s.isConnected&&document.body.removeChild(s)}},[]),e?Qf(t,e):null};var pe={ref:"_ref_1rcyi_1",root:"_root_1rcyi_7",positionAbove:"_positionAbove_1rcyi_13",positionBelow:"_positionBelow_1rcyi_17",positionLeft:"_positionLeft_1rcyi_21",positionRight:"_positionRight_1rcyi_25",alignStart:"_alignStart_1rcyi_29",alignCenter:"_alignCenter_1rcyi_34",alignEnd:"_alignEnd_1rcyi_40"};import{jsx as tr}from"react/jsx-runtime";var gn=(t=!1)=>{let[e,o]=th(t),n=er(()=>o(!0),[]),s=er(()=>o(!1),[]),r=er(()=>o(a=>!a),[]),i=eh(null);return{opened:e,open:n,close:s,toggle:r,triggerRef:i}};function or(t,e=null,o=0){if(!t)return{display:"none"};let n=e?t.top-e.top<0||t.top<e.top-o?e.top-o:t.top+t.height>e.top+e.height+o?e.top+e.height+o-t.height:t.top:t.top,s=e?t.left<e.left-o?e.left-o:t.left+t.width>e.left+e.width+o?e.left+e.width+o-t.width:t.left:t.left;return{top:n,left:s,height:t.height,width:t.width}}var mn=({className:t,triggerRef:e,boundaryRef:o=Jf(),position:n="above",align:s="center",children:r,toStyle:i=or,...a})=>{let l=Ys(e),c=Ys(o),d=Yf(()=>i(l,c,0),[l,c]);return tr(ql,{children:tr("div",{className:$l(pe.ref,{[pe.positionAbove]:n==="above",[pe.positionBelow]:n==="below",[pe.positionLeft]:n==="left",[pe.positionRight]:n==="right",[pe.alignStart]:s==="start",[pe.alignCenter]:s==="center",[pe.alignEnd]:s==="end"}),style:d,...a,role:"dialog",children:tr("div",{className:$l(t,pe.root),children:r})})})};import oh from"classnames";import{forwardRef as nh,useRef as sh}from"react";var we={root:"_root_81non_1",container:"_container_81non_3",agentText:"_agentText_81non_5",tabText:"_tabText_81non_6",hint:"_hint_81non_6",matchSelection:"_matchSelection_81non_10",focus:"_focus_81non_16",resetIndent:"_resetIndent_81non_20",matchKeyword:"_matchKeyword_81non_24",matchPlaceholder:"_matchPlaceholder_81non_25",hover:"_hover_81non_31",hintText:"_hintText_81non_64",popover:"_popover_81non_72",popoverRoot:"_popoverRoot_81non_77",popoverContentContainer:"_popoverContentContainer_81non_81",popoverContent:"_popoverContent_81non_81",selectionOptions:"_selectionOptions_81non_107",selectionOptionsIsHidden:"_selectionOptionsIsHidden_81non_112",selectionOptionsButton:"_selectionOptionsButton_81non_116",caret:"_caret_81non_132",popoverSuggestionsRoot:"_popoverSuggestionsRoot_81non_136",suggestionsOverlayInputStyles:"_suggestionsOverlayInputStyles_81non_141"};import{jsx as Wl}from"react/jsx-runtime";var fn=nh(({className:t,children:e,...o},n)=>{let s=sh(null),r=h("TabCompletion",we);return Wl("div",{ref:un([s,n]),className:oh(t,r.popoverContentContainer),...o,children:Wl("div",{className:r.popoverContent,children:e})})});import{jsx as to,jsxs as ph}from"react/jsx-runtime";var ch=t=>e=>{let o=or(e);return"top"in o&&(o.width=t.width-(e.left-t.left)-10),o},dh=({inputElement:t,boundaryRef:e,inputStyle:o,children:n,suggestion:s})=>{let r=h("TabCompletion",we),i=gn(),a=lh(()=>ch(t.getBoundingClientRect()),[t]),[l,c]=pn(t);return ah(()=>{c?i.open():i.close()},[c]),ph("span",{children:[to("mark",{ref:un([l,i.triggerRef]),className:rh(r.matchKeyword,{[r.hover]:c}),"aria-haspopup":"dialog","aria-expanded":i.opened?"true":"false",children:n}),i.opened&&to(mn,{className:r.popover,triggerRef:i.triggerRef,boundaryRef:e,position:"below",align:"start",toStyle:a,children:to(fn,{style:o,children:to("div",{className:r.hintText,children:s})})})]})},hn=class extends ih{keywordMatches=[];preparedKeywordMatches=[];usedKeywordMatches=new Set;onBeforeParse(e,o){return o.keywordMatches&&o.keywordMatches!==this.keywordMatches&&(this.preparedKeywordMatches=o.keywordMatches.map(n=>({...n,keywordRegex:new RegExp(`\\b${Kl(n.keyword)}\\b`,"i")})),this.keywordMatches=o.keywordMatches),this.usedKeywordMatches.clear(),e}match(e){let o=this.preparedKeywordMatches.map(s=>{if(this.usedKeywordMatches.has(s))return null;let r=e.match(s.keywordRegex);if(!r)return null;let i=e.charAt(r.index-1),a=e.charAt(r.index+s.keyword.length);return i==="{"&&a==="}"?null:{index:r.index,length:r[0].length,match:r[0],matchString:r[0],suggestion:s.suggestion,preparedKeywordMatch:s,valid:!0}}).filter(Ul);if(o.length===0)return null;let n=o.reduce((s,r)=>r.index<s.index?r:s);return this.usedKeywordMatches.add(n.preparedKeywordMatch),n}replaceWith(e,o){return to(dh,{inputElement:o.inputElement,suggestion:o.suggestion,inputStyle:o.inputStyle,boundaryRef:o.boundaryRef,children:e},`keyword_${o.matchString}_${o.key}`)}asTag(){return"mark"}};import{Matcher as uh}from"interweave";import gh from"classnames";import{jsx as Gl}from"react/jsx-runtime";var mh=({inputElement:t,children:e})=>{let o=h("TabCompletion",we),[n,s]=pn(t);return Gl("mark",{ref:n,className:gh(o.matchPlaceholder,{[o.hover]:s}),children:e})},yn=class extends uh{match(e){let o=e.match(/(((\$!\{)|(\{))[a-zA-Z0-9_.]+\}(?!\}))/);return o?{index:o.index,length:o[0].length,match:o[0],matchString:o[0],valid:!0}:null}replaceWith(e,o){return Gl(mh,{inputElement:o.inputElement,children:e},`placeholder_${o.matchString}_${o.key}`)}asTag(){return"mark"}};import ar from"classnames";import{Matcher as wh}from"interweave";import{createRef as Ch,forwardRef as Th,useCallback as Eh,useEffect as oc,useRef as nc,useState as sc}from"react";import{useDispatch as kh}from"react-redux";import{jsx as Xl}from"react/jsx-runtime";var Zl=()=>Xl("svg",{width:"1.3em",height:"1.3em",focusable:"false","aria-hidden":"true",viewBox:"0 0 24 24","data-testid":"InsertLinkIcon",tabIndex:-1,children:Xl("path",{fill:"currentColor",d:"M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76 0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71 0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71 0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76 0 5-2.24 5-5s-2.24-5-5-5z"})});import{useCallback as fh,useEffect as Jl,useState as Yl}from"react";import{useDispatch as hh,useSelector as ec}from"react-redux";import yh from"lodash.debounce";var Ql={root:"_root_1muu8_1",content:"_content_1muu8_7"};function vn(t,e,o){var s;let n=((s=t.imageSizes)==null?void 0:s[e])||t.image||o;if(!n)return null;try{return new URL(n).toString()}catch{return null}}function nr(t){return t.replace("https://www.","").replace("https://","")}import{jsx as Ze,jsxs as sr}from"react/jsx-runtime";var vh=3,Sh=t=>({image:t.image||"",text:t.text,id:t.id,title:t.title}),_h=({onSelectLink:t,onDismiss:e,placeholder:o,visitUrlText:n,linkCount:s=vh})=>{let r=h("LinkSearch",Ql),[i,a]=Yl(""),l=hh(),c=ec(Ja("url")),d=ec(Ci("URL",Sh)),[p,g]=Yl(d.length-1),u=b("fallbackImage"),f=_=>{let y=_.target;a(y.value)},m=(_,y)=>{_.stopPropagation(),_.preventDefault(),window.open(y,"_blank")},v=_=>{var S;let y=p-1<0?d.length-1:p-1,x=p+1===d.length?0:p+1;_.code==="Escape"&&(a(""),e()),_.code==="ArrowUp"&&g(y),_.code==="ArrowDown"&&g(x),_.code==="Enter"&&t(((S=d[p])==null?void 0:S.text)||i)},T=fh(yh(_=>{l(ze({query:_,type:"URL",tags:["link-search"]}))},300),[]);return Jl(()=>{i&&T(i)},[i]),Jl(()=>()=>{l(Po())},[]),sr("div",{className:r.root,children:[Ze(te,{withDivider:!0,children:(i?d:c).slice(0,s).map((_,y)=>Ze(L,{selected:p===y,onClick:()=>t(_.text),"data-testid":"linksearch-suggestion",children:sr(N,{children:[Ze(N.Image,{src:vn(_,"small",u||void 0),title:_.title||_.text}),sr(N.Content,{className:r.content,cropText:!0,children:[Ze(N.Title,{children:_.title||nr(_.text)}),_.title&&nr(_.text)]}),Ze(L.Actions,{children:Ze(L.ActionButton,{label:n,onClick:x=>m(x,_.text)})})]})},_.text))}),Ze(jt,{value:i,onChange:f,autoFocus:!0,placeholder:o,onKeyUp:v})]})},tc=_h;var rr={};Z(rr,{enUS:()=>xh,nlNL:()=>bh});var xh={insertLink:[{type:0,value:"Insert link"}],linkInputPlaceholder:[{type:0,value:"Search, type or paste link"}],visitUrl:[{type:0,value:"Visit"}]},bh={insertLink:[{type:0,value:"Voeg link toe"}],linkInputPlaceholder:[{type:0,value:"Zoek, typ of plak link"}],visitUrl:[{type:0,value:"Bekijk"}]};import{jsx as ue,jsxs as ir}from"react/jsx-runtime";var Ih=Th((t,e)=>{let o=h("TabCompletion",we);return ue("mark",{ref:e,className:ar(o.matchSelection)},"selection-start")}),Rh=({startRef:t,boundaryRef:e,inputStyle:o,inputElement:n,children:s})=>{let r=E(rr),i=h("TabCompletion",we),a=nc(null),l=nc(null),[c,d]=sc(null),p=kh(),g=gn(document.activeElement===n),[u]=sc(()=>document.createRange());g.triggerRef.current=u,oc(()=>()=>u.detach(),[]),oc(()=>{let m=t.current,v=a.current;!m||!v||(u.setStart(m,0),u.setEnd(v,0))},[t.current,a.current]),vt(()=>{g.close()});let f=Eh(m=>{let v=u.toString(),T=/^http(s?):\/\//.test(m)?m:`https://${m}`;p(To({text:`[${v}](${T})`,replace:"selection"}))},[]);return ir("span",{children:[ue("mark",{ref:a,className:ar(i.matchSelection),"aria-haspopup":"dialog","aria-expanded":g.opened?"true":"false",children:s}),g.opened&&ue(mn,{className:i.popoverRoot,triggerRef:g.triggerRef,boundaryRef:e,position:"above",align:"start",children:ir(fn,{style:o,ref:l,children:[ue("div",{className:ar(i.selectionOptions,{[i.selectionOptionsIsHidden]:c!==null}),children:ir("button",{type:"button",tabIndex:c===null?-1:void 0,className:i.selectionOptionsButton,onClick:()=>d("insertLink"),children:[ue(Zl,{}),ue("span",{children:"\xA0"}),ue("span",{children:r("insertLink")})]})}),c==="insertLink"&&ue(tc,{placeholder:r("linkInputPlaceholder"),visitUrlText:r("visitUrl"),onSelectLink:f,onDismiss:()=>{d(null),g.close()}})]})})]},"selection-end")},Sn=class extends wh{charCount=0;foundIndex=0;startRef=null;props;onBeforeParse(e,o){return this.props=o,this.charCount=0,this.startRef=Ch(),this.foundIndex=0,e}match(e){if(!this.props||this.props.selection===null||this.foundIndex===2)return null;let[o,n]=this.props.selection;if(o===n)return null;let s=this.foundIndex===0?o:n,r=s>=this.charCount&&s<=this.charCount+e.length?{index:s-this.charCount,length:0,match:"",valid:!0}:null;r&&this.foundIndex++;let i=this.foundIndex===1;return r&&i?this.charCount+=s-this.charCount:this.charCount+=e.length,r?{isStart:i,...r}:null}replaceWith(e,o){return o.isStart?ue(Ih,{ref:this.startRef}):ue(Rh,{inputElement:o.inputElement,startRef:this.startRef,boundaryRef:o.boundaryRef,inputStyle:o.inputStyle})}asTag(){return"mark"}};import{useSelector as Nh}from"react-redux";import{jsx as _t,jsxs as Fh}from"react/jsx-runtime";var Dh=({enabled:t,content:e,tabText:o,showTabHint:n,showTabCompletion:s,showStyleSuggestions:r,keywordMatches:i,inputElement:a,source:l})=>{let c=h("TabCompletion",Fl),d=b("insertLink"),p=b("showMidSentenceSuggestions"),g=b("inlineSuggestions"),u=Dl(a),f=Mh(null),m=Nh(G);Lh(()=>{De(a)&&u&&Hl(a,u)},[u]);let v=Ah(y=>{if(!s||!o)return y;let x=[_t("span",{className:c.resetIndent,children:"\u200B"},"u200B"),_t("span",{"data-testid":"tab-completion",className:lr(c.tabText,c.resetIndent),"data-source":l,children:o},"tabText")];return n&&x.push(_t("span",{className:lr(c.hint,c.resetIndent),children:_t(jn,{keyCode:"tab"},"tabHint")})),Js(y,x)},[s,o,n]),T=rc(()=>{let y=[];return d&&y.push(new Sn("selection")),y.push(new yn("placeholders")),r&&y.push(new hn("keywords")),y},[g,d,r]),_=rc(()=>{let y=window.getComputedStyle(a);return{"--dd-color":y.color,"--dd-font-size":y.fontSize,"--dd-font-family":y.fontFamily,"--dd-font-variant":y.fontVariant}},[]);return!t||!m?null:Fh("div",{ref:y=>{y!=null&&y.parentElement&&(f.current=y==null?void 0:y.parentElement)},className:c.root,style:_,children:[_t(Ph,{tagName:"span",containerTagName:"div",className:lr(c.container,c.agentText),disableLineBreaks:De(a),content:e||"\u200B",onAfterParse:v,matchers:T,selection:u,keywordMatches:i,inputElement:a,inputStyle:_,boundaryRef:f,inlineSuggestionsOnlyAtEnd:!p}),_t("br",{})]})},Hh=({input:t,ui:e,settings:o,styleSuggestions:n,conversation:s})=>{var m;let{tabCompletionSuggestion:r}=t,i=(r==null?void 0:r.text)||"",a=(r==null?void 0:r.source)||"",l=t.html??Wt(t.text),c=i.indexOf(t.text)===0?i.slice(t.text.length):"",{showTabHint:d}=e,{isSupported:p}=s,{showTabCompletion:g,visible:u,showStyleSuggestions:f}=o;return{showTabHint:d,showStyleSuggestions:f,showTabCompletion:g,content:l,tabText:c,source:a,keywordMatches:((m=n.list)==null?void 0:m.keywordMatches)??[],enabled:u&&p!==!1}},ic=Oh(Hh)(Dh);import Ey from"classnames";import{useEffect as ky}from"react";import{useDispatch as Iy,useSelector as X}from"react-redux";import{createAsyncThunk as oo,createSlice as Bh}from"@reduxjs/toolkit";var ac={list:[],fetchState:"idle",isInitialRequest:null},cc=t=>t.autoflows.list||[],lc=t=>e=>{var o;return(o=e.list)==null?void 0:o.find(n=>n.triggerPayload===t)},Ce=oo("autoflows/getAll",async(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");return o.getAutoflows(t)}),cr=oo("autoflows/start",async(t,e)=>{let{dispatch:o}=e,{deepdeskBrokerAPI:n}=e.extra;if(!n)throw new Error("Deepdesk Broker not initialized");await n.startAutoflowSession(t),await o(Ce(t.platformSessionId))}),dr=oo("autoflows/stop",async(t,e)=>{let{dispatch:o}=e,{deepdeskBrokerAPI:n}=e.extra;if(!n)throw new Error("Deepdesk Broker not initialized");await n.stopAutoflowSession(t.platformSessionId),await o(Ce(t.platformSessionId))}),Kh=Bh({name:"autoflows",initialState:ac,reducers:{},extraReducers:t=>{t.addCase(cr.pending,(e,o)=>{let n=lc(o.meta.arg.triggerPayload)(e);n.state="Started",n.isBusy=!0}),t.addCase(dr.pending,(e,o)=>{let n=lc(o.meta.arg.triggerPayload)(e);n.state="Aborted",n.isBusy=!0}),t.addCase(Ce.pending,e=>{e.isInitialRequest=e.isInitialRequest===null,e.fetchState="loading"}),t.addCase(Ce.rejected,e=>{e.fetchState="error"}),t.addCase(Ce.fulfilled,(e,o)=>{e.list=o.payload,e.fetchState="done"}),t.addCase(M,()=>ac)}}),dc=oo("autoflows/openStream",(t,e)=>{let{dispatch:o}=e,{deepdeskBrokerAPI:n}=e.extra;if(!n)throw new Error("Deepdesk Broker not initialized");let s=n.openStream(t);s.on("sessionAborted",()=>{o(Ce(t))}),s.on("sessionCompleted",()=>{o(Ce(t))})}),pc=oo("autoflows/closeStream",(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");o.closeStream(t)}),uc=Kh.reducer;import{createAsyncThunk as so,createSlice as Uh}from"@reduxjs/toolkit";var gc={list:[],fetchState:"idle",isInitialRequest:null,sentSuggestions:[],errorSuggestions:[],answeredSuggestions:[]},mc=t=>t.customMessages.list,fc=t=>e=>!!e.customMessages.sentSuggestions.find(o=>o===t),hc=t=>e=>!!e.customMessages.answeredSuggestions.find(o=>o===t),yc=t=>e=>!!e.customMessages.errorSuggestions.find(o=>o===t),no=so("customMessages/getAll",async(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");return o.getCustomMessages(t)}),_n=so("customMessages/send",async(t,e)=>{let{platformSessionId:o,suggestion:n}=t,{deepdeskBrokerAPI:s}=e.extra;if(!s)throw new Error("Deepdesk Broker not initialized");await s.sendCustomMessage(o,n)}),xn=so("customMessages/answer",async(t,e)=>{let{platformSessionId:o,reply:n}=t,{deepdeskBrokerAPI:s}=e.extra;if(!s)throw new Error("Deepdesk Broker not initialized");await s.answerCustomMessage(o,n)}),vc=Uh({name:"customMessages",initialState:gc,reducers:{onCustomMessage(t,e){Array.isArray(e.payload)?t.list=e.payload:t.list=[e.payload]}},extraReducers:t=>{t.addCase(no.pending,e=>{e.isInitialRequest=e.isInitialRequest===null,e.fetchState="loading"}).addCase(no.rejected,e=>{e.fetchState="error"}).addCase(no.fulfilled,(e,o)=>{e.fetchState="done",e.list=o.payload||[]}).addCase(_n.pending,(e,o)=>{e.sentSuggestions.push(o.meta.arg.suggestion.text),e.errorSuggestions=e.errorSuggestions.filter(n=>o.meta.arg.suggestion.text!==n)}).addCase(_n.rejected,(e,o)=>{let n=e.sentSuggestions.indexOf(o.meta.arg.suggestion.text);e.errorSuggestions.push(...e.sentSuggestions.splice(n,1))}).addCase(xn.pending,(e,o)=>{e.sentSuggestions.push(o.meta.arg.suggestion.text),e.answeredSuggestions.push(o.meta.arg.suggestion.text)}).addCase(xn.rejected,(e,o)=>{let n=e.answeredSuggestions.indexOf(o.meta.arg.suggestion.text);e.errorSuggestions.push(...e.sentSuggestions.splice(n,1)),e.answeredSuggestions.splice(n,1)}).addCase(M,()=>gc)}}),Sc=so("customMessages/openStream",(t,e)=>{let{dispatch:o}=e,{deepdeskBrokerAPI:n}=e.extra;if(!n)throw new Error("Deepdesk Broker not initialized");n.openStream(t).on("customMessageSuggestion",r=>{o(vc.actions.onCustomMessage(r))})}),_c=so("customMessages/closeStream",(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");o.closeStream(t)}),xc=vc.reducer;import{createAsyncThunk as bc,createSlice as zh}from"@reduxjs/toolkit";var jh={token:null,accountUrl:null,interval:null},wc=t=>e=>{let{passwordlessToken:{token:o,accountUrl:n}}=e;return o&&n?`${n}/apis/admin/session/passwordless/login/?token=${o}&redirect=${t}`:null},pr=bc("passwordlessToken/getTemporaryPasswordlessToken",async(t,e)=>{let{deepdeskAPI:o}=e.extra,n=await o.requestPasswordlessToken();return{accountUrl:o.client.baseUrl,token:n}}),ur=bc("passwordlessToken/pollPasswordlessToken",(t={},e)=>{let{interval:o=1e3*60*10}=t,{dispatch:n}=e;return n(pr()),setInterval(()=>n(pr()),o)}),Cc=zh({name:"passwordlessToken",initialState:jh,reducers:{stopPollPasswordlessToken(t){t.interval&&clearInterval(t.interval),t.interval=null}},extraReducers:t=>{t.addCase(pr.fulfilled,(e,o)=>{e.token=o.payload.token,e.accountUrl=o.payload.accountUrl}),t.addCase(ur.fulfilled,(e,o)=>{e.interval=o.payload})}}),{stopPollPasswordlessToken:Tc}=Cc.actions,Ec=Cc.reducer;function kc(t){let{customMessages:e,autoflows:o}=t;return o.fetchState==="loading"&&o.isInitialRequest===!0||e.fetchState==="loading"&&e.isInitialRequest===!0}import{Fragment as Yh}from"react";import{connect as ey}from"react-redux";import Zh from"classnames";import{Fragment as Qh}from"react";import Vh from"classnames";var Ic={root:"_root_838fd_1"};import{jsx as $h}from"react/jsx-runtime";var qh=({className:t,children:e})=>{let o=h("Unicode",Ic);return $h("span",{className:Vh(t,o.root),children:e})},Rc=qh;var Pc={isDisabled:"_isDisabled_1rmfm_1",buttonStart:"_buttonStart_1rmfm_5",root:"_root_1rmfm_8",buttonStop:"_buttonStop_1rmfm_8",stateBadge:"_stateBadge_1rmfm_19",isCompleted:"_isCompleted_1rmfm_26",isStarted:"_isStarted_1rmfm_30",isAborted:"_isAborted_1rmfm_34"};var gr={};Z(gr,{enUS:()=>Wh,nlNL:()=>Gh});var Wh={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"}]},Gh={start:[{type:0,value:"Start"}],stop:[{type:0,value:"Stop"}],aborted:[{type:0,value:"Stopped"}],completed:[{type:0,value:"Completed"}],Aborted:[{type:0,value:"Stopped"}],Started:[{type:0,value:"Running"}],Completed:[{type:0,value:"Completed"}]};import{jsx as Qe,jsxs as bn}from"react/jsx-runtime";var Jh=({disabled:t,state:e,displayName:o,description:n,onStartAutoflow:s,onStopAutoflow:r})=>{let i=h("Autoflow",Pc),a=E(gr),l=e==="Started"?"stop":"start",c=l==="start"?"\u25B6":l==="stop"?"\u25FC":"";return bn(L,{className:Zh(i.root,{[i.isDisabled]:t,[i.isCompleted]:e==="Completed",[i.isAborted]:e==="Aborted",[i.isStarted]:e==="Started"}),children:[Qe(N,{children:bn(N.Content,{children:[bn(N.Title,{children:[e&&Qe("span",{className:i.stateBadge,children:a(e)}),o]}),Qe("span",{children:n})]})}),Qe(L.Actions,{fixed:e==="Started",children:Qe(L.ActionButton,{primary:!0,className:l==="start"?i.buttonStart:i.buttonStop,onClick:e==="Started"?r:s,disabled:t,label:bn(Qh,{children:[Qe(Rc,{children:c})," ",Qe("span",{children:a(l)})]})})})]})},Ac=Jh;import{jsx as Lc}from"react/jsx-runtime";var ty=(t,e)=>{let o=e.filter(n=>n.state==="Started");return o.length>0?o.indexOf(t)===-1:!1},oy=({autoflows:t,onStartAutoflow:e,onStopAutoflow:o,platformSessionId:n})=>Lc(Yh,{children:t.map(s=>Lc(Ac,{displayName:s.displayName,description:s.description,disabled:s.isBusy||ty(s,t),state:s.state,onStartAutoflow:()=>e({platformSessionId:n,triggerPayload:s.triggerPayload}),onStopAutoflow:()=>o({platformSessionId:n,triggerPayload:s.triggerPayload})},s.displayName))}),ny=({autoflows:t,conversation:e})=>{var o;return{autoflows:t.list,platformSessionId:(o=e.current)==null?void 0:o.sessionId}},sy={onStartAutoflow:cr,onStopAutoflow:dr},Mc=ey(ny,sy)(oy);import ry from"classnames";import{useCallback as Oc}from"react";import{useDispatch as iy,useSelector as wn}from"react-redux";var Te={root:"_root_1e6ej_1",title:"_title_1e6ej_8",isUsed:"_isUsed_1e6ej_13",quickReplies:"_quickReplies_1e6ej_22",quickReply:"_quickReply_1e6ej_29",hasError:"_hasError_1e6ej_39",label:"_label_1e6ej_43",errorIcon:"_errorIcon_1e6ej_48"};import{jsx as He,jsxs as Cn}from"react/jsx-runtime";var ay=({suggestion:t})=>{let e=E($e),o=iy(),n=wn(fc(t.text)),s=wn(hc(t.text)),r=wn(yc(t.text)),i=wn(vo),{replyOptions:a}=t,l=Oc(d=>{d.preventDefault(),d.stopPropagation(),!(n||!i)&&o(_n({platformSessionId:i,suggestion:t}))},[t,n,o,i]),c=Oc(d=>{if(d.preventDefault(),d.stopPropagation(),!i||!a)return;let p=parseInt(d.target.dataset.index,10),g=a[p];o(xn({platformSessionId:i,reply:g,suggestion:t}))},[t,n,o,i]);return Cn(L,{onClick:l,className:ry(Te.root,{[Te.isUsed]:n,[Te.hasError]:r}),children:[He(N,{children:Cn(N.Content,{children:[Cn(N.Title,{className:Te.title,children:[t.text," ",He(Vn,{className:Te.label,children:"analyse tool"})," ",r&&He("span",{className:Te.errorIcon,role:"img","aria-label":e("sendingError"),title:e("sendingError"),children:"!"})]}),a&&a.length>0&&He("ul",{className:Te.quickReplies,children:a.map(d=>He("li",{className:Te.quickReply,children:d.title},d.title))})]})}),Cn(L.Actions,{fixed:r||n,children:[a&&a.length>0&&He(L.DropdownButton,{label:e("answer"),disabled:s,children:a.map((d,p)=>He(L.DropdownItem,{index:p,label:d.title,onClick:c},d.title))}),He(L.ActionButton,{primary:!0,disabled:n,onClick:l,label:e(n?"suggestionSent":r?"tryAgain":"sendSuggestion")})]})]})},Nc=ay;import{useEffect as ly,useState as cy}from"react";import{useDispatch as dy}from"react-redux";import Fc from"classnames";import{jsx as Dc}from"react/jsx-runtime";var mr=()=>Dc("svg",{width:"1em",height:"1em",viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",children:Dc("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 Hc={root:"_root_rjdyr_1",entity:"_entity_rjdyr_10",entityText:"_entityText_rjdyr_46",iconWrapper:"_iconWrapper_rjdyr_53",icon:"_icon_rjdyr_53",iconClicked:"_iconClicked_rjdyr_67"};import{jsx as xt,jsxs as Bc}from"react/jsx-runtime";var py=({entities:t})=>{let e=h("EntitiesWidgetList",Hc),[o,n]=cy(void 0),s=dy(),r=()=>{n(void 0)},i=a=>{t&&(n(t.indexOf(a)),qt(a.text),s($({name:"entity copied",data:{entity:a,type:"copy"}})))};return ly(()=>{let a=setTimeout(r,500);return()=>{clearTimeout(a)}},[o]),!t||t.length===0?null:xt("div",{className:e.root,"data-testid":"widget-entities-list",children:t.map((a,l)=>Bc("button",{title:a.text,className:e.entity,type:"button",onClick:()=>i(a),children:[xt("span",{className:e.entityText,children:a.text}),Bc("span",{className:e.iconWrapper,children:[xt("span",{className:Fc(e.icon),children:xt(mr,{})}),xt("span",{className:Fc(e.icon,o===l&&e.iconClicked),children:xt(mr,{})})]})]},a.text))})},Kc=py;import{jsx as Uc}from"react/jsx-runtime";var zc=()=>Uc("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:Uc("path",{d:"M17 13.5v6H5v-12h6m3-3h6v6m0-6-9 9",stroke:"currentColor",strokeWidth:"1.5",fill:"none",fillRule:"evenodd",strokeLinecap:"round",strokeLinejoin:"round"})});import{jsx as jc}from"react/jsx-runtime";var Vc=()=>jc("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:jc("path",{d:"M543-340q16.595 0 28.798-12.202Q584-364.405 584-381t-12.202-28.798Q559.595-422 543-422t-28.798 12.202Q502-397.595 502-381t12.202 28.798Q526.405-340 543-340Zm-25-126h47q2-29 8.5-43t32.5-39q27-26 37.5-45.395Q654-612.79 654-639q0-45.882-31.5-74.941Q591-743 540-743q-38 0-68 20.5T428-665l45 19q11-25 27.5-38t39.5-13q29.778 0 48.389 17Q607-663 607-637q0 20-9 35t-32 32q-32 29-40 46.5t-8 57.5ZM260-200q-24 0-42-18t-18-42v-560q0-24 18-42t42-18h560q24 0 42 18t18 42v560q0 24-18 42t-42 18H260Zm0-60h560v-560H260v560ZM140-80q-24 0-42-18t-18-42v-620h60v620h620v60H140Zm120-740v560-560Z"})});import{jsx as qc}from"react/jsx-runtime";var $c=()=>qc("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:qc("path",{d:"M319-250h322v-60H319v60Zm0-170h322v-60H319v60ZM220-80q-24 0-42-18t-18-42v-680q0-24 18-42t42-18h361l219 219v521q0 24-18 42t-42 18H220Zm331-554v-186H220v680h520v-494H551ZM220-820v186-186 680-680Z"})});import{useEffect as my,useState as fy}from"react";var fr={};Z(fr,{enUS:()=>uy,nlNL:()=>gy});var uy={copyCue:[{type:0,value:"Copy"}],copiedCue:[{type:0,value:"Copied!"}],removeCue:[{type:0,value:"Close"}]},gy={copyCue:[{type:0,value:"Kopieer"}],copiedCue:[{type:0,value:"Gekopieerd!"}],removeCue:[{type:0,value:"Sluiten"}]};import{jsx as ro,jsxs as Wc}from"react/jsx-runtime";var hy=({cue:t,onRemove:e,onCopy:o})=>{let n=E(fr),[s,r]=fy(!1),i=l=>{l.preventDefault(),l.stopPropagation(),o&&(o(t.text),r(!0))},a=l=>{l.preventDefault(),l.stopPropagation(),e&&e(t.id)};return my(()=>{if(!s)return;let l=setTimeout(()=>{r(!1)},1e3);return()=>{clearTimeout(l)}},[s]),ro(L,{"data-testid":"cue",children:Wc(N,{children:[Wc(N.Content,{children:[t.title&&ro(N.Title,{"data-testid":"widget-cue-title",children:t.title}),t.text]}),ro(L.Actions,{children:o&&ro(L.ActionButton,{primary:!0,onClick:i,label:n(s?"copiedCue":"copyCue")})}),ro(N.CloseIcon,{title:n("removeCue"),onClick:a})]})})},Gc=hy;import{Fragment as vy,jsx as Xc}from"react/jsx-runtime";var yy=({cues:t,onCopyCue:e,onRemoveCue:o})=>Xc(vy,{children:t.map(n=>Xc(Gc,{cue:n,onRemove:o,onCopy:e},`${n.id}_${n.timestamp}`))}),Zc=yy;import{useCallback as _y}from"react";var Sy=/(https?:\/\/[^\s]+)/,Qc=t=>t.split(" ").find(e=>Sy.test(e));import{jsx as bt,jsxs as Tn}from"react/jsx-runtime";var xy=({suggestion:t,lines:e,onUse:o})=>{var d;let n=t.text||t.url||t.message,s=Qc(n),r=E($e),i=b("showImages"),a=b("fallbackImage"),l=p=>{p.preventDefault(),p.stopPropagation(),o(n)},c=_y(p=>{window.open(s,"_blank"),p.stopPropagation(),p.preventDefault()},[s]);return Tn(L,{onClick:l,"data-testid":"edit-suggestion",children:[Tn(N,{children:[i&&t.image&&bt(N.Image,{src:vn(t,"small",a||void 0),title:t.title}),Tn(N.Content,{children:[t.title&&bt(N.Title,{"data-testid":"widget-suggestion-title",children:t.title}),t.searchKeywords&&((d=t.searchKeywords)==null?void 0:d.length)>0&&bt(L.Labels,{labels:t.searchKeywords}),bt(N.Content,{cropText:e==="single",lineClamp:e==="multiple",children:n})]})]}),Tn(L.Actions,{children:[s&&bt(L.ActionButton,{onClick:c,label:r("visitUrl")}),bt(L.ActionButton,{primary:!0,onClick:l,label:r("useSuggestion")})]})]})},Jc=xy;import{Fragment as wy,jsx as Yc}from"react/jsx-runtime";var by=({lines:t,suggestions:e})=>{let o=de(),n=(s,r)=>{o.send(pt,{text:s,suggestion:{...r,source:r.source,sourceText:r.text}})};return Yc(wy,{children:e.map(s=>Yc(Jc,{suggestion:s,lines:t,onUse:r=>n(r,s)},s.text||s.url||s.message))})},ed=by;var hr={};Z(hr,{enUS:()=>Cy,nlNL:()=>Ty});var Cy={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"}],titleCues:[{type:0,value:"Assistant updates"}],actions:[{type:0,value:"Shortcuts"}],linkStudioLogin:[{type:0,value:"My "},{type:1,value:"productName"}],linkSummary:[{type:0,value:"Summarize"}],linkKnowledgeSearch:[{type:0,value:"Knowledge Assist"}],linkSearch:[{type:0,value:"Search"}]},Ty={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"}],titleCues:[{type:0,value:"Assistant updates"}],actions:[{type:0,value:"Shortcuts"}],linkStudioLogin:[{type:0,value:"Mijn "},{type:1,value:"productName"}],linkSummary:[{type:0,value:"Gesprek samenvatten"}],linkKnowledgeSearch:[{type:0,value:"Knowledge assist"}],linkSearch:[{type:0,value:"Zoeken"}]};var td={root:"_root_x0pwe_1",loginText:"_loginText_x0pwe_7",stateText:"_stateText_x0pwe_8",sectionList:"_sectionList_x0pwe_20",shortcutList:"_shortcutList_x0pwe_24",shortcut:"_shortcut_x0pwe_24",link:"_link_x0pwe_52"};import{jsx as P,jsxs as wt}from"react/jsx-runtime";var En=(t,e)=>{let o=X(G);ky(()=>o?e.every(n=>!!n)?t():()=>{}:()=>{},[...e,o])},Ry=({onLogIn:t})=>{let e=E(hr),o=Iy(),n=b("isEmbedded"),s=h("Widget",td),r=b("showAutoflows"),i=b("showCustomMessages"),a=b("showSummaryCommand"),l=b("showKnowledgeSearch"),c=b("showSearch"),d=X(Oe),p=X(Qo),g=X(cc),u=X(ki),f=X(Xo),m=X(mc),v=X(So),T=X(at),_=X(G),y=X(vo),x=X(kc),S=X(Jo),O=de(),F=X(Ya),K=X(wc("/admin/")),H=b("adminUrl"),I=b("productName");if(En(()=>(o(no(y)),o(Sc(y)),()=>{o(_c(y))}),[o,T,i,y]),En(()=>(o(Ce(y)),o(dc(y)),()=>{o(pc(y))}),[o,T,r,y]),En(()=>{p.forEach(({type:k})=>{o(k==="entities"?ae():le(k))})},[o,T,v,d]),En(()=>(o(ur()),()=>{o(Tc())}),[o]),T===!1)return P("div",{className:s.stateText,children:P("div",{children:P("p",{children:e("notSupported")})})},"supported");if(_===!1)return P("div",{className:s.loginText,children:P("div",{children:P(cn,{isEmbedded:n,loginUrl:H,onLogIn:t})})},"login");if(!d||!y||_===null||F||x)return P("div",{className:s.stateText,children:P("div",{children:P("p",{children:e("waiting")})})},"waiting");let A=c||a||l||K;return P("div",{className:Ey(s.root),"data-testid":"widget",children:wt($n,{className:s.sectionList,children:[A&&P(ke,{title:e("actions"),type:"shortcuts",children:wt("div",{className:s.shortcutList,children:[c&&wt("button",{className:s.shortcut,"data-testid":"shortcut-search",onClick:()=>O.send("ShowCommandPalette",{isOpen:!0}),children:[P(ut,{}),e("linkSearch")]}),a&&wt("button",{className:s.shortcut,"data-testid":"shortcut-summary",onClick:()=>O.send("ShowCommandPalette",{isOpen:!0,page:"summary"}),children:[P($c,{}),e("linkSummary")]}),l&&wt("button",{className:s.shortcut,"data-testid":"shortcut-knowledge-assist",onClick:()=>O.send("ShowCommandPalette",{isOpen:!0,page:"knowledgeAssist"}),children:[P(Vc,{}),e("linkKnowledgeSearch")]}),K&&wt("a",{className:s.shortcut,target:"_blank",href:K,"data-testid":"shortcut-studio-login",rel:"noreferrer",children:[P(zc,{}),e("linkStudioLogin",{productName:I})]})]})}),i&&m.length>0&&P(ke,{type:"custom-messages","data-testid":"custom-messages",children:P(te,{withDivider:!0,children:m.map(k=>P(Nc,{suggestion:k},k.text))})}),r&&g.length>0&&P(ke,{type:"autoflows",title:e("titleAutoflows"),"data-testid":"autoflows",children:P(te,{withDivider:!0,children:P(Mc,{})})}),p.map(({type:k,title:V,amount:Bn,lines:Kn})=>{var et;switch(k){case"entities":return f&&f.length>0&&P(ke,{type:k,title:V,"data-testid":`type-${k}`,children:P(Kc,{entities:f})},k);case"cues":return u&&u.length>0&&P(ke,{type:k,title:V,"data-testid":`type-${k}`,children:P(te,{withDivider:!0,children:P(Zc,{cues:u,onRemoveCue:Ke=>o(Ri({id:Ke}))})})},k);default:return((et=S[k])==null?void 0:et.fetchState)==="done"&&S[k].suggestions.length>0&&P(ke,{type:k,title:V,"data-testid":`type-${k}`,children:P(te,{withDivider:!0,children:P(ed,{lines:Kn,contentType:k,suggestions:S[k].suggestions.slice(0,Bn)||[]})})},k)}})]})})},od=Ry;function ao(t){let e=new Range;return e.selectNodeContents(t),e}function nd(t,e,o){try{return Je(t,e,o),!0}catch{return!1}}function kn(t){return"tagName"in t&&(t.tagName==="DIV"||t.tagName==="P")}function In(t){return"tagName"in t&&t.tagName==="BR"}var io=/[\u200B-\u200D\uFEFF]/g;function Je(t,e,o){let n=new Range;if(t.firstChild===null&&e===0&&o===0)return n.selectNodeContents(t),n;let s=0,r=!1;function i(l,c){let d=-1,p=/[\u200B-\u200D\uFEFF]/;if(!p.test(l))return c;for(let g=0;g<=l.length;g++)if(p.test(l[g])||d++,d===c)return g;throw new Error("Offset out of range")}function a(l){switch(l.nodeType){case Node.TEXT_NODE:{let c=l.textContent,d=c.replace(io,""),p=s+d.length,g=e>=s&&e<=p,u=o>=s&&o<=p;if(g){let f=i(c,e-s);f===0&&!u?n.setStartBefore(l):n.setStart(l,f)}u&&(n.setEnd(l,i(c,o-s)),r=!0),s=p;break}case Node.ELEMENT_NODE:{if(In(l)&&(s===e&&n.setStartBefore(l),s++,s===o)){n.setEndAfter(l),r=!0;return}for(let d=0;d<l.childNodes.length&&(a(l.childNodes[d]),!r);d++);let c=l.lastChild;kn(l)&&c&&!kn(c)&&!In(c)&&s++;break}default:break}}if(a(t),n.startContainer===document)throw new Error("Offsets out of bound");return n}function Rn(t,e){if(!t.contains(e.startContainer)||!t.contains(e.endContainer))throw new Error("Range not within root element");let{startContainer:o,startOffset:n,endContainer:s,endOffset:r,collapsed:i}=e,a,l,c=0;function d(p){let g=p===o,u=p===s;switch(p.nodeType){case Node.TEXT_NODE:{let f=p.textContent;g&&(a=c+f.substring(0,n).replace(io,"").length),u&&(l=c+f.substring(0,r).replace(io,"").length),c+=f.replace(io,"").length;break}case Node.ELEMENT_NODE:{let f=p.nextSibling===null;In(p)&&!f&&c++;for(let m=0;m<p.childNodes.length;m++){let v=g&&m===n,T=u&&m===r;if(v&&(a=c),T&&(l=c),l!==void 0||((!v||!i)&&d(p.childNodes[m]),u&&m===r-1&&(l=c),l!==void 0))break}!u&&kn(p)&&!f&&c++,u&&(l=c);break}default:break}}if(d(t),l===void 0)throw new Error("Could not determine start and end");return{start:a??l,end:l}}function Pn(t,e){if(!t.contains(e.startContainer)||!t.contains(e.endContainer))throw new Error("Range not within root element");let{startContainer:o,startOffset:n,endContainer:s,endOffset:r}=e,i=-1,a="";function l(c){let d=c===o,p=c===s;switch(d&&i++,c.nodeType){case Node.TEXT_NODE:{if(i!==0)return;let g=d?n:0,u=p?r:void 0,f=c.textContent.replace(io,"");g===0&&u===void 0?a+=f:a+=f.substring(g,u);break}case Node.ELEMENT_NODE:{let g=c.nextSibling===null;i===0&&In(c)&&!g&&(a+=`
|
|
8
8
|
`);for(let u=d?n:0;u<(p?Math.min(r,c.childNodes.length):c.childNodes.length)&&(l(c.childNodes[u]),i!==1);u++);!p&&i===0&&kn(c)&&!g&&(a+=`
|
|
9
|
-
`);break}default:break}p&&i++}return l(t),a}var sd=(i=>(i.CUT="Cut",i.BACKSPACE="Backspace",i.DELETE="Delete",i.ERASEEOF="EraseEof",i.UNDO="Undo",i.CLEAR="Clear",i))(sd||{}),Fe=class{constructor(e){this.element=e;this.currentText=this.getText(),this.currentHTML=this.getHTML(),this.listen()}eventListeners={};disposeHandlers=[];currentText="";currentCaret=null;currentSelection={start:0,end:0};currentHTML="";isFocused=!1;isActive=!0;isSettingValue=!1;isSubmitting=!1;isPossibleClearInputAction=!1;isDisposed=!1;addEventListener(e,o){let n=s=>{o(s)};this.element.addEventListener(e,n),this.disposeHandlers.push(()=>{this.element.removeEventListener(e,n)})}removeEventListener(e,o){this.element.removeEventListener(e,o)}triggerChange(){let e=this.getText(),o=this.getHTML(),n=e!==this.currentText;this.isActive&&(e===""&&this.currentText!==""&&!this.isSettingValue&&!this.isPossibleClearInputAction&&(this.isSubmitting=!0,this.emit("submit")),!this.isSettingValue&&n&&!this.isSubmitting&&this.emit("change",{plainText:e}),n&&(this.currentSelection=this.getSelection()),this.currentText=e,this.isSubmitting=!1,(this.currentHTML!==o||o===null&&n)&&(this.emit("updated",{plainText:e}),this.triggerCaretPosition(),this.currentHTML=o))}triggerSelection(){let e=this.getSelection();(e.start!==this.currentSelection.start||e.end!==this.currentSelection.end)&&(this.currentSelection=e,this.emit("selection",e),this.triggerCaretPosition())}triggerCaretPosition(){let e=this.getCaretPosition();Re(e,this.currentCaret)||(this.currentCaret=e,this.emit("caret",e))}handleKeyUp(e){let{key:o,shiftKey:n}=e;(o==="Enter"&&n===!0||o==="Backspace")&&this.triggerChange(),this.triggerSelection()}handleClick(){this.triggerSelection()}handleFocus(){this.isFocused||this.emit("focus"),this.triggerSelection(),this.isFocused=!0}handleBlur(){this.isPossibleClearInputAction=!1,this.isFocused&&this.emit("blur"),this.isFocused=!1}handleKeyDown(e){let{key:o,ctrlKey:n,metaKey:s}=e;this.isPossibleClearInputAction=Object.values(sd).includes(o)||o.toLowerCase()==="z"&&(n||s),this.emit("keydown",e)}handleCut(){this.isPossibleClearInputAction=!0,this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(e){var n,s;let o=((n=e.clipboardData)==null?void 0:n.getData("text"))||((s=e.clipboardData)==null?void 0:s.getData("text/plain"))||"";this.emit("paste",{pastedText:o,selectionText:this.getSelectedText()})}listen(){this.addEventListener("keydown",o=>this.handleKeyDown(o)),this.addEventListener("keyup",o=>this.handleKeyUp(o)),this.addEventListener("input",()=>this.triggerChange()),this.addEventListener("change",()=>this.triggerChange()),this.addEventListener("focus",()=>this.handleFocus()),this.addEventListener("blur",()=>this.handleBlur()),this.addEventListener("cut",()=>this.handleCut()),this.addEventListener("paste",o=>this.handlePaste(o)),this.addEventListener("click",()=>this.triggerSelection()),document.activeElement===this.element&&setTimeout(()=>{this.handleFocus()},0);let e=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});e.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{e.disconnect()}),this.currentSelection=this.getSelection()}focus(){this.element.focus()}emit(e,...o){this.isDisposed||this.eventListeners[e]&&this.eventListeners[e].forEach(n=>{n(...o)})}on(e,o){this.isDisposed||(this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(o))}activate(){let e=this.isActive===!1;this.isActive=!0,e&&this.triggerChange()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(e=>e()),this.eventListeners={},this.isDisposed=!0}};function rd(t){return t.top!==0||t.left!==0||t.height!==0||t.width!==0}var Ct=class extends Fe{observer;lastKnownSelection=null;getRootNode(){return this.element.getRootNode()}getText(){let e=new Range;return e.selectNodeContents(this.element),Pn(this.element,e)}getHTML(){return this.element.innerHTML||""}getRange(){var r;let e=this.getRootNode();if(e.activeElement!==this.element)return null;let o="getSelection"in e?e.getSelection():window.getSelection();if(!o)return null;let n="getComposedRanges"in o&&e instanceof ShadowRoot?(r=o.getComposedRanges(e))==null?void 0:r[0]:o.rangeCount>0?o.getRangeAt(0):null;if(!n)return null;let s=this.element.ownerDocument.createRange();return s.setStart(n==null?void 0:n.startContainer,n==null?void 0:n.startOffset),s.setEnd(n==null?void 0:n.endContainer,n==null?void 0:n.endOffset),!s||!this.element.contains(s.startContainer)||!this.element.contains(s.endContainer)?null:s}getCaretPosition(){let e=this.getRange();if(!e||!e.collapsed||!("getBoundingClientRect"in e))return null;let o=e.getBoundingClientRect();return!rd(o)&&(e.insertNode(this.element.ownerDocument.createTextNode("\u2060")),o=e.getBoundingClientRect(),e.deleteContents(),!rd(o))?null:{top:o.top+o.height,left:o.left}}getSelection(){let e=this.getRange();if(e)return Rn(this.element,e);let o=this.lastKnownSelection;if(o&&nd(this.element,o.start,o.end))return o;let n=ao(this.element);return n.collapse(!1),Rn(this.element,n)}getSelectedText(){let{start:e,end:o}=this.getSelection();return Pn(this.element,Je(this.element,e,o))}applyChanges(e){var s;if(!this.isActive)return;this.isSettingValue=!0;let o=this.getText(),n=e(this.element);return(s=this.observer)==null||s.takeRecords(),Promise.resolve(n).then(()=>{this.currentText=this.getText(),o!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(){super.listen(),this.observer=new MutationObserver(()=>{setTimeout(()=>{this.triggerChange()},0)}),this.observer.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0});let e=this.element.isContentEditable,o=new MutationObserver(()=>{this.element.isContentEditable!==e&&(e=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>o.disconnect())}dispose(){super.dispose(),this.observer&&this.observer.disconnect()}};var Tt=class extends Fe{lastKnownSelection=null;getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:e,selectionEnd:o}=this.element;return{start:e,end:o}}getSelectedText(){let e=this.getSelection();return e?this.getText().slice(e.start,e.end):""}getCaretPosition(){return null}applyChanges(e){if(!this.isActive)return;this.isSettingValue=!0;let o=this.getText(),n=e(this.element);return Promise.resolve(n).then(()=>{this.currentText=this.getText(),o!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(){super.listen();let e=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var s;return(s=e==null?void 0:e.get)==null?void 0:s.call(this.element)},set:s=>{var r;(r=e==null?void 0:e.set)==null||r.call(this.element,s),this.triggerChange()}});let o=this.element.disabled,n=new MutationObserver(()=>{this.element.disabled!==o&&(o=this.element.disabled,this.emit(o?"disabled":"enabled"))});n.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>n.disconnect())}};function id(t,e,o){let n=`deepdesk-iframe-${t}`,s=document.getElementById(n);if(s)return s;let r=document.createElement("iframe"),i=new URL(e);return Object.entries(o).forEach(([a,l])=>{i.searchParams.append(a,l)}),r.style.position="absolute",r.style.left="-999em",r.style.width="0px",r.style.height="0px",r.tabIndex=-1,r.id=n,r.title=`iframe-${t}`,r.src=i.toString(),window.document.body.appendChild(r),r}var yr=class{constructor(e){this.name=e;this.broadcastChannel=new BroadcastChannel(e)}broadcastChannel;disposeHandlers=[];onMessage(e){this.broadcastChannel.addEventListener("message",e),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",e)})}postMessage(e){this.broadcastChannel.postMessage(JSON.stringify(e))}close(){this.disposeHandlers.forEach(e=>e()),this.broadcastChannel.close()}},vr=class{constructor(e,o,n){this.name=e;this.targetOrigin=o;this.options=n;this.iframe=id(e,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}iframe;disposeHandlers=[];onMessage(e){window.addEventListener("message",e),this.disposeHandlers.push(()=>{window.removeEventListener("message",e)})}postMessage(e){var o;(o=this.iframe.contentWindow)==null||o.postMessage(JSON.stringify(e),this.targetOrigin)}close(){var e;this.disposeHandlers.forEach(o=>o()),(e=this.iframe)==null||e.remove()}},Sr=class{constructor(e){this.params=e;this.deepdeskUrl=e.deepdeskUrl,this.eventMap=e.eventMap,this.sessionId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}sessionId;deepdeskUrl;channel;defaultChannel;eventMap;get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setSessionId(e){this.sessionId!==e&&(this.cleanup(),C.info("Set sessionId",e),this.sessionId=e,this.channel=this.createChannel(e))}createChannel(e){let o=this.params.createCustomChannel?this.params.createCustomChannel(e):this.isCrossOrigin?new vr(e,this.deepdeskUrl,{debug:!0}):new yr(e),n=s=>{var i,a;if(s.origin!==this.deepdeskUrl)return;let r=typeof s.data=="string"?JSON.parse(s.data):s.data;r.type==="event"&&r.channel===e&&(C.info("Received broadcast event",this.sessionId,s),(a=(i=this.eventMap)[r.name])==null||a.call(i,r.payload))};return o.onMessage(n),o}send(e,o,n){var i,a;C.info("Broadcast event",{sessionId:this.sessionId,name:e,payload:o});let s={type:"event",name:e,payload:o};n!==!1&&((a=(i=this.eventMap)[e])==null||a.call(i,o));let r=this.sessionId==="deepdesk-general"?this.defaultChannel:this.channel;r==null||r.postMessage({...s,channel:this.sessionId})}cleanup(e=!1){var o,n;(o=this.channel)==null||o.close(),delete this.channel,e&&((n=this.defaultChannel)==null||n.close(),delete this.defaultChannel)}},ad=Sr;var Et=class extends Error{constructor(o,n){super(o);this.body=n}name="CustomError"};var _r=t=>new Promise(e=>{setTimeout(e,t)});var kt=class extends Et{name="ClientError"},xr=class extends Et{name="ServerError"},ge=class t{constructor(e="",o={}){this.baseUrl=e;this.options=o;o.fetch&&(this.fetch=o.fetch)}latestRequestByUrl={};csrfToken;fetch=window.fetch.bind(window);static refreshingToken=null;patchFetch(e){this.fetch=e(this.fetch)}setCsrfToken(e){this.csrfToken=e}request(e,o={}){return new Promise((n,s)=>{let r={isAborted:!1,reject:s},i=`${this.baseUrl}${e}`,a=this.fetch,{abortLatest:l=!1,attempts:c=1,retryDelay:d=500,refreshTokenOn401:p=!0,retryOnError:g=x=>x instanceof TypeError,retryOnResponse:u=x=>x.status>=500,version:f="v1",...m}=o,v={credentials:"include",...m,headers:{"Content-Type":"application/json",...m.headers}};o.method!==void 0&&o.method!=="GET"&&this.csrfToken&&(v.headers={...v.headers,"X-CSRFToken":this.csrfToken}),typeof f=="string"&&(v.headers={...v.headers,"X-Deepdesk-API-Version":f});let T=c,_=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[i]&&l&&(this.latestRequestByUrl[i].isAborted=!0,this.latestRequestByUrl[i].reject(new Error("Aborted"))),this.latestRequestByUrl[i]=r;let y=async()=>(T--,a(i,v).then(async x=>u(x)&&!r.isAborted&&T>0?(await _r(d),y()):x.status===401&&p===!0&&_===!1?(_=!0,await this.refreshToken(),y()):x).catch(async x=>{if(g(x)&&!r.isAborted&&T>0)return await _r(d),y();throw x}));y().then(x=>x.json().catch(()=>null).then(S=>{x.status>=500?s(new xr("Server Error",S)):x.status===401?s(new kt("Unauthorized",S)):x.status===403?s(new kt("Forbidden",S)):x.status===404?s(new kt("Not Found",S)):x.status>=400&&s(new kt("Bad Request",S)),delete this.latestRequestByUrl[i],n(S)})).catch(x=>{s(x)})})}async validateToken(){let{has_valid_access_token:e}=await this.get("/auth/validate");if(!e)return!1;let{is_logged_in:o}=await this.get("/apis/admin/session/validate/",{version:null});return!!o}refreshToken(){return t.refreshingToken||(t.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{t.refreshingToken=null},1e3*60)})),t.refreshingToken}get(e,o){return this.request(e,o)}post(e,o,n){return this.request(e,{method:"POST",body:JSON.stringify(o),...n})}patch(e,o,n){return this.request(e,{method:"PATCH",body:JSON.stringify(o),...n})}put(e,o,n){return this.request(e,{method:"PUT",body:JSON.stringify(o),...n})}delete(e,o){return this.request(e,{method:"DELETE",...o})}};var Py;(e=>{let t;(l=>(l.SEND_MESSAGE="Send Message",l.HANDLING_TIME="Handling Time",l.START_AUTOFLOW="Start Autoflow",l.ABORT_AUTOFLOW="Abort Autoflow",l.ADD_TO_PERSONAL_COLLECTION="Add to personal collection",l.DELETE_FROM_PERSONAL_COLLECTION="Delete from personal collection"))(t=e.EventType||={})})(Py||={});function An(t){return{...R(t),tags:t.tags}}var Be=class t{constructor(e,o={}){this.options=o;this.client=new ge(e,{fetch:o.fetch}),this.client.patchFetch(n=>async(s,r)=>{let i=await n(s,r);return this.handleDeepdeskVersionHeaders(i),i})}latestReceivedDeepdeskVersions={};client;shouldFetchCsrfToken=!0;static exchangeTokenPromise=null;async preflight(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let e=await this.getCsrfToken();this.client.setCsrfToken(e)}return this.options.token?(t.exchangeTokenPromise||(t.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),t.exchangeTokenPromise):Promise.resolve()}async createConversation(e){await this.preflight(),C.info(`Creating conversation for session ${e.sessionId} and agent ${e.agentId}`);let o=await this.client.post("/api/conversations",{...U(e),tags:e.tags},{version:"v2"});return An(o)}async getProfile(e){let o=await this.client.get(`/apis/admin/profiles/${e}/`,{version:null});return R(o)}async getKnowledgeAssistant(e){let o=await this.client.get(`/apis/admin/knowledge-assist/assistants/${e}/`,{version:null});return R(o)}async getContentTypes(){let e=await this.client.get("/apis/admin/content-types/",{version:null});return R(e)}async getPlatformConfig(){let{config:e}=await this.client.get("/platform/config/",{version:null});return R(e)}async checkUserExists(e){let{exists:o}=await this.client.get(`/apis/admin/users/exists?external_id=${e}`);return o}async getConversationBySessionId(e,o={}){await this.preflight(),C.info(`Getting conversation for session ${e}`);let{attempts:n=1,retryDelay:s=1e3}=o,r=await this.client.get(`/api/conversations/by_session_id/${e}`,{attempts:n,retryDelay:s,retryOnResponse:i=>i.status===404||i.status>=500,version:"v2"});return C.info(`Successfully retrieved conversation ${r.id} for session ${e}`),An(r)}async isConversationSupported(e,o={}){C.info(`Check if conversation for session ${e} is supported`);let{attempts:n=1,retryDelay:s=1e3}=o;return(await this.client.get(`/api/conversations/by_session_id/${e}/active_profile`,{attempts:n,retryDelay:s,retryOnResponse:i=>i.status===404||i.status>=500,version:"v2"})).has_active_profile}async updateConversation(e,o){let n=U(o);o.tags&&(n.tags=o.tags);let s=await this.client.put(`/api/conversations/${e}`,n,{version:"v2"});return An(s)}async postMessages(e,o){return(await this.client.post(`/api/conversations/${e}/messages`,o.map(s=>({...U(s),tags:s.tags})),{version:"v2"})).map(s=>An(s))}async sendEvent(e,o){let{data:n,...s}=o,r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((i,[a,l])=>({...i,[a]:l}),{});return this.client.post("/api/events",U({...r,...s,data:n,name:e}),{version:"v2"})}async sendEventV1(e,o){let n=Object.entries(this.latestReceivedDeepdeskVersions).reduce((s,[r,i])=>({...s,[r]:i}),{});return this.client.post("/api/events",{event:e,data:U({...o,...n})})}async getEntities(e){return(await this.client.post("/api/entities",{messages:e.filter(n=>n.text)})).entities}async getSummary(e,o={}){return(await this.client.post("/api/summary",{conversation:{messages:e.filter(s=>s.text&&s.source),agent_id:o.agentId,id:o.externalConversationId},prompt_instruction:o.promptInstruction,model:o.model})).summary}async getTemporaryExchangeToken(){return(await this.client.get("/auth/exchange-token",{version:null})).jwt}async exchangeTokenForAccessCookie(e){return this.client.post("/apis/admin/session/jwt/",{jwt:e},{version:null}).catch(o=>{throw C.warn(`Invalid token '${e}'`),o})}async authenticateWithKey(e,o){await this.client.post("/apis/admin/session/api-key/",U(o),{version:null,refreshTokenOn401:!1,headers:{apikey:e}})}async getTextSuggestions(e,o={},n){return n==="sticky-messages"?this.getPinnedMessages(e):(await this.client.post(`/api/conversations/${e}/recommend/${n}`,U(o),{abortLatest:!0})).map(r=>({...R(r),text:r.text||r.url||r.message,source:n,type:n})).filter((r,i,a)=>i===a.findIndex(l=>l.text===r.text))}async isLoggedIn(){return await this.preflight(),this.client.validateToken()}async getAutocompleteSuggestions(e,o){return(await this.client.post(`/api/conversations/${e}/autocomplete`,U(o),{abortLatest:!0})).map(s=>({score:1,source:s.source,sourceText:s.source_text,text:s.label,trainingJobs:s.training_jobs,searchKeywords:s.search_keywords,type:s.source})).filter((s,r,i)=>r===i.findIndex(a=>a.text===s.text))}async getPinnedMessages(e){let o=await this.client.get(`/api/conversations/${e}/sticky-messages`,{abortLatest:!0});return R(o).map(n=>({...n,text:n.message,source:"sticky-messages",type:"pinned-message"}))}async getStyleSuggestions(e){let o=await this.client.post("/api/style-suggestions",U(e),{abortLatest:!0});return R(o)}async search(e){let o=await this.client.post(`/api/profiles/${e.profile}/search`,U(e),{version:"v2"});return R(o)}async knowledgeAssist(e,o,n,s={}){let r=await this.client.post(`/api/knowledge-assist/assistants/${n}/search`,U({question:e.question,promptInstruction:e.promptInstruction,chatHistory:o.map(i=>({question:i.question,answer:i.answer.answer})),agentId:s.agentId,conversationId:s.conversationId}),{version:"v2"});return R(r)}async requestLoginByEmail(e){let o=await this.client.post("/apis/admin/session/passwordless/request/",{email:e},{version:null});return R(o)}async requestPasswordlessToken(){let e=await this.client.get("/apis/admin/session/passwordless/request/",{version:null});return R(e.token)}async getCsrfToken(){let{token:e}=await this.client.get("/apis/admin/session/csrf/",{version:null});return e}async verifyLoginToken(e){let o=await this.client.post("/apis/admin/session/passwordless/login/",{token:e},{version:null});return R(o)}async evaluateRule(e,o,n,s={}){let r=new URLSearchParams;s.raiseForFailingConditions&&r.set("raise_for_failing_conditions","true");let i=await this.client.post(`/api/conversations/${o}/rules/${e}/evaluate?${r.toString()}`,n,{version:"v2"});return R(i.cues)}handleDeepdeskVersionHeaders(e){e.headers.forEach((o,n)=>{let s=n.toLowerCase(),r=s.match(Ur);if(!o||!r)return;let i=r[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&o&&a!==o&&C.warn(`Overwritten Version header ${s}: ${JSON.stringify(a)} -> ${JSON.stringify(o)}`),this.latestReceivedDeepdeskVersions[i]=o})}};var lo=class{constructor(e,o){this.url=e;this.options={timeout:25e3,...o}}eventListeners={};options;timeoutTimer;eventSource;proxyEvent(e){this.eventSource.addEventListener(ts(e),o=>{let{data:n}=o;try{let s=JSON.parse(n);this.emit(e,R(s))}catch{C.warn(`Invalid JSON for ${e}: ${n}`)}})}connect(){clearTimeout(this.timeoutTimer);let e=new EventSource(this.url,{withCredentials:!0});this.eventSource=e;let o=!1;e.onopen=()=>{o=!0},e.onerror=()=>{o&&e.readyState===2&&this.connect()},this.timeoutTimer=setTimeout(()=>{e.close(),this.connect()},this.options.timeout),Object.keys(this.eventListeners).forEach(n=>{this.proxyEvent(n)})}disconnect(){var e;clearTimeout(this.timeoutTimer),this.eventListeners={},(e=this.eventSource)==null||e.close()}emit(e,o){this.eventListeners[e]&&this.eventListeners[e].forEach(n=>n(o))}on(e,o){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(o),this.proxyEvent(e),()=>{this.off(e,o)}}off(e,o){let n;this.eventListeners[e]&&(n=this.eventListeners[e].indexOf(o),n>-1&&this.eventListeners[e].splice(n,1))}};var Ay;(e=>{let t;(r=>(r.Started="Started",r.Aborted="Aborted",r.Completed="Completed"))(t=e.AutoflowSessionState||={})})(Ay||={});var co=class{constructor(e,o={}){this.apiUrl=e;this.client=new ge(e,o)}client;streams={};logger=C;async getCustomMessages(e){let o=await this.client.get(`/sessions/${e}/suggestions`);return R(o.suggestions)}async sendCustomMessage(e,o){let n=await this.client.post(`/sessions/${e}/messages`,U(o));return R(n)}async answerCustomMessage(e,o){await this.client.post(`/sessions/${e}/answers`,U(o))}async getAutoflows(e){let o=await this.client.get(`/sessions/${e}/autoflows`);return R(o.autoflows)}async startAutoflowSession(e){let o=await this.client.post("/autoflow-sessions",U(e));return R(o)}async stopAutoflowSession(e){await this.client.delete(`/autoflow-sessions/${e}`)}openStream(e){return this.streams[e]||(this.streams[e]=new lo(`${this.apiUrl}/sessions/${e}/events`),this.streams[e].connect()),this.streams[e]}closeStream(e){this.streams[e]||(this.streams[e].disconnect(),delete this.streams[e])}};import{combineReducers as Fy,configureStore as By}from"@reduxjs/toolkit";import{createSlice as Ly}from"@reduxjs/toolkit";var ld={startTime:null,stopTime:null},cd=Ly({name:"handlingTime",initialState:ld,reducers:{handlingTimeStart(t){if(t.startTime&&!t.stopTime)throw new Error("Timing already started");t.startTime=new Date,t.stopTime=null},handlingTimeStop(t){if(!t.startTime)throw new Error("Timing not started");t.stopTime=new Date},handlingTimeReset(t){t.startTime=null,t.stopTime=null}},extraReducers:t=>{t.addCase(M,()=>ld)}}),{handlingTimeStart:dd,handlingTimeStop:Ln,handlingTimeReset:pd}=cd.actions,ud=cd.reducer;var gd=(t={})=>{let e={onAuthError:rt(!1),...t};return o=>n=>s=>("error"in s&&s.error.message==="Unauthorized"&&o.dispatch(e.onAuthError),n(s))};import{createAsyncThunk as My,createSlice as Oy}from"@reduxjs/toolkit";var Mn={list:{keywordMatches:[]},fetchState:"idle",isInitialRequest:null};var Ye=My("styleSuggestions/getAll",async({text:t},e)=>{var i;let{deepdeskAPI:o}=e.extra,n=e.getState(),{showStyleSuggestions:s}=n.settings,r=(i=n.conversation.current)==null?void 0:i.profileCode;if(!s)return Mn.list;if(!r)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:r,message:t})}),Ny=Oy({name:"styleSuggestions",initialState:Mn,reducers:{},extraReducers:t=>{t.addCase(Ye.pending,e=>{e.isInitialRequest=e.isInitialRequest===null,e.fetchState="loading"}).addCase(Ye.rejected,e=>{e.fetchState="error"}).addCase(Ye.fulfilled,(e,o)=>{e.fetchState="done",Re(e.list,o.payload)||(e.list=o.payload)}).addCase(Ue,e=>{e.list=Mn.list}).addCase(M,()=>Mn)}}),md=Ny.reducer;var fd=(t={})=>{let e,o=!0,n={getStyleSuggestions:Ye,debounce:500,...t};return s=>r=>i=>{var u;let a=s.getState().input.text,l=r(i),c=s.getState();if(c.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:d}=c.settings;if(!((u=c.conversation.current)==null?void 0:u.id)||!d)return l;let{text:g}=c.input;return g===a&&!o||(clearTimeout(e),g==="")||(e=setTimeout(()=>{o=!1,s.dispatch(n.getStyleSuggestions({text:g}))},t.debounce)),l}};function Dy(t,e){return t.text===e.text&&t.selection.start===e.selection.start&&t.selection.end===e.selection.end}var hd=(t={})=>{let e={getTextSuggestions:le,getAutocompleteSuggestions:Qt,debounce:200,check:St,...t},o;return n=>s=>r=>{var m;let{input:{userCommitted:i}}=n.getState(),a=s(r),l=n.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:c,showTabCompletion:d}=l.settings,p=(m=l.conversation.current)==null?void 0:m.id,g=r.type===Yo.toString();if(!p||!c&&!d)return a;let{input:{userCommitted:u}}=l;return Dy(u,i)&&!g||(clearTimeout(o),!e.check(l))||(o=setTimeout(()=>{let v=ct(l);v===""?n.dispatch(e.getTextSuggestions("default")):n.dispatch(e.getAutocompleteSuggestions(v))},g?0:e.debounce)),a}};var yd=Ye.fulfilled.toString();function Hy(t,e){let o=new Set([...e.keywordMatches.map(s=>s.keyword)]),n=[];return o.forEach(s=>{let r=t.keywordMatches.filter(l=>l.keyword===s),i=e.keywordMatches.filter(l=>l.keyword===s),a=i.length-r.length;a<=0||n.push(...i.slice(0,a))}),n}var vd=t=>e=>o=>n=>{var c;if(n.type!==yd){o(n);return}let s=e.getState().styleSuggestions.list;o(n);let r=e.getState(),i=r.styleSuggestions.list,a=(c=r.conversation)==null?void 0:c.current;if(s===i)return;let l=Hy(s,i);n.type===yd&&l.length>0&&t.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var Ky=Fy({answer:Ka,auth:Zr,autoflows:uc,conversation:ei,contentTypes:Ji,customMessages:xc,passwordlessToken:Ec,entities:Ca,knowledgeAssistant:Ha,handlingTime:ud,info:Si,input:fi,settings:jr,profile:$a,search:Ei,summary:Aa,styleSuggestions:md,ui:vl,rules:Pi,textSuggestions:ol});function Sd(t){return By({reducer:Ky,middleware:e=>[...e({thunk:{extraArgument:{dynamicThunkObject:t.dynamicThunkObject,deepdeskAPI:t.deepdeskAPI,deepdeskBrokerAPI:t.deepdeskBrokerAPI}},serializableCheck:!1}),gd(),hd({debounce:200}),fd({debounce:500}),vd(t.deepdeskAPI),...t.middleware?t.middleware:[]],preloadedState:t.preloadedState})}var Uy=t=>{var e;return((e=t==null?void 0:t.type)==null?void 0:e.toLowerCase())??"unknown"},zy=t=>e=>o=>n=>{var a;let s=e.getState(),r=Xn("inlineSuggestions")(s);switch(n.type){case rt.toString():{!n.payload&&t.emit("logout",void 0);break}case se.toString():{let{start:l,end:c}=s.input.selection;t.emit("select-suggestion",{type:Uy(n.payload.suggestion),...n.payload,replace:n.payload.replace==="selection"?{start:l,end:c}:{start:0,end:c}},{mayApplyChanges:!0});break}case To.toString():{let{start:l,end:c}=s.input.selection;t.emit("replace",{...n.payload,replace:n.payload.replace==="selection"?{start:l,end:c}:{start:0,end:c}},{mayApplyChanges:!0});break}case Nt.toString():{let l=e.getState(),{text:c,selection:d}=l.input.userCommitted;t.emit("reset",{text:c,selectionAfter:d},{mayApplyChanges:!0});break}case Io.toString():t.emit("select-image",n.payload,{mayApplyChanges:!0}),t.sendEvent("Image attached",{conversationId:s.conversation.current.id,data:{path:n.payload.suggestion.image,title:n.payload.suggestion.title}});break;case ae.fulfilled.toString():n.payload.length>0&&t.sendEvent("entities found",{conversationId:s.conversation.current.id,data:{entities:n.payload}});break;case _e.fulfilled.toString():t.sendEvent("conversation summarized",{conversationId:s.conversation.current.id,data:{summary:n.payload.summary}});break;case $.toString():t.sendEvent(n.payload.name,{conversationId:((a=n.payload.options)==null?void 0:a.includeConversationData)&&s.conversation.current.id,data:n.payload.data});break;case Eo.toString():t.handleKeyDown(n.payload);break;case Ue.toString():t.logSendMessage(n.payload);break;case ko.toString():t.handleInputChanged(n.payload);break;case Se.fulfilled.toString():t.broadcast(is,n.payload,!1),t.emit("cues",n.payload);break;default:break}let i=o(n);switch(n.type){case Ue.toString():t.handleAfterSendMessage(n.payload);break;case Jt.toString():t.onUpdateShowTabHint(n.payload);break;case Ln.toString():t.logHandlingTime();break;case se.toString():{r&&(e.dispatch(ce([])),e.dispatch(ve()));break}case ce.toString():{r&&n.payload.length>0&&e.dispatch(Ae(0));break}default:break}return i},_d=zy;function br(t){return t.toISOString().replace("T"," ").replace("Z","")}function xd(t,e){var s,r,i;let{startTime:o,stopTime:n}=t.handlingTime;if(!o||!n)throw new Error("No startTime and stopTime for handling time metrics");return{conversationId:t.conversation.current.id,clientVersion:e.version,agentId:(s=t.info.agentInfo)==null?void 0:s.agentId,agentName:(r=t.info.agentInfo)==null?void 0:r.agentName,agentEmail:(i=t.info.agentInfo)==null?void 0:i.agentEmail,timeStart:br(o),timeStop:br(n)}}function bd(t,e,o){var F,K,H;let{text:n,metrics:{numCharsTyped:s,numCharsPasted:r,numCharsCut:i,numCharsDeleted:a,numPaste:l,agentStartedTypingTimestamp:c,externalTimeTotalSeconds:d,pastes:p,cuts:g,deletions:u,textSuggestions:f,offeredTextSuggestions:m}}=e[t],v=n.length,_=f.reduce((I,{text:A,searchTerm:k})=>I+A.length-(k?k.length:0),0),y=c??Date.now(),x=(Date.now()-y)/1e3+(d||0),S=s/x,O=f.reduce((I,{searchTerm:A})=>I+(A?A.length:0),0);return{conversationId:e.conversation.current.id,source:"agent",text:n,clientVersion:o.version,pastes:p,cuts:g,deletions:u,lenTextTyped:s+O,lenTextTotal:v,lenTextAssisted:_,lenTextPasted:r,lenTextCut:i,lenTextDeleted:a,timeTotalSeconds:x,charsPerSecond:S,numPastes:l,textSuggestionsV2:f,suggestionsCounters:[{source:"gpt",countOffered:m.filter(I=>I.source==="gpt").length}],agentId:(F=e.info.agentInfo)==null?void 0:F.agentId,agentName:(K=e.info.agentInfo)==null?void 0:K.agentName,agentEmail:(H=e.info.agentInfo)==null?void 0:H.agentEmail}}function wr(t,e){var r;let o=t.closest(e);if(o)return o;let n=t.getRootNode().host;if(n instanceof HTMLElement)return wr(n,e);let s=(r=t.ownerDocument.defaultView)==null?void 0:r.frameElement;return s?wr(s,e):null}function wd(t,e){return wr(t,e)}function Cd(t){return typeof t=="object"&&t!==null&&"name"in t&&"message"in t}function jy(t){return typeof t=="object"&&t!==null&&"tagName"in t}function Cr(t){return jy(t)&&(De(t)||dn(t))}var Td,me=new Map,Vy=["bottom","height","left","right","top","width"],qy=(t={},e={})=>Vy.some(o=>t[o]!==e[o]);function Ed(t){var o,n;if(t.ownerDocument===document)return[];let e=((n=(o=t.ownerDocument)==null?void 0:o.defaultView)==null?void 0:n.frameElement)??null;return e?[e,...Ed(e)]:[]}function kd(t,e){return!t||!e?null:{...t,top:t.top+e.top,left:t.left+e.left}}var On=!1,Id=()=>{On=!0;let t=[];if(me.forEach((e,o)=>{if(!o.isConnected){e.rect=null,t.push(e),me.delete(o);return}let n=o.getBoundingClientRect();qy(n,e.rect)&&(e.rect=n,t.push(e))}),t.forEach(e=>{let o=e.parentRects?e.parentRects.reduce(kd,e.rect):e.rect;e.callbacks.forEach(n=>n(o))}),me.size===0){On=!1;return}Td=window.requestAnimationFrame(Id)};function Tr(t,e){let o=Ed(t),n=[],s=o.map((r,i)=>Tr(r,a=>{n[i]=a;let l=me.get(t);if(!l)return;let c=n.reduce(kd,l.rect);l.callbacks.forEach(d=>d(c))}));return{observe(r=!0){if(s.forEach(i=>i.observe(!1)),me.has(t)){let i=me.get(t);i.callbacks.push(e),i.rect&&e(i.rect)}else me.set(t,{rect:void 0,callbacks:[e],parentRects:n});r&&!On&&Id()},unobserve(){s.forEach(i=>i.unobserve());let r=me.get(t);if(r){let i=r.callbacks.indexOf(e);i>=0&&r.callbacks.splice(i,1),r.callbacks.length||me.delete(t),me.size||(cancelAnimationFrame(Td),On=!1)}}}}var Rd,fe=new Map,Pd=()=>{fe.forEach((t,e)=>{if(!e.isConnected){fe.delete(e);return}let{clientHeight:o,scrollHeight:n}=e,s=n>o;t.visible!==s&&(t.visible=s,t.callbacks.forEach(r=>r(t.visible)))}),fe.size!==0&&(Rd=window.requestAnimationFrame(Pd))};function Ad(t,e){return{observe(){let o=fe.size===0;fe.has(t)?fe.get(t).callbacks.push(e):fe.set(t,{visible:void 0,callbacks:[e]}),o&&Pd()},unobserve(){let o=fe.get(t);if(o){let n=o.callbacks.indexOf(e);n>=0&&o.callbacks.splice(n,1),o.callbacks.length||fe.delete(t),fe.size||cancelAnimationFrame(Rd)}}}}var Er=["borderLeftWidth","borderRightWidth","borderTopWidth","borderBottomWidth","borderStyle","boxSizing","color","overflowWrap","fontFamily","fontSize","fontSizeAdjust","fontStretch","fontWeight","fontKerning","lineHeight","letterSpacing","paddingLeft","paddingTop","paddingRight","paddingBottom","width","height","textIndent","whiteSpace","wordBreak","wordSpacing","wordWrap"];function kr(t,e,o){return o.forEach(n=>{e.style[n]=t[n]})}function It(t){return parseFloat(t)}function Nn(t){return Math.round(t*1e6)}function Ld(t){return t/1e6}function Ir(t,e,o){if(t.boxSizing==="content-box")return;let{clientWidth:n}=e,s=It(t.width),r=It(t.borderLeftWidth),i=It(t.borderRightWidth),a=It(t.paddingRight),l=Ld(Nn(s)-Nn(r)-Nn(i)),c=Ld(Nn(n));if(l-c>2){let d=l-c;o.style.paddingRight=`${a+d}px`}}function Dn(t,e={}){var d;let o=e.overlayContainer||document.createElement("div");o.style.display="none",o.style.position=e.position??"fixed",o.style.pointerEvents="none",o.style.borderColor="transparent",Ge(o);let n=window.getComputedStyle(t),s=!0,r=()=>{o.scrollTop=t.scrollTop};kr(n,o,Er),Ir(n,t,o),e.mirrorOverflow&&(o.style.overflow="hidden",t.addEventListener("scroll",r));let i=Ad(t,()=>{kr(n,o,Er),Ir(n,t,o),r(),setTimeout(r,0)}),a,l=!0,c=Tr(t,p=>{if(p===null){e.onRemove&&e.onRemove(),o.remove();return}if(!l&&e.onMoveStart&&(Promise.resolve().then(()=>e.onMoveStart()),l=!0),clearTimeout(a),a=setTimeout(()=>{e.onMoveEnd&&e.onMoveEnd(),l=!1},200),p.height===0&&p.width===0){if(s===!0)return;e.onHide&&e.onHide(),o.style.display="none",s=!0;return}if(kr(n,o,Er),Ir(n,t,o),r(),o.style.top=`${p.top}px`,o.style.left=`${p.left}px`,e.closestScrollElement&&e.closestScrollElement!==t){let g=e.closestScrollElement.getBoundingClientRect(),u=window.getComputedStyle(e.closestScrollElement),f=It(u.borderTopWidth),m=It(u.borderBottomWidth),v=g.top+f-p.top,T=p.top+p.height+-(g.top+g.height-m);o.style.clipPath=`inset(${v}px 0px ${T}px 0px)`}s&&(o.style.display="block",e.onShow&&e.onShow(),s=!1)});return e.appendTo?e.appendTo.appendChild(o):(d=t.parentElement)==null||d.appendChild(o),c.observe(),i.observe(),[o,()=>{t.removeEventListener("scroll",r),c.unobserve(),i.unobserve()}]}var Md=(t,e)=>({value(){try{let o=sessionStorage.getItem(`dd-${t}`);if(!o)return e;try{return JSON.parse(o)}catch{return e}}catch{return e}},update(o){try{sessionStorage.setItem(`dd-${t}`,JSON.stringify(o))}catch{C.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function $y(t){return t.offsetParent!==null}function Od(t){if(!$y(t))return!1;let e=t.getBoundingClientRect();return e.top>=0&&e.left>=0&&e.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&e.right<=(window.innerWidth||document.documentElement.clientWidth)}function Rr(t,e,o=100){let n=Od(t);e({isVisible:n});let s=setInterval(()=>{let r=Od(t);r!==n&&(n=r,e({isVisible:n}))},o);return()=>{clearTimeout(s)}}import{jsx as z}from"react/jsx-runtime";var Nd=Md("showTabHint",!0),Fn=class t{static version="10.12.1-beta.8";static count=0;deepdeskApi;inputMediator=null;version;broadcastEvents;eventListeners={};unmountHandlers=[];widgetRoot=null;dynamicThunkObject={};isMounted=!1;instanceId;shouldRender=!0;store;constructor({deepdeskUrl:e,brokerUrl:o,version:n=t.version||"unknown",locale:s="en-US",token:r,fetch:i,productName:a,createCustomChannel:l}){let c=e.replace(/\/api$/,"");this.deepdeskApi=new Be(c,{token:r,fetch:i}),this.version=n,this.instanceId=t.count++;let d={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[_d({broadcast:(p,g,u)=>{this.broadcastEvents.send(p,g,u)},emit:(p,g,u)=>this.emit(p,g,u),handleAfterSendMessage:p=>this.handleAfterSendMessage(p),handleInputChanged:p=>this.handleInputChanged(p),handleKeyDown:p=>this.handleKeyDown(p),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:p=>this.logSendMessage(p),onUpdateShowTabHint:p=>Nd.update(p),sendEvent:(p,g)=>this.deepdeskApi.sendEvent(p,g)})]};o&&Object.assign(d,{deepdeskBrokerAPI:new co(o)}),this.store=Sd(d),this.broadcastEvents=new ad({debug:!0,deepdeskUrl:c,eventMap:Ai(this.store),createCustomChannel:l}),this.store.dispatch(Jt(Nd.value())),this.store.dispatch(yo({locale:s,adminUrl:c,productName:a}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){return this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex]??null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(C.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(C.warn("Profile has not been loaded (yet)"),!0):(C.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(rt(null)),this.store.dispatch(ye()),new Promise(e=>{let o=this.store.subscribe(()=>{let n=this.store.getState();G(n)&&Vr(n)!=="loading"&&(o(),e())});this.unmountHandlers.push(()=>{o()})})}async isLoggedIn(){return(await this.store.dispatch(ye())).payload}async setPlatformAgentId(e){try{if((await this.deepdeskApi.client.get("/apis/admin/session/me/",{version:null})).external_id)return;await this.deepdeskApi.client.request("/apis/admin/session/me/",{method:"PATCH",body:JSON.stringify({external_id:e}),version:null})}catch(o){C.warn("Failed to attach user:",o)}}async isConversationSupported(e,o){return(await this.store.dispatch(Jn({sessionId:e,options:o}))).payload}async createConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(_o(e))).payload}async getConversationBySessionId(e,o){return this.hasConversation()&&this.sessionId()!==e&&this.resetConversation(),(await this.store.dispatch(xo({sessionId:e,options:o}))).payload}async upsertConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(Yn(e))).payload}async postMessages(e){return(await this.store.dispatch(wo(e))).payload}async updateConversation(e){return(await this.store.dispatch(bo(e))).payload}resetConversation(){this.store.dispatch(M()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}async getSummary(){let e=await this.store.dispatch(_e());if(e.error)throw new Error(e.error.message);return e.payload.summary}configure(e){this.store.dispatch(yo(e))}setVisitorInfo(e){this.store.dispatch(vi(e))}async setAgentInfo(e){await this.store.dispatch(Dt(e))}async setAgentSettings(e){await this.store.dispatch(ns(e))}async getAgentSettings(){return(await this.store.dispatch(ss())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let e=[];return this.store.dispatch(Yo()),e.push(this.refreshWidgetSuggestions()),Promise.all(e).then(()=>{})}notifyInputChanged(e){this.store.dispatch(ko(e))}notifyKeyDown(e){this.store.dispatch(Eo(e))}notifyPaste(e,o){this.store.dispatch(pi({text:e,selectionText:o}))}notifyCut(e){this.store.dispatch(ci(e))}notifyExternalSuggestion(e){this.store.dispatch(se(e)),this.store.dispatch(ve())}async evaluateRule(e,o={}){let{payload:n,error:s}=await this.store.dispatch(Se({label:e,params:o}));if(s)throw s;return n}handleInputChanged(e){let{overlayCollapsed:o,openOverlayWhenTyping:n}=this.state.ui;o&&n&&this.store.dispatch(Ne({collapse:!1})),this.inputMediator&&this.store.dispatch(si({text:e,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(ce([])))}handleKeyDown(e){let{overlayCollapsed:o}=this.state.ui,{textSuggestions:n,selectedSuggestionIndex:s,selection:r}=this.state.input,{inlineSuggestions:i}=this.state.settings,a=n.length>0,l=s!==-1;if(this.store.dispatch(di(ti(e))),e.key!=="Tab"&&!this.settings.showTextSuggestions)return;let c=()=>{o||!a||r&&(e.shiftKey||(this.store.dispatch(ii()),i||this.stageSelectedSuggestion({inputType:"arrow"}),e.preventDefault()))},d=()=>{o||!a||i&&s<=0||r&&(e.shiftKey||(this.store.dispatch(li()),e.preventDefault(),!i&&(this.state.input.selectedSuggestionIndex===-1?this.store.dispatch(Nt()):this.stageSelectedSuggestion({inputType:"arrow"}))))};switch(e.key){case"Up":case"ArrowUp":i?d():c();return;case"Down":case"ArrowDown":{i?c():d();return}case"Esc":case"Escape":{i&&l&&this.store.dispatch(Ae(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(Ae(-1)),this.store.dispatch(Nt()),e.preventDefault()):o||(this.store.dispatch(Ne({collapse:!0})),this.store.dispatch(hl(!0)),e.preventDefault());return}case"Tab":{let{userCommitted:p}=this.state.input,g=p.text.substring(0,p.selection.end),{tabCompletionSuggestion:u}=this.state.input;this.store.dispatch(Jt(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!i&&this.settings.showTabCompletion&&u&&u.text.startsWith(g)&&(this.store.dispatch(se({text:u.text,suggestion:u,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch(ve())),e.preventDefault();break}default:}}handleAfterSendMessage(e){this.emit("send-message",e),this.store.dispatch(ui()),this.store.dispatch(ce([]))}handlingTimeStart(){this.state.handlingTime.startTime||(C.info("Start handling time"),this.store.dispatch(dd()))}handlingTimeStop(){this.state.handlingTime.startTime&&(C.info("Stop handling time"),this.store.dispatch(Ln()))}logSendMessage(e){let o=bd("input",this.state,{version:this.version});e&&(Object.assign(o,{text:e}),Object.assign(o,{lenTextTotal:e.length})),this.deepdeskApi.sendEventV1("Send Message",o),this.emit("send-message-event",o)}logHandlingTime(){let e=xd(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",e),this.store.dispatch(pd())}notifySubmit(e={}){this.shouldAbort()||(this.store.dispatch(ve()),this.store.dispatch(Ue(e.text??this.state.input.text)))}stageSelectedSuggestion(e){let o=this.state.input.selectedSuggestionIndex,{textSuggestions:n}=this.state.input;this.store.dispatch(se({text:n[o].text,suggestion:n[o],eventMetrics:e,replace:"until-selection-end"}))}emit(e,o,n={}){let s=()=>{this.eventListeners[e]&&this.eventListeners[e].forEach(r=>{try{r(o)}catch(i){C.warn(`The following error occurred in deepdeskSDK.on('${e}', handler)`),C.error(i)}})};this.inputMediator&&n.mayApplyChanges?this.inputMediator.applyChanges(s):s()}on(e,o){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(o),()=>{this.off(e,o)}}off(e,o){if(!e&&!o){this.eventListeners={};return}let n;this.eventListeners[e]&&(n=this.eventListeners[e].indexOf(o),n>-1&&this.eventListeners[e].splice(n,1))}setConversationQuery(e){this.dynamicThunkObject.conversationQuery=e}whenConversationLoaded(e){let o=()=>this.loadProfileConfig().then(()=>e());this.hasConversation()&&o();let n=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==n&&(n=this.hasConversation(),n&&o())})}overlayContainerFactory(e,o,n,s){let[r,i]=Dn(o,n);return r.setAttribute("translate","no"),r.dataset.testid=e,s&&r.classList.add(s),this.unmountHandlers.push(()=>{Hn(r),i(),r.remove()}),r}createInlineContainer(e,o){var i;let n=document.createElement("div");n.style.position="absolute",n.style.top="0px",n.style.left="0px",n.style.height="0px",n.style.width="0px";let s=document.createElement("div");s.style.display="none",s.style.position="absolute",s.style.height="0px",s.style.width="0px",s.style.backgroundColor="red",n.appendChild(s);let r=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;if(r){let[a,l]=Dn(r,{appendTo:document.body,onMoveStart:()=>{s.style.display="none"}});a.dataset.testid=o,a.style.zIndex="2",a.appendChild(n),this.unmountHandlers.push(()=>{Hn(s),l()})}else document.body.appendChild(n);return s}createContainer(e,o=document.body){let n=window.getComputedStyle(o),s=document.createElement("div");return Ge(s),s.dataset.testid=e,s.style.color=n.color,s.style.fontSize=n.fontSize,s.style.fontFamily=n.fontFamily,s.style.fontVariant=n.fontVariant,s.setAttribute("translate","no"),o.appendChild(s),this.unmountHandlers.push(()=>{Hn(s),s.remove()}),s}storeMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,o=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(e,o),C.info(`Stored analytics for ${this.conversationId()}`)}catch{}}restoreMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,o=window.sessionStorage.getItem(e);if(!o)return;let n=JSON.parse(o);n.text.trim()===this.state.input.text.trim()?(C.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(mi(n.metrics))):C.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(e)}catch{}}mount(e,o={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!Cr(e))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let{customStyles:n={},showStyleSuggestions:s,showTabCompletion:r,showTextSuggestions:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:c,showSuggestionsAfterPattern:d,isEmbedded:p,detectSubmit:g,insertLink:u,inputMediator:f,closestScrollSelector:m,appendOverlayTo:v,inlineSuggestions:T,floatingMenu:_}=o;this.configure({showStyleSuggestions:s,showTabCompletion:r,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:c,showSuggestionsAfterPattern:d,showTextSuggestions:i,insertLink:u,isEmbedded:p,inlineSuggestions:T,floatingMenu:!!_}),o.automaticHandlingTime&&this.setupHandlingTime(e),Ge(e),this.inputMediator=f||(De(e)?new Tt(e):new Ct(e)),this.inputMediator.on("change",({plainText:S})=>{this.notifyInputChanged(S)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(gi({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",S=>{this.notifyKeyDown(S)}),this.inputMediator.on("paste",({pastedText:S,selectionText:O})=>{this.notifyPaste(S,O)}),this.inputMediator.on("cut",({selectionText:S})=>{this.notifyCut(S)});let y=m&&wd(e,m)||void 0;if(T){let{customStyles:S,appendOverlayTo:O}=o;if(De(e))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let F=this.createInlineContainer(e,"deepdesk-caret");Rt(z(Xe,{store:this.store,customStyles:S,children:z(je,{broadcastEvents:this.broadcastEvents,children:z(Cl,{})})}),F),this.inputMediator.on("caret",H=>{this.store.dispatch(ce([])),H?(F.style.display="block",F.style.top=`${H.top}px`,F.style.left=`${H.left}px`):F.style.display="none"});let K=this.overlayContainerFactory("floating-menu",y||e,{appendTo:typeof _=="object"&&"appendOverlayTo"in _?_.appendOverlayTo:O},S==null?void 0:S.floatingMenuRootNode);Rt(z(Xe,{store:this.store,customStyles:S,children:z(je,{broadcastEvents:this.broadcastEvents,children:z(ml,{onLogIn:()=>this.loginViaPopup().catch(H=>C.warn(H.message))})})}),K)}else{let S=this.overlayContainerFactory("deepdesk-tab-completion",y||e,{appendTo:v,closestScrollElement:y,mirrorOverflow:!0,onRemove:()=>this.unmount()},n==null?void 0:n.rootNode),O=this.overlayContainerFactory("deepdesk-suggestions-overlay",y||e,{appendTo:v},n==null?void 0:n.suggestionsRootNode);Rt(z(Xe,{store:this.store,customStyles:n,children:z(je,{broadcastEvents:this.broadcastEvents,children:z(ic,{inputElement:e})})}),S),Rt(z(Xe,{store:this.store,customStyles:n,children:z(je,{broadcastEvents:this.broadcastEvents,children:z(Ol,{onLogIn:()=>this.loginViaPopup().catch(F=>C.warn(F.message))})})}),O)}Rt(z(Xe,{store:this.store,customStyles:n,children:z(je,{broadcastEvents:this.broadcastEvents,children:z(ll,{})})}),this.createContainer("deepdesk-overlays"));let x;this.inputMediator.on("selection",S=>{clearTimeout(x),S===null?x=setTimeout(()=>{S!==null&&this.store.dispatch(es(S))},500):this.store.dispatch(es(S))}),this.inputMediator.on("disabled",()=>{var S;(S=this.inputMediator)==null||S.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{g&&this.notifySubmit()}),this.inputMediator.on("blur",()=>this.store.dispatch($s(!1))),this.inputMediator.on("focus",()=>this.store.dispatch($s(!0))),this.store.dispatch(ri({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.unmountHandlers.push(()=>{this.state.input.text!==""&&(this.store.dispatch(ve()),this.storeMetrics())}),this.whenConversationLoaded(()=>{var S;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((S=this.state.conversation.current)==null?void 0:S.sessionId)}),this.isMounted=!0}unmount(){var e;this.unmountHandlers.forEach(o=>o()),this.unmountHandlers=[],(e=this.inputMediator)==null||e.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(e,o={}){if(this.widgetRoot&&C.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:n,showImages:s,isEmbedded:r}=o;this.widgetRoot=e,this.configure({showImages:s,isEmbedded:r}),Rt(z(Xe,{store:this.store,customStyles:n,children:z(je,{broadcastEvents:this.broadcastEvents,children:z(od,{onLogIn:()=>this.loginViaPopup().catch(i=>C.warn(i.message))})})}),e),this.whenConversationLoaded(()=>{var i;this.broadcastEvents.setSessionId((i=this.state.conversation.current)==null?void 0:i.sessionId)})}unmountWidget(){this.widgetRoot&&Hn(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(e){let o=Rr(e,({isVisible:n})=>{n?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),o()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){Cd(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(Zt());let e=Oe(this.state);e&&(await this.store.dispatch(Xt()),this.store.dispatch(yo({showSearch:e.search,showAutoflows:e.autoflows,showCustomMessages:e.customMessages,showImageSearch:e.imageSearch,showEntitiesCommand:e.entitiesCommand,showSummaryCommand:e.summarizer,showKnowledgeSearch:!!e.knowledgeAssistant,recommendTextSuggestions:e.recommendTextSuggestions})))}),this.loadProfileConfigPromise)}async loginViaPopup(e){return new Promise((o,n)=>{let s=new MessageChannel,r=s.port1,i=this.state.settings.adminUrl,a=new URL(e!=null&&e.url?e==null?void 0:e.url:`${i}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let l=!1,c=()=>{d&&!d.closed&&d.close(),window.removeEventListener("message",p),clearInterval(g)};r.onmessage=async u=>{var f,m;if((f=u.data)!=null&&f.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((m=u.data)==null?void 0:m.jwt),await this.isLoggedIn(),this.broadcastEvents.send(Ft),l=!0,s.port1.close(),o()}catch(v){console.error(v),n(v)}finally{l=!0,c()}};let d=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");d===null&&n(new Error("Popup blocked by browser"));let p=async u=>{var f;if(u.origin===a.origin)switch((f=u.data)==null?void 0:f.type){case"deepdesk-popup-loaded":{try{let m=JSON.stringify({type:"deepdesk-popup-create-channel"});d==null||d.postMessage(m,a.origin,[s.port2])}catch(m){C.error("Error posting message to popup",m),n(m)}break}case"deepdesk-popup-error":{c(),u.data.message==="Timeout"&&C.warn("Popup timed out. Check if the account's platform url is configured correctly."),n(new Error(u.data.message));break}}};window.addEventListener("message",p);let g=setInterval(()=>{d&&!d.closed||(c(),l||n(new Error("Popup closed by user")))},200);this.unmountHandlers.push(c)})}async checkForTrialMode(e){try{let{account:o}=await this.deepdeskApi.getPlatformConfig();if(!o.isTrial){this.shouldRender=!0;return}if(C.info("Trial is active"),!await this.deepdeskApi.checkUserExists(e))throw new Error("User is not in trial");this.shouldRender=!0}catch(o){let{message:n}=o;C.info(n),this.shouldRender=!1}}async refreshWidgetSuggestions(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:e}=this.state.profile.data;if(!e.widget)return;let o=Qo(this.state);try{o.forEach(({type:n})=>{n==="entities"?this.store.dispatch(ae()):this.store.dispatch(le(n))})}catch(n){this.handleError(n)}}};async function Wy(t,e,o={}){let{value:n}=t,{start:s,end:r}=o.replace??{start:0,end:n.length},i=`${n.slice(0,s)}${e}${n.slice(r)}`,a=o.selectionAfter??{start:s+e.length,end:s+e.length},l=()=>{if(o.setValue)return o.setValue(i);t.value=i};return Promise.resolve(l()).then(()=>{t.selectionStart=a.start,t.selectionEnd=a.end,t.blur(),t.focus()})}async function Gy(t,e,o={}){let n=o.replace?Je(t,o.replace.start,o.replace.end):ao(t),s,r=()=>{if(o.setRange)return o.setRange(n.cloneRange());n.deleteContents(),s=document.createElement("span"),n.insertNode(s),o.insertBRs!==!1?e.split(`
|
|
9
|
+
`);break}default:break}p&&i++}return l(t),a}var sd=(i=>(i.CUT="Cut",i.BACKSPACE="Backspace",i.DELETE="Delete",i.ERASEEOF="EraseEof",i.UNDO="Undo",i.CLEAR="Clear",i))(sd||{}),Fe=class{constructor(e){this.element=e;this.currentText=this.getText(),this.currentHTML=this.getHTML(),this.listen()}eventListeners={};disposeHandlers=[];currentText="";currentCaret=null;currentSelection={start:0,end:0};currentHTML="";isFocused=!1;isActive=!0;isSettingValue=!1;isSubmitting=!1;isPossibleClearInputAction=!1;isDisposed=!1;addEventListener(e,o){let n=s=>{o(s)};this.element.addEventListener(e,n),this.disposeHandlers.push(()=>{this.element.removeEventListener(e,n)})}removeEventListener(e,o){this.element.removeEventListener(e,o)}triggerChange(){let e=this.getText(),o=this.getHTML(),n=e!==this.currentText;this.isActive&&(e===""&&this.currentText!==""&&!this.isSettingValue&&!this.isPossibleClearInputAction&&(this.isSubmitting=!0,this.emit("submit")),!this.isSettingValue&&n&&!this.isSubmitting&&this.emit("change",{plainText:e}),n&&(this.currentSelection=this.getSelection()),this.currentText=e,this.isSubmitting=!1,(this.currentHTML!==o||o===null&&n)&&(this.emit("updated",{plainText:e}),this.triggerCaretPosition(),this.currentHTML=o))}triggerSelection(){let e=this.getSelection();(e.start!==this.currentSelection.start||e.end!==this.currentSelection.end)&&(this.currentSelection=e,this.emit("selection",e),this.triggerCaretPosition())}triggerCaretPosition(){let e=this.getCaretPosition();Re(e,this.currentCaret)||(this.currentCaret=e,this.emit("caret",e))}handleKeyUp(e){let{key:o,shiftKey:n}=e;(o==="Enter"&&n===!0||o==="Backspace")&&this.triggerChange(),this.triggerSelection()}handleClick(){this.triggerSelection()}handleFocus(){this.isFocused||this.emit("focus"),this.triggerSelection(),this.isFocused=!0}handleBlur(){this.isPossibleClearInputAction=!1,this.isFocused&&this.emit("blur"),this.isFocused=!1}handleKeyDown(e){let{key:o,ctrlKey:n,metaKey:s}=e;this.isPossibleClearInputAction=Object.values(sd).includes(o)||o.toLowerCase()==="z"&&(n||s),this.emit("keydown",e)}handleCut(){this.isPossibleClearInputAction=!0,this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(e){var n,s;let o=((n=e.clipboardData)==null?void 0:n.getData("text"))||((s=e.clipboardData)==null?void 0:s.getData("text/plain"))||"";this.emit("paste",{pastedText:o,selectionText:this.getSelectedText()})}listen(){this.addEventListener("keydown",o=>this.handleKeyDown(o)),this.addEventListener("keyup",o=>this.handleKeyUp(o)),this.addEventListener("input",()=>this.triggerChange()),this.addEventListener("change",()=>this.triggerChange()),this.addEventListener("focus",()=>this.handleFocus()),this.addEventListener("blur",()=>this.handleBlur()),this.addEventListener("cut",()=>this.handleCut()),this.addEventListener("paste",o=>this.handlePaste(o)),this.addEventListener("click",()=>this.triggerSelection()),document.activeElement===this.element&&setTimeout(()=>{this.handleFocus()},0);let e=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});e.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{e.disconnect()}),this.currentSelection=this.getSelection()}focus(){this.element.focus()}emit(e,...o){this.isDisposed||this.eventListeners[e]&&this.eventListeners[e].forEach(n=>{n(...o)})}on(e,o){this.isDisposed||(this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(o))}activate(){let e=this.isActive===!1;this.isActive=!0,e&&this.triggerChange()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(e=>e()),this.eventListeners={},this.isDisposed=!0}};function rd(t){return t.top!==0||t.left!==0||t.height!==0||t.width!==0}var Ct=class extends Fe{observer;lastKnownSelection=null;getRootNode(){return this.element.getRootNode()}getText(){let e=new Range;return e.selectNodeContents(this.element),Pn(this.element,e)}getHTML(){return this.element.innerHTML||""}getRange(){var r;let e=this.getRootNode();if(e.activeElement!==this.element)return null;let o="getSelection"in e?e.getSelection():window.getSelection();if(!o)return null;let n="getComposedRanges"in o&&e instanceof ShadowRoot?(r=o.getComposedRanges(e))==null?void 0:r[0]:o.rangeCount>0?o.getRangeAt(0):null;if(!n)return null;let s=this.element.ownerDocument.createRange();return s.setStart(n==null?void 0:n.startContainer,n==null?void 0:n.startOffset),s.setEnd(n==null?void 0:n.endContainer,n==null?void 0:n.endOffset),!s||!this.element.contains(s.startContainer)||!this.element.contains(s.endContainer)?null:s}getCaretPosition(){let e=this.getRange();if(!e||!e.collapsed||!("getBoundingClientRect"in e))return null;let o=e.getBoundingClientRect();return!rd(o)&&(e.insertNode(this.element.ownerDocument.createTextNode("\u2060")),o=e.getBoundingClientRect(),e.deleteContents(),!rd(o))?null:{top:o.top+o.height,left:o.left}}getSelection(){let e=this.getRange();if(e)return Rn(this.element,e);let o=this.lastKnownSelection;if(o&&nd(this.element,o.start,o.end))return o;let n=ao(this.element);return n.collapse(!1),Rn(this.element,n)}getSelectedText(){let{start:e,end:o}=this.getSelection();return Pn(this.element,Je(this.element,e,o))}applyChanges(e){var s;if(!this.isActive)return;this.isSettingValue=!0;let o=this.getText(),n=e(this.element);return(s=this.observer)==null||s.takeRecords(),Promise.resolve(n).then(()=>{this.currentText=this.getText(),o!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(){super.listen(),this.observer=new MutationObserver(()=>{setTimeout(()=>{this.triggerChange()},0)}),this.observer.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0});let e=this.element.isContentEditable,o=new MutationObserver(()=>{this.element.isContentEditable!==e&&(e=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>o.disconnect())}dispose(){super.dispose(),this.observer&&this.observer.disconnect()}};var Tt=class extends Fe{lastKnownSelection=null;getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:e,selectionEnd:o}=this.element;return{start:e,end:o}}getSelectedText(){let e=this.getSelection();return e?this.getText().slice(e.start,e.end):""}getCaretPosition(){return null}applyChanges(e){if(!this.isActive)return;this.isSettingValue=!0;let o=this.getText(),n=e(this.element);return Promise.resolve(n).then(()=>{this.currentText=this.getText(),o!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(){super.listen();let e=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var s;return(s=e==null?void 0:e.get)==null?void 0:s.call(this.element)},set:s=>{var r;(r=e==null?void 0:e.set)==null||r.call(this.element,s),this.triggerChange()}});let o=this.element.disabled,n=new MutationObserver(()=>{this.element.disabled!==o&&(o=this.element.disabled,this.emit(o?"disabled":"enabled"))});n.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>n.disconnect())}};function id(t,e,o){let n=`deepdesk-iframe-${t}`,s=document.getElementById(n);if(s)return s;let r=document.createElement("iframe"),i=new URL(e);return Object.entries(o).forEach(([a,l])=>{i.searchParams.append(a,l)}),r.style.position="absolute",r.style.left="-999em",r.style.width="0px",r.style.height="0px",r.tabIndex=-1,r.id=n,r.title=`iframe-${t}`,r.src=i.toString(),window.document.body.appendChild(r),r}var yr=class{constructor(e){this.name=e;this.broadcastChannel=new BroadcastChannel(e)}broadcastChannel;disposeHandlers=[];onMessage(e){this.broadcastChannel.addEventListener("message",e),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",e)})}postMessage(e){this.broadcastChannel.postMessage(JSON.stringify(e))}close(){this.disposeHandlers.forEach(e=>e()),this.broadcastChannel.close()}},vr=class{constructor(e,o,n){this.name=e;this.targetOrigin=o;this.options=n;this.iframe=id(e,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}iframe;disposeHandlers=[];onMessage(e){window.addEventListener("message",e),this.disposeHandlers.push(()=>{window.removeEventListener("message",e)})}postMessage(e){var o;(o=this.iframe.contentWindow)==null||o.postMessage(JSON.stringify(e),this.targetOrigin)}close(){var e;this.disposeHandlers.forEach(o=>o()),(e=this.iframe)==null||e.remove()}},Sr=class{constructor(e){this.params=e;this.deepdeskUrl=e.deepdeskUrl,this.eventMap=e.eventMap,this.sessionId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}sessionId;deepdeskUrl;channel;defaultChannel;eventMap;get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setSessionId(e){this.sessionId!==e&&(this.cleanup(),C.info("Set sessionId",e),this.sessionId=e,this.channel=this.createChannel(e))}createChannel(e){let o=this.params.createCustomChannel?this.params.createCustomChannel(e):this.isCrossOrigin?new vr(e,this.deepdeskUrl,{debug:!0}):new yr(e),n=s=>{var i,a;if(s.origin!==this.deepdeskUrl)return;let r=typeof s.data=="string"?JSON.parse(s.data):s.data;r.type==="event"&&r.channel===e&&(C.info("Received broadcast event",this.sessionId,s),(a=(i=this.eventMap)[r.name])==null||a.call(i,r.payload))};return o.onMessage(n),o}send(e,o,n){var i,a;C.info("Broadcast event",{sessionId:this.sessionId,name:e,payload:o});let s={type:"event",name:e,payload:o};n!==!1&&((a=(i=this.eventMap)[e])==null||a.call(i,o));let r=this.sessionId==="deepdesk-general"?this.defaultChannel:this.channel;r==null||r.postMessage({...s,channel:this.sessionId})}cleanup(e=!1){var o,n;(o=this.channel)==null||o.close(),delete this.channel,e&&((n=this.defaultChannel)==null||n.close(),delete this.defaultChannel)}},ad=Sr;var Et=class extends Error{constructor(o,n){super(o);this.body=n}name="CustomError"};var _r=t=>new Promise(e=>{setTimeout(e,t)});var kt=class extends Et{name="ClientError"},xr=class extends Et{name="ServerError"},ge=class t{constructor(e="",o={}){this.baseUrl=e;this.options=o;o.fetch&&(this.fetch=o.fetch)}latestRequestByUrl={};csrfToken;fetch=window.fetch.bind(window);static refreshingToken=null;patchFetch(e){this.fetch=e(this.fetch)}setCsrfToken(e){this.csrfToken=e}request(e,o={}){return new Promise((n,s)=>{let r={isAborted:!1,reject:s},i=`${this.baseUrl}${e}`,a=this.fetch,{abortLatest:l=!1,attempts:c=1,retryDelay:d=500,refreshTokenOn401:p=!0,retryOnError:g=x=>x instanceof TypeError,retryOnResponse:u=x=>x.status>=500,version:f="v1",...m}=o,v={credentials:"include",...m,headers:{"Content-Type":"application/json",...m.headers}};o.method!==void 0&&o.method!=="GET"&&this.csrfToken&&(v.headers={...v.headers,"X-CSRFToken":this.csrfToken}),typeof f=="string"&&(v.headers={...v.headers,"X-Deepdesk-API-Version":f});let T=c,_=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[i]&&l&&(this.latestRequestByUrl[i].isAborted=!0,this.latestRequestByUrl[i].reject(new Error("Aborted"))),this.latestRequestByUrl[i]=r;let y=async()=>(T--,a(i,v).then(async x=>u(x)&&!r.isAborted&&T>0?(await _r(d),y()):x.status===401&&p===!0&&_===!1?(_=!0,await this.refreshToken(),y()):x).catch(async x=>{if(g(x)&&!r.isAborted&&T>0)return await _r(d),y();throw x}));y().then(x=>x.json().catch(()=>null).then(S=>{x.status>=500?s(new xr("Server Error",S)):x.status===401?s(new kt("Unauthorized",S)):x.status===403?s(new kt("Forbidden",S)):x.status===404?s(new kt("Not Found",S)):x.status>=400&&s(new kt("Bad Request",S)),delete this.latestRequestByUrl[i],n(S)})).catch(x=>{s(x)})})}async validateToken(){let{has_valid_access_token:e}=await this.get("/auth/validate");if(!e)return!1;let{is_logged_in:o}=await this.get("/apis/admin/session/validate/",{version:null});return!!o}refreshToken(){return t.refreshingToken||(t.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{t.refreshingToken=null},1e3*60)})),t.refreshingToken}get(e,o){return this.request(e,o)}post(e,o,n){return this.request(e,{method:"POST",body:JSON.stringify(o),...n})}patch(e,o,n){return this.request(e,{method:"PATCH",body:JSON.stringify(o),...n})}put(e,o,n){return this.request(e,{method:"PUT",body:JSON.stringify(o),...n})}delete(e,o){return this.request(e,{method:"DELETE",...o})}};var Py;(e=>{let t;(l=>(l.SEND_MESSAGE="Send Message",l.HANDLING_TIME="Handling Time",l.START_AUTOFLOW="Start Autoflow",l.ABORT_AUTOFLOW="Abort Autoflow",l.ADD_TO_PERSONAL_COLLECTION="Add to personal collection",l.DELETE_FROM_PERSONAL_COLLECTION="Delete from personal collection"))(t=e.EventType||={})})(Py||={});function An(t){return{...R(t),tags:t.tags}}var Be=class t{constructor(e,o={}){this.options=o;this.client=new ge(e,{fetch:o.fetch}),this.client.patchFetch(n=>async(s,r)=>{let i=await n(s,r);return this.handleDeepdeskVersionHeaders(i),i})}latestReceivedDeepdeskVersions={};client;shouldFetchCsrfToken=!0;static exchangeTokenPromise=null;async preflight(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let e=await this.getCsrfToken();this.client.setCsrfToken(e)}return this.options.token?(t.exchangeTokenPromise||(t.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),t.exchangeTokenPromise):Promise.resolve()}async createConversation(e){await this.preflight(),C.info(`Creating conversation for session ${e.sessionId} and agent ${e.agentId}`);let o=await this.client.post("/api/conversations",{...U(e),tags:e.tags},{version:"v2"});return An(o)}async getProfile(e){let o=await this.client.get(`/apis/admin/profiles/${e}/`,{version:null});return R(o)}async getKnowledgeAssistant(e){let o=await this.client.get(`/apis/admin/knowledge-assist/assistants/${e}/`,{version:null});return R(o)}async getContentTypes(){let e=await this.client.get("/apis/admin/content-types/",{version:null});return R(e)}async getPlatformConfig(){let{config:e}=await this.client.get("/platform/config/",{version:null});return R(e)}async checkUserExists(e){let{exists:o}=await this.client.get(`/apis/admin/users/exists?external_id=${e}`);return o}async getConversationBySessionId(e,o={}){await this.preflight(),C.info(`Getting conversation for session ${e}`);let{attempts:n=1,retryDelay:s=1e3}=o,r=await this.client.get(`/api/conversations/by_session_id/${e}`,{attempts:n,retryDelay:s,retryOnResponse:i=>i.status===404||i.status>=500,version:"v2"});return C.info(`Successfully retrieved conversation ${r.id} for session ${e}`),An(r)}async isConversationSupported(e,o={}){C.info(`Check if conversation for session ${e} is supported`);let{attempts:n=1,retryDelay:s=1e3}=o;return(await this.client.get(`/api/conversations/by_session_id/${e}/active_profile`,{attempts:n,retryDelay:s,retryOnResponse:i=>i.status===404||i.status>=500,version:"v2"})).has_active_profile}async updateConversation(e,o){let n=U(o);o.tags&&(n.tags=o.tags);let s=await this.client.put(`/api/conversations/${e}`,n,{version:"v2"});return An(s)}async postMessages(e,o){return(await this.client.post(`/api/conversations/${e}/messages`,o.map(s=>({...U(s),tags:s.tags})),{version:"v2"})).map(s=>An(s))}async sendEvent(e,o){let{data:n,...s}=o,r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((i,[a,l])=>({...i,[a]:l}),{});return this.client.post("/api/events",U({...r,...s,data:n,name:e}),{version:"v2"})}async sendEventV1(e,o){let n=Object.entries(this.latestReceivedDeepdeskVersions).reduce((s,[r,i])=>({...s,[r]:i}),{});return this.client.post("/api/events",{event:e,data:U({...o,...n})})}async getEntities(e){return(await this.client.post("/api/entities",{messages:e.filter(n=>n.text)})).entities}async getSummary(e,o={}){return(await this.client.post("/api/summary",{conversation:{messages:e.filter(s=>s.text&&s.source),agent_id:o.agentId,id:o.externalConversationId},prompt_instruction:o.promptInstruction,model:o.model})).summary}async getTemporaryExchangeToken(){return(await this.client.get("/auth/exchange-token",{version:null})).jwt}async exchangeTokenForAccessCookie(e){return this.client.post("/apis/admin/session/jwt/",{jwt:e},{version:null}).catch(o=>{throw C.warn(`Invalid token '${e}'`),o})}async authenticateWithKey(e,o){await this.preflight(),await this.client.post("/apis/admin/session/api-key/",U(o),{version:null,refreshTokenOn401:!1,headers:{apikey:e}})}async getTextSuggestions(e,o={},n){return n==="sticky-messages"?this.getPinnedMessages(e):(await this.client.post(`/api/conversations/${e}/recommend/${n}`,U(o),{abortLatest:!0})).map(r=>({...R(r),text:r.text||r.url||r.message,source:n,type:n})).filter((r,i,a)=>i===a.findIndex(l=>l.text===r.text))}async isLoggedIn(){return await this.preflight(),this.client.validateToken()}async getAutocompleteSuggestions(e,o){return(await this.client.post(`/api/conversations/${e}/autocomplete`,U(o),{abortLatest:!0})).map(s=>({score:1,source:s.source,sourceText:s.source_text,text:s.label,trainingJobs:s.training_jobs,searchKeywords:s.search_keywords,type:s.source})).filter((s,r,i)=>r===i.findIndex(a=>a.text===s.text))}async getPinnedMessages(e){let o=await this.client.get(`/api/conversations/${e}/sticky-messages`,{abortLatest:!0});return R(o).map(n=>({...n,text:n.message,source:"sticky-messages",type:"pinned-message"}))}async getStyleSuggestions(e){let o=await this.client.post("/api/style-suggestions",U(e),{abortLatest:!0});return R(o)}async search(e){let o=await this.client.post(`/api/profiles/${e.profile}/search`,U(e),{version:"v2"});return R(o)}async knowledgeAssist(e,o,n,s={}){let r=await this.client.post(`/api/knowledge-assist/assistants/${n}/search`,U({question:e.question,promptInstruction:e.promptInstruction,chatHistory:o.map(i=>({question:i.question,answer:i.answer.answer})),agentId:s.agentId,conversationId:s.conversationId}),{version:"v2"});return R(r)}async requestLoginByEmail(e){let o=await this.client.post("/apis/admin/session/passwordless/request/",{email:e},{version:null});return R(o)}async requestPasswordlessToken(){let e=await this.client.get("/apis/admin/session/passwordless/request/",{version:null});return R(e.token)}async getCsrfToken(){let{token:e}=await this.client.get("/apis/admin/session/csrf/",{version:null});return e}async verifyLoginToken(e){let o=await this.client.post("/apis/admin/session/passwordless/login/",{token:e},{version:null});return R(o)}async evaluateRule(e,o,n,s={}){let r=new URLSearchParams;s.raiseForFailingConditions&&r.set("raise_for_failing_conditions","true");let i=await this.client.post(`/api/conversations/${o}/rules/${e}/evaluate?${r.toString()}`,n,{version:"v2"});return R(i.cues)}handleDeepdeskVersionHeaders(e){e.headers.forEach((o,n)=>{let s=n.toLowerCase(),r=s.match(Ur);if(!o||!r)return;let i=r[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&o&&a!==o&&C.warn(`Overwritten Version header ${s}: ${JSON.stringify(a)} -> ${JSON.stringify(o)}`),this.latestReceivedDeepdeskVersions[i]=o})}};var lo=class{constructor(e,o){this.url=e;this.options={timeout:25e3,...o}}eventListeners={};options;timeoutTimer;eventSource;proxyEvent(e){this.eventSource.addEventListener(ts(e),o=>{let{data:n}=o;try{let s=JSON.parse(n);this.emit(e,R(s))}catch{C.warn(`Invalid JSON for ${e}: ${n}`)}})}connect(){clearTimeout(this.timeoutTimer);let e=new EventSource(this.url,{withCredentials:!0});this.eventSource=e;let o=!1;e.onopen=()=>{o=!0},e.onerror=()=>{o&&e.readyState===2&&this.connect()},this.timeoutTimer=setTimeout(()=>{e.close(),this.connect()},this.options.timeout),Object.keys(this.eventListeners).forEach(n=>{this.proxyEvent(n)})}disconnect(){var e;clearTimeout(this.timeoutTimer),this.eventListeners={},(e=this.eventSource)==null||e.close()}emit(e,o){this.eventListeners[e]&&this.eventListeners[e].forEach(n=>n(o))}on(e,o){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(o),this.proxyEvent(e),()=>{this.off(e,o)}}off(e,o){let n;this.eventListeners[e]&&(n=this.eventListeners[e].indexOf(o),n>-1&&this.eventListeners[e].splice(n,1))}};var Ay;(e=>{let t;(r=>(r.Started="Started",r.Aborted="Aborted",r.Completed="Completed"))(t=e.AutoflowSessionState||={})})(Ay||={});var co=class{constructor(e,o={}){this.apiUrl=e;this.client=new ge(e,o)}client;streams={};logger=C;async getCustomMessages(e){let o=await this.client.get(`/sessions/${e}/suggestions`);return R(o.suggestions)}async sendCustomMessage(e,o){let n=await this.client.post(`/sessions/${e}/messages`,U(o));return R(n)}async answerCustomMessage(e,o){await this.client.post(`/sessions/${e}/answers`,U(o))}async getAutoflows(e){let o=await this.client.get(`/sessions/${e}/autoflows`);return R(o.autoflows)}async startAutoflowSession(e){let o=await this.client.post("/autoflow-sessions",U(e));return R(o)}async stopAutoflowSession(e){await this.client.delete(`/autoflow-sessions/${e}`)}openStream(e){return this.streams[e]||(this.streams[e]=new lo(`${this.apiUrl}/sessions/${e}/events`),this.streams[e].connect()),this.streams[e]}closeStream(e){this.streams[e]||(this.streams[e].disconnect(),delete this.streams[e])}};import{combineReducers as Fy,configureStore as By}from"@reduxjs/toolkit";import{createSlice as Ly}from"@reduxjs/toolkit";var ld={startTime:null,stopTime:null},cd=Ly({name:"handlingTime",initialState:ld,reducers:{handlingTimeStart(t){if(t.startTime&&!t.stopTime)throw new Error("Timing already started");t.startTime=new Date,t.stopTime=null},handlingTimeStop(t){if(!t.startTime)throw new Error("Timing not started");t.stopTime=new Date},handlingTimeReset(t){t.startTime=null,t.stopTime=null}},extraReducers:t=>{t.addCase(M,()=>ld)}}),{handlingTimeStart:dd,handlingTimeStop:Ln,handlingTimeReset:pd}=cd.actions,ud=cd.reducer;var gd=(t={})=>{let e={onAuthError:rt(!1),...t};return o=>n=>s=>("error"in s&&s.error.message==="Unauthorized"&&o.dispatch(e.onAuthError),n(s))};import{createAsyncThunk as My,createSlice as Oy}from"@reduxjs/toolkit";var Mn={list:{keywordMatches:[]},fetchState:"idle",isInitialRequest:null};var Ye=My("styleSuggestions/getAll",async({text:t},e)=>{var i;let{deepdeskAPI:o}=e.extra,n=e.getState(),{showStyleSuggestions:s}=n.settings,r=(i=n.conversation.current)==null?void 0:i.profileCode;if(!s)return Mn.list;if(!r)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:r,message:t})}),Ny=Oy({name:"styleSuggestions",initialState:Mn,reducers:{},extraReducers:t=>{t.addCase(Ye.pending,e=>{e.isInitialRequest=e.isInitialRequest===null,e.fetchState="loading"}).addCase(Ye.rejected,e=>{e.fetchState="error"}).addCase(Ye.fulfilled,(e,o)=>{e.fetchState="done",Re(e.list,o.payload)||(e.list=o.payload)}).addCase(Ue,e=>{e.list=Mn.list}).addCase(M,()=>Mn)}}),md=Ny.reducer;var fd=(t={})=>{let e,o=!0,n={getStyleSuggestions:Ye,debounce:500,...t};return s=>r=>i=>{var u;let a=s.getState().input.text,l=r(i),c=s.getState();if(c.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:d}=c.settings;if(!((u=c.conversation.current)==null?void 0:u.id)||!d)return l;let{text:g}=c.input;return g===a&&!o||(clearTimeout(e),g==="")||(e=setTimeout(()=>{o=!1,s.dispatch(n.getStyleSuggestions({text:g}))},t.debounce)),l}};function Dy(t,e){return t.text===e.text&&t.selection.start===e.selection.start&&t.selection.end===e.selection.end}var hd=(t={})=>{let e={getTextSuggestions:le,getAutocompleteSuggestions:Qt,debounce:200,check:St,...t},o;return n=>s=>r=>{var m;let{input:{userCommitted:i}}=n.getState(),a=s(r),l=n.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:c,showTabCompletion:d}=l.settings,p=(m=l.conversation.current)==null?void 0:m.id,g=r.type===Yo.toString();if(!p||!c&&!d)return a;let{input:{userCommitted:u}}=l;return Dy(u,i)&&!g||(clearTimeout(o),!e.check(l))||(o=setTimeout(()=>{let v=ct(l);v===""?n.dispatch(e.getTextSuggestions("default")):n.dispatch(e.getAutocompleteSuggestions(v))},g?0:e.debounce)),a}};var yd=Ye.fulfilled.toString();function Hy(t,e){let o=new Set([...e.keywordMatches.map(s=>s.keyword)]),n=[];return o.forEach(s=>{let r=t.keywordMatches.filter(l=>l.keyword===s),i=e.keywordMatches.filter(l=>l.keyword===s),a=i.length-r.length;a<=0||n.push(...i.slice(0,a))}),n}var vd=t=>e=>o=>n=>{var c;if(n.type!==yd){o(n);return}let s=e.getState().styleSuggestions.list;o(n);let r=e.getState(),i=r.styleSuggestions.list,a=(c=r.conversation)==null?void 0:c.current;if(s===i)return;let l=Hy(s,i);n.type===yd&&l.length>0&&t.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var Ky=Fy({answer:Ka,auth:Zr,autoflows:uc,conversation:ei,contentTypes:Ji,customMessages:xc,passwordlessToken:Ec,entities:Ca,knowledgeAssistant:Ha,handlingTime:ud,info:Si,input:fi,settings:jr,profile:$a,search:Ei,summary:Aa,styleSuggestions:md,ui:vl,rules:Pi,textSuggestions:ol});function Sd(t){return By({reducer:Ky,middleware:e=>[...e({thunk:{extraArgument:{dynamicThunkObject:t.dynamicThunkObject,deepdeskAPI:t.deepdeskAPI,deepdeskBrokerAPI:t.deepdeskBrokerAPI}},serializableCheck:!1}),gd(),hd({debounce:200}),fd({debounce:500}),vd(t.deepdeskAPI),...t.middleware?t.middleware:[]],preloadedState:t.preloadedState})}var Uy=t=>{var e;return((e=t==null?void 0:t.type)==null?void 0:e.toLowerCase())??"unknown"},zy=t=>e=>o=>n=>{var a;let s=e.getState(),r=Xn("inlineSuggestions")(s);switch(n.type){case rt.toString():{!n.payload&&t.emit("logout",void 0);break}case se.toString():{let{start:l,end:c}=s.input.selection;t.emit("select-suggestion",{type:Uy(n.payload.suggestion),...n.payload,replace:n.payload.replace==="selection"?{start:l,end:c}:{start:0,end:c}},{mayApplyChanges:!0});break}case To.toString():{let{start:l,end:c}=s.input.selection;t.emit("replace",{...n.payload,replace:n.payload.replace==="selection"?{start:l,end:c}:{start:0,end:c}},{mayApplyChanges:!0});break}case Nt.toString():{let l=e.getState(),{text:c,selection:d}=l.input.userCommitted;t.emit("reset",{text:c,selectionAfter:d},{mayApplyChanges:!0});break}case Io.toString():t.emit("select-image",n.payload,{mayApplyChanges:!0}),t.sendEvent("Image attached",{conversationId:s.conversation.current.id,data:{path:n.payload.suggestion.image,title:n.payload.suggestion.title}});break;case ae.fulfilled.toString():n.payload.length>0&&t.sendEvent("entities found",{conversationId:s.conversation.current.id,data:{entities:n.payload}});break;case _e.fulfilled.toString():t.sendEvent("conversation summarized",{conversationId:s.conversation.current.id,data:{summary:n.payload.summary}});break;case $.toString():t.sendEvent(n.payload.name,{conversationId:((a=n.payload.options)==null?void 0:a.includeConversationData)&&s.conversation.current.id,data:n.payload.data});break;case Eo.toString():t.handleKeyDown(n.payload);break;case Ue.toString():t.logSendMessage(n.payload);break;case ko.toString():t.handleInputChanged(n.payload);break;case Se.fulfilled.toString():t.broadcast(is,n.payload,!1),t.emit("cues",n.payload);break;default:break}let i=o(n);switch(n.type){case Ue.toString():t.handleAfterSendMessage(n.payload);break;case Jt.toString():t.onUpdateShowTabHint(n.payload);break;case Ln.toString():t.logHandlingTime();break;case se.toString():{r&&(e.dispatch(ce([])),e.dispatch(ve()));break}case ce.toString():{r&&n.payload.length>0&&e.dispatch(Ae(0));break}default:break}return i},_d=zy;function br(t){return t.toISOString().replace("T"," ").replace("Z","")}function xd(t,e){var s,r,i;let{startTime:o,stopTime:n}=t.handlingTime;if(!o||!n)throw new Error("No startTime and stopTime for handling time metrics");return{conversationId:t.conversation.current.id,clientVersion:e.version,agentId:(s=t.info.agentInfo)==null?void 0:s.agentId,agentName:(r=t.info.agentInfo)==null?void 0:r.agentName,agentEmail:(i=t.info.agentInfo)==null?void 0:i.agentEmail,timeStart:br(o),timeStop:br(n)}}function bd(t,e,o){var F,K,H;let{text:n,metrics:{numCharsTyped:s,numCharsPasted:r,numCharsCut:i,numCharsDeleted:a,numPaste:l,agentStartedTypingTimestamp:c,externalTimeTotalSeconds:d,pastes:p,cuts:g,deletions:u,textSuggestions:f,offeredTextSuggestions:m}}=e[t],v=n.length,_=f.reduce((I,{text:A,searchTerm:k})=>I+A.length-(k?k.length:0),0),y=c??Date.now(),x=(Date.now()-y)/1e3+(d||0),S=s/x,O=f.reduce((I,{searchTerm:A})=>I+(A?A.length:0),0);return{conversationId:e.conversation.current.id,source:"agent",text:n,clientVersion:o.version,pastes:p,cuts:g,deletions:u,lenTextTyped:s+O,lenTextTotal:v,lenTextAssisted:_,lenTextPasted:r,lenTextCut:i,lenTextDeleted:a,timeTotalSeconds:x,charsPerSecond:S,numPastes:l,textSuggestionsV2:f,suggestionsCounters:[{source:"gpt",countOffered:m.filter(I=>I.source==="gpt").length}],agentId:(F=e.info.agentInfo)==null?void 0:F.agentId,agentName:(K=e.info.agentInfo)==null?void 0:K.agentName,agentEmail:(H=e.info.agentInfo)==null?void 0:H.agentEmail}}function wr(t,e){var r;let o=t.closest(e);if(o)return o;let n=t.getRootNode().host;if(n instanceof HTMLElement)return wr(n,e);let s=(r=t.ownerDocument.defaultView)==null?void 0:r.frameElement;return s?wr(s,e):null}function wd(t,e){return wr(t,e)}function Cd(t){return typeof t=="object"&&t!==null&&"name"in t&&"message"in t}function jy(t){return typeof t=="object"&&t!==null&&"tagName"in t}function Cr(t){return jy(t)&&(De(t)||dn(t))}var Td,me=new Map,Vy=["bottom","height","left","right","top","width"],qy=(t={},e={})=>Vy.some(o=>t[o]!==e[o]);function Ed(t){var o,n;if(t.ownerDocument===document)return[];let e=((n=(o=t.ownerDocument)==null?void 0:o.defaultView)==null?void 0:n.frameElement)??null;return e?[e,...Ed(e)]:[]}function kd(t,e){return!t||!e?null:{...t,top:t.top+e.top,left:t.left+e.left}}var On=!1,Id=()=>{On=!0;let t=[];if(me.forEach((e,o)=>{if(!o.isConnected){e.rect=null,t.push(e),me.delete(o);return}let n=o.getBoundingClientRect();qy(n,e.rect)&&(e.rect=n,t.push(e))}),t.forEach(e=>{let o=e.parentRects?e.parentRects.reduce(kd,e.rect):e.rect;e.callbacks.forEach(n=>n(o))}),me.size===0){On=!1;return}Td=window.requestAnimationFrame(Id)};function Tr(t,e){let o=Ed(t),n=[],s=o.map((r,i)=>Tr(r,a=>{n[i]=a;let l=me.get(t);if(!l)return;let c=n.reduce(kd,l.rect);l.callbacks.forEach(d=>d(c))}));return{observe(r=!0){if(s.forEach(i=>i.observe(!1)),me.has(t)){let i=me.get(t);i.callbacks.push(e),i.rect&&e(i.rect)}else me.set(t,{rect:void 0,callbacks:[e],parentRects:n});r&&!On&&Id()},unobserve(){s.forEach(i=>i.unobserve());let r=me.get(t);if(r){let i=r.callbacks.indexOf(e);i>=0&&r.callbacks.splice(i,1),r.callbacks.length||me.delete(t),me.size||(cancelAnimationFrame(Td),On=!1)}}}}var Rd,fe=new Map,Pd=()=>{fe.forEach((t,e)=>{if(!e.isConnected){fe.delete(e);return}let{clientHeight:o,scrollHeight:n}=e,s=n>o;t.visible!==s&&(t.visible=s,t.callbacks.forEach(r=>r(t.visible)))}),fe.size!==0&&(Rd=window.requestAnimationFrame(Pd))};function Ad(t,e){return{observe(){let o=fe.size===0;fe.has(t)?fe.get(t).callbacks.push(e):fe.set(t,{visible:void 0,callbacks:[e]}),o&&Pd()},unobserve(){let o=fe.get(t);if(o){let n=o.callbacks.indexOf(e);n>=0&&o.callbacks.splice(n,1),o.callbacks.length||fe.delete(t),fe.size||cancelAnimationFrame(Rd)}}}}var Er=["borderLeftWidth","borderRightWidth","borderTopWidth","borderBottomWidth","borderStyle","boxSizing","color","overflowWrap","fontFamily","fontSize","fontSizeAdjust","fontStretch","fontWeight","fontKerning","lineHeight","letterSpacing","paddingLeft","paddingTop","paddingRight","paddingBottom","width","height","textIndent","whiteSpace","wordBreak","wordSpacing","wordWrap"];function kr(t,e,o){return o.forEach(n=>{e.style[n]=t[n]})}function It(t){return parseFloat(t)}function Nn(t){return Math.round(t*1e6)}function Ld(t){return t/1e6}function Ir(t,e,o){if(t.boxSizing==="content-box")return;let{clientWidth:n}=e,s=It(t.width),r=It(t.borderLeftWidth),i=It(t.borderRightWidth),a=It(t.paddingRight),l=Ld(Nn(s)-Nn(r)-Nn(i)),c=Ld(Nn(n));if(l-c>2){let d=l-c;o.style.paddingRight=`${a+d}px`}}function Dn(t,e={}){var d;let o=e.overlayContainer||document.createElement("div");o.style.display="none",o.style.position=e.position??"fixed",o.style.pointerEvents="none",o.style.borderColor="transparent",Ge(o);let n=window.getComputedStyle(t),s=!0,r=()=>{o.scrollTop=t.scrollTop};kr(n,o,Er),Ir(n,t,o),e.mirrorOverflow&&(o.style.overflow="hidden",t.addEventListener("scroll",r));let i=Ad(t,()=>{kr(n,o,Er),Ir(n,t,o),r(),setTimeout(r,0)}),a,l=!0,c=Tr(t,p=>{if(p===null){e.onRemove&&e.onRemove(),o.remove();return}if(!l&&e.onMoveStart&&(Promise.resolve().then(()=>e.onMoveStart()),l=!0),clearTimeout(a),a=setTimeout(()=>{e.onMoveEnd&&e.onMoveEnd(),l=!1},200),p.height===0&&p.width===0){if(s===!0)return;e.onHide&&e.onHide(),o.style.display="none",s=!0;return}if(kr(n,o,Er),Ir(n,t,o),r(),o.style.top=`${p.top}px`,o.style.left=`${p.left}px`,e.closestScrollElement&&e.closestScrollElement!==t){let g=e.closestScrollElement.getBoundingClientRect(),u=window.getComputedStyle(e.closestScrollElement),f=It(u.borderTopWidth),m=It(u.borderBottomWidth),v=g.top+f-p.top,T=p.top+p.height+-(g.top+g.height-m);o.style.clipPath=`inset(${v}px 0px ${T}px 0px)`}s&&(o.style.display="block",e.onShow&&e.onShow(),s=!1)});return e.appendTo?e.appendTo.appendChild(o):(d=t.parentElement)==null||d.appendChild(o),c.observe(),i.observe(),[o,()=>{t.removeEventListener("scroll",r),c.unobserve(),i.unobserve()}]}var Md=(t,e)=>({value(){try{let o=sessionStorage.getItem(`dd-${t}`);if(!o)return e;try{return JSON.parse(o)}catch{return e}}catch{return e}},update(o){try{sessionStorage.setItem(`dd-${t}`,JSON.stringify(o))}catch{C.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function $y(t){return t.offsetParent!==null}function Od(t){if(!$y(t))return!1;let e=t.getBoundingClientRect();return e.top>=0&&e.left>=0&&e.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&e.right<=(window.innerWidth||document.documentElement.clientWidth)}function Rr(t,e,o=100){let n=Od(t);e({isVisible:n});let s=setInterval(()=>{let r=Od(t);r!==n&&(n=r,e({isVisible:n}))},o);return()=>{clearTimeout(s)}}import{jsx as z}from"react/jsx-runtime";var Nd=Md("showTabHint",!0),Fn=class t{static version="10.12.1-beta.9";static count=0;deepdeskApi;inputMediator=null;version;broadcastEvents;eventListeners={};unmountHandlers=[];widgetRoot=null;dynamicThunkObject={};isMounted=!1;instanceId;shouldRender=!0;store;constructor({deepdeskUrl:e,brokerUrl:o,version:n=t.version||"unknown",locale:s="en-US",token:r,fetch:i,productName:a,createCustomChannel:l}){let c=e.replace(/\/api$/,"");this.deepdeskApi=new Be(c,{token:r,fetch:i}),this.version=n,this.instanceId=t.count++;let d={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[_d({broadcast:(p,g,u)=>{this.broadcastEvents.send(p,g,u)},emit:(p,g,u)=>this.emit(p,g,u),handleAfterSendMessage:p=>this.handleAfterSendMessage(p),handleInputChanged:p=>this.handleInputChanged(p),handleKeyDown:p=>this.handleKeyDown(p),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:p=>this.logSendMessage(p),onUpdateShowTabHint:p=>Nd.update(p),sendEvent:(p,g)=>this.deepdeskApi.sendEvent(p,g)})]};o&&Object.assign(d,{deepdeskBrokerAPI:new co(o)}),this.store=Sd(d),this.broadcastEvents=new ad({debug:!0,deepdeskUrl:c,eventMap:Ai(this.store),createCustomChannel:l}),this.store.dispatch(Jt(Nd.value())),this.store.dispatch(yo({locale:s,adminUrl:c,productName:a}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){return this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex]??null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(C.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(C.warn("Profile has not been loaded (yet)"),!0):(C.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(rt(null)),this.store.dispatch(ye()),new Promise(e=>{let o=this.store.subscribe(()=>{let n=this.store.getState();G(n)&&Vr(n)!=="loading"&&(o(),e())});this.unmountHandlers.push(()=>{o()})})}async isLoggedIn(){return(await this.store.dispatch(ye())).payload}async setPlatformAgentId(e){try{if((await this.deepdeskApi.client.get("/apis/admin/session/me/",{version:null})).external_id)return;await this.deepdeskApi.client.request("/apis/admin/session/me/",{method:"PATCH",body:JSON.stringify({external_id:e}),version:null})}catch(o){C.warn("Failed to attach user:",o)}}async isConversationSupported(e,o){return(await this.store.dispatch(Jn({sessionId:e,options:o}))).payload}async createConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(_o(e))).payload}async getConversationBySessionId(e,o){return this.hasConversation()&&this.sessionId()!==e&&this.resetConversation(),(await this.store.dispatch(xo({sessionId:e,options:o}))).payload}async upsertConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(Yn(e))).payload}async postMessages(e){return(await this.store.dispatch(wo(e))).payload}async updateConversation(e){return(await this.store.dispatch(bo(e))).payload}resetConversation(){this.store.dispatch(M()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}async getSummary(){let e=await this.store.dispatch(_e());if(e.error)throw new Error(e.error.message);return e.payload.summary}configure(e){this.store.dispatch(yo(e))}setVisitorInfo(e){this.store.dispatch(vi(e))}async setAgentInfo(e){await this.store.dispatch(Dt(e))}async setAgentSettings(e){await this.store.dispatch(ns(e))}async getAgentSettings(){return(await this.store.dispatch(ss())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let e=[];return this.store.dispatch(Yo()),e.push(this.refreshWidgetSuggestions()),Promise.all(e).then(()=>{})}notifyInputChanged(e){this.store.dispatch(ko(e))}notifyKeyDown(e){this.store.dispatch(Eo(e))}notifyPaste(e,o){this.store.dispatch(pi({text:e,selectionText:o}))}notifyCut(e){this.store.dispatch(ci(e))}notifyExternalSuggestion(e){this.store.dispatch(se(e)),this.store.dispatch(ve())}async evaluateRule(e,o={}){let{payload:n,error:s}=await this.store.dispatch(Se({label:e,params:o}));if(s)throw s;return n}handleInputChanged(e){let{overlayCollapsed:o,openOverlayWhenTyping:n}=this.state.ui;o&&n&&this.store.dispatch(Ne({collapse:!1})),this.inputMediator&&this.store.dispatch(si({text:e,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(ce([])))}handleKeyDown(e){let{overlayCollapsed:o}=this.state.ui,{textSuggestions:n,selectedSuggestionIndex:s,selection:r}=this.state.input,{inlineSuggestions:i}=this.state.settings,a=n.length>0,l=s!==-1;if(this.store.dispatch(di(ti(e))),e.key!=="Tab"&&!this.settings.showTextSuggestions)return;let c=()=>{o||!a||r&&(e.shiftKey||(this.store.dispatch(ii()),i||this.stageSelectedSuggestion({inputType:"arrow"}),e.preventDefault()))},d=()=>{o||!a||i&&s<=0||r&&(e.shiftKey||(this.store.dispatch(li()),e.preventDefault(),!i&&(this.state.input.selectedSuggestionIndex===-1?this.store.dispatch(Nt()):this.stageSelectedSuggestion({inputType:"arrow"}))))};switch(e.key){case"Up":case"ArrowUp":i?d():c();return;case"Down":case"ArrowDown":{i?c():d();return}case"Esc":case"Escape":{i&&l&&this.store.dispatch(Ae(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(Ae(-1)),this.store.dispatch(Nt()),e.preventDefault()):o||(this.store.dispatch(Ne({collapse:!0})),this.store.dispatch(hl(!0)),e.preventDefault());return}case"Tab":{let{userCommitted:p}=this.state.input,g=p.text.substring(0,p.selection.end),{tabCompletionSuggestion:u}=this.state.input;this.store.dispatch(Jt(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!i&&this.settings.showTabCompletion&&u&&u.text.startsWith(g)&&(this.store.dispatch(se({text:u.text,suggestion:u,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch(ve())),e.preventDefault();break}default:}}handleAfterSendMessage(e){this.emit("send-message",e),this.store.dispatch(ui()),this.store.dispatch(ce([]))}handlingTimeStart(){this.state.handlingTime.startTime||(C.info("Start handling time"),this.store.dispatch(dd()))}handlingTimeStop(){this.state.handlingTime.startTime&&(C.info("Stop handling time"),this.store.dispatch(Ln()))}logSendMessage(e){let o=bd("input",this.state,{version:this.version});e&&(Object.assign(o,{text:e}),Object.assign(o,{lenTextTotal:e.length})),this.deepdeskApi.sendEventV1("Send Message",o),this.emit("send-message-event",o)}logHandlingTime(){let e=xd(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",e),this.store.dispatch(pd())}notifySubmit(e={}){this.shouldAbort()||(this.store.dispatch(ve()),this.store.dispatch(Ue(e.text??this.state.input.text)))}stageSelectedSuggestion(e){let o=this.state.input.selectedSuggestionIndex,{textSuggestions:n}=this.state.input;this.store.dispatch(se({text:n[o].text,suggestion:n[o],eventMetrics:e,replace:"until-selection-end"}))}emit(e,o,n={}){let s=()=>{this.eventListeners[e]&&this.eventListeners[e].forEach(r=>{try{r(o)}catch(i){C.warn(`The following error occurred in deepdeskSDK.on('${e}', handler)`),C.error(i)}})};this.inputMediator&&n.mayApplyChanges?this.inputMediator.applyChanges(s):s()}on(e,o){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(o),()=>{this.off(e,o)}}off(e,o){if(!e&&!o){this.eventListeners={};return}let n;this.eventListeners[e]&&(n=this.eventListeners[e].indexOf(o),n>-1&&this.eventListeners[e].splice(n,1))}setConversationQuery(e){this.dynamicThunkObject.conversationQuery=e}whenConversationLoaded(e){let o=()=>this.loadProfileConfig().then(()=>e());this.hasConversation()&&o();let n=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==n&&(n=this.hasConversation(),n&&o())})}overlayContainerFactory(e,o,n,s){let[r,i]=Dn(o,n);return r.setAttribute("translate","no"),r.dataset.testid=e,s&&r.classList.add(s),this.unmountHandlers.push(()=>{Hn(r),i(),r.remove()}),r}createInlineContainer(e,o){var i;let n=document.createElement("div");n.style.position="absolute",n.style.top="0px",n.style.left="0px",n.style.height="0px",n.style.width="0px";let s=document.createElement("div");s.style.display="none",s.style.position="absolute",s.style.height="0px",s.style.width="0px",s.style.backgroundColor="red",n.appendChild(s);let r=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;if(r){let[a,l]=Dn(r,{appendTo:document.body,onMoveStart:()=>{s.style.display="none"}});a.dataset.testid=o,a.style.zIndex="2",a.appendChild(n),this.unmountHandlers.push(()=>{Hn(s),l()})}else document.body.appendChild(n);return s}createContainer(e,o=document.body){let n=window.getComputedStyle(o),s=document.createElement("div");return Ge(s),s.dataset.testid=e,s.style.color=n.color,s.style.fontSize=n.fontSize,s.style.fontFamily=n.fontFamily,s.style.fontVariant=n.fontVariant,s.setAttribute("translate","no"),o.appendChild(s),this.unmountHandlers.push(()=>{Hn(s),s.remove()}),s}storeMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,o=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(e,o),C.info(`Stored analytics for ${this.conversationId()}`)}catch{}}restoreMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,o=window.sessionStorage.getItem(e);if(!o)return;let n=JSON.parse(o);n.text.trim()===this.state.input.text.trim()?(C.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(mi(n.metrics))):C.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(e)}catch{}}mount(e,o={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!Cr(e))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let{customStyles:n={},showStyleSuggestions:s,showTabCompletion:r,showTextSuggestions:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:c,showSuggestionsAfterPattern:d,isEmbedded:p,detectSubmit:g,insertLink:u,inputMediator:f,closestScrollSelector:m,appendOverlayTo:v,inlineSuggestions:T,floatingMenu:_}=o;this.configure({showStyleSuggestions:s,showTabCompletion:r,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:c,showSuggestionsAfterPattern:d,showTextSuggestions:i,insertLink:u,isEmbedded:p,inlineSuggestions:T,floatingMenu:!!_}),o.automaticHandlingTime&&this.setupHandlingTime(e),Ge(e),this.inputMediator=f||(De(e)?new Tt(e):new Ct(e)),this.inputMediator.on("change",({plainText:S})=>{this.notifyInputChanged(S)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(gi({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",S=>{this.notifyKeyDown(S)}),this.inputMediator.on("paste",({pastedText:S,selectionText:O})=>{this.notifyPaste(S,O)}),this.inputMediator.on("cut",({selectionText:S})=>{this.notifyCut(S)});let y=m&&wd(e,m)||void 0;if(T){let{customStyles:S,appendOverlayTo:O}=o;if(De(e))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let F=this.createInlineContainer(e,"deepdesk-caret");Rt(z(Xe,{store:this.store,customStyles:S,children:z(je,{broadcastEvents:this.broadcastEvents,children:z(Cl,{})})}),F),this.inputMediator.on("caret",H=>{this.store.dispatch(ce([])),H?(F.style.display="block",F.style.top=`${H.top}px`,F.style.left=`${H.left}px`):F.style.display="none"});let K=this.overlayContainerFactory("floating-menu",y||e,{appendTo:typeof _=="object"&&"appendOverlayTo"in _?_.appendOverlayTo:O},S==null?void 0:S.floatingMenuRootNode);Rt(z(Xe,{store:this.store,customStyles:S,children:z(je,{broadcastEvents:this.broadcastEvents,children:z(ml,{onLogIn:()=>this.loginViaPopup().catch(H=>C.warn(H.message))})})}),K)}else{let S=this.overlayContainerFactory("deepdesk-tab-completion",y||e,{appendTo:v,closestScrollElement:y,mirrorOverflow:!0,onRemove:()=>this.unmount()},n==null?void 0:n.rootNode),O=this.overlayContainerFactory("deepdesk-suggestions-overlay",y||e,{appendTo:v},n==null?void 0:n.suggestionsRootNode);Rt(z(Xe,{store:this.store,customStyles:n,children:z(je,{broadcastEvents:this.broadcastEvents,children:z(ic,{inputElement:e})})}),S),Rt(z(Xe,{store:this.store,customStyles:n,children:z(je,{broadcastEvents:this.broadcastEvents,children:z(Ol,{onLogIn:()=>this.loginViaPopup().catch(F=>C.warn(F.message))})})}),O)}Rt(z(Xe,{store:this.store,customStyles:n,children:z(je,{broadcastEvents:this.broadcastEvents,children:z(ll,{})})}),this.createContainer("deepdesk-overlays"));let x;this.inputMediator.on("selection",S=>{clearTimeout(x),S===null?x=setTimeout(()=>{S!==null&&this.store.dispatch(es(S))},500):this.store.dispatch(es(S))}),this.inputMediator.on("disabled",()=>{var S;(S=this.inputMediator)==null||S.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{g&&this.notifySubmit()}),this.inputMediator.on("blur",()=>this.store.dispatch($s(!1))),this.inputMediator.on("focus",()=>this.store.dispatch($s(!0))),this.store.dispatch(ri({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.unmountHandlers.push(()=>{this.state.input.text!==""&&(this.store.dispatch(ve()),this.storeMetrics())}),this.whenConversationLoaded(()=>{var S;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((S=this.state.conversation.current)==null?void 0:S.sessionId)}),this.isMounted=!0}unmount(){var e;this.unmountHandlers.forEach(o=>o()),this.unmountHandlers=[],(e=this.inputMediator)==null||e.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(e,o={}){if(this.widgetRoot&&C.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:n,showImages:s,isEmbedded:r}=o;this.widgetRoot=e,this.configure({showImages:s,isEmbedded:r}),Rt(z(Xe,{store:this.store,customStyles:n,children:z(je,{broadcastEvents:this.broadcastEvents,children:z(od,{onLogIn:()=>this.loginViaPopup().catch(i=>C.warn(i.message))})})}),e),this.whenConversationLoaded(()=>{var i;this.broadcastEvents.setSessionId((i=this.state.conversation.current)==null?void 0:i.sessionId)})}unmountWidget(){this.widgetRoot&&Hn(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(e){let o=Rr(e,({isVisible:n})=>{n?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),o()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){Cd(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(Zt());let e=Oe(this.state);e&&(await this.store.dispatch(Xt()),this.store.dispatch(yo({showSearch:e.search,showAutoflows:e.autoflows,showCustomMessages:e.customMessages,showImageSearch:e.imageSearch,showEntitiesCommand:e.entitiesCommand,showSummaryCommand:e.summarizer,showKnowledgeSearch:!!e.knowledgeAssistant,recommendTextSuggestions:e.recommendTextSuggestions})))}),this.loadProfileConfigPromise)}async loginViaPopup(e){return new Promise((o,n)=>{let s=new MessageChannel,r=s.port1,i=this.state.settings.adminUrl,a=new URL(e!=null&&e.url?e==null?void 0:e.url:`${i}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let l=!1,c=()=>{d&&!d.closed&&d.close(),window.removeEventListener("message",p),clearInterval(g)};r.onmessage=async u=>{var f,m;if((f=u.data)!=null&&f.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((m=u.data)==null?void 0:m.jwt),await this.isLoggedIn(),this.broadcastEvents.send(Ft),l=!0,s.port1.close(),o()}catch(v){console.error(v),n(v)}finally{l=!0,c()}};let d=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");d===null&&n(new Error("Popup blocked by browser"));let p=async u=>{var f;if(u.origin===a.origin)switch((f=u.data)==null?void 0:f.type){case"deepdesk-popup-loaded":{try{let m=JSON.stringify({type:"deepdesk-popup-create-channel"});d==null||d.postMessage(m,a.origin,[s.port2])}catch(m){C.error("Error posting message to popup",m),n(m)}break}case"deepdesk-popup-error":{c(),u.data.message==="Timeout"&&C.warn("Popup timed out. Check if the account's platform url is configured correctly."),n(new Error(u.data.message));break}}};window.addEventListener("message",p);let g=setInterval(()=>{d&&!d.closed||(c(),l||n(new Error("Popup closed by user")))},200);this.unmountHandlers.push(c)})}async checkForTrialMode(e){try{let{account:o}=await this.deepdeskApi.getPlatformConfig();if(!o.isTrial){this.shouldRender=!0;return}if(C.info("Trial is active"),!await this.deepdeskApi.checkUserExists(e))throw new Error("User is not in trial");this.shouldRender=!0}catch(o){let{message:n}=o;C.info(n),this.shouldRender=!1}}async refreshWidgetSuggestions(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:e}=this.state.profile.data;if(!e.widget)return;let o=Qo(this.state);try{o.forEach(({type:n})=>{n==="entities"?this.store.dispatch(ae()):this.store.dispatch(le(n))})}catch(n){this.handleError(n)}}};async function Wy(t,e,o={}){let{value:n}=t,{start:s,end:r}=o.replace??{start:0,end:n.length},i=`${n.slice(0,s)}${e}${n.slice(r)}`,a=o.selectionAfter??{start:s+e.length,end:s+e.length},l=()=>{if(o.setValue)return o.setValue(i);t.value=i};return Promise.resolve(l()).then(()=>{t.selectionStart=a.start,t.selectionEnd=a.end,t.blur(),t.focus()})}async function Gy(t,e,o={}){let n=o.replace?Je(t,o.replace.start,o.replace.end):ao(t),s,r=()=>{if(o.setRange)return o.setRange(n.cloneRange());n.deleteContents(),s=document.createElement("span"),n.insertNode(s),o.insertBRs!==!1?e.split(`
|
|
10
10
|
`).reverse().forEach((i,a)=>{a>0&&n.insertNode(document.createElement("br")),n.insertNode(document.createTextNode(i))}):n.insertNode(document.createTextNode(e))};return Promise.resolve(r()).then(()=>{try{if(o.selectionAfter!==!1){t.focus();let i=o.selectionAfter?Je(t,o.selectionAfter.start,o.selectionAfter.end):(n.collapse(!1),n),a=window.getSelection();a==null||a.removeAllRanges(),a==null||a.addRange(i)}if(!s)return;s.scrollIntoView&&s.scrollIntoView({block:"nearest",inline:"nearest"})}finally{s&&s.remove()}})}function Xy(t){let e=document.createElement("template");return e.innerHTML=t.replace(/(\[([^\]]+)])\(([^)]+)\)/g,'<a href="$3" target="_blank" rel="noopener noreferrer">$2</a>'),e.content}function Zy(t){let e=document.createDocumentFragment();return t.split(`
|
|
11
11
|
`).forEach((o,n)=>{n>0&&e.appendChild(document.createElement("br"));let s={index:0},r=0;for(;s=o.slice(r).match(/(\[([^\]]+)])\(([^)]+)\)/);){let i=document.createElement("a");i.href=s[3],i.setAttribute("target","_blank"),i.setAttribute("rel","noopener noreferrer"),i.appendChild(document.createTextNode(s[2])),e.appendChild(document.createTextNode(o.slice(r,r+s.index))),e.appendChild(i),r=r+s.index+s[0].length}e.appendChild(document.createTextNode(o.slice(r)))}),e}function Dd(t,e){return!t.contains(e)||e===t?null:e.parentNode===t?e:Dd(t,e.parentNode)}async function Qy(t,e,{isBlock:o,isHTML:n}={}){let s;t.dispatchEvent(new InputEvent("beforeinput",{inputType:"insertText",data:e,bubbles:!0,cancelable:!0}));let r=()=>{let i=t.ownerDocument.defaultView??window,a=i.getSelection();if((!a||a.rangeCount===0)&&(t.focus(),a=i.getSelection()),!a||a.rangeCount===0)return;let l=a.getRangeAt(0);if(!l)return;s=document.createElement("span"),l.insertNode(s);let c=n?Xy(e):Zy(e);if(o){let d=l.startContainer===t?t.childNodes[l.startOffset]:l.startContainer,p=Dd(t,d)??t.firstChild;t.insertBefore(c,(p==null?void 0:p.nextSibling)??null)}else l.insertNode(c),l.collapse(!1)};return Promise.resolve(r()).then(()=>{if(t.dispatchEvent(new InputEvent("input",{inputType:"insertText",data:e,bubbles:!0,cancelable:!0})),t.focus(),!!s)try{s.scrollIntoView&&s.scrollIntoView({block:"nearest",inline:"nearest"})}finally{s&&s.remove()}})}function Jy(t){return t.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}async function Yy(t,e,o){await new Be(t).authenticateWithKey(e,o)}async function ev(t){let o=await new ge(t).get("/platform/config/",{version:null});return R(o)}async function tv(t){let o=await(t.fetch??window.fetch)(t.url),n=await o.blob();return new File([n],t.name,{type:t.mimeType??o.headers.get("Content-Type")??"image/jpeg"})}async function ov(t,e){let o=await tv(e),n=new Event("change",{bubbles:!0,cancelable:!0});try{Object.defineProperty(t,"files",{configurable:!0,get:()=>[o]}),t.dispatchEvent(n)}finally{Object.hasOwn(t,"files")&&delete t.files}}export{N as Card,Ct as ContentEditableInput,Be as DeepdeskAPI,Fn as DeepdeskSDK,ge as HTTPClient,Fe as InputMediator,st as InputType,jn as KeyboardHint,Vn as Label,ho as Locale,ke as Section,$n as SectionList,Ie as Sources,L as Suggestion,te as SuggestionList,Tt as TextAreaInput,nt as ToggleButton,ov as attachFile,Yy as authenticateWithKey,ao as createFullRange,Dn as createOverlayContainer,Je as createRangeFromOffsets,Wt as escapeHTML,ev as fetchPlatformConfig,Jy as formatTextMarkup,Rn as getRangeOffsets,Pn as getRangeText,Qy as insertCKEditor,ws as isHTML,Cr as isSupportedInputElement,Gy as updateContentEditable,Wy as updateTextArea,h as useStyles,Rr as waitForElementVisibilityChange};
|