@deepdesk/deepdesk-sdk 19.6.2-beta.12 → 19.6.2-beta.14
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 +1 -1
package/dist/index.iife.js
CHANGED
|
@@ -80,7 +80,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
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 WS=E(A()),Z6={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},dI=({className:e,color:t})=>(0,WS.jsx)("svg",{className:e,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:(0,WS.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:Z6[t||"pink"]})});var fI={root:"dd-LbeUM",text:"dd-Dpfn1",isLoggedIn:"dd-XvHAn",isLoggedOut:"dd-21y-z",icon:"dd-8rLqS",logo:"dd-slXhD",lock:"dd-ByzlR"};var $S={};ut($S,{enUS:()=>J6,nlNL:()=>ez});var J6={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},ez={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};var Ci=E(A()),mI=({onLogIn:e})=>{let t=ae($S),n=Z("floatingMenu"),r=Z("productName"),o=ve(),s=K(kt),i=F("FloatingMenu",fI);if(s===null||n===!1)return null;let a=()=>{s===!0?o(ur(!0)):e()};return(0,Ci.jsxs)("button",{type:"button",className:(0,pI.default)(i.root,{[i.isLoggedIn]:s,[i.isLoggedOut]:!s}),onClick:a,children:[(0,Ci.jsx)("div",{className:i.text,children:t(s?"search":"signin",{productName:r})}),(0,Ci.jsxs)("div",{className:i.icon,children:[(0,Ci.jsx)(dI,{className:i.logo,color:"pink"}),s===!1&&(0,Ci.jsx)(uI,{className:i.lock})]})]})};var jm=E(Q());function Gr(e){let{showMidSentenceSuggestions:t,showSuggestionsBeforePattern:n,showSuggestionsAfterPattern:r}=e.settings,{text:o,selection:s}=e.input;return s.end<e.input.suggestionTextStart||s.start!==s.end?!1:s.end>=o.length?!0:t?n&&new RegExp(n).test(o.substring(s.end))||r&&new RegExp(r).test(o.substring(0,s.end))?!0:n===!1&&r===!1:!1}var tz={showTabHint:!1,inputHasFocus:!1,overlayCollapsed:!1,openOverlayWhenTyping:!1,overlayCollapsedUserOverwrite:!1},zm=({ui:e})=>e.overlayCollapsed,gI=Pe({name:"ui",initialState:tz,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:xu,setInputFocus:Hm,setOverlayCollapsed:xs,setOpenOverlayWhenTyping:hI,setOverlayCollapsedUserOverwrite:yI}=gI.actions,vI=gI.reducer;var SI={styleRow:"dd-prYfH",styleSuggestion:"dd-JTmXy"};var wu=E(A()),nz=({match:e,selected:t,styles:n})=>(0,wu.jsx)(fe,{as:"button",selected:t,className:n.styleRow,"data-testid":"style-suggestion-item",title:e.suggestion,children:(0,wu.jsx)("span",{className:n.styleSuggestion,children:e.suggestion})}),rz=({matches:e,selectedIndex:t})=>{let n=F("StyleSuggestionList",SI);return(0,wu.jsx)(Ct,{children:e.map((r,o)=>(0,wu.jsx)(nz,{match:r,selected:t===o,styles:n},`${r.keyword}-${o}`))})},Bm=rz;var TI=E(Q());var ws=E(Q());var xI=E(Q());function wI(e,t,n){(0,xI.useEffect)(()=>{let r=e.current;return r?(r.addEventListener(t,n),()=>{r.removeEventListener(t,n)}):()=>{}},[e,t,n])}var bI={root:"dd-1MBCO",actions:"dd--x4cy",closeIconContainer:"dd-1z5NR",closeIcon:"dd-8qMF-",badge:"dd-4Fpkz",formattedText:"dd-EzvTB",assistantContainer:"dd-j6o8F",formattedTextTruncated:"dd-fv169",assistantBadge:"dd-VD57E"};var bu=E(A()),EI=({title:e})=>(0,bu.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"18px",height:"18px",viewBox:"0 0 24 24","aria-labelledby":"closeTitle",children:[(0,bu.jsx)("title",{id:"closeTitle",children:e}),(0,bu.jsx)("path",{d:"M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"})]});var jS={};ut(jS,{enUS:()=>oz,nlNL:()=>sz});var oz={assistant:[{type:0,value:"Assistant"}],close:[{type:0,value:"Close"}]},sz={assistant:[{type:0,value:"Assistent"}],close:[{type:0,value:"Sluiten"}]};var zn=E(A()),az=["search","personal-collection-search","search-autocomplete"];function lz(e,t,n,r={}){var s;let o="";return az.includes(t)?o=OA(NS(e,n,{stripAgentPart:!0}),(s=r.searchKeywords)!=null?s:[n]):o=NS(e,n,r),r.placeholders===!0&&(o=NA(o)),o}var cz=()=>{},uz=({selected:e,suggestion:t})=>{let n=ae(jS),r=Z("inlineSuggestions"),o=K(Ns),[s,i]=(0,ws.useState)(!1),a=Z("enableSuggestionFeedback"),l=K(S=>S.input.text),c=ve(),u=F("TextSuggestion",bI),f=(0,ws.useRef)(null),d=t.source==="assistant",p=a&&!d;(0,ws.useEffect)(()=>{let S=setTimeout(()=>{c(oE({text:t.text,suggestion:t}))},500);return()=>{clearTimeout(S)}},[t]),wI(f,"click",()=>{c(Cn({suggestion:t,text:t.text,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"}))});let h=()=>{c(Fs({source:t.source,text:t.text,assistantCode:t.assistantCode}))},y=(0,ws.useMemo)(()=>lz(t.text,t.source,o,{stripAgentPart:r,placeholders:!0,searchKeywords:t.searchKeywords}),[r,t.text,t.source,o,t.searchKeywords]);return t.source==="gpt"&&!r?null:(0,zn.jsxs)("div",{className:u.root,onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),children:[(0,zn.jsx)(fe,{ref:f,as:"button","data-testid":"suggestions-overlay-item",selected:e,onClick:cz,children:t.source==="assistant"?(0,zn.jsxs)("div",{className:u.assistantContainer,children:[(0,zn.jsx)(ys,{containerTagName:"div",tagName:"span",className:u.formattedTextTruncated,content:y}),(0,zn.jsx)("span",{className:u.assistantBadge,children:n("assistant")})]}):(0,zn.jsx)(ys,{containerTagName:"div",tagName:"span",className:u.formattedText,content:y})}),p&&s&&(0,zn.jsx)("div",{className:u.actions,children:(0,zn.jsx)(Om,{source:"overlay",context:l,suggestion:t})}),d&&s&&(0,zn.jsx)("div",{className:u.closeIconContainer,children:(0,zn.jsx)("button",{type:"button",className:u.closeIcon,onClick:h,title:n("close"),children:(0,zn.jsx)(EI,{title:n("close")})})})]})},CI=uz;var kI=E(A()),dz=({suggestions:e,selectedIndex:t,reverse:n})=>(0,TI.useMemo)(()=>{let o=e.map((s,i)=>(0,kI.jsx)(CI,{index:i,selected:i===t,suggestion:s},`${s.text}-${s.source}`));return n?o.reverse():o},[e,t,n]),Um=dz;var RI={root:"dd-PfvRI",paper:"dd-HYlyY"};var Vm={list:{keywordMatches:[]},fetchState:"idle"},Wm=e=>e.styleSuggestions.list,Ti=me("styleSuggestions/getAll",(n,r)=>M(null,[n,r],function*({text:e},t){var l;let{deepdeskAPI:o}=t.extra,s=t.getState(),{showStyleSuggestions:i}=s.settings,a=(l=s.conversation.current)==null?void 0:l.profileCode;if(!i)return Vm.list;if(!a)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:a,message:e})})),PI=Pe({name:"styleSuggestions",initialState:Vm,reducers:{commitStyleSuggestion(e,t){let{keyword:n,suggestion:r}=t.payload;e.list.keywordMatches=e.list.keywordMatches.filter(o=>o.keyword.toLowerCase()!==n.toLowerCase()||o.suggestion!==r)}},extraReducers:e=>{e.addCase(Ti.pending,t=>{t.fetchState="loading"}).addCase(Ti.rejected,t=>{t.fetchState="error"}).addCase(Ti.fulfilled,(t,n)=>{t.fetchState="done",Bo(t.list,n.payload)||(t.list=n.payload)}).addCase(zs,t=>{t.list=Vm.list}).addCase(Ke,()=>Vm)}}),{commitStyleSuggestion:AI}=PI.actions,II=PI.reducer;var $m=e=>{let t=new Set;return e.filter(({keyword:n,suggestion:r})=>{let o=JSON.stringify([n.toLowerCase(),r]);return t.has(o)?!1:(t.add(o),!0)})};var ki=E(A()),fz=()=>{var S;let e=(0,jm.useRef)(null),t=F("InlineSuggestionsOverlay",RI),n=K(Gr),r=ve(),o=K(kt),s=K(Yi),i=K(zm),a=Z("showTextSuggestions"),l=K(Ds),c=K(Rl),u=Z("showStyleSuggestions"),f=Z("showStyleSuggestionList"),d=K(Wm),p=u&&f?$m((S=d.keywordMatches)!=null?S:[]):[],h=p.length>0,y=a&&l.length>0;return ms(()=>{setTimeout(()=>{r(xs({collapse:!0,skipWhenInputFocus:!0}))})}),(0,jm.useEffect)(()=>{let m=e.current;if(!m||!m.parentElement)return;m.parentElement.style.left="0px";let g=m.getBoundingClientRect();m.parentElement.style.left=`${Math.min(window.innerWidth-4-g.right,0)}px`}),i||o!==!0||s===!1||!n&&!h||!y&&!h?null:(0,ki.jsx)("div",{className:t.root,"data-variant":"inline",children:(0,ki.jsxs)("div",{ref:e,className:t.paper,children:[h&&(0,ki.jsx)(Bm,{matches:p,selectedIndex:-1}),y&&(0,ki.jsx)(Ct,{children:(0,ki.jsx)(Um,{suggestions:l,selectedIndex:c})})]})})},_I=fz;var bs=E(Q());var MI={root:"dd-7zvcP",dialogContent:"dd-4C0lK",continueButton:"dd-YUPQW",buttonContinueWrapper:"dd-IKpYs",nicknameInput:"dd-rxhGp",titleWrapper:"dd-nw3nD",title:"dd-5iof5",closeButtonWrapper:"dd-UUAzA",closeButton:"dd-7rjP5",buttonsWrapper:"dd-5e9Xb",errorMessage:"dd--5VgX",errorLink:"dd-u461n"};var KS={};ut(KS,{enUS:()=>pz,nlNL:()=>mz});var pz={title:[{type:0,value:"Enter your nickname"}],close:[{type:0,value:"Close"}],nicknameDialogTitle:[{type:0,value:"Please enter the name you'd like customers to see during chat conversations. This nickname will be used across your Deepdesk environment."}],nicknameDialogInputPlaceholder:[{type:0,value:"Enter your nickname"}],nicknameDialogContinueButton:[{type:0,value:"Continue"}],nicknameDialogError:[{type:0,value:"Nickname cannot be empty or spaces only"}],nicknameDialogEmojiError:[{type:0,value:"You cannot use emojis in this field."}],nicknameDialogSaveError:[{type:0,value:"We couldn't save your details just now. Please try again, or update it at "},{type:1,value:"account"},{type:0,value:".deepdesk.com/admin/user-settings"}],nicknameDialogSaveErrorWithoutLink:[{type:0,value:"We couldn\u2019t save your details just now. Please try again later, or update them in My Deepdesk \u2192 Settings."}]},mz={title:[{type:0,value:"Voer je bijnaam in"}],close:[{type:0,value:"Sluiten"}],nicknameDialogTitle:[{type:0,value:"Voer de naam in die je wilt dat klanten zien tijdens chatgesprekken. Deze bijnaam wordt gebruikt in je Deepdesk-omgeving."}],nicknameDialogInputPlaceholder:[{type:0,value:"Voer je bijnaam in"}],nicknameDialogContinueButton:[{type:0,value:"Doorgaan"}],nicknameDialogError:[{type:0,value:"Bijnaam mag niet leeg of alleen spaties zijn"}],nicknameDialogEmojiError:[{type:0,value:"Je kunt geen emoji's gebruiken in dit veld."}],nicknameDialogSaveError:[{type:0,value:"We konden je gegevens nu niet opslaan. Probeer het opnieuw of werk het bij op "},{type:1,value:"account"},{type:0,value:".deepdesk.com/admin/user-settings"}],nicknameDialogSaveErrorWithoutLink:[{type:0,value:"We konden je gegevens nu niet opslaan. Probeer het opnieuw later, of werk ze bij in My Deepdesk \u2192 Instellingen."}]};var ht=E(A()),LI=({onClose:e,onSave:t,id:n,error:r})=>{let[o,s]=(0,bs.useState)(""),[i,a]=(0,bs.useState)(!1),[l,c]=(0,bs.useState)(!1),u=F("Nickname",MI),f=bs.default.useRef(null),d=K(m=>m.info.showNicknameDialog),p=ae(KS),h=Z("adminUrl");(0,bs.useEffect)(()=>{r&&a(!0)},[r]);let y=()=>{if(!f.current)return;o.trim()?f.current.setCustomValidity(""):f.current.setCustomValidity(p("nicknameDialogError")),f.current.reportValidity()},S=m=>{m.preventDefault();let g=o.trim(),v=m.currentTarget.querySelector("#nickname-input");if(!g){v.setCustomValidity(p("nicknameDialogError")),v.reportValidity();return}v.setCustomValidity(""),t(g)};return(0,ht.jsxs)(qa,{isOpen:d,"datatest-id":n,onClose:e||(()=>{}),onBack:e||(()=>{}),children:[(0,ht.jsx)("div",{className:u.titleWrapper,children:(0,ht.jsx)("h1",{className:u.title,children:p("title")})}),(0,ht.jsxs)("form",{className:u.dialogContent,onSubmit:S,children:[(0,ht.jsx)("p",{children:p("nicknameDialogTitle")}),i&&r&&(0,ht.jsx)("div",{className:u.errorMessage,children:h?(()=>{let m=p("nicknameDialogSaveError",{account:h}),g=`${h}.deepdesk.com/admin/user-settings`,v=m.indexOf(g);if(v!==-1){let x=m.substring(0,v),T=m.substring(v+g.length);return(0,ht.jsxs)(ht.Fragment,{children:[x,(0,ht.jsx)("a",{href:g,target:"_blank",rel:"noopener noreferrer",className:u.errorLink,children:g}),T]})}return m})():p("nicknameDialogSaveErrorWithoutLink")}),(0,ht.jsx)("input",{required:!0,minLength:1,maxLength:20,"data-testid":"nickname-input",id:"nickname-input",className:u.nicknameInput,type:"text",placeholder:p("nicknameDialogInputPlaceholder"),value:o,onChange:m=>{c(new RegExp("\\p{Extended_Pictographic}","u").test(m.target.value)),s(m.target.value)},onBlur:y,ref:f}),l&&(0,ht.jsx)("div",{className:u.errorMessage,role:"alert",children:p("nicknameDialogEmojiError")}),(0,ht.jsxs)("div",{className:u.buttonsWrapper,children:[r?(0,ht.jsx)("div",{className:u.closeButtonWrapper,children:(0,ht.jsx)("button",{type:"button",className:u.closeButton,onClick:()=>e==null?void 0:e(),children:p("close")})}):null,(0,ht.jsx)("div",{className:u.buttonContinueWrapper,children:(0,ht.jsx)("button",{type:"submit",className:u.continueButton,disabled:!o.trim()||new RegExp("\\p{Extended_Pictographic}","u").test(o),children:p("nicknameDialogContinueButton")})})]})]})]})};var Eu=E(A()),gz=({children:e})=>{let n=Z("locale").replace("-","");return(0,Eu.jsx)(Uh.Provider,{value:n,children:e})},hz=({store:e,customStyles:t={},children:n})=>(0,Eu.jsx)(Qw,{store:e,children:(0,Eu.jsx)(gz,{children:(0,Eu.jsx)(gl.Provider,{value:t,children:n})})}),Ro=hz;var Gm=E(De()),tl=E(Q());var OI=E(Q());function NI(e,t){let[n,r]=(0,OI.useState)(()=>{if(typeof window=="undefined")return t;try{let s=window.localStorage.getItem(e);return s?JSON.parse(s):t}catch(s){return J.error(s),t}});return[n,s=>{try{let i=s instanceof Function?s(n):s;r(i),typeof window!="undefined"&&window.localStorage.setItem(e,JSON.stringify(i))}catch(i){J.error(i)}}]}var DI=()=>/Mac/i.test(navigator.platform);var zI=E(De()),Po=E(Q());var GS={};ut(GS,{enUS:()=>yz,nlNL:()=>vz});var yz={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"}]}]},vz={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 FI={root:"dd-uTPjX",anchor:"dd-C8lsZ",anchorButton:"dd-IoSx9"};var Es=E(A()),qS=(e,t,n)=>r=>(0,Es.jsx)("button",{className:e.anchorButton,type:"button",value:t,onClick:n,children:r},t),Sz=({className:e,loginUrl:t,isEmbedded:n,onSnooze:r,onLogIn:o})=>{let s=ae(GS),i=cn(),a=F("Login",FI),l=Z("productName"),c=Z("signInViaPopup"),u=n&&!c,f=(0,Po.useCallback)(g=>{g.preventDefault(),r&&r(Number.parseInt(g.target.value,10))},[]),d=(0,Po.useCallback)(g=>{g.preventDefault(),i.send(ea,!0)},[t]),p=(0,Po.useMemo)(()=>g=>(0,Es.jsx)("a",{onClick:x=>{x.preventDefault(),o()},href:t,className:a.anchor,target:"_blank",rel:"noreferrer",children:g},"login"),[t]),h=(0,Po.useCallback)(g=>(0,Es.jsx)("button",{type:"button",className:a.anchorButton,onClick:d,children:g},"prompt"),[d]),{min:y,hour:S,day:m}=(0,Po.useMemo)(()=>({min:qS(a,600,f),hour:qS(a,3600,f),day:qS(a,3600*12,f)}),[]);return(0,Es.jsxs)("div",{className:(0,zI.default)(e,a.root),children:[s("loginPlease",{login:u?h:p,productName:l}),r&&(0,Es.jsxs)(Po.Fragment,{children:[(0,Es.jsx)("br",{}),s("snooze",{min:y,hour:S,day:m})]})]})},Km=Sz;var HI={root:"dd-DoQhb",text:"dd-Jwnev"};var Cu=E(A()),xz=({title:e})=>{let t=F("SearchTrigger",HI),n=ve(),r=tt();return(0,Cu.jsxs)("button",{type:"button",className:t.root,onClick:()=>{n(ur(!0)),r("open search",{via:"autocomplete-overlay"})},children:[(0,Cu.jsx)(Ja,{}),(0,Cu.jsx)("span",{className:t.text,children:e})]})},BI=xz;var YS={};ut(YS,{enUS:()=>wz,nlNL:()=>bz});var wz={arrowHint:[{type:0,value:"Tip: use arrow keys to navigate suggestions"}],searchHintWindows:[{type:0,value:"Press CTRL+"},{type:1,value:"searchTriggerKey"},{type:0,value:" to search"}],searchHintMac:[{type:0,value:"Press CMD+"},{type:1,value:"searchTriggerKey"},{type:0,value:" to search"}],open:[{type:0,value:"Open "},{type:1,value:"productName"}],collapse:[{type:0,value:"Close"}],search:[{type:0,value:"Search"}],dismiss:[{type:0,value:"Dismiss"}],dismissError:[{type:0,value:"Dismiss error"}]},bz={arrowHint:[{type:0,value:"Tip: Selecteer suggesties met pijltoetsen"}],searchHintWindows:[{type:0,value:"Druk CTRL+"},{type:1,value:"searchTriggerKey"},{type:0,value:" om te zoeken"}],searchHintMac:[{type:0,value:"Druk CMD+"},{type:1,value:"searchTriggerKey"},{type:0,value:" om te zoeken"}],open:[{type:0,value:"Open "},{type:1,value:"productName"}],collapse:[{type:0,value:"Sluiten"}],search:[{type:0,value:"Zoeken"}],dismiss:[{type:0,value:"Sluiten"}],dismissError:[{type:0,value:"Foutmelding sluiten"}]};var UI={root:"dd-oa7Vc",isInline:"dd-bwk31",toggleButton:"dd-MSB8Z",toggleButtonWrapper:"dd-ZkCzT",toggleButtonWrapperHidden:"dd-Sq66c",isCollapsed:"dd-vkrPk",collapsible:"dd-CWQJe",hints:"dd-IOoo3",hintsHidden:"dd-psVuT",triggers:"dd-toIoo",triggersRight:"dd-mc4l2",loginError:"dd-KCXeb",loginErrorMessage:"dd-Bv-BG",loginErrorDismiss:"dd-iSCjU"};var Le=E(A()),Ez=({onLogIn:e})=>{var $;let t=F("SuggestionsOverlay",UI),n=ae(YS),r=K(Gr),o=K(rE),s=ve(),i=(0,tl.useRef)(null),a=Z("searchTriggerKey"),l=Z("productName"),c=K(zm),u=K(kt),f=K(Wb),d=K(Yi),[p,h]=(0,tl.useState)(null),y=Z("showSearch"),S=Z("showTextSuggestions"),m=Z("adminUrl"),g=Z("isEmbedded"),v=Z("suggestionsPlacement"),[x,T]=NI("dd-snooze-until-ms",0),C=c||x>Date.now(),k=K(Ds),P=K(Rl),L=Z("showStyleSuggestions"),N=Z("showStyleSuggestionList"),B=K(Wm),Y=L&&N?$m(($=B.keywordMatches)!=null?$:[]):[],X=Y.length>0,I=k.filter(O=>O.source!=="gpt").length,z=()=>{C&&T(0),s(yI(!C))},W=O=>{let q=Date.now()+O*1e3;T(q),J.info(`Snooze until: ${new Date(q)}`),s(xs({collapse:!0}))};return(0,tl.useEffect)(()=>{I===0&&h(null)},[k,I]),ms(()=>{s(xs({collapse:!0,skipWhenInputFocus:!0}))}),u===null||d===!1?null:u===!1?(0,Le.jsxs)("div",{ref:i,className:(0,Gm.default)(t.root,{[t.isCollapsed]:C}),children:[!C&&(0,Le.jsxs)("div",{className:t.triggers,children:[(0,Le.jsx)("div",{style:{flex:1}}),(0,Le.jsx)("div",{className:t.triggersRight,children:(0,Le.jsx)(_s,{className:t.toggleButton,title:n("collapse"),onClick:z,isCollapsed:!1})})]}),(0,Le.jsx)("div",{className:t.toggleButtonWrapper,children:(0,Le.jsx)(_s,{className:t.toggleButton,title:n("open",{productName:l}),onClick:z,isCollapsed:!0})}),(0,Le.jsxs)("div",{className:t.collapsible,children:[f&&(0,Le.jsxs)("div",{className:t.loginError,children:[(0,Le.jsx)("span",{className:t.loginErrorMessage,children:f}),(0,Le.jsx)("button",{type:"button",className:t.loginErrorDismiss,onClick:()=>s(Od()),"aria-label":n("dismissError"),children:n("dismiss")})]}),(0,Le.jsx)(Km,{loginUrl:m,isEmbedded:g,onLogIn:e,onSnooze:W})]})]}):!o||!r&&!X?null:(0,Le.jsxs)("div",{ref:i,className:(0,Gm.default)(t.root,{[t.isCollapsed]:C}),children:[!C&&(0,Le.jsxs)("div",{className:t.triggers,children:[(0,Le.jsx)("div",{style:{flex:1},children:y&&(0,Le.jsx)("div",{style:{display:"inline-block"},onFocus:()=>{},onMouseOver:()=>h(n(DI()?"searchHintMac":"searchHintWindows",{searchTriggerKey:a.toUpperCase()})),onMouseLeave:()=>h(null),children:(0,Le.jsx)(BI,{title:n("search")})})}),(0,Le.jsxs)("div",{className:t.triggersRight,onFocus:()=>{},children:[(0,Le.jsx)("div",{className:(0,Gm.default)(!p&&t.hintsHidden,t.hints),children:p}),(0,Le.jsx)(_s,{className:t.toggleButton,title:n("collapse"),onClick:z,isCollapsed:!1})]})]}),(0,Le.jsx)("div",{className:t.toggleButtonWrapper,children:(0,Le.jsx)(_s,{className:t.toggleButton,title:n("open",{productName:l}),onClick:z,isCollapsed:!0})}),(X||I>0&&S)&&(0,Le.jsxs)("div",{className:t.collapsible,onFocus:()=>{},children:[X&&(0,Le.jsx)(Bm,{matches:Y,selectedIndex:-1}),I>0&&S&&(0,Le.jsx)(Ct,{children:(0,Le.jsx)(Um,{suggestions:k,selectedIndex:P,reverse:v==="above"})})]})]})},VI=Ez;var ig=E(De());var _o=E(Q());var nl=E(Q());function qm(e){return e.contentEditable==="true"}function Cz(e){let t=0,n=0,r=window.getSelection();if(r.rangeCount!==0){let o=r.getRangeAt(0),s=o.cloneRange();s.selectNodeContents(e),s.setEnd(o.endContainer,o.endOffset),n=s.toString().length,s.selectNodeContents(e),s.setEnd(o.startContainer,o.startOffset),t=s.toString().length}return{selectionStart:t,selectionEnd:n}}function WI(e){let{selectionStart:t,selectionEnd:n}=qm(e)?Cz(e):e;return[t,n]}function $I(e){let[,t]=(0,nl.useState)(),n=(0,nl.useRef)(null);return n.current=WI(e),(0,nl.useEffect)(()=>{let r=()=>{var a;let[o,s]=(a=n.current)!=null?a:[],i=WI(e);(!i||o!==i[0]||s!==i[1])&&(n.current=i,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 jI(e,t){if(!t)return;let n=e,{value:r}=n,[o,s]=t,i=r.match(ld);if(!i||i.length===0)return;let a=0;i.find(l=>{let c=r.indexOf(l,a);return o>c&&s<c+l.length?(n.selectionStart=c,n.selectionEnd=c+l.length,!0):(a=c+l.length,!1)})}var KI=E(Q()),Tz=["div","span","mark","strong","b","i","u","em"];function XS(e,t,n=0){var s;let r=e[e.length-1],o=typeof r=="object"&&r!==null?(s=r.props)==null?void 0:s.tagName:void 0;if(o==="br")return e.pop(),[...e,...t,r];if(Tz.includes(o)){let i=Array.isArray(r.props.children)?r.props.children:[r.props.children];return[...e.slice(0,e.length-1),(0,KI.cloneElement)(r,{children:XS(i,t,n+1)})]}return[...e,...t]}function Ri(e){return e.tagName.toLowerCase()==="textarea"}var GI={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 QI=E(De());var tg=E(Q());var rl=E(Q());function qI(e,t){let n;return[(...r)=>{window.cancelAnimationFrame(n);let o=t?t(...r):r;n=window.requestAnimationFrame(()=>{e(...o)})},()=>window.cancelAnimationFrame(n)]}function Ym(e){let t=(0,rl.useRef)(null),[n,r]=(0,rl.useState)(!1);return(0,rl.useEffect)(()=>{var u;let o=!1,s=Number.parseFloat((u=window.getComputedStyle(document.body).zoom)!=null?u:"1"),[i,a]=qI((f,d)=>{let p=t.current;if(!p)return;let h=f/s,y=d/s,S=p.getBoundingClientRect(),m=h>S.x&&h<S.x+S.width&&y>S.y&&y<S.y+S.height;m&&!o?(o=!0,r(!0)):!m&&o&&(o=!1,r(!1))},({clientX:f,clientY:d})=>[f,d]),[l,c]=qI(()=>{o=!1,r(!1)});return e.addEventListener("mousemove",i),e.addEventListener("mouseleave",l),()=>{a(),c(),e.removeEventListener("mousemove",i),e.removeEventListener("mouseleave",l)}},[t]),[t,n]}function Xm(e){return e.replace(/[.*+^${}()|[\]\\]/g,"\\$&")}function Qm(e){return t=>{e.forEach(n=>{typeof n=="function"?n(t):n!=null&&(n.current=t)})}}function YI(e){return e!=null}var XI=E(De()),Zm=E(Q());var Ao={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 QS=E(A()),Jm=(0,Zm.forwardRef)((o,r)=>{var s=o,{className:e,children:t}=s,n=ie(s,["className","children"]);let i=(0,Zm.useRef)(null),a=F("TabCompletion",Ao);return(0,QS.jsx)("div",_(b({ref:Qm([i,r]),className:(0,XI.default)(e,a.popoverContentContainer)},n),{children:(0,QS.jsx)("div",{className:a.popoverContent,children:t})}))});var Cs=E(A()),kz=e=>t=>{let n=hS(t);return"top"in n&&(n.width=e.width-(t.left-e.left)-10),n},Rz=({inputElement:e,boundaryRef:t,inputStyle:n,children:r,suggestion:o})=>{let s=F("TabCompletion",Ao),i=um(),a=(0,tg.useMemo)(()=>kz(e.getBoundingClientRect()),[e]),[l,c]=Ym(e);return(0,tg.useEffect)(()=>{c?i.open():i.close()},[c]),(0,Cs.jsxs)("span",{children:[(0,Cs.jsx)("mark",{ref:Qm([l,i.triggerRef]),className:(0,QI.default)(s.matchKeyword,{[s.hover]:c}),"aria-haspopup":"dialog","aria-expanded":i.opened?"true":"false",children:r}),i.opened&&(0,Cs.jsx)(Ga,{className:s.popover,triggerRef:i.triggerRef,boundaryRef:t,position:"below",align:"start",toStyle:a,children:(0,Cs.jsx)(Jm,{style:n,children:(0,Cs.jsx)("div",{className:s.hintText,children:o})})})]})},eg=class extends Co{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=>_(b({},o),{keywordRegex:new RegExp(`\\b${Xm(o.keyword)}\\b`,"i")})),this.keywordMatches=r.keywordMatches),this.usedKeywordMatches.clear(),n}match(n){let r=this.preparedKeywordMatches.map(s=>{if(this.usedKeywordMatches.has(s))return null;let i=n.match(s.keywordRegex);if(!i)return null;let a=n.charAt(i.index-1),l=n.charAt(i.index+s.keyword.length);return a==="{"&&l==="}"?null:{index:i.index,length:i[0].length,match:i[0],matchString:i[0],suggestion:s.suggestion,preparedKeywordMatch:s,valid:!0}}).filter(YI);if(r.length===0)return null;let o=r.reduce((s,i)=>i.index<s.index?i:s);return this.usedKeywordMatches.add(o.preparedKeywordMatch),o}replaceWith(n,r){return(0,Cs.jsx)(Rz,{inputElement:r.inputElement,suggestion:r.suggestion,inputStyle:r.inputStyle,boundaryRef:r.boundaryRef,children:n},`keyword_${r.matchString}_${r.key}`)}asTag(){return"mark"}};var ZI=E(De());var ZS=E(A()),Pz=({inputElement:e,children:t})=>{let n=F("TabCompletion",Ao),[r,o]=Ym(e);return(0,ZS.jsx)("mark",{ref:r,className:(0,ZI.default)(n.matchPlaceholder,{[n.hover]:o}),children:t})},ng=class extends Co{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,ZS.jsx)(Pz,{inputElement:n.inputElement,children:t},`placeholder_${n.matchString}_${n.key}`)}asTag(){return"mark"}};var og=E(De());var sn=E(Q());function JI(e,t){let n=new URL(e),r=n.searchParams.get("redirect");if(r){let o=new URL(r,n.origin);return t.forEach((s,i)=>{o.searchParams.set(i,s)}),n.searchParams.set("redirect",`${o.pathname}${o.search}${o.hash}`),n.toString()}return t.forEach((o,s)=>{n.searchParams.set(s,o)}),n.toString()}var JS=E(A()),e_=()=>(0,JS.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,JS.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 qr=E(Q());var n_=E(CS());var t_={root:"dd-ky-Bv",content:"dd-kV5e1"};function rg(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(s){return null}}function ex(e){return e.replace("https://www.","").replace("https://","")}var nr=E(A()),Az=3,Iz=e=>({image:e.image||"",text:e.text,id:e.id,title:e.title}),_z=({onSelectLink:e,onDismiss:t,placeholder:n,visitUrlText:r,linkCount:o=Az})=>{let s=F("LinkSearch",t_),[i,a]=(0,qr.useState)(""),l=ve(),c=K(eI("url")),u=K(RE("URL")),f=(0,qr.useMemo)(()=>u.map(Iz),[u]),[d,p]=(0,qr.useState)(f.length-1),h=Z("fallbackImage"),y=v=>{let x=v.target;a(x.value)},S=(v,x)=>{v.stopPropagation(),v.preventDefault(),window.open(x,"_blank")},m=v=>{var C;let x=d-1<0?f.length-1:d-1,T=d+1===f.length?0:d+1;v.code==="Escape"&&(a(""),t()),v.code==="ArrowUp"&&p(x),v.code==="ArrowDown"&&p(T),v.code==="Enter"&&e(((C=f[d])==null?void 0:C.text)||i)},g=(0,qr.useCallback)((0,n_.default)(v=>{l(Hs({query:v,type:"URL",tags:["link-search"]}))},300),[]);return(0,qr.useEffect)(()=>{i&&g(i)},[i]),(0,qr.useEffect)(()=>()=>{l($d())},[]),(0,nr.jsxs)("div",{className:s.root,children:[(0,nr.jsx)(Ct,{withDivider:!0,children:(i?f:c).slice(0,o).map((v,x)=>(0,nr.jsx)(fe,{selected:d===x,onClick:()=>e(v.text),"data-testid":"linksearch-suggestion",children:(0,nr.jsxs)(Ee,{children:[(0,nr.jsx)(Ee.Image,{src:rg(v,"small",h||void 0),title:v.title||v.text}),(0,nr.jsxs)(Ee.Content,{className:s.content,cropText:!0,children:[(0,nr.jsx)(Ee.Title,{children:v.title||ex(v.text)}),v.title&&ex(v.text)]}),(0,nr.jsx)(fe.Actions,{children:(0,nr.jsx)(fe.ActionButton,{label:r,onClick:T=>S(T,v.text)})})]})},v.text))}),(0,nr.jsx)(tu,{value:i,onChange:y,autoFocus:!0,placeholder:n,onKeyUp:m})]})},r_=_z;var tx={};ut(tx,{enUS:()=>Mz,nlNL:()=>Lz});var Mz={insertLink:[{type:0,value:"Insert link"}],linkInputPlaceholder:[{type:0,value:"Search, type or paste link"}],visitUrl:[{type:0,value:"Visit"}],addToPersonalCollection:[{type:0,value:"Add to Personal Collection"}]},Lz={insertLink:[{type:0,value:"Voeg link toe"}],linkInputPlaceholder:[{type:0,value:"Zoek, typ of plak link"}],visitUrl:[{type:0,value:"Bekijk"}],addToPersonalCollection:[{type:0,value:"Toevoegen aan Personal Collection"}]};var It=E(A()),Oz=(0,sn.forwardRef)((e,t)=>{let n=F("TabCompletion",Ao);return(0,It.jsx)("mark",{ref:t,className:(0,og.default)(n.matchSelection)},"selection-start")}),Nz=({startRef:e,boundaryRef:t,inputStyle:n,inputElement:r,children:o})=>{let s=ae(tx),i=F("TabCompletion",Ao),a=Z("addToPersonalCollection"),l=K(na("/admin/personal-collection/new")),c=K(v=>{var x;return(x=v.conversation.current)==null?void 0:x.profileCode}),u=K(Vn)!==null,f=(0,sn.useRef)(null),d=(0,sn.useRef)(null),[p,h]=(0,sn.useState)(null),y=ve(),S=um(document.activeElement===r),[m]=(0,sn.useState)(()=>document.createRange());S.triggerRef.current=m,(0,sn.useEffect)(()=>()=>m.detach(),[]),(0,sn.useEffect)(()=>{let v=e.current,x=f.current;!v||!x||(m.setStart(v,0),m.setEnd(x,0))},[e.current,f.current]),ms(()=>{S.close()});let g=(0,sn.useCallback)(v=>{let x=m.toString(),T=/^http(s?):\/\//.test(v)?v:`https://${v}`,C=`[${x}](${T})`;y(Cn({text:C,suggestion:{text:C,source:"search-url",type:"url"},eventMetrics:{inputType:"mouse"},replace:"selection"}))},[]);return(0,It.jsxs)("span",{children:[(0,It.jsx)("mark",{ref:f,className:(0,og.default)(i.matchSelection),"aria-haspopup":"dialog","aria-expanded":S.opened?"true":"false",children:o}),S.opened&&(0,It.jsx)(Ga,{className:i.popoverRoot,triggerRef:S.triggerRef,boundaryRef:t,position:"above",align:"start",children:(0,It.jsxs)(Jm,{style:n,ref:d,children:[(0,It.jsxs)("div",{className:(0,og.default)(i.selectionOptions,{[i.selectionOptionsIsHidden]:p!==null}),children:[(0,It.jsxs)("button",{type:"button",tabIndex:p===null?-1:void 0,className:i.selectionOptionsButton,onClick:()=>h("insertLink"),children:[(0,It.jsx)(e_,{}),(0,It.jsx)("span",{children:"\xA0"}),(0,It.jsx)("span",{children:s("insertLink")})]}),a&&l&&(0,It.jsx)("button",{type:"button",tabIndex:p===null?-1:void 0,className:i.selectionOptionsButton,onClick:()=>{let v=m.toString(),x=new URLSearchParams({text:v});u&&c&&x.set("profile",c);let T=JI(l,x);window.open(T,"_blank")},children:(0,It.jsx)("span",{children:s("addToPersonalCollection")})})]}),p==="insertLink"&&(0,It.jsx)(r_,{placeholder:s("linkInputPlaceholder"),visitUrlText:s("visitUrl"),onSelectLink:g,onDismiss:()=>{h(null),S.close()}})]})})]},"selection-end")},sg=class extends Co{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,sn.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 s=this.foundIndex===0?r:o,i=s>=this.charCount&&s<=this.charCount+n.length?{index:s-this.charCount,length:0,match:"",valid:!0}:null;i&&this.foundIndex++;let a=this.foundIndex===1;return i&&a?this.charCount+=s-this.charCount:this.charCount+=n.length,i?b({isStart:a},i):null}replaceWith(n,r){return r.isStart?(0,It.jsx)(Oz,{ref:this.startRef}):(0,It.jsx)(Nz,{inputElement:r.inputElement,startRef:this.startRef,boundaryRef:r.boundaryRef,inputStyle:r.inputStyle})}asTag(){return"mark"}};var Io=E(A()),Dz=({enabled:e,content:t,tabText:n,showTabHint:r,showTabCompletion:o,showStyleSuggestions:s,keywordMatches:i,inputElement:a,source:l})=>{let c=F("TabCompletion",GI),u=Z("insertLink"),f=Z("addToPersonalCollection"),d=Z("showMidSentenceSuggestions"),p=Z("inlineSuggestions"),h=$I(a),y=(0,_o.useRef)(null),S=K(kt);(0,_o.useEffect)(()=>{Ri(a)&&h&&jI(a,h)},[h]);let m=(0,_o.useCallback)(x=>{if(!o||!n)return x;let T=[(0,Io.jsx)("span",{className:c.resetIndent,children:"\u200B"},"u200B"),(0,Io.jsx)("span",{"data-testid":"tab-completion",className:(0,ig.default)(c.tabText,c.resetIndent),"data-source":l,children:n},"tabText")];return r&&T.push((0,Io.jsx)("span",{className:(0,ig.default)(c.hint,c.resetIndent),children:(0,Io.jsx)(sd,{keyCode:"tab"},"tabHint")},"tabHint")),XS(x,T)},[o,n,r]),g=(0,_o.useMemo)(()=>{let x=[];return(u||f)&&x.push(new sg("selection")),x.push(new ng("placeholders")),s&&x.push(new eg("keywords")),x},[p,u,f,s]),v=(0,_o.useMemo)(()=>{let x=window.getComputedStyle(a);return{"--dd-color":x.color,"--dd-font-size":x.fontSize,"--dd-font-family":x.fontFamily,"--dd-font-variant":x.fontVariant}},[]);return!e||!S?null:(0,Io.jsxs)("div",{ref:x=>{x!=null&&x.parentElement&&(y.current=x==null?void 0:x.parentElement)},className:c.root,style:v,children:[(0,Io.jsx)(ys,{tagName:"span",containerTagName:"div",className:(0,ig.default)(c.container,c.agentText),disableLineBreaks:Ri(a),content:t||"\u200B",onAfterParse:m,matchers:g,selection:h,keywordMatches:i,inputElement:a,inputStyle:v,boundaryRef:y,inlineSuggestionsOnlyAtEnd:!d}),(0,Io.jsx)("br",{})]},"tab-completion")},Fz=e=>{var m,g,v;let{input:t,ui:n,settings:r,styleSuggestions:o,conversation:s}=e,i=Xi({input:t}),a=(i==null?void 0:i.text)||"",l=(i==null?void 0:i.source)||"",c=(m=t.html)!=null?m:Qa(t.text),u=t.text.slice(t.suggestionTextStart,t.selection.end),f=a.indexOf(u)===0?a.slice(u.length):"",{showTabHint:d}=n,{isSupported:p}=s,{showTabCompletion:h,visible:y,showStyleSuggestions:S}=r;return{showTabHint:d,showStyleSuggestions:S,showTabCompletion:h&&Gr(e),content:c,tabText:f,source:l,keywordMatches:(v=(g=o.list)==null?void 0:g.keywordMatches)!=null?v:[],enabled:y&&p!==!1}},o_=Xw(Fz)(Dz);var or=E(Q());var zz={token:null,interval:null},nx=me("passwordlessToken/getTemporaryPasswordlessToken",(e,t)=>M(null,null,function*(){let{deepdeskAPI:n}=t.extra;return{token:yield n.requestPasswordlessToken()}})),rx=me("passwordlessToken/pollPasswordlessToken",(e={},t)=>{let{interval:n=1e3*60*10}=e,{dispatch:r}=t;return r(nx()),setInterval(()=>r(nx()),n)}),s_=Pe({name:"passwordlessToken",initialState:zz,reducers:{stopPollPasswordlessToken(e){e.interval&&clearInterval(e.interval),e.interval=null}},extraReducers:e=>{e.addCase(nx.fulfilled,(t,n)=>{t.token=n.payload.token}),e.addCase(rx.fulfilled,(t,n)=>{t.interval=n.payload})}}),{stopPollPasswordlessToken:i_}=s_.actions,a_=s_.reducer;function Hz(e){return"buttonText"in e&&"eventName"in e}function l_(e){if(e)return Hz(e)?{label:e.buttonText,event:e.eventName,value:e.payload}:e}function Bz(e){return e==null?void 0:e.map(t=>l_(t))}function ag(e){return typeof e!="string"?void 0:e.trim().toLowerCase()||void 0}function Tu(e,t){let n=ag(t);n&&e.add(n)}function Uz(e){var r,o,s;let t=new Set,n=new Set;if(!Array.isArray(e))return{codes:t,names:n};for(let i of e){if(!i||typeof i!="object")continue;let a=i,l=typeof a.assistant=="object"?a.assistant:void 0;((s=(o=(r=a.isSilent)!=null?r:a.is_silent)!=null?o:l==null?void 0:l.isSilent)!=null?s:l!=null&&l.is_silent)&&(Tu(t,typeof a.assistant=="string"?a.assistant:l==null?void 0:l.code),Tu(n,a.assistantName),Tu(n,a.assistant_name),Tu(n,a.displayName),Tu(n,a.display_name))}return{codes:t,names:n}}function ox(e,t){var s,i,a;let{codes:n,names:r}=Uz(t);if(n.size===0&&r.size===0)return!1;let o=(i=ag(e.code))!=null?i:ag((s=e.rule)==null?void 0:s.label);return o?n.has(o):[e.name,e.title,(a=e.rule)==null?void 0:a.name].some(l=>{let c=ag(l);return c!==void 0&&(r.has(c)||n.has(c))})}function Vz(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_=Yt([sC,Nd,Xa],(e,t,n)=>(t?e.filter(i=>!i.externalConversationId||i.externalConversationId===t):e).filter(i=>!ox(i,n)).map(i=>{var c;let a=l_(i.callToAction),l=Bz(i.callToActions);return _(b(b(b(b({text:i.response,title:i.name},a?{callToAction:a}:{}),l!=null&&l.length?{callToActions:l}:{}),i.message!==void 0?{message:i.message}:{}),(c=i.sources)!=null&&c.length?{sources:i.sources}:{}),{editable:i.editable,isLoading:i.isLoading,evaluationId:i.evaluationId,rule:{id:Vz(i.code),label:i.code,name:i.name,description:i.name}})}));var lg=E(Q()),ix=E(De());var sx=E(A()),ol=()=>(0,sx.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",children:(0,sx.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 u_={root:"dd-WcEru",entity:"dd-LfP8y",entityText:"dd-L-v0f",iconWrapper:"dd-9Deh1",icon:"dd-tM7E2",iconClicked:"dd-EEdDL"};var Yr=E(A()),Wz=({entities:e})=>{let t=F("EntitiesWidgetList",u_),[n,r]=(0,lg.useState)(void 0),o=tt(),s=()=>{r(void 0)},i=a=>{e&&(r(e.indexOf(a)),Mr(a.text),o("entity copied",{entity:a,type:"copy"}))};return(0,lg.useEffect)(()=>{let a=setTimeout(s,500);return()=>{clearTimeout(a)}},[n]),!e||e.length===0?null:(0,Yr.jsx)("div",{className:t.root,"data-testid":"widget-entities-list",children:e.map((a,l)=>(0,Yr.jsxs)("button",{title:a.text,className:t.entity,type:"button",onClick:()=>i(a),children:[(0,Yr.jsx)("span",{className:t.entityText,children:a.text}),(0,Yr.jsxs)("span",{className:t.iconWrapper,children:[(0,Yr.jsx)("span",{className:(0,ix.default)(t.icon),children:(0,Yr.jsx)(ol,{})}),(0,Yr.jsx)("span",{className:(0,ix.default)(t.icon,n===l&&t.iconClicked),children:(0,Yr.jsx)(ol,{})})]})]},a.text))})},d_=Wz;var ax=E(A()),f_=()=>(0,ax.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,ax.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 S_=E(Q());var p_={root:"dd-ohnXe",trigger:"dd-7i-S3",button:"dd-t53Cg",nav:"dd-qZFnm",item:"dd-FZC0F"};var m_={root:"dd-nazq3",rotation:"dd-3EHTv"};var h_=E(A()),$z=({size:e=12})=>{let t=F("LoadingSpinner",m_);return(0,h_.jsx)("span",{"data-testid":"loading-spinner",style:{width:`${e}px`,height:`${e}px`},className:t.root})},g_=$z;var lx=E(A()),y_=()=>(0,lx.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 0 512 512",fill:"currentColor",children:(0,lx.jsx)("path",{d:"M256 32c14.2 0 27.3 7.5 34.5 19.8l216 368c7.3 12.4 7.3 27.7 .2 40.1S486.3 480 472 480H40c-14.3 0-27.6-7.7-34.7-20.1s-7-27.8 .2-40.1l216-368C228.7 39.5 241.8 32 256 32zm0 128c-13.3 0-24 10.7-24 24V296c0 13.3 10.7 24 24 24s24-10.7 24-24V184c0-13.3-10.7-24-24-24zm32 224c0-17.7-14.3-32-32-32s-32 14.3-32 32s14.3 32 32 32s32-14.3 32-32z"})});var ku=E(A()),v_=e=>(0,ku.jsxs)("svg",_(b({xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 448 512","aria-labelledby":"checkTitle"},e),{children:[(0,ku.jsx)("title",{id:"checkTitle",children:"Check"}),(0,ku.jsx)("path",{fill:"#666",d:"M438.6 105.4c12.5 12.5 12.5 32.8 0 45.3l-256 256c-12.5 12.5-32.8 12.5-45.3 0l-128-128c-12.5-12.5-12.5-32.8 0-45.3s32.8-12.5 45.3 0L160 338.7 393.4 105.4c12.5-12.5 32.8-12.5 45.3 0z"})]}));var cx={};ut(cx,{enUS:()=>jz,nlNL:()=>Kz});var jz={error:[{type:0,value:"Something went wrong"}]},Kz={error:[{type:0,value:"Er ging iets fout"}]};var Hn=E(A()),Gz=3e3,qz=({assistantOptions:e})=>{let t=F("OnDemandAssistants",p_),n=ae(cx),r=(0,S_.useRef)(),o=ve(),s=_l(kn),i=K(Xa),a=tt(),l=i.filter(d=>d.isPinned),c=i.filter(d=>!d.isPinned),u=()=>M(null,null,function*(){return e.attachments&&e.attachments.length>0?e.attachments:o(((d,p,h)=>M(null,null,function*(){let y;if(e.transcript==="in-memory-transcript"){let S=h.dynamicThunkObject.conversationQuery;if(S){let m=yield S();y=Array.isArray(m)?m:void 0}}else Array.isArray(e.transcript)&&(y=e.transcript);return ry({transcript:y})})))}),f=(d,p=!1)=>M(null,null,function*(){clearTimeout(r.current);let h=yield u();a("trigger on demand assistant",{assistantCode:d}),yield s.call(b(_(b({},e),{assistantCode:d,silent:p}),h.length>0?{attachments:h}:{})),r.current=setTimeout(()=>s.reset(),Gz)});return i.length===0?null:(0,Hn.jsxs)("div",{className:t.root,children:[l.map(({assistant:d,assistantName:p,displayName:h,isSilent:y})=>(0,Hn.jsx)("button",{type:"button",className:t.button,disabled:s.state==="loading",onClick:()=>f(d,y),children:h||p},d)),c.length>0&&(0,Hn.jsxs)(Xe,{placement:"top-end",children:[(0,Hn.jsx)(Xe.Trigger,{className:t.trigger,disabled:s.state==="loading",children:(0,Hn.jsx)(Lm,{"data-testid":"trigger"})}),(0,Hn.jsx)(Xe.Content,{className:t.nav,"data-testid":"popover",children:c.map(({assistant:d,assistantName:p,displayName:h,isSilent:y})=>(0,Hn.jsx)(Xe.Button,{className:t.item,disabled:s.state==="loading",onClick:()=>f(d,y),children:h||p},d))})]}),s.state==="loading"&&(0,Hn.jsx)(g_,{}),s.state==="done"&&(0,Hn.jsx)(v_,{"data-testid":"trigger-done"}),s.state==="error"&&(0,Hn.jsx)(DP,{trigger:(0,Hn.jsx)(y_,{}),children:n("error")})]})},x_=qz;var Pi=E(Q());var Ru={};ut(Ru,{enUS:()=>Yz,nlNL:()=>Xz});var Yz={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"}]},Xz={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 ux={title:"dd-YBHrC",fadeup:"dd-cRM0K",fadedown:"dd-7D4Pq",selected:"dd-bueui",actions:"dd-9Iqn9",ctaMessage:"dd-ge8nB",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 _t=E(A()),Qz=500,Zz=100,Jz=({content:e,onChange:t,onCopy:n})=>{let r=(0,Pi.useRef)(null),o=F("WidgetCue",ux);return(0,Pi.useEffect)(()=>{let s=r.current;if(!s)return;s.style.setProperty("height","0px");let i=Math.min(Math.max(s.scrollHeight,Zz),Qz);s.style.setProperty("height",`${i}px`)},[e]),(0,_t.jsx)("textarea",{ref:r,className:o.editableCue,onCopy:n,onChange:t,value:e})},e9=({cue:e,onCallToAction:t,onRemove:n,onCopy:r,onUse:o,onSourceClick:s})=>{var S;let i=F("WidgetCue",ux),a=ae(Ru),l=tt(),c=Z("hasKeyboardInput"),[u,f]=(0,Pi.useState)(e.text),d=m=>{let g=m?_(b({},e),{callToAction:m}):e;t&&t(u,g),n(e)},p=(m,g)=>{r&&r(m,e),g&&Vo(g,i.fadeup)},h=m=>{o&&o(m,e)},y=m=>{m.preventDefault(),m.stopPropagation(),n(e)};return(0,Pi.useEffect)(()=>{l("Assistant response displayed",{evaluationId:e.evaluationId,assistantCode:e.rule.label,assistantOutput:e.text})},[]),(0,_t.jsxs)(fe,{"data-testid":"cue",children:[(0,_t.jsx)(Ee,{children:(0,_t.jsxs)(Ee.Content,{children:[e.title&&(0,_t.jsx)(Ee.Title,{className:i.title,"data-testid":"widget-cue-title",children:e.rule.label.startsWith("__")?a(e.rule.label):e.title}),e.message&&(0,_t.jsx)("p",{className:i.ctaMessage,children:e.message}),e.editable?(0,_t.jsx)(Jz,{content:u,onCopy:()=>{let m=document.getSelection();m&&p(m.toString())},onChange:m=>{var g;return f((g=m.target.value)!=null?g:"")}}):(0,_t.jsx)(gi,{content:e.text,sources:e.sources,onSourceClick:m=>s==null?void 0:s(m,e),useLabel:a("useCue"),copyLabel:a("copyCue"),onCopy:p,onUse:c?h:void 0})]})}),(0,_t.jsxs)(fe.ButtonsContainer,{children:[(0,_t.jsxs)("div",{className:i.actions,children:[(0,_t.jsx)(fe.Button,{onClick:m=>{var g;return p((g=uf(u,"reply")[0])!=null?g:u,m.target)},variant:"primary",children:a("copyCue")}),e.callToAction&&(0,_t.jsx)(fe.Button,{onClick:()=>d(),variant:"primary",children:e.callToAction.label}),(S=e.callToActions)==null?void 0:S.map((m,g)=>(0,_t.jsx)(fe.Button,{onClick:()=>d(m),variant:"primary",children:m.label},`${m.event}-${m.label}-${g}`)),(0,_t.jsx)(fe.Button,{onClick:y,variant:"secondary",children:a("removeCue")})]}),(0,_t.jsx)(yf,{evaluationId:e.evaluationId,assistantCode:e.rule.label,assistantOutput:e.text,feedbackType:"assistant"})]})]})},w_=e9;var sl=E(A()),t9=({cues:e})=>{let t=ve(),n=cn(),r=ae(Ru),o=tt(),s=K(Xa),i=d=>{t(ff({code:d.rule.label})),o("Assistant response closed",{evaluationId:d.evaluationId,assistantCode:d.rule.label,assistantOutput:d.text})},a=(d,p)=>{Mr(d),o("Assistant response copied",{evaluationId:p.evaluationId,assistantCode:p.rule.label,assistantOutput:p.text,copiedText:d})},l=(d,p)=>{var h;p.callToAction&&(t(df(p)),o("Assistant call to action",{evaluationId:p.evaluationId,assistantCode:p.rule.label,assistantOutput:p.text,eventName:p.callToAction.event,value:(h=p.callToAction.value)!=null?h:d}))},c=(d,p)=>{var h;n.send(no,{text:d,suggestion:{source:"assistant",assistantCode:(h=p.rule)==null?void 0:h.label,sourceText:d}}),o("Assistant response used",{evaluationId:p.evaluationId,assistantCode:p.rule.label,assistantOutput:p.text,usedText:d})},u=(d,p)=>{o("Assistant source clicked",{evaluationId:p.evaluationId,assistantCode:p.rule.label,source:d})},f=e.filter(d=>!ox(d,s));return(0,sl.jsx)(sl.Fragment,{children:f.map(d=>d.isLoading?(0,sl.jsx)(fm,{title:d.rule.label.startsWith("__")?r(d.rule.label):d.title},d.rule.id):(0,sl.jsx)(w_,{cue:d,onCallToAction:l,onRemove:i,onCopy:a,onUse:c,onSourceClick:u},d.evaluationId))})},b_=t9;var cg=E(Q());var E_={root:"dd-cvTAY",label:"dd-QWQxD",value:"dd-WSUHF",copyButton:"dd-67o9H",copyButtonText:"dd-oos-l",isTrue:"dd--1g2O",isFalse:"dd-sz2ir"};var Sn=E(A());function n9(e,t){return t.split(".").reduce((n,r)=>!n||typeof n!="object"||!(r in n)?null:n[r],e)}var C_=({data:e,schema:t})=>{let n=F("WidgetCustomData",E_),r=o=>{Mr(o)};return(0,cg.useEffect)(()=>{J.info("Custom data",e,t)},[e]),(0,Sn.jsx)("dl",{className:n.root,children:t.map(o=>{let s=n9(e,o.path);return(0,Sn.jsxs)(cg.Fragment,{children:[(0,Sn.jsx)("dt",{className:n.label,children:o.label}),(0,Sn.jsx)("dd",{className:n.value,children:o.type==="boolean"&&s?(0,Sn.jsx)("span",{className:n.isTrue,children:o.trueValue}):o.type==="boolean"&&!s?(0,Sn.jsx)("span",{className:n.isFalse,children:o.falseValue}):o.type==="array"&&Array.isArray(s)&&s.length>0?(0,Sn.jsxs)("button",{type:"button",onClick:()=>r(s.join(", ")),className:n.copyButton,children:[(0,Sn.jsx)("span",{className:n.copyButtonText,children:s.join(", ")}),(0,Sn.jsx)(ol,{})]}):typeof s=="string"||typeof s=="number"?(0,Sn.jsxs)("button",{type:"button",onClick:()=>r(`${s}`),className:n.copyButton,children:[(0,Sn.jsx)("span",{className:n.copyButtonText,children:s}),(0,Sn.jsx)(ol,{})]}):"-"})]},o.label)})})};var k_=E(Q());var r9=/(https?:\/\/[^\s]+)/,T_=e=>e.split(" ").find(t=>r9.test(t));var rr=E(A()),o9=({suggestion:e,lines:t,onUse:n})=>{var f;let r=e.text||e.url||e.message,o=T_(r),s=ae(gu),i=Z("showImages"),a=Z("fallbackImage"),l=Z("hasKeyboardInput"),c=d=>{d.preventDefault(),d.stopPropagation(),l&&n(r)},u=(0,k_.useCallback)(d=>{window.open(o,"_blank"),d.stopPropagation(),d.preventDefault()},[o]);return(0,rr.jsxs)(fe,{onClick:l?c:void 0,"data-testid":"edit-suggestion",children:[(0,rr.jsxs)(Ee,{children:[i&&e.image&&(0,rr.jsx)(Ee.Image,{src:rg(e,"small",a||void 0),title:e.title}),(0,rr.jsxs)(Ee.Content,{children:[e.title&&(0,rr.jsx)(Ee.Title,{"data-testid":"widget-suggestion-title",children:e.title}),e.searchKeywords&&((f=e.searchKeywords)==null?void 0:f.length)>0&&(0,rr.jsx)(fe.Labels,{labels:e.searchKeywords}),(0,rr.jsx)(Ee.Content,{cropText:t==="single",lineClamp:t==="multiple",children:r})]})]}),(0,rr.jsxs)(fe.Actions,{children:[o&&(0,rr.jsx)(fe.ActionButton,{onClick:u,label:s("visitUrl")}),l&&(0,rr.jsx)(fe.ActionButton,{primary:!0,onClick:c,label:s("useSuggestion")})]})]})},R_=o9;var Pu=E(A()),s9=({lines:e,suggestions:t})=>{let n=cn(),r=(o,s)=>{n.send(no,{text:o,suggestion:_(b({},s),{source:s.source,sourceText:s.text})})};return(0,Pu.jsx)(Pu.Fragment,{children:t.map(o=>(0,Pu.jsx)(R_,{suggestion:o,lines:e,onUse:s=>r(s,o)},o.text||o.url||o.message))})},P_=s9;var Au={};ut(Au,{enUS:()=>i9,nlNL:()=>a9});var i9={waiting:[{type:0,value:"Loading\u2026"}],waitingForConversation:[{type:0,value:"Waiting for conversation\u2026"}],notSupported:[{type:0,value:"This conversation is not supported"}],noResults:[{type:0,value:"No results found\u2026"}],titleCues:[{type:0,value:"Assistant updates"}],actions:[{type:0,value:"Shortcuts"}],linkStudioLogin:[{type:0,value:"My "},{type:1,value:"productName"}],linkSummary:[{type:0,value:"Summarize"}],linkKnowledgeSearch:[{type:0,value:"Knowledge Assist"}],linkSearch:[{type:0,value:"Search"}],close:[{type:0,value:"Close"}]},a9={waiting:[{type:0,value:"Laden\u2026"}],waitingForConversation:[{type:0,value:"Wachten op gesprek\u2026"}],notSupported:[{type:0,value:"Dit gesprek wordt niet ondersteund"}],noResults:[{type:0,value:"Geen resultaten gevonden\u2026"}],titleCues:[{type:0,value:"Assistant updates"}],actions:[{type:0,value:"Shortcuts"}],linkStudioLogin:[{type:0,value:"Mijn "},{type:1,value:"productName"}],linkSummary:[{type:0,value:"Gesprek samenvatten"}],linkKnowledgeSearch:[{type:0,value:"Knowledge assist"}],linkSearch:[{type:0,value:"Zoeken"}],close:[{type:0,value:"Sluiten"}]};var Ai={root:"dd-W9VCG",loginText:"dd--dS6t",stateText:"dd-348OC",footer:"dd-tvofr",shortcutList:"dd-MuKK-",shortcut:"dd-5CnK9",footerShortcut:"dd-dH7XJ",link:"dd-DRo0x",interactiveAssistantTabs:"dd-eSP1-",interactiveAssistantTab:"dd-CwcHD",interactiveAssistantTabActive:"dd-GzRs-"};var le=E(A()),A_=(e,t)=>{let n=K(kt);(0,or.useEffect)(()=>n?t.every(r=>!!r)?e():()=>{}:()=>{},[...t,n])},l9=({onLogIn:e})=>{let t=F("Widget",Ai),n=Z("isEmbedded"),r=Z("adminUrl");return(0,le.jsx)("div",{className:t.loginText,children:(0,le.jsx)("div",{children:(0,le.jsx)(Km,{isEmbedded:n,loginUrl:r,onLogIn:e})})},"login")},dx=({text:e})=>{let t=F("Widget",Ai);return(0,le.jsx)("div",{className:t.stateText,children:(0,le.jsx)("div",{children:(0,le.jsx)("p",{children:e})})},"notification")},c9=()=>{let e=ae(Au),t=ve(),n=F("Widget",Ai),r=Z("showSearch"),o=Z("isEmbedded"),s=K(na("/admin/")),i=cn(),a=Z("productName"),l=tt();return A_(()=>{if(o)return t(rx()),()=>{t(i_())}},[t,o]),!r&&!s?null:(0,le.jsxs)("div",{className:n.shortcutList,children:[r&&(0,le.jsx)(fe.Button,{"data-testid":"shortcut-search","aria-label":e("linkSearch"),className:n.shortcut,icon:(0,le.jsx)(Ja,{}),onClick:()=>{i.send("ShowCommandPalette",{isOpen:!0}),l("open search",{via:"widget-shortcut"})},children:e("linkSearch")}),s&&(0,le.jsx)(fe.Button,{as:"a",target:"_blank",icon:(0,le.jsx)(f_,{}),href:s,"data-testid":"shortcut-studio-login","aria-label":e("linkStudioLogin",{productName:a}),className:n.shortcut,rel:"noreferrer",onClick:()=>{l("open my deepdesk",{via:"widget-shortcut"})},children:e("linkStudioLogin",{productName:a})})]})},u9=({title:e,content:t})=>{let n=ae(Au),[r,o]=(0,or.useState)(!0);return r?(0,le.jsx)(Pr,{"data-testid":"custom-data-banner",type:"custom-data-banner",title:e,children:(0,le.jsx)(Ct,{withDivider:!0,children:(0,le.jsxs)(fe,{children:[(0,le.jsx)(Ee,{children:(0,le.jsx)(Ee.Content,{children:(0,le.jsx)(gi,{content:t})})}),(0,le.jsx)(fe.ButtonsContainer,{children:(0,le.jsx)(fe.Button,{onClick:()=>o(!1),children:n("close")})})]})})}):null},d9=()=>{let e=ve(),t=K(ou),n=K(bA),r=K(c_),o=K(hE),s=K(Mm),i=K(Nm),a=K(tr),l=K(Vn);return(0,or.useEffect)(()=>{o&&!n&&J.warn("Custom data provided, but no schema.")},[o,n]),A_(()=>{t.forEach(({type:c})=>{c==="entities"?e(Er()):cd.includes(c)||e(Cr(c))})},[e,l,a]),(0,or.useEffect)(()=>{r.length>0&&!t.some(c=>c.type==="cues")&&J.warn("Received cues, but cues are not configured in widget.")},[t,r]),(0,le.jsx)(or.Fragment,{children:t.map(({type:c,title:u,amount:f,lines:d,schema:p,property:h})=>{var y,S;switch(c){case"entities":return s&&s.length>0&&(0,le.jsx)(Pr,{type:c,title:u,"data-testid":`type-${c}`,children:(0,le.jsx)(d_,{entities:s})},c);case"cues":return r&&r.length>0&&(0,le.jsx)(Pr,{type:c,title:u,"data-testid":`type-${c}`,children:(0,le.jsx)(Ct,{withDivider:!0,children:(0,le.jsx)(b_,{cues:r})})},c);case"custom-data-banner":return o&&h&&o[h]&&(0,le.jsx)(u9,{title:u,content:String(o[h])},c);case"custom-data":return o&&p&&(0,le.jsx)(Pr,{type:c,title:u,"data-testid":`type-${c}`,children:(0,le.jsx)(Ct,{withDivider:!0,children:(0,le.jsx)(C_,{data:o,schema:p})})},c);default:return((S=(y=i[c])==null?void 0:y.suggestions)==null?void 0:S.length)>0&&(0,le.jsx)(Pr,{type:c,title:u,"data-testid":`type-${c}`,children:(0,le.jsx)(Ct,{withDivider:!0,children:(0,le.jsx)(P_,{lines:d,contentType:c,suggestions:i[c].suggestions.slice(0,f)||[]})})},c)}})})},fx=({children:e})=>{let t=F("Widget",Ai);return(0,le.jsx)("div",{className:t.footer,children:e})},px=({children:e})=>{let t=F("Widget",Ai);return(0,le.jsx)("div",{className:t.root,"data-testid":"widget",children:e})},f9=({onLogIn:e,knowledgeAssistOptions:t={},assistantOptions:n={transcript:"in-memory-transcript"},openAdminFeedback:r})=>{var x;let o=ae(Au),s=F("Widget",Ai),i=ve(),a=K(Yi),l=K(kt),c=K(Nd),u=K(tr),f=K(wA("knowledge-assist")),d=K(EA),p=K(lC),h=K(aC),y=(x=d.find(T=>T.code===p))!=null?x:d[0],[S,m]=(0,or.useState)(t.initialQuestion);(0,or.useEffect)(()=>{m(t.initialQuestion)},[c,t.initialQuestion]),(0,or.useEffect)(()=>{if(!c)return;let T=kl(c);T&&i(sy(T))},[i,c]),(0,or.useEffect)(()=>{if(d.length===0)return;let T=d.some(C=>C.code===p);(!p||!T)&&i(oy(d[0].code))},[d,p,i]);let g=!!f&&d.length>0&&!!y,v=(y==null?void 0:y.displayName)||(y==null?void 0:y.name)||(f==null?void 0:f.title)||"Knowledge Assistant";return a===!1?(0,le.jsx)(dx,{text:o("notSupported")}):l===!1?(0,le.jsx)(l9,{onLogIn:e}):l===null?(0,le.jsx)(dx,{text:o("waiting")}):!c||!u?(0,le.jsx)(dx,{text:o("waitingForConversation")}):(0,le.jsx)(CC,{handler:r,children:(0,le.jsx)(px,{children:(0,le.jsxs)(gm,{initialQuestion:S,onInitialQuestionConsumed:()=>m(void 0),assistantCode:y==null?void 0:y.code,threadId:h,onThreadIdChange:T=>{y!=null&&y.code&&T!=null&&i(iy({assistantCode:y.code,threadId:T}))},evaluateKnowledgeAssistFn:Gl,children:[(0,le.jsxs)($i,{children:[(0,le.jsx)(c9,{}),(0,le.jsx)(d9,{}),g&&(0,le.jsx)(ym,{title:v,emptyState:t.emptyState})]}),(0,le.jsxs)(fx,{children:[g&&d.length>1&&(0,le.jsx)("div",{className:s.interactiveAssistantTabs,"data-testid":"widget-interactive-assistant-tabs",children:d.map(T=>{let C=T.code===(y==null?void 0:y.code);return(0,le.jsx)("button",{type:"button","aria-pressed":C,className:C?s.interactiveAssistantTabActive:s.interactiveAssistantTab,onClick:()=>i(oy(T.code)),children:T.displayName||T.name},T.code)})}),g&&(0,le.jsx)(hm,{}),(0,le.jsx)(x_,{assistantOptions:n})]})]},y==null?void 0:y.code)})})},I_=f9;function il(e){let t=new Range;return t.selectNodeContents(e),t}function __(e,t,n){try{return Ts(e,t,n),!0}catch(r){return!1}}function ug(e){return"tagName"in e&&(e.tagName==="DIV"||e.tagName==="P")}function dg(e){return"tagName"in e&&e.tagName==="BR"}var Iu=/[\u200B-\u200D\uFEFF]/g;function Ts(e,t,n){let r=new Range;if(e.firstChild===null&&t===0&&n===0)return r.selectNodeContents(e),r;let o=0,s=!1;function i(l,c){let u=-1,f=/[\u200B-\u200D\uFEFF]/;if(!f.test(l))return c;for(let d=0;d<=l.length;d++)if(f.test(l[d])||u++,u===c)return d;throw new Error("Offset out of range")}function a(l){switch(l.nodeType){case Node.TEXT_NODE:{let c=l.textContent,u=c.replace(Iu,""),f=o+u.length,d=t>=o&&t<=f,p=n>=o&&n<=f;if(d){let h=i(c,t-o);h===0&&!p?r.setStartBefore(l):r.setStart(l,h)}p&&(r.setEnd(l,i(c,n-o)),s=!0),o=f;break}case Node.ELEMENT_NODE:{if(dg(l)&&(o===t&&r.setStartBefore(l),o++,o===n)){r.setEndAfter(l),s=!0;return}for(let u=0;u<l.childNodes.length&&(a(l.childNodes[u]),!s);u++);let c=l.lastChild;ug(l)&&c&&!ug(c)&&!dg(c)&&o++;break}default:break}}if(a(e),r.startContainer===document)throw new Error("Offsets out of bound");return r}function _u(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:s,collapsed:i}=t,a,l,c=0;function u(f){let d=f===e,p=f===n,h=f===o;switch(f.nodeType){case Node.TEXT_NODE:{let y=f.textContent;p&&(a=c+y.substring(0,r).replace(Iu,"").length),h&&(l=c+y.substring(0,s).replace(Iu,"").length),c+=y.replace(Iu,"").length;break}case Node.ELEMENT_NODE:{if(dg(f)&&f.nextSibling){c++;break}!d&&ug(f)&&f.previousSibling&&c++;for(let y=0;y<f.childNodes.length;y++){let S=p&&y===r,m=h&&y===s;if(S&&(a=c),m&&(l=c),l!==void 0||((!S||!i)&&u(f.childNodes[y]),h&&y===s-1&&(l=c),l!==void 0))break}h&&(l=c);break}default:break}}if(u(e),l===void 0)throw new Error("Could not determine start and end");return{start:a!=null?a:l,end:l}}function Mu(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:s,collapsed:i}=t,a=0,l="";function c(u){let f=u===e,d=u===n,p=u===o;switch(d&&(a=1),u.nodeType){case Node.TEXT_NODE:{if(a!==1)return;let h=d?r:0,y=p?s:void 0;l+=u.textContent.replace(Iu,"").substring(h,y);break}case Node.ELEMENT_NODE:{if(!i&&a===1&&dg(u)&&u.nextSibling){l+=`
|
|
82
82
|
`;break}!f&&!i&&a===1&&ug(u)&&u.previousSibling&&(l+=`
|
|
83
|
-
`);let h=d?r:0,y=p?Math.min(s,u.childNodes.length):u.childNodes.length;for(let S=h;S<y&&(c(u.childNodes[S]),a!==2);S++);break}default:break}p&&(a=2)}return c(e),l}var M_=(i=>(i.CUT="Cut",i.BACKSPACE="Backspace",i.DELETE="Delete",i.ERASEEOF="EraseEof",i.UNDO="Undo",i.CLEAR="Clear",i))(M_||{}),Mo=class{constructor(t){this.element=t;this.isFocused=!1;this.isActive=!0;this.isDisposed=!1;this.eventListeners={};this.disposeHandlers=[];this.cachedText="";this.cachedSuggestionTextStart=0;this.cachedCaretPosition=null;this.cachedSelection={start:0,end:0};this.cachedHTML="";this.isSubmitting=!1;this.isPossibleClearInputAction=!1;this.cachedText=this.getText(),this.cachedSuggestionTextStart=this.getSuggestionTextStart(),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.getSuggestionTextStart(),s=this.cachedCaretPosition===null;if(!this.isActive)return;t===""&&this.cachedText!==""&&!this.isPossibleClearInputAction&&this.emit("submit");let i=t!==this.cachedText,a=n!==null&&n!==this.cachedHTML,l=o!==this.cachedSuggestionTextStart;if((i||a||l)&&(i?(this.cachedText=t,this.cachedHTML=n):a&&(this.cachedHTML=n),this.cachedSuggestionTextStart=o,s=!0,this.emit("change",{plainText:t,rawHTML:n,suggestionTextStart:o})),(r.start!==this.cachedSelection.start||r.end!==this.cachedSelection.end)&&(this.cachedSelection=r,s=!0,this.emit("selection",r)),!s)return;let c=this.getCaretPosition();Bo(c,this.cachedCaretPosition)||(this.cachedCaretPosition=c,this.emit("caretposition",c))}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(M_).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()})}getSuggestionTextStart(){return 0}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 L_(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var Ii=class extends Mo{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),Mu(this.element,n)}getHTML(){return this.element.innerHTML||""}getRange(){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=r.rangeCount>0?r.getRangeAt(0):null;if(!o)return null;let s=this.element.ownerDocument.createRange();return s.setStart(o==null?void 0:o.startContainer,o==null?void 0:o.startOffset),s.setEnd(o==null?void 0:o.endContainer,o==null?void 0:o.endOffset),!s||!this.element.contains(s.startContainer)||!this.element.contains(s.endContainer)?null:s}getCaretPosition(){let n=this.getRange();if(!n||!n.collapsed||!("getBoundingClientRect"in n))return null;let r=n.getBoundingClientRect();return!L_(r)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),r=n.getBoundingClientRect(),n.deleteContents(),!L_(r))?null:{top:r.top+r.height,left:r.left}}getSelection(){let n=this.getRange();if(n)return _u(this.element,n);let r=this.lastKnownSelection;if(r&&__(this.element,r.start,r.end))return r;let o=il(this.element);return o.collapse(!1),_u(this.element,o)}getSelectedText(){let{start:n,end:r}=this.getSelection();return Mu(this.element,Ts(this.element,n,r))}listen(){super.listen();let n=new MutationObserver(s=>{var i,a;s.length===2&&s[0].addedNodes.length===1&&((i=s[0].addedNodes[0])==null?void 0:i.textContent)==="\u2060"&&((a=s[1].removedNodes[0])==null?void 0:a.textContent)==="\u2060"||setTimeout(()=>{this.handleInteraction()},0)});n.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0}),this.disposeHandlers.push(()=>n.disconnect());let 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 p9=["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 O_(e,t){let n="mozInnerScreenX"in window,r=document.createElement("div");r.id="input-textarea-caret-position-mirror-div";let o=r.style,s=window.getComputedStyle(e),i=e.ownerDocument.body;o.whiteSpace="pre-wrap",o.wordWrap="break-word",o.position="absolute",o.visibility="hidden",p9.forEach(u=>{o[u]=s[u]}),n?e.scrollHeight>Number.parseInt(s.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),i.appendChild(r);let l=e.getBoundingClientRect(),c={top:l.top-e.scrollTop+a.offsetTop+Number.parseInt(s.borderTopWidth)+a.offsetHeight,left:l.left-e.scrollLeft+a.offsetLeft+Number.parseInt(s.borderLeftWidth)};return i.removeChild(r),c}var _i=class extends Mo{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 O_(this.element,this.element.selectionEnd)}listen(){super.listen();let n=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var s;return(s=n==null?void 0:n.get)==null?void 0:s.call(this.element)},set:s=>{var i;(i=n==null?void 0:n.set)==null||i.call(this.element,s),this.handleInteraction()}}),this.addEventListener("scroll",()=>{this.emit("caretposition",this.getCaretPosition())});let 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 N_(e,t,n){let r=`deepdesk-iframe-${e}`,o=document.getElementById(r);if(o)return o;let s=document.createElement("iframe"),i=new URL(t);return Object.entries(n).forEach(([a,l])=>{i.searchParams.append(a,l)}),s.style.position="absolute",s.style.left="-999em",s.style.width="0px",s.style.height="0px",s.tabIndex=-1,s.id=r,s.title=`iframe-${e}`,s.src=i.toString(),window.document.body.appendChild(s),s}function m9(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(t){return e}}var mx=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()}},gx=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.disposeHandlers=[];this.iframe=N_(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()}},hx=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.eventMap,this.externalId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setExternalId(t){this.externalId!==t&&(this.cleanup(),J.info("Set externalId",t),this.externalId=t,this.channel=this.createChannel(t))}createChannel(t){let n=this.params.createCustomChannel?this.params.createCustomChannel(t):this.isCrossOrigin?new gx(t,this.deepdeskUrl,{debug:!0}):new mx(t),r=o=>{var i,a;if(o.origin!==this.deepdeskUrl)return;let s=m9(o.data);typeof s!="object"||s.type!=="event"||s.channel!==t||(J.info("Received broadcast event",this.externalId,o),(a=(i=this.eventMap)[s.name])==null||a.call(i,s.payload))};return n.onMessage(r),n}send(t,n,r){var i,a;J.info("Broadcast event",{externalId:this.externalId,name:t,payload:n});let o={type:"event",name:t,payload:n};r!==!1&&((a=(i=this.eventMap)[t])==null||a.call(i,n));let s=this.externalId==="deepdesk-general"?this.defaultChannel:this.channel;s==null||s.postMessage(_(b({},o),{channel:this.externalId}))}cleanup(t=!1){var n,r;(n=this.channel)==null||n.close(),this.channel=void 0,t&&((r=this.defaultChannel)==null||r.close(),this.defaultChannel=void 0)}},D_=hx;function g9(e){return e.replace(/(_\w)/g,t=>t[1].toUpperCase())}function He(e){return Array.isArray(e)?e.map(He):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>_(b({},t),{[g9(n)]:He(e[n])}),{}):e}function h9(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function Mt(e){return Array.isArray(e)?e.map(Mt):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>_(b({},t),{[h9(n)]:Mt(e[n])}),{}):e}var al=class extends Error{constructor(n,r){super(n);this.body=r;this.name="CustomError"}};var Lu=e=>new Promise(t=>{setTimeout(t,e)});var Tr=class extends al{constructor(){super(...arguments);this.name="ClientError"}},fg=class extends al{constructor(){super(...arguments);this.name="ServerError"}},yx=new Map;function F_(e){return M(this,null,function*(){if(e.status===204)return e.text().catch(()=>{}),null;let t=e.headers.get("content-type");if(t!=null&&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 Mi=class{constructor(t="",n={}){this.baseUrl=t;this.options=n;this.latestRequestByUrl={};this.refreshingToken=null;this.lastFailedRefreshAt=null;this.failedRefreshCooldown=1e4;var r;this.fetch=(r=n.fetch)!=null?r:window.fetch.bind(window)}patchFetch(t){this.fetch=t(this.fetch)}setCsrfToken(t){this.csrfToken=t}request(t,n={}){return new Promise((r,o)=>{let s={isAborted:!1,reject:o},i=`${this.baseUrl}${t}`,a=this.fetch,l=n.method===void 0||n.method.toLowerCase()==="get",C=n,{useCache:c=!1,abortLatest:u=!1,attempts:f=1,retryDelay:d=500,refreshTokenOn401:p=!0,retryOnError:h=k=>k instanceof TypeError,retryOnResponse:y=k=>k.status>=500,version:S=null}=C,m=ie(C,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]);if(c){if(!l)throw new Error(`Can't use 'useCache' for ${n.method}`);if(yx.has(i)){r(yx.get(i));return}}let g=_(b({credentials:"include"},m),{headers:b({Accept:"application/json","Content-Type":"application/json"},m.headers)});!l&&this.csrfToken&&(g.headers=_(b({},g.headers),{"X-CSRFToken":this.csrfToken})),typeof S=="string"&&(g.headers=_(b({},g.headers),{"X-Deepdesk-API-Version":S}));let v=f,x=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[i]&&u&&(this.latestRequestByUrl[i].isAborted=!0,this.latestRequestByUrl[i].reject(new Error("Aborted"))),this.latestRequestByUrl[i]=s;let T=()=>M(this,null,function*(){return v--,a(i,g).then(k=>M(this,null,function*(){return y(k)&&!s.isAborted&&v>0?(yield Lu(d),T()):k.status===401&&p===!0&&x===!1?(x=!0,yield this.refreshToken(),T()):k})).catch(k=>M(this,null,function*(){if(h(k)&&!s.isAborted&&v>0)return yield Lu(d),T();throw k}))});T().then(k=>M(this,null,function*(){let P=yield F_(k);if(delete this.latestRequestByUrl[i],k.status>=500){o(new fg("Server Error",P));return}if(k.status===401){o(new Tr("Unauthorized",P));return}if(k.status===403){o(new Tr("Forbidden",P));return}if(k.status===404){o(new Tr("Not Found",P));return}if(k.status>=400){o(new Tr("Bad Request",P));return}c&&yx.set(i,P),r(P)})).catch(k=>{o(k)})})}validateToken(){return M(this,null,function*(){let t,n,r;try{({has_valid_access_token:t,is_logged_in:n,has_valid_refresh_token:r}=yield this.get("/apis/admin/session/validate/",{refreshTokenOn401:!1}))}catch(o){return!1}if(!t){if(!r)return!1;try{yield this.refreshToken();let{is_logged_in:o}=yield this.get("/apis/admin/session/validate/",{refreshTokenOn401:!1});return o}catch(o){return!1}}return n})}refreshToken(){let t=Date.now();return this.lastFailedRefreshAt&&t-this.lastFailedRefreshAt<this.failedRefreshCooldown?Promise.reject(new Tr("Unauthorized","Failed to refresh token")):this.refreshingToken?this.refreshingToken:(this.refreshingToken=this.get("/apis/admin/session/refresh/",{refreshTokenOn401:!1}).catch(n=>{throw(n==null?void 0:n.message)==="Unauthorized"&&(this.lastFailedRefreshAt=Date.now()),n}).finally(()=>{this.refreshingToken=null}),this.refreshingToken)}get(t,n){return this.request(t,n)}post(t,n,r){return this.request(t,b({method:"POST",body:JSON.stringify(n)},r))}postWithStatus(t,n,r){return this.requestWithStatus(t,b({method:"POST",body:JSON.stringify(n)},r))}requestWithStatus(t,n={}){return new Promise((r,o)=>{let s={isAborted:!1,reject:o},i=`${this.baseUrl}${t}`,a=this.fetch,T=n,{useCache:l=!1,abortLatest:c=!1,attempts:u=1,retryDelay:f=500,refreshTokenOn401:d=!0,retryOnError:p=C=>C instanceof TypeError,retryOnResponse:h=C=>C.status>=500,version:y=null}=T,S=ie(T,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]),m=_(b({credentials:"include"},S),{headers:b({Accept:"application/json","Content-Type":"application/json"},S.headers)});this.csrfToken&&(m.headers=_(b({},m.headers),{"X-CSRFToken":this.csrfToken})),typeof y=="string"&&(m.headers=_(b({},m.headers),{"X-Deepdesk-API-Version":y}));let g=u,v=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[i]&&c&&(this.latestRequestByUrl[i].isAborted=!0,this.latestRequestByUrl[i].reject(new Error("Aborted"))),this.latestRequestByUrl[i]=s;let x=()=>M(this,null,function*(){return g--,a(i,m).then(C=>M(this,null,function*(){return h(C)&&!s.isAborted&&g>0?(yield Lu(f),x()):C.status===401&&d===!0&&v===!1?(v=!0,yield this.refreshToken(),x()):C})).catch(C=>M(this,null,function*(){if(p(C)&&!s.isAborted&&g>0)return yield Lu(f),x();throw C}))});x().then(C=>M(this,null,function*(){let k=yield F_(C);if(delete this.latestRequestByUrl[i],C.status>=500){o(new fg("Server Error",k));return}if(C.status===401){o(new Tr("Unauthorized",k));return}if(C.status===403){o(new Tr("Forbidden",k));return}if(C.status===404){o(new Tr("Not Found",k));return}if(C.status>=400){o(new Tr("Bad Request",k));return}r({status:C.status,data:k})})).catch(C=>{delete this.latestRequestByUrl[i],o(C)})})}patch(t,n,r){return this.request(t,b({method:"PATCH",body:JSON.stringify(n)},r))}put(t,n,r){return this.request(t,b({method:"PUT",body:JSON.stringify(n)},r))}delete(t,n){return this.request(t,b({method:"DELETE"},n))}};var z_;(t=>{let e;(a=>(a.SUCCESS="success",a.FAILURE="failure",a.CONDITIONS_NOT_MET="conditions_not_met",a.MAX_RECURSION_LEVEL="max_recursion_level",a.NO_ACCESS_TO_ASSISTANT="no_access_to_assistant"))(e=t.EvaluationStatus||(t.EvaluationStatus={}))})(z_||(z_={}));function pg(e){return _(b({},He(e)),{metadata:e.metadata})}var Li=class Li{constructor(t,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new Mi(t,{fetch:n.fetch}),this.client.patchFetch(r=>(o,s)=>M(this,null,function*(){let i=yield r(o,s);return this.handleDeepdeskVersionHeaders(i),i}))}preflight(){return M(this,null,function*(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=yield this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(Li.exchangeTokenPromise||(Li.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),Li.exchangeTokenPromise):Promise.resolve()})}createConversation(t){return M(this,null,function*(){var r;yield this.preflight(),J.info(`Creating conversation for session ${t.externalId} and agent ${t.agentId}`);let n=yield this.client.post("/api/v2/conversations",_(b({chat_start_time:new Date().toISOString()},Mt(t)),{metadata:(r=t.metadata)!=null?r:{}}));return pg(n)})}upsertConversation(t){return M(this,null,function*(){var u;yield this.preflight(),J.info(`Upserting conversation for session ${t.externalId} and agent ${t.agentId}`);let{status:n,data:r}=yield this.client.postWithStatus("/api/v2/conversations",_(b({chat_start_time:new Date().toISOString()},Mt(t)),{metadata:(u=t.metadata)!=null?u:{}}),{version:"v2"}),o=pg(r);if(n===201)return o;let{agentId:s,agentName:i,agentEmail:a,agentNickname:l,metadata:c}=t;return this.updateConversation(o.id,{agentId:s,agentEmail:a,agentName:i,agentNickname:l,metadata:c})})}getMe(){return M(this,null,function*(){yield this.preflight();let t=yield this.client.get("/apis/admin/session/me/");return He(t)})}postIdentity(t){return M(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/me/identities/",Mt(t))})}patchMe(t){return M(this,null,function*(){yield this.preflight();let n=yield this.client.patch("/apis/admin/session/me/",Mt(t));return He(n)})}getProfile(t){return M(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${t}/`,{useCache:!0});return He(n)})}getKnowledgeAssistant(t){return M(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{useCache:!0});return He(n)})}getContentTypes(){return M(this,null,function*(){let t=yield this.client.get("/apis/admin/content-types/",{useCache:!0});return He(t)})}getAccount(){return M(this,null,function*(){let t=yield this.client.get("/apis/admin/account/",{useCache:!0});return He(t)})}getPlatformConfig(t){return M(this,null,function*(){let n=t!==void 0?`/platform/config/${t}/`:"/platform/config/",{config:r}=yield this.client.get(n,{useCache:!0});return He(r)})}checkUserExists(t){return M(this,null,function*(){let{exists:n}=yield this.client.get(`/apis/admin/users/exists?external_id=${t}`,{version:"v1"});return n})}getConversationByExternalId(r){return M(this,arguments,function*(t,n={}){yield this.preflight(),J.info(`Getting conversation for session ${t}`);let{attempts:o=1,retryDelay:s=1e3}=n,i=yield this.client.get(`/api/v2/conversations/by_external_id/${t}`,{attempts:o,retryDelay:s,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"});return J.info(`Successfully retrieved conversation ${i.id} for session ${t}`),pg(i)})}isConversationSupported(r){return M(this,arguments,function*(t,n={}){J.info(`Check if conversation for session ${t} is supported`);let{attempts:o=1,retryDelay:s=1e3}=n;return(yield this.client.get(`/api/v2/conversations/by_external_id/${t}/has_active_profile`,{attempts:o,retryDelay:s,retryOnResponse:a=>a.status===404||a.status>=500})).has_active_profile})}updateConversation(t,n){return M(this,null,function*(){var s;yield this.preflight();let r=Mt(n);n.metadata&&(r.metadata=(s=n.metadata)!=null?s:{});let o=yield this.client.put(`/api/v2/conversations/${t}`,r);return pg(o)})}postMessages(t,n){return M(this,null,function*(){yield this.preflight(),yield this.client.post(`/api/v2/conversations/${t}/messages`,n.map(r=>_(b({},Mt(r)),{metadata:r.metadata})))})}sendEvent(t,n){return M(this,null,function*(){yield this.preflight();let a=n,{data:r}=a,o=ie(a,["data"]),s=Object.entries(this.latestReceivedDeepdeskVersions).reduce((l,[c,u])=>_(b({},l),{[c]:u}),{}),i=["platform","agentId","agentName","agentEmail","conversationId"].reduce((l,c)=>(o[c]&&(l[c]=o[c]),l),{});return this.client.post("/api/v2/events",Mt(_(b(b({},s),i),{data:r,name:t})),{version:"v2"})})}getEntities(t){return M(this,null,function*(){return yield this.preflight(),yield this.client.post("/api/v2/entities",{messages:t.filter(r=>r.text)})})}getTemporaryExchangeToken(){return M(this,null,function*(){return(yield this.client.get("/apis/admin/session/exchange-token/")).jwt})}exchangeTokenForAccessCookie(t){return M(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 M(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/api-key/",Mt(n),{refreshTokenOn401:!1,headers:{apikey:t}})})}getTextSuggestions(o){return M(this,arguments,function*(t,n={},r){if(yield this.preflight(),r==="sticky-messages")throw new Error("Use getPinnedMessages instead");return(yield this.client.post(`/api/v2/conversations/${t}/recommend/${r}`,Mt(n),{abortLatest:!0})).map(i=>_(b({},He(i)),{text:i.text||i.url||i.message,source:r,type:r})).filter((i,a,l)=>a===l.findIndex(c=>c.text===i.text))})}isLoggedIn(){return M(this,null,function*(){return yield this.preflight(),this.client.validateToken()})}getAutocompleteSuggestions(t,n){return M(this,null,function*(){return yield this.preflight(),(yield this.client.post(`/api/v2/conversations/${t}/autocomplete`,Mt(n),{abortLatest:!0})).map(o=>({score:1,source:o.source,sourceText:o.source_text,text:o.label,trainingJobs:o.training_jobs,searchKeywords:o.search_keywords,type:o.source})).filter((o,s,i)=>s===i.findIndex(a=>a.text===o.text))})}syncPersonalCollection(t){return M(this,null,function*(){yield this.preflight(),yield this.client.post(`/api/v2/conversations/${t}/personal-collection/sync`,{},{version:"v2"})})}getPinnedMessages(t){return M(this,null,function*(){let n=yield this.client.get(`/api/v2/profiles/${t}/pinned-messages`,{abortLatest:!0});return He(n).map(r=>_(b({},r),{text:r.message,source:"sticky-messages",type:"pinned-message"}))})}getStyleSuggestions(t){return M(this,null,function*(){let n=yield this.client.post("/api/v2/style-suggestions",Mt(t),{abortLatest:!0,version:"v2"});return He(n)})}search(t){return M(this,null,function*(){let n=yield this.client.post(`/api/v2/profiles/${t.profile}/search`,Mt(t));return He(n)})}loginWithPassword(t,n){return M(this,null,function*(){yield this.preflight();let r=yield this.client.post("/apis/admin/session/login/",{username:t,password:n},{refreshTokenOn401:!1});return He(r)})}logout(){return M(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/logout/",{},{refreshTokenOn401:!1})})}requestLoginByEmail(t){return M(this,null,function*(){yield this.preflight();let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:t});return He(n)})}requestPasswordlessToken(){return M(this,null,function*(){let t=yield this.client.get("/apis/admin/session/passwordless/request/");return He(t.token)})}getCsrfToken(){return M(this,null,function*(){let{token:t}=yield this.client.get("/apis/admin/session/csrf/");return t})}verifyLoginToken(t){return M(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/login/",{token:t});return He(n)})}evaluateAssistant(t,n){return M(this,null,function*(){var l,c,u;yield this.preflight();let r=new URLSearchParams;n!=null&&n.externalConversationId&&r.append("external_conversation_id",n.externalConversationId);let o=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=f=>Mt(f),i=(l=n==null?void 0:n.transcript)==null?void 0:l.map(f=>{var d;return b({source:f.source,text:f.text},(d=f.attachments)!=null&&d.length?{attachments:f.attachments.map(s)}:{})}),a=yield this.client.post(o,b({input:(c=n==null?void 0:n.input)!=null?c:{},conversation:i},(u=n==null?void 0:n.attachments)!=null&&u.length?{attachments:n.attachments.map(s)}:{}));return He(a)})}interactWithAssistant(t){return M(this,null,function*(){yield this.preflight();let n=new URLSearchParams;t.sessionId&&n.append("session_id",t.sessionId),t.externalConversationId&&n.append("external_conversation_id",t.externalConversationId);let r=`/api/v2/assistants/${t.assistantCode}/interact?${n.toString()}`,o=yield this.client.post(r,{message:t.message});return He(o)})}resetAssistantThread(t){return M(this,null,function*(){yield this.preflight();let n=encodeURIComponent(t.assistantCode),r=encodeURIComponent(t.sessionId);yield this.client.delete(`/api/v2/assistants/${n}/sessions/${r}/thread`)})}createAssistantThread(t){return M(this,null,function*(){yield this.preflight();let{assistantCode:n}=t,r=yield this.client.post(`/apis/admin/assistants/${n}/threads/`,{});return He(r)})}postMessageToAssistantThread(t){return M(this,null,function*(){yield this.preflight();let{assistantCode:n,threadId:r,message:o}=t,s=yield this.client.post(`/apis/admin/assistants/${n}/threads/${r}/messages/`,{content:o,role:"user"});return He(s)})}translateMessages(t){return M(this,null,function*(){yield this.preflight();let n=yield this.client.post("/api/v2/translate",Mt(t));return He(n)})}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),s=o.match(Ow);if(!n||!s)return;let i=s[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&n&&a!==n&&J.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[i]=n})}};Li.exchangeTokenPromise=null;var Lo=Li;var mg=class{constructor(t){this.options=t;this.socket=null;this.maxReconnectAttempts=5;this.reconnectInterval=25e3;this.cleanupCallbacks=[];var n,r;this.socket,this.eventListeners=new Map,this.url=t.url,this.maxReconnectAttempts=(n=t.maxReconnectAttempts)!=null?n:this.maxReconnectAttempts,this.reconnectInterval=(r=t.reconnectInterval)!=null?r:this.reconnectInterval,this.shouldReconnect=t.shouldReconnect}connect(){let t=()=>this.cleanup();window.addEventListener("beforeunload",t),this.cleanupCallbacks.push(()=>window.removeEventListener("beforeunload",t)),this.reconnect()}setupListeners(){this.socket&&(this.socket.onmessage=t=>{var n;try{let r=He(JSON.parse(t.data));r.event&&this.eventListeners.has(r.event)&&((n=this.eventListeners.get(r.event))==null||n.forEach(o=>o(r.data)))}catch(r){console.error("Error parsing WebSocket message:",r)}},this.socket.onclose=t=>{console.log("WebSocket connection closed:",t),setTimeout(()=>{this.reconnect()},this.reconnectInterval)},this.socket.onerror=t=>{console.error("WebSocket error:",t)})}reconnect(){var t,n;if(this.maxReconnectAttempts<=0){console.error("Max reconnect attempts reached, closing WebSocket connection."),(t=this.socket)==null||t.close();return}if(!this.shouldReconnect()){console.error("Should not reconnect, closing WebSocket connection."),(n=this.socket)==null||n.close();return}this.socket&&(this.socket.onmessage=null,this.socket.onclose=null,this.socket.onerror=null,this.socket.close()),this.socket=new WebSocket(this.url),this.setupListeners(),this.maxReconnectAttempts--}send(t,n){if(!this.socket){console.error("WebSocket connection is not open.");return}this.socket.send(JSON.stringify({event:t,data:n}))}on(t,n){this.eventListeners.has(t)||this.eventListeners.set(t,[]);let r=this.eventListeners.get(t);r&&!r.includes(n)&&r.push(n)}close(){var t;(t=this.socket)==null||t.close()}cleanup(){this.close(),this.cleanupCallbacks.forEach(t=>t()),this.cleanupCallbacks=[]}};var H_={startTime:null,stopTime:null},B_=e=>e.handlingTime,U_=Pe({name:"handlingTime",initialState:H_,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(Ke,()=>H_)}}),{handlingTimeStart:V_,handlingTimeStop:gg,handlingTimeReset:W_}=U_.actions,$_=U_.reducer;var j_=(e={})=>{let t=b({onAuthError:qi(!1)},e);return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var K_=(e={})=>{let t,n=!0,r=b({getStyleSuggestions:Ti,debounce:500},e);return o=>s=>i=>{var p;let a=o.getState().input.text,l=s(i),c=o.getState();if(c.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:u}=c.settings;if(!((p=c.conversation.current)==null?void 0:p.id)||!u)return l;let{text:d}=c.input;return d===a&&!n||(clearTimeout(t),d==="")||(t=setTimeout(()=>{n=!1,o.dispatch(r.getStyleSuggestions({text:d}))},e.debounce)),l}};function y9(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end&&e.suggestionTextStart===t.suggestionTextStart}var G_=(e={})=>{let t=b({getTextSuggestions:Cr,getAutocompleteSuggestions:vu,debounce:200,check:Gr},e),n;return r=>o=>s=>{var y;let{input:i}=r.getState(),a=o(s),l=r.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:c,showTabCompletion:u}=l.settings,f=(y=l.conversation.current)==null?void 0:y.id,d=s.type===Dm.toString();if(!f||!c&&!u)return a;let{input:p}=l;return y9(p,i)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let S=Ns(l);S===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(S))},d?0:t.debounce)),a}};var q_=Ti.fulfilled.toString();function v9(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let s=e.keywordMatches.filter(l=>l.keyword===o),i=t.keywordMatches.filter(l=>l.keyword===o),a=i.length-s.length;a<=0||r.push(...i.slice(0,a))}),r}var Y_=e=>t=>n=>r=>{var c;if(r.type!==q_){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let s=t.getState(),i=s.styleSuggestions.list,a=(c=s.conversation)==null?void 0:c.current;if(o===i)return;let l=v9(o,i);r.type===q_&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var S9=pd({assistants:yC,auth:Gb,conversation:tE,contentTypes:vA,passwordlessToken:a_,entities:GA,handlingTime:$_,info:EE,input:pE,settings:SC,profile:CA,search:AE,styleSuggestions:II,ui:vI,textSuggestions:rI});function X_(e){return Ob({reducer:S9,middleware:t=>{var r;let n=t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI}},serializableCheck:!1}).concat(j_()).concat(G_({debounce:200})).concat(K_({debounce:500})).concat(Y_(e.deepdeskAPI));return((r=e.middleware)!=null?r:[]).reduce((o,s)=>o.concat(s),n)},preloadedState:e.preloadedState})}function Q_(e,t,n){if(t==="")return null;let r=new RegExp(`\\b${Xm(t)}\\b`,"gi"),o,s=null;for(;(o=r.exec(e))!==null&&!(o.index>n);)s={start:o.index,end:o.index+o[0].length};return s}var x9=e=>{var t,n;return(n=(t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())!=null?n:"unknown"},w9=e=>t=>n=>r=>{var l,c,u,f,d,p;let o=t.getState(),s=Ws("inlineSuggestions")(o),i=Ws("autoSelectSuggestion")(o)||s;switch(r.type){case qi.toString():{!r.payload&&e.emit("logout",void 0);break}case Ld.fulfilled.toString():{e.emit("logout",void 0);break}case Er.fulfilled.toString():r.payload.length>0&&e.sendEvent("entities found",{conversationId:(l=o.conversation.current)==null?void 0:l.id,data:{entities:r.payload}});break;case zs.toString():e.logSendMessage(r.payload);break;case df.toString():e.emit("call-to-action",{cue:r.payload});break;case kn.fulfilled.toString():if(!r.isBroadcasted){let{externalConversationId:h,currentExternalIdAtRequest:y}=(c=r.payload)!=null?c:{};(!h||!y||h===y)&&e.broadcast(_h,r,!1)}break;case kn.rejected.toString():break;default:break}let a=n(r);switch(r.type){case zs.toString():e.handleAfterSendMessage(r.payload);break;case xu.toString():e.onUpdateShowTabHint(r.payload);break;case gg.toString():e.logHandlingTime();break;case Qi.toString():e.broadcast(Kd,r);break;case Fs.toString():e.broadcast(Kd,r);break;case ff.toString():t.dispatch(Fs({source:"assistant",assistantCode:r.payload.code}));break;case"analytics/logEvent/fulfilled":{let h=o.assistants.cues.find(y=>y.code===r.meta.arg.data.assistantCode);e.emit("event",_(b({},r.meta.arg),{cue:h}));break}case Cn.toString():{let{start:h,end:y}=o.input.selection;e.emit("select-suggestion",_(b({type:x9(r.payload.suggestion)},r.payload),{replace:r.payload.replace==="selection"?{start:h,end:y}:{start:0,end:y}})),s&&t.dispatch(Uo([]));break}case AI.toString():{let{keyword:h,suggestion:y,eventMetrics:S}=r.payload,{text:m,selection:g}=o.input,v=Q_(m,h,(u=g==null?void 0:g.end)!=null?u:m.length);if(!v)break;e.emit("select-suggestion",{text:y,type:"style",replace:v,suggestion:{text:y,source:"style"},eventMetrics:S});break}case Hd.toString():e.emit("select-image",r.payload),e.sendEvent("Image attached",{conversationId:(f=o.conversation.current)==null?void 0:f.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case Uo.toString():{i&&r.payload.length>0&&t.dispatch(Bd(0));break}case kn.fulfilled.toString():{let{evaluationId:h,output:y,externalConversationId:S}=r.payload,m=r.meta.arg.assistantCode;if(e.emit("event",{name:"Assistant evaluation completed",data:{evaluationId:h,assistantCode:m,assistantOutput:dC(y),externalConversationId:S,evaluationStatus:"success"}}),!r.meta.arg.skipState){let g=t.getState().assistants.cues;e.emit("cues",g)}break}case kn.rejected.toString():{let h=r.meta.arg.assistantCode,y=(p=r.meta.arg.externalConversationId)!=null?p:(d=t.getState().conversation.current)==null?void 0:d.externalId;e.emit("event",{name:"Assistant evaluation completed",data:{evaluationId:"",assistantCode:h,assistantOutput:"",externalConversationId:y,evaluationStatus:"failed"}});break}default:break}return a},Z_=w9;function vx(e){return e.toISOString().replace("T"," ").replace("Z","")}var b9=(e,t)=>t.version,J_=Yt([Zi,Vn,B_,b9],(e,t,n,r)=>{if(!t)return J.warn("No conversationId for handling time metrics"),null;let{startTime:o,stopTime:s}=n;return!o||!s?(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:vx(o),timeStop:vx(s)}});function eM(e,t){let{text:n,metrics:{numPaste:r,pastes:o,textSuggestions:s}}=e.input,i=n.length;return{source:"agent",clientVersion:t.version,pastes:o,lenTextTotal:i,numPastes:r,suggestions:s}}var Ou=class extends Error{};function E9(){let e,t;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}}var hg=class{constructor(){this.queues={}}push(t,n){let r=()=>{let s=this.queues[t][1];s?(this.queues[t]=[s.promise,null],s.resolve()):delete this.queues[t]};if(!this.queues[t]){let s=n().finally(r);return this.queues[t]=[s,null],s}this.queues[t][1]&&this.queues[t][1].reject(new Ou("Queued async function is outdated"));let o=E9();return this.queues[t][1]=o,o.promise.then(()=>n().finally(r))}};function Sx(e,t){var s;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return Sx(r,t);let o=(s=e.ownerDocument.defaultView)==null?void 0:s.frameElement;return o?Sx(o,t):null}function xx(e,t){return Sx(e,t)}var C9={accepted:"onConversationAcceptedAssistants","new-message":"onConversationNewMessageAssistants",ended:"onConversationEndedAssistants"},tM=(e,t)=>{var o,s,i;if(!((i=(s=(o=e.uiConfig)==null?void 0:o.widget)==null?void 0:s.types.find(a=>a.type==="cues"))==null?void 0:i.isActive))return J.warn("Triggered a conversation assistant, but cues are not configured in widget."),[];let r=e[C9[t]];if(r&&r.length>0){let a=r.map(l=>l.code);return e.summarizerAssistantNew&&t!=="ended"&&(a=a.filter(l=>l!==e.summarizerAssistantNew)),a}return J.warn(`No assistant set in profile for conversation event "${t}"`),[]};function T9(e){var t,n,r,o;return(o=(r=(n=(t=e.uiConfig)==null?void 0:t.widget)==null?void 0:n.types)==null?void 0:r.some(s=>s.type==="knowledge-assist"&&s.isActive))!=null?o:!1}function nM(e){var n,r;return((r=(n=e.widgetInteractiveAssistants)==null?void 0:n.length)!=null?r:0)>0&&T9(e)?!0:!!e.knowledgeAssistantNew||!!e.knowledgeAssistant}function k9(e){return typeof e=="object"&&e!==null&&"tagName"in e}function yg(e){return k9(e)&&(Ri(e)||qm(e))}var oM,Xr=new Map,R9=["bottom","height","left","right","top","width"],rM=(e,t)=>!e&&!t?!1:e&&!t||!e&&t?!0:R9.some(n=>e[n]!==t[n]);function sM(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,...sM(t)]:[]}function iM(e,t){return!e||!t?null:_(b({},e),{top:e.top+t.top,left:e.left+t.left})}var vg=!1,aM=()=>{vg=!0;let e=[];if(Xr.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),Xr.delete(n);return}let r=n.getBoundingClientRect();rM(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(iM,t.rect):t.rect;rM(n,t.totalRect)&&t.callbacks.forEach(r=>r(n)),t.totalRect=n}),Xr.size===0){vg=!1;return}oM=window.requestAnimationFrame(aM)};function wx(e,t){let n=sM(e),r=[],o=n.map((s,i)=>wx(s,a=>{r[i]=a;let l=Xr.get(e);if(!l)return;let c=r.reduce(iM,l.rect);l.callbacks.forEach(u=>u(c))}));return{observe(s=!0){if(o.forEach(i=>i.observe(!1)),Xr.has(e)){let i=Xr.get(e);i.callbacks.push(t),i.rect&&t(i.rect)}else Xr.set(e,{rect:void 0,callbacks:[t],parentRects:r});s&&!vg&&aM()},unobserve(){o.forEach(i=>i.unobserve());let s=Xr.get(e);if(s){let i=s.callbacks.indexOf(t);i>=0&&s.callbacks.splice(i,1),s.callbacks.length||Xr.delete(e),Xr.size||(cancelAnimationFrame(oM),vg=!1)}}}}var lM,Qr=new Map,cM=()=>{Qr.forEach((e,t)=>{if(!t.isConnected){Qr.delete(t);return}let{clientHeight:n,scrollHeight:r}=t,o=r>n;e.visible!==o&&(e.visible=o,e.callbacks.forEach(s=>s(e.visible)))}),Qr.size!==0&&(lM=window.requestAnimationFrame(cM))};function uM(e,t){return{observe(){let n=Qr.size===0;Qr.has(e)?Qr.get(e).callbacks.push(t):Qr.set(e,{visible:void 0,callbacks:[t]}),n&&cM()},unobserve(){let n=Qr.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||Qr.delete(e),Qr.size||cancelAnimationFrame(lM)}}}}var bx=["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 Ex(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function ll(e){return Number.parseFloat(e)}function Sg(e){return Math.round(e*1e6)}function dM(e){return e/1e6}function Cx(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=ll(e.width),s=ll(e.borderLeftWidth),i=ll(e.borderRightWidth),a=ll(e.paddingRight),l=dM(Sg(o)-Sg(s)-Sg(i)),c=dM(Sg(r));if(l-c>2){let u=l-c;n.style.paddingRight=`${a+u}px`}}function Nu(e,t={}){var u,f;let n=t.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=(u=t.position)!=null?u:"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",mi(n);let r=window.getComputedStyle(e),o=!0,s=()=>{n.scrollTop=e.scrollTop};Ex(r,n,bx),Cx(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",s));let i=uM(e,()=>{Ex(r,n,bx),Cx(r,e,n),s(),setTimeout(s,0)}),a,l=!0,c=wx(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(Ex(r,n,bx),Cx(r,e,n),s(),t.placement==="below"&&n.classList.add("below"),n.style.top=`${d.top}px`,n.style.left=`${d.left}px`,t.closestScrollElement&&t.closestScrollElement!==e){let p=t.closestScrollElement.getBoundingClientRect(),h=window.getComputedStyle(t.closestScrollElement),y=ll(h.borderTopWidth),S=ll(h.borderBottomWidth),m=p.top+y-d.top,g=d.top+d.height+-(p.top+p.height-S);n.style.clipPath=`inset(${m}px 0px ${g}px 0px)`}o&&(n.style.display="block",t.onShow&&t.onShow(),o=!1)});return t.appendTo?t.appendTo.appendChild(n):(f=e.parentElement)==null||f.appendChild(n),c.observe(),i.observe(),[n,()=>{e.removeEventListener("scroll",s),c.unobserve(),i.unobserve(),n.remove()}]}function P9(e){return e.offsetParent!==null}function fM(e){if(!P9(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 xg(e,t,n=100){let r=fM(e);t({isVisible:r});let o=setInterval(()=>{let s=fM(e);s!==r&&(r=s,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var pM=(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")}}});var Re=E(A());var mM=pM("showTabHint",!0),cl=class cl{constructor({deepdeskUrl:t,version:n=cl.version||"unknown",locale:r="en-US",token:o,fetch:s,productName:i,createCustomChannel:a,websocketClient:l=mg}){this.inputMediator=null;this.eventListeners={};this.unmountHandlers=[];this.disposeHandlers=[];this.inlineSuggestions=null;this.aboveSuggestions=null;this.belowSuggestions=null;this.floatingMenu=null;this.widgetElement=null;this.widgetRoot=null;this.nicknameDialogUnsubscribe=null;this.nicknameDialogFailed=!1;this.dynamicThunkObject={};this.queues=new hg;this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;this.loadProfileConfigPromiseKey=null;this.personalCollectionSyncPendingKey=null;this.personalCollectionSyncDrainPromise=null;let c=t.replace(/\/api$/,"");this.deepdeskApi=new Lo(c,{token:o,fetch:s}),this.version=n,this.instanceId=cl.count++;let u={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[Z_({broadcast:(h,y,S)=>{this.broadcastEvents.send(h,y,S)},emit:(h,y)=>this.emit(h,y),handleAfterSendMessage:h=>this.handleAfterSendMessage(h),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:h=>this.logSendMessage(h),onUpdateShowTabHint:h=>mM.update(h),sendEvent:(h,y)=>this.deepdeskApi.sendEvent(h,y)})]};this.store=X_(u),this.broadcastEvents=new D_({debug:!0,deepdeskUrl:c,eventMap:IE(this.store),createCustomChannel:a}),this.disposeHandlers.push(()=>{this.broadcastEvents.cleanup()}),this.ws=new l({url:`${c}/api/v2/me/realtime`.replace("https","wss"),reconnectInterval:25e3,shouldReconnect:()=>M(this,null,function*(){var h;return(h=kt(this.state))!=null?h:!1})}),this.whenLoggedIn(()=>this.ws.connect()),this.store.dispatch(xu(mM.value())),this.store.dispatch(ql({locale:r,adminUrl:c,productName:i}));let f=[],d=h=>{if(!h.conversationId)return;let y=()=>{this.conversationId()===h.conversationId&&this.store.dispatch(gC(h))};this.hasConversation()?y():f.push(y)};this.ws.on("assistants::direct_response",d),this.ws.on("assistants::user_notification",d),this.ws.on("assistants::response_chunk",h=>{if(!h.conversationId)return;let y=()=>{this.conversationId()===h.conversationId&&this.store.dispatch(mC(h))};this.hasConversation()?y():f.push(y)}),this.ws.on("assistants::suggest_as_reply",h=>{if(!h.conversationId)return;let y=()=>{this.conversationId()===h.conversationId&&this.store.dispatch(Qi([{text:h.payload.message,type:"text",source:"assistant",assistantCode:h.code,sourceLabel:h.name}]))};this.hasConversation()?y():f.push(y)});let p=this.whenConversationLoaded(()=>{var h;this.broadcastEvents.setExternalId((h=this.state.conversation.current)==null?void 0:h.externalId),f.forEach(y=>y()),f.length=0});this.disposeHandlers.push(()=>{this.ws.cleanup(),f.length=0,p()})}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){var t;return(t=Ds(this.state)[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}externalId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.externalId}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)}whenLoggedIn(t){if(kt(this.state))t();else{let n=this.subscribe(kt,r=>{r&&t()});this.disposeHandlers.push(()=>{n()})}}login(){return this.store.dispatch(qi(null)),this.store.dispatch(to()),new Promise(t=>{this.whenLoggedIn(()=>t())})}isLoggedIn(){return M(this,null,function*(){return(yield this.store.dispatch(to())).payload})}isConversationSupported(t,n){return M(this,null,function*(){return(yield this.store.dispatch(Ch({externalId:t,options:n}))).payload})}createConversation(t){return M(this,null,function*(){var r;return this.hasConversation()&&this.externalId()!==t.externalId&&this.resetConversation(),(yield this.store.dispatch(Dd(_(b({},t),{metadata:(r=t.metadata)!=null?r:{}})))).payload})}getConversationByExternalId(t,n){return M(this,null,function*(){return this.hasConversation()&&this.externalId()!==t&&this.resetConversation(),(yield this.store.dispatch(Fd({externalId:t,options:n}))).payload})}upsertConversation(t){return M(this,null,function*(){var r;return this.hasConversation()&&this.externalId()!==t.externalId&&this.resetConversation(),(yield this.store.dispatch(Th(_(b({},t),{metadata:(r=t.metadata)!=null?r:{}})))).payload})}postMessages(t){return M(this,null,function*(){yield this.store.dispatch(kh(t))})}updateConversation(t){return M(this,null,function*(){return(yield this.store.dispatch(zd(t))).payload})}resetConversation(){this.store.dispatch(Ke()),this.loadProfileConfigPromise=null,this.loadProfileConfigPromiseKey=null,this.dynamicThunkObject.conversationQuery=null}configure(t){this.store.dispatch(ql(t))}setVisitorInfo(t){this.store.dispatch(SE(t))}setCustomData(t){this.store.dispatch(xE(t))}setAgentInfo(t,n){return M(this,null,function*(){var o;yield this.store.dispatch(Pl(b(b({},t),n))),(o=this.state.info.agentInfo)!=null&&o.agentNickname||this.broadcastEvents.send(jd,{showNicknameDialog:!0})})}setAgentSettings(t){return M(this,null,function*(){yield this.store.dispatch(Ph(t))})}getAgentSettings(){return M(this,null,function*(){return(yield this.store.dispatch(Ah())).payload})}getMe(){return M(this,null,function*(){return this.deepdeskApi.getMe()})}refresh(){return M(this,null,function*(){if(this.shouldAbort())return Promise.resolve();let t=[];return t.push(this.refreshTextSuggestions()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})})}syncInputMediator(){this.inputMediator&&this.store.dispatch(Ud({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),suggestionTextStart:this.inputMediator.getSuggestionTextStart()}))}notifyExternalSuggestion(t){this.store.dispatch(Cn(t))}evaluateAssistant(t,n){return M(this,null,function*(){var u;let{input:r={},attachments:o=[],transcript:s,showCuesInWidget:i=!0,includeMetadata:a,externalConversationId:l}=n||{},c=yield this.store.dispatch(kn({assistantCode:t,attachments:o,transcript:s,includeMetadata:a,input:r,externalConversationId:l,skipState:!i}));if(c.error)throw new Error(`Assistant evaluation failed: ${(u=c.payload)!=null?u:c.error.message}`);return c.payload.output})}evaluateConversationAssistant(t,n){return M(this,null,function*(){var u,f,p;yield this.loadProfileConfig();let r=this.state.profile.data;if(!r&&((u=this.state.conversation.current)!=null&&u.profileCode)&&(yield this.loadProfileConfig(),r=this.state.profile.data),!r){J.warn("Can't evaluate assistant when profile is not loaded yet.");return}let o=tM(r,t),s=(f=n==null?void 0:n.showCuesInWidget)!=null?f:!0,d=n!=null?n:{},{showCuesInWidget:i}=d,a=ie(d,["showCuesInWidget"]),l=(p=n==null?void 0:n.externalConversationId)!=null?p:this.hasConversation()?this.externalId():"",c=yield Promise.all(o.map(h=>this.queues.push(h,()=>M(this,null,function*(){var S,m;let y=yield this.store.dispatch(kn(b(_(b({assistantCode:h,includeMetadata:!0},a),{skipState:!s}),n!=null&&n.attachments&&(n==null?void 0:n.attachments.length)>0?{attachments:n==null?void 0:n.attachments}:{})));if(y.error)throw new Error(`Assistant evaluation failed: ${(S=y.payload)!=null?S:y.error.message}`);return{assistantCode:h,evaluationId:y.payload.evaluationId,output:y.payload.output,externalConversationId:(m=y.payload.externalConversationId)!=null?m:l}})).catch(y=>{if(y instanceof Ou)return J.warn(`Queued assistant "${h}" was outdated and dropped`),null;throw y})));if(!s)return c.filter(h=>h!==null)})}handleKeyDown(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui,{textSuggestions:o,selectedSuggestionIndex:s,selection:i}=this.state.input,{inlineSuggestions:a,autoSelectSuggestion:l,showTextSuggestions:c,suggestionsPlacement:u}=this.settings,f=a||l,d=u==="inline"||u==="below"?"below":"above",p=o.length>0;if(this.store.dispatch(iE(Rh(t))),!Gr(this.state)||t.key!=="Tab"&&!c)return;let h=()=>{n||!p||i&&(t.shiftKey||(this.store.dispatch(cE()),t.preventDefault()))},y=()=>{n||!p||f&&s<=0||i&&(t.shiftKey||(this.store.dispatch(uE()),t.preventDefault()))};switch(t.key){case"ArrowUp":d==="below"?y():h();break;case"ArrowDown":{d==="below"?h():y();break}case"Escape":{n||(this.store.dispatch(Bd(-1)),this.store.dispatch(xs({collapse:!0})),this.store.dispatch(hI(!0)),t.preventDefault());break}case"Tab":{t.preventDefault();let S=Xi(this.state);if(!S)return;this.store.dispatch(xu(!1)),this.store.dispatch(Cn({text:S.text,suggestion:S,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(f||this.state.input.selectedSuggestionIndex===-1)return;let S=Xi(this.state);if(!S)return;this.store.dispatch(Cn({text:S.text,suggestion:S,eventMetrics:{inputType:"space"},replace:"until-selection-end"}));break}case"Enter":{if(f||t.shiftKey||this.state.input.selectedSuggestionIndex===-1)return;let S=Xi(this.state);if(!S)return;this.store.dispatch(Cn({text:S.text,suggestion:S,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),t.preventDefault();break}default:}n&&r&&this.store.dispatch(xs({collapse:!1}))}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(Uo([]))}handlingTimeStart(){this.state.handlingTime.startTime||(J.info("Start handling time"),this.store.dispatch(V_()))}handlingTimeStop(){this.state.handlingTime.startTime&&(J.info("Stop handling time"),this.store.dispatch(gg()))}logSendMessage(t){let n=eM(this.state,{version:this.version});n&&(t&&(Object.assign(n,{text:t}),Object.assign(n,{lenTextTotal:t.length})),this.deepdeskApi.sendEvent("Send Message",{conversationId:this.conversationId(),data:n}),this.emit("send-message-event",n))}logHandlingTime(){let t=J_(this.state,{version:this.version});t&&(this.deepdeskApi.sendEvent("Handling Time",{conversationId:this.conversationId(),data:t}),this.store.dispatch(W_()))}notifySubmit(t={}){var n;this.shouldAbort()||(this.store.dispatch(zs((n=t.text)!=null?n:this.state.input.text)),this.store.dispatch(fE()))}emit(t,n){let r=this.eventListeners[t];r&&r.forEach(o=>{try{o(n)}catch(s){J.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),J.error(s)}})}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(wE(t))}whenConversationLoaded(t){let n=()=>this.getConversationLoadedKey(),r=()=>{let s=n();s&&this.loadProfileConfig().then(()=>{if(n()!==s)return;let i=this.state.conversation.current,a=tr(this.state);!(i!=null&&i.id)||i.profileCode&&(a==null?void 0:a.code)!==i.profileCode||t()})};return n()&&r(),this.subscribe(s=>this.getConversationProfileKey(s.conversation.current),s=>{s&&r()})}overlayContainerFactory(t,n,r,o){let[s,i]=Nu(n,r);return s.setAttribute("translate","no"),s.dataset.testid=t,o&&s.classList.add(o),[s,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 s=(a=t.ownerDocument.defaultView)==null?void 0:a.frameElement,i=s?s.ownerDocument.defaultView:null;if(s&&(i===window||(i==null?void 0:i.parent)===window)){let[l,c]=Nu(s,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});l.dataset.testid=n,l.style.zIndex="2",l.appendChild(r),this.unmountHandlers.push(()=>{c()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return mi(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),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(dE(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(!yg(t))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let d=n,{customStyles:r,closestScrollSelector:o,floatingMenuParent:s,appendOverlayTo:i,inputMediator:a}=d,l=ie(d,["customStyles","closestScrollSelector","floatingMenuParent","appendOverlayTo","inputMediator"]),c={customStyles:r,closestScrollSelector:o,floatingMenuParent:s,appendOverlayTo:i};this.configure(l),this.settings.automaticHandlingTime&&this.setupHandlingTime(t),mi(t),this.inputMediator=a||(Ri(t)?new _i(t):new Ii(t)),this.inputMediator.on("change",({plainText:p,rawHTML:h,suggestionTextStart:y})=>{this.store.dispatch(Ud({text:p,html:h,suggestionTextStart:y}))}),this.inputMediator.on("keyup",p=>{this.store.dispatch(aE(Rh(p)))}),this.inputMediator.on("keydown",p=>{this.handleKeyDown(p)}),this.inputMediator.on("paste",({pastedText:p,selectionText:h})=>{this.store.dispatch(lE({text:p,selectionText:h}))}),this.inputMediator.on("cut",({selectionText:p})=>{this.store.dispatch(sE(p))});let u;this.inputMediator.on("selection",p=>{clearTimeout(u),p===null?u=setTimeout(()=>{p!==null&&this.store.dispatch(Vd(p))},500):this.store.dispatch(Vd(p))}),this.unmountHandlers.push(()=>{clearTimeout(u)}),this.inputMediator.on("disabled",()=>{var p;(p=this.inputMediator)==null||p.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(Hm(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(Hm(!0))}),this.renderSuggestions(t,c),this.subscribe(Ws("inlineSuggestions"),()=>{this.renderSuggestions(t,c)}),this.subscribe(Ws("suggestionsPlacement"),()=>{this.renderSuggestions(t,c)});let f=this.renderOverlays(n);this.unmountHandlers.push(()=>{f.unmount()}),this.store.dispatch(Ud({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),suggestionTextStart:this.inputMediator.getSuggestionTextStart()})),this.store.dispatch(Vd(this.inputMediator.getSelection())),this.store.dispatch(Hm(this.inputMediator.isFocused)),this.unmountHandlers.push(()=>{this.state.input.text!==""&&this.storeMetrics()}),this.whenConversationLoaded(()=>{this.restoreMetrics(),this.syncInputMediator(),this.refreshTextSuggestions(),this.promptForNickname()}),this.isMounted=!0}promptForNickname(t){if(this.nicknameDialogUnsubscribe||this.nicknameDialogFailed)return;let n=this.createContainer("nickname-dialog",document.body);document.body.appendChild(n);let r=(0,Oo.createRoot)(n),o=null,s=a=>{o=a,i()},i=()=>{r==null||r.render((0,Re.jsx)(Ro,{store:this.store,children:(0,Re.jsx)(ro,{broadcastEvents:this.broadcastEvents,children:(0,Re.jsx)(LI,{id:"deepdesk-nickname-dialog",error:o,onSave:a=>M(this,null,function*(){try{yield this.store.dispatch(yE({agentNickname:a})).unwrap(),console.log("setAgentNickname",a),this.broadcastEvents.send(jd,{showNicknameDialog:!1}),this.nicknameDialogUnsubscribe&&this.nicknameDialogUnsubscribe()}catch(l){J.error("Error setting agent nickname",l),s("error"),this.nicknameDialogFailed=!0}})})})}))};i(),this.nicknameDialogUnsubscribe=()=>{r.unmount(),n.remove(),this.nicknameDialogUnsubscribe=null}}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,s;(t=this.inlineSuggestions)==null||t.unmount(),(n=this.aboveSuggestions)==null||n.unmount(),(r=this.belowSuggestions)==null||r.unmount(),(o=this.floatingMenu)==null||o.unmount(),this.unmountHandlers.forEach(i=>i()),this.unmountHandlers=[],(s=this.inputMediator)==null||s.dispose(),this.nicknameDialogUnsubscribe&&this.nicknameDialogUnsubscribe(),this.isMounted=!1}dispose(){this.unmount(),this.unmountWidget(),this.disposeHandlers.forEach(t=>t()),this.disposeHandlers=[],this.off()}renderSuggestions(t,n){var r,o,s,i;(r=this.floatingMenu)==null||r.unmount(),(o=this.inlineSuggestions)==null||o.unmount(),(s=this.aboveSuggestions)==null||s.unmount(),(i=this.belowSuggestions)==null||i.unmount(),this.settings.floatingMenu&&(this.floatingMenu=this.renderFloatingMenu(t,n)),this.settings.inlineSuggestions||this.settings.suggestionsPlacement==="inline"?this.inlineSuggestions=this.renderInlineSuggestions(t,n):this.settings.suggestionsPlacement==="below"?this.belowSuggestions=this.renderAboveOrBelowSuggestions(t,n,"below"):this.aboveSuggestions=this.renderAboveOrBelowSuggestions(t,n,"above")}renderInlineSuggestions(t,n){let{customStyles:r}=n,o=this.createInlineContainer(t,"deepdesk-caret"),s=(0,Oo.createRoot)(o);s.render((0,Re.jsx)(Ro,{store:this.store,customStyles:r,children:(0,Re.jsx)(ro,{broadcastEvents:this.broadcastEvents,children:(0,Re.jsx)(_I,{})})}));let i=a=>{a?(o.style.display="block",o.style.top=`${a.top}px`,o.style.left=`${a.left}px`):o.style.display="none"};return this.inputMediator.on("caretposition",i),{unmount:()=>{var a;(a=this.inputMediator)==null||a.off("caretposition",i),s.unmount(),o.remove()}}}renderAboveOrBelowSuggestions(t,n,r){let{customStyles:o,closestScrollSelector:s,appendOverlayTo:i}=n,a=s&&xx(t,s)||void 0,[l,c]=this.overlayContainerFactory("deepdesk-tab-completion",a||t,{appendTo:i,closestScrollElement:a,mirrorOverflow:!0,onRemove:()=>this.unmount()},o==null?void 0:o.rootNode),[u,f]=this.overlayContainerFactory("deepdesk-suggestions-overlay",a||t,{appendTo:i,placement:r},o==null?void 0:o.suggestionsRootNode),d=(0,Oo.createRoot)(l);d.render((0,Re.jsx)(Ro,{store:this.store,customStyles:o,children:(0,Re.jsx)(ro,{broadcastEvents:this.broadcastEvents,children:(0,Re.jsx)(o_,{inputElement:t})})}));let p=(0,Oo.createRoot)(u);return p.render((0,Re.jsx)(Ro,{store:this.store,customStyles:o,children:(0,Re.jsx)(ro,{broadcastEvents:this.broadcastEvents,children:(0,Re.jsx)(VI,{onLogIn:()=>this.loginViaPopup().catch(h=>J.warn(h.message))})})})),{unmount(){d.unmount(),p.unmount(),c(),f()}}}renderFloatingMenu(t,n){let{customStyles:r,closestScrollSelector:o,appendOverlayTo:s,floatingMenuParent:i}=n,a=o&&xx(t,o)||void 0,[l,c]=this.overlayContainerFactory("floating-menu",a||t,{appendTo:i!=null?i:s},r==null?void 0:r.floatingMenuParent),u=(0,Oo.createRoot)(l);return u.render((0,Re.jsx)(Ro,{store:this.store,customStyles:r,children:(0,Re.jsx)(ro,{broadcastEvents:this.broadcastEvents,children:(0,Re.jsx)(mI,{onLogIn:()=>this.loginViaPopup().catch(f=>J.warn(f.message))})})})),{unmount(){u.unmount(),c()}}}renderOverlays(t){let{customStyles:n}=t,r=this.createContainer("deepdesk-overlays"),o=(0,Oo.createRoot)(r);return o.render((0,Re.jsx)(Ro,{store:this.store,customStyles:n,children:(0,Re.jsx)(ro,{broadcastEvents:this.broadcastEvents,children:(0,Re.jsx)(cI,{})})})),{unmount(){o.unmount(),r.remove()}}}renderWidget(t,n={}){if(this.widgetElement&&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:s,signInViaPopup:i,ssoUrl:a,openAdminFeedback:l}=n;this.widgetElement=t,this.configure({showImages:o,isEmbedded:s,signInViaPopup:i});let c;if(a)try{c={url:new URL(a,this.settings.adminUrl).toString()}}catch(u){J.warn(`Invalid ssoUrl '${a}' passed to renderWidget`)}this.widgetRoot=(0,Oo.createRoot)(t),this.widgetRoot.render((0,Re.jsx)(Ro,{store:this.store,customStyles:r,children:(0,Re.jsx)(ro,{broadcastEvents:this.broadcastEvents,children:(0,Re.jsx)(Sm,{report:u=>this.deepdeskApi.sendEvent(rA,{data:u}),children:(0,Re.jsx)(I_,{assistantOptions:n.assistantOptions,knowledgeAssistOptions:n.knowledgeAssist,openAdminFeedback:l,onLogIn:()=>this.loginViaPopup(c).catch(u=>J.warn(u.message))})})})}))}unmountWidget(){var t,n;(n=(t=this.widgetRoot)==null?void 0:t.unmount)==null||n.call(t),this.widgetRoot=null,this.widgetElement=null}renderKnowledgeAssistantWidget(t,n,r={}){let{customStyles:o,initialQuestion:s}=r,i=(0,Oo.createRoot)(n);return i.render((0,Re.jsx)(Ro,{store:this.store,customStyles:o,children:(0,Re.jsx)(ro,{broadcastEvents:this.broadcastEvents,children:(0,Re.jsx)(px,{children:(0,Re.jsxs)(gm,{assistantCode:t,initialQuestion:s,evaluateKnowledgeAssistFn:Gl,children:[(0,Re.jsx)($i,{children:(0,Re.jsx)(ym,{title:r.title,emptyState:r.emptyState})}),(0,Re.jsx)(fx,{children:(0,Re.jsx)(hm,{})})]})})})})),{unmount(){i.unmount()}}}setupHandlingTime(t){let n=xg(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){vm(t)&&t.message==="Unauthorized"&&this.login()}getConversationProfileKey(t){var n;if(t!=null&&t.id)return`${t.id}:${(n=t.profileCode)!=null?n:""}`}getProfileLoadKey(){var n;let t=this.state.conversation.current;return t!=null&&t.profileCode&&(n=this.getConversationProfileKey(t))!=null?n:null}isCurrentProfileLoadKey(t){return this.getProfileLoadKey()===t}getConversationLoadedKey(){return this.getConversationProfileKey(this.state.conversation.current)}resetProfileDerivedSettings(){this.store.dispatch(TS()),this.store.dispatch(ql(ay))}syncPersonalCollectionForConversation(t){this.personalCollectionSyncPendingKey=t,this.ensurePersonalCollectionSyncDrain()}ensurePersonalCollectionSyncDrain(){return this.personalCollectionSyncDrainPromise?this.personalCollectionSyncDrainPromise:(this.personalCollectionSyncDrainPromise=this.drainPersonalCollectionSync().finally(()=>{this.personalCollectionSyncDrainPromise=null,this.personalCollectionSyncPendingKey&&this.ensurePersonalCollectionSyncDrain()}),this.personalCollectionSyncDrainPromise)}drainPersonalCollectionSync(){return M(this,null,function*(){for(;this.personalCollectionSyncPendingKey;){let t=this.personalCollectionSyncPendingKey;if(this.personalCollectionSyncPendingKey=null,!this.isCurrentProfileLoadKey(t))continue;let n=this.state.conversation.current,r=n==null?void 0:n.id;if(!(!r||!n.profileCode))try{yield this.deepdeskApi.syncPersonalCollection(r)}catch(o){this.isCurrentProfileLoadKey(t)&&J.warn("Failed to sync personal collection for profile",o)}}})}loadProfileConfig(t=!0){let n=this.getProfileLoadKey();if(!n)return this.loadProfileConfigPromise=null,this.loadProfileConfigPromiseKey=null,this.resetProfileDerivedSettings(),Promise.resolve();let r=this.state.conversation.current,o=tr(this.state);if(o&&o.code!==(r==null?void 0:r.profileCode)&&(this.loadProfileConfigPromise=null,this.loadProfileConfigPromiseKey=null,this.resetProfileDerivedSettings()),this.loadProfileConfigPromise&&this.loadProfileConfigPromiseKey===n)return this.loadProfileConfigPromise;this.loadProfileConfigPromise=null,this.loadProfileConfigPromiseKey=n;let s=Promise.resolve().then(()=>M(this,null,function*(){try{yield this.store.dispatch(ru()).unwrap()}catch(l){if(l===Ya)return this.loadProfileConfigPromise===s&&(this.loadProfileConfigPromise=null,this.loadProfileConfigPromiseKey=null),t&&this.isCurrentProfileLoadKey(n)&&!tr(this.state)?this.loadProfileConfig(!1):void 0;throw l}if(!this.isCurrentProfileLoadKey(n))return;let i=tr(this.state),a=this.state.conversation.current;!i||i.code!==(a==null?void 0:a.profileCode)||(this.store.dispatch(ql({showSearch:i.search,showImageSearch:i.imageSearch,showEntitiesCommand:i.entitiesCommand,showSummaryCommand:!!i.summarizerAssistantNew,showKnowledgeSearch:nM(i),recommendTextSuggestions:i.recommendTextSuggestions})),this.syncPersonalCollectionForConversation(n))})).finally(()=>{this.loadProfileConfigPromise===s&&(tr(this.state)||(this.loadProfileConfigPromise=null,this.loadProfileConfigPromiseKey=null))});return this.loadProfileConfigPromise=s,s}loginViaPopup(t){return M(this,null,function*(){return new Promise((n,r)=>{this.store.dispatch(Od());let o=new MessageChannel,s=o.port1,i=this.settings.adminUrl,a=new URL(t!=null&&t.url?t==null?void 0:t.url:`${i}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let l=!1,c=()=>{u&&!u.closed&&u.close(),window.removeEventListener("message",f),clearInterval(d)};s.onmessage=p=>M(this,null,function*(){var h,y;if((h=p.data)!=null&&h.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((y=p.data)==null?void 0:y.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(Il),l=!0,o.port1.close(),n()}catch(S){console.error(S),r(S)}finally{l=!0,c()}});let u=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");if(u===null){r(new Error("Popup blocked by browser"));return}let f=p=>M(this,null,function*(){var h;if(!(p.origin!==a.origin||p.source!==u))switch((h=p.data)==null?void 0:h.type){case"deepdesk-popup-request-origin":{try{let y=JSON.stringify({type:"deepdesk-popup-parent-origin"});u.postMessage(y,a.origin)}catch(y){J.error("Error posting message to popup",y),r(y)}break}case"deepdesk-popup-loaded":{try{let y=JSON.stringify({type:"deepdesk-popup-create-channel"});u.postMessage(y,a.origin,[o.port2])}catch(y){J.error("Error posting message to popup",y),r(y)}break}case"deepdesk-popup-error":{if(c(),p.data.message==="Platform account url mismatch"){let y="Please contact your administrator: The page that opened the popup is not a trusted origin.";J.warn(y),this.store.dispatch(xh(y)),r(new Error(y));return}if(p.data.message==="Timeout"){let y="Please contact your administrator: Popup timed out. Check if the account's platform.url or account.url is configured correctly.";J.warn(y),this.store.dispatch(xh(y)),r(new Error(y));return}r(new Error(p.data.message));break}}});window.addEventListener("message",f);let d=setInterval(()=>{u&&!u.closed||(c(),l||r(new Error("Popup closed by user")))},200);this.disposeHandlers.push(c)})})}translateMessages(t){return this.deepdeskApi.translateMessages(t)}refreshTextSuggestions(){return M(this,null,function*(){this.isMounted&&(yield this.store.dispatch(Dm()))})}refreshWidgetSuggestions(){return M(this,null,function*(){if(!this.widgetRoot)return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=ou(this.state);try{n.forEach(({type:r})=>{switch(r){case"entities":this.store.dispatch(Er());break;case"pinned-messages":case"sticky-messages":break;default:cd.includes(r)||this.store.dispatch(Cr(r))}})}catch(r){this.handleError(r)}})}};cl.version="19.6.2-beta.12",cl.count=0;var Du=cl;function A9(e){return M(this,null,function*(){var o,s,i;let n=yield((o=e.fetch)!=null?o:window.fetch)(e.url),r=yield n.blob();return new File([r],e.name,{type:(i=(s=e.mimeType)!=null?s:n.headers.get("Content-Type"))!=null?i:"image/jpeg"})})}function gM(e,t){return M(this,null,function*(){let n=yield A9(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 hM(e,t,n){return M(this,null,function*(){yield new Lo(e).authenticateWithKey(t,n)})}function yM(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function vM(r,o){return M(this,arguments,function*(e,t,n={}){var f,d;let{value:s}=e,{start:i,end:a}=(f=n.replace)!=null?f:{start:0,end:s.length},l=`${s.slice(0,i)}${t}${s.slice(a)}`,c=(d=n.selectionAfter)!=null?d:{start:i+t.length,end:i+t.length},u=()=>{if(n.setValue)return n.setValue(l);e.value=l};return Promise.resolve(u()).then(()=>{e.selectionStart=c.start,e.selectionEnd=c.end,e.blur(),e.focus()})})}function SM(r,o){return M(this,arguments,function*(e,t,n={}){let s=n.replace?Ts(e,n.replace.start,n.replace.end):il(e),i,a=()=>{if(n.setRange)return n.setRange(s.cloneRange());s.deleteContents(),i=document.createElement("span"),s.insertNode(i),n.insertBRs!==!1?t.split(`
|
|
83
|
+
`);let h=d?r:0,y=p?Math.min(s,u.childNodes.length):u.childNodes.length;for(let S=h;S<y&&(c(u.childNodes[S]),a!==2);S++);break}default:break}p&&(a=2)}return c(e),l}var M_=(i=>(i.CUT="Cut",i.BACKSPACE="Backspace",i.DELETE="Delete",i.ERASEEOF="EraseEof",i.UNDO="Undo",i.CLEAR="Clear",i))(M_||{}),Mo=class{constructor(t){this.element=t;this.isFocused=!1;this.isActive=!0;this.isDisposed=!1;this.eventListeners={};this.disposeHandlers=[];this.cachedText="";this.cachedSuggestionTextStart=0;this.cachedCaretPosition=null;this.cachedSelection={start:0,end:0};this.cachedHTML="";this.isSubmitting=!1;this.isPossibleClearInputAction=!1;this.cachedText=this.getText(),this.cachedSuggestionTextStart=this.getSuggestionTextStart(),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.getSuggestionTextStart(),s=this.cachedCaretPosition===null;if(!this.isActive)return;t===""&&this.cachedText!==""&&!this.isPossibleClearInputAction&&this.emit("submit");let i=t!==this.cachedText,a=n!==null&&n!==this.cachedHTML,l=o!==this.cachedSuggestionTextStart;if((i||a||l)&&(i?(this.cachedText=t,this.cachedHTML=n):a&&(this.cachedHTML=n),this.cachedSuggestionTextStart=o,s=!0,this.emit("change",{plainText:t,rawHTML:n,suggestionTextStart:o})),(r.start!==this.cachedSelection.start||r.end!==this.cachedSelection.end)&&(this.cachedSelection=r,s=!0,this.emit("selection",r)),!s)return;let c=this.getCaretPosition();Bo(c,this.cachedCaretPosition)||(this.cachedCaretPosition=c,this.emit("caretposition",c))}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(M_).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()})}getSuggestionTextStart(){return 0}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 L_(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var Ii=class extends Mo{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),Mu(this.element,n)}getHTML(){return this.element.innerHTML||""}getRange(){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=r.rangeCount>0?r.getRangeAt(0):null;if(!o)return null;let s=this.element.ownerDocument.createRange();return s.setStart(o==null?void 0:o.startContainer,o==null?void 0:o.startOffset),s.setEnd(o==null?void 0:o.endContainer,o==null?void 0:o.endOffset),!s||!this.element.contains(s.startContainer)||!this.element.contains(s.endContainer)?null:s}getCaretPosition(){let n=this.getRange();if(!n||!n.collapsed||!("getBoundingClientRect"in n))return null;let r=n.getBoundingClientRect();return!L_(r)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),r=n.getBoundingClientRect(),n.deleteContents(),!L_(r))?null:{top:r.top+r.height,left:r.left}}getSelection(){let n=this.getRange();if(n)return _u(this.element,n);let r=this.lastKnownSelection;if(r&&__(this.element,r.start,r.end))return r;let o=il(this.element);return o.collapse(!1),_u(this.element,o)}getSelectedText(){let{start:n,end:r}=this.getSelection();return Mu(this.element,Ts(this.element,n,r))}listen(){super.listen();let n=new MutationObserver(s=>{var i,a;s.length===2&&s[0].addedNodes.length===1&&((i=s[0].addedNodes[0])==null?void 0:i.textContent)==="\u2060"&&((a=s[1].removedNodes[0])==null?void 0:a.textContent)==="\u2060"||setTimeout(()=>{this.handleInteraction()},0)});n.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0}),this.disposeHandlers.push(()=>n.disconnect());let 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 p9=["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 O_(e,t){let n="mozInnerScreenX"in window,r=document.createElement("div");r.id="input-textarea-caret-position-mirror-div";let o=r.style,s=window.getComputedStyle(e),i=e.ownerDocument.body;o.whiteSpace="pre-wrap",o.wordWrap="break-word",o.position="absolute",o.visibility="hidden",p9.forEach(u=>{o[u]=s[u]}),n?e.scrollHeight>Number.parseInt(s.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),i.appendChild(r);let l=e.getBoundingClientRect(),c={top:l.top-e.scrollTop+a.offsetTop+Number.parseInt(s.borderTopWidth)+a.offsetHeight,left:l.left-e.scrollLeft+a.offsetLeft+Number.parseInt(s.borderLeftWidth)};return i.removeChild(r),c}var _i=class extends Mo{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 O_(this.element,this.element.selectionEnd)}listen(){super.listen();let n=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var s;return(s=n==null?void 0:n.get)==null?void 0:s.call(this.element)},set:s=>{var i;(i=n==null?void 0:n.set)==null||i.call(this.element,s),this.handleInteraction()}}),this.addEventListener("scroll",()=>{this.emit("caretposition",this.getCaretPosition())});let 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 N_(e,t,n){let r=`deepdesk-iframe-${e}`,o=document.getElementById(r);if(o)return o;let s=document.createElement("iframe"),i=new URL(t);return Object.entries(n).forEach(([a,l])=>{i.searchParams.append(a,l)}),s.style.position="absolute",s.style.left="-999em",s.style.width="0px",s.style.height="0px",s.tabIndex=-1,s.id=r,s.title=`iframe-${e}`,s.src=i.toString(),window.document.body.appendChild(s),s}function m9(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(t){return e}}var mx=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()}},gx=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.disposeHandlers=[];this.iframe=N_(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()}},hx=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.eventMap,this.externalId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setExternalId(t){this.externalId!==t&&(this.cleanup(),J.info("Set externalId",t),this.externalId=t,this.channel=this.createChannel(t))}createChannel(t){let n=this.params.createCustomChannel?this.params.createCustomChannel(t):this.isCrossOrigin?new gx(t,this.deepdeskUrl,{debug:!0}):new mx(t),r=o=>{var i,a;if(o.origin!==this.deepdeskUrl)return;let s=m9(o.data);typeof s!="object"||s.type!=="event"||s.channel!==t||(J.info("Received broadcast event",this.externalId,o),(a=(i=this.eventMap)[s.name])==null||a.call(i,s.payload))};return n.onMessage(r),n}send(t,n,r){var i,a;J.info("Broadcast event",{externalId:this.externalId,name:t,payload:n});let o={type:"event",name:t,payload:n};r!==!1&&((a=(i=this.eventMap)[t])==null||a.call(i,n));let s=this.externalId==="deepdesk-general"?this.defaultChannel:this.channel;s==null||s.postMessage(_(b({},o),{channel:this.externalId}))}cleanup(t=!1){var n,r;(n=this.channel)==null||n.close(),this.channel=void 0,t&&((r=this.defaultChannel)==null||r.close(),this.defaultChannel=void 0)}},D_=hx;function g9(e){return e.replace(/(_\w)/g,t=>t[1].toUpperCase())}function He(e){return Array.isArray(e)?e.map(He):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>_(b({},t),{[g9(n)]:He(e[n])}),{}):e}function h9(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function Mt(e){return Array.isArray(e)?e.map(Mt):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>_(b({},t),{[h9(n)]:Mt(e[n])}),{}):e}var al=class extends Error{constructor(n,r){super(n);this.body=r;this.name="CustomError"}};var Lu=e=>new Promise(t=>{setTimeout(t,e)});var Tr=class extends al{constructor(){super(...arguments);this.name="ClientError"}},fg=class extends al{constructor(){super(...arguments);this.name="ServerError"}},yx=new Map;function F_(e){return M(this,null,function*(){if(e.status===204)return e.text().catch(()=>{}),null;let t=e.headers.get("content-type");if(t!=null&&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 Mi=class{constructor(t="",n={}){this.baseUrl=t;this.options=n;this.latestRequestByUrl={};this.refreshingToken=null;this.lastFailedRefreshAt=null;this.failedRefreshCooldown=1e4;var r;this.fetch=(r=n.fetch)!=null?r:window.fetch.bind(window)}patchFetch(t){this.fetch=t(this.fetch)}setCsrfToken(t){this.csrfToken=t}request(t,n={}){return new Promise((r,o)=>{let s={isAborted:!1,reject:o},i=`${this.baseUrl}${t}`,a=this.fetch,l=n.method===void 0||n.method.toLowerCase()==="get",C=n,{useCache:c=!1,abortLatest:u=!1,attempts:f=1,retryDelay:d=500,refreshTokenOn401:p=!0,retryOnError:h=k=>k instanceof TypeError,retryOnResponse:y=k=>k.status>=500,version:S=null}=C,m=ie(C,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]);if(c){if(!l)throw new Error(`Can't use 'useCache' for ${n.method}`);if(yx.has(i)){r(yx.get(i));return}}let g=_(b({credentials:"include"},m),{headers:b({Accept:"application/json","Content-Type":"application/json"},m.headers)});!l&&this.csrfToken&&(g.headers=_(b({},g.headers),{"X-CSRFToken":this.csrfToken})),typeof S=="string"&&(g.headers=_(b({},g.headers),{"X-Deepdesk-API-Version":S}));let v=f,x=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[i]&&u&&(this.latestRequestByUrl[i].isAborted=!0,this.latestRequestByUrl[i].reject(new Error("Aborted"))),this.latestRequestByUrl[i]=s;let T=()=>M(this,null,function*(){return v--,a(i,g).then(k=>M(this,null,function*(){return y(k)&&!s.isAborted&&v>0?(yield Lu(d),T()):k.status===401&&p===!0&&x===!1?(x=!0,yield this.refreshToken(),T()):k})).catch(k=>M(this,null,function*(){if(h(k)&&!s.isAborted&&v>0)return yield Lu(d),T();throw k}))});T().then(k=>M(this,null,function*(){let P=yield F_(k);if(delete this.latestRequestByUrl[i],k.status>=500){o(new fg("Server Error",P));return}if(k.status===401){o(new Tr("Unauthorized",P));return}if(k.status===403){o(new Tr("Forbidden",P));return}if(k.status===404){o(new Tr("Not Found",P));return}if(k.status>=400){o(new Tr("Bad Request",P));return}c&&yx.set(i,P),r(P)})).catch(k=>{o(k)})})}validateToken(){return M(this,null,function*(){let t,n,r;try{({has_valid_access_token:t,is_logged_in:n,has_valid_refresh_token:r}=yield this.get("/apis/admin/session/validate/",{refreshTokenOn401:!1}))}catch(o){return!1}if(!t){if(!r)return!1;try{yield this.refreshToken();let{is_logged_in:o}=yield this.get("/apis/admin/session/validate/",{refreshTokenOn401:!1});return o}catch(o){return!1}}return n})}refreshToken(){let t=Date.now();return this.lastFailedRefreshAt&&t-this.lastFailedRefreshAt<this.failedRefreshCooldown?Promise.reject(new Tr("Unauthorized","Failed to refresh token")):this.refreshingToken?this.refreshingToken:(this.refreshingToken=this.get("/apis/admin/session/refresh/",{refreshTokenOn401:!1}).catch(n=>{throw(n==null?void 0:n.message)==="Unauthorized"&&(this.lastFailedRefreshAt=Date.now()),n}).finally(()=>{this.refreshingToken=null}),this.refreshingToken)}get(t,n){return this.request(t,n)}post(t,n,r){return this.request(t,b({method:"POST",body:JSON.stringify(n)},r))}postWithStatus(t,n,r){return this.requestWithStatus(t,b({method:"POST",body:JSON.stringify(n)},r))}requestWithStatus(t,n={}){return new Promise((r,o)=>{let s={isAborted:!1,reject:o},i=`${this.baseUrl}${t}`,a=this.fetch,T=n,{useCache:l=!1,abortLatest:c=!1,attempts:u=1,retryDelay:f=500,refreshTokenOn401:d=!0,retryOnError:p=C=>C instanceof TypeError,retryOnResponse:h=C=>C.status>=500,version:y=null}=T,S=ie(T,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]),m=_(b({credentials:"include"},S),{headers:b({Accept:"application/json","Content-Type":"application/json"},S.headers)});this.csrfToken&&(m.headers=_(b({},m.headers),{"X-CSRFToken":this.csrfToken})),typeof y=="string"&&(m.headers=_(b({},m.headers),{"X-Deepdesk-API-Version":y}));let g=u,v=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[i]&&c&&(this.latestRequestByUrl[i].isAborted=!0,this.latestRequestByUrl[i].reject(new Error("Aborted"))),this.latestRequestByUrl[i]=s;let x=()=>M(this,null,function*(){return g--,a(i,m).then(C=>M(this,null,function*(){return h(C)&&!s.isAborted&&g>0?(yield Lu(f),x()):C.status===401&&d===!0&&v===!1?(v=!0,yield this.refreshToken(),x()):C})).catch(C=>M(this,null,function*(){if(p(C)&&!s.isAborted&&g>0)return yield Lu(f),x();throw C}))});x().then(C=>M(this,null,function*(){let k=yield F_(C);if(delete this.latestRequestByUrl[i],C.status>=500){o(new fg("Server Error",k));return}if(C.status===401){o(new Tr("Unauthorized",k));return}if(C.status===403){o(new Tr("Forbidden",k));return}if(C.status===404){o(new Tr("Not Found",k));return}if(C.status>=400){o(new Tr("Bad Request",k));return}r({status:C.status,data:k})})).catch(C=>{delete this.latestRequestByUrl[i],o(C)})})}patch(t,n,r){return this.request(t,b({method:"PATCH",body:JSON.stringify(n)},r))}put(t,n,r){return this.request(t,b({method:"PUT",body:JSON.stringify(n)},r))}delete(t,n){return this.request(t,b({method:"DELETE"},n))}};var z_;(t=>{let e;(a=>(a.SUCCESS="success",a.FAILURE="failure",a.CONDITIONS_NOT_MET="conditions_not_met",a.MAX_RECURSION_LEVEL="max_recursion_level",a.NO_ACCESS_TO_ASSISTANT="no_access_to_assistant"))(e=t.EvaluationStatus||(t.EvaluationStatus={}))})(z_||(z_={}));function pg(e){return _(b({},He(e)),{metadata:e.metadata})}var Li=class Li{constructor(t,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new Mi(t,{fetch:n.fetch}),this.client.patchFetch(r=>(o,s)=>M(this,null,function*(){let i=yield r(o,s);return this.handleDeepdeskVersionHeaders(i),i}))}preflight(){return M(this,null,function*(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=yield this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(Li.exchangeTokenPromise||(Li.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),Li.exchangeTokenPromise):Promise.resolve()})}createConversation(t){return M(this,null,function*(){var r;yield this.preflight(),J.info(`Creating conversation for session ${t.externalId} and agent ${t.agentId}`);let n=yield this.client.post("/api/v2/conversations",_(b({chat_start_time:new Date().toISOString()},Mt(t)),{metadata:(r=t.metadata)!=null?r:{}}));return pg(n)})}upsertConversation(t){return M(this,null,function*(){var u;yield this.preflight(),J.info(`Upserting conversation for session ${t.externalId} and agent ${t.agentId}`);let{status:n,data:r}=yield this.client.postWithStatus("/api/v2/conversations",_(b({chat_start_time:new Date().toISOString()},Mt(t)),{metadata:(u=t.metadata)!=null?u:{}}),{version:"v2"}),o=pg(r);if(n===201)return o;let{agentId:s,agentName:i,agentEmail:a,agentNickname:l,metadata:c}=t;return this.updateConversation(o.id,{agentId:s,agentEmail:a,agentName:i,agentNickname:l,metadata:c})})}getMe(){return M(this,null,function*(){yield this.preflight();let t=yield this.client.get("/apis/admin/session/me/");return He(t)})}postIdentity(t){return M(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/me/identities/",Mt(t))})}patchMe(t){return M(this,null,function*(){yield this.preflight();let n=yield this.client.patch("/apis/admin/session/me/",Mt(t));return He(n)})}getProfile(t){return M(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${t}/`,{useCache:!0});return He(n)})}getKnowledgeAssistant(t){return M(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{useCache:!0});return He(n)})}getContentTypes(){return M(this,null,function*(){let t=yield this.client.get("/apis/admin/content-types/",{useCache:!0});return He(t)})}getAccount(){return M(this,null,function*(){let t=yield this.client.get("/apis/admin/account/",{useCache:!0});return He(t)})}getPlatformConfig(t){return M(this,null,function*(){let n=t!==void 0?`/platform/config/${t}/`:"/platform/config/",{config:r}=yield this.client.get(n,{useCache:!0});return He(r)})}checkUserExists(t){return M(this,null,function*(){let{exists:n}=yield this.client.get(`/apis/admin/users/exists?external_id=${t}`,{version:"v1"});return n})}getConversationByExternalId(r){return M(this,arguments,function*(t,n={}){yield this.preflight(),J.info(`Getting conversation for session ${t}`);let{attempts:o=1,retryDelay:s=1e3}=n,i=yield this.client.get(`/api/v2/conversations/by_external_id/${t}`,{attempts:o,retryDelay:s,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"});return J.info(`Successfully retrieved conversation ${i.id} for session ${t}`),pg(i)})}isConversationSupported(r){return M(this,arguments,function*(t,n={}){J.info(`Check if conversation for session ${t} is supported`);let{attempts:o=1,retryDelay:s=1e3}=n;return(yield this.client.get(`/api/v2/conversations/by_external_id/${t}/has_active_profile`,{attempts:o,retryDelay:s,retryOnResponse:a=>a.status===404||a.status>=500})).has_active_profile})}updateConversation(t,n){return M(this,null,function*(){var s;yield this.preflight();let r=Mt(n);n.metadata&&(r.metadata=(s=n.metadata)!=null?s:{});let o=yield this.client.put(`/api/v2/conversations/${t}`,r);return pg(o)})}postMessages(t,n){return M(this,null,function*(){yield this.preflight(),yield this.client.post(`/api/v2/conversations/${t}/messages`,n.map(r=>_(b({},Mt(r)),{metadata:r.metadata})))})}sendEvent(t,n){return M(this,null,function*(){yield this.preflight();let a=n,{data:r}=a,o=ie(a,["data"]),s=Object.entries(this.latestReceivedDeepdeskVersions).reduce((l,[c,u])=>_(b({},l),{[c]:u}),{}),i=["platform","agentId","agentName","agentEmail","conversationId"].reduce((l,c)=>(o[c]&&(l[c]=o[c]),l),{});return this.client.post("/api/v2/events",Mt(_(b(b({},s),i),{data:r,name:t})),{version:"v2"})})}getEntities(t){return M(this,null,function*(){return yield this.preflight(),yield this.client.post("/api/v2/entities",{messages:t.filter(r=>r.text)})})}getTemporaryExchangeToken(){return M(this,null,function*(){return(yield this.client.get("/apis/admin/session/exchange-token/")).jwt})}exchangeTokenForAccessCookie(t){return M(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 M(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/api-key/",Mt(n),{refreshTokenOn401:!1,headers:{apikey:t}})})}getTextSuggestions(o){return M(this,arguments,function*(t,n={},r){if(yield this.preflight(),r==="sticky-messages")throw new Error("Use getPinnedMessages instead");return(yield this.client.post(`/api/v2/conversations/${t}/recommend/${r}`,Mt(n),{abortLatest:!0})).map(i=>_(b({},He(i)),{text:i.text||i.url||i.message,source:r,type:r})).filter((i,a,l)=>a===l.findIndex(c=>c.text===i.text))})}isLoggedIn(){return M(this,null,function*(){return yield this.preflight(),this.client.validateToken()})}getAutocompleteSuggestions(t,n){return M(this,null,function*(){return yield this.preflight(),(yield this.client.post(`/api/v2/conversations/${t}/autocomplete`,Mt(n),{abortLatest:!0})).map(o=>({score:1,source:o.source,sourceText:o.source_text,text:o.label,trainingJobs:o.training_jobs,searchKeywords:o.search_keywords,type:o.source})).filter((o,s,i)=>s===i.findIndex(a=>a.text===o.text))})}syncPersonalCollection(t){return M(this,null,function*(){yield this.preflight(),yield this.client.post(`/api/v2/conversations/${t}/personal-collection/sync`,{},{version:"v2"})})}getPinnedMessages(t){return M(this,null,function*(){let n=yield this.client.get(`/api/v2/profiles/${t}/pinned-messages`,{abortLatest:!0});return He(n).map(r=>_(b({},r),{text:r.message,source:"sticky-messages",type:"pinned-message"}))})}getStyleSuggestions(t){return M(this,null,function*(){let n=yield this.client.post("/api/v2/style-suggestions",Mt(t),{abortLatest:!0,version:"v2"});return He(n)})}search(t){return M(this,null,function*(){let n=yield this.client.post(`/api/v2/profiles/${t.profile}/search`,Mt(t));return He(n)})}loginWithPassword(t,n){return M(this,null,function*(){yield this.preflight();let r=yield this.client.post("/apis/admin/session/login/",{username:t,password:n},{refreshTokenOn401:!1});return He(r)})}logout(){return M(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/logout/",{},{refreshTokenOn401:!1})})}requestLoginByEmail(t){return M(this,null,function*(){yield this.preflight();let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:t});return He(n)})}requestPasswordlessToken(){return M(this,null,function*(){let t=yield this.client.get("/apis/admin/session/passwordless/request/");return He(t.token)})}getCsrfToken(){return M(this,null,function*(){let{token:t}=yield this.client.get("/apis/admin/session/csrf/");return t})}verifyLoginToken(t){return M(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/login/",{token:t});return He(n)})}evaluateAssistant(t,n){return M(this,null,function*(){var l,c,u;yield this.preflight();let r=new URLSearchParams;n!=null&&n.externalConversationId&&r.append("external_conversation_id",n.externalConversationId);let o=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=f=>Mt(f),i=(l=n==null?void 0:n.transcript)==null?void 0:l.map(f=>{var d;return b({source:f.source,text:f.text},(d=f.attachments)!=null&&d.length?{attachments:f.attachments.map(s)}:{})}),a=yield this.client.post(o,b({input:(c=n==null?void 0:n.input)!=null?c:{},conversation:i},(u=n==null?void 0:n.attachments)!=null&&u.length?{attachments:n.attachments.map(s)}:{}));return He(a)})}interactWithAssistant(t){return M(this,null,function*(){yield this.preflight();let n=new URLSearchParams;t.sessionId&&n.append("session_id",t.sessionId),t.externalConversationId&&n.append("external_conversation_id",t.externalConversationId);let r=`/api/v2/assistants/${t.assistantCode}/interact?${n.toString()}`,o=yield this.client.post(r,{message:t.message});return He(o)})}resetAssistantThread(t){return M(this,null,function*(){yield this.preflight();let n=encodeURIComponent(t.assistantCode),r=encodeURIComponent(t.sessionId);yield this.client.delete(`/api/v2/assistants/${n}/sessions/${r}/thread`)})}createAssistantThread(t){return M(this,null,function*(){yield this.preflight();let{assistantCode:n}=t,r=yield this.client.post(`/apis/admin/assistants/${n}/threads/`,{});return He(r)})}postMessageToAssistantThread(t){return M(this,null,function*(){yield this.preflight();let{assistantCode:n,threadId:r,message:o}=t,s=yield this.client.post(`/apis/admin/assistants/${n}/threads/${r}/messages/`,{content:o,role:"user"});return He(s)})}translateMessages(t){return M(this,null,function*(){yield this.preflight();let n=yield this.client.post("/api/v2/translate",Mt(t));return He(n)})}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),s=o.match(Ow);if(!n||!s)return;let i=s[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&n&&a!==n&&J.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[i]=n})}};Li.exchangeTokenPromise=null;var Lo=Li;var mg=class{constructor(t){this.options=t;this.socket=null;this.maxReconnectAttempts=5;this.reconnectInterval=25e3;this.cleanupCallbacks=[];var n,r;this.socket,this.eventListeners=new Map,this.url=t.url,this.maxReconnectAttempts=(n=t.maxReconnectAttempts)!=null?n:this.maxReconnectAttempts,this.reconnectInterval=(r=t.reconnectInterval)!=null?r:this.reconnectInterval,this.shouldReconnect=t.shouldReconnect}connect(){let t=()=>this.cleanup();window.addEventListener("beforeunload",t),this.cleanupCallbacks.push(()=>window.removeEventListener("beforeunload",t)),this.reconnect()}setupListeners(){this.socket&&(this.socket.onmessage=t=>{var n;try{let r=He(JSON.parse(t.data));r.event&&this.eventListeners.has(r.event)&&((n=this.eventListeners.get(r.event))==null||n.forEach(o=>o(r.data)))}catch(r){console.error("Error parsing WebSocket message:",r)}},this.socket.onclose=t=>{console.log("WebSocket connection closed:",t),setTimeout(()=>{this.reconnect()},this.reconnectInterval)},this.socket.onerror=t=>{console.error("WebSocket error:",t)})}reconnect(){var t,n;if(this.maxReconnectAttempts<=0){console.error("Max reconnect attempts reached, closing WebSocket connection."),(t=this.socket)==null||t.close();return}if(!this.shouldReconnect()){console.error("Should not reconnect, closing WebSocket connection."),(n=this.socket)==null||n.close();return}this.socket&&(this.socket.onmessage=null,this.socket.onclose=null,this.socket.onerror=null,this.socket.close()),this.socket=new WebSocket(this.url),this.setupListeners(),this.maxReconnectAttempts--}send(t,n){if(!this.socket){console.error("WebSocket connection is not open.");return}this.socket.send(JSON.stringify({event:t,data:n}))}on(t,n){this.eventListeners.has(t)||this.eventListeners.set(t,[]);let r=this.eventListeners.get(t);r&&!r.includes(n)&&r.push(n)}close(){var t;(t=this.socket)==null||t.close()}cleanup(){this.close(),this.cleanupCallbacks.forEach(t=>t()),this.cleanupCallbacks=[]}};var H_={startTime:null,stopTime:null},B_=e=>e.handlingTime,U_=Pe({name:"handlingTime",initialState:H_,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(Ke,()=>H_)}}),{handlingTimeStart:V_,handlingTimeStop:gg,handlingTimeReset:W_}=U_.actions,$_=U_.reducer;var j_=(e={})=>{let t=b({onAuthError:qi(!1)},e);return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var K_=(e={})=>{let t,n=!0,r=b({getStyleSuggestions:Ti,debounce:500},e);return o=>s=>i=>{var p;let a=o.getState().input.text,l=s(i),c=o.getState();if(c.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:u}=c.settings;if(!((p=c.conversation.current)==null?void 0:p.id)||!u)return l;let{text:d}=c.input;return d===a&&!n||(clearTimeout(t),d==="")||(t=setTimeout(()=>{n=!1,o.dispatch(r.getStyleSuggestions({text:d}))},e.debounce)),l}};function y9(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end&&e.suggestionTextStart===t.suggestionTextStart}var G_=(e={})=>{let t=b({getTextSuggestions:Cr,getAutocompleteSuggestions:vu,debounce:200,check:Gr},e),n;return r=>o=>s=>{var y;let{input:i}=r.getState(),a=o(s),l=r.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:c,showTabCompletion:u}=l.settings,f=(y=l.conversation.current)==null?void 0:y.id,d=s.type===Dm.toString();if(!f||!c&&!u)return a;let{input:p}=l;return y9(p,i)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let S=Ns(l);S===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(S))},d?0:t.debounce)),a}};var q_=Ti.fulfilled.toString();function v9(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let s=e.keywordMatches.filter(l=>l.keyword===o),i=t.keywordMatches.filter(l=>l.keyword===o),a=i.length-s.length;a<=0||r.push(...i.slice(0,a))}),r}var Y_=e=>t=>n=>r=>{var c;if(r.type!==q_){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let s=t.getState(),i=s.styleSuggestions.list,a=(c=s.conversation)==null?void 0:c.current;if(o===i)return;let l=v9(o,i);r.type===q_&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var S9=pd({assistants:yC,auth:Gb,conversation:tE,contentTypes:vA,passwordlessToken:a_,entities:GA,handlingTime:$_,info:EE,input:pE,settings:SC,profile:CA,search:AE,styleSuggestions:II,ui:vI,textSuggestions:rI});function X_(e){return Ob({reducer:S9,middleware:t=>{var r;let n=t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI}},serializableCheck:!1}).concat(j_()).concat(G_({debounce:200})).concat(K_({debounce:500})).concat(Y_(e.deepdeskAPI));return((r=e.middleware)!=null?r:[]).reduce((o,s)=>o.concat(s),n)},preloadedState:e.preloadedState})}function Q_(e,t,n){if(t==="")return null;let r=new RegExp(`\\b${Xm(t)}\\b`,"gi"),o,s=null;for(;(o=r.exec(e))!==null&&!(o.index>n);)s={start:o.index,end:o.index+o[0].length};return s}var x9=e=>{var t,n;return(n=(t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())!=null?n:"unknown"},w9=e=>t=>n=>r=>{var l,c,u,f,d,p;let o=t.getState(),s=Ws("inlineSuggestions")(o),i=Ws("autoSelectSuggestion")(o)||s;switch(r.type){case qi.toString():{!r.payload&&e.emit("logout",void 0);break}case Ld.fulfilled.toString():{e.emit("logout",void 0);break}case Er.fulfilled.toString():r.payload.length>0&&e.sendEvent("entities found",{conversationId:(l=o.conversation.current)==null?void 0:l.id,data:{entities:r.payload}});break;case zs.toString():e.logSendMessage(r.payload);break;case df.toString():e.emit("call-to-action",{cue:r.payload});break;case kn.fulfilled.toString():if(!r.isBroadcasted){let{externalConversationId:h,currentExternalIdAtRequest:y}=(c=r.payload)!=null?c:{};(!h||!y||h===y)&&e.broadcast(_h,r,!1)}break;case kn.rejected.toString():break;default:break}let a=n(r);switch(r.type){case zs.toString():e.handleAfterSendMessage(r.payload);break;case xu.toString():e.onUpdateShowTabHint(r.payload);break;case gg.toString():e.logHandlingTime();break;case Qi.toString():e.broadcast(Kd,r);break;case Fs.toString():e.broadcast(Kd,r);break;case ff.toString():t.dispatch(Fs({source:"assistant",assistantCode:r.payload.code}));break;case"analytics/logEvent/fulfilled":{let h=o.assistants.cues.find(y=>y.code===r.meta.arg.data.assistantCode);e.emit("event",_(b({},r.meta.arg),{cue:h}));break}case Cn.toString():{let{start:h,end:y}=o.input.selection;e.emit("select-suggestion",_(b({type:x9(r.payload.suggestion)},r.payload),{replace:r.payload.replace==="selection"?{start:h,end:y}:{start:0,end:y}})),s&&t.dispatch(Uo([]));break}case AI.toString():{let{keyword:h,suggestion:y,eventMetrics:S}=r.payload,{text:m,selection:g}=o.input,v=Q_(m,h,(u=g==null?void 0:g.end)!=null?u:m.length);if(!v)break;e.emit("select-suggestion",{text:y,type:"style",replace:v,suggestion:{text:y,source:"style"},eventMetrics:S});break}case Hd.toString():e.emit("select-image",r.payload),e.sendEvent("Image attached",{conversationId:(f=o.conversation.current)==null?void 0:f.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case Uo.toString():{i&&r.payload.length>0&&t.dispatch(Bd(0));break}case kn.fulfilled.toString():{let{evaluationId:h,output:y,externalConversationId:S}=r.payload,m=r.meta.arg.assistantCode;if(e.emit("event",{name:"Assistant evaluation completed",data:{evaluationId:h,assistantCode:m,assistantOutput:dC(y),externalConversationId:S,evaluationStatus:"success"}}),!r.meta.arg.skipState){let g=t.getState().assistants.cues;e.emit("cues",g)}break}case kn.rejected.toString():{let h=r.meta.arg.assistantCode,y=(p=r.meta.arg.externalConversationId)!=null?p:(d=t.getState().conversation.current)==null?void 0:d.externalId;e.emit("event",{name:"Assistant evaluation completed",data:{evaluationId:"",assistantCode:h,assistantOutput:"",externalConversationId:y,evaluationStatus:"failed"}});break}default:break}return a},Z_=w9;function vx(e){return e.toISOString().replace("T"," ").replace("Z","")}var b9=(e,t)=>t.version,J_=Yt([Zi,Vn,B_,b9],(e,t,n,r)=>{if(!t)return J.warn("No conversationId for handling time metrics"),null;let{startTime:o,stopTime:s}=n;return!o||!s?(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:vx(o),timeStop:vx(s)}});function eM(e,t){let{text:n,metrics:{numPaste:r,pastes:o,textSuggestions:s}}=e.input,i=n.length;return{source:"agent",clientVersion:t.version,pastes:o,lenTextTotal:i,numPastes:r,suggestions:s}}var Ou=class extends Error{};function E9(){let e,t;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}}var hg=class{constructor(){this.queues={}}push(t,n){let r=()=>{let s=this.queues[t][1];s?(this.queues[t]=[s.promise,null],s.resolve()):delete this.queues[t]};if(!this.queues[t]){let s=n().finally(r);return this.queues[t]=[s,null],s}this.queues[t][1]&&this.queues[t][1].reject(new Ou("Queued async function is outdated"));let o=E9();return this.queues[t][1]=o,o.promise.then(()=>n().finally(r))}};function Sx(e,t){var s;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return Sx(r,t);let o=(s=e.ownerDocument.defaultView)==null?void 0:s.frameElement;return o?Sx(o,t):null}function xx(e,t){return Sx(e,t)}var C9={accepted:"onConversationAcceptedAssistants","new-message":"onConversationNewMessageAssistants",ended:"onConversationEndedAssistants"},tM=(e,t)=>{var o,s,i;if(!((i=(s=(o=e.uiConfig)==null?void 0:o.widget)==null?void 0:s.types.find(a=>a.type==="cues"))==null?void 0:i.isActive))return J.warn("Triggered a conversation assistant, but cues are not configured in widget."),[];let r=e[C9[t]];if(r&&r.length>0){let a=r.map(l=>l.code);return e.summarizerAssistantNew&&t!=="ended"&&(a=a.filter(l=>l!==e.summarizerAssistantNew)),a}return J.warn(`No assistant set in profile for conversation event "${t}"`),[]};function T9(e){var t,n,r,o;return(o=(r=(n=(t=e.uiConfig)==null?void 0:t.widget)==null?void 0:n.types)==null?void 0:r.some(s=>s.type==="knowledge-assist"&&s.isActive))!=null?o:!1}function nM(e){var n,r;return((r=(n=e.widgetInteractiveAssistants)==null?void 0:n.length)!=null?r:0)>0&&T9(e)?!0:!!e.knowledgeAssistantNew||!!e.knowledgeAssistant}function k9(e){return typeof e=="object"&&e!==null&&"tagName"in e}function yg(e){return k9(e)&&(Ri(e)||qm(e))}var oM,Xr=new Map,R9=["bottom","height","left","right","top","width"],rM=(e,t)=>!e&&!t?!1:e&&!t||!e&&t?!0:R9.some(n=>e[n]!==t[n]);function sM(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,...sM(t)]:[]}function iM(e,t){return!e||!t?null:_(b({},e),{top:e.top+t.top,left:e.left+t.left})}var vg=!1,aM=()=>{vg=!0;let e=[];if(Xr.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),Xr.delete(n);return}let r=n.getBoundingClientRect();rM(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(iM,t.rect):t.rect;rM(n,t.totalRect)&&t.callbacks.forEach(r=>r(n)),t.totalRect=n}),Xr.size===0){vg=!1;return}oM=window.requestAnimationFrame(aM)};function wx(e,t){let n=sM(e),r=[],o=n.map((s,i)=>wx(s,a=>{r[i]=a;let l=Xr.get(e);if(!l)return;let c=r.reduce(iM,l.rect);l.callbacks.forEach(u=>u(c))}));return{observe(s=!0){if(o.forEach(i=>i.observe(!1)),Xr.has(e)){let i=Xr.get(e);i.callbacks.push(t),i.rect&&t(i.rect)}else Xr.set(e,{rect:void 0,callbacks:[t],parentRects:r});s&&!vg&&aM()},unobserve(){o.forEach(i=>i.unobserve());let s=Xr.get(e);if(s){let i=s.callbacks.indexOf(t);i>=0&&s.callbacks.splice(i,1),s.callbacks.length||Xr.delete(e),Xr.size||(cancelAnimationFrame(oM),vg=!1)}}}}var lM,Qr=new Map,cM=()=>{Qr.forEach((e,t)=>{if(!t.isConnected){Qr.delete(t);return}let{clientHeight:n,scrollHeight:r}=t,o=r>n;e.visible!==o&&(e.visible=o,e.callbacks.forEach(s=>s(e.visible)))}),Qr.size!==0&&(lM=window.requestAnimationFrame(cM))};function uM(e,t){return{observe(){let n=Qr.size===0;Qr.has(e)?Qr.get(e).callbacks.push(t):Qr.set(e,{visible:void 0,callbacks:[t]}),n&&cM()},unobserve(){let n=Qr.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||Qr.delete(e),Qr.size||cancelAnimationFrame(lM)}}}}var bx=["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 Ex(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function ll(e){return Number.parseFloat(e)}function Sg(e){return Math.round(e*1e6)}function dM(e){return e/1e6}function Cx(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=ll(e.width),s=ll(e.borderLeftWidth),i=ll(e.borderRightWidth),a=ll(e.paddingRight),l=dM(Sg(o)-Sg(s)-Sg(i)),c=dM(Sg(r));if(l-c>2){let u=l-c;n.style.paddingRight=`${a+u}px`}}function Nu(e,t={}){var u,f;let n=t.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=(u=t.position)!=null?u:"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",mi(n);let r=window.getComputedStyle(e),o=!0,s=()=>{n.scrollTop=e.scrollTop};Ex(r,n,bx),Cx(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",s));let i=uM(e,()=>{Ex(r,n,bx),Cx(r,e,n),s(),setTimeout(s,0)}),a,l=!0,c=wx(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(Ex(r,n,bx),Cx(r,e,n),s(),t.placement==="below"&&n.classList.add("below"),n.style.top=`${d.top}px`,n.style.left=`${d.left}px`,t.closestScrollElement&&t.closestScrollElement!==e){let p=t.closestScrollElement.getBoundingClientRect(),h=window.getComputedStyle(t.closestScrollElement),y=ll(h.borderTopWidth),S=ll(h.borderBottomWidth),m=p.top+y-d.top,g=d.top+d.height+-(p.top+p.height-S);n.style.clipPath=`inset(${m}px 0px ${g}px 0px)`}o&&(n.style.display="block",t.onShow&&t.onShow(),o=!1)});return t.appendTo?t.appendTo.appendChild(n):(f=e.parentElement)==null||f.appendChild(n),c.observe(),i.observe(),[n,()=>{e.removeEventListener("scroll",s),c.unobserve(),i.unobserve(),n.remove()}]}function P9(e){return e.offsetParent!==null}function fM(e){if(!P9(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 xg(e,t,n=100){let r=fM(e);t({isVisible:r});let o=setInterval(()=>{let s=fM(e);s!==r&&(r=s,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var pM=(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")}}});var Re=E(A());var mM=pM("showTabHint",!0),cl=class cl{constructor({deepdeskUrl:t,version:n=cl.version||"unknown",locale:r="en-US",token:o,fetch:s,productName:i,createCustomChannel:a,websocketClient:l=mg}){this.inputMediator=null;this.eventListeners={};this.unmountHandlers=[];this.disposeHandlers=[];this.inlineSuggestions=null;this.aboveSuggestions=null;this.belowSuggestions=null;this.floatingMenu=null;this.widgetElement=null;this.widgetRoot=null;this.nicknameDialogUnsubscribe=null;this.nicknameDialogFailed=!1;this.dynamicThunkObject={};this.queues=new hg;this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;this.loadProfileConfigPromiseKey=null;this.personalCollectionSyncPendingKey=null;this.personalCollectionSyncDrainPromise=null;let c=t.replace(/\/api$/,"");this.deepdeskApi=new Lo(c,{token:o,fetch:s}),this.version=n,this.instanceId=cl.count++;let u={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[Z_({broadcast:(h,y,S)=>{this.broadcastEvents.send(h,y,S)},emit:(h,y)=>this.emit(h,y),handleAfterSendMessage:h=>this.handleAfterSendMessage(h),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:h=>this.logSendMessage(h),onUpdateShowTabHint:h=>mM.update(h),sendEvent:(h,y)=>this.deepdeskApi.sendEvent(h,y)})]};this.store=X_(u),this.broadcastEvents=new D_({debug:!0,deepdeskUrl:c,eventMap:IE(this.store),createCustomChannel:a}),this.disposeHandlers.push(()=>{this.broadcastEvents.cleanup()}),this.ws=new l({url:`${c}/api/v2/me/realtime`.replace("https","wss"),reconnectInterval:25e3,shouldReconnect:()=>M(this,null,function*(){var h;return(h=kt(this.state))!=null?h:!1})}),this.whenLoggedIn(()=>this.ws.connect()),this.store.dispatch(xu(mM.value())),this.store.dispatch(ql({locale:r,adminUrl:c,productName:i}));let f=[],d=h=>{if(!h.conversationId)return;let y=()=>{this.conversationId()===h.conversationId&&this.store.dispatch(gC(h))};this.hasConversation()?y():f.push(y)};this.ws.on("assistants::direct_response",d),this.ws.on("assistants::user_notification",d),this.ws.on("assistants::response_chunk",h=>{if(!h.conversationId)return;let y=()=>{this.conversationId()===h.conversationId&&this.store.dispatch(mC(h))};this.hasConversation()?y():f.push(y)}),this.ws.on("assistants::suggest_as_reply",h=>{if(!h.conversationId)return;let y=()=>{this.conversationId()===h.conversationId&&this.store.dispatch(Qi([{text:h.payload.message,type:"text",source:"assistant",assistantCode:h.code,sourceLabel:h.name}]))};this.hasConversation()?y():f.push(y)});let p=this.whenConversationLoaded(()=>{var h;this.broadcastEvents.setExternalId((h=this.state.conversation.current)==null?void 0:h.externalId),f.forEach(y=>y()),f.length=0});this.disposeHandlers.push(()=>{this.ws.cleanup(),f.length=0,p()})}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){var t;return(t=Ds(this.state)[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}externalId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.externalId}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)}whenLoggedIn(t){if(kt(this.state))t();else{let n=this.subscribe(kt,r=>{r&&t()});this.disposeHandlers.push(()=>{n()})}}login(){return this.store.dispatch(qi(null)),this.store.dispatch(to()),new Promise(t=>{this.whenLoggedIn(()=>t())})}isLoggedIn(){return M(this,null,function*(){return(yield this.store.dispatch(to())).payload})}isConversationSupported(t,n){return M(this,null,function*(){return(yield this.store.dispatch(Ch({externalId:t,options:n}))).payload})}createConversation(t){return M(this,null,function*(){var r;return this.hasConversation()&&this.externalId()!==t.externalId&&this.resetConversation(),(yield this.store.dispatch(Dd(_(b({},t),{metadata:(r=t.metadata)!=null?r:{}})))).payload})}getConversationByExternalId(t,n){return M(this,null,function*(){return this.hasConversation()&&this.externalId()!==t&&this.resetConversation(),(yield this.store.dispatch(Fd({externalId:t,options:n}))).payload})}upsertConversation(t){return M(this,null,function*(){var r;return this.hasConversation()&&this.externalId()!==t.externalId&&this.resetConversation(),(yield this.store.dispatch(Th(_(b({},t),{metadata:(r=t.metadata)!=null?r:{}})))).payload})}postMessages(t){return M(this,null,function*(){yield this.store.dispatch(kh(t))})}updateConversation(t){return M(this,null,function*(){return(yield this.store.dispatch(zd(t))).payload})}resetConversation(){this.store.dispatch(Ke()),this.loadProfileConfigPromise=null,this.loadProfileConfigPromiseKey=null,this.dynamicThunkObject.conversationQuery=null}configure(t){this.store.dispatch(ql(t))}setVisitorInfo(t){this.store.dispatch(SE(t))}setCustomData(t){this.store.dispatch(xE(t))}setAgentInfo(t,n){return M(this,null,function*(){var o;yield this.store.dispatch(Pl(b(b({},t),n))),(o=this.state.info.agentInfo)!=null&&o.agentNickname||this.broadcastEvents.send(jd,{showNicknameDialog:!0})})}setAgentSettings(t){return M(this,null,function*(){yield this.store.dispatch(Ph(t))})}getAgentSettings(){return M(this,null,function*(){return(yield this.store.dispatch(Ah())).payload})}getMe(){return M(this,null,function*(){return this.deepdeskApi.getMe()})}refresh(){return M(this,null,function*(){if(this.shouldAbort())return Promise.resolve();let t=[];return t.push(this.refreshTextSuggestions()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})})}syncInputMediator(){this.inputMediator&&this.store.dispatch(Ud({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),suggestionTextStart:this.inputMediator.getSuggestionTextStart()}))}notifyExternalSuggestion(t){this.store.dispatch(Cn(t))}evaluateAssistant(t,n){return M(this,null,function*(){var u;let{input:r={},attachments:o=[],transcript:s,showCuesInWidget:i=!0,includeMetadata:a,externalConversationId:l}=n||{},c=yield this.store.dispatch(kn({assistantCode:t,attachments:o,transcript:s,includeMetadata:a,input:r,externalConversationId:l,skipState:!i}));if(c.error)throw new Error(`Assistant evaluation failed: ${(u=c.payload)!=null?u:c.error.message}`);return c.payload.output})}evaluateConversationAssistant(t,n){return M(this,null,function*(){var u,f,p;yield this.loadProfileConfig();let r=this.state.profile.data;if(!r&&((u=this.state.conversation.current)!=null&&u.profileCode)&&(yield this.loadProfileConfig(),r=this.state.profile.data),!r){J.warn("Can't evaluate assistant when profile is not loaded yet.");return}let o=tM(r,t),s=(f=n==null?void 0:n.showCuesInWidget)!=null?f:!0,d=n!=null?n:{},{showCuesInWidget:i}=d,a=ie(d,["showCuesInWidget"]),l=(p=n==null?void 0:n.externalConversationId)!=null?p:this.hasConversation()?this.externalId():"",c=yield Promise.all(o.map(h=>this.queues.push(h,()=>M(this,null,function*(){var S,m;let y=yield this.store.dispatch(kn(b(_(b({assistantCode:h,includeMetadata:!0},a),{skipState:!s}),n!=null&&n.attachments&&(n==null?void 0:n.attachments.length)>0?{attachments:n==null?void 0:n.attachments}:{})));if(y.error)throw new Error(`Assistant evaluation failed: ${(S=y.payload)!=null?S:y.error.message}`);return{assistantCode:h,evaluationId:y.payload.evaluationId,output:y.payload.output,externalConversationId:(m=y.payload.externalConversationId)!=null?m:l}})).catch(y=>{if(y instanceof Ou)return J.warn(`Queued assistant "${h}" was outdated and dropped`),null;throw y})));if(!s)return c.filter(h=>h!==null)})}handleKeyDown(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui,{textSuggestions:o,selectedSuggestionIndex:s,selection:i}=this.state.input,{inlineSuggestions:a,autoSelectSuggestion:l,showTextSuggestions:c,suggestionsPlacement:u}=this.settings,f=a||l,d=u==="inline"||u==="below"?"below":"above",p=o.length>0;if(this.store.dispatch(iE(Rh(t))),!Gr(this.state)||t.key!=="Tab"&&!c)return;let h=()=>{n||!p||i&&(t.shiftKey||(this.store.dispatch(cE()),t.preventDefault()))},y=()=>{n||!p||f&&s<=0||i&&(t.shiftKey||(this.store.dispatch(uE()),t.preventDefault()))};switch(t.key){case"ArrowUp":d==="below"?y():h();break;case"ArrowDown":{d==="below"?h():y();break}case"Escape":{n||(this.store.dispatch(Bd(-1)),this.store.dispatch(xs({collapse:!0})),this.store.dispatch(hI(!0)),t.preventDefault());break}case"Tab":{t.preventDefault();let S=Xi(this.state);if(!S)return;this.store.dispatch(xu(!1)),this.store.dispatch(Cn({text:S.text,suggestion:S,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(f||this.state.input.selectedSuggestionIndex===-1)return;let S=Xi(this.state);if(!S)return;this.store.dispatch(Cn({text:S.text,suggestion:S,eventMetrics:{inputType:"space"},replace:"until-selection-end"}));break}case"Enter":{if(f||t.shiftKey||this.state.input.selectedSuggestionIndex===-1)return;let S=Xi(this.state);if(!S)return;this.store.dispatch(Cn({text:S.text,suggestion:S,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),t.preventDefault();break}default:}n&&r&&this.store.dispatch(xs({collapse:!1}))}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(Uo([]))}handlingTimeStart(){this.state.handlingTime.startTime||(J.info("Start handling time"),this.store.dispatch(V_()))}handlingTimeStop(){this.state.handlingTime.startTime&&(J.info("Stop handling time"),this.store.dispatch(gg()))}logSendMessage(t){let n=eM(this.state,{version:this.version});n&&(t&&(Object.assign(n,{text:t}),Object.assign(n,{lenTextTotal:t.length})),this.deepdeskApi.sendEvent("Send Message",{conversationId:this.conversationId(),data:n}),this.emit("send-message-event",n))}logHandlingTime(){let t=J_(this.state,{version:this.version});t&&(this.deepdeskApi.sendEvent("Handling Time",{conversationId:this.conversationId(),data:t}),this.store.dispatch(W_()))}notifySubmit(t={}){var n;this.shouldAbort()||(this.store.dispatch(zs((n=t.text)!=null?n:this.state.input.text)),this.store.dispatch(fE()))}emit(t,n){let r=this.eventListeners[t];r&&r.forEach(o=>{try{o(n)}catch(s){J.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),J.error(s)}})}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(wE(t))}whenConversationLoaded(t){let n=()=>this.getConversationLoadedKey(),r=()=>{let s=n();s&&this.loadProfileConfig().then(()=>{if(n()!==s)return;let i=this.state.conversation.current,a=tr(this.state);!(i!=null&&i.id)||i.profileCode&&(a==null?void 0:a.code)!==i.profileCode||t()})};return n()&&r(),this.subscribe(s=>this.getConversationProfileKey(s.conversation.current),s=>{s&&r()})}overlayContainerFactory(t,n,r,o){let[s,i]=Nu(n,r);return s.setAttribute("translate","no"),s.dataset.testid=t,o&&s.classList.add(o),[s,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 s=(a=t.ownerDocument.defaultView)==null?void 0:a.frameElement,i=s?s.ownerDocument.defaultView:null;if(s&&(i===window||(i==null?void 0:i.parent)===window)){let[l,c]=Nu(s,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});l.dataset.testid=n,l.style.zIndex="2",l.appendChild(r),this.unmountHandlers.push(()=>{c()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return mi(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),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(dE(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(!yg(t))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let d=n,{customStyles:r,closestScrollSelector:o,floatingMenuParent:s,appendOverlayTo:i,inputMediator:a}=d,l=ie(d,["customStyles","closestScrollSelector","floatingMenuParent","appendOverlayTo","inputMediator"]),c={customStyles:r,closestScrollSelector:o,floatingMenuParent:s,appendOverlayTo:i};this.configure(l),this.settings.automaticHandlingTime&&this.setupHandlingTime(t),mi(t),this.inputMediator=a||(Ri(t)?new _i(t):new Ii(t)),this.inputMediator.on("change",({plainText:p,rawHTML:h,suggestionTextStart:y})=>{this.store.dispatch(Ud({text:p,html:h,suggestionTextStart:y}))}),this.inputMediator.on("keyup",p=>{this.store.dispatch(aE(Rh(p)))}),this.inputMediator.on("keydown",p=>{this.handleKeyDown(p)}),this.inputMediator.on("paste",({pastedText:p,selectionText:h})=>{this.store.dispatch(lE({text:p,selectionText:h}))}),this.inputMediator.on("cut",({selectionText:p})=>{this.store.dispatch(sE(p))});let u;this.inputMediator.on("selection",p=>{clearTimeout(u),p===null?u=setTimeout(()=>{p!==null&&this.store.dispatch(Vd(p))},500):this.store.dispatch(Vd(p))}),this.unmountHandlers.push(()=>{clearTimeout(u)}),this.inputMediator.on("disabled",()=>{var p;(p=this.inputMediator)==null||p.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(Hm(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(Hm(!0))}),this.renderSuggestions(t,c),this.subscribe(Ws("inlineSuggestions"),()=>{this.renderSuggestions(t,c)}),this.subscribe(Ws("suggestionsPlacement"),()=>{this.renderSuggestions(t,c)});let f=this.renderOverlays(n);this.unmountHandlers.push(()=>{f.unmount()}),this.store.dispatch(Ud({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),suggestionTextStart:this.inputMediator.getSuggestionTextStart()})),this.store.dispatch(Vd(this.inputMediator.getSelection())),this.store.dispatch(Hm(this.inputMediator.isFocused)),this.unmountHandlers.push(()=>{this.state.input.text!==""&&this.storeMetrics()}),this.whenConversationLoaded(()=>{this.restoreMetrics(),this.syncInputMediator(),this.refreshTextSuggestions(),this.promptForNickname()}),this.isMounted=!0}promptForNickname(t){if(this.nicknameDialogUnsubscribe||this.nicknameDialogFailed)return;let n=this.createContainer("nickname-dialog",document.body);document.body.appendChild(n);let r=(0,Oo.createRoot)(n),o=null,s=a=>{o=a,i()},i=()=>{r==null||r.render((0,Re.jsx)(Ro,{store:this.store,children:(0,Re.jsx)(ro,{broadcastEvents:this.broadcastEvents,children:(0,Re.jsx)(LI,{id:"deepdesk-nickname-dialog",error:o,onSave:a=>M(this,null,function*(){try{yield this.store.dispatch(yE({agentNickname:a})).unwrap(),console.log("setAgentNickname",a),this.broadcastEvents.send(jd,{showNicknameDialog:!1}),this.nicknameDialogUnsubscribe&&this.nicknameDialogUnsubscribe()}catch(l){J.error("Error setting agent nickname",l),s("error"),this.nicknameDialogFailed=!0}})})})}))};i(),this.nicknameDialogUnsubscribe=()=>{r.unmount(),n.remove(),this.nicknameDialogUnsubscribe=null}}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,s;(t=this.inlineSuggestions)==null||t.unmount(),(n=this.aboveSuggestions)==null||n.unmount(),(r=this.belowSuggestions)==null||r.unmount(),(o=this.floatingMenu)==null||o.unmount(),this.unmountHandlers.forEach(i=>i()),this.unmountHandlers=[],(s=this.inputMediator)==null||s.dispose(),this.nicknameDialogUnsubscribe&&this.nicknameDialogUnsubscribe(),this.isMounted=!1}dispose(){this.unmount(),this.unmountWidget(),this.disposeHandlers.forEach(t=>t()),this.disposeHandlers=[],this.off()}renderSuggestions(t,n){var r,o,s,i;(r=this.floatingMenu)==null||r.unmount(),(o=this.inlineSuggestions)==null||o.unmount(),(s=this.aboveSuggestions)==null||s.unmount(),(i=this.belowSuggestions)==null||i.unmount(),this.settings.floatingMenu&&(this.floatingMenu=this.renderFloatingMenu(t,n)),this.settings.inlineSuggestions||this.settings.suggestionsPlacement==="inline"?this.inlineSuggestions=this.renderInlineSuggestions(t,n):this.settings.suggestionsPlacement==="below"?this.belowSuggestions=this.renderAboveOrBelowSuggestions(t,n,"below"):this.aboveSuggestions=this.renderAboveOrBelowSuggestions(t,n,"above")}renderInlineSuggestions(t,n){let{customStyles:r}=n,o=this.createInlineContainer(t,"deepdesk-caret"),s=(0,Oo.createRoot)(o);s.render((0,Re.jsx)(Ro,{store:this.store,customStyles:r,children:(0,Re.jsx)(ro,{broadcastEvents:this.broadcastEvents,children:(0,Re.jsx)(_I,{})})}));let i=a=>{a?(o.style.display="block",o.style.top=`${a.top}px`,o.style.left=`${a.left}px`):o.style.display="none"};return this.inputMediator.on("caretposition",i),{unmount:()=>{var a;(a=this.inputMediator)==null||a.off("caretposition",i),s.unmount(),o.remove()}}}renderAboveOrBelowSuggestions(t,n,r){let{customStyles:o,closestScrollSelector:s,appendOverlayTo:i}=n,a=s&&xx(t,s)||void 0,[l,c]=this.overlayContainerFactory("deepdesk-tab-completion",a||t,{appendTo:i,closestScrollElement:a,mirrorOverflow:!0,onRemove:()=>this.unmount()},o==null?void 0:o.rootNode),[u,f]=this.overlayContainerFactory("deepdesk-suggestions-overlay",a||t,{appendTo:i,placement:r},o==null?void 0:o.suggestionsRootNode),d=(0,Oo.createRoot)(l);d.render((0,Re.jsx)(Ro,{store:this.store,customStyles:o,children:(0,Re.jsx)(ro,{broadcastEvents:this.broadcastEvents,children:(0,Re.jsx)(o_,{inputElement:t})})}));let p=(0,Oo.createRoot)(u);return p.render((0,Re.jsx)(Ro,{store:this.store,customStyles:o,children:(0,Re.jsx)(ro,{broadcastEvents:this.broadcastEvents,children:(0,Re.jsx)(VI,{onLogIn:()=>this.loginViaPopup().catch(h=>J.warn(h.message))})})})),{unmount(){d.unmount(),p.unmount(),c(),f()}}}renderFloatingMenu(t,n){let{customStyles:r,closestScrollSelector:o,appendOverlayTo:s,floatingMenuParent:i}=n,a=o&&xx(t,o)||void 0,[l,c]=this.overlayContainerFactory("floating-menu",a||t,{appendTo:i!=null?i:s},r==null?void 0:r.floatingMenuParent),u=(0,Oo.createRoot)(l);return u.render((0,Re.jsx)(Ro,{store:this.store,customStyles:r,children:(0,Re.jsx)(ro,{broadcastEvents:this.broadcastEvents,children:(0,Re.jsx)(mI,{onLogIn:()=>this.loginViaPopup().catch(f=>J.warn(f.message))})})})),{unmount(){u.unmount(),c()}}}renderOverlays(t){let{customStyles:n}=t,r=this.createContainer("deepdesk-overlays"),o=(0,Oo.createRoot)(r);return o.render((0,Re.jsx)(Ro,{store:this.store,customStyles:n,children:(0,Re.jsx)(ro,{broadcastEvents:this.broadcastEvents,children:(0,Re.jsx)(cI,{})})})),{unmount(){o.unmount(),r.remove()}}}renderWidget(t,n={}){if(this.widgetElement&&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:s,signInViaPopup:i,ssoUrl:a,openAdminFeedback:l}=n;this.widgetElement=t,this.configure({showImages:o,isEmbedded:s,signInViaPopup:i});let c;if(a)try{c={url:new URL(a,this.settings.adminUrl).toString()}}catch(u){J.warn(`Invalid ssoUrl '${a}' passed to renderWidget`)}this.widgetRoot=(0,Oo.createRoot)(t),this.widgetRoot.render((0,Re.jsx)(Ro,{store:this.store,customStyles:r,children:(0,Re.jsx)(ro,{broadcastEvents:this.broadcastEvents,children:(0,Re.jsx)(Sm,{report:u=>this.deepdeskApi.sendEvent(rA,{data:u}),children:(0,Re.jsx)(I_,{assistantOptions:n.assistantOptions,knowledgeAssistOptions:n.knowledgeAssist,openAdminFeedback:l,onLogIn:()=>this.loginViaPopup(c).catch(u=>J.warn(u.message))})})})}))}unmountWidget(){var t,n;(n=(t=this.widgetRoot)==null?void 0:t.unmount)==null||n.call(t),this.widgetRoot=null,this.widgetElement=null}renderKnowledgeAssistantWidget(t,n,r={}){let{customStyles:o,initialQuestion:s}=r,i=(0,Oo.createRoot)(n);return i.render((0,Re.jsx)(Ro,{store:this.store,customStyles:o,children:(0,Re.jsx)(ro,{broadcastEvents:this.broadcastEvents,children:(0,Re.jsx)(px,{children:(0,Re.jsxs)(gm,{assistantCode:t,initialQuestion:s,evaluateKnowledgeAssistFn:Gl,children:[(0,Re.jsx)($i,{children:(0,Re.jsx)(ym,{title:r.title,emptyState:r.emptyState})}),(0,Re.jsx)(fx,{children:(0,Re.jsx)(hm,{})})]})})})})),{unmount(){i.unmount()}}}setupHandlingTime(t){let n=xg(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){vm(t)&&t.message==="Unauthorized"&&this.login()}getConversationProfileKey(t){var n;if(t!=null&&t.id)return`${t.id}:${(n=t.profileCode)!=null?n:""}`}getProfileLoadKey(){var n;let t=this.state.conversation.current;return t!=null&&t.profileCode&&(n=this.getConversationProfileKey(t))!=null?n:null}isCurrentProfileLoadKey(t){return this.getProfileLoadKey()===t}getConversationLoadedKey(){return this.getConversationProfileKey(this.state.conversation.current)}resetProfileDerivedSettings(){this.store.dispatch(TS()),this.store.dispatch(ql(ay))}syncPersonalCollectionForConversation(t){this.personalCollectionSyncPendingKey=t,this.ensurePersonalCollectionSyncDrain()}ensurePersonalCollectionSyncDrain(){return this.personalCollectionSyncDrainPromise?this.personalCollectionSyncDrainPromise:(this.personalCollectionSyncDrainPromise=this.drainPersonalCollectionSync().finally(()=>{this.personalCollectionSyncDrainPromise=null,this.personalCollectionSyncPendingKey&&this.ensurePersonalCollectionSyncDrain()}),this.personalCollectionSyncDrainPromise)}drainPersonalCollectionSync(){return M(this,null,function*(){for(;this.personalCollectionSyncPendingKey;){let t=this.personalCollectionSyncPendingKey;if(this.personalCollectionSyncPendingKey=null,!this.isCurrentProfileLoadKey(t))continue;let n=this.state.conversation.current,r=n==null?void 0:n.id;if(!(!r||!n.profileCode))try{yield this.deepdeskApi.syncPersonalCollection(r)}catch(o){this.isCurrentProfileLoadKey(t)&&J.warn("Failed to sync personal collection for profile",o)}}})}loadProfileConfig(t=!0){let n=this.getProfileLoadKey();if(!n)return this.loadProfileConfigPromise=null,this.loadProfileConfigPromiseKey=null,this.resetProfileDerivedSettings(),Promise.resolve();let r=this.state.conversation.current,o=tr(this.state);if(o&&o.code!==(r==null?void 0:r.profileCode)&&(this.loadProfileConfigPromise=null,this.loadProfileConfigPromiseKey=null,this.resetProfileDerivedSettings()),this.loadProfileConfigPromise&&this.loadProfileConfigPromiseKey===n)return this.loadProfileConfigPromise;this.loadProfileConfigPromise=null,this.loadProfileConfigPromiseKey=n;let s=Promise.resolve().then(()=>M(this,null,function*(){try{yield this.store.dispatch(ru()).unwrap()}catch(l){if(l===Ya)return this.loadProfileConfigPromise===s&&(this.loadProfileConfigPromise=null,this.loadProfileConfigPromiseKey=null),t&&this.isCurrentProfileLoadKey(n)&&!tr(this.state)?this.loadProfileConfig(!1):void 0;throw l}if(!this.isCurrentProfileLoadKey(n))return;let i=tr(this.state),a=this.state.conversation.current;!i||i.code!==(a==null?void 0:a.profileCode)||(this.store.dispatch(ql({showSearch:i.search,showImageSearch:i.imageSearch,showEntitiesCommand:i.entitiesCommand,showSummaryCommand:!!i.summarizerAssistantNew,showKnowledgeSearch:nM(i),recommendTextSuggestions:i.recommendTextSuggestions})),this.syncPersonalCollectionForConversation(n))})).finally(()=>{this.loadProfileConfigPromise===s&&(tr(this.state)||(this.loadProfileConfigPromise=null,this.loadProfileConfigPromiseKey=null))});return this.loadProfileConfigPromise=s,s}loginViaPopup(t){return M(this,null,function*(){return new Promise((n,r)=>{this.store.dispatch(Od());let o=new MessageChannel,s=o.port1,i=this.settings.adminUrl,a=new URL(t!=null&&t.url?t==null?void 0:t.url:`${i}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let l=!1,c=()=>{u&&!u.closed&&u.close(),window.removeEventListener("message",f),clearInterval(d)};s.onmessage=p=>M(this,null,function*(){var h,y;if((h=p.data)!=null&&h.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((y=p.data)==null?void 0:y.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(Il),l=!0,o.port1.close(),n()}catch(S){console.error(S),r(S)}finally{l=!0,c()}});let u=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");if(u===null){r(new Error("Popup blocked by browser"));return}let f=p=>M(this,null,function*(){var h;if(!(p.origin!==a.origin||p.source!==u))switch((h=p.data)==null?void 0:h.type){case"deepdesk-popup-request-origin":{try{let y=JSON.stringify({type:"deepdesk-popup-parent-origin"});u.postMessage(y,a.origin)}catch(y){J.error("Error posting message to popup",y),r(y)}break}case"deepdesk-popup-loaded":{try{let y=JSON.stringify({type:"deepdesk-popup-create-channel"});u.postMessage(y,a.origin,[o.port2])}catch(y){J.error("Error posting message to popup",y),r(y)}break}case"deepdesk-popup-error":{if(c(),p.data.message==="Platform account url mismatch"){let y="Please contact your administrator: The page that opened the popup is not a trusted origin.";J.warn(y),this.store.dispatch(xh(y)),r(new Error(y));return}if(p.data.message==="Timeout"){let y="Please contact your administrator: Popup timed out. Check if the account's platform.url or account.url is configured correctly.";J.warn(y),this.store.dispatch(xh(y)),r(new Error(y));return}r(new Error(p.data.message));break}}});window.addEventListener("message",f);let d=setInterval(()=>{u&&!u.closed||(c(),l||r(new Error("Popup closed by user")))},200);this.disposeHandlers.push(c)})})}translateMessages(t){return this.deepdeskApi.translateMessages(t)}refreshTextSuggestions(){return M(this,null,function*(){this.isMounted&&(yield this.store.dispatch(Dm()))})}refreshWidgetSuggestions(){return M(this,null,function*(){if(!this.widgetRoot)return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=ou(this.state);try{n.forEach(({type:r})=>{switch(r){case"entities":this.store.dispatch(Er());break;case"pinned-messages":case"sticky-messages":break;default:cd.includes(r)||this.store.dispatch(Cr(r))}})}catch(r){this.handleError(r)}})}};cl.version="19.6.2-beta.14",cl.count=0;var Du=cl;function A9(e){return M(this,null,function*(){var o,s,i;let n=yield((o=e.fetch)!=null?o:window.fetch)(e.url),r=yield n.blob();return new File([r],e.name,{type:(i=(s=e.mimeType)!=null?s:n.headers.get("Content-Type"))!=null?i:"image/jpeg"})})}function gM(e,t){return M(this,null,function*(){let n=yield A9(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 hM(e,t,n){return M(this,null,function*(){yield new Lo(e).authenticateWithKey(t,n)})}function yM(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function vM(r,o){return M(this,arguments,function*(e,t,n={}){var f,d;let{value:s}=e,{start:i,end:a}=(f=n.replace)!=null?f:{start:0,end:s.length},l=`${s.slice(0,i)}${t}${s.slice(a)}`,c=(d=n.selectionAfter)!=null?d:{start:i+t.length,end:i+t.length},u=()=>{if(n.setValue)return n.setValue(l);e.value=l};return Promise.resolve(u()).then(()=>{e.selectionStart=c.start,e.selectionEnd=c.end,e.blur(),e.focus()})})}function SM(r,o){return M(this,arguments,function*(e,t,n={}){let s=n.replace?Ts(e,n.replace.start,n.replace.end):il(e),i,a=()=>{if(n.setRange)return n.setRange(s.cloneRange());s.deleteContents(),i=document.createElement("span"),s.insertNode(i),n.insertBRs!==!1?t.split(`
|
|
84
84
|
`).reverse().forEach((l,c)=>{c>0&&s.insertNode(document.createElement("br")),s.insertNode(document.createTextNode(l))}):s.insertNode(document.createTextNode(t))};return Promise.resolve(a()).then(()=>{try{if(n.selectionAfter!==!1){e.focus();let l=n.selectionAfter?Ts(e,n.selectionAfter.start,n.selectionAfter.end):(s.collapse(!1),s),c=window.getSelection();c==null||c.removeAllRanges(),c==null||c.addRange(l)}if(!i)return;i.scrollIntoView&&i.scrollIntoView({block:"nearest",inline:"nearest"})}finally{i&&i.remove()}})})}function I9(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 _9(e){let t=document.createDocumentFragment();return e.split(`
|
|
85
85
|
`).forEach((n,r)=>{r>0&&t.appendChild(document.createElement("br"));let o={index:0},s=0;for(;o=n.slice(s).match(/(\[([^\]]+)])\(([^)]+)\)/);){let i=document.createElement("a");i.href=o[3],i.setAttribute("target","_blank"),i.setAttribute("rel","noopener noreferrer"),i.appendChild(document.createTextNode(o[2])),t.appendChild(document.createTextNode(n.slice(s,s+o.index))),t.appendChild(i),s=s+o.index+o[0].length}t.appendChild(document.createTextNode(n.slice(s)))}),t}function xM(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):xM(n,t)}function wM(o,s){return M(this,arguments,function*(e,t,{isBlock:n,isHTML:r}={}){let i;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,c=l.getSelection();if((!c||c.rangeCount===0)&&(e.focus(),c=l.getSelection()),!c||c.rangeCount===0)return;let u=c.getRangeAt(0);if(!u)return;i=document.createElement("span"),u.insertNode(i);let f=r?I9(t):_9(t);n?xM(u.startContainer,f):(u.insertNode(f),u.collapse(!1))};return Promise.resolve(a()).then(()=>{if(e.dispatchEvent(new InputEvent("input",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0})),e.focus(),!!i)try{i.scrollIntoView&&i.scrollIntoView({block:"nearest",inline:"nearest"})}finally{i&&i.remove()}})})}return $M(M9);})();
|
|
86
86
|
/*! Bundled license information:
|