@deepdesk/deepdesk-sdk 15.1.1-beta.3 → 15.1.1-beta.4
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 +1 -1
- package/package.json +2 -2
package/dist/index.iife.js
CHANGED
|
@@ -80,7 +80,7 @@ Please report this to https://github.com/markedjs/marked.`,t){let o="<p>An error
|
|
|
80
80
|
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
|
|
81
81
|
c32.4,32.4,47.8,70,47.8,115.2v70h11.9c9.4,0,17.9,3.4,24.7,10.2C462.1,250,465.5,257.7,465.5,267.9z`})})});var Fy=x(C()),qM={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},nC=({className:e,color:t})=>(0,Fy.jsx)("svg",{className:e,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:(0,Fy.jsx)("path",{d:"M172.03 0.0199966H0V86.03C47.5 86.03 86 124.54 86 172.04C86 124.54 124.51 86.03 172.01 86.03C219.51 86.03 258.03 124.54 258.03 172.04C258.03 219.54 219.52 258.05 172.01 258.05C124.5 258.05 86 219.54 86 172.04C86 219.54 47.5 258.05 0 258.05V344.06H172.03C267.04 344.06 344.06 267.04 344.06 172.03C344.06 77.02 267.04 0 172.03 0V0.0199966Z",fill:qM[t||"pink"]})});var rC={root:"dd-LbeUM",text:"dd-Dpfn1",isLoggedIn:"dd-XvHAn",isLoggedOut:"dd-21y-z",icon:"dd-8rLqS",logo:"dd-slXhD",lock:"dd-ByzlR"};var zy={};dt(zy,{enUS:()=>GM,nlNL:()=>QM});var GM={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},QM={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};var ii=x(C()),iC=({onLogIn:e})=>{let t=q(zy),n=H("floatingMenu"),r=H("productName"),o=G(),i=_(gt),s=I("FloatingMenu",rC);if(i===null||n===!1)return null;let a=()=>{i===!0?o(en(!0)):e()};return(0,ii.jsxs)("button",{className:(0,oC.default)(s.root,{[s.isLoggedIn]:i,[s.isLoggedOut]:!i}),onClick:a,children:[(0,ii.jsx)("div",{className:s.text,children:t(i?"search":"signin",{productName:r})}),(0,ii.jsxs)("div",{className:s.icon,children:[(0,ii.jsx)(nC,{className:s.logo,color:"pink"}),i===!1&&(0,ii.jsx)(tC,{className:s.lock})]})]})};var Np=x(F());function Vn(e){let{showMidSentenceSuggestions:t,showSuggestionsBeforePattern:n,showSuggestionsAfterPattern:r}=e.settings,{text:o,selection:i}=e.input;return i.start!==i.end?!1:i.end>=o.length?!0:t?n&&new RegExp(n).test(o.substring(i.end))||r&&new RegExp(r).test(o.substring(0,i.end))?!0:n===!1&&r===!1:!1}var YM={showTabHint:!1,inputHasFocus:!1,overlayCollapsed:!1,openOverlayWhenTyping:!1,overlayCollapsedUserOverwrite:!1},Ap=({ui:e})=>e.overlayCollapsed,sC=te({name:"ui",initialState:YM,reducers:{setShowTabHint(e,t){e.showTabHint=t.payload},setInputFocus(e,t){e.overlayCollapsedUserOverwrite!==!0&&(t.payload===!0&&(e.overlayCollapsed=!1),e.inputHasFocus=t.payload)},setOverlayCollapsed(e,t){t.payload.collapse===!1&&(e.openOverlayWhenTyping=!1),!(t.payload.skipWhenInputFocus&&e.inputHasFocus)&&(e.overlayCollapsed=t.payload.collapse)},setOpenOverlayWhenTyping(e,t){e.openOverlayWhenTyping=t.payload},setOverlayCollapsedUserOverwrite(e,t){e.overlayCollapsedUserOverwrite=t.payload,e.overlayCollapsed=t.payload}}}),{setShowTabHint:nu,setInputFocus:Lp,setOverlayCollapsed:so,setOpenOverlayWhenTyping:aC,setOverlayCollapsedUserOverwrite:lC}=sC.actions,uC=sC.reducer;var Ip=x(F());var Ns=x(F());var cC=x(F());function dC(e,t,n){(0,cC.useEffect)(()=>{let r=e.current;return r?(r.addEventListener(t,n),()=>{r.removeEventListener(t,n)}):()=>{}},[e,t,n])}var pC={root:"dd-1MBCO",actions:"dd--x4cy",badge:"dd-4Fpkz",formattedText:"dd-EzvTB"};var si=x(C()),ZM=["search","personal-collection-search","search-autocomplete"];function JM(e,t,n,r={}){var i;let o="";return ZM.includes(t)?o=PE(ry(e,n,{stripAgentPart:!0}),(i=r.searchKeywords)!=null?i:[n]):o=ry(e,n,r),r.placeholders===!0&&(o=AE(o)),o}var e2=()=>{},t2=({selected:e,suggestion:t})=>{let n=H("inlineSuggestions"),r=_(hs),o=H("enableSuggestionFeedback"),i=_(c=>c.input.text),s=G(),a=I("TextSuggestion",pC),l=(0,Ns.useRef)(null);(0,Ns.useEffect)(()=>{let c=setTimeout(()=>{s(y1({text:t.text,suggestion:t}))},500);return()=>{clearTimeout(c)}},[t]),dC(l,"click",()=>{s(mn({suggestion:t,text:t.text,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"}))});let u=(0,Ns.useMemo)(()=>JM(t.text,t.source,r,{stripAgentPart:n,placeholders:!0,searchKeywords:t.searchKeywords}),[n,t.text,t.source,r,t.searchKeywords]);return t.source==="gpt"&&!n?null:(0,si.jsxs)("div",{className:a.root,children:[(0,si.jsx)(ie,{ref:l,as:"button","data-testid":"suggestions-overlay-item",selected:e,onClick:e2,children:(0,si.jsx)(ws,{containerTagName:"div",noWrap:!1,tagName:"span",className:a.formattedText,content:u})}),o&&(0,si.jsx)("div",{className:a.actions,children:(0,si.jsx)(Cp,{source:"overlay",context:i,suggestion:t})})]})},fC=t2;var Hy=x(C()),n2=({suggestions:e,selectedIndex:t,reverse:n})=>{let r=(0,Ip.useMemo)(()=>{let o=e.map((i,s)=>(0,Hy.jsx)(fC,{index:s,selected:s===t,suggestion:i},`${i.text}-${i.source}`));return n?o.reverse():o},[e,t,n]);return(0,Hy.jsx)(Ip.Fragment,{children:r})},Op=n2;var mC={root:"dd-PfvRI",paper:"dd-HYlyY"};var ru=x(C()),r2=({textSuggestions:e,selectedIndex:t})=>{let n=(0,Np.useRef)(null),r=I("InlineSuggestionsOverlay",mC),o=_(Vn),i=G(),s=_(gt),a=_(gs),l=_(Ap),u=H("showTextSuggestions");return io(()=>{setTimeout(()=>{i(so({collapse:!0,skipWhenInputFocus:!0}))})}),(0,Np.useEffect)(()=>{let c=n.current;if(!c||!c.parentElement)return;c.parentElement.style.left="0px";let p=c.getBoundingClientRect();c.parentElement.style.left=`${Math.min(window.innerWidth-4-p.right,0)}px`}),l||!o||!u||e.length===0||s!==!0||a===!1?null:(0,ru.jsx)("div",{className:r.root,"data-variant":"inline",children:(0,ru.jsx)("div",{ref:n,className:r.paper,children:(0,ru.jsx)(Rt,{children:(0,ru.jsx)(Op,{suggestions:e,selectedIndex:t})})})})},o2=({input:e})=>({selectedIndex:e.selectedSuggestionIndex,textSuggestions:e.textSuggestions}),gC=Do(o2)(r2);var ou=x(C()),i2=({children:e})=>{let n=H("locale").replace("-","");return(0,ou.jsx)(Bh.Provider,{value:n,children:e})},s2=({store:e,customStyles:t={},children:n})=>(0,ou.jsx)(bh,{store:e,children:(0,ou.jsx)(i2,{children:(0,ou.jsx)(Zs.Provider,{value:t,children:n})})}),ai=s2;var _p=x(de()),Ms=x(F());var hC=x(F());function yC(e,t){let[n,r]=(0,hC.useState)(()=>{if(typeof window=="undefined")return t;try{let i=window.localStorage.getItem(e);return i?JSON.parse(i):t}catch(i){return j.error(i),t}});return[n,i=>{try{let s=i instanceof Function?i(n):i;r(s),typeof window!="undefined"&&window.localStorage.setItem(e,JSON.stringify(s))}catch(s){j.error(s)}}]}var vC=()=>/Mac/i.test(navigator.platform);var xC=x(de()),yr=x(F());var Uy={};dt(Uy,{enUS:()=>a2,nlNL:()=>l2});var a2={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"}]}]},l2={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 SC={root:"dd-uTPjX",anchor:"dd-C8lsZ",anchorButton:"dd-IoSx9"};var ao=x(C()),jy=(e,t,n)=>r=>(0,ao.jsx)("button",{className:e.anchorButton,type:"button",value:t,onClick:n,children:r},t),u2=({className:e,loginUrl:t,isEmbedded:n,onSnooze:r,onLogIn:o})=>{let i=q(Uy),s=Nt(),a=I("Login",SC),l=H("productName"),u=(0,yr.useCallback)(m=>{m.preventDefault(),r&&r(parseInt(m.target.value,10))},[]),c=(0,yr.useCallback)(m=>{m.preventDefault(),s.send(Ss,!0)},[t]),p=(0,yr.useMemo)(()=>m=>(0,ao.jsx)("a",{onClick:y=>{y.preventDefault(),o()},href:t,className:a.anchor,target:"_blank",rel:"noreferrer",children:m},"login"),[t]),d=(0,yr.useCallback)(m=>(0,ao.jsx)("button",{type:"button",className:a.anchorButton,onClick:c,children:m},"prompt"),[c]),{min:f,hour:h,day:v}=(0,yr.useMemo)(()=>({min:jy(a,60*10,u),hour:jy(a,60*60,u),day:jy(a,60*60*12,u)}),[]);return(0,ao.jsxs)("div",{className:(0,xC.default)(e,a.root),children:[i("loginPlease",{login:n?d:p,productName:l}),r&&(0,ao.jsxs)(yr.Fragment,{children:[(0,ao.jsx)("br",{}),i("snooze",{min:f,hour:h,day:v})]})]})},Mp=u2;var wC={root:"dd-DoQhb",text:"dd-Jwnev"};var iu=x(C()),c2=({title:e})=>{let t=I("SearchTrigger",wC),n=G();return(0,iu.jsxs)("button",{type:"button",className:t.root,onClick:()=>n(en(!0)),children:[(0,iu.jsx)(Es,{}),(0,iu.jsx)("span",{className:t.text,children:e})]})},bC=c2;var By={};dt(By,{enUS:()=>d2,nlNL:()=>p2});var d2={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"}]},p2={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 EC={root:"dd-oa7Vc",isInline:"dd-bwk31",toggleButton:"dd-MSB8Z",toggleButtonWrapper:"dd-ZkCzT",toggleButtonWrapperHidden:"dd-Sq66c",isCollapsed:"dd-vkrPk",collapsible:"dd-CWQJe",hints:"dd-IOoo3",hintsHidden:"dd-psVuT",triggers:"dd-toIoo",triggersRight:"dd-mc4l2"};var Ce=x(C()),f2=({textSuggestions:e,selectedIndex:t,onLogIn:n})=>{let r=I("SuggestionsOverlay",EC),o=q(By),i=_(Vn),s=h1(),a=G(),l=(0,Ms.useRef)(null),u=H("searchTriggerKey"),c=H("productName"),p=_(Ap),d=_(gt),f=_(gs),[h,v]=(0,Ms.useState)(null),m=H("showSearch"),g=H("showTextSuggestions"),y=H("adminUrl"),S=H("isEmbedded"),[w,k]=yC("dd-snooze-until-ms",0),E=p||w>Date.now(),R=e.filter(Y=>Y.source!=="gpt").length,A=()=>{E&&k(0),a(lC(!E))},M=Y=>{let z=Date.now()+Y*1e3;k(z),j.info(`Snooze until: ${new Date(z)}`),a(so({collapse:!0}))};return(0,Ms.useEffect)(()=>{R===0&&v(null)},[e,R]),io(()=>{a(so({collapse:!0,skipWhenInputFocus:!0}))}),d===null||f===!1?null:d===!1?(0,Ce.jsxs)("div",{ref:l,className:(0,_p.default)(r.root,{[r.isCollapsed]:E}),children:[!E&&(0,Ce.jsxs)("div",{className:r.triggers,children:[(0,Ce.jsx)("div",{style:{flex:1}}),(0,Ce.jsx)("div",{className:r.triggersRight,children:(0,Ce.jsx)(vo,{className:r.toggleButton,title:o("collapse"),onClick:A,isCollapsed:!1})})]}),(0,Ce.jsx)("div",{className:r.toggleButtonWrapper,children:(0,Ce.jsx)(vo,{className:r.toggleButton,title:o("open",{productName:c}),onClick:A,isCollapsed:!0})}),(0,Ce.jsx)("div",{className:r.collapsible,children:(0,Ce.jsx)(Mp,{loginUrl:y,isEmbedded:S,onLogIn:n,onSnooze:M})})]}):!s||!i?null:(0,Ce.jsxs)("div",{ref:l,className:(0,_p.default)(r.root,{[r.isCollapsed]:E}),children:[!E&&(0,Ce.jsxs)("div",{className:r.triggers,children:[(0,Ce.jsx)("div",{style:{flex:1},children:m&&(0,Ce.jsx)("div",{style:{display:"inline-block"},onFocus:()=>{},onMouseOver:()=>v(o(vC()?"searchHintMac":"searchHintWindows",{searchTriggerKey:u.toUpperCase()})),onMouseLeave:()=>v(null),children:(0,Ce.jsx)(bC,{title:o("search")})})}),(0,Ce.jsxs)("div",{className:r.triggersRight,onFocus:()=>{},children:[(0,Ce.jsx)("div",{className:(0,_p.default)(!h&&r.hintsHidden,r.hints),children:h}),(0,Ce.jsx)(vo,{className:r.toggleButton,title:o("collapse"),onClick:A,isCollapsed:!1})]})]}),(0,Ce.jsx)("div",{className:r.toggleButtonWrapper,children:(0,Ce.jsx)(vo,{className:r.toggleButton,title:o("open",{productName:c}),onClick:A,isCollapsed:!0})}),R>0&&g&&(0,Ce.jsx)("div",{className:r.collapsible,onFocus:()=>{},children:(0,Ce.jsx)(Rt,{children:(0,Ce.jsx)(Op,{suggestions:e,selectedIndex:t,reverse:!0})})})]})},m2=({input:e})=>({selectedIndex:e.selectedSuggestionIndex,textSuggestions:e.textSuggestions}),TC=Do(m2)(f2);var qp=x(de());var xr=x(F());var _s=x(F());function Dp(e){return e.contentEditable==="true"}function g2(e){let t=0,n=0,r=window.getSelection();if(r.rangeCount!==0){let o=r.getRangeAt(0),i=o.cloneRange();i.selectNodeContents(e),i.setEnd(o.endContainer,o.endOffset),n=i.toString().length,i.selectNodeContents(e),i.setEnd(o.startContainer,o.startOffset),t=i.toString().length}return{selectionStart:t,selectionEnd:n}}function CC(e){let{selectionStart:t,selectionEnd:n}=Dp(e)?g2(e):e;return[t,n]}function kC(e){let[,t]=(0,_s.useState)(),n=(0,_s.useRef)(null);return n.current=CC(e),(0,_s.useEffect)(()=>{let r=()=>{var a;let[o,i]=(a=n.current)!=null?a:[],s=CC(e);(!s||o!==s[0]||i!==s[1])&&(n.current=s,t({}))};return e.addEventListener("keyup",r),e.addEventListener("click",r),e.addEventListener("focus",r),document.addEventListener("selectionchange",r),()=>{e.removeEventListener("keyup",r),e.removeEventListener("click",r),e.removeEventListener("focus",r),document.removeEventListener("selectionchange",r)}},[e]),n.current}function RC(e,t){if(!t)return;let n=e,{value:r}=n,[o,i]=t,s=r.match(Mu);if(!s||s.length===0)return;let a=0;s.find(l=>{let u=r.indexOf(l,a);return o>u&&i<u+l.length?(n.selectionStart=u,n.selectionEnd=u+l.length,!0):(a=u+l.length,!1)})}var PC=x(F()),h2=["div","span","mark","strong","b","i","u","em"];function Vy(e,t,n=0){var i;let r=e[e.length-1],o=typeof r=="object"&&r!==null?(i=r.props)==null?void 0:i.tagName:void 0;if(o==="br")return e.pop(),[...e,...t,r];if(h2.includes(o)){let s=Array.isArray(r.props.children)?r.props.children:[r.props.children];return[...e.slice(0,e.length-1),(0,PC.cloneElement)(r,{children:Vy(s,t,n+1)})]}return[...e,...t]}function li(e){return e.tagName.toLowerCase()==="textarea"}var AC={root:"dd-7-cgW",container:"dd-PsRQ8",agentText:"dd-qnW-V",tabText:"dd-cUHUr",hint:"dd-v7fSg",matchSelection:"dd-8cr8y",focus:"dd-3tr9l",resetIndent:"dd-TvQfZ",matchKeyword:"dd-oJkRD",matchPlaceholder:"dd-QvNoo",hover:"dd--wi0R",hintText:"dd-7gQQh",popover:"dd-xbRu-",popoverRoot:"dd-rA2x8",popoverContentContainer:"dd-JHICl",popoverContent:"dd--mfkC",selectionOptions:"dd-p52wn",selectionOptionsIsHidden:"dd-sSTDp",selectionOptionsButton:"dd-Q6kRY",caret:"dd-jIhc8",popoverSuggestionsRoot:"dd-iFDbL",suggestionsOverlayInputStyles:"dd-zzENA"};var MC=x(de());var Bp=x(F());var Ds=x(F());function LC(e,t){let n;return[(...r)=>{window.cancelAnimationFrame(n);let o=t?t(...r):r;n=window.requestAnimationFrame(()=>{e(...o)})},()=>window.cancelAnimationFrame(n)]}function Fp(e){let t=(0,Ds.useRef)(null),[n,r]=(0,Ds.useState)(!1);return(0,Ds.useEffect)(()=>{var c;let o=!1,i=parseFloat((c=window.getComputedStyle(document.body).zoom)!=null?c:"1"),[s,a]=LC((p,d)=>{let f=t.current;if(!f)return;let h=p/i,v=d/i,m=f.getBoundingClientRect(),g=h>m.x&&h<m.x+m.width&&v>m.y&&v<m.y+m.height;g&&!o?(o=!0,r(!0)):!g&&o&&(o=!1,r(!1))},({clientX:p,clientY:d})=>[p,d]),[l,u]=LC(()=>{o=!1,r(!1)});return e.addEventListener("mousemove",s),e.addEventListener("mouseleave",l),()=>{a(),u(),e.removeEventListener("mousemove",s),e.removeEventListener("mouseleave",l)}},[t]),[t,n]}function IC(e){return e.replace(/[.*+^${}()|[\]\\]/g,"\\$&")}function zp(e){return t=>{e.forEach(n=>{typeof n=="function"?n(t):n!=null&&(n.current=t)})}}function OC(e){return e!=null}var NC=x(de()),Hp=x(F());var vr={root:"dd-7-cgW",container:"dd-PsRQ8",agentText:"dd-qnW-V",tabText:"dd-cUHUr",hint:"dd-v7fSg",matchSelection:"dd-8cr8y",focus:"dd-3tr9l",resetIndent:"dd-TvQfZ",matchKeyword:"dd-oJkRD",matchPlaceholder:"dd-QvNoo",hover:"dd--wi0R",hintText:"dd-7gQQh",popover:"dd-xbRu-",popoverRoot:"dd-rA2x8",popoverContentContainer:"dd-JHICl",popoverContent:"dd--mfkC",selectionOptions:"dd-p52wn",selectionOptionsIsHidden:"dd-sSTDp",selectionOptionsButton:"dd-Q6kRY",caret:"dd-jIhc8",popoverSuggestionsRoot:"dd-iFDbL",suggestionsOverlayInputStyles:"dd-zzENA"};var $y=x(C()),Up=(0,Hp.forwardRef)((o,r)=>{var i=o,{className:e,children:t}=i,n=Z(i,["className","children"]);let s=(0,Hp.useRef)(null),a=I("TabCompletion",vr);return(0,$y.jsx)("div",L(T({ref:zp([s,r]),className:(0,NC.default)(e,a.popoverContentContainer)},n),{children:(0,$y.jsx)("div",{className:a.popoverContent,children:t})}))});var lo=x(C()),y2=e=>t=>{let n=by(t);return"top"in n&&(n.width=e.width-(t.left-e.left)-10),n},v2=({inputElement:e,boundaryRef:t,inputStyle:n,children:r,suggestion:o})=>{let i=I("TabCompletion",vr),s=Sp(),a=(0,Bp.useMemo)(()=>y2(e.getBoundingClientRect()),[e]),[l,u]=Fp(e);return(0,Bp.useEffect)(()=>{u?s.open():s.close()},[u]),(0,lo.jsxs)("span",{children:[(0,lo.jsx)("mark",{ref:zp([l,s.triggerRef]),className:(0,MC.default)(i.matchKeyword,{[i.hover]:u}),"aria-haspopup":"dialog","aria-expanded":s.opened?"true":"false",children:r}),s.opened&&(0,lo.jsx)(As,{className:i.popover,triggerRef:s.triggerRef,boundaryRef:t,position:"below",align:"start",toStyle:a,children:(0,lo.jsx)(Up,{style:n,children:(0,lo.jsx)("div",{className:i.hintText,children:o})})})]})},jp=class extends dr{constructor(){super(...arguments);this.keywordMatches=[];this.preparedKeywordMatches=[];this.usedKeywordMatches=new Set}onBeforeParse(n,r){return r.keywordMatches&&r.keywordMatches!==this.keywordMatches&&(this.preparedKeywordMatches=r.keywordMatches.map(o=>L(T({},o),{keywordRegex:new RegExp(`\\b${IC(o.keyword)}\\b`,"i")})),this.keywordMatches=r.keywordMatches),this.usedKeywordMatches.clear(),n}match(n){let r=this.preparedKeywordMatches.map(i=>{if(this.usedKeywordMatches.has(i))return null;let s=n.match(i.keywordRegex);if(!s)return null;let a=n.charAt(s.index-1),l=n.charAt(s.index+i.keyword.length);return a==="{"&&l==="}"?null:{index:s.index,length:s[0].length,match:s[0],matchString:s[0],suggestion:i.suggestion,preparedKeywordMatch:i,valid:!0}}).filter(OC);if(r.length===0)return null;let o=r.reduce((i,s)=>s.index<i.index?s:i);return this.usedKeywordMatches.add(o.preparedKeywordMatch),o}replaceWith(n,r){return(0,lo.jsx)(v2,{inputElement:r.inputElement,suggestion:r.suggestion,inputStyle:r.inputStyle,boundaryRef:r.boundaryRef,children:n},`keyword_${r.matchString}_${r.key}`)}asTag(){return"mark"}};var _C=x(de());var Wy=x(C()),S2=({inputElement:e,children:t})=>{let n=I("TabCompletion",vr),[r,o]=Fp(e);return(0,Wy.jsx)("mark",{ref:r,className:(0,_C.default)(n.matchPlaceholder,{[n.hover]:o}),children:t})},Vp=class extends dr{match(t){let n=t.match(/(((\$!\{)|(\{))[a-zA-Z0-9_.]+\}(?!\}))/);return n?{index:n.index,length:n[0].length,match:n[0],matchString:n[0],valid:!0}:null}replaceWith(t,n){return(0,Wy.jsx)(S2,{inputElement:n.inputElement,children:t},`placeholder_${n.matchString}_${n.key}`)}asTag(){return"mark"}};var Wp=x(de());var bt=x(F());var Ky=x(C()),DC=()=>(0,Ky.jsx)("svg",{width:"1.3em",height:"1.3em",focusable:"false","aria-hidden":"true",viewBox:"0 0 24 24","data-testid":"InsertLinkIcon",tabIndex:-1,children:(0,Ky.jsx)("path",{fill:"currentColor",d:"M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76 0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71 0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71 0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76 0 5-2.24 5-5s-2.24-5-5-5z"})});var $n=x(F());var zC=x(qh());var FC={root:"dd-ky-Bv",content:"dd-kV5e1"};function $p(e,t,n){var o;let r=((o=e.imageSizes)==null?void 0:o[t])||e.image||n;if(!r)return null;try{return new URL(r).toString()}catch(i){return null}}function qy(e){return e.replace("https://www.","").replace("https://","")}var sn=x(C()),x2=3,w2=e=>({image:e.image||"",text:e.text,id:e.id,title:e.title}),b2=({onSelectLink:e,onDismiss:t,placeholder:n,visitUrlText:r,linkCount:o=x2})=>{let i=I("LinkSearch",FC),[s,a]=(0,$n.useState)(""),l=G(),u=_(WT("url")),c=_(z1("URL")),p=(0,$n.useMemo)(()=>c.map(w2),[c]),[d,f]=(0,$n.useState)(p.length-1),h=H("fallbackImage"),v=S=>{let w=S.target;a(w.value)},m=(S,w)=>{S.stopPropagation(),S.preventDefault(),window.open(w,"_blank")},g=S=>{var E;let w=d-1<0?p.length-1:d-1,k=d+1===p.length?0:d+1;S.code==="Escape"&&(a(""),t()),S.code==="ArrowUp"&&f(w),S.code==="ArrowDown"&&f(k),S.code==="Enter"&&e(((E=p[d])==null?void 0:E.text)||s)},y=(0,$n.useCallback)((0,zC.default)(S=>{l(Ho({query:S,type:"URL",tags:["link-search"]}))},300),[]);return(0,$n.useEffect)(()=>{s&&y(s)},[s]),(0,$n.useEffect)(()=>()=>{l(Bd())},[]),(0,sn.jsxs)("div",{className:i.root,children:[(0,sn.jsx)(Rt,{withDivider:!0,children:(s?p:u).slice(0,o).map((S,w)=>(0,sn.jsx)(ie,{selected:d===w,onClick:()=>e(S.text),"data-testid":"linksearch-suggestion",children:(0,sn.jsxs)(ve,{children:[(0,sn.jsx)(ve.Image,{src:$p(S,"small",h||void 0),title:S.title||S.text}),(0,sn.jsxs)(ve.Content,{className:i.content,cropText:!0,children:[(0,sn.jsx)(ve.Title,{children:S.title||qy(S.text)}),S.title&&qy(S.text)]}),(0,sn.jsx)(ie.Actions,{children:(0,sn.jsx)(ie.ActionButton,{label:r,onClick:k=>m(k,S.text)})})]})},S.text))}),(0,sn.jsx)(El,{value:s,onChange:v,autoFocus:!0,placeholder:n,onKeyUp:g})]})},HC=b2;var Gy={};dt(Gy,{enUS:()=>E2,nlNL:()=>T2});var E2={insertLink:[{type:0,value:"Insert link"}],linkInputPlaceholder:[{type:0,value:"Search, type or paste link"}],visitUrl:[{type:0,value:"Visit"}]},T2={insertLink:[{type:0,value:"Voeg link toe"}],linkInputPlaceholder:[{type:0,value:"Zoek, typ of plak link"}],visitUrl:[{type:0,value:"Bekijk"}]};var wt=x(C()),C2=(0,bt.forwardRef)((e,t)=>{let n=I("TabCompletion",vr);return(0,wt.jsx)("mark",{ref:t,className:(0,Wp.default)(n.matchSelection)},"selection-start")}),k2=({startRef:e,boundaryRef:t,inputStyle:n,inputElement:r,children:o})=>{let i=q(Gy),s=I("TabCompletion",vr),a=(0,bt.useRef)(null),l=(0,bt.useRef)(null),[u,c]=(0,bt.useState)(null),p=G(),d=Sp(document.activeElement===r),[f]=(0,bt.useState)(()=>document.createRange());d.triggerRef.current=f,(0,bt.useEffect)(()=>()=>f.detach(),[]),(0,bt.useEffect)(()=>{let v=e.current,m=a.current;!v||!m||(f.setStart(v,0),f.setEnd(m,0))},[e.current,a.current]),io(()=>{d.close()});let h=(0,bt.useCallback)(v=>{let m=f.toString(),g=/^http(s?):\/\//.test(v)?v:`https://${v}`;p(Dd({text:`[${m}](${g})`,replace:"selection"}))},[]);return(0,wt.jsxs)("span",{children:[(0,wt.jsx)("mark",{ref:a,className:(0,Wp.default)(s.matchSelection),"aria-haspopup":"dialog","aria-expanded":d.opened?"true":"false",children:o}),d.opened&&(0,wt.jsx)(As,{className:s.popoverRoot,triggerRef:d.triggerRef,boundaryRef:t,position:"above",align:"start",children:(0,wt.jsxs)(Up,{style:n,ref:l,children:[(0,wt.jsx)("div",{className:(0,Wp.default)(s.selectionOptions,{[s.selectionOptionsIsHidden]:u!==null}),children:(0,wt.jsxs)("button",{type:"button",tabIndex:u===null?-1:void 0,className:s.selectionOptionsButton,onClick:()=>c("insertLink"),children:[(0,wt.jsx)(DC,{}),(0,wt.jsx)("span",{children:"\xA0"}),(0,wt.jsx)("span",{children:i("insertLink")})]})}),u==="insertLink"&&(0,wt.jsx)(HC,{placeholder:i("linkInputPlaceholder"),visitUrlText:i("visitUrl"),onSelectLink:h,onDismiss:()=>{c(null),d.close()}})]})})]},"selection-end")},Kp=class extends dr{constructor(){super(...arguments);this.charCount=0;this.foundIndex=0;this.startRef=null}onBeforeParse(n,r){return this.props=r,this.charCount=0,this.startRef=(0,bt.createRef)(),this.foundIndex=0,n}match(n){if(!this.props||this.props.selection===null||this.foundIndex===2)return null;let[r,o]=this.props.selection;if(r===o)return null;let i=this.foundIndex===0?r:o,s=i>=this.charCount&&i<=this.charCount+n.length?{index:i-this.charCount,length:0,match:"",valid:!0}:null;s&&this.foundIndex++;let a=this.foundIndex===1;return s&&a?this.charCount+=i-this.charCount:this.charCount+=n.length,s?T({isStart:a},s):null}replaceWith(n,r){return r.isStart?(0,wt.jsx)(C2,{ref:this.startRef}):(0,wt.jsx)(k2,{inputElement:r.inputElement,startRef:this.startRef,boundaryRef:r.boundaryRef,inputStyle:r.inputStyle})}asTag(){return"mark"}};var Sr=x(C()),R2=({enabled:e,content:t,tabText:n,showTabHint:r,showTabCompletion:o,showStyleSuggestions:i,keywordMatches:s,inputElement:a,source:l})=>{let u=I("TabCompletion",AC),c=H("insertLink"),p=H("showMidSentenceSuggestions"),d=H("inlineSuggestions"),f=kC(a),h=(0,xr.useRef)(null),v=_(gt);(0,xr.useEffect)(()=>{li(a)&&f&&RC(a,f)},[f]);let m=(0,xr.useCallback)(S=>{if(!o||!n)return S;let w=[(0,Sr.jsx)("span",{className:u.resetIndent,children:"\u200B"},"u200B"),(0,Sr.jsx)("span",{"data-testid":"tab-completion",className:(0,qp.default)(u.tabText,u.resetIndent),"data-source":l,children:n},"tabText")];return r&&w.push((0,Sr.jsx)("span",{className:(0,qp.default)(u.hint,u.resetIndent),children:(0,Sr.jsx)(Iu,{keyCode:"tab"},"tabHint")})),Vy(S,w)},[o,n,r]),g=(0,xr.useMemo)(()=>{let S=[];return c&&S.push(new Kp("selection")),S.push(new Vp("placeholders")),i&&S.push(new jp("keywords")),S},[d,c,i]),y=(0,xr.useMemo)(()=>{let S=window.getComputedStyle(a);return{"--dd-color":S.color,"--dd-font-size":S.fontSize,"--dd-font-family":S.fontFamily,"--dd-font-variant":S.fontVariant}},[]);return!e||!v?null:(0,Sr.jsxs)("div",{ref:S=>{S!=null&&S.parentElement&&(h.current=S==null?void 0:S.parentElement)},className:u.root,style:y,children:[(0,Sr.jsx)(ws,{tagName:"span",containerTagName:"div",className:(0,qp.default)(u.container,u.agentText),disableLineBreaks:li(a),content:t||"\u200B",onAfterParse:m,matchers:g,selection:f,keywordMatches:s,inputElement:a,inputStyle:y,boundaryRef:h,inlineSuggestionsOnlyAtEnd:!p}),(0,Sr.jsx)("br",{})]})},P2=e=>{var m,g,y;let{input:t,ui:n,settings:r,styleSuggestions:o,conversation:i}=e,s=ys({input:t}),a=(s==null?void 0:s.text)||"",l=(s==null?void 0:s.source)||"",u=(m=t.html)!=null?m:bs(t.text),c=a.indexOf(t.text)===0?a.slice(t.text.length):"",{showTabHint:p}=n,{isSupported:d}=i,{showTabCompletion:f,visible:h,showStyleSuggestions:v}=r;return{showTabHint:p,showStyleSuggestions:v,showTabCompletion:f&&Vn(e),content:u,tabText:c,source:l,keywordMatches:(y=(g=o.list)==null?void 0:g.keywordMatches)!=null?y:[],enabled:h&&d!==!1}},UC=Do(P2)(R2);var pk=x(de()),Hs=x(F());var A2={token:null,interval:null},Qy=Q("passwordlessToken/getTemporaryPasswordlessToken",(e,t)=>P(void 0,null,function*(){let{deepdeskAPI:n}=t.extra;return{token:yield n.requestPasswordlessToken()}})),Yy=Q("passwordlessToken/pollPasswordlessToken",(e={},t)=>{let{interval:n=1e3*60*10}=e,{dispatch:r}=t;return r(Qy()),setInterval(()=>r(Qy()),n)}),jC=te({name:"passwordlessToken",initialState:A2,reducers:{stopPollPasswordlessToken(e){e.interval&&clearInterval(e.interval),e.interval=null}},extraReducers:e=>{e.addCase(Qy.fulfilled,(t,n)=>{t.token=n.payload.token}),e.addCase(Yy.fulfilled,(t,n)=>{t.interval=n.payload})}}),{stopPollPasswordlessToken:BC}=jC.actions,VC=jC.reducer;function L2(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return t}var $C=fn([dE],e=>e.map(n=>({text:n.response,title:n.name,callToAction:n.callToAction,isLoading:n.isLoading,specialType:n.specialType,rule:{id:L2(n.code),label:n.code,name:n.name,description:n.name}})));var Gp=x(F());var Zy=x(de());var Xy=x(C()),su=()=>(0,Xy.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",children:(0,Xy.jsx)("path",{d:"M502.6 70.63l-61.25-61.25C435.4 3.371 427.2 0 418.7 0H255.1c-35.35 0-64 28.66-64 64l.0195 256C192 355.4 220.7 384 256 384h192c35.2 0 64-28.8 64-64V93.25C512 84.77 508.6 76.63 502.6 70.63zM464 320c0 8.836-7.164 16-16 16H255.1c-8.838 0-16-7.164-16-16L239.1 64.13c0-8.836 7.164-16 16-16h128L384 96c0 17.67 14.33 32 32 32h47.1V320zM272 448c0 8.836-7.164 16-16 16H63.1c-8.838 0-16-7.164-16-16L47.98 192.1c0-8.836 7.164-16 16-16H160V128H63.99c-35.35 0-64 28.65-64 64l.0098 256C.002 483.3 28.66 512 64 512h192c35.2 0 64-28.8 64-64v-32h-47.1L272 448z"})});var WC={root:"dd-WcEru",entity:"dd-LfP8y",entityText:"dd-L-v0f",iconWrapper:"dd-9Deh1",icon:"dd-tM7E2",iconClicked:"dd-EEdDL"};var Wn=x(C()),I2=({entities:e})=>{let t=I("EntitiesWidgetList",WC),[n,r]=(0,Gp.useState)(void 0),o=G(),i=()=>{r(void 0)},s=a=>{e&&(r(e.indexOf(a)),Un(a.text),o(Jt({name:"entity copied",data:{entity:a,type:"copy"}})))};return(0,Gp.useEffect)(()=>{let a=setTimeout(i,500);return()=>{clearTimeout(a)}},[n]),!e||e.length===0?null:(0,Wn.jsx)("div",{className:t.root,"data-testid":"widget-entities-list",children:e.map((a,l)=>(0,Wn.jsxs)("button",{title:a.text,className:t.entity,type:"button",onClick:()=>s(a),children:[(0,Wn.jsx)("span",{className:t.entityText,children:a.text}),(0,Wn.jsxs)("span",{className:t.iconWrapper,children:[(0,Wn.jsx)("span",{className:(0,Zy.default)(t.icon),children:(0,Wn.jsx)(su,{})}),(0,Wn.jsx)("span",{className:(0,Zy.default)(t.icon,n===l&&t.iconClicked),children:(0,Wn.jsx)(su,{})})]})]},a.text))})},KC=I2;var Jy=x(C()),qC=()=>(0,Jy.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,Jy.jsx)("path",{d:"M17 13.5v6H5v-12h6m3-3h6v6m0-6-9 9",stroke:"currentColor",strokeWidth:"1.5",fill:"none",fillRule:"evenodd",strokeLinecap:"round",strokeLinejoin:"round"})});var ev=x(C()),GC=()=>(0,ev.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:(0,ev.jsx)("path",{d:"M543-340q16.595 0 28.798-12.202Q584-364.405 584-381t-12.202-28.798Q559.595-422 543-422t-28.798 12.202Q502-397.595 502-381t12.202 28.798Q526.405-340 543-340Zm-25-126h47q2-29 8.5-43t32.5-39q27-26 37.5-45.395Q654-612.79 654-639q0-45.882-31.5-74.941Q591-743 540-743q-38 0-68 20.5T428-665l45 19q11-25 27.5-38t39.5-13q29.778 0 48.389 17Q607-663 607-637q0 20-9 35t-32 32q-32 29-40 46.5t-8 57.5ZM260-200q-24 0-42-18t-18-42v-560q0-24 18-42t42-18h560q24 0 42 18t18 42v560q0 24-18 42t-42 18H260Zm0-60h560v-560H260v560ZM140-80q-24 0-42-18t-18-42v-620h60v620h620v60H140Zm120-740v560-560Z"})});var tv=x(C()),QC=()=>(0,tv.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:(0,tv.jsx)("path",{d:"M319-250h322v-60H319v60Zm0-170h322v-60H319v60ZM220-80q-24 0-42-18t-18-42v-680q0-24 18-42t42-18h361l219 219v521q0 24-18 42t-42 18H220Zm331-554v-186H220v680h520v-494H551ZM220-820v186-186 680-680Z"})});var ZC=x(F());var YC={loadingBar:"dd-6as-V",placeHolderShimmer:"dd-TFYmA"};var XC=x(C()),O2=({width:e})=>{let t=I("LoadingProgressBar",YC);return(0,XC.jsx)("div",{className:t.loadingBar,style:{width:e}})},Qp=O2;var wr=x(C()),Yp=({title:e})=>{let t=(0,ZC.useRef)(null);return x0(t),(0,wr.jsx)(ie,{ref:t,children:(0,wr.jsx)(ve,{children:(0,wr.jsxs)(ve.Content,{children:[(0,wr.jsx)(ve.Title,{children:e}),(0,wr.jsx)(Qp,{width:"60%"}),(0,wr.jsx)(Qp,{width:"90%"}),(0,wr.jsx)(Qp,{width:"50%"})]})})})};var au={};dt(au,{enUS:()=>N2,nlNL:()=>M2});var N2={useCue:[{type:0,value:"Add to message"}],__summarizerAssistant__:[{type:0,value:"Summary"}],copyCue:[{type:0,value:"Copy"}],removeCue:[{type:0,value:"Close"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}]},M2={useCue:[{type:0,value:"Voeg toe aan bericht"}],__summarizerAssistant__:[{type:0,value:"Samenvatting"}],copyCue:[{type:0,value:"Kopi\xEBren"}],removeCue:[{type:0,value:"Sluiten"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}]};var ui=x(F());var nv={title:"dd-YBHrC",fadeup:"dd-cRM0K",fadedown:"dd-7D4Pq",selected:"dd-bueui",actions:"dd-9Iqn9",thumbsUp:"dd-6QwVx",thumbsDown:"dd-d3E8l",form:"dd-sPNU2",formInput:"dd-F3E4I",formSubmit:"dd-vw5S0",actionButton:"dd-cCWyJ",editableCue:"dd-nWSD-",inputSpace:"dd-DGYB1"};var lt=x(C()),_2=500,D2=100,F2=({content:e,onChange:t,onCopy:n})=>{let r=(0,ui.useRef)(null),o=I("WidgetCue",nv);return(0,ui.useEffect)(()=>{let i=r.current;if(!i)return;i.style.setProperty("height","0px");let s=Math.min(Math.max(i.scrollHeight,D2),_2);i.style.setProperty("height",`${s}px`)},[e]),(0,lt.jsx)("textarea",{ref:r,className:o.editableCue,onCopy:n,onChange:t,value:e})},z2=({cue:e,onCallToAction:t,onRemove:n,onCopy:r,onUse:o})=>{var v;let i=I("WidgetCue",nv),s=q(au),a=oo(),l=H("hasKeyboardInput"),[u,c]=(0,ui.useState)(e.text),p=()=>{t&&t(e),n(e)},d=m=>{r&&r(m,e)},f=m=>{o&&o(m,e)},h=m=>{m.preventDefault(),m.stopPropagation(),n(e)};return(0,ui.useEffect)(()=>{a("Assistant response displayed",{name:e.rule.name,description:e.rule.description,group:e.rule.label,cueText:e.text})},[]),(0,lt.jsxs)(ie,{"data-testid":"cue",children:[(0,lt.jsx)(ve,{children:(0,lt.jsxs)(ve.Content,{children:[e.title&&(0,lt.jsx)(ve.Title,{className:i.title,"data-testid":"widget-cue-title",children:e.rule.label.startsWith("__")?s(e.rule.label):e.title}),e.specialType==="summary"?(0,lt.jsx)(F2,{content:u,onCopy:()=>{let m=document.getSelection();m&&d(m.toString())},onChange:m=>{var g;return c((g=m.target.value)!=null?g:"")}}):(0,lt.jsx)(Os,{content:e.text,useLabel:s("useCue"),copyLabel:s("copyCue"),onCopy:d,onUse:l?f:void 0})]})}),(0,lt.jsxs)(ie.ButtonsContainer,{children:[(0,lt.jsxs)("div",{className:i.actions,children:[e.specialType==="summary"&&(0,lt.jsx)(ie.Button,{onClick:()=>d(u),children:s("copyCue")}),e.callToAction&&(0,lt.jsx)(ie.Button,{onClick:p,children:e.callToAction.label}),(0,lt.jsx)(ie.Button,{onClick:h,children:s("removeCue")})]}),e.specialType==="summary"?(0,lt.jsx)(Yo,{eventName:"summary feedback",feedbackText:(v=e.text)!=null?v:"",feedbackType:"summary",eventData:{summary:e.text}}):(0,lt.jsx)(Yo,{eventName:"Assistant response feedback",eventData:{name:e.rule.name,group:e.rule.label,description:e.rule.description,cueText:e.text},feedbackText:e.text,feedbackType:"assistant"})]})]})},JC=z2;var Fs=x(C()),H2=({cues:e})=>{let t=G(),n=Nt(),r=q(au),o=oo(),i=u=>{t(fE({code:u.rule.label})),o("Assistant response closed",{name:u.rule.name,group:u.rule.label,description:u.rule.description,cueText:u.text})},s=(u,c)=>{switch(Un(u),c.specialType){case"summary":o("summary copied to clipboard",{originalText:c.text,finalText:u,assistant:c.rule.label});break;default:o("Assistant response copied",{name:c.rule.name,group:c.rule.label,description:c.rule.description,copiedText:u})}},a=u=>{u.callToAction&&(t(ep(u)),o("Assistant call to action",{name:u.rule.name,group:u.rule.label,description:u.rule.description,eventName:u.callToAction.event,value:u.callToAction.value}))},l=(u,c)=>{n.send(zn,{text:u,suggestion:{source:"cue",sourceText:u}}),o("Assistant response used",{name:c.rule.name,group:c.rule.label,description:c.rule.description,usedText:u})};return(0,Fs.jsx)(Fs.Fragment,{children:e.map(u=>u.isLoading?(0,Fs.jsx)(Yp,{title:u.rule.label.startsWith("__")?r(u.rule.label):u.title},u.rule.id):(0,Fs.jsx)(JC,{cue:u,onCallToAction:a,onRemove:i,onCopy:s,onUse:l},u.rule.id))})},ek=H2;var Xp=x(F());var tk={root:"dd-cvTAY",label:"dd-QWQxD",value:"dd-WSUHF",copyButton:"dd-67o9H",copyButtonText:"dd-oos-l",isTrue:"dd--1g2O",isFalse:"dd-sz2ir"};var Tn=x(C());function U2(e,t){return t.split(".").reduce((n,r)=>!n||typeof n!="object"||!(r in n)?null:n[r],e)}var nk=({data:e,schema:t})=>{let n=I("WidgetCustomData",tk),r=o=>{Un(o)};return(0,Xp.useEffect)(()=>{j.info("Custom data",e,t)},[e]),(0,Tn.jsx)("dl",{className:n.root,children:t.map(o=>{let i=U2(e,o.path);return(0,Tn.jsxs)(Xp.Fragment,{children:[(0,Tn.jsx)("dt",{className:n.label,children:o.label}),(0,Tn.jsx)("dd",{className:n.value,children:o.type==="boolean"&&i?(0,Tn.jsx)("span",{className:n.isTrue,children:o.trueValue}):o.type==="boolean"&&!i?(0,Tn.jsx)("span",{className:n.isFalse,children:o.falseValue}):i?(0,Tn.jsxs)("button",{type:"button",onClick:()=>r(i),className:n.copyButton,children:[(0,Tn.jsx)("span",{className:n.copyButtonText,children:i}),(0,Tn.jsx)(su,{})]}):"-"})]},o.label)})})};var Mt=x(F());var rv=x(C()),rk=()=>(0,rv.jsx)("svg",{focusable:"false","aria-hidden":"true",viewBox:"0 0 24 24","data-testid":"ReplayIcon",children:(0,rv.jsx)("path",{d:"M12 5V1L7 6l5 5V7c3.31 0 6 2.69 6 6s-2.69 6-6 6-6-2.69-6-6H4c0 4.42 3.58 8 8 8s8-3.58 8-8-3.58-8-8-8"})});var zs={};dt(zs,{enUS:()=>j2,nlNL:()=>B2});var j2={titleKnowledgeAssistant:[{type:0,value:"Knowledge Assistant"}],inputPlaceholder:[{type:0,value:"What is your question?"}],useCue:[{type:0,value:"Add to message"}],copyCue:[{type:0,value:"Copy"}],removeCue:[{type:0,value:"Close"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}],submitLabel:[{type:0,value:"Submit"}],resetLabel:[{type:0,value:"Reset"}],showMore:[{type:0,value:"Show "},{type:1,value:"amount"},{type:0,value:" more"}]},B2={titleKnowledgeAssistant:[{type:0,value:"Knowledge Assistant"}],inputPlaceholder:[{type:0,value:"Wat is je vraag?"}],useCue:[{type:0,value:"Voeg toe aan bericht"}],copyCue:[{type:0,value:"Kopi\xEBren"}],removeCue:[{type:0,value:"Sluiten"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}],submitLabel:[{type:0,value:"Verzend"}],resetLabel:[{type:0,value:"Reset"}],showMore:[{type:0,value:"Toon "},{type:1,value:"amount"},{type:0,value:" meer"}]};var ov={form:"dd-pleCH",formInput:"dd-pGJMY",formSubmit:"dd--gkRg",actionButton:"dd-I2NEH",sources:"dd-xf9c6",source:"dd-a-vyX",link:"dd-PyUPS",linkContent:"dd-gARDA",showMoreSources:"dd-uDGi-"};var he=x(C()),V2=3,$2=({sources:e,onClick:t})=>{let n=q(zs),r=I("WidgetKnowledgeAssistant",ov),[o,i]=(0,Mt.useState)(!1),s=o?e:e.slice(0,V2);return s.length===0?null:(0,he.jsxs)("ul",{className:r.sources,children:[s.map(a=>(0,he.jsx)("li",{className:r.source,"data-testid":"knowledge-assist-source",children:(0,he.jsx)("a",{className:r.link,rel:"noreferrer",target:"_blank",href:a.url,onClick:l=>{l.stopPropagation(),t(a)},"data-tooltip":a.url?decodeURIComponent(a.url):void 0,children:(0,he.jsx)("span",{className:r.linkContent,children:a.name})})},a.name)),s<e&&(0,he.jsx)("button",{type:"button",className:r.showMoreSources,onClick:()=>i(!0),children:n("showMore",{amount:e.length-s.length})})]})},W2=({innerRef:e,item:t,index:n,hasKeyboardInput:r,onCopy:o,onUse:i,onSourceClick:s})=>{var l;let a=q(zs);return(0,he.jsxs)(ie,{"data-testid":"knowledge-assist-answer",ref:e,children:[(0,he.jsx)(ve,{children:(0,he.jsxs)(ve.Content,{children:[(0,he.jsx)(ve.Title,{children:t.question}),(0,he.jsx)(Os,{content:t.answer.answer,useLabel:a("useCue"),copyLabel:a("copyCue"),onCopy:o,onUse:r?i:void 0}),(0,he.jsx)($2,{sources:(l=t.answer.sources)!=null?l:[],onClick:u=>s(u,t.question)})]})}),(0,he.jsxs)(ie.ButtonsContainer,{children:[(0,he.jsx)("div",{}),(0,he.jsx)(Yo,{eventName:"knowledge assist feedback",eventData:{question:t.question,isFollowUpQuestion:n>0,isAgent:!0,answer:t.answer.answer},feedbackText:t.answer.answer,feedbackType:"assistant"})]})]})},iv=(0,Mt.createContext)(null),ok=({children:e})=>{let[t,n]=(0,Mt.useState)(null),r=_(Il("knowledge-assist")),[o,i]=(0,Mt.useState)(!1),[s,a]=(0,Mt.useState)(null),l=G(),u=Qo(d=>Rl({input:d,threadId:t,onNewThreadId(f){n(f)}})),c={isEnabled:r,isSubmitting:o,threadId:t,pendingInput:s,onSubmit(d){return P(this,null,function*(){i(!0),a(d),yield u.call(d),i(!1),a(null)})},onReset(){t&&l(xs(t))}};return(0,he.jsx)(iv.Provider,{value:c,children:e})},ik=()=>{let e=q(zs),t=I("WidgetKnowledgeAssistant",ov),n=(0,Mt.useContext)(iv),r=(0,Mt.useRef)(null),[o,i]=(0,Mt.useState)(""),s=u=>{i(u.target.value)},a=u=>{u.preventDefault(),n.onSubmit(o).then(()=>{var c;r.current&&((c=r.current)==null||c.focus(),i(""))})},l=u=>{u.preventDefault(),n.onReset()};return n.isEnabled?(0,he.jsxs)("form",{className:t.form,onSubmit:a,children:[(0,he.jsx)("input",{ref:r,className:t.formInput,placeholder:e("inputPlaceholder"),type:"text",disabled:n.isSubmitting,value:o,onChange:s}),(0,he.jsx)("button",{type:"submit",disabled:n.isSubmitting||o==="",className:t.formSubmit,children:e("submitLabel")}),(0,he.jsx)("button",{type:"button",title:e("resetLabel"),disabled:n.threadId===null||n.isSubmitting,onClick:l,className:t.actionButton,children:(0,he.jsx)(rk,{})})]}):null},sk=()=>{var c,p;let e=q(zs),t=oo(),n=(0,Mt.useRef)(null),r=(0,Mt.useContext)(iv),o=(p=_(kl((c=r.threadId)!=null?c:-1)))!=null?p:[],i=H("hasKeyboardInput"),s=Nt(),a=d=>{Un(d),t("Assistant response copied",{name:"Knowledge Assistant",group:"knowlegde-assist",description:"",copiedText:d})},l=(d,f)=>{t("knowledge assist source viewed",{question:f,sourceViewed:d.url||d.name})},u=d=>{s.send(zn,{text:d,suggestion:{source:"cue",sourceText:d}}),t("Assistant response used",{name:"Knowledge Assistant",group:"knowlegde-assist",description:"",usedText:d})};return!r.isEnabled||(o==null?void 0:o.length)===0&&!r.isSubmitting?null:(0,he.jsx)(Pn,{type:"knowledge",title:e("titleKnowledgeAssistant"),"data-testid":"knowledge",children:(0,he.jsxs)(Rt,{withDivider:!0,children:[o.map((d,f)=>(0,he.jsx)(W2,{innerRef:f===o.length-1?n:void 0,item:d,index:f,hasKeyboardInput:i,onCopy:a,onUse:u,onSourceClick:l},`${d.question}_${d.answer}_${f}`)),r.pendingInput&&(0,he.jsx)(Yp,{title:r.pendingInput})]})})};var lk=x(F());var q2=/(https?:\/\/[^\s]+)/,ak=e=>e.split(" ").find(t=>q2.test(t));var an=x(C()),G2=({suggestion:e,lines:t,onUse:n})=>{var p;let r=e.text||e.url||e.message,o=ak(r),i=q(Zl),s=H("showImages"),a=H("fallbackImage"),l=H("hasKeyboardInput"),u=d=>{d.preventDefault(),d.stopPropagation(),l&&n(r)},c=(0,lk.useCallback)(d=>{window.open(o,"_blank"),d.stopPropagation(),d.preventDefault()},[o]);return(0,an.jsxs)(ie,{onClick:l?u:void 0,"data-testid":"edit-suggestion",children:[(0,an.jsxs)(ve,{children:[s&&e.image&&(0,an.jsx)(ve.Image,{src:$p(e,"small",a||void 0),title:e.title}),(0,an.jsxs)(ve.Content,{children:[e.title&&(0,an.jsx)(ve.Title,{"data-testid":"widget-suggestion-title",children:e.title}),e.searchKeywords&&((p=e.searchKeywords)==null?void 0:p.length)>0&&(0,an.jsx)(ie.Labels,{labels:e.searchKeywords}),(0,an.jsx)(ve.Content,{cropText:t==="single",lineClamp:t==="multiple",children:r})]})]}),(0,an.jsxs)(ie.Actions,{children:[o&&(0,an.jsx)(ie.ActionButton,{onClick:c,label:i("visitUrl")}),l&&(0,an.jsx)(ie.ActionButton,{primary:!0,onClick:u,label:i("useSuggestion")})]})]})},uk=G2;var lu=x(C()),Q2=({lines:e,suggestions:t})=>{let n=Nt(),r=(o,i)=>{n.send(zn,{text:o,suggestion:L(T({},i),{source:i.source,sourceText:i.text})})};return(0,lu.jsx)(lu.Fragment,{children:t.map(o=>(0,lu.jsx)(uk,{suggestion:o,lines:e,onUse:i=>r(i,o)},o.text||o.url||o.message))})},ck=Q2;var uu={};dt(uu,{enUS:()=>Y2,nlNL:()=>X2});var Y2={waiting:[{type:0,value:"Loading\u2026"}],notSupported:[{type:0,value:"This conversation is not supported"}],noResults:[{type:0,value:"No results found\u2026"}],titleCues:[{type:0,value:"Assistant updates"}],actions:[{type:0,value:"Shortcuts"}],linkStudioLogin:[{type:0,value:"My "},{type:1,value:"productName"}],linkSummary:[{type:0,value:"Summarize"}],linkKnowledgeSearch:[{type:0,value:"Knowledge Assist"}],linkSearch:[{type:0,value:"Search"}]},X2={waiting:[{type:0,value:"Laden\u2026"}],notSupported:[{type:0,value:"Dit gesprek wordt niet ondersteund"}],noResults:[{type:0,value:"Geen resultaten gevonden\u2026"}],titleCues:[{type:0,value:"Assistant updates"}],actions:[{type:0,value:"Shortcuts"}],linkStudioLogin:[{type:0,value:"Mijn "},{type:1,value:"productName"}],linkSummary:[{type:0,value:"Gesprek samenvatten"}],linkKnowledgeSearch:[{type:0,value:"Knowledge assist"}],linkSearch:[{type:0,value:"Zoeken"}]};var ci={root:"dd-W9VCG",loginText:"dd--dS6t",stateText:"dd-348OC",sectionList:"dd-bF9pF",footer:"dd-tvofr",shortcutList:"dd-MuKK-",shortcut:"dd-5CnK9",footerShortcut:"dd-dH7XJ",link:"dd-DRo0x"};var W=x(C()),fk=(e,t)=>{let n=_(gt);(0,Hs.useEffect)(()=>n?t.every(r=>!!r)?e():()=>{}:()=>{},[...t,n])},Z2=({onLogIn:e})=>{let t=I("Widget",ci),n=H("isEmbedded"),r=H("adminUrl");return(0,W.jsx)("div",{className:t.loginText,children:(0,W.jsx)("div",{children:(0,W.jsx)(Mp,{isEmbedded:n,loginUrl:r,onLogIn:e})})},"login")},dk=({text:e})=>{let t=I("Widget",ci);return(0,W.jsx)("div",{className:t.stateText,children:(0,W.jsx)("div",{children:(0,W.jsx)("p",{children:e})})},"notification")},J2=()=>{let e=q(uu),t=I("Widget",ci),n=Qo(()=>Hn({})),r=H("showSummaryCommand"),o=_(Il("knowledge-assist"));return(0,W.jsx)(W.Fragment,{children:r&&o&&(0,W.jsx)("button",{type:"button",disabled:n.state==="loading",className:t.footerShortcut,onClick:()=>n.call(),children:e("linkSummary")})})},e_=()=>{let e=q(uu),t=G(),n=I("Widget",ci),r=H("showSearch"),o=H("showSummaryCommand"),i=H("showKnowledgeSearch"),s=_(Il("knowledge-assist")),a=H("isEmbedded"),l=_(Rs("/admin/")),u=Nt(),c=H("productName"),p=H("hasKeyboardInput"),d=Qo(()=>Hn({})),f=r||o||i||l;return fk(()=>{if(a)return t(Yy()),()=>{t(BC())}},[t,a]),!f||!p?null:(0,W.jsx)(Pn,{title:e("actions"),type:"shortcuts",children:(0,W.jsxs)("div",{className:n.shortcutList,children:[r&&(0,W.jsxs)("button",{type:"button",className:n.shortcut,"data-testid":"shortcut-search","aria-label":e("linkSearch"),onClick:()=>u.send("ShowCommandPalette",{isOpen:!0}),children:[(0,W.jsx)(Es,{}),e("linkSearch")]}),o&&!s&&(0,W.jsxs)("button",{type:"button",className:n.shortcut,"data-testid":"shortcut-summary","aria-label":e("linkSummary"),disabled:d.state==="loading",onClick:()=>d.call(),children:[(0,W.jsx)(QC,{}),e("linkSummary")]}),i&&!s&&(0,W.jsxs)("button",{type:"button",className:n.shortcut,"data-testid":"shortcut-knowledge-assist","aria-label":e("linkKnowledgeSearch"),onClick:()=>u.send("ShowCommandPalette",{isOpen:!0,page:"knowledgeAssist"}),children:[(0,W.jsx)(GC,{}),e("linkKnowledgeSearch")]}),l&&(0,W.jsxs)("a",{className:n.shortcut,target:"_blank",href:l,"data-testid":"shortcut-studio-login","aria-label":e("linkStudioLogin",{productName:c}),rel:"noreferrer",children:[(0,W.jsx)(qC,{}),e("linkStudioLogin",{productName:c})]})]})})},t_=()=>{let e=G(),t=_(Ll),n=_(yE),r=_($C),o=_(A1),i=_(pp),s=_(kp),a=_(Bo),l=_(Fn);return(0,Hs.useEffect)(()=>{!!o&&!n&&j.warn("Custom data provided, but no schema.")},[o,n]),fk(()=>{t.forEach(({type:u})=>{u==="entities"?e(vn()):_u.includes(u)||e(En(u))})},[e,l,a]),(0,Hs.useEffect)(()=>{r.length>0&&!t.some(u=>u.type==="cues")&&j.warn("Received cues, but cues are not configured in widget.")},[t,r]),(0,W.jsx)(Hs.Fragment,{children:t.map(({type:u,title:c,amount:p,lines:d,schema:f})=>{var h,v;switch(u){case"entities":return i&&i.length>0&&(0,W.jsx)(Pn,{type:u,title:c,"data-testid":`type-${u}`,children:(0,W.jsx)(KC,{entities:i})},u);case"cues":return r&&r.length>0&&(0,W.jsx)(Pn,{type:u,title:c,"data-testid":`type-${u}`,children:(0,W.jsx)(Rt,{withDivider:!0,children:(0,W.jsx)(ek,{cues:r})})},u);case"custom-data":return o&&f&&(0,W.jsx)(Pn,{type:u,title:c,"data-testid":`type-${u}`,children:(0,W.jsx)(Rt,{withDivider:!0,children:(0,W.jsx)(nk,{data:o,schema:f})})},u);default:return((v=(h=s[u])==null?void 0:h.suggestions)==null?void 0:v.length)>0&&(0,W.jsx)(Pn,{type:u,title:c,"data-testid":`type-${u}`,children:(0,W.jsx)(Rt,{withDivider:!0,children:(0,W.jsx)(ck,{lines:d,contentType:u,suggestions:s[u].suggestions.slice(0,p)||[]})})},u)}})})},n_=({children:e})=>{let t=I("Widget",ci);return(0,W.jsx)("div",{className:t.footer,children:e})},r_=({onLogIn:e})=>{let t=q(uu),n=I("Widget",ci),r=_(gs),o=_(gt),i=_(f1),s=_(Bo);return r===!1?(0,W.jsx)(dk,{text:t("notSupported")}):o===!1?(0,W.jsx)(Z2,{onLogIn:e}):!s||!i||o===null?(0,W.jsx)(dk,{text:t("waiting")}):(0,W.jsx)("div",{className:(0,pk.default)(n.root),"data-testid":"widget",children:(0,W.jsxs)(ok,{children:[(0,W.jsxs)(Ou,{className:n.sectionList,children:[(0,W.jsx)(e_,{}),(0,W.jsx)(t_,{}),(0,W.jsx)(sk,{})]}),(0,W.jsxs)(n_,{children:[(0,W.jsx)(ik,{}),(0,W.jsx)(J2,{})]})]})})},mk=r_;function Us(e){let t=new Range;return t.selectNodeContents(e),t}function gk(e,t,n){try{return uo(e,t,n),!0}catch(r){return!1}}function Zp(e){return"tagName"in e&&(e.tagName==="DIV"||e.tagName==="P")}function Jp(e){return"tagName"in e&&e.tagName==="BR"}var cu=/[\u200B-\u200D\uFEFF]/g;function uo(e,t,n){let r=new Range;if(e.firstChild===null&&t===0&&n===0)return r.selectNodeContents(e),r;let o=0,i=!1;function s(l,u){let c=-1,p=/[\u200B-\u200D\uFEFF]/;if(!p.test(l))return u;for(let d=0;d<=l.length;d++)if(p.test(l[d])||c++,c===u)return d;throw new Error("Offset out of range")}function a(l){switch(l.nodeType){case Node.TEXT_NODE:{let u=l.textContent,c=u.replace(cu,""),p=o+c.length,d=t>=o&&t<=p,f=n>=o&&n<=p;if(d){let h=s(u,t-o);h===0&&!f?r.setStartBefore(l):r.setStart(l,h)}f&&(r.setEnd(l,s(u,n-o)),i=!0),o=p;break}case Node.ELEMENT_NODE:{if(Jp(l)&&(o===t&&r.setStartBefore(l),o++,o===n)){r.setEndAfter(l),i=!0;return}for(let c=0;c<l.childNodes.length&&(a(l.childNodes[c]),!i);c++);let u=l.lastChild;Zp(l)&&u&&!Zp(u)&&!Jp(u)&&o++;break}default:break}}if(a(e),r.startContainer===document)throw new Error("Offsets out of bound");return r}function du(e,t){if(!e.contains(t.startContainer)||!e.contains(t.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:r,endContainer:o,endOffset:i,collapsed:s}=t,a,l,u=0;function c(p){let d=p===e,f=p===n,h=p===o;switch(p.nodeType){case Node.TEXT_NODE:{let v=p.textContent;f&&(a=u+v.substring(0,r).replace(cu,"").length),h&&(l=u+v.substring(0,i).replace(cu,"").length),u+=v.replace(cu,"").length;break}case Node.ELEMENT_NODE:{if(Jp(p)&&p.nextSibling){u++;break}!d&&Zp(p)&&p.previousSibling&&u++;for(let v=0;v<p.childNodes.length;v++){let m=f&&v===r,g=h&&v===i;if(m&&(a=u),g&&(l=u),l!==void 0||((!m||!s)&&c(p.childNodes[v]),h&&v===i-1&&(l=u),l!==void 0))break}h&&(l=u);break}default:break}}if(c(e),l===void 0)throw new Error("Could not determine start and end");return{start:a!=null?a:l,end:l}}function pu(e,t){if(!e.contains(t.startContainer)||!e.contains(t.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:r,endContainer:o,endOffset:i,collapsed:s}=t,a=0,l="";function u(c){let p=c===e,d=c===n,f=c===o;switch(d&&(a=1),c.nodeType){case Node.TEXT_NODE:{if(a!==1)return;let h=d?r:0,v=f?i:void 0;l+=c.textContent.replace(cu,"").substring(h,v);break}case Node.ELEMENT_NODE:{if(!s&&a===1&&Jp(c)&&c.nextSibling){l+=`
|
|
82
82
|
`;break}!p&&!s&&a===1&&Zp(c)&&c.previousSibling&&(l+=`
|
|
83
|
-
`);let h=d?r:0,v=f?Math.min(i,c.childNodes.length):c.childNodes.length;for(let m=h;m<v&&(u(c.childNodes[m]),a!==2);m++);break}default:break}f&&(a=2)}return u(e),l}var hk=(s=>(s.CUT="Cut",s.BACKSPACE="Backspace",s.DELETE="Delete",s.ERASEEOF="EraseEof",s.UNDO="Undo",s.CLEAR="Clear",s))(hk||{}),br=class{constructor(t){this.element=t;this.isFocused=!1;this.isActive=!0;this.isDisposed=!1;this.eventListeners={};this.disposeHandlers=[];this.cachedText="";this.cachedCaretPosition=null;this.cachedSelection={start:0,end:0};this.cachedHTML="";this.isSubmitting=!1;this.isPossibleClearInputAction=!1;this.cachedText=this.getText(),this.cachedHTML=this.getHTML(),this.cachedSelection=this.getSelection(),this.listen()}addEventListener(t,n){let r=o=>{n(o)};this.element.addEventListener(t,r),this.disposeHandlers.push(()=>{this.element.removeEventListener(t,r)})}removeEventListener(t,n){this.element.removeEventListener(t,n)}handleInteraction(){let t=this.getText(),n=this.getHTML(),r=this.getSelection(),o=this.cachedCaretPosition===null;if(!this.isActive||(t===""&&this.cachedText!==""&&!this.isPossibleClearInputAction&&this.emit("submit"),t!==this.cachedText?(this.cachedText=t,this.cachedHTML=n,o=!0,this.emit("change",{plainText:t,rawHTML:n})):n!==null&&n!==this.cachedHTML&&(this.cachedHTML=n,o=!0,this.emit("change",{plainText:t,rawHTML:n})),(r.start!==this.cachedSelection.start||r.end!==this.cachedSelection.end)&&(this.cachedSelection=r,o=!0,this.emit("selection",r)),!o))return;let i=this.getCaretPosition();Jr(i,this.cachedCaretPosition)||(this.cachedCaretPosition=i,this.emit("caretposition",i))}handleClick(){this.handleInteraction()}handleFocus(){let t=!this.isFocused;this.isFocused=!0,t&&this.emit("focus"),this.handleInteraction()}handleBlur(){this.isPossibleClearInputAction=!1;let t=this.isFocused;this.isFocused=!1,t&&this.emit("blur")}handleKeyDown(t){let{key:n,ctrlKey:r,metaKey:o}=t;this.isPossibleClearInputAction=Object.values(hk).includes(n)||n.toLowerCase()==="z"&&(r||o),this.emit("keydown",t)}handleKeyUp(t){this.handleInteraction(),this.emit("keyup",t)}handleCut(){this.isPossibleClearInputAction=!0,this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(t){var r,o;let n=((r=t.clipboardData)==null?void 0:r.getData("text"))||((o=t.clipboardData)==null?void 0:o.getData("text/plain"))||"";this.emit("paste",{pastedText:n,selectionText:this.getSelectedText()})}listen(){this.addEventListener("keydown",n=>this.handleKeyDown(n)),this.addEventListener("keyup",n=>this.handleKeyUp(n)),this.addEventListener("input",()=>this.handleInteraction()),this.addEventListener("change",()=>this.handleInteraction()),this.addEventListener("focus",()=>this.handleFocus()),this.addEventListener("blur",()=>this.handleBlur()),this.addEventListener("cut",()=>this.handleCut()),this.addEventListener("paste",n=>this.handlePaste(n)),this.addEventListener("click",()=>this.handleInteraction()),document.activeElement===this.element&&(this.isFocused=!0);let t=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});t.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{t.disconnect()})}focus(){this.element.focus()}emit(t,...n){this.isDisposed||this.eventListeners[t]&&this.eventListeners[t].forEach(r=>{r(...n)})}on(t,n){this.isDisposed||(this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n))}off(t,n){if(!this.eventListeners[t])return;let r=this.eventListeners[t].indexOf(n);r!==-1&&this.eventListeners[t].splice(r,1)}activate(){let t=this.isActive===!1;this.isActive=!0,t&&this.handleInteraction()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(t=>t()),this.eventListeners={},this.isDisposed=!0}};function yk(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var di=class extends br{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),pu(this.element,n)}getHTML(){return this.element.innerHTML||""}getRange(){var s;let n=this.getRootNode();if(n.activeElement!==this.element)return null;let r="getSelection"in n?n.getSelection():window.getSelection();if(!r)return null;let o="getComposedRanges"in r&&n instanceof ShadowRoot?(s=r.getComposedRanges(n))==null?void 0:s[0]:r.rangeCount>0?r.getRangeAt(0):null;if(!o)return null;let i=this.element.ownerDocument.createRange();return i.setStart(o==null?void 0:o.startContainer,o==null?void 0:o.startOffset),i.setEnd(o==null?void 0:o.endContainer,o==null?void 0:o.endOffset),!i||!this.element.contains(i.startContainer)||!this.element.contains(i.endContainer)?null:i}getCaretPosition(){let n=this.getRange();if(!n||!n.collapsed||!("getBoundingClientRect"in n))return null;let r=n.getBoundingClientRect();return!yk(r)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),r=n.getBoundingClientRect(),n.deleteContents(),!yk(r))?null:{top:r.top+r.height,left:r.left}}getSelection(){let n=this.getRange();if(n)return du(this.element,n);let r=this.lastKnownSelection;if(r&&gk(this.element,r.start,r.end))return r;let o=Us(this.element);return o.collapse(!1),du(this.element,o)}getSelectedText(){let{start:n,end:r}=this.getSelection();return pu(this.element,uo(this.element,n,r))}listen(){super.listen();let n=new MutationObserver(i=>{var s,a;i.length===2&&i[0].addedNodes.length===1&&((s=i[0].addedNodes[0])==null?void 0:s.textContent)==="\u2060"&&((a=i[1].removedNodes[0])==null?void 0:a.textContent)==="\u2060"||setTimeout(()=>{this.handleInteraction()},0)});n.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0}),this.disposeHandlers.push(()=>n.disconnect());let r=this.element.isContentEditable,o=new MutationObserver(()=>{this.element.isContentEditable!==r&&(r=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>o.disconnect())}};var o_=["direction","boxSizing","width","height","overflowX","overflowY","borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth","borderStyle","paddingTop","paddingRight","paddingBottom","paddingLeft","fontStyle","fontVariant","fontWeight","fontStretch","fontSize","fontSizeAdjust","lineHeight","fontFamily","textAlign","textTransform","textIndent","textDecoration","letterSpacing","wordSpacing","tabSize"];function vk(e,t){let n="mozInnerScreenX"in window,r=document.createElement("div");r.id="input-textarea-caret-position-mirror-div";let o=r.style,i=window.getComputedStyle(e),s=e.ownerDocument.body;o.whiteSpace="pre-wrap",o.wordWrap="break-word",o.position="absolute",o.visibility="hidden",o_.forEach(function(c){o[c]=i[c]}),n?e.scrollHeight>parseInt(i.height)&&(o.overflowY="scroll"):o.overflow="hidden",r.textContent=e.value.substring(0,t);let a=document.createElement("span");a.textContent=e.value.substring(t)||".",r.appendChild(a),s.appendChild(r);let l=e.getBoundingClientRect(),u={top:l.top-e.scrollTop+a.offsetTop+parseInt(i.borderTopWidth)+a.offsetHeight,left:l.left-e.scrollLeft+a.offsetLeft+parseInt(i.borderLeftWidth)};return s.removeChild(r),u}var pi=class extends br{constructor(){super(...arguments);this.lastKnownSelection=null}getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:n,selectionEnd:r}=this.element;return{start:n,end:r}}getSelectedText(){let n=this.getSelection();return n?this.getText().slice(n.start,n.end):""}getCaretPosition(){return vk(this.element,this.element.selectionEnd)}listen(){super.listen();let n=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var i;return(i=n==null?void 0:n.get)==null?void 0:i.call(this.element)},set:i=>{var s;(s=n==null?void 0:n.set)==null||s.call(this.element,i),this.handleInteraction()}}),this.addEventListener("scroll",()=>{this.emit("caretposition",this.getCaretPosition())});let r=this.element.disabled,o=new MutationObserver(()=>{this.element.disabled!==r&&(r=this.element.disabled,this.emit(r?"disabled":"enabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>o.disconnect())}};function Sk(e,t,n){let r=`deepdesk-iframe-${e}`,o=document.getElementById(r);if(o)return o;let i=document.createElement("iframe"),s=new URL(t);return Object.entries(n).forEach(([a,l])=>{s.searchParams.append(a,l)}),i.style.position="absolute",i.style.left="-999em",i.style.width="0px",i.style.height="0px",i.tabIndex=-1,i.id=r,i.title=`iframe-${e}`,i.src=s.toString(),window.document.body.appendChild(i),i}function i_(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(t){return e}}var sv=class{constructor(t){this.name=t;this.disposeHandlers=[];this.broadcastChannel=new BroadcastChannel(t)}onMessage(t){this.broadcastChannel.addEventListener("message",t),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",t)})}postMessage(t){this.broadcastChannel.postMessage(JSON.stringify(t))}close(){this.disposeHandlers.forEach(t=>t()),this.broadcastChannel.close()}},av=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.disposeHandlers=[];this.iframe=Sk(t,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}onMessage(t){window.addEventListener("message",t),this.disposeHandlers.push(()=>{window.removeEventListener("message",t)})}postMessage(t){var n;(n=this.iframe.contentWindow)==null||n.postMessage(JSON.stringify(t),this.targetOrigin)}close(){var t;this.disposeHandlers.forEach(n=>n()),(t=this.iframe)==null||t.remove()}},lv=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.eventMap,this.sessionId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setSessionId(t){this.sessionId!==t&&(this.cleanup(),j.info("Set sessionId",t),this.sessionId=t,this.channel=this.createChannel(t))}createChannel(t){let n=this.params.createCustomChannel?this.params.createCustomChannel(t):this.isCrossOrigin?new av(t,this.deepdeskUrl,{debug:!0}):new sv(t),r=o=>{var s,a;if(o.origin!==this.deepdeskUrl)return;let i=i_(o.data);typeof i!="object"||i.type!=="event"||i.channel!==t||(j.info("Received broadcast event",this.sessionId,o),(a=(s=this.eventMap)[i.name])==null||a.call(s,i.payload))};return n.onMessage(r),n}send(t,n,r){var s,a;j.info("Broadcast event",{sessionId:this.sessionId,name:t,payload:n});let o={type:"event",name:t,payload:n};r!==!1&&((a=(s=this.eventMap)[t])==null||a.call(s,n));let i=this.sessionId==="deepdesk-general"?this.defaultChannel:this.channel;i==null||i.postMessage(L(T({},o),{channel:this.sessionId}))}cleanup(t=!1){var n,r;(n=this.channel)==null||n.close(),delete this.channel,t&&((r=this.defaultChannel)==null||r.close(),delete this.defaultChannel)}},xk=lv;function s_(e){return e.replace(/(_\w)/g,t=>t[1].toUpperCase())}function ke(e){return Array.isArray(e)?e.map(ke):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>L(T({},t),{[s_(n)]:ke(e[n])}),{}):e}function a_(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function Ye(e){return Array.isArray(e)?e.map(Ye):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>L(T({},t),{[a_(n)]:Ye(e[n])}),{}):e}var js=class extends Error{constructor(n,r){super(n);this.body=r;this.name="CustomError"}};var uv=e=>new Promise(t=>{setTimeout(t,e)});var Bs=class extends js{constructor(){super(...arguments);this.name="ClientError"}},dv=class extends js{constructor(){super(...arguments);this.name="ServerError"}},cv=new Map;function l_(e){return P(this,null,function*(){if(e.status===204)return e.text().catch(()=>{}),null;let t=e.headers.get("content-type");if(t&&t.includes("application/json"))return e.json();let n=yield e.text();return n===""?null:(j.warn("Unexpected response body:",n.slice(0,20)),JSON.parse(n))})}var co=class co{constructor(t="",n={}){this.baseUrl=t;this.options=n;this.latestRequestByUrl={};this.fetch=window.fetch.bind(window);n.fetch&&(this.fetch=n.fetch)}patchFetch(t){this.fetch=t(this.fetch)}setCsrfToken(t){this.csrfToken=t}request(t,n={}){return new Promise((r,o)=>{let i={isAborted:!1,reject:o},s=`${this.baseUrl}${t}`,a=this.fetch,l=n.method===void 0||n.method.toLowerCase()==="get",E=n,{useCache:u=!1,abortLatest:c=!1,attempts:p=1,retryDelay:d=500,refreshTokenOn401:f=!0,retryOnError:h=R=>R instanceof TypeError,retryOnResponse:v=R=>R.status>=500,version:m=null}=E,g=Z(E,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]);if(u)if(l){if(cv.has(s)){r(cv.get(s));return}}else throw new Error(`Can't use 'useCache' for ${n.method}`);let y=L(T({credentials:"include"},g),{headers:T({Accept:"application/json","Content-Type":"application/json"},g.headers)});!l&&this.csrfToken&&(y.headers=L(T({},y.headers),{"X-CSRFToken":this.csrfToken})),typeof m=="string"&&(y.headers=L(T({},y.headers),{"X-Deepdesk-API-Version":m}));let S=p,w=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[s]&&c&&(this.latestRequestByUrl[s].isAborted=!0,this.latestRequestByUrl[s].reject(new Error("Aborted"))),this.latestRequestByUrl[s]=i;let k=()=>P(this,null,function*(){return S--,a(s,y).then(R=>P(this,null,function*(){return v(R)&&!i.isAborted&&S>0?(yield uv(d),k()):R.status===401&&f===!0&&w===!1?(w=!0,yield this.refreshToken(),k()):R})).catch(R=>P(this,null,function*(){if(h(R)&&!i.isAborted&&S>0)return yield uv(d),k();throw R}))});k().then(R=>P(this,null,function*(){let A=yield l_(R);if(delete this.latestRequestByUrl[s],R.status>=500){o(new dv("Server Error",A));return}else if(R.status===401){o(new Bs("Unauthorized",A));return}else if(R.status===403){o(new Bs("Forbidden",A));return}else if(R.status===404){o(new Bs("Not Found",A));return}else if(R.status>=400){o(new Bs("Bad Request",A));return}u&&cv.set(s,A),r(A)})).catch(R=>{o(R)})})}validateToken(){return P(this,null,function*(){let{has_valid_access_token:t}=yield this.get("/auth/validate");if(!t)try{yield this.refreshToken()}catch(r){return!1}let{is_logged_in:n}=yield this.get("/apis/admin/session/validate/");return!!n})}refreshToken(){return co.refreshingToken||(co.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{co.refreshingToken=null},1e3*60)})),co.refreshingToken}get(t,n){return this.request(t,n)}post(t,n,r){return this.request(t,T({method:"POST",body:JSON.stringify(n)},r))}patch(t,n,r){return this.request(t,T({method:"PATCH",body:JSON.stringify(n)},r))}put(t,n,r){return this.request(t,T({method:"PUT",body:JSON.stringify(n)},r))}delete(t,n){return this.request(t,T({method:"DELETE"},n))}};co.refreshingToken=null;var fi=co;var wk;(t=>{let e;(s=>(s.SEND_MESSAGE="Send Message",s.HANDLING_TIME="Handling Time",s.ADD_TO_PERSONAL_COLLECTION="Add to personal collection",s.DELETE_FROM_PERSONAL_COLLECTION="Delete from personal collection"))(e=t.EventType||(t.EventType={}))})(wk||(wk={}));function ef(e){return L(T({},ke(e)),{tags:e.tags})}var mi=class mi{constructor(t,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new fi(t,{fetch:n.fetch}),this.client.patchFetch(r=>(o,i)=>P(this,null,function*(){let s=yield r(o,i);return this.handleDeepdeskVersionHeaders(s),s}))}preflight(){return P(this,null,function*(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=yield this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(mi.exchangeTokenPromise||(mi.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),mi.exchangeTokenPromise):Promise.resolve()})}createConversation(t){return P(this,null,function*(){yield this.preflight(),j.info(`Creating conversation for session ${t.sessionId} and agent ${t.agentId}`);let n=yield this.client.post("/api/conversations",L(T({},Ye(t)),{tags:t.tags}),{version:"v2"});return ef(n)})}getMe(){return P(this,null,function*(){let t=yield this.client.get("/apis/admin/session/me/");return ke(t)})}postIdentity(t){return P(this,null,function*(){yield this.client.post("/apis/admin/session/me/identities/",Ye(t))})}patchMe(t){return P(this,null,function*(){let n=yield this.client.patch("/apis/admin/session/me/",Ye(t));return ke(n)})}getProfile(t){return P(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${t}/`,{useCache:!0});return ke(n)})}getKnowledgeAssistant(t){return P(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{useCache:!0});return ke(n)})}getContentTypes(){return P(this,null,function*(){let t=yield this.client.get("/apis/admin/content-types/",{useCache:!0});return ke(t)})}getAccount(){return P(this,null,function*(){let t=yield this.client.get("/apis/admin/account/",{useCache:!0});return ke(t)})}getPlatformConfig(t){return P(this,null,function*(){let n=t!==void 0?`/platform/config/${t}/`:"/platform/config/",{config:r}=yield this.client.get(n,{useCache:!0});return ke(r)})}checkUserExists(t){return P(this,null,function*(){let{exists:n}=yield this.client.get(`/apis/admin/users/exists?external_id=${t}`,{version:"v1"});return n})}getConversationBySessionId(r){return P(this,arguments,function*(t,n={}){yield this.preflight(),j.info(`Getting conversation for session ${t}`);let{attempts:o=1,retryDelay:i=1e3}=n,s=yield this.client.get(`/api/conversations/by_session_id/${t}`,{attempts:o,retryDelay:i,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"});return j.info(`Successfully retrieved conversation ${s.id} for session ${t}`),ef(s)})}isConversationSupported(r){return P(this,arguments,function*(t,n={}){j.info(`Check if conversation for session ${t} is supported`);let{attempts:o=1,retryDelay:i=1e3}=n;return(yield this.client.get(`/api/conversations/by_session_id/${t}/active_profile`,{attempts:o,retryDelay:i,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"})).has_active_profile})}updateConversation(t,n){return P(this,null,function*(){let r=Ye(n);n.tags&&(r.tags=n.tags);let o=yield this.client.put(`/api/conversations/${t}`,r,{version:"v2"});return ef(o)})}postMessages(t,n){return P(this,null,function*(){return(yield this.client.post(`/api/conversations/${t}/messages`,n.map(o=>L(T({},Ye(o)),{tags:o.tags})),{version:"v2"})).map(o=>ef(o))})}sendEvent(t,n){return P(this,null,function*(){let s=n,{data:r}=s,o=Z(s,["data"]),i=Object.entries(this.latestReceivedDeepdeskVersions).reduce((a,[l,u])=>L(T({},a),{[l]:u}),{});return this.client.post("/api/events",Ye(L(T(T({},i),o),{data:r,name:t})),{version:"v2"})})}sendEventV1(t,n){return P(this,null,function*(){let r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((o,[i,s])=>L(T({},o),{[i]:s}),{});return this.client.post("/api/events",{event:t,data:Ye(T(T({},n),r))},{version:"v1"})})}getEntities(t){return P(this,null,function*(){return(yield this.client.post("/api/entities",{messages:t.filter(r=>r.text)},{version:"v1"})).entities})}getTemporaryExchangeToken(){return P(this,null,function*(){return(yield this.client.get("/auth/exchange-token")).jwt})}exchangeTokenForAccessCookie(t){return P(this,null,function*(){return this.client.post("/apis/admin/session/jwt/",{jwt:t}).catch(n=>{throw j.warn(`Invalid token '${t}'`),n})})}authenticateWithKey(t,n){return P(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/api-key/",Ye(n),{refreshTokenOn401:!1,headers:{apikey:t}})})}getTextSuggestions(o){return P(this,arguments,function*(t,n={},r){return r==="sticky-messages"?this.getPinnedMessages(t):(yield this.client.post(`/api/conversations/${t}/recommend/${r}`,Ye(n),{abortLatest:!0,version:"v1"})).map(s=>L(T({},ke(s)),{text:s.text||s.url||s.message,source:r,type:r})).filter((s,a,l)=>a===l.findIndex(u=>u.text===s.text))})}isLoggedIn(){return P(this,null,function*(){return yield this.preflight(),this.client.validateToken()})}getAutocompleteSuggestions(t,n){return P(this,null,function*(){return(yield this.client.post(`/api/conversations/${t}/autocomplete`,Ye(n),{abortLatest:!0,version:"v1"})).map(o=>({score:1,source:o.source,sourceText:o.source_text,text:o.label,trainingJobs:o.training_jobs,searchKeywords:o.search_keywords,type:o.source})).filter((o,i,s)=>i===s.findIndex(a=>a.text===o.text))})}getPinnedMessages(t){return P(this,null,function*(){let n=yield this.client.get(`/api/conversations/${t}/sticky-messages`,{abortLatest:!0,version:"v1"});return ke(n).map(r=>L(T({},r),{text:r.message,source:"sticky-messages",type:"pinned-message"}))})}getStyleSuggestions(t){return P(this,null,function*(){let n=yield this.client.post("/api/style-suggestions",Ye(t),{abortLatest:!0,version:"v1"});return ke(n)})}search(t){return P(this,null,function*(){let n=yield this.client.post(`/api/profiles/${t.profile}/search`,Ye(t),{version:"v2"});return ke(n)})}knowledgeAssist(i,s,a){return P(this,arguments,function*(t,n,r,o={}){let l=yield this.client.post(`/api/knowledge-assist/assistants/${r}/search`,Ye({question:t.question,doNotKnowAnswer:t.doNotKnowAnswer,customerInstruction:t.customerInstruction,chatHistory:n.map(u=>({question:u.question,answer:u.answer.answer})),agentId:o.agentId,conversationId:o.conversationId}),{version:"v2"});return ke(l)})}requestLoginByEmail(t){return P(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:t});return ke(n)})}requestPasswordlessToken(){return P(this,null,function*(){let t=yield this.client.get("/apis/admin/session/passwordless/request/");return ke(t.token)})}getCsrfToken(){return P(this,null,function*(){let{token:t}=yield this.client.get("/apis/admin/session/csrf/");return t})}verifyLoginToken(t){return P(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/login/",{token:t});return ke(n)})}getSummary(r){return P(this,arguments,function*(t,n={}){let o=yield this.client.post("/api/summary",{conversation:{messages:t.filter(i=>i.text&&i.source),agent_id:n.agentId,id:n.externalConversationId},prompt_instruction:n.promptInstruction,model:n.model},{version:"v1"});return ke(o)})}evaluateAssistant(t,n){return P(this,null,function*(){var a;let r=new URLSearchParams,{expectFormat:o="text"}=n||{};if(o.startsWith("json-schema:")){let l=o.replace("json-schema:","");r.append("expect_response_format","json-schema"),r.append("expect_response_format_schema",l)}else r.append("expect_response_format",o);n!=null&&n.externalConversationId&&r.append("external_conversation_id",n.externalConversationId);let i=n!=null&&n.threadId?`/api/v2/assistants/${t}/threads/${n==null?void 0:n.threadId}/evaluate?${r.toString()}`:`/api/v2/assistants/${t}/evaluate?${r.toString()}`,s=yield this.client.post(i,{input:(a=n==null?void 0:n.input)!=null?a:{},conversation:n==null?void 0:n.transcript});return ke(s.output)})}createAssistantThread(t){return P(this,null,function*(){let{assistantCode:n}=t,r=yield this.client.post(`/apis/admin/assistants/${n}/threads/`,{});return ke(r)})}postMessageToAssistantThread(t){return P(this,null,function*(){let{assistantCode:n,threadId:r,message:o}=t,i=yield this.client.post(`/apis/admin/assistants/${n}/threads/${r}/messages/`,{content:o,role:"user"});return ke(i)})}translateMessages(t){return P(this,null,function*(){let n=yield this.client.post("/api/translate",Ye(t),{version:"v2"});return ke(n)})}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),i=o.match(I0);if(!n||!i)return;let s=i[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[s];a&&n&&a!==n&&j.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[s]=n})}};mi.exchangeTokenPromise=null;var Er=mi;var bk={startTime:null,stopTime:null},Ek=e=>e.handlingTime,Tk=te({name:"handlingTime",initialState:bk,reducers:{handlingTimeStart(e){if(e.startTime&&!e.stopTime)throw new Error("Timing already started");e.startTime=new Date,e.stopTime=null},handlingTimeStop(e){if(!e.startTime)throw new Error("Timing not started");e.stopTime=new Date},handlingTimeReset(e){e.startTime=null,e.stopTime=null}},extraReducers:e=>{e.addCase(Fe,()=>bk)}}),{handlingTimeStart:Ck,handlingTimeStop:tf,handlingTimeReset:kk}=Tk.actions,Rk=Tk.reducer;var Pk=(e={})=>{let t=T({onAuthError:ms(!1)},e);return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var nf={list:{keywordMatches:[]},fetchState:"idle"};var gi=Q("styleSuggestions/getAll",(n,r)=>P(void 0,[n,r],function*({text:e},t){var l;let{deepdeskAPI:o}=t.extra,i=t.getState(),{showStyleSuggestions:s}=i.settings,a=(l=i.conversation.current)==null?void 0:l.profileCode;if(!s)return nf.list;if(!a)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:a,message:e})})),u_=te({name:"styleSuggestions",initialState:nf,reducers:{},extraReducers:e=>{e.addCase(gi.pending,t=>{t.fetchState="loading"}).addCase(gi.rejected,t=>{t.fetchState="error"}).addCase(gi.fulfilled,(t,n)=>{t.fetchState="done",Jr(t.list,n.payload)||(t.list=n.payload)}).addCase(zo,t=>{t.list=nf.list}).addCase(Fe,()=>nf)}}),Ak=u_.reducer;var Lk=(e={})=>{let t,n=!0,r=T({getStyleSuggestions:gi,debounce:500},e);return o=>i=>s=>{var f;let a=o.getState().input.text,l=i(s),u=o.getState();if(u.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:c}=u.settings;if(!((f=u.conversation.current)==null?void 0:f.id)||!c)return l;let{text:d}=u.input;return d===a&&!n||(clearTimeout(t),d==="")||(t=setTimeout(()=>{n=!1,o.dispatch(r.getStyleSuggestions({text:d}))},e.debounce)),l}};function c_(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var Ik=(e={})=>{let t=T({getTextSuggestions:En,getAutocompleteSuggestions:eu,debounce:200,check:Vn},e),n;return r=>o=>i=>{var v;let{input:s}=r.getState(),a=o(i),l=r.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:u,showTabCompletion:c}=l.settings,p=(v=l.conversation.current)==null?void 0:v.id,d=i.type===Rp.toString();if(!p||!u&&!c)return a;let{input:f}=l;return c_(f,s)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let m=hs(l);m===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(m))},d?0:t.debounce)),a}};var Ok=gi.fulfilled.toString();function d_(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let i=e.keywordMatches.filter(l=>l.keyword===o),s=t.keywordMatches.filter(l=>l.keyword===o),a=s.length-i.length;a<=0||r.push(...s.slice(0,a))}),r}var Nk=e=>t=>n=>r=>{var u;if(r.type!==Ok){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let i=t.getState(),s=i.styleSuggestions.list,a=(u=i.conversation)==null?void 0:u.current;if(o===s)return;let l=d_(o,s);r.type===Ok&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var p_=ed({assistants:mE,auth:r1,conversation:m1,contentTypes:hE,passwordlessToken:VC,entities:VE,knowledgeAssistant:uE,handlingTime:Rk,info:M1,input:k1,settings:Yb,profile:vE,search:U1,styleSuggestions:Ak,ui:uC,textSuggestions:GT});function Mk(e){return nb({reducer:p_,middleware:t=>[...t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI}},serializableCheck:!1}),Pk(),Ik({debounce:200}),Lk({debounce:500}),Nk(e.deepdeskAPI),...e.middleware?e.middleware:[]],preloadedState:e.preloadedState})}var f_=e=>{var t,n;return(n=(t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())!=null?n:"unknown"},m_=e=>t=>n=>r=>{var a,l,u,c,p,d;let o=t.getState(),i=sl("inlineSuggestions")(o);switch(r.type){case ms.toString():{!r.payload&&e.emit("logout",void 0);break}case vn.fulfilled.toString():r.payload.length>0&&e.sendEvent("entities found",{conversationId:(a=o.conversation.current)==null?void 0:a.id,data:{entities:r.payload}});break;case Jt.toString():e.sendEvent(r.payload.name,{conversationId:((l=r.payload.options)==null?void 0:l.includeConversationData)&&((u=o.conversation.current)==null?void 0:u.id),data:r.payload.data});break;case zo.toString():e.logSendMessage(r.payload);break;case ep.toString():e.emit("call-to-action",{cue:r.payload});break;case ur.fulfilled.toString():r.isBroadcasted||e.broadcast(Oh,r,!1);break;default:break}let s=n(r);switch(r.type){case zo.toString():e.handleAfterSendMessage(r.payload);break;case nu.toString():e.onUpdateShowTabHint(r.payload);break;case tf.toString():e.logHandlingTime();break;case"analytics/logEvent/fulfilled":{e.emit("event",r.meta.arg);break}case Dd.toString():{let{start:f,end:h}=o.input.selection;e.emit("replace",L(T({},r.payload),{replace:r.payload.replace==="selection"?{start:f,end:h}:{start:0,end:h}}));break}case mn.toString():{let{start:f,end:h}=o.input.selection;e.emit("select-suggestion",L(T({type:f_(r.payload.suggestion)},r.payload),{replace:r.payload.replace==="selection"?{start:f,end:h}:{start:0,end:h}})),i&&t.dispatch(eo([]));break}case Fd.toString():e.emit("select-image",r.payload),e.sendEvent("Image attached",{conversationId:(c=o.conversation.current)==null?void 0:c.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case eo.toString():{i&&r.payload.length>0&&t.dispatch(zd(0));break}case Hn.fulfilled.toString():{e.sendEvent("conversation summarized",{conversationId:(p=o.conversation.current)==null?void 0:p.id,data:{summary:r.payload,assistant:(d=t.getState().profile.data)==null?void 0:d.summarizerAssistantNew}});break}default:break}return s},_k=m_;function pv(e){return e.toISOString().replace("T"," ").replace("Z","")}var g_=(e,t)=>t.version,Dk=fn([vs,Fn,Ek,g_],(e,t,n,r)=>{if(!t)return j.warn("No conversationId for handling time metrics"),null;let{startTime:o,stopTime:i}=n;return!o||!i?(j.warn("No startTime and stopTime for handling time metrics"),null):{conversationId:t,clientVersion:r,agentId:e==null?void 0:e.agentId,agentName:e==null?void 0:e.agentName,agentEmail:e==null?void 0:e.agentEmail,timeStart:pv(o),timeStop:pv(i)}});function Fk(e,t,n){var A,M,Y,z;let r=(A=t.conversation.current)==null?void 0:A.id;if(!r)return j.warn("No conversationId for send message metrics"),null;let{text:o,metrics:{numCharsTyped:i,numCharsPasted:s,numCharsCut:a,numCharsDeleted:l,numPaste:u,agentStartedTypingTimestamp:c,externalTimeTotalSeconds:p,pastes:d,cuts:f,deletions:h,textSuggestions:v,offeredTextSuggestions:m}}=t[e],g=o.length,S=v.reduce((V,{text:me,searchTerm:Ue})=>V+me.length-(Ue?Ue.length:0),0),w=c!=null?c:Date.now(),k=(Date.now()-w)/1e3+(p||0),E=i/k,R=v.reduce((V,{searchTerm:me})=>V+(me?me.length:0),0);return{conversationId:r,source:"agent",text:o,clientVersion:n.version,pastes:d,cuts:f,deletions:h,lenTextTyped:i+R,lenTextTotal:g,lenTextAssisted:S,lenTextPasted:s,lenTextCut:a,lenTextDeleted:l,timeTotalSeconds:k,charsPerSecond:E,numPastes:u,textSuggestionsV2:v,suggestionsCounters:[{source:"gpt",countOffered:m.filter(V=>V.source==="gpt").length}],agentId:(M=t.info.agentInfo)==null?void 0:M.agentId,agentName:(Y=t.info.agentInfo)==null?void 0:Y.agentName,agentEmail:(z=t.info.agentInfo)==null?void 0:z.agentEmail}}function fv(e,t){var i;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return fv(r,t);let o=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;return o?fv(o,t):null}function mv(e,t){return fv(e,t)}function zk(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function h_(e){return typeof e=="object"&&e!==null&&"tagName"in e}function rf(e){return h_(e)&&(li(e)||Dp(e))}var Uk,Kn=new Map,y_=["bottom","height","left","right","top","width"],Hk=(e,t)=>!e&&!t?!1:e&&!t||!e&&t?!0:y_.some(n=>e[n]!==t[n]);function jk(e){var n,r,o;if(e.ownerDocument===document)return[];let t=(o=(r=(n=e.ownerDocument)==null?void 0:n.defaultView)==null?void 0:r.frameElement)!=null?o:null;return t?[t,...jk(t)]:[]}function Bk(e,t){return!e||!t?null:L(T({},e),{top:e.top+t.top,left:e.left+t.left})}var of=!1,Vk=()=>{of=!0;let e=[];if(Kn.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),Kn.delete(n);return}let r=n.getBoundingClientRect();Hk(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(Bk,t.rect):t.rect;Hk(n,t.totalRect)&&t.callbacks.forEach(r=>r(n)),t.totalRect=n}),Kn.size===0){of=!1;return}Uk=window.requestAnimationFrame(Vk)};function gv(e,t){let n=jk(e),r=[],o=n.map((i,s)=>gv(i,a=>{r[s]=a;let l=Kn.get(e);if(!l)return;let u=r.reduce(Bk,l.rect);l.callbacks.forEach(c=>c(u))}));return{observe(i=!0){if(o.forEach(s=>s.observe(!1)),Kn.has(e)){let s=Kn.get(e);s.callbacks.push(t),s.rect&&t(s.rect)}else Kn.set(e,{rect:void 0,callbacks:[t],parentRects:r});i&&!of&&Vk()},unobserve(){o.forEach(s=>s.unobserve());let i=Kn.get(e);if(i){let s=i.callbacks.indexOf(t);s>=0&&i.callbacks.splice(s,1),i.callbacks.length||Kn.delete(e),Kn.size||(cancelAnimationFrame(Uk),of=!1)}}}}var $k,qn=new Map,Wk=()=>{qn.forEach((e,t)=>{if(!t.isConnected){qn.delete(t);return}let{clientHeight:n,scrollHeight:r}=t,o=r>n;e.visible!==o&&(e.visible=o,e.callbacks.forEach(i=>i(e.visible)))}),qn.size!==0&&($k=window.requestAnimationFrame(Wk))};function Kk(e,t){return{observe(){let n=qn.size===0;qn.has(e)?qn.get(e).callbacks.push(t):qn.set(e,{visible:void 0,callbacks:[t]}),n&&Wk()},unobserve(){let n=qn.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||qn.delete(e),qn.size||cancelAnimationFrame($k)}}}}var hv=["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 yv(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function Vs(e){return parseFloat(e)}function sf(e){return Math.round(e*1e6)}function qk(e){return e/1e6}function vv(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=Vs(e.width),i=Vs(e.borderLeftWidth),s=Vs(e.borderRightWidth),a=Vs(e.paddingRight),l=qk(sf(o)-sf(i)-sf(s)),u=qk(sf(r));if(l-u>2){let c=l-u;n.style.paddingRight=`${a+c}px`}}function fu(e,t={}){var c,p;let n=t.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=(c=t.position)!=null?c:"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",Zo(n);let r=window.getComputedStyle(e),o=!0,i=()=>{n.scrollTop=e.scrollTop};yv(r,n,hv),vv(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",i));let s=Kk(e,()=>{yv(r,n,hv),vv(r,e,n),i(),setTimeout(i,0)}),a,l=!0,u=gv(e,d=>{if(d===null){t.onRemove&&t.onRemove(),n.remove();return}if(!l&&t.onMoveStart&&(Promise.resolve().then(()=>t.onMoveStart()),l=!0),clearTimeout(a),a=setTimeout(()=>{t.onMoveEnd&&t.onMoveEnd(),l=!1},200),d.height===0&&d.width===0){if(o===!0)return;t.onHide&&t.onHide(),n.style.display="none",o=!0;return}if(yv(r,n,hv),vv(r,e,n),i(),n.style.top=`${d.top}px`,n.style.left=`${d.left}px`,t.closestScrollElement&&t.closestScrollElement!==e){let f=t.closestScrollElement.getBoundingClientRect(),h=window.getComputedStyle(t.closestScrollElement),v=Vs(h.borderTopWidth),m=Vs(h.borderBottomWidth),g=f.top+v-d.top,y=d.top+d.height+-(f.top+f.height-m);n.style.clipPath=`inset(${g}px 0px ${y}px 0px)`}o&&(n.style.display="block",t.onShow&&t.onShow(),o=!1)});return t.appendTo?t.appendTo.appendChild(n):(p=e.parentElement)==null||p.appendChild(n),u.observe(),s.observe(),[n,()=>{e.removeEventListener("scroll",i),u.unobserve(),s.unobserve()}]}var Gk=(e,t)=>({value(){try{let n=sessionStorage.getItem(`dd-${e}`);if(!n)return t;try{return JSON.parse(n)}catch(r){return t}}catch(n){return t}},update(n){try{sessionStorage.setItem(`dd-${e}`,JSON.stringify(n))}catch(r){j.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function v_(e){return e.offsetParent!==null}function Qk(e){if(!v_(e))return!1;let t=e.getBoundingClientRect();return t.top>=0&&t.left>=0&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&t.right<=(window.innerWidth||document.documentElement.clientWidth)}function af(e,t,n=100){let r=Qk(e);t({isVisible:r});let o=setInterval(()=>{let i=Qk(e);i!==r&&(r=i,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var He=x(C());var Yk=Gk("showTabHint",!0),$s=class $s{constructor({deepdeskUrl:t,version:n=$s.version||"unknown",locale:r="en-US",token:o,fetch:i,productName:s,createCustomChannel:a}){this.inputMediator=null;this.eventListeners={};this.unmountHandlers=[];this.inlineSuggestions=null;this.aboveSuggestions=null;this.floatingMenu=null;this.widgetRoot=null;this.dynamicThunkObject={};this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;let l=t.replace(/\/api$/,"");this.deepdeskApi=new Er(l,{token:o,fetch:i}),this.version=n,this.instanceId=$s.count++;let u={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[_k({broadcast:(c,p,d)=>{this.broadcastEvents.send(c,p,d)},emit:(c,p)=>this.emit(c,p),handleAfterSendMessage:c=>this.handleAfterSendMessage(c),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:c=>this.logSendMessage(c),onUpdateShowTabHint:c=>Yk.update(c),sendEvent:(c,p)=>this.deepdeskApi.sendEvent(c,p)})]};this.store=Mk(u),this.broadcastEvents=new xk({debug:!0,deepdeskUrl:l,eventMap:j1(this.store),createCustomChannel:a}),this.store.dispatch(nu(Yk.value())),this.store.dispatch(Ld({locale:r,adminUrl:l,productName:s}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){var t;return(t=this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex])!=null?t:null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(j.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(j.warn("Profile has not been loaded (yet)"),!0):(j.warn("No conversation loaded (yet)"),!0)}login(){this.store.dispatch(ms(null)),this.store.dispatch(sr());let t=n=>gt(n)&&Xb(n)!=="loading";return new Promise(n=>{let r=this.subscribe(t,o=>{o&&(r(),n())});this.unmountHandlers.push(()=>{r()})})}isLoggedIn(){return P(this,null,function*(){return(yield this.store.dispatch(sr())).payload})}isConversationSupported(t,n){return P(this,null,function*(){return(yield this.store.dispatch(kh({sessionId:t,options:n}))).payload})}createConversation(t){return P(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(yield this.store.dispatch(Od(t))).payload})}getConversationBySessionId(t,n){return P(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(yield this.store.dispatch(Nd({sessionId:t,options:n}))).payload})}upsertConversation(t){return P(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(yield this.store.dispatch(Rh(t))).payload})}postMessages(t){return P(this,null,function*(){return(yield this.store.dispatch(_d(t))).payload})}updateConversation(t){return P(this,null,function*(){return(yield this.store.dispatch(Md(t))).payload})}resetConversation(){this.store.dispatch(Fe()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}configure(t){this.store.dispatch(Ld(t))}setVisitorInfo(t){this.store.dispatch(I1(t))}setCustomData(t){this.store.dispatch(O1(t))}setAgentInfo(t,n){return P(this,null,function*(){yield this.store.dispatch(ul(T(T({},t),n)))})}setAgentSettings(t){return P(this,null,function*(){yield this.store.dispatch(Ah(t))})}getAgentSettings(){return P(this,null,function*(){return(yield this.store.dispatch(Lh())).payload})}refresh(){return P(this,null,function*(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.store.dispatch(Hd({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()}));let t=[];return this.store.dispatch(Rp()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})})}notifyExternalSuggestion(t){this.store.dispatch(mn(t))}evaluateAssistant(t,n){return P(this,null,function*(){let c=n||{},{input:r={},transcript:o,showCuesInWidget:i=!0,includeTags:s,expectFormat:a}=c,l=Z(c,["input","transcript","showCuesInWidget","includeTags","expectFormat"]);Object.assign(r,l);let u=yield this.store.dispatch(ur({assistantCode:t,expectFormat:a||"json-schema:cues",transcript:o,includeTags:s,input:r,skipState:!i}));if(u.error)throw new Error(u.error.message);return u.payload})}evaluateConversationAssistant(t,n){return P(this,null,function*(){yield this.loadProfileConfig();let r={accepted:"conversationAcceptedAssistant","new-message":"conversationNewMessageAssistant",ended:"conversationEndedAssistant"},o=this.state.profile.data[r[t]];if(!o){j.warn(`No assistant set in profile for conversation event "${t}"`);return}yield this.evaluateAssistant(o,T({transcript:"stored-transcript",includeTags:!0},n))})}getSummary(){return P(this,null,function*(){var n;if(!this.hasConversation())return j.warn("No conversation to create summary for."),null;(n=this.state.profile.data)!=null&&n.summarizerAssistantNew||j.warn("No profile loaded yet, or no summarizer assistant set in profile");let t=yield this.store.dispatch(Hn({}));if(t.error)throw new Error(t.error.message);return t.payload})}handleKeyDown(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui,{textSuggestions:o,selectedSuggestionIndex:i,selection:s}=this.state.input,{inlineSuggestions:a,showTextSuggestions:l}=this.settings,u=a?"below":"above",c=o.length>0;if(this.store.dispatch(S1(Ph(t))),!Vn(this.state)||t.key!=="Tab"&&!l)return;let p=()=>{n||!c||s&&(t.shiftKey||(this.store.dispatch(b1()),t.preventDefault()))},d=()=>{n||!c||a&&i<=0||s&&(t.shiftKey||(this.store.dispatch(E1()),t.preventDefault()))};switch(t.key){case"ArrowUp":u==="below"?d():p();break;case"ArrowDown":{u==="below"?p():d();break}case"Escape":{n||(this.store.dispatch(zd(-1)),this.store.dispatch(so({collapse:!0})),this.store.dispatch(aC(!0)),t.preventDefault());break}case"Tab":{t.preventDefault();let f=ys(this.state);if(!f)return;this.store.dispatch(nu(!1)),this.store.dispatch(mn({text:f.text,suggestion:f,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(this.settings.inlineSuggestions||this.state.input.selectedSuggestionIndex===-1)return;let f=ys(this.state);if(!f)return;this.store.dispatch(mn({text:f.text,suggestion:f,eventMetrics:{inputType:"space"},replace:"until-selection-end"}));break}case"Enter":{if(this.settings.inlineSuggestions||t.shiftKey||this.state.input.selectedSuggestionIndex===-1)return;let f=ys(this.state);if(!f)return;this.store.dispatch(mn({text:f.text,suggestion:f,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),t.preventDefault();break}default:}n&&r&&this.store.dispatch(so({collapse:!1}))}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(eo([]))}handlingTimeStart(){this.state.handlingTime.startTime||(j.info("Start handling time"),this.store.dispatch(Ck()))}handlingTimeStop(){this.state.handlingTime.startTime&&(j.info("Stop handling time"),this.store.dispatch(tf()))}logSendMessage(t){let n=Fk("input",this.state,{version:this.version});n&&(t&&(Object.assign(n,{text:t}),Object.assign(n,{lenTextTotal:t.length})),this.deepdeskApi.sendEventV1("Send Message",n),this.emit("send-message-event",n))}logHandlingTime(){let t=Dk(this.state,{version:this.version});t&&(this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch(kk()))}notifySubmit(t={}){var n;this.shouldAbort()||(this.store.dispatch(zo((n=t.text)!=null?n:this.state.input.text)),this.store.dispatch(C1()))}emit(t,n){let r=this.eventListeners[t];r&&r.forEach(o=>{try{o(n)}catch(i){j.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),j.error(i)}})}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),()=>{this.off(t,n)}}off(t,n){if(!t&&!n){this.eventListeners={};return}let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}setConversationQuery(t){this.dynamicThunkObject.conversationQuery=t}setPlatformVariables(t){this.store.dispatch(N1(t))}whenConversationLoaded(t){let n=o=>{var i;return(i=o.conversation.current)==null?void 0:i.id},r=()=>this.loadProfileConfig().then(()=>t());n(this.state)&&r(),this.subscribe(n,o=>{o&&r()})}overlayContainerFactory(t,n,r,o){let[i,s]=fu(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),this.unmountHandlers.push(()=>{(0,Xe.unmountComponentAtNode)(i),s(),i.remove()}),i}createInlineContainer(t,n){var a;let r=document.createElement("div");r.style.position="absolute",r.style.top="0px",r.style.left="0px",r.style.height="0px",r.style.width="0px";let o=document.createElement("div");o.style.display="none",o.style.position="absolute",o.style.height="0px",o.style.width="0px",o.style.backgroundColor="red",r.appendChild(o);let i=(a=t.ownerDocument.defaultView)==null?void 0:a.frameElement,s=i?i.ownerDocument.defaultView:null;if(i&&(s===window||(s==null?void 0:s.parent)===window)){let[l,u]=fu(i,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});l.dataset.testid=n,l.style.zIndex="2",l.appendChild(r),this.unmountHandlers.push(()=>{(0,Xe.unmountComponentAtNode)(o),u()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return Zo(o),o.dataset.testid=t,o.style.color=r.color,o.style.fontSize=r.fontSize,o.style.fontFamily=r.fontFamily,o.style.fontVariant=r.fontVariant,o.setAttribute("translate","no"),n.appendChild(o),this.unmountHandlers.push(()=>{(0,Xe.unmountComponentAtNode)(o),o.remove()}),o}storeMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(t,n),j.info(`Stored analytics for ${this.conversationId()}`)}catch(t){}}restoreMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=window.sessionStorage.getItem(t);if(!n)return;let r=JSON.parse(n);r.text.trim()===this.state.input.text.trim()?(j.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(T1(r.metrics))):j.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(t)}catch(t){}}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!rf(t))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let d=n,{customStyles:r,closestScrollSelector:o,floatingMenuParent:i,appendOverlayTo:s,inputMediator:a}=d,l=Z(d,["customStyles","closestScrollSelector","floatingMenuParent","appendOverlayTo","inputMediator"]),u={customStyles:r,closestScrollSelector:o,floatingMenuParent:i,appendOverlayTo:s};this.configure(l),this.settings.automaticHandlingTime&&this.setupHandlingTime(t),Zo(t),this.inputMediator=a||(li(t)?new pi(t):new di(t)),this.inputMediator.on("change",({plainText:f,rawHTML:h})=>{this.store.dispatch(Hd({text:f,html:h}))}),this.inputMediator.on("keyup",f=>{this.store.dispatch(x1(Ph(f)))}),this.inputMediator.on("keydown",f=>{this.handleKeyDown(f)}),this.inputMediator.on("paste",({pastedText:f,selectionText:h})=>{this.store.dispatch(w1({text:f,selectionText:h}))}),this.inputMediator.on("cut",({selectionText:f})=>{this.store.dispatch(v1(f))});let c;this.inputMediator.on("selection",f=>{clearTimeout(c),f===null?c=setTimeout(()=>{f!==null&&this.store.dispatch(Ud(f))},500):this.store.dispatch(Ud(f))}),this.inputMediator.on("disabled",()=>{var f;(f=this.inputMediator)==null||f.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{this.settings.detectSubmit&&this.notifySubmit()}),this.inputMediator.on("blur",()=>{this.store.dispatch(Lp(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(Lp(!0))}),this.renderSuggestions(t,u),this.subscribe(sl("inlineSuggestions"),()=>{this.renderSuggestions(t,u)});let p=this.renderOverlays(n);this.unmountHandlers.push(()=>{p.unmount()}),this.store.dispatch(Hd({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()})),this.store.dispatch(Ud(this.inputMediator.getSelection())),this.store.dispatch(Lp(this.inputMediator.isFocused)),this.unmountHandlers.push(()=>{this.state.input.text!==""&&this.storeMetrics()}),this.whenConversationLoaded(()=>{var f;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((f=this.state.conversation.current)==null?void 0:f.sessionId)}),this.isMounted=!0}subscribe(t,n){let r=t(this.store.getState());return this.store.subscribe(()=>{let o=t(this.store.getState());o!==r&&(r=o,n(r))})}unmount(){var t,n,r,o;(t=this.inlineSuggestions)==null||t.unmount(),(n=this.aboveSuggestions)==null||n.unmount(),(r=this.floatingMenu)==null||r.unmount(),this.unmountHandlers.forEach(i=>i()),this.unmountHandlers=[],(o=this.inputMediator)==null||o.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderSuggestions(t,n){var r,o,i;(r=this.floatingMenu)==null||r.unmount(),(o=this.inlineSuggestions)==null||o.unmount(),(i=this.aboveSuggestions)==null||i.unmount(),this.settings.floatingMenu&&(this.floatingMenu=this.renderFloatingMenu(t,n)),this.settings.inlineSuggestions?this.inlineSuggestions=this.renderInlineSuggestions(t,n):this.aboveSuggestions=this.renderAboveSuggestions(t,n)}renderInlineSuggestions(t,n){let{customStyles:r}=n,o=this.createInlineContainer(t,"deepdesk-caret");(0,Xe.render)((0,He.jsx)(ai,{store:this.store,customStyles:r,children:(0,He.jsx)(Uo,{broadcastEvents:this.broadcastEvents,children:(0,He.jsx)(gC,{})})}),o);let i=s=>{s?(o.style.display="block",o.style.top=`${s.top}px`,o.style.left=`${s.left}px`):o.style.display="none"};return this.inputMediator.on("caretposition",i),{unmount:()=>{var s;(0,Xe.unmountComponentAtNode)(o),(s=this.inputMediator)==null||s.off("caretposition",i),o.remove()}}}renderAboveSuggestions(t,n){let{customStyles:r,closestScrollSelector:o,appendOverlayTo:i}=n,s=o&&mv(t,o)||void 0,a=this.overlayContainerFactory("deepdesk-tab-completion",s||t,{appendTo:i,closestScrollElement:s,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),l=this.overlayContainerFactory("deepdesk-suggestions-overlay",s||t,{appendTo:i},r==null?void 0:r.suggestionsRootNode);return(0,Xe.render)((0,He.jsx)(ai,{store:this.store,customStyles:r,children:(0,He.jsx)(Uo,{broadcastEvents:this.broadcastEvents,children:(0,He.jsx)(UC,{inputElement:t})})}),a),(0,Xe.render)((0,He.jsx)(ai,{store:this.store,customStyles:r,children:(0,He.jsx)(Uo,{broadcastEvents:this.broadcastEvents,children:(0,He.jsx)(TC,{onLogIn:()=>this.loginViaPopup().catch(u=>j.warn(u.message))})})}),l),{unmount(){(0,Xe.unmountComponentAtNode)(a),(0,Xe.unmountComponentAtNode)(l),a.remove(),l.remove()}}}renderFloatingMenu(t,n){let{customStyles:r,closestScrollSelector:o,appendOverlayTo:i,floatingMenuParent:s}=n,a=o&&mv(t,o)||void 0,l=this.overlayContainerFactory("floating-menu",a||t,{appendTo:s!=null?s:i},r==null?void 0:r.floatingMenuParent);return(0,Xe.render)((0,He.jsx)(ai,{store:this.store,customStyles:r,children:(0,He.jsx)(Uo,{broadcastEvents:this.broadcastEvents,children:(0,He.jsx)(iC,{onLogIn:()=>this.loginViaPopup().catch(u=>j.warn(u.message))})})}),l),{unmount(){(0,Xe.unmountComponentAtNode)(l),l.remove()}}}renderOverlays(t){let{customStyles:n}=t,r=this.createContainer("deepdesk-overlays");return(0,Xe.render)((0,He.jsx)(ai,{store:this.store,customStyles:n,children:(0,He.jsx)(Uo,{broadcastEvents:this.broadcastEvents,children:(0,He.jsx)(eC,{})})}),r),{unmount(){(0,Xe.unmountComponentAtNode)(r),r.remove()}}}renderWidget(t,n={}){if(this.widgetRoot&&j.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:i}=n;this.widgetRoot=t,this.configure({showImages:o,isEmbedded:i}),(0,Xe.render)((0,He.jsx)(ai,{store:this.store,customStyles:r,children:(0,He.jsx)(Uo,{broadcastEvents:this.broadcastEvents,children:(0,He.jsx)(mk,{onLogIn:()=>this.loginViaPopup().catch(s=>j.warn(s.message))})})}),t),this.whenConversationLoaded(()=>{var s;this.broadcastEvents.setSessionId((s=this.state.conversation.current)==null?void 0:s.sessionId)})}unmountWidget(){this.widgetRoot&&(0,Xe.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(t){let n=af(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){zk(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(()=>P(this,null,function*(){yield this.store.dispatch(Al());let t=Bo(this.state);t&&(yield this.store.dispatch(Tl()),this.store.dispatch(Ld({showSearch:t.search,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:!!t.summarizerAssistantNew||t.summarizer,showKnowledgeSearch:!!t.knowledgeAssistantNew||!!t.knowledgeAssistant,recommendTextSuggestions:t.recommendTextSuggestions})))})),this.loadProfileConfigPromise)}loginViaPopup(t){return P(this,null,function*(){return new Promise((n,r)=>{let o=new MessageChannel,i=o.port1,s=this.settings.adminUrl,a=new URL(t!=null&&t.url?t==null?void 0:t.url:`${s}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let l=!1,u=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",p),clearInterval(d)};i.onmessage=f=>P(this,null,function*(){var h,v;if((h=f.data)!=null&&h.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((v=f.data)==null?void 0:v.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(dl),l=!0,o.port1.close(),n()}catch(m){console.error(m),r(m)}finally{l=!0,u()}});let c=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");c===null&&r(new Error("Popup blocked by browser"));let p=f=>P(this,null,function*(){var h;if(f.origin===a.origin)switch((h=f.data)==null?void 0:h.type){case"deepdesk-popup-loaded":{try{let v=JSON.stringify({type:"deepdesk-popup-create-channel"});c==null||c.postMessage(v,a.origin,[o.port2])}catch(v){j.error("Error posting message to popup",v),r(v)}break}case"deepdesk-popup-error":{u(),f.data.message==="Timeout"&&j.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(f.data.message));break}}});window.addEventListener("message",p);let d=setInterval(()=>{c&&!c.closed||(u(),l||r(new Error("Popup closed by user")))},200);this.unmountHandlers.push(u)})})}translateMessages(t){return this.deepdeskApi.translateMessages(t)}checkForTrialMode(t){return P(this,null,function*(){try{let{account:n}=yield this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(j.info("Trial is active"),!(yield this.deepdeskApi.checkUserExists(t)))throw new Error("User is not in trial");this.shouldRender=!0}catch(n){let{message:r}=n;j.info(r),this.shouldRender=!1}})}refreshWidgetSuggestions(){return P(this,null,function*(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=Ll(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch(vn()):_u.includes(r)||this.store.dispatch(En(r))})}catch(r){this.handleError(r)}})}};$s.version="15.1.1-beta.3",$s.count=0;var mu=$s;function S_(e){return P(this,null,function*(){var o,i,s;let n=yield((o=e.fetch)!=null?o:window.fetch)(e.url),r=yield n.blob();return new File([r],e.name,{type:(s=(i=e.mimeType)!=null?i:n.headers.get("Content-Type"))!=null?s:"image/jpeg"})})}function Xk(e,t){return P(this,null,function*(){let n=yield S_(t),r=new Event("change",{bubbles:!0,cancelable:!0});try{Object.defineProperty(e,"files",{configurable:!0,get:()=>[n]}),e.dispatchEvent(r)}finally{Object.hasOwn(e,"files")&&delete e.files}})}function Zk(e,t,n){return P(this,null,function*(){yield new Er(e).authenticateWithKey(t,n)})}function Jk(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function eR(r,o){return P(this,arguments,function*(e,t,n={}){var p,d;let{value:i}=e,{start:s,end:a}=(p=n.replace)!=null?p:{start:0,end:i.length},l=`${i.slice(0,s)}${t}${i.slice(a)}`,u=(d=n.selectionAfter)!=null?d:{start:s+t.length,end:s+t.length},c=()=>{if(n.setValue)return n.setValue(l);e.value=l};return Promise.resolve(c()).then(()=>{e.selectionStart=u.start,e.selectionEnd=u.end,e.blur(),e.focus()})})}function tR(r,o){return P(this,arguments,function*(e,t,n={}){let i=n.replace?uo(e,n.replace.start,n.replace.end):Us(e),s,a=()=>{if(n.setRange)return n.setRange(i.cloneRange());i.deleteContents(),s=document.createElement("span"),i.insertNode(s),n.insertBRs!==!1?t.split(`
|
|
83
|
+
`);let h=d?r:0,v=f?Math.min(i,c.childNodes.length):c.childNodes.length;for(let m=h;m<v&&(u(c.childNodes[m]),a!==2);m++);break}default:break}f&&(a=2)}return u(e),l}var hk=(s=>(s.CUT="Cut",s.BACKSPACE="Backspace",s.DELETE="Delete",s.ERASEEOF="EraseEof",s.UNDO="Undo",s.CLEAR="Clear",s))(hk||{}),br=class{constructor(t){this.element=t;this.isFocused=!1;this.isActive=!0;this.isDisposed=!1;this.eventListeners={};this.disposeHandlers=[];this.cachedText="";this.cachedCaretPosition=null;this.cachedSelection={start:0,end:0};this.cachedHTML="";this.isSubmitting=!1;this.isPossibleClearInputAction=!1;this.cachedText=this.getText(),this.cachedHTML=this.getHTML(),this.cachedSelection=this.getSelection(),this.listen()}addEventListener(t,n){let r=o=>{n(o)};this.element.addEventListener(t,r),this.disposeHandlers.push(()=>{this.element.removeEventListener(t,r)})}removeEventListener(t,n){this.element.removeEventListener(t,n)}handleInteraction(){let t=this.getText(),n=this.getHTML(),r=this.getSelection(),o=this.cachedCaretPosition===null;if(!this.isActive||(t===""&&this.cachedText!==""&&!this.isPossibleClearInputAction&&this.emit("submit"),t!==this.cachedText?(this.cachedText=t,this.cachedHTML=n,o=!0,this.emit("change",{plainText:t,rawHTML:n})):n!==null&&n!==this.cachedHTML&&(this.cachedHTML=n,o=!0,this.emit("change",{plainText:t,rawHTML:n})),(r.start!==this.cachedSelection.start||r.end!==this.cachedSelection.end)&&(this.cachedSelection=r,o=!0,this.emit("selection",r)),!o))return;let i=this.getCaretPosition();Jr(i,this.cachedCaretPosition)||(this.cachedCaretPosition=i,this.emit("caretposition",i))}handleClick(){this.handleInteraction()}handleFocus(){let t=!this.isFocused;this.isFocused=!0,t&&this.emit("focus"),this.handleInteraction()}handleBlur(){this.isPossibleClearInputAction=!1;let t=this.isFocused;this.isFocused=!1,t&&this.emit("blur")}handleKeyDown(t){let{key:n,ctrlKey:r,metaKey:o}=t;this.isPossibleClearInputAction=Object.values(hk).includes(n)||n.toLowerCase()==="z"&&(r||o),this.emit("keydown",t)}handleKeyUp(t){this.handleInteraction(),this.emit("keyup",t)}handleCut(){this.isPossibleClearInputAction=!0,this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(t){var r,o;let n=((r=t.clipboardData)==null?void 0:r.getData("text"))||((o=t.clipboardData)==null?void 0:o.getData("text/plain"))||"";this.emit("paste",{pastedText:n,selectionText:this.getSelectedText()})}listen(){this.addEventListener("keydown",n=>this.handleKeyDown(n)),this.addEventListener("keyup",n=>this.handleKeyUp(n)),this.addEventListener("input",()=>this.handleInteraction()),this.addEventListener("change",()=>this.handleInteraction()),this.addEventListener("focus",()=>this.handleFocus()),this.addEventListener("blur",()=>this.handleBlur()),this.addEventListener("cut",()=>this.handleCut()),this.addEventListener("paste",n=>this.handlePaste(n)),this.addEventListener("click",()=>this.handleInteraction()),document.activeElement===this.element&&(this.isFocused=!0);let t=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});t.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{t.disconnect()})}focus(){this.element.focus()}emit(t,...n){this.isDisposed||this.eventListeners[t]&&this.eventListeners[t].forEach(r=>{r(...n)})}on(t,n){this.isDisposed||(this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n))}off(t,n){if(!this.eventListeners[t])return;let r=this.eventListeners[t].indexOf(n);r!==-1&&this.eventListeners[t].splice(r,1)}activate(){let t=this.isActive===!1;this.isActive=!0,t&&this.handleInteraction()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(t=>t()),this.eventListeners={},this.isDisposed=!0}};function yk(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var di=class extends br{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),pu(this.element,n)}getHTML(){return this.element.innerHTML||""}getRange(){var s;let n=this.getRootNode();if(n.activeElement!==this.element)return null;let r="getSelection"in n?n.getSelection():window.getSelection();if(!r)return null;let o="getComposedRanges"in r&&n instanceof ShadowRoot?(s=r.getComposedRanges(n))==null?void 0:s[0]:r.rangeCount>0?r.getRangeAt(0):null;if(!o)return null;let i=this.element.ownerDocument.createRange();return i.setStart(o==null?void 0:o.startContainer,o==null?void 0:o.startOffset),i.setEnd(o==null?void 0:o.endContainer,o==null?void 0:o.endOffset),!i||!this.element.contains(i.startContainer)||!this.element.contains(i.endContainer)?null:i}getCaretPosition(){let n=this.getRange();if(!n||!n.collapsed||!("getBoundingClientRect"in n))return null;let r=n.getBoundingClientRect();return!yk(r)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),r=n.getBoundingClientRect(),n.deleteContents(),!yk(r))?null:{top:r.top+r.height,left:r.left}}getSelection(){let n=this.getRange();if(n)return du(this.element,n);let r=this.lastKnownSelection;if(r&&gk(this.element,r.start,r.end))return r;let o=Us(this.element);return o.collapse(!1),du(this.element,o)}getSelectedText(){let{start:n,end:r}=this.getSelection();return pu(this.element,uo(this.element,n,r))}listen(){super.listen();let n=new MutationObserver(i=>{var s,a;i.length===2&&i[0].addedNodes.length===1&&((s=i[0].addedNodes[0])==null?void 0:s.textContent)==="\u2060"&&((a=i[1].removedNodes[0])==null?void 0:a.textContent)==="\u2060"||setTimeout(()=>{this.handleInteraction()},0)});n.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0}),this.disposeHandlers.push(()=>n.disconnect());let r=this.element.isContentEditable,o=new MutationObserver(()=>{this.element.isContentEditable!==r&&(r=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>o.disconnect())}};var o_=["direction","boxSizing","width","height","overflowX","overflowY","borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth","borderStyle","paddingTop","paddingRight","paddingBottom","paddingLeft","fontStyle","fontVariant","fontWeight","fontStretch","fontSize","fontSizeAdjust","lineHeight","fontFamily","textAlign","textTransform","textIndent","textDecoration","letterSpacing","wordSpacing","tabSize"];function vk(e,t){let n="mozInnerScreenX"in window,r=document.createElement("div");r.id="input-textarea-caret-position-mirror-div";let o=r.style,i=window.getComputedStyle(e),s=e.ownerDocument.body;o.whiteSpace="pre-wrap",o.wordWrap="break-word",o.position="absolute",o.visibility="hidden",o_.forEach(function(c){o[c]=i[c]}),n?e.scrollHeight>parseInt(i.height)&&(o.overflowY="scroll"):o.overflow="hidden",r.textContent=e.value.substring(0,t);let a=document.createElement("span");a.textContent=e.value.substring(t)||".",r.appendChild(a),s.appendChild(r);let l=e.getBoundingClientRect(),u={top:l.top-e.scrollTop+a.offsetTop+parseInt(i.borderTopWidth)+a.offsetHeight,left:l.left-e.scrollLeft+a.offsetLeft+parseInt(i.borderLeftWidth)};return s.removeChild(r),u}var pi=class extends br{constructor(){super(...arguments);this.lastKnownSelection=null}getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:n,selectionEnd:r}=this.element;return{start:n,end:r}}getSelectedText(){let n=this.getSelection();return n?this.getText().slice(n.start,n.end):""}getCaretPosition(){return vk(this.element,this.element.selectionEnd)}listen(){super.listen();let n=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var i;return(i=n==null?void 0:n.get)==null?void 0:i.call(this.element)},set:i=>{var s;(s=n==null?void 0:n.set)==null||s.call(this.element,i),this.handleInteraction()}}),this.addEventListener("scroll",()=>{this.emit("caretposition",this.getCaretPosition())});let r=this.element.disabled,o=new MutationObserver(()=>{this.element.disabled!==r&&(r=this.element.disabled,this.emit(r?"disabled":"enabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>o.disconnect())}};function Sk(e,t,n){let r=`deepdesk-iframe-${e}`,o=document.getElementById(r);if(o)return o;let i=document.createElement("iframe"),s=new URL(t);return Object.entries(n).forEach(([a,l])=>{s.searchParams.append(a,l)}),i.style.position="absolute",i.style.left="-999em",i.style.width="0px",i.style.height="0px",i.tabIndex=-1,i.id=r,i.title=`iframe-${e}`,i.src=s.toString(),window.document.body.appendChild(i),i}function i_(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(t){return e}}var sv=class{constructor(t){this.name=t;this.disposeHandlers=[];this.broadcastChannel=new BroadcastChannel(t)}onMessage(t){this.broadcastChannel.addEventListener("message",t),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",t)})}postMessage(t){this.broadcastChannel.postMessage(JSON.stringify(t))}close(){this.disposeHandlers.forEach(t=>t()),this.broadcastChannel.close()}},av=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.disposeHandlers=[];this.iframe=Sk(t,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}onMessage(t){window.addEventListener("message",t),this.disposeHandlers.push(()=>{window.removeEventListener("message",t)})}postMessage(t){var n;(n=this.iframe.contentWindow)==null||n.postMessage(JSON.stringify(t),this.targetOrigin)}close(){var t;this.disposeHandlers.forEach(n=>n()),(t=this.iframe)==null||t.remove()}},lv=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.eventMap,this.sessionId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setSessionId(t){this.sessionId!==t&&(this.cleanup(),j.info("Set sessionId",t),this.sessionId=t,this.channel=this.createChannel(t))}createChannel(t){let n=this.params.createCustomChannel?this.params.createCustomChannel(t):this.isCrossOrigin?new av(t,this.deepdeskUrl,{debug:!0}):new sv(t),r=o=>{var s,a;if(o.origin!==this.deepdeskUrl)return;let i=i_(o.data);typeof i!="object"||i.type!=="event"||i.channel!==t||(j.info("Received broadcast event",this.sessionId,o),(a=(s=this.eventMap)[i.name])==null||a.call(s,i.payload))};return n.onMessage(r),n}send(t,n,r){var s,a;j.info("Broadcast event",{sessionId:this.sessionId,name:t,payload:n});let o={type:"event",name:t,payload:n};r!==!1&&((a=(s=this.eventMap)[t])==null||a.call(s,n));let i=this.sessionId==="deepdesk-general"?this.defaultChannel:this.channel;i==null||i.postMessage(L(T({},o),{channel:this.sessionId}))}cleanup(t=!1){var n,r;(n=this.channel)==null||n.close(),delete this.channel,t&&((r=this.defaultChannel)==null||r.close(),delete this.defaultChannel)}},xk=lv;function s_(e){return e.replace(/(_\w)/g,t=>t[1].toUpperCase())}function ke(e){return Array.isArray(e)?e.map(ke):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>L(T({},t),{[s_(n)]:ke(e[n])}),{}):e}function a_(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function Ye(e){return Array.isArray(e)?e.map(Ye):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>L(T({},t),{[a_(n)]:Ye(e[n])}),{}):e}var js=class extends Error{constructor(n,r){super(n);this.body=r;this.name="CustomError"}};var uv=e=>new Promise(t=>{setTimeout(t,e)});var Bs=class extends js{constructor(){super(...arguments);this.name="ClientError"}},dv=class extends js{constructor(){super(...arguments);this.name="ServerError"}},cv=new Map;function l_(e){return P(this,null,function*(){if(e.status===204)return e.text().catch(()=>{}),null;let t=e.headers.get("content-type");if(t&&t.includes("application/json"))return e.json();let n=yield e.text();return n===""?null:(j.warn("Unexpected response body:",n.slice(0,20)),JSON.parse(n))})}var co=class co{constructor(t="",n={}){this.baseUrl=t;this.options=n;this.latestRequestByUrl={};this.fetch=window.fetch.bind(window);n.fetch&&(this.fetch=n.fetch)}patchFetch(t){this.fetch=t(this.fetch)}setCsrfToken(t){this.csrfToken=t}request(t,n={}){return new Promise((r,o)=>{let i={isAborted:!1,reject:o},s=`${this.baseUrl}${t}`,a=this.fetch,l=n.method===void 0||n.method.toLowerCase()==="get",E=n,{useCache:u=!1,abortLatest:c=!1,attempts:p=1,retryDelay:d=500,refreshTokenOn401:f=!0,retryOnError:h=R=>R instanceof TypeError,retryOnResponse:v=R=>R.status>=500,version:m=null}=E,g=Z(E,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]);if(u)if(l){if(cv.has(s)){r(cv.get(s));return}}else throw new Error(`Can't use 'useCache' for ${n.method}`);let y=L(T({credentials:"include"},g),{headers:T({Accept:"application/json","Content-Type":"application/json"},g.headers)});!l&&this.csrfToken&&(y.headers=L(T({},y.headers),{"X-CSRFToken":this.csrfToken})),typeof m=="string"&&(y.headers=L(T({},y.headers),{"X-Deepdesk-API-Version":m}));let S=p,w=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[s]&&c&&(this.latestRequestByUrl[s].isAborted=!0,this.latestRequestByUrl[s].reject(new Error("Aborted"))),this.latestRequestByUrl[s]=i;let k=()=>P(this,null,function*(){return S--,a(s,y).then(R=>P(this,null,function*(){return v(R)&&!i.isAborted&&S>0?(yield uv(d),k()):R.status===401&&f===!0&&w===!1?(w=!0,yield this.refreshToken(),k()):R})).catch(R=>P(this,null,function*(){if(h(R)&&!i.isAborted&&S>0)return yield uv(d),k();throw R}))});k().then(R=>P(this,null,function*(){let A=yield l_(R);if(delete this.latestRequestByUrl[s],R.status>=500){o(new dv("Server Error",A));return}else if(R.status===401){o(new Bs("Unauthorized",A));return}else if(R.status===403){o(new Bs("Forbidden",A));return}else if(R.status===404){o(new Bs("Not Found",A));return}else if(R.status>=400){o(new Bs("Bad Request",A));return}u&&cv.set(s,A),r(A)})).catch(R=>{o(R)})})}validateToken(){return P(this,null,function*(){let{has_valid_access_token:t}=yield this.get("/auth/validate");if(!t)try{yield this.refreshToken()}catch(r){return!1}let{is_logged_in:n}=yield this.get("/apis/admin/session/validate/");return!!n})}refreshToken(){return co.refreshingToken||(co.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{co.refreshingToken=null},1e3*60)})),co.refreshingToken}get(t,n){return this.request(t,n)}post(t,n,r){return this.request(t,T({method:"POST",body:JSON.stringify(n)},r))}patch(t,n,r){return this.request(t,T({method:"PATCH",body:JSON.stringify(n)},r))}put(t,n,r){return this.request(t,T({method:"PUT",body:JSON.stringify(n)},r))}delete(t,n){return this.request(t,T({method:"DELETE"},n))}};co.refreshingToken=null;var fi=co;var wk;(t=>{let e;(s=>(s.SEND_MESSAGE="Send Message",s.HANDLING_TIME="Handling Time",s.ADD_TO_PERSONAL_COLLECTION="Add to personal collection",s.DELETE_FROM_PERSONAL_COLLECTION="Delete from personal collection"))(e=t.EventType||(t.EventType={}))})(wk||(wk={}));function ef(e){return L(T({},ke(e)),{tags:e.tags})}var mi=class mi{constructor(t,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new fi(t,{fetch:n.fetch}),this.client.patchFetch(r=>(o,i)=>P(this,null,function*(){let s=yield r(o,i);return this.handleDeepdeskVersionHeaders(s),s}))}preflight(){return P(this,null,function*(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=yield this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(mi.exchangeTokenPromise||(mi.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),mi.exchangeTokenPromise):Promise.resolve()})}createConversation(t){return P(this,null,function*(){yield this.preflight(),j.info(`Creating conversation for session ${t.sessionId} and agent ${t.agentId}`);let n=yield this.client.post("/api/conversations",L(T({},Ye(t)),{tags:t.tags}),{version:"v2"});return ef(n)})}getMe(){return P(this,null,function*(){let t=yield this.client.get("/apis/admin/session/me/");return ke(t)})}postIdentity(t){return P(this,null,function*(){yield this.client.post("/apis/admin/session/me/identities/",Ye(t))})}patchMe(t){return P(this,null,function*(){let n=yield this.client.patch("/apis/admin/session/me/",Ye(t));return ke(n)})}getProfile(t){return P(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${t}/`,{useCache:!0});return ke(n)})}getKnowledgeAssistant(t){return P(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{useCache:!0});return ke(n)})}getContentTypes(){return P(this,null,function*(){let t=yield this.client.get("/apis/admin/content-types/",{useCache:!0});return ke(t)})}getAccount(){return P(this,null,function*(){let t=yield this.client.get("/apis/admin/account/",{useCache:!0});return ke(t)})}getPlatformConfig(t){return P(this,null,function*(){let n=t!==void 0?`/platform/config/${t}/`:"/platform/config/",{config:r}=yield this.client.get(n,{useCache:!0});return ke(r)})}checkUserExists(t){return P(this,null,function*(){let{exists:n}=yield this.client.get(`/apis/admin/users/exists?external_id=${t}`,{version:"v1"});return n})}getConversationBySessionId(r){return P(this,arguments,function*(t,n={}){yield this.preflight(),j.info(`Getting conversation for session ${t}`);let{attempts:o=1,retryDelay:i=1e3}=n,s=yield this.client.get(`/api/conversations/by_session_id/${t}`,{attempts:o,retryDelay:i,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"});return j.info(`Successfully retrieved conversation ${s.id} for session ${t}`),ef(s)})}isConversationSupported(r){return P(this,arguments,function*(t,n={}){j.info(`Check if conversation for session ${t} is supported`);let{attempts:o=1,retryDelay:i=1e3}=n;return(yield this.client.get(`/api/conversations/by_session_id/${t}/active_profile`,{attempts:o,retryDelay:i,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"})).has_active_profile})}updateConversation(t,n){return P(this,null,function*(){let r=Ye(n);n.tags&&(r.tags=n.tags);let o=yield this.client.put(`/api/conversations/${t}`,r,{version:"v2"});return ef(o)})}postMessages(t,n){return P(this,null,function*(){return(yield this.client.post(`/api/conversations/${t}/messages`,n.map(o=>L(T({},Ye(o)),{tags:o.tags})),{version:"v2"})).map(o=>ef(o))})}sendEvent(t,n){return P(this,null,function*(){let s=n,{data:r}=s,o=Z(s,["data"]),i=Object.entries(this.latestReceivedDeepdeskVersions).reduce((a,[l,u])=>L(T({},a),{[l]:u}),{});return this.client.post("/api/events",Ye(L(T(T({},i),o),{data:r,name:t})),{version:"v2"})})}sendEventV1(t,n){return P(this,null,function*(){let r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((o,[i,s])=>L(T({},o),{[i]:s}),{});return this.client.post("/api/events",{event:t,data:Ye(T(T({},n),r))},{version:"v1"})})}getEntities(t){return P(this,null,function*(){return(yield this.client.post("/api/entities",{messages:t.filter(r=>r.text)},{version:"v1"})).entities})}getTemporaryExchangeToken(){return P(this,null,function*(){return(yield this.client.get("/auth/exchange-token")).jwt})}exchangeTokenForAccessCookie(t){return P(this,null,function*(){return this.client.post("/apis/admin/session/jwt/",{jwt:t}).catch(n=>{throw j.warn(`Invalid token '${t}'`),n})})}authenticateWithKey(t,n){return P(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/api-key/",Ye(n),{refreshTokenOn401:!1,headers:{apikey:t}})})}getTextSuggestions(o){return P(this,arguments,function*(t,n={},r){return r==="sticky-messages"?this.getPinnedMessages(t):(yield this.client.post(`/api/conversations/${t}/recommend/${r}`,Ye(n),{abortLatest:!0,version:"v1"})).map(s=>L(T({},ke(s)),{text:s.text||s.url||s.message,source:r,type:r})).filter((s,a,l)=>a===l.findIndex(u=>u.text===s.text))})}isLoggedIn(){return P(this,null,function*(){return yield this.preflight(),this.client.validateToken()})}getAutocompleteSuggestions(t,n){return P(this,null,function*(){return(yield this.client.post(`/api/conversations/${t}/autocomplete`,Ye(n),{abortLatest:!0,version:"v1"})).map(o=>({score:1,source:o.source,sourceText:o.source_text,text:o.label,trainingJobs:o.training_jobs,searchKeywords:o.search_keywords,type:o.source})).filter((o,i,s)=>i===s.findIndex(a=>a.text===o.text))})}getPinnedMessages(t){return P(this,null,function*(){let n=yield this.client.get(`/api/conversations/${t}/sticky-messages`,{abortLatest:!0,version:"v1"});return ke(n).map(r=>L(T({},r),{text:r.message,source:"sticky-messages",type:"pinned-message"}))})}getStyleSuggestions(t){return P(this,null,function*(){let n=yield this.client.post("/api/style-suggestions",Ye(t),{abortLatest:!0,version:"v1"});return ke(n)})}search(t){return P(this,null,function*(){let n=yield this.client.post(`/api/profiles/${t.profile}/search`,Ye(t),{version:"v2"});return ke(n)})}knowledgeAssist(i,s,a){return P(this,arguments,function*(t,n,r,o={}){let l=yield this.client.post(`/api/knowledge-assist/assistants/${r}/search`,Ye({question:t.question,doNotKnowAnswer:t.doNotKnowAnswer,customerInstruction:t.customerInstruction,chatHistory:n.map(u=>({question:u.question,answer:u.answer.answer})),agentId:o.agentId,conversationId:o.conversationId}),{version:"v2"});return ke(l)})}requestLoginByEmail(t){return P(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:t});return ke(n)})}requestPasswordlessToken(){return P(this,null,function*(){let t=yield this.client.get("/apis/admin/session/passwordless/request/");return ke(t.token)})}getCsrfToken(){return P(this,null,function*(){let{token:t}=yield this.client.get("/apis/admin/session/csrf/");return t})}verifyLoginToken(t){return P(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/login/",{token:t});return ke(n)})}getSummary(r){return P(this,arguments,function*(t,n={}){let o=yield this.client.post("/api/summary",{conversation:{messages:t.filter(i=>i.text&&i.source),agent_id:n.agentId,id:n.externalConversationId},prompt_instruction:n.promptInstruction,model:n.model},{version:"v1"});return ke(o)})}evaluateAssistant(t,n){return P(this,null,function*(){var a;let r=new URLSearchParams,{expectFormat:o="text"}=n||{};if(o.startsWith("json-schema:")){let l=o.replace("json-schema:","");r.append("expect_response_format","json-schema"),r.append("expect_response_format_schema",l)}else r.append("expect_response_format",o);n!=null&&n.externalConversationId&&r.append("external_conversation_id",n.externalConversationId);let i=n!=null&&n.threadId?`/api/v2/assistants/${t}/threads/${n==null?void 0:n.threadId}/evaluate?${r.toString()}`:`/api/v2/assistants/${t}/evaluate?${r.toString()}`,s=yield this.client.post(i,{input:(a=n==null?void 0:n.input)!=null?a:{},conversation:n==null?void 0:n.transcript});return ke(s.output)})}createAssistantThread(t){return P(this,null,function*(){let{assistantCode:n}=t,r=yield this.client.post(`/apis/admin/assistants/${n}/threads/`,{});return ke(r)})}postMessageToAssistantThread(t){return P(this,null,function*(){let{assistantCode:n,threadId:r,message:o}=t,i=yield this.client.post(`/apis/admin/assistants/${n}/threads/${r}/messages/`,{content:o,role:"user"});return ke(i)})}translateMessages(t){return P(this,null,function*(){let n=yield this.client.post("/api/translate",Ye(t),{version:"v2"});return ke(n)})}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),i=o.match(I0);if(!n||!i)return;let s=i[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[s];a&&n&&a!==n&&j.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[s]=n})}};mi.exchangeTokenPromise=null;var Er=mi;var bk={startTime:null,stopTime:null},Ek=e=>e.handlingTime,Tk=te({name:"handlingTime",initialState:bk,reducers:{handlingTimeStart(e){if(e.startTime&&!e.stopTime)throw new Error("Timing already started");e.startTime=new Date,e.stopTime=null},handlingTimeStop(e){if(!e.startTime)throw new Error("Timing not started");e.stopTime=new Date},handlingTimeReset(e){e.startTime=null,e.stopTime=null}},extraReducers:e=>{e.addCase(Fe,()=>bk)}}),{handlingTimeStart:Ck,handlingTimeStop:tf,handlingTimeReset:kk}=Tk.actions,Rk=Tk.reducer;var Pk=(e={})=>{let t=T({onAuthError:ms(!1)},e);return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var nf={list:{keywordMatches:[]},fetchState:"idle"};var gi=Q("styleSuggestions/getAll",(n,r)=>P(void 0,[n,r],function*({text:e},t){var l;let{deepdeskAPI:o}=t.extra,i=t.getState(),{showStyleSuggestions:s}=i.settings,a=(l=i.conversation.current)==null?void 0:l.profileCode;if(!s)return nf.list;if(!a)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:a,message:e})})),u_=te({name:"styleSuggestions",initialState:nf,reducers:{},extraReducers:e=>{e.addCase(gi.pending,t=>{t.fetchState="loading"}).addCase(gi.rejected,t=>{t.fetchState="error"}).addCase(gi.fulfilled,(t,n)=>{t.fetchState="done",Jr(t.list,n.payload)||(t.list=n.payload)}).addCase(zo,t=>{t.list=nf.list}).addCase(Fe,()=>nf)}}),Ak=u_.reducer;var Lk=(e={})=>{let t,n=!0,r=T({getStyleSuggestions:gi,debounce:500},e);return o=>i=>s=>{var f;let a=o.getState().input.text,l=i(s),u=o.getState();if(u.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:c}=u.settings;if(!((f=u.conversation.current)==null?void 0:f.id)||!c)return l;let{text:d}=u.input;return d===a&&!n||(clearTimeout(t),d==="")||(t=setTimeout(()=>{n=!1,o.dispatch(r.getStyleSuggestions({text:d}))},e.debounce)),l}};function c_(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var Ik=(e={})=>{let t=T({getTextSuggestions:En,getAutocompleteSuggestions:eu,debounce:200,check:Vn},e),n;return r=>o=>i=>{var v;let{input:s}=r.getState(),a=o(i),l=r.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:u,showTabCompletion:c}=l.settings,p=(v=l.conversation.current)==null?void 0:v.id,d=i.type===Rp.toString();if(!p||!u&&!c)return a;let{input:f}=l;return c_(f,s)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let m=hs(l);m===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(m))},d?0:t.debounce)),a}};var Ok=gi.fulfilled.toString();function d_(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let i=e.keywordMatches.filter(l=>l.keyword===o),s=t.keywordMatches.filter(l=>l.keyword===o),a=s.length-i.length;a<=0||r.push(...s.slice(0,a))}),r}var Nk=e=>t=>n=>r=>{var u;if(r.type!==Ok){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let i=t.getState(),s=i.styleSuggestions.list,a=(u=i.conversation)==null?void 0:u.current;if(o===s)return;let l=d_(o,s);r.type===Ok&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var p_=ed({assistants:mE,auth:r1,conversation:m1,contentTypes:hE,passwordlessToken:VC,entities:VE,knowledgeAssistant:uE,handlingTime:Rk,info:M1,input:k1,settings:Yb,profile:vE,search:U1,styleSuggestions:Ak,ui:uC,textSuggestions:GT});function Mk(e){return nb({reducer:p_,middleware:t=>[...t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI}},serializableCheck:!1}),Pk(),Ik({debounce:200}),Lk({debounce:500}),Nk(e.deepdeskAPI),...e.middleware?e.middleware:[]],preloadedState:e.preloadedState})}var f_=e=>{var t,n;return(n=(t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())!=null?n:"unknown"},m_=e=>t=>n=>r=>{var a,l,u,c,p,d;let o=t.getState(),i=sl("inlineSuggestions")(o);switch(r.type){case ms.toString():{!r.payload&&e.emit("logout",void 0);break}case vn.fulfilled.toString():r.payload.length>0&&e.sendEvent("entities found",{conversationId:(a=o.conversation.current)==null?void 0:a.id,data:{entities:r.payload}});break;case Jt.toString():e.sendEvent(r.payload.name,{conversationId:((l=r.payload.options)==null?void 0:l.includeConversationData)&&((u=o.conversation.current)==null?void 0:u.id),data:r.payload.data});break;case zo.toString():e.logSendMessage(r.payload);break;case ep.toString():e.emit("call-to-action",{cue:r.payload});break;case ur.fulfilled.toString():r.isBroadcasted||e.broadcast(Oh,r,!1);break;default:break}let s=n(r);switch(r.type){case zo.toString():e.handleAfterSendMessage(r.payload);break;case nu.toString():e.onUpdateShowTabHint(r.payload);break;case tf.toString():e.logHandlingTime();break;case"analytics/logEvent/fulfilled":{e.emit("event",r.meta.arg);break}case Dd.toString():{let{start:f,end:h}=o.input.selection;e.emit("replace",L(T({},r.payload),{replace:r.payload.replace==="selection"?{start:f,end:h}:{start:0,end:h}}));break}case mn.toString():{let{start:f,end:h}=o.input.selection;e.emit("select-suggestion",L(T({type:f_(r.payload.suggestion)},r.payload),{replace:r.payload.replace==="selection"?{start:f,end:h}:{start:0,end:h}})),i&&t.dispatch(eo([]));break}case Fd.toString():e.emit("select-image",r.payload),e.sendEvent("Image attached",{conversationId:(c=o.conversation.current)==null?void 0:c.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case eo.toString():{i&&r.payload.length>0&&t.dispatch(zd(0));break}case Hn.fulfilled.toString():{e.sendEvent("conversation summarized",{conversationId:(p=o.conversation.current)==null?void 0:p.id,data:{summary:r.payload,assistant:(d=t.getState().profile.data)==null?void 0:d.summarizerAssistantNew}});break}default:break}return s},_k=m_;function pv(e){return e.toISOString().replace("T"," ").replace("Z","")}var g_=(e,t)=>t.version,Dk=fn([vs,Fn,Ek,g_],(e,t,n,r)=>{if(!t)return j.warn("No conversationId for handling time metrics"),null;let{startTime:o,stopTime:i}=n;return!o||!i?(j.warn("No startTime and stopTime for handling time metrics"),null):{conversationId:t,clientVersion:r,agentId:e==null?void 0:e.agentId,agentName:e==null?void 0:e.agentName,agentEmail:e==null?void 0:e.agentEmail,timeStart:pv(o),timeStop:pv(i)}});function Fk(e,t,n){var A,M,Y,z;let r=(A=t.conversation.current)==null?void 0:A.id;if(!r)return j.warn("No conversationId for send message metrics"),null;let{text:o,metrics:{numCharsTyped:i,numCharsPasted:s,numCharsCut:a,numCharsDeleted:l,numPaste:u,agentStartedTypingTimestamp:c,externalTimeTotalSeconds:p,pastes:d,cuts:f,deletions:h,textSuggestions:v,offeredTextSuggestions:m}}=t[e],g=o.length,S=v.reduce((V,{text:me,searchTerm:Ue})=>V+me.length-(Ue?Ue.length:0),0),w=c!=null?c:Date.now(),k=(Date.now()-w)/1e3+(p||0),E=i/k,R=v.reduce((V,{searchTerm:me})=>V+(me?me.length:0),0);return{conversationId:r,source:"agent",text:o,clientVersion:n.version,pastes:d,cuts:f,deletions:h,lenTextTyped:i+R,lenTextTotal:g,lenTextAssisted:S,lenTextPasted:s,lenTextCut:a,lenTextDeleted:l,timeTotalSeconds:k,charsPerSecond:E,numPastes:u,textSuggestionsV2:v,suggestionsCounters:[{source:"gpt",countOffered:m.filter(V=>V.source==="gpt").length}],agentId:(M=t.info.agentInfo)==null?void 0:M.agentId,agentName:(Y=t.info.agentInfo)==null?void 0:Y.agentName,agentEmail:(z=t.info.agentInfo)==null?void 0:z.agentEmail}}function fv(e,t){var i;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return fv(r,t);let o=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;return o?fv(o,t):null}function mv(e,t){return fv(e,t)}function zk(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function h_(e){return typeof e=="object"&&e!==null&&"tagName"in e}function rf(e){return h_(e)&&(li(e)||Dp(e))}var Uk,Kn=new Map,y_=["bottom","height","left","right","top","width"],Hk=(e,t)=>!e&&!t?!1:e&&!t||!e&&t?!0:y_.some(n=>e[n]!==t[n]);function jk(e){var n,r,o;if(e.ownerDocument===document)return[];let t=(o=(r=(n=e.ownerDocument)==null?void 0:n.defaultView)==null?void 0:r.frameElement)!=null?o:null;return t?[t,...jk(t)]:[]}function Bk(e,t){return!e||!t?null:L(T({},e),{top:e.top+t.top,left:e.left+t.left})}var of=!1,Vk=()=>{of=!0;let e=[];if(Kn.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),Kn.delete(n);return}let r=n.getBoundingClientRect();Hk(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(Bk,t.rect):t.rect;Hk(n,t.totalRect)&&t.callbacks.forEach(r=>r(n)),t.totalRect=n}),Kn.size===0){of=!1;return}Uk=window.requestAnimationFrame(Vk)};function gv(e,t){let n=jk(e),r=[],o=n.map((i,s)=>gv(i,a=>{r[s]=a;let l=Kn.get(e);if(!l)return;let u=r.reduce(Bk,l.rect);l.callbacks.forEach(c=>c(u))}));return{observe(i=!0){if(o.forEach(s=>s.observe(!1)),Kn.has(e)){let s=Kn.get(e);s.callbacks.push(t),s.rect&&t(s.rect)}else Kn.set(e,{rect:void 0,callbacks:[t],parentRects:r});i&&!of&&Vk()},unobserve(){o.forEach(s=>s.unobserve());let i=Kn.get(e);if(i){let s=i.callbacks.indexOf(t);s>=0&&i.callbacks.splice(s,1),i.callbacks.length||Kn.delete(e),Kn.size||(cancelAnimationFrame(Uk),of=!1)}}}}var $k,qn=new Map,Wk=()=>{qn.forEach((e,t)=>{if(!t.isConnected){qn.delete(t);return}let{clientHeight:n,scrollHeight:r}=t,o=r>n;e.visible!==o&&(e.visible=o,e.callbacks.forEach(i=>i(e.visible)))}),qn.size!==0&&($k=window.requestAnimationFrame(Wk))};function Kk(e,t){return{observe(){let n=qn.size===0;qn.has(e)?qn.get(e).callbacks.push(t):qn.set(e,{visible:void 0,callbacks:[t]}),n&&Wk()},unobserve(){let n=qn.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||qn.delete(e),qn.size||cancelAnimationFrame($k)}}}}var hv=["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 yv(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function Vs(e){return parseFloat(e)}function sf(e){return Math.round(e*1e6)}function qk(e){return e/1e6}function vv(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=Vs(e.width),i=Vs(e.borderLeftWidth),s=Vs(e.borderRightWidth),a=Vs(e.paddingRight),l=qk(sf(o)-sf(i)-sf(s)),u=qk(sf(r));if(l-u>2){let c=l-u;n.style.paddingRight=`${a+c}px`}}function fu(e,t={}){var c,p;let n=t.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=(c=t.position)!=null?c:"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",Zo(n);let r=window.getComputedStyle(e),o=!0,i=()=>{n.scrollTop=e.scrollTop};yv(r,n,hv),vv(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",i));let s=Kk(e,()=>{yv(r,n,hv),vv(r,e,n),i(),setTimeout(i,0)}),a,l=!0,u=gv(e,d=>{if(d===null){t.onRemove&&t.onRemove(),n.remove();return}if(!l&&t.onMoveStart&&(Promise.resolve().then(()=>t.onMoveStart()),l=!0),clearTimeout(a),a=setTimeout(()=>{t.onMoveEnd&&t.onMoveEnd(),l=!1},200),d.height===0&&d.width===0){if(o===!0)return;t.onHide&&t.onHide(),n.style.display="none",o=!0;return}if(yv(r,n,hv),vv(r,e,n),i(),n.style.top=`${d.top}px`,n.style.left=`${d.left}px`,t.closestScrollElement&&t.closestScrollElement!==e){let f=t.closestScrollElement.getBoundingClientRect(),h=window.getComputedStyle(t.closestScrollElement),v=Vs(h.borderTopWidth),m=Vs(h.borderBottomWidth),g=f.top+v-d.top,y=d.top+d.height+-(f.top+f.height-m);n.style.clipPath=`inset(${g}px 0px ${y}px 0px)`}o&&(n.style.display="block",t.onShow&&t.onShow(),o=!1)});return t.appendTo?t.appendTo.appendChild(n):(p=e.parentElement)==null||p.appendChild(n),u.observe(),s.observe(),[n,()=>{e.removeEventListener("scroll",i),u.unobserve(),s.unobserve()}]}var Gk=(e,t)=>({value(){try{let n=sessionStorage.getItem(`dd-${e}`);if(!n)return t;try{return JSON.parse(n)}catch(r){return t}}catch(n){return t}},update(n){try{sessionStorage.setItem(`dd-${e}`,JSON.stringify(n))}catch(r){j.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function v_(e){return e.offsetParent!==null}function Qk(e){if(!v_(e))return!1;let t=e.getBoundingClientRect();return t.top>=0&&t.left>=0&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&t.right<=(window.innerWidth||document.documentElement.clientWidth)}function af(e,t,n=100){let r=Qk(e);t({isVisible:r});let o=setInterval(()=>{let i=Qk(e);i!==r&&(r=i,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var He=x(C());var Yk=Gk("showTabHint",!0),$s=class $s{constructor({deepdeskUrl:t,version:n=$s.version||"unknown",locale:r="en-US",token:o,fetch:i,productName:s,createCustomChannel:a}){this.inputMediator=null;this.eventListeners={};this.unmountHandlers=[];this.inlineSuggestions=null;this.aboveSuggestions=null;this.floatingMenu=null;this.widgetRoot=null;this.dynamicThunkObject={};this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;let l=t.replace(/\/api$/,"");this.deepdeskApi=new Er(l,{token:o,fetch:i}),this.version=n,this.instanceId=$s.count++;let u={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[_k({broadcast:(c,p,d)=>{this.broadcastEvents.send(c,p,d)},emit:(c,p)=>this.emit(c,p),handleAfterSendMessage:c=>this.handleAfterSendMessage(c),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:c=>this.logSendMessage(c),onUpdateShowTabHint:c=>Yk.update(c),sendEvent:(c,p)=>this.deepdeskApi.sendEvent(c,p)})]};this.store=Mk(u),this.broadcastEvents=new xk({debug:!0,deepdeskUrl:l,eventMap:j1(this.store),createCustomChannel:a}),this.store.dispatch(nu(Yk.value())),this.store.dispatch(Ld({locale:r,adminUrl:l,productName:s}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){var t;return(t=this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex])!=null?t:null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(j.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(j.warn("Profile has not been loaded (yet)"),!0):(j.warn("No conversation loaded (yet)"),!0)}login(){this.store.dispatch(ms(null)),this.store.dispatch(sr());let t=n=>gt(n)&&Xb(n)!=="loading";return new Promise(n=>{let r=this.subscribe(t,o=>{o&&(r(),n())});this.unmountHandlers.push(()=>{r()})})}isLoggedIn(){return P(this,null,function*(){return(yield this.store.dispatch(sr())).payload})}isConversationSupported(t,n){return P(this,null,function*(){return(yield this.store.dispatch(kh({sessionId:t,options:n}))).payload})}createConversation(t){return P(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(yield this.store.dispatch(Od(t))).payload})}getConversationBySessionId(t,n){return P(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(yield this.store.dispatch(Nd({sessionId:t,options:n}))).payload})}upsertConversation(t){return P(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(yield this.store.dispatch(Rh(t))).payload})}postMessages(t){return P(this,null,function*(){return(yield this.store.dispatch(_d(t))).payload})}updateConversation(t){return P(this,null,function*(){return(yield this.store.dispatch(Md(t))).payload})}resetConversation(){this.store.dispatch(Fe()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}configure(t){this.store.dispatch(Ld(t))}setVisitorInfo(t){this.store.dispatch(I1(t))}setCustomData(t){this.store.dispatch(O1(t))}setAgentInfo(t,n){return P(this,null,function*(){yield this.store.dispatch(ul(T(T({},t),n)))})}setAgentSettings(t){return P(this,null,function*(){yield this.store.dispatch(Ah(t))})}getAgentSettings(){return P(this,null,function*(){return(yield this.store.dispatch(Lh())).payload})}refresh(){return P(this,null,function*(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.store.dispatch(Hd({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()}));let t=[];return this.store.dispatch(Rp()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})})}notifyExternalSuggestion(t){this.store.dispatch(mn(t))}evaluateAssistant(t,n){return P(this,null,function*(){let c=n||{},{input:r={},transcript:o,showCuesInWidget:i=!0,includeTags:s,expectFormat:a}=c,l=Z(c,["input","transcript","showCuesInWidget","includeTags","expectFormat"]);Object.assign(r,l);let u=yield this.store.dispatch(ur({assistantCode:t,expectFormat:a||"json-schema:cues",transcript:o,includeTags:s,input:r,skipState:!i}));if(u.error)throw new Error(u.error.message);return u.payload})}evaluateConversationAssistant(t,n){return P(this,null,function*(){yield this.loadProfileConfig();let r={accepted:"conversationAcceptedAssistant","new-message":"conversationNewMessageAssistant",ended:"conversationEndedAssistant"},o=this.state.profile.data[r[t]];if(!o){j.warn(`No assistant set in profile for conversation event "${t}"`);return}yield this.evaluateAssistant(o,T({transcript:"stored-transcript",includeTags:!0},n))})}getSummary(){return P(this,null,function*(){var n;if(!this.hasConversation())return j.warn("No conversation to create summary for."),null;(n=this.state.profile.data)!=null&&n.summarizerAssistantNew||j.warn("No profile loaded yet, or no summarizer assistant set in profile");let t=yield this.store.dispatch(Hn({}));if(t.error)throw new Error(t.error.message);return t.payload})}handleKeyDown(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui,{textSuggestions:o,selectedSuggestionIndex:i,selection:s}=this.state.input,{inlineSuggestions:a,showTextSuggestions:l}=this.settings,u=a?"below":"above",c=o.length>0;if(this.store.dispatch(S1(Ph(t))),!Vn(this.state)||t.key!=="Tab"&&!l)return;let p=()=>{n||!c||s&&(t.shiftKey||(this.store.dispatch(b1()),t.preventDefault()))},d=()=>{n||!c||a&&i<=0||s&&(t.shiftKey||(this.store.dispatch(E1()),t.preventDefault()))};switch(t.key){case"ArrowUp":u==="below"?d():p();break;case"ArrowDown":{u==="below"?p():d();break}case"Escape":{n||(this.store.dispatch(zd(-1)),this.store.dispatch(so({collapse:!0})),this.store.dispatch(aC(!0)),t.preventDefault());break}case"Tab":{t.preventDefault();let f=ys(this.state);if(!f)return;this.store.dispatch(nu(!1)),this.store.dispatch(mn({text:f.text,suggestion:f,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(this.settings.inlineSuggestions||this.state.input.selectedSuggestionIndex===-1)return;let f=ys(this.state);if(!f)return;this.store.dispatch(mn({text:f.text,suggestion:f,eventMetrics:{inputType:"space"},replace:"until-selection-end"}));break}case"Enter":{if(this.settings.inlineSuggestions||t.shiftKey||this.state.input.selectedSuggestionIndex===-1)return;let f=ys(this.state);if(!f)return;this.store.dispatch(mn({text:f.text,suggestion:f,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),t.preventDefault();break}default:}n&&r&&this.store.dispatch(so({collapse:!1}))}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(eo([]))}handlingTimeStart(){this.state.handlingTime.startTime||(j.info("Start handling time"),this.store.dispatch(Ck()))}handlingTimeStop(){this.state.handlingTime.startTime&&(j.info("Stop handling time"),this.store.dispatch(tf()))}logSendMessage(t){let n=Fk("input",this.state,{version:this.version});n&&(t&&(Object.assign(n,{text:t}),Object.assign(n,{lenTextTotal:t.length})),this.deepdeskApi.sendEventV1("Send Message",n),this.emit("send-message-event",n))}logHandlingTime(){let t=Dk(this.state,{version:this.version});t&&(this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch(kk()))}notifySubmit(t={}){var n;this.shouldAbort()||(this.store.dispatch(zo((n=t.text)!=null?n:this.state.input.text)),this.store.dispatch(C1()))}emit(t,n){let r=this.eventListeners[t];r&&r.forEach(o=>{try{o(n)}catch(i){j.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),j.error(i)}})}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),()=>{this.off(t,n)}}off(t,n){if(!t&&!n){this.eventListeners={};return}let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}setConversationQuery(t){this.dynamicThunkObject.conversationQuery=t}setPlatformVariables(t){this.store.dispatch(N1(t))}whenConversationLoaded(t){let n=o=>{var i;return(i=o.conversation.current)==null?void 0:i.id},r=()=>this.loadProfileConfig().then(()=>t());n(this.state)&&r(),this.subscribe(n,o=>{o&&r()})}overlayContainerFactory(t,n,r,o){let[i,s]=fu(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),this.unmountHandlers.push(()=>{(0,Xe.unmountComponentAtNode)(i),s(),i.remove()}),i}createInlineContainer(t,n){var a;let r=document.createElement("div");r.style.position="absolute",r.style.top="0px",r.style.left="0px",r.style.height="0px",r.style.width="0px";let o=document.createElement("div");o.style.display="none",o.style.position="absolute",o.style.height="0px",o.style.width="0px",o.style.backgroundColor="red",r.appendChild(o);let i=(a=t.ownerDocument.defaultView)==null?void 0:a.frameElement,s=i?i.ownerDocument.defaultView:null;if(i&&(s===window||(s==null?void 0:s.parent)===window)){let[l,u]=fu(i,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});l.dataset.testid=n,l.style.zIndex="2",l.appendChild(r),this.unmountHandlers.push(()=>{(0,Xe.unmountComponentAtNode)(o),u()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return Zo(o),o.dataset.testid=t,o.style.color=r.color,o.style.fontSize=r.fontSize,o.style.fontFamily=r.fontFamily,o.style.fontVariant=r.fontVariant,o.setAttribute("translate","no"),n.appendChild(o),this.unmountHandlers.push(()=>{(0,Xe.unmountComponentAtNode)(o),o.remove()}),o}storeMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(t,n),j.info(`Stored analytics for ${this.conversationId()}`)}catch(t){}}restoreMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=window.sessionStorage.getItem(t);if(!n)return;let r=JSON.parse(n);r.text.trim()===this.state.input.text.trim()?(j.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(T1(r.metrics))):j.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(t)}catch(t){}}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!rf(t))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let d=n,{customStyles:r,closestScrollSelector:o,floatingMenuParent:i,appendOverlayTo:s,inputMediator:a}=d,l=Z(d,["customStyles","closestScrollSelector","floatingMenuParent","appendOverlayTo","inputMediator"]),u={customStyles:r,closestScrollSelector:o,floatingMenuParent:i,appendOverlayTo:s};this.configure(l),this.settings.automaticHandlingTime&&this.setupHandlingTime(t),Zo(t),this.inputMediator=a||(li(t)?new pi(t):new di(t)),this.inputMediator.on("change",({plainText:f,rawHTML:h})=>{this.store.dispatch(Hd({text:f,html:h}))}),this.inputMediator.on("keyup",f=>{this.store.dispatch(x1(Ph(f)))}),this.inputMediator.on("keydown",f=>{this.handleKeyDown(f)}),this.inputMediator.on("paste",({pastedText:f,selectionText:h})=>{this.store.dispatch(w1({text:f,selectionText:h}))}),this.inputMediator.on("cut",({selectionText:f})=>{this.store.dispatch(v1(f))});let c;this.inputMediator.on("selection",f=>{clearTimeout(c),f===null?c=setTimeout(()=>{f!==null&&this.store.dispatch(Ud(f))},500):this.store.dispatch(Ud(f))}),this.inputMediator.on("disabled",()=>{var f;(f=this.inputMediator)==null||f.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{this.settings.detectSubmit&&this.notifySubmit()}),this.inputMediator.on("blur",()=>{this.store.dispatch(Lp(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(Lp(!0))}),this.renderSuggestions(t,u),this.subscribe(sl("inlineSuggestions"),()=>{this.renderSuggestions(t,u)});let p=this.renderOverlays(n);this.unmountHandlers.push(()=>{p.unmount()}),this.store.dispatch(Hd({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()})),this.store.dispatch(Ud(this.inputMediator.getSelection())),this.store.dispatch(Lp(this.inputMediator.isFocused)),this.unmountHandlers.push(()=>{this.state.input.text!==""&&this.storeMetrics()}),this.whenConversationLoaded(()=>{var f;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((f=this.state.conversation.current)==null?void 0:f.sessionId)}),this.isMounted=!0}subscribe(t,n){let r=t(this.store.getState());return this.store.subscribe(()=>{let o=t(this.store.getState());o!==r&&(r=o,n(r))})}unmount(){var t,n,r,o;(t=this.inlineSuggestions)==null||t.unmount(),(n=this.aboveSuggestions)==null||n.unmount(),(r=this.floatingMenu)==null||r.unmount(),this.unmountHandlers.forEach(i=>i()),this.unmountHandlers=[],(o=this.inputMediator)==null||o.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderSuggestions(t,n){var r,o,i;(r=this.floatingMenu)==null||r.unmount(),(o=this.inlineSuggestions)==null||o.unmount(),(i=this.aboveSuggestions)==null||i.unmount(),this.settings.floatingMenu&&(this.floatingMenu=this.renderFloatingMenu(t,n)),this.settings.inlineSuggestions?this.inlineSuggestions=this.renderInlineSuggestions(t,n):this.aboveSuggestions=this.renderAboveSuggestions(t,n)}renderInlineSuggestions(t,n){let{customStyles:r}=n,o=this.createInlineContainer(t,"deepdesk-caret");(0,Xe.render)((0,He.jsx)(ai,{store:this.store,customStyles:r,children:(0,He.jsx)(Uo,{broadcastEvents:this.broadcastEvents,children:(0,He.jsx)(gC,{})})}),o);let i=s=>{s?(o.style.display="block",o.style.top=`${s.top}px`,o.style.left=`${s.left}px`):o.style.display="none"};return this.inputMediator.on("caretposition",i),{unmount:()=>{var s;(0,Xe.unmountComponentAtNode)(o),(s=this.inputMediator)==null||s.off("caretposition",i),o.remove()}}}renderAboveSuggestions(t,n){let{customStyles:r,closestScrollSelector:o,appendOverlayTo:i}=n,s=o&&mv(t,o)||void 0,a=this.overlayContainerFactory("deepdesk-tab-completion",s||t,{appendTo:i,closestScrollElement:s,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),l=this.overlayContainerFactory("deepdesk-suggestions-overlay",s||t,{appendTo:i},r==null?void 0:r.suggestionsRootNode);return(0,Xe.render)((0,He.jsx)(ai,{store:this.store,customStyles:r,children:(0,He.jsx)(Uo,{broadcastEvents:this.broadcastEvents,children:(0,He.jsx)(UC,{inputElement:t})})}),a),(0,Xe.render)((0,He.jsx)(ai,{store:this.store,customStyles:r,children:(0,He.jsx)(Uo,{broadcastEvents:this.broadcastEvents,children:(0,He.jsx)(TC,{onLogIn:()=>this.loginViaPopup().catch(u=>j.warn(u.message))})})}),l),{unmount(){(0,Xe.unmountComponentAtNode)(a),(0,Xe.unmountComponentAtNode)(l),a.remove(),l.remove()}}}renderFloatingMenu(t,n){let{customStyles:r,closestScrollSelector:o,appendOverlayTo:i,floatingMenuParent:s}=n,a=o&&mv(t,o)||void 0,l=this.overlayContainerFactory("floating-menu",a||t,{appendTo:s!=null?s:i},r==null?void 0:r.floatingMenuParent);return(0,Xe.render)((0,He.jsx)(ai,{store:this.store,customStyles:r,children:(0,He.jsx)(Uo,{broadcastEvents:this.broadcastEvents,children:(0,He.jsx)(iC,{onLogIn:()=>this.loginViaPopup().catch(u=>j.warn(u.message))})})}),l),{unmount(){(0,Xe.unmountComponentAtNode)(l),l.remove()}}}renderOverlays(t){let{customStyles:n}=t,r=this.createContainer("deepdesk-overlays");return(0,Xe.render)((0,He.jsx)(ai,{store:this.store,customStyles:n,children:(0,He.jsx)(Uo,{broadcastEvents:this.broadcastEvents,children:(0,He.jsx)(eC,{})})}),r),{unmount(){(0,Xe.unmountComponentAtNode)(r),r.remove()}}}renderWidget(t,n={}){if(this.widgetRoot&&j.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:i}=n;this.widgetRoot=t,this.configure({showImages:o,isEmbedded:i}),(0,Xe.render)((0,He.jsx)(ai,{store:this.store,customStyles:r,children:(0,He.jsx)(Uo,{broadcastEvents:this.broadcastEvents,children:(0,He.jsx)(mk,{onLogIn:()=>this.loginViaPopup().catch(s=>j.warn(s.message))})})}),t),this.whenConversationLoaded(()=>{var s;this.broadcastEvents.setSessionId((s=this.state.conversation.current)==null?void 0:s.sessionId)})}unmountWidget(){this.widgetRoot&&(0,Xe.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(t){let n=af(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){zk(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(()=>P(this,null,function*(){yield this.store.dispatch(Al());let t=Bo(this.state);t&&(yield this.store.dispatch(Tl()),this.store.dispatch(Ld({showSearch:t.search,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:!!t.summarizerAssistantNew||t.summarizer,showKnowledgeSearch:!!t.knowledgeAssistantNew||!!t.knowledgeAssistant,recommendTextSuggestions:t.recommendTextSuggestions})))})),this.loadProfileConfigPromise)}loginViaPopup(t){return P(this,null,function*(){return new Promise((n,r)=>{let o=new MessageChannel,i=o.port1,s=this.settings.adminUrl,a=new URL(t!=null&&t.url?t==null?void 0:t.url:`${s}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let l=!1,u=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",p),clearInterval(d)};i.onmessage=f=>P(this,null,function*(){var h,v;if((h=f.data)!=null&&h.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((v=f.data)==null?void 0:v.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(dl),l=!0,o.port1.close(),n()}catch(m){console.error(m),r(m)}finally{l=!0,u()}});let c=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");c===null&&r(new Error("Popup blocked by browser"));let p=f=>P(this,null,function*(){var h;if(f.origin===a.origin)switch((h=f.data)==null?void 0:h.type){case"deepdesk-popup-loaded":{try{let v=JSON.stringify({type:"deepdesk-popup-create-channel"});c==null||c.postMessage(v,a.origin,[o.port2])}catch(v){j.error("Error posting message to popup",v),r(v)}break}case"deepdesk-popup-error":{u(),f.data.message==="Timeout"&&j.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(f.data.message));break}}});window.addEventListener("message",p);let d=setInterval(()=>{c&&!c.closed||(u(),l||r(new Error("Popup closed by user")))},200);this.unmountHandlers.push(u)})})}translateMessages(t){return this.deepdeskApi.translateMessages(t)}checkForTrialMode(t){return P(this,null,function*(){try{let{account:n}=yield this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(j.info("Trial is active"),!(yield this.deepdeskApi.checkUserExists(t)))throw new Error("User is not in trial");this.shouldRender=!0}catch(n){let{message:r}=n;j.info(r),this.shouldRender=!1}})}refreshWidgetSuggestions(){return P(this,null,function*(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=Ll(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch(vn()):_u.includes(r)||this.store.dispatch(En(r))})}catch(r){this.handleError(r)}})}};$s.version="15.1.1-beta.4",$s.count=0;var mu=$s;function S_(e){return P(this,null,function*(){var o,i,s;let n=yield((o=e.fetch)!=null?o:window.fetch)(e.url),r=yield n.blob();return new File([r],e.name,{type:(s=(i=e.mimeType)!=null?i:n.headers.get("Content-Type"))!=null?s:"image/jpeg"})})}function Xk(e,t){return P(this,null,function*(){let n=yield S_(t),r=new Event("change",{bubbles:!0,cancelable:!0});try{Object.defineProperty(e,"files",{configurable:!0,get:()=>[n]}),e.dispatchEvent(r)}finally{Object.hasOwn(e,"files")&&delete e.files}})}function Zk(e,t,n){return P(this,null,function*(){yield new Er(e).authenticateWithKey(t,n)})}function Jk(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function eR(r,o){return P(this,arguments,function*(e,t,n={}){var p,d;let{value:i}=e,{start:s,end:a}=(p=n.replace)!=null?p:{start:0,end:i.length},l=`${i.slice(0,s)}${t}${i.slice(a)}`,u=(d=n.selectionAfter)!=null?d:{start:s+t.length,end:s+t.length},c=()=>{if(n.setValue)return n.setValue(l);e.value=l};return Promise.resolve(c()).then(()=>{e.selectionStart=u.start,e.selectionEnd=u.end,e.blur(),e.focus()})})}function tR(r,o){return P(this,arguments,function*(e,t,n={}){let i=n.replace?uo(e,n.replace.start,n.replace.end):Us(e),s,a=()=>{if(n.setRange)return n.setRange(i.cloneRange());i.deleteContents(),s=document.createElement("span"),i.insertNode(s),n.insertBRs!==!1?t.split(`
|
|
84
84
|
`).reverse().forEach((l,u)=>{u>0&&i.insertNode(document.createElement("br")),i.insertNode(document.createTextNode(l))}):i.insertNode(document.createTextNode(t))};return Promise.resolve(a()).then(()=>{try{if(n.selectionAfter!==!1){e.focus();let l=n.selectionAfter?uo(e,n.selectionAfter.start,n.selectionAfter.end):(i.collapse(!1),i),u=window.getSelection();u==null||u.removeAllRanges(),u==null||u.addRange(l)}if(!s)return;s.scrollIntoView&&s.scrollIntoView({block:"nearest",inline:"nearest"})}finally{s&&s.remove()}})})}function x_(e){let t=document.createElement("template");return t.innerHTML=e.replace(/(\[([^\]]+)])\(([^)]+)\)/g,'<a href="$3" target="_blank" rel="noopener noreferrer">$2</a>'),t.content}function w_(e){let t=document.createDocumentFragment();return e.split(`
|
|
85
85
|
`).forEach((n,r)=>{r>0&&t.appendChild(document.createElement("br"));let o={index:0},i=0;for(;o=n.slice(i).match(/(\[([^\]]+)])\(([^)]+)\)/);){let s=document.createElement("a");s.href=o[3],s.setAttribute("target","_blank"),s.setAttribute("rel","noopener noreferrer"),s.appendChild(document.createTextNode(o[2])),t.appendChild(document.createTextNode(n.slice(i,i+o.index))),t.appendChild(s),i=i+o.index+o[0].length}t.appendChild(document.createTextNode(n.slice(i)))}),t}function nR(e,t){let n=e.parentElement;if(!n){console.warn("No insert point found");return}let{display:r}=window.getComputedStyle(n);r.includes("block")||r==="table-cell"?n==null||n.insertBefore(t,e.nextSibling):nR(n,t)}function rR(o,i){return P(this,arguments,function*(e,t,{isBlock:n,isHTML:r}={}){let s;e.dispatchEvent(new InputEvent("beforeinput",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0}));let a=()=>{var d;let l=(d=e.ownerDocument.defaultView)!=null?d:window,u=l.getSelection();if((!u||u.rangeCount===0)&&(e.focus(),u=l.getSelection()),!u||u.rangeCount===0)return;let c=u.getRangeAt(0);if(!c)return;s=document.createElement("span"),c.insertNode(s);let p=r?x_(t):w_(t);n?nR(c.startContainer,p):(c.insertNode(p),c.collapse(!1))};return Promise.resolve(a()).then(()=>{if(e.dispatchEvent(new InputEvent("input",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0})),e.focus(),!!s)try{s.scrollIntoView&&s.scrollIntoView({block:"nearest",inline:"nearest"})}finally{s&&s.remove()}})})}return vR(b_);})();
|
|
86
86
|
/*! Bundled license information:
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@deepdesk/deepdesk-sdk",
|
|
3
|
-
"version": "15.1.1-beta.
|
|
3
|
+
"version": "15.1.1-beta.4",
|
|
4
4
|
"description": "Deepdesk SDK",
|
|
5
5
|
"author": "Lukas Batteau",
|
|
6
6
|
"license": "ISC",
|
|
@@ -78,7 +78,7 @@
|
|
|
78
78
|
"@types/react-redux": "^7.1.25",
|
|
79
79
|
"@types/uuid": "^9.0.2",
|
|
80
80
|
"args": "^5.0.3",
|
|
81
|
-
"esbuild": "^0.
|
|
81
|
+
"esbuild": "^0.25.0",
|
|
82
82
|
"eslint": "^8.44.0",
|
|
83
83
|
"eslint-config-custom": "*",
|
|
84
84
|
"jest": "^29.5.0",
|