@deepdesk/deepdesk-sdk 19.5.1-beta.1 → 19.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs.js CHANGED
@@ -1,13 +1,13 @@
1
- "use strict";var yg=Object.create;var to=Object.defineProperty,vg=Object.defineProperties,Sg=Object.getOwnPropertyDescriptor,xg=Object.getOwnPropertyDescriptors,bg=Object.getOwnPropertyNames,ns=Object.getOwnPropertySymbols,Cg=Object.getPrototypeOf,oi=Object.prototype.hasOwnProperty,Ba=Object.prototype.propertyIsEnumerable;var Ha=(t,e,n)=>e in t?to(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,h=(t,e)=>{for(var n in e||(e={}))oi.call(e,n)&&Ha(t,n,e[n]);if(ns)for(var n of ns(e))Ba.call(e,n)&&Ha(t,n,e[n]);return t},b=(t,e)=>vg(t,xg(e));var O=(t,e)=>{var n={};for(var o in t)oi.call(t,o)&&e.indexOf(o)<0&&(n[o]=t[o]);if(t!=null&&ns)for(var o of ns(t))e.indexOf(o)<0&&Ba.call(t,o)&&(n[o]=t[o]);return n};var Z=(t,e)=>{for(var n in e)to(t,n,{get:e[n],enumerable:!0})},Ua=(t,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of bg(e))!oi.call(t,s)&&s!==n&&to(t,s,{get:()=>e[s],enumerable:!(o=Sg(e,s))||o.enumerable});return t};var D=(t,e,n)=>(n=t!=null?yg(Cg(t)):{},Ua(e||!t||!t.__esModule?to(n,"default",{value:t,enumerable:!0}):n,t)),Tg=t=>Ua(to({},"__esModule",{value:!0}),t);var S=(t,e,n)=>new Promise((o,s)=>{var r=d=>{try{a(n.next(d))}catch(l){s(l)}},i=d=>{try{a(n.throw(d))}catch(l){s(l)}},a=d=>d.done?o(d.value):Promise.resolve(d.value).then(r,i);a((n=n.apply(t,e)).next())});var by={};Z(by,{Card:()=>H,ContentEditableInput:()=>vn,DeepdeskAPI:()=>xt,DeepdeskSDK:()=>ts,HTTPClient:()=>xn,InputMediator:()=>St,InputType:()=>$t,KeyboardHint:()=>as,Label:()=>Ga,Locale:()=>oo,Section:()=>ze,SectionList:()=>wn,Sources:()=>Ve,Suggestion:()=>M,SuggestionList:()=>oe,TextAreaInput:()=>Sn,ToggleButton:()=>jt,attachFile:()=>cg,authenticateWithKey:()=>ug,createFullRange:()=>Qn,createOverlayContainer:()=>es,createRangeFromOffsets:()=>Kt,escapeHTML:()=>Un,formatTextMarkup:()=>pg,getRangeOffsets:()=>Jo,getRangeText:()=>Qo,insertCKEditor:()=>hg,isHTML:()=>Ro,isSupportedInputElement:()=>Yr,logEvent:()=>ks,updateContentEditable:()=>mg,updateTextArea:()=>gg,useClickOutsideRoot:()=>Lt,useStyles:()=>C,waitForElementVisibilityChange:()=>ni});module.exports=Tg(by);var ri=D(require("classnames")),we=D(require("react"));var os=D(require("react")),Ka=D(require("classnames"));var no=os.default.createContext({});function C(t,e){let r=(0,os.useContext)(no),{debug:n}=r,s=O(r,["debug"])[t];return Object.entries(e).reduce((i,[a,d])=>{let l=s==null?void 0:s[a];return b(h({},i),{[a]:(0,Ka.default)(d,l,n?`${t}__${a}`:!1)})},{})}var Wa={root:"dd-4s9wq"};var zt=require("react/jsx-runtime"),ss=()=>(0,zt.jsxs)("svg",{className:Wa.root,width:"185",height:"170",viewBox:"0 0 185 170",xmlns:"http://www.w3.org/2000/svg",children:[(0,zt.jsx)("defs",{children:(0,zt.jsx)("style",{children:".cls-1 { fill: #b3b3b3; }"})}),(0,zt.jsx)("title",{children:"Failed loading image"}),(0,zt.jsx)("path",{className:"cls-1",d:"M15 130.896V16.994c0-1.097.898-1.994 2.007-1.994h150.986A2 2 0 0 1 170 16.994v69.147L133.015 51 87.26 120.377l-35.863-17.758L15 130.896zM2 0C.895 0 0 .887 0 2v166c0 1.105.887 2 2 2h181c1.105 0 2-.887 2-2V2c0-1.105-.887-2-2-2H2zm49 72c11.046 0 20-9.178 20-20.5S62.046 31 51 31s-20 9.178-20 20.5S39.954 72 51 72z",fillRule:"evenodd"})]});var si={root:"dd-c9KvZ",imageWrapper:"dd-sE7D9",image:"dd-bEGMz",content:"dd-oFIQa",title:"dd-mSgoo",contentIsCropped:"dd-Uvjv4",lineClamp:"dd-ApQo-"};var Vt=require("react/jsx-runtime"),rs=(0,we.createContext)(si),wg=({title:t,src:e})=>{let n=(0,we.useContext)(rs),[o,s]=(0,we.useState)(!1);return(0,we.useEffect)(()=>{s(!1)},[e]),(0,Vt.jsx)("div",{className:n.imageWrapper,children:e&&!o?(0,Vt.jsx)("img",{className:n.image,alt:t,src:e,onError:()=>s(!0)}):(0,Vt.jsx)(ss,{})})},Eg=({className:t,lineClamp:e=!1,cropText:n=!1,children:o})=>{let s=(0,we.useContext)(rs);return(0,Vt.jsx)("div",{className:(0,ri.default)(s.content,t,{[s.contentIsCropped]:n,[s.lineClamp]:e}),children:o})},kg=r=>{var i=r,{as:t="h1",cropText:e=!1,className:n,children:o}=i,s=O(i,["as","cropText","className","children"]);let a=(0,we.useContext)(rs);return we.default.createElement(t,h({className:(0,ri.default)(a.title,n,{[a.contentIsCropped]:e})},s),o)},is=({children:t})=>{let e=C("Card",si);return(0,Vt.jsx)("div",{className:e.root,children:(0,Vt.jsx)(rs.Provider,{value:e,children:t})})};is.Image=wg;is.Content=Eg;is.Title=kg;var H=is;var Va=D(require("classnames"));var za={root:"dd-llBx9"};var ja=require("react/jsx-runtime");var Rg={"arrow-up":"\u25B2","arrow-down":"\u25BC",tab:"tab",esc:"Esc",enter:"\u21B5"},Pg=o=>{var s=o,{className:t,keyCode:e}=s,n=O(s,["className","keyCode"]);let r=C("KeyboardHint",za);return(0,ja.jsx)("span",h({"data-key":Rg[e],className:(0,Va.default)(t,r.root)},n))},as=Pg;var qa=D(require("classnames"));var $a={root:"dd-e6HXZ"};var Xa=require("react/jsx-runtime"),Ig=o=>{var s=o,{className:t,children:e}=s,n=O(s,["className","children"]);let r=C("Label",$a);return(0,Xa.jsx)("span",b(h({},n),{className:(0,qa.default)(t,r.root),children:e}))},Ga=Ig;var Ja={root:"dd-FiMI7",subTitleContainer:"dd-98jc7",subtitle:"dd-3MnW8",suggestions:"dd-0SGL8"};var Tn=require("react/jsx-runtime"),Ag=s=>{var r=s,{title:t,children:e,type:n}=r,o=O(r,["title","children","type"]);let i=C("Section",Ja);return(0,Tn.jsxs)("section",b(h({},o),{className:i.root,"data-section-type":n,children:[t&&(0,Tn.jsx)("div",{className:i.subTitleContainer,children:(0,Tn.jsx)("span",{className:i.subtitle,children:t})}),(0,Tn.jsx)("div",{className:i.suggestions,children:e})]}))},ze=Ag;var tl=D(require("classnames")),nl=require("react");var Ct=require("react"),Ya=require("react/jsx-runtime"),Qa=(0,Ct.createContext)(null),Za=({scrollContainerRef:t,children:e})=>{let n=(0,Ct.useCallback)(o=>{let s=t.current;if(!s||s.scrollHeight<=s.clientHeight)return;let{top:r}=s.getBoundingClientRect(),{top:i}=o.getBoundingClientRect(),a=s.scrollTop+(i-r);typeof s.scrollTo=="function"?s.scrollTo({top:a}):s.scrollTop=a},[]);return(0,Ya.jsx)(Qa.Provider,{value:n,children:e})},ls=t=>{let e=(0,Ct.useContext)(Qa);(0,Ct.useEffect)(()=>{let n=t.current;n&&e(n)},[])};var el={root:"dd-uoTXh"};var ii=require("react/jsx-runtime"),Lg=({className:t,children:e})=>{let n=C("SectionList",el),o=(0,nl.useRef)(null);return(0,ii.jsx)(Za,{scrollContainerRef:o,children:(0,ii.jsx)("div",{ref:o,className:(0,tl.default)(n.root,t),children:e})})},wn=Lg;var En=D(require("classnames")),me=D(require("react"));var ai={root:"dd-1g-A9",fadein:"dd-McXxq",isClickable:"dd-CTG8E",isSelected:"dd-yhg27",actions:"dd-Nlm6p",actionsIsFixed:"dd-OK-kw",actionButton:"dd-zbXsQ",dropdownList:"dd-AvwWP",dropdownButton:"dd-piaJi",dropdownItem:"dd-qgkTO",dropdownItemButton:"dd-sTE2D",actionButtonIsPrimary:"dd-mhkWS",actionButtonIsDisabled:"dd-0eKLQ",labels:"dd-QKJu6",label:"dd-aMplE",buttonsContainer:"dd-uRYN4",button:"dd-9UE-x",buttonPrimary:"dd-aYDCB",buttonSecondary:"dd--cpPL",buttonWithIcon:"dd-MQVt5",icon:"dd-Jr-ww",buttonDisabled:"dd-agTuH"};var de=require("react/jsx-runtime"),Tt=(0,me.createContext)(ai),Mg=o=>{var s=o,{fixed:t,children:e}=s,n=O(s,["fixed","children"]);let r=(0,me.useContext)(Tt);return(0,de.jsx)("div",b(h({},n),{className:(0,En.default)(r.actions,{[r.actionsIsFixed]:t}),children:e}))};function Ng(d){var l=d,{as:t,className:e,icon:n,title:o,children:s,disabled:r,variant:i}=l,a=O(l,["as","className","icon","title","children","disabled","variant"]);let c=(0,me.useContext)(Tt);return(0,de.jsxs)(t||"button",b(h({type:"button",className:(0,En.default)(c.button,{[c.buttonWithIcon]:n,[c.buttonDisabled]:r,[c.buttonPrimary]:i==="primary",[c.buttonSecondary]:i==="secondary"},e),title:o,"aria-label":o},a),{children:[n&&(0,de.jsx)("span",{className:c.icon,children:n}),s]}))}var Og=({children:t})=>{let e=(0,me.useContext)(Tt);return(0,de.jsx)("div",{className:e.buttonsContainer,children:t})},Dg=({className:t,primary:e,disabled:n,label:o,children:s})=>{let r=(0,me.useContext)(Tt);return(0,de.jsxs)("div",{className:(0,En.default)(t,r.actionButton,r.dropdownButton,{[r.actionButtonIsPrimary]:e,[r.actionButtonIsDisabled]:n}),onMouseDown:i=>i.stopPropagation(),onClick:i=>i.stopPropagation(),children:[o,(0,de.jsx)("ul",{className:r.dropdownList,children:s})]})},_g=({index:t,label:e,onClick:n})=>{let o=(0,me.useContext)(Tt);return(0,de.jsx)("li",{className:o.dropdownItem,children:(0,de.jsx)("button",{className:o.dropdownItemButton,type:"button","data-index":t,onClick:n,children:e})})},Fg=({className:t,primary:e,disabled:n,onClick:o,label:s})=>{let r=(0,me.useContext)(Tt);return(0,de.jsx)("button",{type:"button",className:(0,En.default)(t,r.actionButton,{[r.actionButtonIsPrimary]:e,[r.actionButtonIsDisabled]:n}),onClick:o!=null?o:(i=>i.stopPropagation()),disabled:n,"aria-hidden":n,children:s})},Hg=({labels:t})=>{let e=(0,me.useContext)(Tt);return(0,de.jsx)("div",{className:e.labels,children:t.map(n=>(0,de.jsx)("span",{className:e.label,children:n},n))})},wt=me.default.forwardRef((a,i)=>{var d=a,{className:t,selected:e,onClick:n,children:o,as:s="div"}=d,r=O(d,["className","selected","onClick","children","as"]);let l=C("Suggestion",ai),c=(0,me.useCallback)(p=>{p.preventDefault(),n&&n(p)},[n]);return(0,de.jsx)(s,b(h({},r),{ref:i,className:(0,En.default)(t,l.root,{[l.isSelected]:e,[l.isClickable]:!!n}),onClick:c,children:(0,de.jsx)(Tt.Provider,{value:l,children:o})}))});wt.Labels=Hg;wt.Actions=Mg;wt.ActionButton=Fg;wt.DropdownButton=Dg;wt.DropdownItem=_g;wt.ButtonsContainer=Og;wt.Button=Ng;var M=wt;var sl=D(require("classnames"));var ol={root:"dd-W35K-",isWithDivider:"dd-sscOy"};var rl=require("react/jsx-runtime"),Bg=({withDivider:t,children:e})=>{let n=C("SuggestionList",ol);return(0,rl.jsx)("div",{"data-testid":"suggestions-overlay-list",className:(0,sl.default)(n.root,{[n.isWithDivider]:t}),children:e})},oe=Bg;var al=D(require("classnames"));var il={root:"dd-oWarc",isCollapsed:"dd-tfZI0"};var ds=require("react/jsx-runtime"),Ug=({className:t,isCollapsed:e,title:n,onClick:o})=>{let s=C("ToggleButton",il);return(0,ds.jsx)("button",{type:"button",className:(0,al.default)(s.root,t,{[s.isCollapsed]:e}),onClick:o,title:n,children:(0,ds.jsx)("svg",{width:"14",height:"8",viewBox:"-2.5 -5 75 60",preserveAspectRatio:"none",children:(0,ds.jsx)("path",{d:"M0,0 l35,50 l35,-50",fill:"none",stroke:"grey",strokeLinecap:"round",strokeWidth:"6"})})})},jt=Ug;var ll=/(?:[.,;:!?\\n]|:\\)|:\\(|:-\\)|:-\\()/g,cs=/(((\$!\{)|(\{))[a-zA-Z0-9_.]+\})/g;var dl=/x-deepdesk-(([a-z0-9\-_])+-version)/,us=["cues","custom-data","custom-data-banner","knowledge-assist"],cl=Intl.DateTimeFormat().resolvedOptions().timeZone,Ve=(y=>(y.SEARCH="search",y.TEMPLATE="template",y.ELASTIC_SEARCH="search-autocomplete",y.GPT="gpt",y.TRIE="trie",y.TRIE_WITH_TYPOS="trie-with-typos",y.SEMANTIC="semantic",y.TEXT_RECOMMENDATION="text_recommendation",y.URL_RECOMMENDATION="url_recommendation",y.LINK_RECOMMENDATION="link_recommendation",y.PERSONAL_COLLECTION="personal-collection",y.PERSONAL_COLLECTION_SEARCH="personal-collection-search",y.SEARCH_OVERLAY="search-overlay",y.SEARCH_PREVIEW="search-preview",y.SEARCH_URL="search-url",y.STYLE="style",y))(Ve||{}),$t=(i=>(i.ENTER="enter",i.TAB="tab",i.ARROW="arrow",i.HOTKEY="hotkey",i.MOUSE="mouse",i.SPACE="space",i))($t||{});var G=require("react"),Js=require("react-redux");var Et=require("@reduxjs/toolkit");var oo=(n=>(n.NL_NL="nl-NL",n.EN_US="en-US",n))(oo||{});var Kg={isLoggedIn:null,loginFetchState:"idle",verifyFetchState:"idle",showLoginOverlay:!1,loginError:null},se=t=>t.auth.isLoggedIn;var ul=t=>t.auth.verifyFetchState,pl=t=>t.auth.showLoginOverlay,gl=t=>t.auth.loginError,st=(0,Et.createAsyncThunk)("auth/validate",(t,e)=>S(null,null,function*(){return e.extra.deepdeskAPI.isLoggedIn()})),ml=(0,Et.createAsyncThunk)("auth/requestLogin",(n,o)=>S(null,[n,o],function*({email:t},e){let{deepdeskAPI:s}=e.extra;return s.requestLoginByEmail(t)})),li=(0,Et.createAsyncThunk)("auth/loginWithPassword",(o,s)=>S(null,[o,s],function*({username:t,password:e},n){let{deepdeskAPI:r}=n.extra;return r.loginWithPassword(t,e)})),ps=(0,Et.createAsyncThunk)("auth/logout",(t,e)=>S(null,null,function*(){let{deepdeskAPI:n}=e.extra;yield n.logout()})),so=(0,Et.createAsyncThunk)("auth/verifyLoginToken",(n,o)=>S(null,[n,o],function*({token:t},e){let{deepdeskAPI:s}=e.extra;return s.verifyLoginToken(t)})),fl=(0,Et.createSlice)({name:"auth",initialState:Kg,reducers:{setIsLoggedIn(t,e){t.isLoggedIn=e.payload},setShowLoginOverlay(t,e){t.showLoginOverlay=e.payload},setLoginError(t,e){t.loginError=e.payload},clearLoginError(t){t.loginError=null}},extraReducers:t=>{t.addCase(st.pending,e=>{e.loginFetchState="loading"}),t.addCase(st.fulfilled,(e,{payload:n})=>{e.isLoggedIn=n,e.loginFetchState="done"}),t.addCase(st.rejected,e=>{e.loginFetchState="error",e.isLoggedIn=!1}),t.addCase(li.pending,e=>{e.loginFetchState="loading",e.loginError=null}),t.addCase(li.fulfilled,e=>{e.isLoggedIn=!0,e.loginFetchState="done",e.loginError=null,e.showLoginOverlay=!1}),t.addCase(li.rejected,(e,n)=>{e.loginFetchState="error",e.isLoggedIn=!1,e.loginError=n.error.message==="Bad Request"?"Invalid credentials":"Login failed"}),t.addCase(ps.fulfilled,e=>{e.isLoggedIn=!1,e.loginFetchState="idle",e.loginError=null}),t.addCase(ps.rejected,e=>{e.isLoggedIn=!1,e.loginFetchState="error"}),t.addCase(so.pending,e=>{e.verifyFetchState="loading"}),t.addCase(so.rejected,e=>{e.verifyFetchState="error"}),t.addCase(so.fulfilled,(e,n)=>{n.payload.isLoggedIn?e.verifyFetchState="done":e.verifyFetchState="error"})}}),{setIsLoggedIn:kn,setShowLoginOverlay:hl,setLoginError:di,clearLoginError:gs}=fl.actions,yl=fl.reducer;var Gt=require("@reduxjs/toolkit"),Tl=require("diff");function vl(t){return typeof t=="object"&&!Array.isArray(t)&&t!==null}function kt(t,e,n=10){let o=typeof t,s=typeof e;if(n===0)throw new Error("Max depth deepEqual, possible circular references?");return o!==s?!1:t==null||o==="string"||o==="number"||o==="boolean"?t===e:Array.isArray(t)&&Array.isArray(e)?t.length!==e.length?!1:t.every((r,i)=>kt(r,e[i],n-1)):vl(t)&&vl(e)?Object.keys(t).length!==Object.keys(e).length?!1:Object.keys(t).every(i=>kt(t[i],e[i],n-1)):!1}function Wg(t){return Math.max(...t.map(e=>e.length))}function zg(t,e){let n=t.reduce((o,s)=>{if(s){let r=o[s]?o[s]+1:1;return b(h({},o),{[s]:r})}return o},{});return Object.keys(n).reduce((o,s)=>(n[s]<e&&o.push(s),o),[])}function Sl(t,e){let o=[...t.map(({text:s})=>s.split(/\b(\w+)\b/))];for(let s=0;s<Wg(o);s++){let r=zg(o.map(a=>a[s]),e),i=o.filter(a=>!r.includes(a[s]));if(i.length>=e)o=i;else return{text:o[0].slice(0,s).join("").replace(/ (\?| |!|\.|,|\n)/g,"$1").trimEnd(),source:"mixed"}}}var Vg=2;function xl(t,e=""){if(t.length===0)return;if(t.length===1)return t[0];let n=Sl(t,Vg);return n&&n.text!==e?n:t[0]}var Oe=require("@reduxjs/toolkit");var jg={info(...t){console.info("[Deepdesk]",...t)},warn(...t){console.warn("[Deepdesk]",...t)},error(...t){console.error("[Deepdesk]",...t)}},k=jg;var bl={current:null,isSupported:null},Y=(0,Oe.createAction)("resetConversation"),ms=t=>{let{current:e}=t.conversation;return(e==null?void 0:e.externalId)||null},je=t=>{let{current:e}=t.conversation;return(e==null?void 0:e.id)||null},Rn=t=>t.conversation.isSupported,ci=(0,Oe.createAsyncThunk)("conversation/isSupported",(t,e)=>{let{deepdeskAPI:n}=e.extra;return n.isConversationSupported(t.externalId,t.options)}),fs=(0,Oe.createAsyncThunk)("conversation/create",(t,e)=>{let{deepdeskAPI:n}=e.extra;return n.createConversation(t)}),hs=(0,Oe.createAsyncThunk)("conversation/byExternalId",(t,e)=>{let{deepdeskAPI:n}=e.extra;return n.getConversationByExternalId(t.externalId,t.options)}),ys=(0,Oe.createAsyncThunk)("conversation/update",(t,e)=>{let{deepdeskAPI:n}=e.extra,o=je(e.getState());if(!o)throw new Error("No current conversation to update");return n.updateConversation(o,t)}),ui=(0,Oe.createAsyncThunk)("conversation/upsert",(t,e)=>{let{deepdeskAPI:n}=e.extra;return n.upsertConversation(t)}),pi=(0,Oe.createAsyncThunk)("conversation/postMessages",(t,e)=>{let{deepdeskAPI:n}=e.extra,o=je(e.getState());if(!o)throw new Error("No current conversation to update messages");return n.postMessages(o,t.map(s=>h({},s)))}),$g=[fs.rejected,hs.rejected,ys.rejected,pi.rejected].map(t=>t==null?void 0:t.toString());function qg(t){return $g.includes(t.type)}var Gg=(0,Oe.createSlice)({name:"conversation",initialState:bl,reducers:{},extraReducers:t=>{t.addCase(ci.fulfilled,(e,n)=>{e.isSupported=n.payload}).addCase(fs.fulfilled,(e,n)=>{var o;e.current=n.payload,e.isSupported=!!((o=n.payload)!=null&&o.profileCode)}).addCase(hs.fulfilled,(e,n)=>{var o;e.current=n.payload,e.isSupported=!!((o=n.payload)!=null&&o.profileCode)}).addCase(ui.fulfilled,(e,n)=>{var o;e.current=n.payload,e.isSupported=!!((o=n.payload)!=null&&o.profileCode)}).addCase(ys.fulfilled,(e,n)=>{var o;e.current=n.payload,e.isSupported=!!((o=n.payload)!=null&&o.profileCode)}).addCase(Y,()=>bl).addMatcher(qg,(e,n)=>{var o;throw k.info("Conversation action rejected",n.type,((o=n.error)==null?void 0:o.message)||"No message"),new Error(n.error.message)})}}),Cl=Gg.reducer;var qt={text:"",html:null,suggestionTextStart:0,selection:{start:0,end:0},beforeInputChange:null,mixedSuggestion:null,textSuggestions:[],pinnedSuggestions:[],selectedSuggestionIndex:-1,metrics:{numCharsTyped:0,numCharsPasted:0,numCharsCut:0,numCharsDeleted:0,numPaste:0,agentStartedTypingTimestamp:null,externalTimeTotalSeconds:null,pastes:[],deletions:[],offeredTextSuggestions:[],textSuggestions:[],cuts:[]}};function gi(t){let{key:e,shiftKey:n,ctrlKey:o,metaKey:s,altKey:r}=t;return{key:e,shiftKey:n,ctrlKey:o,metaKey:s,altKey:r}}var vs=(0,Gt.createAction)("input/applyImageSuggestion"),wl=(0,Gt.createSlice)({name:"input",initialState:qt,reducers:{setInput(t,e){var i,a;let{beforeInputChange:n}=t,{text:o,html:s,suggestionTextStart:r}=e.payload;if(t.text=o,t.html=s!=null?s:null,t.suggestionTextStart=o===""?0:Math.max(0,r!=null?r:0),o==="")t.metrics=qt.metrics,t.textSuggestions=[],t.mixedSuggestion=null;else if(n!==null&&t.text!==n.text){let{key:d,shiftKey:l,ctrlKey:c,metaKey:p,altKey:u}=n.keyDown;switch(d){case"Enter":l&&(t.metrics.numCharsTyped+=1);break;case"Backspace":case"Delete":{let{text:g}=t,m=(0,Tl.diffChars)(n.text,g);n.text.length-g.length>1&&t.metrics.deletions.push(...m.filter(f=>f.removed).map(f=>f.value)),t.metrics.numCharsDeleted+=n.text.length-g.length;break}case"Shift":case"Meta":case"Tab":break;case"C":case"V":case"X":case"c":case"v":case"x":if(c||p)break;default:if(!c&&!p&&!u){t.metrics.numCharsTyped+=1;let g=((i=n.selection)==null?void 0:i.start)!==void 0&&((a=n.selection)==null?void 0:a.end)!==void 0?n.text.substring(n.selection.start,n.selection.end):null;g&&g.length>0&&(t.metrics.numCharsDeleted+=g.length,t.metrics.deletions.push(g))}}t.metrics.agentStartedTypingTimestamp||(t.metrics.agentStartedTypingTimestamp=Date.now())}t.beforeInputChange=null},sendMessage(t,e){t.pinnedSuggestions=t.pinnedSuggestions.filter(n=>!t.metrics.textSuggestions.some(o=>o.text===n.text&&o.source===n.source))},setSelection(t,e){e.payload!==null&&(kt(t.selection,e.payload)||(t.selection=e.payload))},commitSuggestion(t,e){let n=e.payload,{text:o,suggestion:{source:s,abVariant:r,abTestName:i,trainingJobs:a,sourceText:d,searchTerm:l,assistantCode:c,text:p},eventMetrics:{inputType:u},replace:g}=n,m=s==="search"||s==="personal-collection-search",f=o.slice(t.text.substring(0,t.selection.start).length);(m||g==="selection")&&(f=o),n.suggestion.source==="search-overlay"&&(f=p),t.metrics.textSuggestions.push({text:f,source:s,assistantCode:c,abVariant:r,abTestName:i,inputType:u,sourceText:d,trainingJobs:a||[],searchTerm:m?t.text:l}),t.textSuggestions=[],t.selectedSuggestionIndex=-1},offeredTextSuggestion(t,e){let{text:n,suggestion:{source:o}}=e.payload;t.metrics.offeredTextSuggestions.find(r=>r.text===n)||t.metrics.offeredTextSuggestions.push({text:n,source:o})},registerKeyDown(t,e){let{key:n}=e.payload;["Control","Meta","Shift","Alt"].includes(n)||(t.beforeInputChange={text:t.text,selection:t.selection,keyDown:e.payload})},registerKeyUp(t,e){},registerCut(t,e){let{metrics:n}=t,o=e.payload;t.metrics=b(h({},t.metrics),{numCharsCut:n.numCharsCut+o.length,cuts:[...n.cuts,o]})},registerPaste(t,e){let{metrics:n}=t,{text:o,selectionText:s}=e.payload,r=n.numCharsDeleted+(s!=null&&s.length?s.length:0),i=s!=null&&s.length?[...n.deletions,s]:n.deletions;t.metrics=b(h({},t.metrics),{numCharsDeleted:r,deletions:i,numCharsPasted:n.numCharsPasted+o.length,numPaste:n.numPaste+1,pastes:[...n.pastes,o]})},selectNextTextSuggestion(t){let e=t.textSuggestions.length+t.pinnedSuggestions.length;t.selectedSuggestionIndex=t.selectedSuggestionIndex<e-1?t.selectedSuggestionIndex+1:t.selectedSuggestionIndex},selectPreviousTextSuggestion(t){t.selectedSuggestionIndex=t.selectedSuggestionIndex>=0?t.selectedSuggestionIndex-1:t.selectedSuggestionIndex},selectTextSuggestionByIndex(t,e){t.selectedSuggestionIndex=e.payload},setTextSuggestions(t,e){if(t.selectedSuggestionIndex=-1,t.textSuggestions=e.payload,e.payload.length===0){t.mixedSuggestion=null;return}let n=Xt({input:t}),o=xl(e.payload,n);t.mixedSuggestion=o!=null&&o.text.includes(n)?o:null},setPinnedSuggestions(t,e){t.pinnedSuggestions=e.payload},removePinnedSuggestions(t,e){t.pinnedSuggestions=t.pinnedSuggestions.filter(o=>o.source!==e.payload.source||e.payload.assistantCode&&o.assistantCode!==e.payload.assistantCode?!0:e.payload.text?o.text!==e.payload.text:!1);let n=t.textSuggestions.length+t.pinnedSuggestions.length;t.selectedSuggestionIndex>n-1&&(t.selectedSuggestionIndex=-1)},setMetrics(t,{payload:e}){t.metrics=e},resetMetrics(t){t.metrics=qt.metrics}},extraReducers:t=>{t.addCase(Y,e=>{e.mixedSuggestion=qt.mixedSuggestion,e.textSuggestions=qt.textSuggestions,e.selectedSuggestionIndex=qt.selectedSuggestionIndex,e.metrics=qt.metrics})}}),Xt=t=>{let{text:e,selection:n,suggestionTextStart:o}=t.input;return e.slice(o,n.end)},Xg=t=>t.input.mixedSuggestion,Jg=t=>t.input.pinnedSuggestions,Qg=t=>t.input.textSuggestions,ro=t=>t.input.selectedSuggestionIndex,Jt=(0,Gt.createSelector)([Qg,Jg],(t,e)=>[...t,...e]),Pn=(0,Gt.createSelector)([Jt,Xg,ro],(t,e,n)=>n>-1?t[n]:e),El=t=>t.input.selection,{commitSuggestion:Se,offeredTextSuggestion:kl,registerCut:Rl,registerKeyDown:Pl,registerKeyUp:Il,registerPaste:Al,selectNextTextSuggestion:Ll,selectPreviousTextSuggestion:Ml,selectTextSuggestionByIndex:Ss,setInput:xs,setMetrics:Nl,setPinnedSuggestions:In,removePinnedSuggestions:Qt,setSelection:bs,setTextSuggestions:Rt,resetMetrics:Ol,sendMessage:Zt}=wl.actions,Dl=wl.reducer;var Ln=require("@reduxjs/toolkit");var Yt=require("@reduxjs/toolkit");function _l(t){try{return Intl.DateTimeFormat(void 0,{timeZone:t}),!0}catch(e){return!1}}var Zg={agentInfo:void 0,agentSettings:{},visitorInfo:void 0,customData:void 0,platformVariables:void 0,fetchState:"idle",showNicknameDialog:!1},An=t=>{var e;return(e=t.info.agentInfo)!=null?e:null},Fl=t=>{var e;return(e=t.info.visitorInfo)!=null?e:null},Hl=t=>{var e;return(e=t.info.customData)!=null?e:null},ao=({info:{visitorInfo:t,agentInfo:e}})=>{var n,o;return{timezone:t!=null&&t.visitorTimeZone&&_l(t.visitorTimeZone)?t.visitorTimeZone:cl,agentName:(n=e==null?void 0:e.agentNickname)!=null?n:"",visitorName:(o=t==null?void 0:t.visitorName)!=null?o:""}},Yg=[["agentNickname","nickname"],["agentDefaultLocale","defaultLocale"],["agentEmail","email"]],Bl=(0,Yt.createAsyncThunk)("info/setAgentNickname",(n,o)=>S(null,[n,o],function*({agentNickname:t},e){var i;let{deepdeskAPI:s}=e.extra,r=yield s.patchMe({nickname:t});return{agentNickname:(i=r==null?void 0:r.nickname)!=null?i:t}})),io=(0,Yt.createAsyncThunk)("info/setAgentInfo",(t,e)=>S(null,null,function*(){var r,i,a;let{deepdeskAPI:n}=e.extra,o=yield n.getMe(),s=[];if(t.agentId&&t.skipSync!==!0&&s.push(n.postIdentity({externalId:t.agentId})),t.skipSync!==!0){let d=Yg.reduce((l,[c,p])=>!o[p]&&c in t?b(h({},l),{[p]:t[c]}):l,{});Object.keys(d).length>0&&s.push(n.patchMe(d).then(l=>o=l))}return s.length>0&&(yield Promise.all(s)),{agentId:t.agentId,agentName:t.agentName,agentNickname:(r=o.nickname)!=null?r:t.agentNickname,agentEmail:(i=o.email)!=null?i:t.agentEmail,agentDefaultLocale:(a=o.defaultLocale)!=null?a:t.agentDefaultLocale,agentTimeZone:t.agentTimeZone}})),mi=(0,Yt.createAsyncThunk)("info/setAgentSettings",(t,e)=>S(null,null,function*(){let{deepdeskAPI:n}=e.extra,o=yield n.getMe(),s=h(h({},typeof o.uiConfig=="object"?o.uiConfig:{}),t);return yield n.patchMe({uiConfig:s}),s})),fi=(0,Yt.createAsyncThunk)("info/getAgentSettings",(t,e)=>S(null,null,function*(){let{deepdeskAPI:n}=e.extra;return(yield n.getMe()).uiConfig})),Ul=(0,Yt.createSlice)({name:"info",initialState:Zg,reducers:{setVisitorInfo(t,e){t.visitorInfo=h(h({},t.visitorInfo),e.payload)},setCustomData(t,e){t.customData=e.payload},setPlatformVariables(t,e){t.platformVariables=e.payload},setShowNicknameDialog(t,e){t.showNicknameDialog=e.payload}},extraReducers:t=>{t.addCase(io.pending,(e,n)=>{e.fetchState="loading",e.agentInfo=h(h({},e.agentInfo),n.meta.arg)}).addCase(io.rejected,e=>{e.fetchState="error"}).addCase(io.fulfilled,(e,n)=>{e.fetchState="done",e.agentInfo=n.payload}).addCase(mi.fulfilled,(e,n)=>{e.agentSettings=n.payload}).addCase(fi.fulfilled,(e,n)=>{e.agentSettings=n.payload}).addCase(Y,e=>{e.visitorInfo=void 0})}}),{setVisitorInfo:Kl,setCustomData:Wl,setPlatformVariables:zl,setShowNicknameDialog:Vl}=Ul.actions,jl=Ul.reducer;function De(t,e){return e?t==null?(k.warn("replaceVars called with non-string text; upstream contract violation",{keys:Object.keys(e)}),t):Object.entries(e).reduce((n,[o,s])=>n.replaceAll(o,s),t):t}var Cs={list:[],fetchState:"idle",isOpen:!1,page:"search",aggregates:{}},$l=t=>t.search.isOpen,ql=t=>t.search.page,hi=t=>t.search.list,Gl=t=>t.search.aggregates,em=(0,Ln.createSelector)([hi,(t,e)=>e],(t,e)=>t.filter(n=>n.type===e)),Xl=t=>e=>em(e,t),en=(0,Ln.createAsyncThunk)("search/getAll",(t,e)=>S(null,null,function*(){var d;let{deepdeskAPI:n}=e.extra,o=e.getState(),s=(d=o.conversation.current)==null?void 0:d.profileCode,{platformVariables:r}=o.info;if(!s)throw new Error("Profile should be provided in order to be able to search");let{results:i,aggregates:a}=yield n.search({profile:s,query:t.query,tags:t.tags,size:t.size,current:t.current,filters:{type:t.type},params:ao(o)});return{results:i.map(l=>b(h(h({},l),l.title&&r?{title:De(l.title,r)}:{}),{text:De(l.text,r!=null?r:{}),source:`search-${l.type.toLowerCase()}`,searchTerm:t.query})),aggregates:a}})),Jl=(0,Ln.createSlice)({name:"search",initialState:Cs,reducers:{setIsOpen(t,e){t.isOpen=e.payload},setPage(t,e){t.page=e.payload},resetSearch(t){t.fetchState=Cs.fetchState,t.list=Cs.list}},extraReducers:t=>{t.addCase(en.pending,e=>{e.fetchState="loading"}).addCase(en.rejected,(e,n)=>{e.fetchState="error",k.error(n.error)}).addCase(en.fulfilled,(e,n)=>{e.fetchState="done",e.list=n.payload.results,e.aggregates=n.payload.aggregates||{}}).addCase(Y,()=>Cs)}}),{resetSearch:Ts,setIsOpen:_e,setPage:Mn}=Jl.actions,Ql=Jl.reducer;var yi="SetOutputs",Nn="ShowLoginOverlay",lo="UserLoggedIn",tm="UserLoggedOut",rt="ApplySuggestion",vi="ApplyImageSuggestion",nm="ShowCommandPalette",ws="ShowNicknameDialog",Es="ReduxAction",om="RemovePinnedSuggestion",sm=t=>({[yi]:e=>{var s,r;let n=(s=t.getState().conversation.current)==null?void 0:s.externalId,o=(r=e==null?void 0:e.payload)==null?void 0:r.externalConversationId;o&&o!==n||t.dispatch(b(h({},e),{isBroadcasted:!0}))},[Es]:e=>{e.isBroadcasted||t.dispatch(b(h({},e),{isBroadcasted:!0}))},[om]:e=>{t.dispatch(Qt(e))},[nm]:e=>{t.dispatch(_e(e.isOpen)),e.page&&t.dispatch(Mn(e.page))},[ws]:e=>{t.dispatch(Vl(e.showNicknameDialog))},[Nn]:e=>{t.dispatch(hl(e))},[lo]:()=>{t.dispatch(st())},[tm]:()=>{t.dispatch(st())},[vi]:e=>{t.dispatch(vs({suggestion:e.suggestion}))},[rt]:e=>{t.dispatch(Se(b(h({},e),{eventMetrics:{inputType:"mouse"},replace:"selection"})))}}),Zl=sm;var ed=require("react-redux");var Yl=require("@reduxjs/toolkit");function ks(t){return(0,Yl.createAsyncThunk)("analytics/logEvent",(e,n)=>{var r,i,a;let o=(i=(r=n.getState())==null?void 0:r.conversation.current)==null?void 0:i.id,s=(a=n.getState())==null?void 0:a.info.agentInfo;return n.extra.deepdeskAPI.sendEvent(e.name,b(h({conversationId:o},s),{data:e.data}))})(t)}function q(){let t=(0,ed.useDispatch)();return(e,n)=>S(null,null,function*(){yield t(ks({name:e,data:n}))})}var On=require("react"),td=require("react-redux");function Rs(t,e){let n=(0,On.useRef)(t);n.current=t;let[o,s]=(0,On.useState)(void 0),[r,i]=(0,On.useState)(void 0),[a,d]=(0,On.useState)("idle"),l=(0,td.useDispatch)();return{error:r,state:a,data:o,call:u=>S(null,null,function*(){d("loading"),yield l(n.current(u)).unwrap().then(g=>{s(g),d("done"),e!=null&&e.onSuccess&&(e==null||e.onSuccess(g))}).catch(g=>{i(g),d("error"),e!=null&&e.onError&&(e==null||e.onError(g))})}),reset:()=>{d("idle"),s(void 0),i(void 0)}}}var co=D(require("react")),od=require("react/jsx-runtime"),nd=co.default.createContext(null),it=({broadcastEvents:t,children:e})=>{let n=co.default.useMemo(()=>t,[]);return(0,od.jsx)(nd.Provider,{value:n,children:e})},fe=()=>{let t=(0,co.useContext)(nd);if(!t)throw new Error("You should use the useBroadcastEvents within a BroadcastEventsProvider");return t};var Ds=require("react");var Si=function(t,e){return Si=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var s in o)Object.prototype.hasOwnProperty.call(o,s)&&(n[s]=o[s])},Si(t,e)};function uo(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");Si(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}var xe=function(){return xe=Object.assign||function(e){for(var n,o=1,s=arguments.length;o<s;o++){n=arguments[o];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},xe.apply(this,arguments)};function sd(t,e){var n={};for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&e.indexOf(o)<0&&(n[o]=t[o]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,o=Object.getOwnPropertySymbols(t);s<o.length;s++)e.indexOf(o[s])<0&&Object.prototype.propertyIsEnumerable.call(t,o[s])&&(n[o[s]]=t[o[s]]);return n}function Ps(t,e,n){if(n||arguments.length===2)for(var o=0,s=e.length,r;o<s;o++)(r||!(o in e))&&(r||(r=Array.prototype.slice.call(e,0,o)),r[o]=e[o]);return t.concat(r||Array.prototype.slice.call(e))}function Is(t,e){var n=e&&e.cache?e.cache:um,o=e&&e.serializer?e.serializer:dm,s=e&&e.strategy?e.strategy:im;return s(t,{cache:n,serializer:o})}function rm(t){return t==null||typeof t=="number"||typeof t=="boolean"}function rd(t,e,n,o){var s=rm(o)?o:n(o),r=e.get(s);return typeof r=="undefined"&&(r=t.call(this,o),e.set(s,r)),r}function id(t,e,n){var o=Array.prototype.slice.call(arguments,3),s=n(o),r=e.get(s);return typeof r=="undefined"&&(r=t.apply(this,o),e.set(s,r)),r}function xi(t,e,n,o,s){return n.bind(e,t,o,s)}function im(t,e){var n=t.length===1?rd:id;return xi(t,this,n,e.cache.create(),e.serializer)}function am(t,e){return xi(t,this,id,e.cache.create(),e.serializer)}function lm(t,e){return xi(t,this,rd,e.cache.create(),e.serializer)}var dm=function(){return JSON.stringify(arguments)},cm=(function(){function t(){this.cache=Object.create(null)}return t.prototype.get=function(e){return this.cache[e]},t.prototype.set=function(e,n){this.cache[e]=n},t})(),um={create:function(){return new cm}},As={variadic:am,monadic:lm};var Ls;(function(t){t[t.EXPECT_ARGUMENT_CLOSING_BRACE=1]="EXPECT_ARGUMENT_CLOSING_BRACE",t[t.EMPTY_ARGUMENT=2]="EMPTY_ARGUMENT",t[t.MALFORMED_ARGUMENT=3]="MALFORMED_ARGUMENT",t[t.EXPECT_ARGUMENT_TYPE=4]="EXPECT_ARGUMENT_TYPE",t[t.INVALID_ARGUMENT_TYPE=5]="INVALID_ARGUMENT_TYPE",t[t.EXPECT_ARGUMENT_STYLE=6]="EXPECT_ARGUMENT_STYLE",t[t.INVALID_NUMBER_SKELETON=7]="INVALID_NUMBER_SKELETON",t[t.INVALID_DATE_TIME_SKELETON=8]="INVALID_DATE_TIME_SKELETON",t[t.EXPECT_NUMBER_SKELETON=9]="EXPECT_NUMBER_SKELETON",t[t.EXPECT_DATE_TIME_SKELETON=10]="EXPECT_DATE_TIME_SKELETON",t[t.UNCLOSED_QUOTE_IN_ARGUMENT_STYLE=11]="UNCLOSED_QUOTE_IN_ARGUMENT_STYLE",t[t.EXPECT_SELECT_ARGUMENT_OPTIONS=12]="EXPECT_SELECT_ARGUMENT_OPTIONS",t[t.EXPECT_PLURAL_ARGUMENT_OFFSET_VALUE=13]="EXPECT_PLURAL_ARGUMENT_OFFSET_VALUE",t[t.INVALID_PLURAL_ARGUMENT_OFFSET_VALUE=14]="INVALID_PLURAL_ARGUMENT_OFFSET_VALUE",t[t.EXPECT_SELECT_ARGUMENT_SELECTOR=15]="EXPECT_SELECT_ARGUMENT_SELECTOR",t[t.EXPECT_PLURAL_ARGUMENT_SELECTOR=16]="EXPECT_PLURAL_ARGUMENT_SELECTOR",t[t.EXPECT_SELECT_ARGUMENT_SELECTOR_FRAGMENT=17]="EXPECT_SELECT_ARGUMENT_SELECTOR_FRAGMENT",t[t.EXPECT_PLURAL_ARGUMENT_SELECTOR_FRAGMENT=18]="EXPECT_PLURAL_ARGUMENT_SELECTOR_FRAGMENT",t[t.INVALID_PLURAL_ARGUMENT_SELECTOR=19]="INVALID_PLURAL_ARGUMENT_SELECTOR",t[t.DUPLICATE_PLURAL_ARGUMENT_SELECTOR=20]="DUPLICATE_PLURAL_ARGUMENT_SELECTOR",t[t.DUPLICATE_SELECT_ARGUMENT_SELECTOR=21]="DUPLICATE_SELECT_ARGUMENT_SELECTOR",t[t.MISSING_OTHER_CLAUSE=22]="MISSING_OTHER_CLAUSE",t[t.INVALID_TAG=23]="INVALID_TAG",t[t.INVALID_TAG_NAME=25]="INVALID_TAG_NAME",t[t.UNMATCHED_CLOSING_TAG=26]="UNMATCHED_CLOSING_TAG",t[t.UNCLOSED_TAG=27]="UNCLOSED_TAG"})(Ls||(Ls={}));var Ms=class{constructor(e){console.warn(`[vite-messages-plugin]: Message "${e}" was not precompiled. Did you use the correct extenstion *.messages.ts?`)}};var Ee;(function(t){t[t.literal=0]="literal",t[t.argument=1]="argument",t[t.number=2]="number",t[t.date=3]="date",t[t.time=4]="time",t[t.select=5]="select",t[t.plural=6]="plural",t[t.pound=7]="pound",t[t.tag=8]="tag"})(Ee||(Ee={}));var Ns;(function(t){t[t.number=0]="number",t[t.dateTime=1]="dateTime"})(Ns||(Ns={}));function bi(t){return t.type===Ee.literal}function Ci(t){return t.type===Ee.argument}function po(t){return t.type===Ee.number}function go(t){return t.type===Ee.date}function mo(t){return t.type===Ee.time}function fo(t){return t.type===Ee.select}function ho(t){return t.type===Ee.plural}function ad(t){return t.type===Ee.pound}function yo(t){return t.type===Ee.tag}function Os(t){return!!(t&&typeof t=="object"&&t.type===Ns.number)}function vo(t){return!!(t&&typeof t=="object"&&t.type===Ns.dateTime)}function Ti(t){t.forEach(function(e){if(delete e.location,fo(e)||ho(e))for(var n in e.options)delete e.options[n].location,Ti(e.options[n].value);else po(e)&&Os(e.style)||(go(e)||mo(e))&&vo(e.style)?delete e.style.location:yo(e)&&Ti(e.children)})}function ld(t,e){e===void 0&&(e={}),e=xe({shouldParseSkeletons:!0,requiresOtherClause:!0},e);var n=new Ms(t,e).parse();if(n.err){var o=SyntaxError(Ls[n.err.kind]);throw o.location=n.err.location,o.originalMessage=n.err.message,o}return e!=null&&e.captureLocation||Ti(n.val),n.val}var tn;(function(t){t.MISSING_VALUE="MISSING_VALUE",t.INVALID_VALUE="INVALID_VALUE",t.MISSING_INTL_API="MISSING_INTL_API"})(tn||(tn={}));var So=(function(t){uo(e,t);function e(n,o,s){var r=t.call(this,n)||this;return r.code=o,r.originalMessage=s,r}return e.prototype.toString=function(){return"[formatjs Error: ".concat(this.code,"] ").concat(this.message)},e})(Error);var wi=(function(t){uo(e,t);function e(n,o,s,r){return t.call(this,'Invalid values for "'.concat(n,'": "').concat(o,'". Options are "').concat(Object.keys(s).join('", "'),'"'),tn.INVALID_VALUE,r)||this}return e})(So);var dd=(function(t){uo(e,t);function e(n,o,s){return t.call(this,'Value for "'.concat(n,'" must be of type ').concat(o),tn.INVALID_VALUE,s)||this}return e})(So);var cd=(function(t){uo(e,t);function e(n,o){return t.call(this,'The intl string context variable "'.concat(n,'" was not provided to the string "').concat(o,'"'),tn.MISSING_VALUE,o)||this}return e})(So);var le;(function(t){t[t.literal=0]="literal",t[t.object=1]="object"})(le||(le={}));function pm(t){return t.length<2?t:t.reduce(function(e,n){var o=e[e.length-1];return!o||o.type!==le.literal||n.type!==le.literal?e.push(n):o.value+=n.value,e},[])}function gm(t){return typeof t=="function"}function xo(t,e,n,o,s,r,i){if(t.length===1&&bi(t[0]))return[{type:le.literal,value:t[0].value}];for(var a=[],d=0,l=t;d<l.length;d++){var c=l[d];if(bi(c)){a.push({type:le.literal,value:c.value});continue}if(ad(c)){typeof r=="number"&&a.push({type:le.literal,value:n.getNumberFormat(e).format(r)});continue}var p=c.value;if(!(s&&p in s))throw new cd(p,i);var u=s[p];if(Ci(c)){(!u||typeof u=="string"||typeof u=="number")&&(u=typeof u=="string"||typeof u=="number"?String(u):""),a.push({type:typeof u=="string"?le.literal:le.object,value:u});continue}if(go(c)){var g=typeof c.style=="string"?o.date[c.style]:vo(c.style)?c.style.parsedOptions:void 0;a.push({type:le.literal,value:n.getDateTimeFormat(e,g).format(u)});continue}if(mo(c)){var g=typeof c.style=="string"?o.time[c.style]:vo(c.style)?c.style.parsedOptions:o.time.medium;a.push({type:le.literal,value:n.getDateTimeFormat(e,g).format(u)});continue}if(po(c)){var g=typeof c.style=="string"?o.number[c.style]:Os(c.style)?c.style.parsedOptions:void 0;g&&g.scale&&(u=u*(g.scale||1)),a.push({type:le.literal,value:n.getNumberFormat(e,g).format(u)});continue}if(yo(c)){var m=c.children,f=c.value,y=s[f];if(!gm(y))throw new dd(f,"function",i);var v=xo(m,e,n,o,s,r),x=y(v.map(function(L){return L.value}));Array.isArray(x)||(x=[x]),a.push.apply(a,x.map(function(L){return{type:typeof L=="string"?le.literal:le.object,value:L}}))}if(fo(c)){var T=c.options[u]||c.options.other;if(!T)throw new wi(c.value,u,Object.keys(c.options),i);a.push.apply(a,xo(T.value,e,n,o,s));continue}if(ho(c)){var T=c.options["=".concat(u)];if(!T){if(!Intl.PluralRules)throw new So(`Intl.PluralRules is not available in this environment.
1
+ "use strict";var wg=Object.create;var to=Object.defineProperty,Eg=Object.defineProperties,kg=Object.getOwnPropertyDescriptor,Rg=Object.getOwnPropertyDescriptors,Pg=Object.getOwnPropertyNames,ss=Object.getOwnPropertySymbols,Ig=Object.getPrototypeOf,ii=Object.prototype.hasOwnProperty,Ha=Object.prototype.propertyIsEnumerable;var Fa=(t,e,n)=>e in t?to(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,h=(t,e)=>{for(var n in e||(e={}))ii.call(e,n)&&Fa(t,n,e[n]);if(ss)for(var n of ss(e))Ha.call(e,n)&&Fa(t,n,e[n]);return t},b=(t,e)=>Eg(t,Rg(e));var O=(t,e)=>{var n={};for(var o in t)ii.call(t,o)&&e.indexOf(o)<0&&(n[o]=t[o]);if(t!=null&&ss)for(var o of ss(t))e.indexOf(o)<0&&Ha.call(t,o)&&(n[o]=t[o]);return n};var Z=(t,e)=>{for(var n in e)to(t,n,{get:e[n],enumerable:!0})},Ba=(t,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Pg(e))!ii.call(t,s)&&s!==n&&to(t,s,{get:()=>e[s],enumerable:!(o=kg(e,s))||o.enumerable});return t};var D=(t,e,n)=>(n=t!=null?wg(Ig(t)):{},Ba(e||!t||!t.__esModule?to(n,"default",{value:t,enumerable:!0}):n,t)),Ag=t=>Ba(to({},"__esModule",{value:!0}),t);var S=(t,e,n)=>new Promise((o,s)=>{var r=d=>{try{a(n.next(d))}catch(l){s(l)}},i=d=>{try{a(n.throw(d))}catch(l){s(l)}},a=d=>d.done?o(d.value):Promise.resolve(d.value).then(r,i);a((n=n.apply(t,e)).next())});var Py={};Z(Py,{Card:()=>H,ContentEditableInput:()=>yn,DeepdeskAPI:()=>xt,DeepdeskSDK:()=>os,HTTPClient:()=>Sn,InputMediator:()=>St,InputType:()=>$t,KeyboardHint:()=>ds,Label:()=>qa,Locale:()=>oo,Section:()=>Ve,SectionList:()=>Tn,Sources:()=>je,Suggestion:()=>M,SuggestionList:()=>oe,TextAreaInput:()=>vn,ToggleButton:()=>jt,attachFile:()=>yg,authenticateWithKey:()=>vg,createFullRange:()=>Qn,createOverlayContainer:()=>ns,createRangeFromOffsets:()=>Kt,escapeHTML:()=>Un,formatTextMarkup:()=>Sg,getRangeOffsets:()=>Zo,getRangeText:()=>Yo,insertCKEditor:()=>Tg,isHTML:()=>Po,isSupportedInputElement:()=>ni,logEvent:()=>Ps,updateContentEditable:()=>bg,updateTextArea:()=>xg,useClickOutsideRoot:()=>At,useStyles:()=>C,waitForElementVisibilityChange:()=>ri});module.exports=Ag(Py);var li=D(require("classnames")),we=D(require("react"));var rs=D(require("react")),Ua=D(require("classnames"));var no=rs.default.createContext({});function C(t,e){let r=(0,rs.useContext)(no),{debug:n}=r,s=O(r,["debug"])[t];return Object.entries(e).reduce((i,[a,d])=>{let l=s==null?void 0:s[a];return b(h({},i),{[a]:(0,Ua.default)(d,l,n?`${t}__${a}`:!1)})},{})}var Ka={root:"dd-4s9wq"};var zt=require("react/jsx-runtime"),is=()=>(0,zt.jsxs)("svg",{className:Ka.root,width:"185",height:"170",viewBox:"0 0 185 170",xmlns:"http://www.w3.org/2000/svg",children:[(0,zt.jsx)("defs",{children:(0,zt.jsx)("style",{children:".cls-1 { fill: #b3b3b3; }"})}),(0,zt.jsx)("title",{children:"Failed loading image"}),(0,zt.jsx)("path",{className:"cls-1",d:"M15 130.896V16.994c0-1.097.898-1.994 2.007-1.994h150.986A2 2 0 0 1 170 16.994v69.147L133.015 51 87.26 120.377l-35.863-17.758L15 130.896zM2 0C.895 0 0 .887 0 2v166c0 1.105.887 2 2 2h181c1.105 0 2-.887 2-2V2c0-1.105-.887-2-2-2H2zm49 72c11.046 0 20-9.178 20-20.5S62.046 31 51 31s-20 9.178-20 20.5S39.954 72 51 72z",fillRule:"evenodd"})]});var ai={root:"dd-c9KvZ",imageWrapper:"dd-sE7D9",image:"dd-bEGMz",content:"dd-oFIQa",title:"dd-mSgoo",contentIsCropped:"dd-Uvjv4",lineClamp:"dd-ApQo-"};var Vt=require("react/jsx-runtime"),as=(0,we.createContext)(ai),Lg=({title:t,src:e})=>{let n=(0,we.useContext)(as),[o,s]=(0,we.useState)(!1);return(0,we.useEffect)(()=>{s(!1)},[e]),(0,Vt.jsx)("div",{className:n.imageWrapper,children:e&&!o?(0,Vt.jsx)("img",{className:n.image,alt:t,src:e,onError:()=>s(!0)}):(0,Vt.jsx)(is,{})})},Mg=({className:t,lineClamp:e=!1,cropText:n=!1,children:o})=>{let s=(0,we.useContext)(as);return(0,Vt.jsx)("div",{className:(0,li.default)(s.content,t,{[s.contentIsCropped]:n,[s.lineClamp]:e}),children:o})},Ng=r=>{var i=r,{as:t="h1",cropText:e=!1,className:n,children:o}=i,s=O(i,["as","cropText","className","children"]);let a=(0,we.useContext)(as);return we.default.createElement(t,h({className:(0,li.default)(a.title,n,{[a.contentIsCropped]:e})},s),o)},ls=({children:t})=>{let e=C("Card",ai);return(0,Vt.jsx)("div",{className:e.root,children:(0,Vt.jsx)(as.Provider,{value:e,children:t})})};ls.Image=Lg;ls.Content=Mg;ls.Title=Ng;var H=ls;var za=D(require("classnames"));var Wa={root:"dd-llBx9"};var Va=require("react/jsx-runtime");var Og={"arrow-up":"\u25B2","arrow-down":"\u25BC",tab:"tab",esc:"Esc",enter:"\u21B5"},Dg=o=>{var s=o,{className:t,keyCode:e}=s,n=O(s,["className","keyCode"]);let r=C("KeyboardHint",Wa);return(0,Va.jsx)("span",h({"data-key":Og[e],className:(0,za.default)(t,r.root)},n))},ds=Dg;var $a=D(require("classnames"));var ja={root:"dd-e6HXZ"};var Ga=require("react/jsx-runtime"),_g=o=>{var s=o,{className:t,children:e}=s,n=O(s,["className","children"]);let r=C("Label",ja);return(0,Ga.jsx)("span",b(h({},n),{className:(0,$a.default)(t,r.root),children:e}))},qa=_g;var Xa={root:"dd-FiMI7",subTitleContainer:"dd-98jc7",subtitle:"dd-3MnW8",suggestions:"dd-0SGL8"};var Cn=require("react/jsx-runtime"),Fg=s=>{var r=s,{title:t,children:e,type:n}=r,o=O(r,["title","children","type"]);let i=C("Section",Xa);return(0,Cn.jsxs)("section",b(h({},o),{className:i.root,"data-section-type":n,children:[t&&(0,Cn.jsx)("div",{className:i.subTitleContainer,children:(0,Cn.jsx)("span",{className:i.subtitle,children:t})}),(0,Cn.jsx)("div",{className:i.suggestions,children:e})]}))},Ve=Fg;var el=D(require("classnames")),tl=require("react");var Ct=require("react"),Za=require("react/jsx-runtime"),Ja=(0,Ct.createContext)(null),Qa=({scrollContainerRef:t,children:e})=>{let n=(0,Ct.useCallback)(o=>{let s=t.current;if(!s||s.scrollHeight<=s.clientHeight)return;let{top:r}=s.getBoundingClientRect(),{top:i}=o.getBoundingClientRect(),a=s.scrollTop+(i-r);typeof s.scrollTo=="function"?s.scrollTo({top:a}):s.scrollTop=a},[]);return(0,Za.jsx)(Ja.Provider,{value:n,children:e})},cs=t=>{let e=(0,Ct.useContext)(Ja);(0,Ct.useEffect)(()=>{let n=t.current;n&&e(n)},[])};var Ya={root:"dd-uoTXh"};var di=require("react/jsx-runtime"),Hg=({className:t,children:e})=>{let n=C("SectionList",Ya),o=(0,tl.useRef)(null);return(0,di.jsx)(Qa,{scrollContainerRef:o,children:(0,di.jsx)("div",{ref:o,className:(0,el.default)(n.root,t),children:e})})},Tn=Hg;var wn=D(require("classnames")),me=D(require("react"));var ci={root:"dd-1g-A9",fadein:"dd-McXxq",isClickable:"dd-CTG8E",isSelected:"dd-yhg27",actions:"dd-Nlm6p",actionsIsFixed:"dd-OK-kw",actionButton:"dd-zbXsQ",dropdownList:"dd-AvwWP",dropdownButton:"dd-piaJi",dropdownItem:"dd-qgkTO",dropdownItemButton:"dd-sTE2D",actionButtonIsPrimary:"dd-mhkWS",actionButtonIsDisabled:"dd-0eKLQ",labels:"dd-QKJu6",label:"dd-aMplE",buttonsContainer:"dd-uRYN4",button:"dd-9UE-x",buttonPrimary:"dd-aYDCB",buttonSecondary:"dd--cpPL",buttonWithIcon:"dd-MQVt5",icon:"dd-Jr-ww",buttonDisabled:"dd-agTuH"};var de=require("react/jsx-runtime"),Tt=(0,me.createContext)(ci),Bg=o=>{var s=o,{fixed:t,children:e}=s,n=O(s,["fixed","children"]);let r=(0,me.useContext)(Tt);return(0,de.jsx)("div",b(h({},n),{className:(0,wn.default)(r.actions,{[r.actionsIsFixed]:t}),children:e}))};function Ug(d){var l=d,{as:t,className:e,icon:n,title:o,children:s,disabled:r,variant:i}=l,a=O(l,["as","className","icon","title","children","disabled","variant"]);let c=(0,me.useContext)(Tt);return(0,de.jsxs)(t||"button",b(h({type:"button",className:(0,wn.default)(c.button,{[c.buttonWithIcon]:n,[c.buttonDisabled]:r,[c.buttonPrimary]:i==="primary",[c.buttonSecondary]:i==="secondary"},e),title:o,"aria-label":o},a),{children:[n&&(0,de.jsx)("span",{className:c.icon,children:n}),s]}))}var Kg=({children:t})=>{let e=(0,me.useContext)(Tt);return(0,de.jsx)("div",{className:e.buttonsContainer,children:t})},Wg=({className:t,primary:e,disabled:n,label:o,children:s})=>{let r=(0,me.useContext)(Tt);return(0,de.jsxs)("div",{className:(0,wn.default)(t,r.actionButton,r.dropdownButton,{[r.actionButtonIsPrimary]:e,[r.actionButtonIsDisabled]:n}),onMouseDown:i=>i.stopPropagation(),onClick:i=>i.stopPropagation(),children:[o,(0,de.jsx)("ul",{className:r.dropdownList,children:s})]})},zg=({index:t,label:e,onClick:n})=>{let o=(0,me.useContext)(Tt);return(0,de.jsx)("li",{className:o.dropdownItem,children:(0,de.jsx)("button",{className:o.dropdownItemButton,type:"button","data-index":t,onClick:n,children:e})})},Vg=({className:t,primary:e,disabled:n,onClick:o,label:s})=>{let r=(0,me.useContext)(Tt);return(0,de.jsx)("button",{type:"button",className:(0,wn.default)(t,r.actionButton,{[r.actionButtonIsPrimary]:e,[r.actionButtonIsDisabled]:n}),onClick:o!=null?o:(i=>i.stopPropagation()),disabled:n,"aria-hidden":n,children:s})},jg=({labels:t})=>{let e=(0,me.useContext)(Tt);return(0,de.jsx)("div",{className:e.labels,children:t.map(n=>(0,de.jsx)("span",{className:e.label,children:n},n))})},wt=me.default.forwardRef((a,i)=>{var d=a,{className:t,selected:e,onClick:n,children:o,as:s="div"}=d,r=O(d,["className","selected","onClick","children","as"]);let l=C("Suggestion",ci),c=(0,me.useCallback)(p=>{p.preventDefault(),n&&n(p)},[n]);return(0,de.jsx)(s,b(h({},r),{ref:i,className:(0,wn.default)(t,l.root,{[l.isSelected]:e,[l.isClickable]:!!n}),onClick:c,children:(0,de.jsx)(Tt.Provider,{value:l,children:o})}))});wt.Labels=jg;wt.Actions=Bg;wt.ActionButton=Vg;wt.DropdownButton=Wg;wt.DropdownItem=zg;wt.ButtonsContainer=Kg;wt.Button=Ug;var M=wt;var ol=D(require("classnames"));var nl={root:"dd-W35K-",isWithDivider:"dd-sscOy"};var sl=require("react/jsx-runtime"),$g=({withDivider:t,children:e})=>{let n=C("SuggestionList",nl);return(0,sl.jsx)("div",{"data-testid":"suggestions-overlay-list",className:(0,ol.default)(n.root,{[n.isWithDivider]:t}),children:e})},oe=$g;var il=D(require("classnames"));var rl={root:"dd-oWarc",isCollapsed:"dd-tfZI0"};var us=require("react/jsx-runtime"),qg=({className:t,isCollapsed:e,title:n,onClick:o})=>{let s=C("ToggleButton",rl);return(0,us.jsx)("button",{type:"button",className:(0,il.default)(s.root,t,{[s.isCollapsed]:e}),onClick:o,title:n,children:(0,us.jsx)("svg",{width:"14",height:"8",viewBox:"-2.5 -5 75 60",preserveAspectRatio:"none",children:(0,us.jsx)("path",{d:"M0,0 l35,50 l35,-50",fill:"none",stroke:"grey",strokeLinecap:"round",strokeWidth:"6"})})})},jt=qg;var al=/(?:[.,;:!?\\n]|:\\)|:\\(|:-\\)|:-\\()/g,ps=/(((\$!\{)|(\{))[a-zA-Z0-9_.]+\})/g;var ll=/x-deepdesk-(([a-z0-9\-_])+-version)/,gs=["cues","custom-data","custom-data-banner","knowledge-assist"],dl=Intl.DateTimeFormat().resolvedOptions().timeZone,je=(y=>(y.SEARCH="search",y.TEMPLATE="template",y.ELASTIC_SEARCH="search-autocomplete",y.GPT="gpt",y.TRIE="trie",y.TRIE_WITH_TYPOS="trie-with-typos",y.SEMANTIC="semantic",y.TEXT_RECOMMENDATION="text_recommendation",y.URL_RECOMMENDATION="url_recommendation",y.LINK_RECOMMENDATION="link_recommendation",y.PERSONAL_COLLECTION="personal-collection",y.PERSONAL_COLLECTION_SEARCH="personal-collection-search",y.SEARCH_OVERLAY="search-overlay",y.SEARCH_PREVIEW="search-preview",y.SEARCH_URL="search-url",y.STYLE="style",y))(je||{}),$t=(i=>(i.ENTER="enter",i.TAB="tab",i.ARROW="arrow",i.HOTKEY="hotkey",i.MOUSE="mouse",i.SPACE="space",i))($t||{});var G=require("react"),er=require("react-redux");var Et=require("@reduxjs/toolkit");var oo=(n=>(n.NL_NL="nl-NL",n.EN_US="en-US",n))(oo||{});var Gg={isLoggedIn:null,loginFetchState:"idle",verifyFetchState:"idle",showLoginOverlay:!1,loginError:null},se=t=>t.auth.isLoggedIn;var cl=t=>t.auth.verifyFetchState,ul=t=>t.auth.showLoginOverlay,pl=t=>t.auth.loginError,rt=(0,Et.createAsyncThunk)("auth/validate",(t,e)=>S(null,null,function*(){return e.extra.deepdeskAPI.isLoggedIn()})),gl=(0,Et.createAsyncThunk)("auth/requestLogin",(n,o)=>S(null,[n,o],function*({email:t},e){let{deepdeskAPI:s}=e.extra;return s.requestLoginByEmail(t)})),ui=(0,Et.createAsyncThunk)("auth/loginWithPassword",(o,s)=>S(null,[o,s],function*({username:t,password:e},n){let{deepdeskAPI:r}=n.extra;return r.loginWithPassword(t,e)})),ms=(0,Et.createAsyncThunk)("auth/logout",(t,e)=>S(null,null,function*(){let{deepdeskAPI:n}=e.extra;yield n.logout()})),so=(0,Et.createAsyncThunk)("auth/verifyLoginToken",(n,o)=>S(null,[n,o],function*({token:t},e){let{deepdeskAPI:s}=e.extra;return s.verifyLoginToken(t)})),ml=(0,Et.createSlice)({name:"auth",initialState:Gg,reducers:{setIsLoggedIn(t,e){t.isLoggedIn=e.payload},setShowLoginOverlay(t,e){t.showLoginOverlay=e.payload},setLoginError(t,e){t.loginError=e.payload},clearLoginError(t){t.loginError=null}},extraReducers:t=>{t.addCase(rt.pending,e=>{e.loginFetchState="loading"}),t.addCase(rt.fulfilled,(e,{payload:n})=>{e.isLoggedIn=n,e.loginFetchState="done"}),t.addCase(rt.rejected,e=>{e.loginFetchState="error",e.isLoggedIn=!1}),t.addCase(ui.pending,e=>{e.loginFetchState="loading",e.loginError=null}),t.addCase(ui.fulfilled,e=>{e.isLoggedIn=!0,e.loginFetchState="done",e.loginError=null,e.showLoginOverlay=!1}),t.addCase(ui.rejected,(e,n)=>{e.loginFetchState="error",e.isLoggedIn=!1,e.loginError=n.error.message==="Bad Request"?"Invalid credentials":"Login failed"}),t.addCase(ms.fulfilled,e=>{e.isLoggedIn=!1,e.loginFetchState="idle",e.loginError=null}),t.addCase(ms.rejected,e=>{e.isLoggedIn=!1,e.loginFetchState="error"}),t.addCase(so.pending,e=>{e.verifyFetchState="loading"}),t.addCase(so.rejected,e=>{e.verifyFetchState="error"}),t.addCase(so.fulfilled,(e,n)=>{n.payload.isLoggedIn?e.verifyFetchState="done":e.verifyFetchState="error"})}}),{setIsLoggedIn:En,setShowLoginOverlay:fl,setLoginError:pi,clearLoginError:fs}=ml.actions,hl=ml.reducer;var Gt=require("@reduxjs/toolkit"),Cl=require("diff");function yl(t){return typeof t=="object"&&!Array.isArray(t)&&t!==null}function kt(t,e,n=10){let o=typeof t,s=typeof e;if(n===0)throw new Error("Max depth deepEqual, possible circular references?");return o!==s?!1:t==null||o==="string"||o==="number"||o==="boolean"?t===e:Array.isArray(t)&&Array.isArray(e)?t.length!==e.length?!1:t.every((r,i)=>kt(r,e[i],n-1)):yl(t)&&yl(e)?Object.keys(t).length!==Object.keys(e).length?!1:Object.keys(t).every(i=>kt(t[i],e[i],n-1)):!1}function Xg(t){return Math.max(...t.map(e=>e.length))}function Jg(t,e){let n=t.reduce((o,s)=>{if(s){let r=o[s]?o[s]+1:1;return b(h({},o),{[s]:r})}return o},{});return Object.keys(n).reduce((o,s)=>(n[s]<e&&o.push(s),o),[])}function vl(t,e){let o=[...t.map(({text:s})=>s.split(/\b(\w+)\b/))];for(let s=0;s<Xg(o);s++){let r=Jg(o.map(a=>a[s]),e),i=o.filter(a=>!r.includes(a[s]));if(i.length>=e)o=i;else return{text:o[0].slice(0,s).join("").replace(/ (\?| |!|\.|,|\n)/g,"$1").trimEnd(),source:"mixed"}}}var Qg=2;function Sl(t,e=""){if(t.length===0)return;if(t.length===1)return t[0];let n=vl(t,Qg);return n&&n.text!==e?n:t[0]}var Oe=require("@reduxjs/toolkit");var Zg={info(...t){console.info("[Deepdesk]",...t)},warn(...t){console.warn("[Deepdesk]",...t)},error(...t){console.error("[Deepdesk]",...t)}},k=Zg;var xl={current:null,isSupported:null},Y=(0,Oe.createAction)("resetConversation"),hs=t=>{let{current:e}=t.conversation;return(e==null?void 0:e.externalId)||null},$e=t=>{let{current:e}=t.conversation;return(e==null?void 0:e.id)||null},kn=t=>t.conversation.isSupported,gi=(0,Oe.createAsyncThunk)("conversation/isSupported",(t,e)=>{let{deepdeskAPI:n}=e.extra;return n.isConversationSupported(t.externalId,t.options)}),ys=(0,Oe.createAsyncThunk)("conversation/create",(t,e)=>{let{deepdeskAPI:n}=e.extra;return n.createConversation(t)}),vs=(0,Oe.createAsyncThunk)("conversation/byExternalId",(t,e)=>{let{deepdeskAPI:n}=e.extra;return n.getConversationByExternalId(t.externalId,t.options)}),Ss=(0,Oe.createAsyncThunk)("conversation/update",(t,e)=>{let{deepdeskAPI:n}=e.extra,o=$e(e.getState());if(!o)throw new Error("No current conversation to update");return n.updateConversation(o,t)}),mi=(0,Oe.createAsyncThunk)("conversation/upsert",(t,e)=>{let{deepdeskAPI:n}=e.extra;return n.upsertConversation(t)}),fi=(0,Oe.createAsyncThunk)("conversation/postMessages",(t,e)=>{let{deepdeskAPI:n}=e.extra,o=$e(e.getState());if(!o)throw new Error("No current conversation to update messages");return n.postMessages(o,t.map(s=>h({},s)))}),Yg=[ys.rejected,vs.rejected,Ss.rejected,fi.rejected].map(t=>t==null?void 0:t.toString());function em(t){return Yg.includes(t.type)}var tm=(0,Oe.createSlice)({name:"conversation",initialState:xl,reducers:{},extraReducers:t=>{t.addCase(gi.fulfilled,(e,n)=>{e.isSupported=n.payload}).addCase(ys.fulfilled,(e,n)=>{var o;e.current=n.payload,e.isSupported=!!((o=n.payload)!=null&&o.profileCode)}).addCase(vs.fulfilled,(e,n)=>{var o;e.current=n.payload,e.isSupported=!!((o=n.payload)!=null&&o.profileCode)}).addCase(mi.fulfilled,(e,n)=>{var o;e.current=n.payload,e.isSupported=!!((o=n.payload)!=null&&o.profileCode)}).addCase(Ss.fulfilled,(e,n)=>{var o;e.current=n.payload,e.isSupported=!!((o=n.payload)!=null&&o.profileCode)}).addCase(Y,()=>xl).addMatcher(em,(e,n)=>{var o;throw k.info("Conversation action rejected",n.type,((o=n.error)==null?void 0:o.message)||"No message"),new Error(n.error.message)})}}),bl=tm.reducer;var qt={text:"",html:null,suggestionTextStart:0,selection:{start:0,end:0},beforeInputChange:null,mixedSuggestion:null,textSuggestions:[],pinnedSuggestions:[],selectedSuggestionIndex:-1,metrics:{numCharsTyped:0,numCharsPasted:0,numCharsCut:0,numCharsDeleted:0,numPaste:0,agentStartedTypingTimestamp:null,externalTimeTotalSeconds:null,pastes:[],deletions:[],offeredTextSuggestions:[],textSuggestions:[],cuts:[]}};function hi(t){let{key:e,shiftKey:n,ctrlKey:o,metaKey:s,altKey:r}=t;return{key:e,shiftKey:n,ctrlKey:o,metaKey:s,altKey:r}}var xs=(0,Gt.createAction)("input/applyImageSuggestion"),Tl=(0,Gt.createSlice)({name:"input",initialState:qt,reducers:{setInput(t,e){var i,a;let{beforeInputChange:n}=t,{text:o,html:s,suggestionTextStart:r}=e.payload;if(t.text=o,t.html=s!=null?s:null,t.suggestionTextStart=o===""?0:Math.max(0,r!=null?r:0),o==="")t.metrics=qt.metrics,t.textSuggestions=[],t.mixedSuggestion=null;else if(n!==null&&t.text!==n.text){let{key:d,shiftKey:l,ctrlKey:c,metaKey:p,altKey:u}=n.keyDown;switch(d){case"Enter":l&&(t.metrics.numCharsTyped+=1);break;case"Backspace":case"Delete":{let{text:g}=t,m=(0,Cl.diffChars)(n.text,g);n.text.length-g.length>1&&t.metrics.deletions.push(...m.filter(f=>f.removed).map(f=>f.value)),t.metrics.numCharsDeleted+=n.text.length-g.length;break}case"Shift":case"Meta":case"Tab":break;case"C":case"V":case"X":case"c":case"v":case"x":if(c||p)break;default:if(!c&&!p&&!u){t.metrics.numCharsTyped+=1;let g=((i=n.selection)==null?void 0:i.start)!==void 0&&((a=n.selection)==null?void 0:a.end)!==void 0?n.text.substring(n.selection.start,n.selection.end):null;g&&g.length>0&&(t.metrics.numCharsDeleted+=g.length,t.metrics.deletions.push(g))}}t.metrics.agentStartedTypingTimestamp||(t.metrics.agentStartedTypingTimestamp=Date.now())}t.beforeInputChange=null},sendMessage(t,e){t.pinnedSuggestions=t.pinnedSuggestions.filter(n=>!t.metrics.textSuggestions.some(o=>o.text===n.text&&o.source===n.source))},setSelection(t,e){e.payload!==null&&(kt(t.selection,e.payload)||(t.selection=e.payload))},commitSuggestion(t,e){let n=e.payload,{text:o,suggestion:{source:s,abVariant:r,abTestName:i,trainingJobs:a,sourceText:d,searchTerm:l,assistantCode:c,text:p},eventMetrics:{inputType:u},replace:g}=n,m=s==="search"||s==="personal-collection-search",f=o.slice(t.text.substring(0,t.selection.start).length);(m||g==="selection")&&(f=o),n.suggestion.source==="search-overlay"&&(f=p),t.metrics.textSuggestions.push({text:f,source:s,assistantCode:c,abVariant:r,abTestName:i,inputType:u,sourceText:d,trainingJobs:a||[],searchTerm:m?t.text:l}),t.textSuggestions=[],t.selectedSuggestionIndex=-1},offeredTextSuggestion(t,e){let{text:n,suggestion:{source:o}}=e.payload;t.metrics.offeredTextSuggestions.find(r=>r.text===n)||t.metrics.offeredTextSuggestions.push({text:n,source:o})},registerKeyDown(t,e){let{key:n}=e.payload;["Control","Meta","Shift","Alt"].includes(n)||(t.beforeInputChange={text:t.text,selection:t.selection,keyDown:e.payload})},registerKeyUp(t,e){},registerCut(t,e){let{metrics:n}=t,o=e.payload;t.metrics=b(h({},t.metrics),{numCharsCut:n.numCharsCut+o.length,cuts:[...n.cuts,o]})},registerPaste(t,e){let{metrics:n}=t,{text:o,selectionText:s}=e.payload,r=n.numCharsDeleted+(s!=null&&s.length?s.length:0),i=s!=null&&s.length?[...n.deletions,s]:n.deletions;t.metrics=b(h({},t.metrics),{numCharsDeleted:r,deletions:i,numCharsPasted:n.numCharsPasted+o.length,numPaste:n.numPaste+1,pastes:[...n.pastes,o]})},selectNextTextSuggestion(t){let e=t.textSuggestions.length+t.pinnedSuggestions.length;t.selectedSuggestionIndex=t.selectedSuggestionIndex<e-1?t.selectedSuggestionIndex+1:t.selectedSuggestionIndex},selectPreviousTextSuggestion(t){t.selectedSuggestionIndex=t.selectedSuggestionIndex>=0?t.selectedSuggestionIndex-1:t.selectedSuggestionIndex},selectTextSuggestionByIndex(t,e){t.selectedSuggestionIndex=e.payload},setTextSuggestions(t,e){if(t.selectedSuggestionIndex=-1,t.textSuggestions=e.payload,e.payload.length===0){t.mixedSuggestion=null;return}let n=Xt({input:t}),o=Sl(e.payload,n);t.mixedSuggestion=o!=null&&o.text.includes(n)?o:null},setPinnedSuggestions(t,e){t.pinnedSuggestions=e.payload},removePinnedSuggestions(t,e){t.pinnedSuggestions=t.pinnedSuggestions.filter(o=>o.source!==e.payload.source||e.payload.assistantCode&&o.assistantCode!==e.payload.assistantCode?!0:e.payload.text?o.text!==e.payload.text:!1);let n=t.textSuggestions.length+t.pinnedSuggestions.length;t.selectedSuggestionIndex>n-1&&(t.selectedSuggestionIndex=-1)},setMetrics(t,{payload:e}){t.metrics=e},resetMetrics(t){t.metrics=qt.metrics}},extraReducers:t=>{t.addCase(Y,e=>{e.mixedSuggestion=qt.mixedSuggestion,e.textSuggestions=qt.textSuggestions,e.selectedSuggestionIndex=qt.selectedSuggestionIndex,e.metrics=qt.metrics})}}),Xt=t=>{let{text:e,selection:n,suggestionTextStart:o}=t.input;return e.slice(o,n.end)},nm=t=>t.input.mixedSuggestion,om=t=>t.input.pinnedSuggestions,sm=t=>t.input.textSuggestions,ro=t=>t.input.selectedSuggestionIndex,Jt=(0,Gt.createSelector)([sm,om],(t,e)=>[...t,...e]),Rn=(0,Gt.createSelector)([Jt,nm,ro],(t,e,n)=>n>-1?t[n]:e),wl=t=>t.input.selection,{commitSuggestion:Se,offeredTextSuggestion:El,registerCut:kl,registerKeyDown:Rl,registerKeyUp:Pl,registerPaste:Il,selectNextTextSuggestion:Al,selectPreviousTextSuggestion:Ll,selectTextSuggestionByIndex:bs,setInput:Cs,setMetrics:Ml,setPinnedSuggestions:Pn,removePinnedSuggestions:Qt,setSelection:Ts,setTextSuggestions:Rt,resetMetrics:Nl,sendMessage:Zt}=Tl.actions,Ol=Tl.reducer;var An=require("@reduxjs/toolkit");var Yt=require("@reduxjs/toolkit");function Dl(t){try{return Intl.DateTimeFormat(void 0,{timeZone:t}),!0}catch(e){return!1}}var rm={agentInfo:void 0,agentSettings:{},visitorInfo:void 0,customData:void 0,platformVariables:void 0,fetchState:"idle",showNicknameDialog:!1},In=t=>{var e;return(e=t.info.agentInfo)!=null?e:null},_l=t=>{var e;return(e=t.info.visitorInfo)!=null?e:null},Fl=t=>{var e;return(e=t.info.customData)!=null?e:null},ao=({info:{visitorInfo:t,agentInfo:e}})=>{var n,o;return{timezone:t!=null&&t.visitorTimeZone&&Dl(t.visitorTimeZone)?t.visitorTimeZone:dl,agentName:(n=e==null?void 0:e.agentNickname)!=null?n:"",visitorName:(o=t==null?void 0:t.visitorName)!=null?o:""}},im=[["agentNickname","nickname"],["agentDefaultLocale","defaultLocale"],["agentEmail","email"]],Hl=(0,Yt.createAsyncThunk)("info/setAgentNickname",(n,o)=>S(null,[n,o],function*({agentNickname:t},e){var i;let{deepdeskAPI:s}=e.extra,r=yield s.patchMe({nickname:t});return{agentNickname:(i=r==null?void 0:r.nickname)!=null?i:t}})),io=(0,Yt.createAsyncThunk)("info/setAgentInfo",(t,e)=>S(null,null,function*(){var r,i,a;let{deepdeskAPI:n}=e.extra,o=yield n.getMe(),s=[];if(t.agentId&&t.skipSync!==!0&&s.push(n.postIdentity({externalId:t.agentId})),t.skipSync!==!0){let d=im.reduce((l,[c,p])=>!o[p]&&c in t?b(h({},l),{[p]:t[c]}):l,{});Object.keys(d).length>0&&s.push(n.patchMe(d).then(l=>o=l))}return s.length>0&&(yield Promise.all(s)),{agentId:t.agentId,agentName:t.agentName,agentNickname:(r=o.nickname)!=null?r:t.agentNickname,agentEmail:(i=o.email)!=null?i:t.agentEmail,agentDefaultLocale:(a=o.defaultLocale)!=null?a:t.agentDefaultLocale,agentTimeZone:t.agentTimeZone}})),yi=(0,Yt.createAsyncThunk)("info/setAgentSettings",(t,e)=>S(null,null,function*(){let{deepdeskAPI:n}=e.extra,o=yield n.getMe(),s=h(h({},typeof o.uiConfig=="object"?o.uiConfig:{}),t);return yield n.patchMe({uiConfig:s}),s})),vi=(0,Yt.createAsyncThunk)("info/getAgentSettings",(t,e)=>S(null,null,function*(){let{deepdeskAPI:n}=e.extra;return(yield n.getMe()).uiConfig})),Bl=(0,Yt.createSlice)({name:"info",initialState:rm,reducers:{setVisitorInfo(t,e){t.visitorInfo=h(h({},t.visitorInfo),e.payload)},setCustomData(t,e){t.customData=e.payload},setPlatformVariables(t,e){t.platformVariables=e.payload},setShowNicknameDialog(t,e){t.showNicknameDialog=e.payload}},extraReducers:t=>{t.addCase(io.pending,(e,n)=>{e.fetchState="loading",e.agentInfo=h(h({},e.agentInfo),n.meta.arg)}).addCase(io.rejected,e=>{e.fetchState="error"}).addCase(io.fulfilled,(e,n)=>{e.fetchState="done",e.agentInfo=n.payload}).addCase(yi.fulfilled,(e,n)=>{e.agentSettings=n.payload}).addCase(vi.fulfilled,(e,n)=>{e.agentSettings=n.payload}).addCase(Y,e=>{e.visitorInfo=void 0})}}),{setVisitorInfo:Ul,setCustomData:Kl,setPlatformVariables:Wl,setShowNicknameDialog:zl}=Bl.actions,Vl=Bl.reducer;function De(t,e){return e?t==null?(k.warn("replaceVars called with non-string text; upstream contract violation",{keys:Object.keys(e)}),t):Object.entries(e).reduce((n,[o,s])=>n.replaceAll(o,s),t):t}var ws={list:[],fetchState:"idle",isOpen:!1,page:"search",aggregates:{}},jl=t=>t.search.isOpen,$l=t=>t.search.page,Si=t=>t.search.list,ql=t=>t.search.aggregates,am=(0,An.createSelector)([Si,(t,e)=>e],(t,e)=>t.filter(n=>n.type===e)),Gl=t=>e=>am(e,t),en=(0,An.createAsyncThunk)("search/getAll",(t,e)=>S(null,null,function*(){var d;let{deepdeskAPI:n}=e.extra,o=e.getState(),s=(d=o.conversation.current)==null?void 0:d.profileCode,{platformVariables:r}=o.info;if(!s)throw new Error("Profile should be provided in order to be able to search");let{results:i,aggregates:a}=yield n.search({profile:s,query:t.query,tags:t.tags,size:t.size,current:t.current,filters:{type:t.type},params:ao(o)});return{results:i.map(l=>b(h(h({},l),l.title&&r?{title:De(l.title,r)}:{}),{text:De(l.text,r!=null?r:{}),source:`search-${l.type.toLowerCase()}`,searchTerm:t.query})),aggregates:a}})),Xl=(0,An.createSlice)({name:"search",initialState:ws,reducers:{setIsOpen(t,e){t.isOpen=e.payload},setPage(t,e){t.page=e.payload},resetSearch(t){t.fetchState=ws.fetchState,t.list=ws.list}},extraReducers:t=>{t.addCase(en.pending,e=>{e.fetchState="loading"}).addCase(en.rejected,(e,n)=>{e.fetchState="error",k.error(n.error)}).addCase(en.fulfilled,(e,n)=>{e.fetchState="done",e.list=n.payload.results,e.aggregates=n.payload.aggregates||{}}).addCase(Y,()=>ws)}}),{resetSearch:Es,setIsOpen:_e,setPage:Ln}=Xl.actions,Jl=Xl.reducer;var xi="SetOutputs",Mn="ShowLoginOverlay",lo="UserLoggedIn",lm="UserLoggedOut",it="ApplySuggestion",bi="ApplyImageSuggestion",dm="ShowCommandPalette",ks="ShowNicknameDialog",Rs="ReduxAction",cm="RemovePinnedSuggestion",um=t=>({[xi]:e=>{var s,r;let n=(s=t.getState().conversation.current)==null?void 0:s.externalId,o=(r=e==null?void 0:e.payload)==null?void 0:r.externalConversationId;o&&o!==n||t.dispatch(b(h({},e),{isBroadcasted:!0}))},[Rs]:e=>{e.isBroadcasted||t.dispatch(b(h({},e),{isBroadcasted:!0}))},[cm]:e=>{t.dispatch(Qt(e))},[dm]:e=>{t.dispatch(_e(e.isOpen)),e.page&&t.dispatch(Ln(e.page))},[ks]:e=>{t.dispatch(zl(e.showNicknameDialog))},[Mn]:e=>{t.dispatch(fl(e))},[lo]:()=>{t.dispatch(rt())},[lm]:()=>{t.dispatch(rt())},[bi]:e=>{t.dispatch(xs({suggestion:e.suggestion}))},[it]:e=>{t.dispatch(Se(b(h({},e),{eventMetrics:{inputType:"mouse"},replace:"selection"})))}}),Ql=um;var Yl=require("react-redux");var Zl=require("@reduxjs/toolkit");function Ps(t){return(0,Zl.createAsyncThunk)("analytics/logEvent",(e,n)=>{var r,i,a;let o=(i=(r=n.getState())==null?void 0:r.conversation.current)==null?void 0:i.id,s=(a=n.getState())==null?void 0:a.info.agentInfo;return n.extra.deepdeskAPI.sendEvent(e.name,b(h({conversationId:o},s),{data:e.data}))})(t)}function q(){let t=(0,Yl.useDispatch)();return(e,n)=>S(null,null,function*(){yield t(Ps({name:e,data:n}))})}var Nn=require("react"),ed=require("react-redux");function Is(t,e){let n=(0,Nn.useRef)(t);n.current=t;let[o,s]=(0,Nn.useState)(void 0),[r,i]=(0,Nn.useState)(void 0),[a,d]=(0,Nn.useState)("idle"),l=(0,ed.useDispatch)();return{error:r,state:a,data:o,call:u=>S(null,null,function*(){d("loading"),yield l(n.current(u)).unwrap().then(g=>{s(g),d("done"),e!=null&&e.onSuccess&&(e==null||e.onSuccess(g))}).catch(g=>{i(g),d("error"),e!=null&&e.onError&&(e==null||e.onError(g))})}),reset:()=>{d("idle"),s(void 0),i(void 0)}}}var co=D(require("react")),nd=require("react/jsx-runtime"),td=co.default.createContext(null),at=({broadcastEvents:t,children:e})=>{let n=co.default.useMemo(()=>t,[]);return(0,nd.jsx)(td.Provider,{value:n,children:e})},fe=()=>{let t=(0,co.useContext)(td);if(!t)throw new Error("You should use the useBroadcastEvents within a BroadcastEventsProvider");return t};var Fs=require("react");var Ci=function(t,e){return Ci=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var s in o)Object.prototype.hasOwnProperty.call(o,s)&&(n[s]=o[s])},Ci(t,e)};function uo(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");Ci(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}var xe=function(){return xe=Object.assign||function(e){for(var n,o=1,s=arguments.length;o<s;o++){n=arguments[o];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},xe.apply(this,arguments)};function od(t,e){var n={};for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&e.indexOf(o)<0&&(n[o]=t[o]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,o=Object.getOwnPropertySymbols(t);s<o.length;s++)e.indexOf(o[s])<0&&Object.prototype.propertyIsEnumerable.call(t,o[s])&&(n[o[s]]=t[o[s]]);return n}function As(t,e,n){if(n||arguments.length===2)for(var o=0,s=e.length,r;o<s;o++)(r||!(o in e))&&(r||(r=Array.prototype.slice.call(e,0,o)),r[o]=e[o]);return t.concat(r||Array.prototype.slice.call(e))}function Ls(t,e){var n=e&&e.cache?e.cache:vm,o=e&&e.serializer?e.serializer:hm,s=e&&e.strategy?e.strategy:gm;return s(t,{cache:n,serializer:o})}function pm(t){return t==null||typeof t=="number"||typeof t=="boolean"}function sd(t,e,n,o){var s=pm(o)?o:n(o),r=e.get(s);return typeof r=="undefined"&&(r=t.call(this,o),e.set(s,r)),r}function rd(t,e,n){var o=Array.prototype.slice.call(arguments,3),s=n(o),r=e.get(s);return typeof r=="undefined"&&(r=t.apply(this,o),e.set(s,r)),r}function Ti(t,e,n,o,s){return n.bind(e,t,o,s)}function gm(t,e){var n=t.length===1?sd:rd;return Ti(t,this,n,e.cache.create(),e.serializer)}function mm(t,e){return Ti(t,this,rd,e.cache.create(),e.serializer)}function fm(t,e){return Ti(t,this,sd,e.cache.create(),e.serializer)}var hm=function(){return JSON.stringify(arguments)},ym=(function(){function t(){this.cache=Object.create(null)}return t.prototype.get=function(e){return this.cache[e]},t.prototype.set=function(e,n){this.cache[e]=n},t})(),vm={create:function(){return new ym}},Ms={variadic:mm,monadic:fm};var Ns;(function(t){t[t.EXPECT_ARGUMENT_CLOSING_BRACE=1]="EXPECT_ARGUMENT_CLOSING_BRACE",t[t.EMPTY_ARGUMENT=2]="EMPTY_ARGUMENT",t[t.MALFORMED_ARGUMENT=3]="MALFORMED_ARGUMENT",t[t.EXPECT_ARGUMENT_TYPE=4]="EXPECT_ARGUMENT_TYPE",t[t.INVALID_ARGUMENT_TYPE=5]="INVALID_ARGUMENT_TYPE",t[t.EXPECT_ARGUMENT_STYLE=6]="EXPECT_ARGUMENT_STYLE",t[t.INVALID_NUMBER_SKELETON=7]="INVALID_NUMBER_SKELETON",t[t.INVALID_DATE_TIME_SKELETON=8]="INVALID_DATE_TIME_SKELETON",t[t.EXPECT_NUMBER_SKELETON=9]="EXPECT_NUMBER_SKELETON",t[t.EXPECT_DATE_TIME_SKELETON=10]="EXPECT_DATE_TIME_SKELETON",t[t.UNCLOSED_QUOTE_IN_ARGUMENT_STYLE=11]="UNCLOSED_QUOTE_IN_ARGUMENT_STYLE",t[t.EXPECT_SELECT_ARGUMENT_OPTIONS=12]="EXPECT_SELECT_ARGUMENT_OPTIONS",t[t.EXPECT_PLURAL_ARGUMENT_OFFSET_VALUE=13]="EXPECT_PLURAL_ARGUMENT_OFFSET_VALUE",t[t.INVALID_PLURAL_ARGUMENT_OFFSET_VALUE=14]="INVALID_PLURAL_ARGUMENT_OFFSET_VALUE",t[t.EXPECT_SELECT_ARGUMENT_SELECTOR=15]="EXPECT_SELECT_ARGUMENT_SELECTOR",t[t.EXPECT_PLURAL_ARGUMENT_SELECTOR=16]="EXPECT_PLURAL_ARGUMENT_SELECTOR",t[t.EXPECT_SELECT_ARGUMENT_SELECTOR_FRAGMENT=17]="EXPECT_SELECT_ARGUMENT_SELECTOR_FRAGMENT",t[t.EXPECT_PLURAL_ARGUMENT_SELECTOR_FRAGMENT=18]="EXPECT_PLURAL_ARGUMENT_SELECTOR_FRAGMENT",t[t.INVALID_PLURAL_ARGUMENT_SELECTOR=19]="INVALID_PLURAL_ARGUMENT_SELECTOR",t[t.DUPLICATE_PLURAL_ARGUMENT_SELECTOR=20]="DUPLICATE_PLURAL_ARGUMENT_SELECTOR",t[t.DUPLICATE_SELECT_ARGUMENT_SELECTOR=21]="DUPLICATE_SELECT_ARGUMENT_SELECTOR",t[t.MISSING_OTHER_CLAUSE=22]="MISSING_OTHER_CLAUSE",t[t.INVALID_TAG=23]="INVALID_TAG",t[t.INVALID_TAG_NAME=25]="INVALID_TAG_NAME",t[t.UNMATCHED_CLOSING_TAG=26]="UNMATCHED_CLOSING_TAG",t[t.UNCLOSED_TAG=27]="UNCLOSED_TAG"})(Ns||(Ns={}));var Os=class{constructor(e){console.warn(`[vite-messages-plugin]: Message "${e}" was not precompiled. Did you use the correct extenstion *.messages.ts?`)}};var Ee;(function(t){t[t.literal=0]="literal",t[t.argument=1]="argument",t[t.number=2]="number",t[t.date=3]="date",t[t.time=4]="time",t[t.select=5]="select",t[t.plural=6]="plural",t[t.pound=7]="pound",t[t.tag=8]="tag"})(Ee||(Ee={}));var Ds;(function(t){t[t.number=0]="number",t[t.dateTime=1]="dateTime"})(Ds||(Ds={}));function wi(t){return t.type===Ee.literal}function Ei(t){return t.type===Ee.argument}function po(t){return t.type===Ee.number}function go(t){return t.type===Ee.date}function mo(t){return t.type===Ee.time}function fo(t){return t.type===Ee.select}function ho(t){return t.type===Ee.plural}function id(t){return t.type===Ee.pound}function yo(t){return t.type===Ee.tag}function _s(t){return!!(t&&typeof t=="object"&&t.type===Ds.number)}function vo(t){return!!(t&&typeof t=="object"&&t.type===Ds.dateTime)}function ki(t){t.forEach(function(e){if(delete e.location,fo(e)||ho(e))for(var n in e.options)delete e.options[n].location,ki(e.options[n].value);else po(e)&&_s(e.style)||(go(e)||mo(e))&&vo(e.style)?delete e.style.location:yo(e)&&ki(e.children)})}function ad(t,e){e===void 0&&(e={}),e=xe({shouldParseSkeletons:!0,requiresOtherClause:!0},e);var n=new Os(t,e).parse();if(n.err){var o=SyntaxError(Ns[n.err.kind]);throw o.location=n.err.location,o.originalMessage=n.err.message,o}return e!=null&&e.captureLocation||ki(n.val),n.val}var tn;(function(t){t.MISSING_VALUE="MISSING_VALUE",t.INVALID_VALUE="INVALID_VALUE",t.MISSING_INTL_API="MISSING_INTL_API"})(tn||(tn={}));var So=(function(t){uo(e,t);function e(n,o,s){var r=t.call(this,n)||this;return r.code=o,r.originalMessage=s,r}return e.prototype.toString=function(){return"[formatjs Error: ".concat(this.code,"] ").concat(this.message)},e})(Error);var Ri=(function(t){uo(e,t);function e(n,o,s,r){return t.call(this,'Invalid values for "'.concat(n,'": "').concat(o,'". Options are "').concat(Object.keys(s).join('", "'),'"'),tn.INVALID_VALUE,r)||this}return e})(So);var ld=(function(t){uo(e,t);function e(n,o,s){return t.call(this,'Value for "'.concat(n,'" must be of type ').concat(o),tn.INVALID_VALUE,s)||this}return e})(So);var dd=(function(t){uo(e,t);function e(n,o){return t.call(this,'The intl string context variable "'.concat(n,'" was not provided to the string "').concat(o,'"'),tn.MISSING_VALUE,o)||this}return e})(So);var le;(function(t){t[t.literal=0]="literal",t[t.object=1]="object"})(le||(le={}));function Sm(t){return t.length<2?t:t.reduce(function(e,n){var o=e[e.length-1];return!o||o.type!==le.literal||n.type!==le.literal?e.push(n):o.value+=n.value,e},[])}function xm(t){return typeof t=="function"}function xo(t,e,n,o,s,r,i){if(t.length===1&&wi(t[0]))return[{type:le.literal,value:t[0].value}];for(var a=[],d=0,l=t;d<l.length;d++){var c=l[d];if(wi(c)){a.push({type:le.literal,value:c.value});continue}if(id(c)){typeof r=="number"&&a.push({type:le.literal,value:n.getNumberFormat(e).format(r)});continue}var p=c.value;if(!(s&&p in s))throw new dd(p,i);var u=s[p];if(Ei(c)){(!u||typeof u=="string"||typeof u=="number")&&(u=typeof u=="string"||typeof u=="number"?String(u):""),a.push({type:typeof u=="string"?le.literal:le.object,value:u});continue}if(go(c)){var g=typeof c.style=="string"?o.date[c.style]:vo(c.style)?c.style.parsedOptions:void 0;a.push({type:le.literal,value:n.getDateTimeFormat(e,g).format(u)});continue}if(mo(c)){var g=typeof c.style=="string"?o.time[c.style]:vo(c.style)?c.style.parsedOptions:o.time.medium;a.push({type:le.literal,value:n.getDateTimeFormat(e,g).format(u)});continue}if(po(c)){var g=typeof c.style=="string"?o.number[c.style]:_s(c.style)?c.style.parsedOptions:void 0;g&&g.scale&&(u=u*(g.scale||1)),a.push({type:le.literal,value:n.getNumberFormat(e,g).format(u)});continue}if(yo(c)){var m=c.children,f=c.value,y=s[f];if(!xm(y))throw new ld(f,"function",i);var v=xo(m,e,n,o,s,r),x=y(v.map(function(L){return L.value}));Array.isArray(x)||(x=[x]),a.push.apply(a,x.map(function(L){return{type:typeof L=="string"?le.literal:le.object,value:L}}))}if(fo(c)){var T=c.options[u]||c.options.other;if(!T)throw new Ri(c.value,u,Object.keys(c.options),i);a.push.apply(a,xo(T.value,e,n,o,s));continue}if(ho(c)){var T=c.options["=".concat(u)];if(!T){if(!Intl.PluralRules)throw new So(`Intl.PluralRules is not available in this environment.
2
2
  Try polyfilling it using "@formatjs/intl-pluralrules"
3
- `,tn.MISSING_INTL_API,i);var w=n.getPluralRules(e,{type:c.pluralType}).select(u-(c.offset||0));T=c.options[w]||c.options.other}if(!T)throw new wi(c.value,u,Object.keys(c.options),i);a.push.apply(a,xo(T.value,e,n,o,s,u-(c.offset||0)));continue}}return pm(a)}function mm(t,e){return e?xe(xe(xe({},t||{}),e||{}),Object.keys(t).reduce(function(n,o){return n[o]=xe(xe({},t[o]),e[o]||{}),n},{})):t}function fm(t,e){return e?Object.keys(t).reduce(function(n,o){return n[o]=mm(t[o],e[o]),n},xe({},t)):t}function Ei(t){return{create:function(){return{get:function(e){return t[e]},set:function(e,n){t[e]=n}}}}}function hm(t){return t===void 0&&(t={number:{},dateTime:{},pluralRules:{}}),{getNumberFormat:Is(function(){for(var e,n=[],o=0;o<arguments.length;o++)n[o]=arguments[o];return new((e=Intl.NumberFormat).bind.apply(e,Ps([void 0],n,!1)))},{cache:Ei(t.number),strategy:As.variadic}),getDateTimeFormat:Is(function(){for(var e,n=[],o=0;o<arguments.length;o++)n[o]=arguments[o];return new((e=Intl.DateTimeFormat).bind.apply(e,Ps([void 0],n,!1)))},{cache:Ei(t.dateTime),strategy:As.variadic}),getPluralRules:Is(function(){for(var e,n=[],o=0;o<arguments.length;o++)n[o]=arguments[o];return new((e=Intl.PluralRules).bind.apply(e,Ps([void 0],n,!1)))},{cache:Ei(t.pluralRules),strategy:As.variadic})}}var ki=(function(){function t(e,n,o,s){n===void 0&&(n=t.defaultLocale);var r=this;if(this.formatterCache={number:{},dateTime:{},pluralRules:{}},this.format=function(l){var c=r.formatToParts(l);if(c.length===1)return c[0].value;var p=c.reduce(function(u,g){return!u.length||g.type!==le.literal||typeof u[u.length-1]!="string"?u.push(g.value):u[u.length-1]+=g.value,u},[]);return p.length<=1?p[0]||"":p},this.formatToParts=function(l){return xo(r.ast,r.locales,r.formatters,r.formats,l,void 0,r.message)},this.resolvedOptions=function(){var l;return{locale:((l=r.resolvedLocale)===null||l===void 0?void 0:l.toString())||Intl.NumberFormat.supportedLocalesOf(r.locales)[0]}},this.getAst=function(){return r.ast},this.locales=n,this.resolvedLocale=t.resolveLocale(n),typeof e=="string"){if(this.message=e,!t.__parse)throw new TypeError("IntlMessageFormat.__parse must be set to process `message` of type `string`");var i=s||{},a=i.formatters,d=sd(i,["formatters"]);this.ast=t.__parse(e,xe(xe({},d),{locale:this.resolvedLocale}))}else this.ast=e;if(!Array.isArray(this.ast))throw new TypeError("A message must be provided as a String or AST.");this.formats=fm(t.formats,o),this.formatters=s&&s.formatters||hm(this.formatterCache)}return Object.defineProperty(t,"defaultLocale",{get:function(){return t.memoizedDefaultLocale||(t.memoizedDefaultLocale=new Intl.NumberFormat().resolvedOptions().locale),t.memoizedDefaultLocale},enumerable:!1,configurable:!0}),t.memoizedDefaultLocale=null,t.resolveLocale=function(e){if(typeof Intl.Locale!="undefined"){var n=Intl.NumberFormat.supportedLocalesOf(e);return n.length>0?new Intl.Locale(n[0]):new Intl.Locale(typeof e=="string"?e:e[0])}},t.__parse=ld,t.formats={number:{integer:{maximumFractionDigits:0},currency:{style:"currency"},percent:{style:"percent"}},date:{short:{month:"numeric",day:"numeric",year:"2-digit"},medium:{month:"short",day:"numeric",year:"numeric"},long:{month:"long",day:"numeric",year:"numeric"},full:{weekday:"long",month:"long",day:"numeric",year:"numeric"}},time:{short:{hour:"numeric",minute:"numeric"},medium:{hour:"numeric",minute:"numeric",second:"numeric"},long:{hour:"numeric",minute:"numeric",second:"numeric",timeZoneName:"short"},full:{hour:"numeric",minute:"numeric",second:"numeric",timeZoneName:"short"}}},t})();function ym(t,e){return e.split(".").reduce((n,o)=>n?n[o]:void 0,t)}var vm="dummy",Ri=(0,Ds.createContext)(null);function P(t){var o;let e=(0,Ds.useContext)(Ri);if(!e)throw new Error("useTranslator() may be used only in the context of a <LocaleContext> component.");let n=(o=t[e])!=null?o:{};return(s,r)=>{let i=ym(n,s);return i?new ki(i).format(r):(e!==vm&&console.warn(`${s} does not exist in messages of ${e}`),`[${s}]`)}}var Pt=require("@reduxjs/toolkit");var ud=require("marked"),_s=(t,e)=>{let n=[],o=new ud.Marked,s=r=>{r.type==="code"&&r.lang===e&&n.push(r.text)};return o.use({walkTokens:s}),o.parse(t),n};function Pi(t){return Array.isArray(t.attachments)&&t.attachments.length>0?t.attachments:Array.isArray(t.transcript)?t.transcript.flatMap(e=>{var n;return(n=e==null?void 0:e.attachments)!=null?n:[]}):[]}var pd={cues:[],threads:{},pending:[]},gd=t=>{var e;return(e=t.assistants)==null?void 0:e.cues};var md=t=>e=>{var n,o;return(o=(n=e.assistants)==null?void 0:n.threads[t])!=null?o:null},Fs=(0,Pt.createAction)("assistants/callToAction"),bo=(0,Pt.createAsyncThunk)("assistants/evaluateKnowledgeAssistant",(t,e)=>S(null,null,function*(){var l,c,p;let{threadId:n}=t,{onNewThreadId:o}=t,{deepdeskAPI:s}=e.extra,r=e.getState(),{platformVariables:i}=r.info;n||(n=(yield s.createAssistantThread({assistantCode:t.assistantCode})).id,o&&o(n)),yield s.postMessageToAssistantThread({assistantCode:t.assistantCode,threadId:n,message:t.input});let a=yield e.dispatch(he(b(h({skipState:!0},t),{input:{},threadId:n,attachments:t.attachments})));if(a.error)throw new Error(a.error.message);let d=(l=a.payload.output[0])!=null?l:{response:"",sources:[]};return{threadId:n,question:t.input,evaluationId:a.payload.evaluationId,answer:{answer:(c=De(d.response,i!=null?i:{}))!=null?c:"",sources:(p=d.sources)!=null?p:[]}}})),Gx=(0,Pt.createAction)("assistants/extractedTextSuggestions");function Sm(t,e){var n,o;return Array.isArray(t.output)?t.output:typeof t.output=="string"?[{code:e,name:e,response:t.output}]:[b(h({code:e,name:e},t.output&&typeof t.output=="object"?t.output:{}),{response:(o=(n=t.output)==null?void 0:n.response)!=null?o:""})]}var he=(0,Pt.createAsyncThunk)("assistants/evaluate",(t,e)=>S(null,null,function*(){var x,T,w,L,R;let{deepdeskAPI:n,dynamicThunkObject:o}=e.extra,{transcript:s,input:r={},threadId:i,attachments:a}=t,d=e.getState(),{platformVariables:l}=d.info,c=(T=(x=d.conversation.current)==null?void 0:x.externalId)!=null?T:null,p=(L=(w=t.externalConversationId)!=null?w:c)!=null?L:void 0,u;if(s==="in-memory-transcript"){if(!o.conversationQuery)throw new Error("Can't include in-memory-transcript, setConversationQuery is not defined");let I=yield o.conversationQuery();u=Array.isArray(I)?I:void 0}else Array.isArray(s)&&(u=s);if(t.includeMetadata&&d.conversation.current&&((R=t.externalConversationId)!=null?R:c)===c){let{metadata:z}=d.conversation.current;Object.assign(r,{metadata:z})}let g=Pi({attachments:a,transcript:u}),m=yield n.evaluateAssistant(t.assistantCode,h({input:r,transcript:u,externalConversationId:p,threadId:i},g.length>0?{attachments:g}:{}));if(m.evaluationStatus!=="success")return e.rejectWithValue(`Assistant ${t.assistantCode} evaluation failed: ${m.evaluationStatus}`);let y=Sm(m,t.assistantCode).map(I=>b(h({},I),{name:De(I.name,l),response:De(I.response,l)||""})),v=[];return y.forEach(I=>{if(!I.response)return;let z=_s(I.response,"reply");z.length!==0&&v.push(...z.map(Me=>({text:Me,type:"text",source:"assistant",assistantCode:I.code,sourceLabel:I.name})))}),v.length>0&&e.dispatch(In(v)),b(h({},m),{output:y,externalConversationId:p,currentExternalIdAtRequest:c})}));function fd(t){return t!=null&&t.length?t.map(e=>e.response).filter(Boolean).join(`
4
- `):""}var hd=(0,Pt.createSlice)({name:"assistants",initialState:pd,reducers:{resetCues(t){t.cues=[]},removeCueByCode(t,e){t.cues=t.cues.filter(n=>n.code!==e.payload.code)},removeThreadById(t,e){delete t.threads[e.payload]},receiveChunk(t,e){let{code:n,name:o,payload:s,evaluationId:r}=e.payload,i=t.cues.findIndex(a=>a.code===n);i!==-1?t.cues[i].response+=s.text:t.cues.push({code:n,name:o,evaluationId:r,response:s.text})},userNotification(t,e){let n=t.cues.find(c=>c.code===e.payload.code),o=t.cues.filter(c=>c.code!==e.payload.code),{code:s,name:r,evaluationId:i,payload:a}=e.payload,{callToAction:d}=a,l=a.sources!==void 0?a.sources.filter(c=>!!c.url):n==null?void 0:n.sources;t.cues=[...o,b(h({code:s,name:r,evaluationId:i,response:a.message,editable:a.editableMessage},l!=null&&l.length?{sources:l}:{}),{callToAction:d&&{label:d.displayName,event:d.onClickEvent,value:d.eventPayload}})]}},extraReducers:t=>{t.addCase(he.pending,(e,n)=>{e.pending.includes(n.meta.arg.assistantCode)&&k.warn(`Assistant ${n.meta.arg.assistantCode} already evaluating`),e.pending.push(n.meta.arg.assistantCode)}).addCase(he.rejected,(e,n)=>{var s;k.warn((s=n.error)==null?void 0:s.message);let o=e.pending.indexOf(n.meta.arg.assistantCode);o!==-1&&e.pending.splice(o,1)}).addCase(he.fulfilled,(e,n)=>{let o=e.pending.indexOf(n.meta.arg.assistantCode);if(o!==-1&&e.pending.splice(o,1),n.meta.arg.skipState)return;let{evaluationId:s,output:r,externalConversationId:i,currentExternalIdAtRequest:a}=n.payload;if(i&&a&&i!==a)return;let d=r.map(p=>p.code),l=e.cues.filter(p=>!d.includes(p.code)),c=r.map(p=>h(b(h({},p),{evaluationId:s}),i?{externalConversationId:i}:{}));e.cues=[...l,...c]}).addCase(bo.fulfilled,(e,n)=>{let r=n.payload,{threadId:o}=r,s=O(r,["threadId"]);e.threads[o]=[...e.threads[o]||[],s]}).addCase(Y,()=>pd)}}),{removeCueByCode:Hs,resetCues:Xx,removeThreadById:yd,receiveChunk:vd,userNotification:Sd}=hd.actions,xd=hd.reducer;var bd=require("@reduxjs/toolkit"),Cd=require("react-redux");var xm={locale:"en-US",deanonymize:!1,fallbackImage:!1,isEmbedded:!1,signInViaPopup:!1,showImages:!1,showSearch:!1,showImageSearch:!1,showStyleSuggestions:!1,showStyleSuggestionList:!1,showMidSentenceSuggestions:!1,showSuggestionsBeforePattern:!1,showSuggestionsAfterPattern:!1,showTabCompletion:!0,showTextSuggestions:!0,showEntitiesCommand:!1,showSummaryCommand:!1,showKnowledgeSearch:!1,textSuggestionsCount:3,recommendTextSuggestions:!0,searchTriggerKey:"k",visible:!0,insertLink:!1,addToPersonalCollection:!1,inlineSuggestions:!1,autoSelectSuggestion:!1,suggestionsPlacement:"above",floatingMenu:!1,detectSubmit:!1,automaticHandlingTime:!1,enableSuggestionFeedback:!1,enableFeedbackForm:!0,adminUrl:void 0,productName:"Deepdesk",hasKeyboardInput:!0},Td=(0,bd.createSlice)({name:"settings",initialState:xm,reducers:{set(t,e){Object.entries(e.payload).forEach(n=>{let[o,s]=n;typeof s!="undefined"&&(t[o]=s)})}}}),{set:Bs}=Td.actions,nn=t=>e=>e.settings[t],E=t=>(0,Cd.useSelector)(nn(t)),wd=Td.reducer;function $e(t){let e=document.createElement("textarea");e.value=t,e.style.position="fixed",e.style.left="-999999px",e.style.top="-999999px",document.body.appendChild(e),e.focus(),e.select(),document.execCommand("copy"),e.remove()}var Ks=D(require("classnames")),Rd=require("react");var Ii=require("react/jsx-runtime"),Ai=t=>(0,Ii.jsx)("svg",b(h({width:"16",height:"16",fill:"#000000"},t),{viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,Ii.jsx)("path",{fillRule:"evenodd",d:"M6.57086468,14.9173453 C6.38997052,14.9711236 6.19835748,15 6,15 L4,15 C2.8954305,15 2,14.1045695 2,13 L2,4 C2,2.8954305 2.8954305,2 4,2 L6,2 C6.68685475,2 7.29284112,2.34623869 7.65294381,2.87370078 C7.95642355,2.67736738 8.29504785,2.51351337 8.66312366,2.3818197 C9.50544052,2.08044754 10.3408482,1.9879107 10.9989281,1.99971266 C11.0150698,2.00005426 13.3487605,2.00015005 18,2 C20.7551411,2 22,6.05643086 22,12 C22,13.6824804 20.8695981,15 19,15 L15.9269768,15 C15.9359266,15.0245465 15.9451954,15.0497804 15.9547911,15.0757271 C16.007193,15.2174219 16.2391583,15.8256341 16.2970775,15.9810953 C16.4872151,16.4914441 16.6259612,16.9026411 16.7382242,17.3098712 C16.9079007,17.9253665 17,18.4798886 17,19 C17,20.4720069 16.091867,21.3862822 14.748281,21.777514 C14.1422801,21.9539723 13.6147967,22.0000922 13.0076976,22.0000008 L12.5204954,22 L12.2202699,21.6261158 C11.2556275,20.4248034 7.64562469,16.4822788 6.57086468,14.9173453 Z M8,13 C8,13.2401953 8.04443154,13.4528921 8.14171093,13.6800176 C8.40663864,14.2985643 11.914268,18.1371493 13.4599624,19.9848695 C13.7113931,19.9660111 13.9483736,19.9273712 14.1891338,19.8572655 C14.7621788,19.6904035 15,19.4509737 15,19 C15,18.6834183 14.9359344,18.2976852 14.8101464,17.8413935 C14.7161494,17.500423 14.5944107,17.1396301 14.4229225,16.6793379 C14.3689242,16.5344009 14.1358033,15.923159 14.0789589,15.7694517 C13.9489218,15.4178313 13.8632547,15.1589343 13.8046536,14.9236885 C13.5555377,13.9236468 13.8054549,13 15,13 L19,13 C19.6912225,13 20,12.6401099 20,12 C20,7.20925475 19.015127,4 18,4 C15.9322103,4 15.9322103,4 10.9655994,3.99940813 C10.5253746,3.99154158 9.91062406,4.05963657 9.33687634,4.2649175 C8.45196659,4.58152894 8,5.09776992 8,6 L8,13 Z M4,4 L4,13 L6,13 L6,4 L4,4 Z"})}));var Li=require("react/jsx-runtime"),Ed=t=>(0,Li.jsx)("svg",b(h({width:"16",height:"16",fill:"#000000"},t),{viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,Li.jsx)("path",{fillRule:"evenodd",d:"M7.65336736,21.1256786 C7.2933164,21.6534897 6.68712411,22 6,22 L4,22 C2.8954305,22 2,21.1045695 2,20 L2,11 C2,9.8954305 2.8954305,9 4,9 L6,9 C6.198171,9 6.38961023,9.02882212 6.57035446,9.08250314 C7.6444817,7.51807482 11.2554748,3.57449216 12.2202699,2.37298955 L12.5204954,1.99910538 L13,1.99910538 C13.6147967,1.99901314 14.1422801,2.04513312 14.748281,2.22159137 C16.091867,2.61282321 17,3.52709845 17,4.99910538 C17,5.51921677 16.9079007,6.07373891 16.7382242,6.68923415 C16.6259612,7.09646424 16.4872151,7.50766133 16.2970775,8.01801005 C16.2391583,8.17347129 16.007193,8.78168345 15.9547911,8.92337824 C15.9451954,8.94932503 15.9359266,8.9745589 15.9269768,8.99910538 L19,8.99910538 C20.8695981,8.99910538 22,10.316625 22,11.9991054 C22,17.9426745 20.7551411,21.9991054 18,21.9991054 L11.0344006,21.9985135 C10.3408482,22.0111947 9.50544052,21.9186578 8.66312366,21.6172857 C8.29521907,21.4856533 7.9567386,21.3218904 7.65336736,21.1256786 Z M8,17.9991054 C8,18.9013355 8.45196659,19.4175764 9.33687634,19.7341879 C9.91062406,19.9394688 10.5253746,20.0075638 10.963066,19.9997143 C10.9703499,19.9995545 10.9703499,19.9995545 11,19.9991054 L18,19.9991054 C19.015127,19.9991054 20,16.7898506 20,11.9991054 C20,11.3589955 19.6912225,10.9991054 19,10.9991054 L15,10.9991054 C13.8054549,10.9991054 13.5555377,10.0754586 13.8046536,9.07541689 C13.8632547,8.84017106 13.9489218,8.5812741 14.0789589,8.22965366 C14.1358033,8.07594642 14.3689242,7.46470447 14.4229225,7.31976744 C14.5944107,6.85947528 14.7161494,6.4986824 14.8101464,6.1577119 C14.9359344,5.70142019 15,5.31568707 15,4.99910538 C15,4.54813166 14.7621788,4.30870189 14.1891338,4.1418399 C13.9483736,4.07173418 13.7113931,4.0330943 13.4599624,4.01423587 C11.914268,5.86195611 8.40663864,9.70054105 8.14171093,10.3190878 C8.04443154,10.5462133 8,10.7589101 8,10.9991054 L8,17.9991054 Z M4,11 L4,20 L6,20 L6,11 L4,11 Z"})}));function It(t,e){var s;let n=t.cloneNode(!0);n.style.top=`${t.offsetTop}px`,n.style.left=`${t.offsetLeft}px`,n.style.position="absolute",e.split(" ").forEach(r=>{n.classList.add(r)}),n.addEventListener("animationend",()=>n.remove()),(s=t.parentElement)==null||s.appendChild(n)}var Mi={};Z(Mi,{enUS:()=>bm,nlNL:()=>Cm});var bm={thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}]},Cm={thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}]};var kd={thumbs:"dd-5F1zq",fadeup:"dd-eTmY-",fadedown:"dd-sS85z",selected:"dd-rid-f",thumbsUp:"dd-4poEf",thumbsDown:"dd-3KozS"};var Oi=require("react-redux");var At=t=>e=>{let{passwordlessToken:{token:n},settings:{isEmbedded:o,adminUrl:s}}=e,r=s||window.location.origin;return o&&!n?null:o&&n?`${r}/apis/admin/session/passwordless/login/?token=${n}&redirect=${encodeURIComponent(t)}`:`${r}${t}`};var Ni=({conversationId:t,evaluationId:e,type:n,assistantCode:o,contentType:s},r,i)=>{let a=new URLSearchParams;return t!=null&&a.set("conversationId",String(t)),e&&a.set("evaluationId",e),a.set("type",n),o&&a.set("assistantCode",o),a.set(s,r),i!==void 0&&a.set("data",i),`/admin/feedback?${a.toString()}`},Us=t=>{let e=t.content,n=t.data,o=Ni(t,e,n),s=encodeURIComponent(o).length;for(;s>3e3&&e.length>0;){let r=Math.max(0,Math.floor(e.length*3e3/s)-1);e=t.content.slice(0,r),o=Ni(t,e?`${e}\u2026`:"",n),s=encodeURIComponent(o).length}for(;s>3e3&&n&&n.length>0;){let r=Math.max(0,Math.floor(n.length*3e3/s)-1);n=n.slice(0,r),o=Ni(t,e,n?`${n}\u2026`:""),s=encodeURIComponent(o).length}return o};var at=require("react/jsx-runtime"),Tm=({assistantCode:t,assistantOutput:e,evaluationId:n,feedbackType:o})=>{let s=C("FeedbackThumbs",kd),r=E("enableFeedbackForm"),i=(0,Oi.useSelector)(je),a=(0,Oi.useSelector)(At(Us({conversationId:i,evaluationId:n,type:o,assistantCode:t,contentType:"assistantOutput",content:e}))),d=P(Mi),l=q(),[c,p]=(0,Rd.useState)(null),u=f=>{l("Assistant response feedback",{assistantCode:t,assistantOutput:e,evaluationId:n,rating:f})},g=f=>{f.stopPropagation(),It(f.target,s.fadeup),p("up"),u("up")},m=f=>{f.stopPropagation(),It(f.target,s.fadedown),p("down"),u("down")};return(0,at.jsxs)("div",{className:s.thumbs,children:[(0,at.jsx)(M.Button,{title:d("thumbsUp"),onClick:g,icon:(0,at.jsx)(Ed,{}),className:(0,Ks.default)(s.thumbsUp,c==="up"&&s.selected),disabled:!!c}),r&&a?(0,at.jsx)(M.Button,{as:"a",title:d("thumbsDown"),href:a,target:"_blank",rel:"noreferrer",onClick:m,icon:(0,at.jsx)(Ai,{}),className:(0,Ks.default)(s.thumbsDown,c==="down"&&s.selected),disabled:!!c}):(0,at.jsx)(M.Button,{title:d("thumbsDown"),onClick:m,icon:(0,at.jsx)(Ai,{}),className:(0,Ks.default)(s.thumbsDown,c==="down"&&s.selected),disabled:!!c})]})},Ws=Tm;var Ud=D(require("dompurify")),Kd=require("marked"),ct=require("react");var Ld=require("react");var U=require("@floating-ui/react"),qe=D(require("react"));var zs={tooltip:"dd-XpCXd",tooltipTrigger:"dd-8TKeF",arrow:"dd-ZEu2Y"};var ke=require("react/jsx-runtime");function wm({initialOpen:t=!1,placement:e="bottom",modal:n,tooltip:o,open:s,onOpenChange:r}={}){let[i,a]=qe.useState(t),d=s!=null?s:i,l=r!=null?r:a,c=(0,U.useFloating)({placement:e,open:d,onOpenChange:l,whileElementsMounted:U.autoUpdate,middleware:[(0,U.offset)(5),(0,U.flip)({crossAxis:e.includes("-"),fallbackAxisSideDirection:"end",padding:5}),(0,U.shift)({padding:10})]}),p=c.context,u=(0,U.useClick)(p,{enabled:s==null}),g=(0,U.useDismiss)(p),m=(0,U.useRole)(p),f=(0,U.useHover)(p,{enabled:o!=null?o:!1,handleClose:(0,U.safePolygon)()}),y=(0,U.useInteractions)([u,g,m,f]);return qe.useMemo(()=>b(h(h({open:d,setOpen:l},y),c),{modal:n}),[d,l,y,c,n])}var Pd=qe.createContext(null),Di=()=>{let t=qe.useContext(Pd);if(t==null)throw new Error("Popover components must be wrapped in <Popover />");return t},on=o=>{var s=o,{children:t,modal:e=!1}=s,n=O(s,["children","modal"]);let r=wm(h({modal:e},n));return(0,ke.jsx)(Pd.Provider,{value:r,children:t})};function Em(o){var s=o,{as:t,children:e}=s,n=O(s,["as","children"]);let r=Di(),i=t||"button",a=e.ref,d=(0,U.useMergeRefs)([r.refs.setReference,a]);return(0,ke.jsx)(i,b(h(h({ref:d},i==="button"||t===void 0||t==="button"?{type:"button"}:{}),r.getReferenceProps(n)),{children:e}))}var km=qe.forwardRef(function(s,o){var r=s,{style:e}=r,n=O(r,["style"]);let l=Di(),{context:i}=l,a=O(l,["context"]),d=(0,U.useMergeRefs)([a.refs.setFloating,o]);return i.open?(0,ke.jsx)(U.FloatingPortal,{children:(0,ke.jsx)(U.FloatingFocusManager,{context:i,modal:a.modal,disabled:n.disableFocusManager,children:(0,ke.jsx)("div",b(h({ref:d,style:h(b(h({},a.floatingStyles),{zIndex:1e7}),e)},a.getFloatingProps(n)),{children:n.children}))})}):null});function Rm(s){var r=s,{as:t,children:e,onClick:n}=r,o=O(r,["as","children","onClick"]);let{setOpen:i}=Di();return(0,ke.jsx)(t||"button",b(h({type:"button",onClick:l=>{n(l),i(!1),l.stopPropagation()}},o),{children:e}))}function Id({trigger:t,children:e,placement:n="top"}){return(0,ke.jsxs)(on,{tooltip:!0,placement:n,children:[(0,ke.jsxs)(on.Content,{className:zs.tooltip,children:[e,(0,ke.jsx)("div",{className:zs.arrow})]}),(0,ke.jsx)(on.Trigger,{className:zs.tooltipTrigger,children:t})]})}on.Trigger=Em;on.Content=km;on.Button=Rm;var j=on;var _i={};Z(_i,{enUS:()=>Pm,nlNL:()=>Im});var Pm={showMore:[{type:0,value:"Show "},{type:1,value:"amount"},{type:0,value:" more"}]},Im={showMore:[{type:0,value:"Toon "},{type:1,value:"amount"},{type:0,value:" meer"}]};var Ad={sources:"dd-cNsGl",source:"dd-LoJ6U",tooltip:"dd-7ZGu9",linkContent:"dd-O2IoN",showMoreSources:"dd-ev8Yr"};var lt=require("react/jsx-runtime"),Am=3,Lm=({sources:t,onClick:e,sourceTestId:n="assistant-source"})=>{let o=P(_i),s=C("AssistantSources",Ad),[r,i]=(0,Ld.useState)(!1),a=t.filter(l=>!!l.url),d=r?a:a.slice(0,Am);return d.length===0?null:(0,lt.jsxs)("ul",{className:s.sources,children:[d.map(l=>(0,lt.jsx)("li",{className:s.source,"data-testid":n,children:(0,lt.jsxs)(j,{tooltip:!0,placement:"top-start",children:[(0,lt.jsx)(j.Trigger,{as:"a",rel:"noreferrer",target:"_blank",href:l.url,onClick:c=>{c.stopPropagation(),e==null||e(l)},children:(0,lt.jsx)("span",{className:s.linkContent,children:l.name})}),l.url&&(0,lt.jsx)(j.Content,{className:s.tooltip,children:decodeURIComponent(l.url)})]})},l.name)),d.length<t.length&&(0,lt.jsx)("button",{type:"button",className:s.showMoreSources,onClick:()=>i(!0),children:o("showMore",{amount:t.length-d.length})})]})},Md=Lm;var Hi=D(require("classnames")),Re=require("react");var Vs=require("react"),Mm=["bottom","height","left","right","top","width"],Nm=(t={},e={})=>Mm.some(n=>t[n]!==e[n]),dt=new Map,Nd,Od=()=>{let t=[],e=[];dt.forEach((n,o)=>{if(o instanceof Element&&!o.isConnected){e.push(o);return}let s=o.getBoundingClientRect();Nm(s,n.rect)&&(n.rect=s,t.push(n))}),e.forEach(n=>{dt.delete(n)}),t.forEach(n=>{n.callbacks.forEach(o=>o(n.rect))}),Nd=window.requestAnimationFrame(Od)};function Om(t,e){return{observe(){let n=dt.size===0;if(dt.has(t)){let o=dt.get(t);o.callbacks.push(e),o.rect&&e(o.rect)}else dt.set(t,{rect:void 0,hasRectChanged:!1,callbacks:[e]});n&&Od()},unobserve(){let n=dt.get(t);if(n){let o=n.callbacks.indexOf(e);o>=0&&n.callbacks.splice(o,1),n.callbacks.length||dt.delete(t),dt.size||cancelAnimationFrame(Nd)}}}}function Fi(t){let[e,n]=(0,Vs.useState)(null);return(0,Vs.useLayoutEffect)(()=>{if(!t.current)return;let o=Om(t.current,s=>{n(s)});return o.observe(),()=>{o.unobserve()}},[t]),e}var Dn=require("react"),Fd=require("react-dom");var Dd=require("react");function Lt(t){(0,Dd.useEffect)(()=>{let e=n=>{n.isWithinRoot||t(n)};return document.body.addEventListener("mouseup",e),()=>{document.body.removeEventListener("mouseup",e)}},[t])}function sn(t){t.addEventListener("mouseup",e=>{e.isWithinRoot=!0},!0)}var _d={root:"dd-r-dgo"};var Hd=({children:t,parentNode:e})=>{let[n,o]=(0,Dn.useState)(null),s=(0,Dn.useContext)(no);return(0,Dn.useLayoutEffect)(()=>{let r=document.createElement("div");return sn(r),r.classList.add(_d.root),s!=null&&s.portalRootNode&&r.classList.add(s==null?void 0:s.portalRootNode),(e||document.body).appendChild(r),o(r),()=>{r.isConnected&&r.remove()}},[]),n?(0,Fd.createPortal)(t,n):null};var Ge={ref:"dd-iz-KP",root:"dd-vEMon",positionAbove:"dd-mUCxM",positionBelow:"dd-7oZI7",positionLeft:"dd-BiWvD",positionRight:"dd-JIWea",alignStart:"dd-5ivu6",alignCenter:"dd-rnVkP",alignEnd:"dd-gZBp4"};var js=require("react/jsx-runtime"),$s=(t=!1)=>{let[e,n]=(0,Re.useState)(t),o=(0,Re.useCallback)(()=>n(!0),[]),s=(0,Re.useCallback)(()=>n(!1),[]),r=(0,Re.useCallback)(()=>n(a=>!a),[]),i=(0,Re.useRef)(null);return{opened:e,open:o,close:s,toggle:r,triggerRef:i}};function Bi(t,e=null,n=0){if(!t)return{display:"none"};let o=e?t.top-e.top<0||t.top<e.top-n?e.top-n:t.top+t.height>e.top+e.height+n?e.top+e.height+n-t.height:t.top:t.top,s=e?t.left<e.left-n?e.left-n:t.left+t.width>e.left+e.width+n?e.left+e.width+n-t.width:t.left:t.left;return{top:o,left:s,height:t.height,width:t.width}}var _n=l=>{var c=l,{className:t,triggerRef:e,boundaryRef:n=(0,Re.createRef)(),position:o="above",align:s="center",children:r,toStyle:i=Bi,parentNode:a}=c,d=O(c,["className","triggerRef","boundaryRef","position","align","children","toStyle","parentNode"]);let p=Fi(e),u=Fi(n),g=(0,Re.useMemo)(()=>i(p,u,0),[p,u]);return(0,js.jsx)(Hd,{parentNode:a,children:(0,js.jsx)("div",b(h({className:(0,Hi.default)(Ge.ref,{[Ge.positionAbove]:o==="above",[Ge.positionBelow]:o==="below",[Ge.positionLeft]:o==="left",[Ge.positionRight]:o==="right",[Ge.alignStart]:s==="start",[Ge.alignCenter]:s==="center",[Ge.alignEnd]:s==="end"}),style:g},d),{role:"dialog",children:(0,js.jsx)("div",{className:(0,Hi.default)(t,Ge.root),children:r})}))})};var Bd={root:"dd-L7b3z",popover:"dd-OQOTB",options:"dd-Y12RE",arrow:"dd-cv33T",copyIcon:"dd-6xOsH",option:"dd-9oFX4",divider:"dd-aiZf8",fadeup:"dd-Jq9pd"};var Pe=require("react/jsx-runtime");function Dm(t){return`<button type="button" data-copy-icon class=${t}><svg version="1.1" x="0px" y="0px" viewBox="0 0 115.77 122.88" width="10px" height="10px" fill="black"><g><path d="M89.62,13.96v7.73h12.19h0.01v0.02c3.85,0.01,7.34,1.57,9.86,4.1c2.5,2.51,4.06,5.98,4.07,9.82h0.02v0.02 v73.27v0.01h-0.02c-0.01,3.84-1.57,7.33-4.1,9.86c-2.51,2.5-5.98,4.06-9.82,4.07v0.02h-0.02h-61.7H40.1v-0.02 c-3.84-0.01-7.34-1.57-9.86-4.1c-2.5-2.51-4.06-5.98-4.07-9.82h-0.02v-0.02V92.51H13.96h-0.01v-0.02c-3.84-0.01-7.34-1.57-9.86-4.1 c-2.5-2.51-4.06-5.98-4.07-9.82H0v-0.02V13.96v-0.01h0.02c0.01-3.85,1.58-7.34,4.1-9.86c2.51-2.5,5.98-4.06,9.82-4.07V0h0.02h61.7 h0.01v0.02c3.85,0.01,7.34,1.57,9.86,4.1c2.5,2.51,4.06,5.98,4.07,9.82h0.02V13.96L89.62,13.96z M79.04,21.69v-7.73v-0.02h0.02 c0-0.91-0.39-1.75-1.01-2.37c-0.61-0.61-1.46-1-2.37-1v0.02h-0.01h-61.7h-0.02v-0.02c-0.91,0-1.75,0.39-2.37,1.01 c-0.61,0.61-1,1.46-1,2.37h0.02v0.01v64.59v0.02h-0.02c0,0.91,0.39,1.75,1.01,2.37c0.61,0.61,1.46,1,2.37,1v-0.02h0.01h12.19V35.65 v-0.01h0.02c0.01-3.85,1.58-7.34,4.1-9.86c2.51-2.5,5.98-4.06,9.82-4.07v-0.02h0.02H79.04L79.04,21.69z M105.18,108.92V35.65v-0.02 h0.02c0-0.91-0.39-1.75-1.01-2.37c-0.61-0.61-1.46-1-2.37-1v0.02h-0.01h-61.7h-0.02v-0.02c-0.91,0-1.75,0.39-2.37,1.01 c-0.61,0.61-1,1.46-1,2.37h0.02v0.01v73.27v0.02h-0.02c0,0.91,0.39,1.75,1.01,2.37c0.61,0.61,1.46,1,2.37,1v-0.02h0.01h61.7h0.02 v0.02c0.91,0,1.75-0.39,2.37-1.01c0.61-0.61,1-1.46,1-2.37h-0.02V108.92L105.18,108.92z"/></g></svg></button>`}function Ui(t){var n,o;let e=t.cloneNode(!0);return e.querySelectorAll("div,button").forEach(s=>s.remove()),(o=(n=e.textContent)==null?void 0:n.trim())!=null?o:""}function _m(t){return t.replace(/\r\n/g,`
5
- `)}var Fm=({content:t,useLabel:e,copyLabel:n,onCopy:o,onUse:s,sources:r,onSourceClick:i})=>{let a=C("Markdown",Bd),d=(0,ct.useRef)(null),[l,c]=(0,ct.useState)(null),p=(0,ct.useMemo)(()=>{let v=Kd.marked.parse(_m(t));return Ud.default.sanitize(v.toString()).replaceAll("</code>",`${Dm(a.copyIcon)}</code>`).replaceAll('<a href="','<a target="_blank" rel="noreferrer noopener" href="')},[t]),u=v=>{var w;let x=v.target,T=!!((w=d.current)!=null&&w.querySelector("code"));if(["A","BUTTON"].includes(x.tagName)){c(null);return}l||T&&x.tagName!=="CODE"||!T&&x!==d.current||(x.addEventListener("mouseleave",()=>c(null),{once:!0}),c(x))},g=()=>{if(!l)return;c(null);let v=l.querySelector("button");v&&(It(v,a.fadeup),o==null||o(Ui(l)))},m=v=>{let x=v.target,T=x instanceof HTMLElement?x:null;if(x instanceof Element?x.closest("a"):null){v.stopPropagation();return}T&&"copyIcon"in T.dataset&&(It(T,a.fadeup),o==null||o(Ui(T.parentElement)))},f=()=>{!l||!s||(c(null),s(Ui(l)))},y=v=>{if(v===null)return;let x=v.getBoundingClientRect();x.left<0?v.style.transform=`translateX(${-x.left+2}px)`:x.right>window.innerWidth&&(v.style.transform=`translateX(${window.innerWidth-x.right-2}px)`)};return(0,Pe.jsxs)(ct.Fragment,{children:[l&&(o||s)&&(0,Pe.jsxs)(_n,{triggerRef:{current:l},className:a.popover,parentNode:l,children:[(0,Pe.jsxs)("div",{className:a.options,ref:y,children:[o&&(l==null?void 0:l.tagName)==="CODE"&&(0,Pe.jsx)("button",{type:"button",className:a.option,onClick:g,children:n}),s&&(0,Pe.jsxs)(ct.Fragment,{children:[(0,Pe.jsx)("div",{className:a.divider}),(0,Pe.jsx)("button",{type:"button",className:a.option,onClick:f,children:e})]})]}),(0,Pe.jsx)("div",{className:a.arrow})]}),(0,Pe.jsx)("div",{ref:d,"data-testid":"widget-markdown-content",className:a.root,dangerouslySetInnerHTML:{__html:p},onMouseOver:u,onClick:m}),r&&r.length>0&&(0,Pe.jsx)(Md,{sources:r,onClick:i})]})},rn=Fm;var Vd=require("react");var Wd={loadingBar:"dd-6as-V",placeHolderShimmer:"dd-TFYmA"};var zd=require("react/jsx-runtime"),Hm=({width:t})=>{let e=C("LoadingProgressBar",Wd);return(0,zd.jsx)("div",{className:e.loadingBar,style:{width:t}})},qs=Hm;var ut=require("react/jsx-runtime"),Gs=({title:t})=>{let e=(0,Vd.useRef)(null);return ls(e),(0,ut.jsx)(M,{ref:e,children:(0,ut.jsx)(H,{children:(0,ut.jsxs)(H.Content,{children:[(0,ut.jsx)(H.Title,{children:t}),(0,ut.jsx)(qs,{width:"60%"}),(0,ut.jsx)(qs,{width:"90%"}),(0,ut.jsx)(qs,{width:"50%"})]})})})};var Fn={};Z(Fn,{enUS:()=>Bm,nlNL:()=>Um});var Bm={inputPlaceholder:[{type:0,value:"What is your question?"}],useCue:[{type:0,value:"Add to message"}],copyCue:[{type:0,value:"Copy"}],removeCue:[{type:0,value:"Close"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}],submitLabel:[{type:0,value:"Submit"}],resetLabel:[{type:0,value:"Reset"}],showMore:[{type:0,value:"Show "},{type:1,value:"amount"},{type:0,value:" more"}]},Um={inputPlaceholder:[{type:0,value:"Wat is je vraag?"}],useCue:[{type:0,value:"Voeg toe aan bericht"}],copyCue:[{type:0,value:"Kopi\xEBren"}],removeCue:[{type:0,value:"Sluiten"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}],submitLabel:[{type:0,value:"Verzend"}],resetLabel:[{type:0,value:"Gesprek wissen"}],showMore:[{type:0,value:"Toon "},{type:1,value:"amount"},{type:0,value:" meer"}]};var Xs={form:"dd-pleCH",formInput:"dd-pGJMY",formSubmit:"dd--gkRg",actionButton:"dd-I2NEH",resetContainer:"dd-qKIDX",sources:"dd-xf9c6",source:"dd-a-vyX",tooltip:"dd-EsgcZ",linkContent:"dd-gARDA",showMoreSources:"dd-uDGi-"};var $d=require("react");var jd={error:"dd-CoAuB"};var Ki={};Z(Ki,{enUS:()=>Km,nlNL:()=>Wm});var Km={errorPrefix:[{type:0,value:"Error:"}]},Wm={errorPrefix:[{type:0,value:"Foutmelding:"}]};var Co=require("react/jsx-runtime"),qd=({message:t})=>{let e=(0,$d.useRef)(null),n=C("WidgetCardError",jd),o=P(Ki);return ls(e),(0,Co.jsx)(M,{ref:e,children:(0,Co.jsx)(H,{children:(0,Co.jsxs)(H.Content,{className:n.error,children:[o("errorPrefix")," ",t]})})})};var _=require("react/jsx-runtime"),zm=3,Vm=({sources:t,onClick:e})=>{let n=P(Fn),o=C("WidgetKnowledgeAssistant",Xs),[s,r]=(0,G.useState)(!1),i=s?t:t.slice(0,zm);return i.length===0?null:(0,_.jsxs)("ul",{className:o.sources,children:[i.map(a=>(0,_.jsx)("li",{className:o.source,"data-testid":"knowledge-assist-source",children:(0,_.jsxs)(j,{tooltip:!0,placement:"top-start",children:[(0,_.jsx)(j.Trigger,{as:"a",rel:"noreferrer",target:"_blank",href:a.url,onClick:d=>{d.stopPropagation(),e(a)},children:(0,_.jsx)("span",{className:o.linkContent,children:a.name})}),a.url&&(0,_.jsx)(j.Content,{className:o.tooltip,children:decodeURIComponent(a.url)})]})},a.name)),i<t&&(0,_.jsx)("button",{type:"button",className:o.showMoreSources,onClick:()=>r(!0),children:n("showMore",{amount:t.length-i.length})})]})},jm=({title:t,description:e})=>(0,_.jsx)(M,{"data-testid":"knowledge-assist-empty-state",children:(0,_.jsx)(H,{children:(0,_.jsxs)(H.Content,{children:[(0,_.jsx)(H.Title,{children:t}),(0,_.jsx)(rn,{content:e})]})})}),$m=({innerRef:t,item:e,hasKeyboardInput:n,onCopy:o,onUse:s,onSourceClick:r})=>{var d;let i=P(Fn),a=(0,G.useContext)(Qs);return(0,_.jsxs)(M,{"data-testid":"knowledge-assist-answer",ref:t,children:[(0,_.jsx)(H,{children:(0,_.jsxs)(H.Content,{children:[(0,_.jsx)(H.Title,{children:e.question}),(0,_.jsx)(rn,{content:e.answer.answer,useLabel:i("useCue"),copyLabel:i("copyCue"),onCopy:o,onUse:n?s:void 0}),(0,_.jsx)(Vm,{sources:(d=e.answer.sources)!=null?d:[],onClick:r})]})}),a.assistantCode&&(0,_.jsxs)(M.ButtonsContainer,{children:[(0,_.jsx)("div",{}),(0,_.jsx)(Ws,{evaluationId:e.evaluationId,feedbackType:"assistant",assistantCode:a.assistantCode,assistantOutput:e.answer.answer})]})]})},Qs=(0,G.createContext)(null),Zs=({assistantCode:t,evaluateKnowledgeAssistFn:e,initialQuestion:n,children:o})=>{let[s,r]=(0,G.useState)(null),[i,a]=(0,G.useState)(!1),[d,l]=(0,G.useState)(null),[c,p]=(0,G.useState)(!!n),[u,g]=(0,G.useState)(null),m=(0,Js.useDispatch)(),f=q(),y=Rs(T=>{if(!t)throw new Error("No knowledge assistant was defined");return l(null),e({assistantCode:t,input:T,threadId:s,onNewThreadId(w){r(w)}})},{onSuccess(T){var w;f("Assistant response displayed",{evaluationId:T.evaluationId,assistantCode:t,assistantOutput:T.answer.answer,input:T.question,sources:(w=T.answer.sources)!=null?w:[]}),p(!1)},onError(T){var w;l((w=T.message)!=null?w:"Unknown error")}}),v=T=>S(null,null,function*(){a(!0),g(T),yield y.call(T),a(!1),g(null)}),x={isEnabled:!!t,assistantCode:t,isSubmitting:i,threadId:s,pendingInput:u,errorMessage:d,onSubmit:v,onReset(){s&&m(yd(s)),l(null),r(null),t&&f("Assistant thread reset",{threadId:s!=null?s:void 0,assistantCode:t})}};return(0,G.useEffect)(()=>{n&&x.isEnabled&&v(n)},[n]),(0,_.jsx)(Qs.Provider,{value:x,children:o})},Ys=()=>{let t=P(Fn),e=C("WidgetKnowledgeAssistant",Xs),n=(0,G.useContext)(Qs),o=(0,G.useRef)(null),[s,r]=(0,G.useState)(""),i=d=>{r(d.target.value)},a=d=>{d.preventDefault(),n.onSubmit(s).then(()=>{var l;o.current&&((l=o.current)==null||l.focus(),r(""))})};return n.isEnabled?(0,_.jsxs)("form",{className:e.form,onSubmit:a,children:[(0,_.jsx)("input",{ref:o,className:e.formInput,placeholder:t("inputPlaceholder"),type:"text",disabled:n.isSubmitting,value:s,onChange:i}),(0,_.jsx)("button",{type:"submit",disabled:n.isSubmitting||s==="",className:e.formSubmit,children:t("submitLabel")})]}):null},er=({title:t,emptyState:e})=>{var m,f;let n=P(Fn),o=q(),s=C("WidgetKnowledgeAssistant",Xs),r=(0,G.useRef)(null),i=(0,G.useContext)(Qs),a=(f=(0,Js.useSelector)(md((m=i.threadId)!=null?m:-1)))!=null?f:[],d=E("hasKeyboardInput"),l=fe(),c=(y,v)=>{$e(y),i.assistantCode&&o("Assistant response copied",{assistantCode:i.assistantCode,assistantOutput:y,copiedText:y,evaluationId:v.evaluationId})},p=(y,v)=>{i.assistantCode&&o("Assistant source clicked",{evaluationId:v.evaluationId,assistantCode:i.assistantCode,source:y})},u=y=>{y.preventDefault(),i.onReset()},g=(y,v)=>{l.send(rt,{text:y,suggestion:{source:"assistant",sourceText:y}}),i.assistantCode&&o("Assistant response used",{assistantCode:i.assistantCode,evaluationId:v.evaluationId,assistantOutput:v.answer.answer,usedText:y})};return!i.isEnabled||(a==null?void 0:a.length)===0&&!i.isSubmitting&&!e&&!i.errorMessage?null:(0,_.jsxs)(G.Fragment,{children:[(0,_.jsx)(ze,{type:"knowledge",title:t,"data-testid":"knowledge",children:(0,_.jsxs)(oe,{withDivider:!0,children:[e&&a.length===0&&!i.pendingInput&&(0,_.jsx)(jm,h({},e)),a.map((y,v)=>(0,_.jsx)($m,{innerRef:v===a.length-1?r:void 0,item:y,hasKeyboardInput:d,onCopy:x=>c(x,y),onUse:x=>g(x,y),onSourceClick:x=>p(x,y)},`${y.question}_${y.answer}_${v}`)),i.pendingInput&&(0,_.jsx)(Gs,{title:i.pendingInput}),i.errorMessage&&(0,_.jsx)(qd,{message:i.errorMessage})]})}),a.length>0&&(0,_.jsx)("div",{className:s.resetContainer,children:(0,_.jsx)(M.Button,{disabled:i.threadId===null||i.isSubmitting,onClick:u,children:n("resetLabel")})})]})};var bt=require("react-dom/client");var Wc=require("react");var Vi=require("react-redux");var nr=D(require("classnames")),Fe=require("react"),or=require("react-redux");var tr=require("react");var Xd={root:"dd-tvkOF",content:"dd-eXA1D"};var Wi=require("react/jsx-runtime"),qm=({isOpen:t,autoFocus:e,children:n,onClose:o,onBack:s,onKeyDown:r,overlayAriaLabel:i,contentAriaLabel:a})=>{let d=(0,tr.useRef)(null),l=C("Dialog",Xd),c=u=>{if(u.key==="Escape"){u.preventDefault(),u.stopPropagation(),s();return}r&&r(u)},p=u=>{u.target===d.current&&t&&o()};return(0,tr.useEffect)(()=>{var u,g;!d.current||!t||!e||(g=(u=d.current)==null?void 0:u.querySelector("input, textarea"))==null||g.focus()},[t,e,d]),t?(0,Wi.jsx)("div",{role:"dialog","data-testid":"dialog",className:l.root,"aria-label":i,ref:d,onKeyDown:c,onMouseDown:p,children:(0,Wi.jsx)("div",{"data-testid":"dialog-content",className:l.content,"aria-label":a,children:n})}):null},Hn=qm;var Qd=D(require("classnames"));var Jd={root:"dd-ranhW"};var Zd=require("react/jsx-runtime"),Gm=o=>{var s=o,{className:t,value:e}=s,n=O(s,["className","value"]);let r=C("TextInput",Jd);return(0,Zd.jsx)("input",h({className:(0,Qd.default)(t,r.root),type:"text",value:e},n))},To=Gm;var zi={};Z(zi,{enUS:()=>Xm,nlNL:()=>Jm});var Xm={back:[{type:0,value:"Back"}],promptTitle:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],verifyCodeTitle:[{type:0,value:"Paste the code from your email"}],verifyCodeBody:[{type:0,value:"Copy the code from the email you just received and paste it here."}],verifyCodeInputPlaceholder:[{type:0,value:"Paste link or code here"}],verifyCodeSubmitLabel:[{type:0,value:"Sign in"}],verifyCodeError:[{type:0,value:"Sign in failed. The code is probably no longer valid. Please "},{type:8,value:"login",children:[{type:0,value:"request new code"}]},{type:0,value:"."}],requestCodeTitle:[{type:0,value:"Have a code sent to your email"}],requestCodeBody:[{type:0,value:"Enter your email and request a code. If you are an existing "},{type:1,value:"productName"},{type:0,value:" user you will receive an email with a code. If you are a new user you will receive an email asking to request access to "},{type:1,value:"productName"},{type:0,value:" first."}],requestCodeInputPlaceholder:[{type:0,value:"Enter your email"}],requestCodeSubmitLabel:[{type:0,value:"Request code"}]},Jm={back:[{type:0,value:"Terug"}],promptTitle:[{type:0,value:"Login bij "},{type:1,value:"productName"}],verifyCodeTitle:[{type:0,value:"Plak de code uit je email"}],verifyCodeBody:[{type:0,value:"Kopieer de code uit de email en plak deze hier."}],verifyCodeInputPlaceholder:[{type:0,value:"Plak hier de code"}],verifyCodeSubmitLabel:[{type:0,value:"Inloggen"}],verifyCodeError:[{type:0,value:"Inloggen is niet gelukt. De code is waarschijnlijk niet meer geldig. "},{type:8,value:"login",children:[{type:0,value:"Vraag een nieuwe code aan"}]},{type:0,value:"."}],requestCodeTitle:[{type:0,value:"Verstuur een login code naar je email"}],requestCodeBody:[{type:0,value:"Voer je e-mailadres in en krijg een login code. Als je een bestaande "},{type:1,value:"productName"},{type:0,value:" gebruiker bent krijg je een email met een code. Als je een nieuwe gebruiker bent wordt er een email verstuurd met een toegangsverzoek voor "},{type:1,value:"productName"},{type:0,value:"."}],requestCodeInputPlaceholder:[{type:0,value:"Typ hier je e-mailadres"}],requestCodeSubmitLabel:[{type:0,value:"Code aanvragen"}]};var Yd={root:"dd-lWxnE",anchorButton:"dd-TZ4in",errorMessage:"dd-fIsPg",title:"dd-pGhJx",subtitle:"dd-f5l29",text:"dd-iamoD",input:"dd-uhQZ3",actions:"dd-lubvx",button:"dd-CJsNI",primaryButton:"dd-MWBfl"};var J=require("react/jsx-runtime");var Qm=t=>{try{let e=new URL(t);return new URLSearchParams(e.search).get("token")||void 0}catch(e){return t}},Zm=({agentEmail:t,isOpen:e,origin:n="",onSuccess:o,onDismiss:s})=>{let r=P(zi),i=C("LoginTokenDialog",Yd),a=(0,or.useSelector)(ul),d=(0,or.useDispatch)(),l=E("productName"),[c,p]=(0,Fe.useState)(t||""),[u,g]=(0,Fe.useState)(0),[m,f]=(0,Fe.useState)(""),y=(0,Fe.useCallback)(w=>S(null,null,function*(){w.preventDefault(),d(ml({email:c})),g(1)}),[n,c]),v=()=>{f(""),g(0)},x=(0,Fe.useCallback)(w=>S(null,null,function*(){w.preventDefault();let L=Qm(w.target.elements.token.value);if(!L){f(r("verifyCodeError",{login:T}));return}d(so({token:L}))}),[n]),T=(0,Fe.useMemo)(()=>w=>(0,J.jsx)("button",{type:"button","data-testid":"login-token-dialog-back-button",className:i.anchorButton,onClick:v,children:w},"back-button"),[]);return(0,Fe.useEffect)(()=>{a==="error"&&f(r("verifyCodeError",{login:T})),a==="done"&&o()},[a]),(0,J.jsx)(Hn,{autoFocus:!0,isOpen:e,contentAriaLabel:r("promptTitle",{productName:l}),overlayAriaLabel:r("promptTitle",{productName:l}),onClose:s,onBack:s,children:(0,J.jsxs)("div",{className:i.root,children:[(0,J.jsx)("h1",{className:i.title,children:r("promptTitle",{productName:l})}),u===0&&(0,J.jsxs)("form",{onSubmit:y,children:[(0,J.jsx)("h2",{className:i.subtitle,children:r("requestCodeTitle")}),(0,J.jsx)("p",{className:i.text,children:r("requestCodeBody",{productName:l})}),(0,J.jsx)(To,{className:i.input,name:"email",placeholder:r("requestCodeInputPlaceholder"),value:c,onChange:w=>p(w.target.value)}),(0,J.jsx)("div",{className:i.actions,children:(0,J.jsx)("button",{type:"submit",className:(0,nr.default)(i.button,i.primaryButton),children:r("requestCodeSubmitLabel")})})]}),u===1&&(0,J.jsxs)("form",{onSubmit:x,children:[(0,J.jsx)("h2",{className:i.subtitle,children:r("verifyCodeTitle")}),(0,J.jsx)("p",{className:i.text,children:r("verifyCodeBody")}),(0,J.jsx)(To,{className:i.input,name:"token",placeholder:r("verifyCodeInputPlaceholder"),disabled:["loading","done"].includes(a)}),m&&(0,J.jsx)("div",{className:i.errorMessage,children:m}),(0,J.jsxs)("div",{className:i.actions,children:[(0,J.jsx)("button",{type:"button",className:(0,nr.default)(i.button),onClick:v,children:r("back")}),(0,J.jsx)("button",{type:"submit",className:(0,nr.default)(i.button,i.primaryButton),disabled:["loading","done"].includes(a),children:r("verifyCodeSubmitLabel")})]})]})]})})},ec=Zm;var nc=require("react/jsx-runtime"),Ym=()=>{let t=(0,Vi.useSelector)(pl),e=(0,Vi.useSelector)(An),n=E("adminUrl"),o=fe(),s=()=>o.send(Nn,!1),r=()=>{o.send(Nn,!1),o.send(lo)};return(0,nc.jsx)(ec,{isOpen:t,agentEmail:e==null?void 0:e.agentEmail,origin:n,onDismiss:s,onSuccess:r})},tc=Ym;var Uc=D(require("lodash.debounce")),ye=require("react"),Xe=require("react-redux");var sr=require("@reduxjs/toolkit");var ef={data:null,fetchState:"idle"},oc=t=>t.contentTypes.data,wo=(0,sr.createAsyncThunk)("contentTypes/getContentTypes",(t,e)=>S(null,null,function*(){return e.extra.deepdeskAPI.getContentTypes()})),tf=(0,sr.createSlice)({name:"contentTypes",initialState:ef,reducers:{},extraReducers:t=>{t.addCase(wo.pending,e=>{e.fetchState="loading"}).addCase(wo.rejected,e=>{e.fetchState="error"}).addCase(wo.fulfilled,(e,n)=>{e.fetchState="done",e.data=n.payload})}}),sc=tf.reducer;var Bn=require("@reduxjs/toolkit");var nf={data:null,fetchState:"idle"},of=[],Mt=t=>t.profile.data,sf=t=>t.profile.data?t.profile.data.uiConfig.widget.types:of,ko=(0,Bn.createSelector)([sf],t=>t.filter(e=>e.isActive)),rc=t=>{var e;return((e=t.profile.data)==null?void 0:e.onDemandAssistants)||[]},ic=t=>e=>ko(e).find(n=>n.type===t),ac=t=>t.profile.data?!!t.profile.data.uiConfig.widget.types.find(e=>e.type==="custom-data"):!1,lc=t=>{var e,n;return(n=(e=t.profile.data)==null?void 0:e.knowledgeAssistantNew)!=null?n:null},Eo=(0,Bn.createAsyncThunk)("profile/getProfile",(t,e)=>S(null,null,function*(){var r;let{deepdeskAPI:n}=e.extra,o=e.getState(),s=o.conversation.current;if(!s||!s.profileCode)throw new Error("No conversation of conversation profileCode found");return((r=o.profile.data)==null?void 0:r.code)===s.profileCode?o.profile.data:n.getProfile(s.profileCode)})),rf=(0,Bn.createSlice)({name:"profile",initialState:nf,reducers:{},extraReducers:t=>{t.addCase(Eo.pending,e=>{e.fetchState="loading"}).addCase(Eo.rejected,e=>{e.fetchState="error"}).addCase(Eo.fulfilled,(e,n)=>{e.fetchState="done",e.data=n.payload})}}),dc=rf.reducer;var gt=require("react");var cc=require("react"),rr=D(require("classnames"));var be={root:"dd-U2SX4",list:"dd-cYTlj",listWrapper:"dd-GLQFR",listHorizontal:"dd-x-knl",page:"dd-1F4vk",search:"dd-nvbxc",pageNav:"dd-sRUuT",pageTitle:"dd-t-MKS",pageBackButton:"dd-cjptm",listHeader:"dd-Fg666",listHeading:"dd-w-xhJ",listMoreButton:"dd--mKep",listItem:"dd-wpvuA",listItemContent:"dd-V-mKo",listItemText:"dd-ukCHL",listItemDescription:"dd-sSyu4",listItemActions:"dd-xelho",listItemTooltip:"dd-SWFsE",listItemTooltipContent:"dd-I7J9N",truncate:"dd-IlopJ",lineClamp:"dd-Twaca",listItemTitle:"dd-lMGHq",listItemAction:"dd-xPLAs",listItemSelected:"dd-jFX0Y",sources:"dd-pZx4v",sourcesTitle:"dd-phYVd",source:"dd-DaR6h",sourceShowMore:"dd-M1-8j",icon:"dd-m6yxD",searchIcon:"dd-0AU-O",searchInputWrapper:"dd-DUFcE",searchInput:"dd-ukrlD",select:"dd--Tifv",selectType:"dd-IkZb2",selectWrapper:"dd-J14mx",image:"dd-RQgsB",imageSrc:"dd-jxh8F",imageSrcHidden:"dd-e20Jk",imageSrcStatus:"dd-j50Tt",imageTitle:"dd-qCjfW",actions:"dd-3mfWc",actionsWrapper:"dd-TjDyI",actionsBar:"dd-LiA35",actionButton:"dd-4wk0u",hasShortKeys:"dd-XilV-",actionShortcut:"dd-s4Mla",actionShortcutFixKerning:"dd-lyh5e"};var pt={};Z(pt,{enUS:()=>af,nlNL:()=>lf});var af={visitUrl:[{type:0,value:"Visit"}],back:[{type:0,value:"Back"}],loading:[{type:0,value:"Loading..."}],imageError:[{type:0,value:"Could not load image"}],showAll:[{type:0,value:"Show more"}],sources:[{type:0,value:"Sources"}],showMore:[{type:0,value:"Show "},{type:1,value:"amount"},{type:0,value:" more"}]},lf={visitUrl:[{type:0,value:"Bekijk"}],back:[{type:0,value:"Terug"}],loading:[{type:0,value:"Laden..."}],imageError:[{type:0,value:"Kan afbeelding niet laden"}],showAll:[{type:0,value:"Toon meer"}],sources:[{type:0,value:"Bronnen"}],showMore:[{type:0,value:"Toon "},{type:1,value:"amount"},{type:0,value:" meer"}]};var Nt=require("react/jsx-runtime"),df=({src:t,title:e})=>{let n=C("CommandPalette",be),[o,s]=(0,cc.useState)("loading"),r=P(pt);return(0,Nt.jsxs)("div",{className:n.image,children:[(0,Nt.jsx)("img",{src:t,alt:e,onLoad:()=>s("done"),onError:()=>s("error"),className:(0,rr.default)(n.imageSrc,{[n.imageSrcHidden]:["loading","error"].includes(o)})}),o==="loading"&&(0,Nt.jsx)("span",{className:(0,rr.default)(n.imageSrc,n.imageSrcStatus),children:r("loading")}),o==="error"&&(0,Nt.jsx)("span",{className:(0,rr.default)(n.imageSrc,n.imageSrcStatus),children:(0,Nt.jsx)(ss,{})}),e&&(0,Nt.jsx)("span",{className:n.imageTitle,children:e})]})},uc=df;var pc=D(require("react")),gc=D(require("classnames"));var an=require("react/jsx-runtime");function ji({children:t,heading:e,orientation:n,hasMore:o,onShowAll:s}){let r=P(pt),i=C("CommandPalette",be);return pc.default.Children.count(t)===0?null:(0,an.jsxs)("div",{"data-testid":"commandpalette-list",className:i.list,children:[(e||o)&&(0,an.jsxs)("div",{className:i.listHeader,children:[e&&(0,an.jsx)("h4",{className:i.listHeading,children:e}),o&&s&&(0,an.jsx)("button",{onClick:s,className:i.listMoreButton,type:"button",children:r("showAll")})]}),(0,an.jsx)("div",{className:(0,gc.default)(i.listWrapper,n==="horizontal"&&i.listHorizontal),children:t})]})}var Po=D(require("classnames")),Gi=require("interweave"),Ot=require("react");var cf=/[.*+?^${}()|[\]\\]/g,uf=/[^0-9A-Za-zÀ-ÖØ-öø-ÿ](?=[0-9A-Za-zÀ-ÖØ-öø-ÿ]*$)/;function pf(t){return t.replace(cf,"\\$&")}function gf(t,e){let n=t.split("").findIndex((o,s)=>o!==e[s]);return n>-1?n:Math.min(t.length,e.length)}function mf(t){return t.search(uf)}function mc(t,e=[]){let n=t;return e.forEach(o=>{if(!o)return;let s=new RegExp(`\\b(${pf(o)})\\b`,"gi");n=n.replace(s,"<strong>$1</strong>")}),n}function fc(t){return t.replace(cs,'<mark data-type="placeholder">$1</mark>')}function Un(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}function ff(t,e){return t.split("").map((i,a)=>({char:i,index:a})).filter(({char:i,index:a})=>/\s/.test(i)&&a<=e).map(({index:i})=>i).reverse()[0]}function $i(t,e,n={}){if(e){let o=gf(e.toLowerCase(),t.toLowerCase()),s=Un(t.substring(o,t.length));if(n.stripAgentPart){let d=t.substring(0,o),l=mf(d);return`<span style="opacity: 0.5">${d.substring(l+1)}</span>${s}`}let i=e.split(ll).length>3||e.length>30?ff(e.trim(),o):0;return`${`${i>0?"\u2026":""}${Un(t.substring(i,o))}`}<strong>${s}</strong>`}return t}var hf=/(<\/[a-zA-Z]+[0-9]?>|<[a-zA-Z]+\s?\/>|<br>)/i;function Ro(t){return hf.test(t)}function qi(t){var n;let e=document.createElement("template");return e.innerHTML=t,(n=e.content.textContent)!=null?n:""}var ir=D(require("react")),vc=require("react/jsx-runtime"),hc=ir.default.createContext(void 0);function Kn(){let t=ir.default.useContext(hc);if(t===void 0)throw new Error("useCommandPalette must be used within the CommandPalette component");return t}var yc=({children:t,page:e,isOpen:n,onChangeOpen:o,selected:s,setSelected:r})=>{let i=ir.default.useMemo(()=>({page:e,isOpen:n,onChangeOpen:o,selected:s,setSelected:r}),[n,e,s]);return(0,vc.jsx)(hc.Provider,{value:i,children:t})};var ce=require("react/jsx-runtime"),yf=3,vf=90,Sc=({children:t})=>{let e=C("CommandPalette",be);return(0,ce.jsx)("div",{className:e.listItemActions,children:t})};function Xi(g){var m=g,{closeOnSelect:t=!0,lineClamp:e,tooltip:n,children:o,onClick:s,extra:r,onSourceClick:i,description:a,sources:d,id:l,styles:c,defaultSourcesAmount:p=yf}=m,u=O(m,["closeOnSelect","lineClamp","tooltip","children","onClick","extra","onSourceClick","description","sources","id","styles","defaultSourcesAmount"]);var nt;let f=P(pt),[y,v]=(0,Ot.useState)(!1),{selected:x,onChangeOpen:T}=Kn(),[w,L]=(0,Ot.useState)(!1),R=C("CommandPalette",be);function I(F){s(F),t&&T(!1)}let z=(0,Ot.useMemo)(()=>typeof a!="string"?a:Ro(a)?qi(a).trim():a,[a]),Me=(0,Ot.useMemo)(()=>typeof n!="string"?n:Ro(n)?qi(n).trim():n,[n]);return(0,Ot.useEffect)(()=>{L(x===l)},[x]),(0,ce.jsxs)("div",{className:(0,Po.default)(R.listItem,l===x&&R.listItemSelected),children:[(0,ce.jsxs)(j,{placement:"right-start",tooltip:!0,onOpenChange:L,open:w,children:[(0,ce.jsx)(j.Trigger,b(h({className:R.listItemAction,"aria-disabled":(nt=u.disabled)!=null?nt:!1,onClick:I,"data-command-palette-item":!0,"data-item-id":l},u),{children:(0,ce.jsxs)("div",{className:R.listItemContent,children:[typeof o=="string"?(0,ce.jsx)("p",{className:(0,Po.default)(R.listItemText,R.truncate,c==null?void 0:c.title),children:o}):o,z&&typeof z=="string"?(0,ce.jsx)(Gi.Interweave,{tagName:"p",allowList:[],content:z,className:(0,Po.default)(R.listItemDescription,c==null?void 0:c.description,e?R.lineClamp:R.truncate)}):a]})})),Me&&Me.length>vf&&(0,ce.jsx)(j.Content,{className:R.listItemTooltip,disableFocusManager:!0,children:(0,ce.jsx)(Gi.Interweave,{className:R.listItemTooltipContent,allowList:["h1","h2","h3","h4","h5","h6","a","p","br"],tagName:"div",content:Me.replace(/\n/g,"<br />")})})]}),l===x&&r,d&&d.length>0&&(0,ce.jsxs)("div",{className:R.sources,children:[(0,ce.jsx)("span",{className:R.sourcesTitle,children:f("sources")}),d.slice(0,y?d.length:p).map(F=>(0,ce.jsx)("a",{className:R.source,href:F.url,target:"_blank",title:F.url,rel:"noopener noreferrer","data-testid":"source",onClick:()=>i==null?void 0:i(F),children:F.name},F.url)),!y&&d.length>p&&(0,ce.jsx)("button",{className:(0,Po.default)(R.source,R.sourceShowMore),type:"button",onClick:()=>v(!0),children:f("showMore",{amount:d.length-p})})]})]})}var Io=require("react/jsx-runtime"),xc=()=>(0,Io.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 256 512","aria-labelledby":"angleLeftTitle",children:[(0,Io.jsx)("title",{id:"angleLeftTitle",children:"AngleLeft"}),(0,Io.jsx)("path",{d:"M192 448c-8.188 0-16.38-3.125-22.62-9.375l-160-160c-12.5-12.5-12.5-32.75 0-45.25l160-160c12.5-12.5 32.75-12.5 45.25 0s12.5 32.75 0 45.25L77.25 256l137.4 137.4c12.5 12.5 12.5 32.75 0 45.25C208.4 444.9 200.2 448 192 448z"})]});var ln=require("react/jsx-runtime");function Ji({children:t,title:e,id:n,onDismiss:o}){let s=P(pt),r=C("CommandPalette",be),{page:i}=Kn();return i!==n?null:(0,ln.jsxs)("div",{className:r.page,id:`page_${n}`,tabIndex:-1,children:[o&&(0,ln.jsxs)("div",{className:r.pageNav,children:[(0,ln.jsxs)("button",{className:r.pageBackButton,type:"button",onClick:o,children:[(0,ln.jsx)(xc,{}),s("back")]}),e&&(0,ln.jsx)("h3",{className:r.pageTitle,children:e})]}),t]})}var bc=require("react");var Ao=require("react/jsx-runtime"),Wn=()=>(0,Ao.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 0 24 24",width:"1em",fill:"currentColor",children:[(0,Ao.jsx)("path",{d:"M0 0h24v24H0z",fill:"none"}),(0,Ao.jsx)("path",{d:"M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"})]});var He=require("react/jsx-runtime");function Sf({onChange:t,onChangeType:e,placeholder:n,typePlaceholder:o,types:s,value:r,selectedType:i},a){let d=C("CommandPalette",be);return(0,He.jsxs)("div",{className:d.search,children:[(0,He.jsx)("div",{className:d.searchIcon,children:(0,He.jsx)(Wn,{})}),(0,He.jsxs)("div",{className:d.searchInputWrapper,children:[(0,He.jsx)("input",{ref:a,spellCheck:!1,autoComplete:"off",onChange:l=>{t(l.currentTarget.value)},onFocus:l=>{l.currentTarget.select()},className:d.searchInput,placeholder:n,value:r,type:"text",id:"command-palette-search-input",autoFocus:!0}),s&&s.length>0&&(0,He.jsx)("div",{className:d.selectWrapper,children:(0,He.jsxs)("select",{"data-testid":"command-palette-type-select",className:d.select,onChange:l=>e(l.target.value===o?void 0:l.target.value),value:i||o,children:[o&&(0,He.jsx)("option",{children:o}),s.map(l=>(0,He.jsx)("option",{value:l.value,children:l.label},l.value))]})})]})]})}var Cc=(0,bc.forwardRef)(Sf);var Qi=D(require("classnames"));var ar=require("react/jsx-runtime"),xf=s=>{var r=s,{onClick:t,shortKeys:e,children:n}=r,o=O(r,["onClick","shortKeys","children"]);let i=C("CommandPalette",be);return(0,ar.jsxs)("button",b(h({type:"button"},o),{onClick:t,className:(0,Qi.default)(i.actionButton,o.className,{[i.hasShortKeys]:e&&e.length>0}),children:[n,e==null?void 0:e.map(a=>(0,ar.jsx)("span",{className:(0,Qi.default)(i.actionShortcut,a===8629&&i.actionShortcutFixKerning),children:typeof a=="number"?String.fromCharCode(a):a},a))]}))},Tc=xf;var Lo=require("react/jsx-runtime"),bf="[data-command-palette-item]";function dn({placeholder:t="Start typing to search...",typePlaceholder:e="All types",defaultPage:n="search",page:o,onChangePage:s,onChangeSearch:r,onChangeType:i,onChangeOpen:a,selectedType:d,types:l,children:c,isOpen:p,search:u,updateDeps:g=[]}){let[m,f]=(0,gt.useState)(),y=(0,gt.useRef)(null),v=()=>{s&&s(n),i(void 0),r(""),a(!1)},x=()=>{var F;if(o!==n&&s){s(n);return}if(d&&i){i(void 0),(F=y.current)==null||F.focus();return}if(u.length>0){r("");return}a(!1)},T=()=>{let F=w();F.length!==0&&f(F[0].dataset.itemId)},w=()=>Array.from(document.querySelectorAll(bf)||[]),L=F=>document.querySelector(`[data-item-id=${F}]`),R=F=>{let V=L(F);V&&f(V.dataset.itemId)},I=F=>{let V=L(F);V&&V.scrollIntoView({behavior:"smooth"})},z=()=>{if(!m)return;let F=w(),V=L(m);if(!V)return;let We=F.indexOf(V),ne=F[We+1];ne!=null&&ne.dataset.itemId?R(ne.dataset.itemId):T()},Me=()=>{if(!m)return;let F=w(),V=L(m);if(!V)return;let We=F.indexOf(V),ne=F[We-1];ne!=null&&ne.dataset.itemId?R(ne.dataset.itemId):R(F[F.length-1].dataset.itemId)},nt=(0,gt.useCallback)(F=>{switch(F.key){case"ArrowDown":{F.preventDefault(),z();break}case"ArrowUp":{F.preventDefault(),Me();break}case"Enter":{if(m){let V=L(m);V==null||V.click()}break}}},[m]);return(0,gt.useEffect)(()=>{T()},[u,o,d,p,...g]),(0,gt.useEffect)(()=>{m&&I(m)},[m]),(0,Lo.jsx)(Hn,{autoFocus:!0,contentAriaLabel:"Search Results",overlayAriaLabel:"Command Palette",isOpen:p,onBack:x,onClose:v,onKeyDown:nt,children:(0,Lo.jsxs)(yc,{selected:m,setSelected:f,isOpen:p,onChangeOpen:a,page:o,children:[o===n&&(0,Lo.jsx)(Cc,{ref:y,onChange:r,onChangeType:i,placeholder:t,value:u,selectedType:d,types:l,typePlaceholder:e}),c]})})}dn.Page=Ji;dn.List=ji;dn.Image=uc;dn.ListItem=Xi;dn.ListItemActions=Sc;dn.Button=Tc;var te=dn;var wc=require("react");function Ec(t,e){(0,wc.useEffect)(()=>{let n=o=>{var s;((s=navigator==null?void 0:navigator.platform)!=null&&s.toLowerCase().includes("mac")?o.metaKey:o.ctrlKey)&&o.key===t&&(o.preventDefault(),o.stopPropagation(),e())};return document.addEventListener("keydown",n),()=>{document.removeEventListener("keydown",n)}},[])}var Mo=require("react"),dr=require("react-redux");var zn=require("@reduxjs/toolkit");var kc={data:null,fetchState:"idle"},Cf=t=>{var e;return(e=t.entities.data)!=null?e:null},lr=(0,zn.createSelector)([Cf,An,Fl],(t,e,n)=>{var a;let o=[],{visitorName:s}=n!=null?n:{},{agentName:r,agentNickname:i}=e!=null?e:{};return r&&r!==s&&o.push(r),i&&i!==s&&o.push(i),(a=t==null?void 0:t.filter(d=>!o.includes(d.text)))!=null?a:null}),Be=(0,zn.createAsyncThunk)("entities/getEntities",(t,e)=>S(null,null,function*(){let{deepdeskAPI:n,dynamicThunkObject:o}=e.extra;if(!o.conversationQuery)return Promise.resolve([]);let s=o.conversationQuery,r=yield s();return r.length===0?Promise.resolve([]):n.getEntities(r)})),Tf=t=>t.filter((e,n)=>n===t.findIndex(o=>o.text===e.text)),wf=(0,zn.createSlice)({name:"entities",initialState:kc,reducers:{},extraReducers:t=>{t.addCase(Be.pending,e=>{e.fetchState="loading"}).addCase(Be.rejected,e=>{e.fetchState="error"}).addCase(Be.fulfilled,(e,n)=>{e.fetchState="done",e.data=Tf(e.data?[...e.data,...n.payload]:n.payload)}).addCase(Y,()=>kc)}}),Rc=wf.reducer;var Zi={};Z(Zi,{enUS:()=>Ef,nlNL:()=>kf});var Ef={noResults:[{type:0,value:"No entities have been found"}],copy:[{type:0,value:"Copy"}],use:[{type:0,value:"Use"}]},kf={noResults:[{type:0,value:"Er zijn geen entiteiten gevonden"}],copy:[{type:0,value:"Kopieer"}],use:[{type:0,value:"Gebruik"}]};var Pc={root:"dd-TYTKs",empty:"dd-AU7uT"};var Vn=require("react/jsx-runtime"),Rf=({onCopy:t})=>{let e=(0,Mo.useRef)(null),n=C("EntitiesList",Pc),o=(0,dr.useSelector)(lr),{setSelected:s}=Kn(),r=P(Zi),i=(0,dr.useDispatch)();return(0,Mo.useEffect)(()=>{i(Be())},[]),(0,Mo.useEffect)(()=>{e.current&&(e.current.focus(),s("entity-0"))},[e]),(0,Vn.jsxs)("div",{className:n.root,ref:e,tabIndex:-1,children:[o&&o.length>0&&(0,Vn.jsx)(te.List,{children:o.map((a,d)=>(0,Vn.jsx)(te.ListItem,{id:`entity-${d}`,closeOnSelect:!0,onClick:()=>t(a),children:a.text},a.text))},"entities"),o&&o.length===0&&(0,Vn.jsx)("p",{className:n.empty,children:r("noResults")})]})},Ic=Rf;var Yi=require("react/jsx-runtime"),cr=t=>(0,Yi.jsx)("svg",b(h({xmlns:"http://www.w3.org/2000/svg",height:"16",width:"14",viewBox:"0 0 448 512"},t),{children:(0,Yi.jsx)("path",{fill:"currentColor",d:"M8 256a56 56 0 1 1 112 0A56 56 0 1 1 8 256zm160 0a56 56 0 1 1 112 0 56 56 0 1 1 -112 0zm216-56a56 56 0 1 1 0 112 56 56 0 1 1 0-112z"})}));var No={};Z(No,{enUS:()=>Pf,nlNL:()=>If});var Pf={preview:[{type:0,value:"Preview"}],useSuggestion:[{type:0,value:"Add"}],sendSuggestion:[{type:0,value:"Send"}],suggestionSent:[{type:0,value:"Sent"}],sendingError:[{type:0,value:"Sending failed"}],tryAgain:[{type:0,value:"Try again"}],editSuggestion:[{type:0,value:"Edit"}],visitUrl:[{type:0,value:"Visit"}],giveFeedback:[{type:0,value:"Give feedback"}],answer:[{type:0,value:"Answer"}]},If={preview:[{type:0,value:"Preview"}],useSuggestion:[{type:0,value:"Gebruik"}],sendSuggestion:[{type:0,value:"Verzenden"}],suggestionSent:[{type:0,value:"Verzonden"}],sendingError:[{type:0,value:"Verzenden mislukt"}],tryAgain:[{type:0,value:"Probeer opnieuw"}],editSuggestion:[{type:0,value:"Bewerken"}],visitUrl:[{type:0,value:"Bekijk"}],giveFeedback:[{type:0,value:"Geef feedback"}],answer:[{type:0,value:"Antwoord"}]};var ea=require("react-redux");var ur={trigger:"dd-dQ-OH",content:"dd-9k0N3",item:"dd-va6pa"};var cn=require("react/jsx-runtime"),Af=({suggestion:t,source:e,context:n})=>{let o=P(No),s=(0,ea.useSelector)(je),r=q(),i=E("enableSuggestionFeedback"),a=Us({conversationId:s,type:e,contentType:"text",content:t.text,data:n?JSON.stringify({context:n}):void 0}),d=(0,ea.useSelector)(At(a)),l=()=>{r("suggestion feedback",{text:t.text,source:e,context:n})};return!i||!d?null:(0,cn.jsxs)(j,{placement:"top-end",children:[(0,cn.jsx)(j.Trigger,{className:ur.trigger,children:(0,cn.jsx)(cr,{"data-testid":"feedback-dropdown-trigger"})}),(0,cn.jsx)(j.Content,{className:ur.content,children:(0,cn.jsx)(j.Button,{className:ur.item,as:"a",onClick:l,target:"_blank",href:d,children:o("giveFeedback")})})]})},pr=Af;var Oo={};Z(Oo,{enUS:()=>Lf,nlNL:()=>Mf});var Lf={personalCollectionLink:[{type:0,value:"Go to Personal Collection"}],searchPlaceholder:[{type:0,value:"Start typing to search..."}],urlSuggestions:[{type:0,value:"URL suggestions"}],personalSuggestions:[{type:0,value:"Personal suggestions"}],pinnedMessages:[{type:0,value:"Pinned messages"}],imageSuggestions:[{type:0,value:"Images"}],typePlaceholder:[{type:0,value:"All types"}],navigation:[{type:0,value:"Navigation"}],entitiesClipboard:[{type:0,value:"Conversation clipper"}],entitiesTitle:[{type:0,value:"Copy to your clipboard"}],knowledgeAssist:[{type:0,value:"Knowledge assist"}],commands:[{type:0,value:"Commands"}],use:[{type:0,value:"Use"}],preview:[{type:0,value:"Preview"}],warning:[{type:0,value:"Are you sure you want to discard the message?"}]},Mf={personalCollectionLink:[{type:0,value:"Ga naar persoonlijke collectie"}],searchPlaceholder:[{type:0,value:"Begin met typen om te zoeken..."}],personalSuggestions:[{type:0,value:"Persoonlijke suggesties"}],urlSuggestions:[{type:0,value:"URL suggesties"}],imageSuggestions:[{type:0,value:"Afbeeldingen"}],navigation:[{type:0,value:"Navigatie"}],typePlaceholder:[{type:0,value:"Alle types"}],pinnedMessages:[{type:0,value:"Actueel"}],entitiesClipboard:[{type:0,value:"Klembord"}],entitiesTitle:[{type:0,value:"Kopieer naar klembord"}],knowledgeAssist:[{type:0,value:"Knowledge assist"}],commands:[{type:0,value:"Acties"}],use:[{type:0,value:"Gebruik"}],preview:[{type:0,value:"Bewerk"}],warning:[{type:0,value:"Weet je zeker dat je de wijzigingen wilt weggooien?"}]};var Hc=require("react"),fr=require("react-redux");var un=require("@reduxjs/toolkit");var Nf=["{amount}"," {amount}","{date}","{email}","{iban}","{name}","{postal_code}","{street}","{tarif}","{usage}","{3_digits}","{4_digits}","{5_digits}","{6_digits}","{7_digits}","{8_digits}","{9_digits}","{10_digits}"],Of=new RegExp(Nf.map(t=>`(?:${t.replace("{","\\{").replace("}","\\}")})`).join("|"));function Ac(t,e){let n=t.split(Of),o=0,s=[];for(let r=0;r<n.length;r++){let i=n[r];if(s.push(i),r===n.length-1)break;if(e.indexOf(i)===-1)return t;let a=n[r+1],d=r===n.length-2;o+=i.length;let l=o;if(d){let p=a.charAt(0),u=0;do l=p?e.indexOf(p,l+1):-1,u+=1;while(l!==-1&&a.indexOf(e.slice(l))!==0);if(l===-1&&u>2)return t}else l=a&&a!==""?e.indexOf(a,o):-1;let c=l===-1?e.slice(o):e.slice(o,l);s.push(c),o=l}return s.join("")}function Lc(t,e){return typeof e=="boolean"?t:t.slice(0,e)}var Nc={suggestions:[],fetchState:"idle"},Mc={default:Nc},Oc=t=>e=>{var n,o;return(o=(n=e.textSuggestions[t])==null?void 0:n.suggestions)!=null?o:[]},gr=t=>t.textSuggestions,Dc=t=>{let e=t.toLowerCase();return n=>{let o=n.text.toLowerCase();return o.startsWith(e)&&o.length>e.length}},mr=(0,un.createAction)("textSuggestions/refresh"),Ue=(0,un.createAsyncThunk)("textSuggestions/recommendations",(t,e)=>S(null,null,function*(){var c,p,u;let{deepdeskAPI:n}=e.extra,o=e.getState(),{platformVariables:s}=o.info,{textSuggestionsCount:r,inlineSuggestions:i}=o.settings,a=Xt(o),d=(c=o.conversation.current)==null?void 0:c.id;if(!d)throw new Error("No current conversation to fetch text suggestions");if(!((p=o.profile.data)!=null&&p.recommendationEngine))return[];let l=[];if(t==="sticky-messages"){let g=(u=o.profile.data)==null?void 0:u.code;if(!g)throw new Error("No current profile to fetch pinned messages");l=yield n.getPinnedMessages(g)}else l=yield n.getTextSuggestions(d,ao(o),t);if(s&&(l=l.map(g=>h(b(h({},g),{text:De(g.text,s)}),g.title?{title:De(g.title,s)}:{}))),t==="default"){let g=i?l.filter(Dc(a)):l;e.dispatch(Rt(g.slice(0,r)))}return l})),Do=(0,un.createAsyncThunk)("textSuggestions/autocompletions",(t,e)=>S(null,null,function*(){var c,p;let{deepdeskAPI:n}=e.extra,o=e.getState(),s=(c=o.conversation.current)==null?void 0:c.id,{platformVariables:r}=o.info,{textSuggestionsCount:i,deanonymize:a,inlineSuggestions:d}=o.settings;if(!((p=o.profile.data)!=null&&p.recommendationEngine))return[];if(!s)throw new Error("No current conversation to fetch text suggestions");let l=yield n.getAutocompleteSuggestions(s,b(h({},ao(o)),{input:t}));if(!e.getState().input.text)throw new Error("Abort");return d&&(l=l.filter(Dc(t))),r&&(l=l.map(u=>b(h({},u),{text:De(u.text,r)}))),a&&(l=l.map(u=>b(h({},u),{text:u.source!=="trie-with-typos"?Ac(u.text,t):u.text}))),l=Lc(l,i),e.dispatch(Rt(l)),l})),_c=(0,un.createSlice)({name:"textSuggestions",initialState:Mc,reducers:{setTextSuggestions:{reducer(t,e){let{contentType:n}=e.payload;t[n].fetchState="done",t[n].suggestions=e.payload.suggestions},prepare(t,e){return{payload:{contentType:t,suggestions:e}}}}},extraReducers:t=>{t.addCase(Ue.pending,(e,n)=>{let o=n.meta.arg,s=e[o]||Nc;return b(h({},e),{[o]:b(h({},s),{fetchState:"loading"})})}).addCase(Ue.rejected,(e,n)=>{let o=n.meta.arg;e[o]&&(e[o].fetchState="error")}).addCase(Ue.fulfilled,(e,n)=>{let o=n.meta.arg;e[o]&&(e[o].fetchState="done",e[o].suggestions=n.payload)}).addCase(Do.pending,e=>{e.default.fetchState="loading"}).addCase(Do.rejected,e=>{e.default.fetchState="error"}).addCase(Do.fulfilled,(e,n)=>{e.default.fetchState="done",e.default.suggestions=n.payload}).addCase(Y,()=>Mc)}}),{setTextSuggestions:bE}=_c.actions,Fc=_c.reducer;var pn=require("react/jsx-runtime"),Df=({types:t,commands:e,onClick:n})=>{let o=(0,fr.useDispatch)(),s=P(Oo),r=(0,fr.useSelector)(gr);return(0,Hc.useEffect)(()=>{t.forEach(({type:i})=>{(!r[i]||r[i].suggestions.length===0)&&o(Ue(i))})},[]),(0,pn.jsxs)("div",{children:[e.length>0&&(0,pn.jsx)(te.List,{heading:s("commands"),children:e.map((i,a)=>(0,pn.jsx)(te.ListItem,{id:`command-${a}`,closeOnSelect:!1,onClick:i.onClick,children:i.label},i.label))}),t.map(({type:i,title:a})=>{var d;return(0,pn.jsx)(te.List,{heading:a,orientation:"vertical",children:(d=r[i])==null?void 0:d.suggestions.map((l,c)=>(0,pn.jsx)(te.ListItem,{id:`${i}-${c}`,closeOnSelect:!1,description:l.title&&l.text,onClick:()=>n(l.text,l),"data-testid":"search-overlay-suggestion",children:l.title||l.text},`${l.id}-${l.text}`))},i)})]})},Bc=Df;var ue=require("react/jsx-runtime"),Ff=200,Hf=5,Bf=4,ta=(t,e,n)=>t.slice(0,n?10:e.toLowerCase()==="image"?Bf:Hf),Uf=(t,e)=>!e||t.toLowerCase().includes(e.toLowerCase()),Kf=()=>{var We,ne,Wt;let t=(0,Xe.useDispatch)(),e=fe(),n=P(Oo),[o,s]=(0,ye.useState)(!1),[r,i]=(0,ye.useState)(""),a=(0,Xe.useSelector)(ql),d=(0,Xe.useSelector)(Mt),[l,c]=(0,ye.useState)(),p=(0,Xe.useSelector)(se),u=E("showSearch"),g=E("enableSuggestionFeedback"),m=E("showEntitiesCommand"),f=E("showImageSearch"),y=E("searchTriggerKey"),v=(0,Xe.useSelector)(oc),x=(0,Xe.useSelector)(hi),T=(0,Xe.useSelector)(Gl),w=(0,Xe.useSelector)($l),L=((Wt=(ne=(We=d==null?void 0:d.uiConfig)==null?void 0:We.search)==null?void 0:ne.initialTypes)==null?void 0:Wt.filter(({isActive:N})=>N))||[],R=q(),I=(0,ye.useMemo)(()=>{let N=ge=>ta(x.filter(X=>X.type===ge.toUpperCase()),ge,l),$=(v==null?void 0:v.map(ge=>({value:ge.code.toUpperCase(),label:`${ge.name}s`,list:N(ge.code.toUpperCase()),listOrientation:"vertical",lineClamp:!0})))||[];if($.push({value:"PERSONAL",label:n("personalSuggestions"),list:N("PERSONAL"),lineClamp:!1,listOrientation:"vertical"},{value:"URL",label:n("urlSuggestions"),list:N("URL"),lineClamp:!1,listOrientation:"vertical"},{value:"STICKYMESSAGE",label:n("pinnedMessages"),list:N("STICKYMESSAGE"),lineClamp:!1,listOrientation:"vertical"}),f&&$.push({value:"IMAGE",label:n("imageSuggestions"),lineClamp:!1,list:N("IMAGE"),listOrientation:"horizontal"}),L.length===0)return $;let ot=L.map(ge=>$.find(X=>X.value.toLowerCase()===ge.type)).filter(ge=>!!ge),Cn=$.filter(ge=>!ot.find(X=>X.value===ge.value));return[...ot,...Cn]},[v,L,f,l]),z=[{label:n("entitiesClipboard"),onClick:()=>t(Mn("entities")),shouldShow:m&&Uf(n("entitiesClipboard"),r)}].filter(N=>N.shouldShow).filter(()=>!l),Me=(0,ye.useCallback)((0,Uc.default)((N,$)=>{t(en({query:N,type:$,tags:["search-overlay"],size:l?50:20}))},Ff),[l]),nt=(0,ye.useCallback)((N,$)=>{$.type==="IMAGE"?e.send(vi,{suggestion:$}):e.send(rt,{text:N,suggestion:$}),t(_e(!1))},[t]),F=N=>{$e(N.text),R("entity copied",{entity:N,type:"copy"}),t(_e(!1))};function V(N){return $=>{o?window.confirm(n("warning"))&&(N($),s(!1)):N($)}}return(0,ye.useEffect)(()=>{r?Me(r,l):t(Ts())},[r,l]),(0,ye.useEffect)(()=>{p&&t(wo())},[p]),Ec(y,()=>{t(_e(!0)),R("open search",{via:"ctrl+k"})}),!u||!d?null:(0,ue.jsxs)(te,{placeholder:n("searchPlaceholder"),typePlaceholder:n("typePlaceholder"),onChangeSearch:i,onChangeOpen:V(N=>t(_e(N))),onChangeType:N=>c(N),onChangePage:V(N=>t(Mn(N))),selectedType:l,search:r,page:a,isOpen:w,types:I,updateDeps:[x],children:[(0,ue.jsxs)(te.Page,{id:"search",children:[r.length===0&&(0,ue.jsx)(Bc,{types:L,commands:z,onClick:nt}),r.length>0&&(0,ue.jsxs)(ye.Fragment,{children:[z.length>0&&(0,ue.jsx)(te.List,{heading:n("commands"),children:z.map((N,$)=>(0,ue.jsx)(te.ListItem,{closeOnSelect:!1,onClick:N.onClick,id:`commands-${$}`,children:N.label},N.label))}),I.map(({value:N,label:$,list:ot,lineClamp:Cn,listOrientation:ge})=>(0,ue.jsx)(te.List,{heading:$,orientation:ge==="horizontal"?"horizontal":"vertical",onShowAll:()=>c(N),hasMore:!l&&T[N.toLowerCase()]>ta(ot,N,l).length,children:ta(ot,N,l).map(X=>(0,ue.jsx)(te.ListItem,{id:`${N}-${X.id}`,closeOnSelect:!1,lineClamp:Cn,onClick:()=>nt(X.text,X),description:N!=="IMAGE"?X.title&&X.text:void 0,tooltip:X.text,extra:g&&(0,ue.jsx)(te.ListItemActions,{children:(0,ue.jsx)(pr,{context:r,source:"search",suggestion:X})}),children:N==="IMAGE"?(0,ue.jsx)(te.Image,{title:X.title||X.text,src:X.image}):X.title||X.text},`${X.id}-${X.text}`))},N))]})]}),(0,ue.jsx)(te.Page,{id:"entities",title:n("entitiesTitle"),onDismiss:V(()=>{t(Mn("search"))}),children:(0,ue.jsx)(Ic,{onCopy:F})})]})},Kc=Kf;var _o=require("react/jsx-runtime"),Wf=()=>{let t=E("showSearch"),e=E("isEmbedded");return(0,_o.jsxs)(Wc.Fragment,{children:[t&&(0,_o.jsx)(Kc,{}),e&&(0,_o.jsx)(tc,{})]})},zc=Wf;var qc=D(require("classnames")),Gc=require("react-redux");var hr=require("react/jsx-runtime"),Vc=({className:t})=>(0,hr.jsx)("svg",{version:"1.1",xmlns:"http://www.w3.org/2000/svg",xmlnsXlink:"http://www.w3.org/1999/xlink",x:"0px",y:"0px",viewBox:"0 0 512 512",xmlSpace:"preserve",className:t,children:(0,hr.jsx)("g",{children:(0,hr.jsx)("path",{d:`M163.4,233h186v-70c0-25.6-9.4-47.8-27.3-65.7C304.2,79.4,282,70,256.4,70s-47.8,9.4-65.7,27.3
3
+ `,tn.MISSING_INTL_API,i);var w=n.getPluralRules(e,{type:c.pluralType}).select(u-(c.offset||0));T=c.options[w]||c.options.other}if(!T)throw new Ri(c.value,u,Object.keys(c.options),i);a.push.apply(a,xo(T.value,e,n,o,s,u-(c.offset||0)));continue}}return Sm(a)}function bm(t,e){return e?xe(xe(xe({},t||{}),e||{}),Object.keys(t).reduce(function(n,o){return n[o]=xe(xe({},t[o]),e[o]||{}),n},{})):t}function Cm(t,e){return e?Object.keys(t).reduce(function(n,o){return n[o]=bm(t[o],e[o]),n},xe({},t)):t}function Pi(t){return{create:function(){return{get:function(e){return t[e]},set:function(e,n){t[e]=n}}}}}function Tm(t){return t===void 0&&(t={number:{},dateTime:{},pluralRules:{}}),{getNumberFormat:Ls(function(){for(var e,n=[],o=0;o<arguments.length;o++)n[o]=arguments[o];return new((e=Intl.NumberFormat).bind.apply(e,As([void 0],n,!1)))},{cache:Pi(t.number),strategy:Ms.variadic}),getDateTimeFormat:Ls(function(){for(var e,n=[],o=0;o<arguments.length;o++)n[o]=arguments[o];return new((e=Intl.DateTimeFormat).bind.apply(e,As([void 0],n,!1)))},{cache:Pi(t.dateTime),strategy:Ms.variadic}),getPluralRules:Ls(function(){for(var e,n=[],o=0;o<arguments.length;o++)n[o]=arguments[o];return new((e=Intl.PluralRules).bind.apply(e,As([void 0],n,!1)))},{cache:Pi(t.pluralRules),strategy:Ms.variadic})}}var Ii=(function(){function t(e,n,o,s){n===void 0&&(n=t.defaultLocale);var r=this;if(this.formatterCache={number:{},dateTime:{},pluralRules:{}},this.format=function(l){var c=r.formatToParts(l);if(c.length===1)return c[0].value;var p=c.reduce(function(u,g){return!u.length||g.type!==le.literal||typeof u[u.length-1]!="string"?u.push(g.value):u[u.length-1]+=g.value,u},[]);return p.length<=1?p[0]||"":p},this.formatToParts=function(l){return xo(r.ast,r.locales,r.formatters,r.formats,l,void 0,r.message)},this.resolvedOptions=function(){var l;return{locale:((l=r.resolvedLocale)===null||l===void 0?void 0:l.toString())||Intl.NumberFormat.supportedLocalesOf(r.locales)[0]}},this.getAst=function(){return r.ast},this.locales=n,this.resolvedLocale=t.resolveLocale(n),typeof e=="string"){if(this.message=e,!t.__parse)throw new TypeError("IntlMessageFormat.__parse must be set to process `message` of type `string`");var i=s||{},a=i.formatters,d=od(i,["formatters"]);this.ast=t.__parse(e,xe(xe({},d),{locale:this.resolvedLocale}))}else this.ast=e;if(!Array.isArray(this.ast))throw new TypeError("A message must be provided as a String or AST.");this.formats=Cm(t.formats,o),this.formatters=s&&s.formatters||Tm(this.formatterCache)}return Object.defineProperty(t,"defaultLocale",{get:function(){return t.memoizedDefaultLocale||(t.memoizedDefaultLocale=new Intl.NumberFormat().resolvedOptions().locale),t.memoizedDefaultLocale},enumerable:!1,configurable:!0}),t.memoizedDefaultLocale=null,t.resolveLocale=function(e){if(typeof Intl.Locale!="undefined"){var n=Intl.NumberFormat.supportedLocalesOf(e);return n.length>0?new Intl.Locale(n[0]):new Intl.Locale(typeof e=="string"?e:e[0])}},t.__parse=ad,t.formats={number:{integer:{maximumFractionDigits:0},currency:{style:"currency"},percent:{style:"percent"}},date:{short:{month:"numeric",day:"numeric",year:"2-digit"},medium:{month:"short",day:"numeric",year:"numeric"},long:{month:"long",day:"numeric",year:"numeric"},full:{weekday:"long",month:"long",day:"numeric",year:"numeric"}},time:{short:{hour:"numeric",minute:"numeric"},medium:{hour:"numeric",minute:"numeric",second:"numeric"},long:{hour:"numeric",minute:"numeric",second:"numeric",timeZoneName:"short"},full:{hour:"numeric",minute:"numeric",second:"numeric",timeZoneName:"short"}}},t})();function wm(t,e){return e.split(".").reduce((n,o)=>n?n[o]:void 0,t)}var Em="dummy",Ai=(0,Fs.createContext)(null);function P(t){var o;let e=(0,Fs.useContext)(Ai);if(!e)throw new Error("useTranslator() may be used only in the context of a <LocaleContext> component.");let n=(o=t[e])!=null?o:{};return(s,r)=>{let i=wm(n,s);return i?new Ii(i).format(r):(e!==Em&&console.warn(`${s} does not exist in messages of ${e}`),`[${s}]`)}}var Pt=require("@reduxjs/toolkit");var cd=require("marked"),Hs=(t,e)=>{let n=[],o=new cd.Marked,s=r=>{r.type==="code"&&r.lang===e&&n.push(r.text)};return o.use({walkTokens:s}),o.parse(t),n};function Li(t){return Array.isArray(t.attachments)&&t.attachments.length>0?t.attachments:Array.isArray(t.transcript)?t.transcript.flatMap(e=>{var n;return(n=e==null?void 0:e.attachments)!=null?n:[]}):[]}var ud={cues:[],threads:{},pending:[]},pd=t=>{var e;return(e=t.assistants)==null?void 0:e.cues};var gd=t=>e=>{var n,o;return(o=(n=e.assistants)==null?void 0:n.threads[t])!=null?o:null},Bs=(0,Pt.createAction)("assistants/callToAction"),bo=(0,Pt.createAsyncThunk)("assistants/evaluateKnowledgeAssistant",(t,e)=>S(null,null,function*(){var l,c,p;let{threadId:n}=t,{onNewThreadId:o}=t,{deepdeskAPI:s}=e.extra,r=e.getState(),{platformVariables:i}=r.info;n||(n=(yield s.createAssistantThread({assistantCode:t.assistantCode})).id,o&&o(n)),yield s.postMessageToAssistantThread({assistantCode:t.assistantCode,threadId:n,message:t.input});let a=yield e.dispatch(he(b(h({skipState:!0},t),{input:{},threadId:n,attachments:t.attachments})));if(a.error)throw new Error(a.error.message);let d=(l=a.payload.output[0])!=null?l:{response:"",sources:[]};return{threadId:n,question:t.input,evaluationId:a.payload.evaluationId,answer:{answer:(c=De(d.response,i!=null?i:{}))!=null?c:"",sources:(p=d.sources)!=null?p:[]}}})),tb=(0,Pt.createAction)("assistants/extractedTextSuggestions");function km(t,e){var n,o;return Array.isArray(t.output)?t.output:typeof t.output=="string"?[{code:e,name:e,response:t.output}]:[b(h({code:e,name:e},t.output&&typeof t.output=="object"?t.output:{}),{response:(o=(n=t.output)==null?void 0:n.response)!=null?o:""})]}var he=(0,Pt.createAsyncThunk)("assistants/evaluate",(t,e)=>S(null,null,function*(){var x,T,w,L,R;let{deepdeskAPI:n,dynamicThunkObject:o}=e.extra,{transcript:s,input:r={},threadId:i,attachments:a}=t,d=e.getState(),{platformVariables:l}=d.info,c=(T=(x=d.conversation.current)==null?void 0:x.externalId)!=null?T:null,p=(L=(w=t.externalConversationId)!=null?w:c)!=null?L:void 0,u;if(s==="in-memory-transcript"){if(!o.conversationQuery)throw new Error("Can't include in-memory-transcript, setConversationQuery is not defined");let I=yield o.conversationQuery();u=Array.isArray(I)?I:void 0}else Array.isArray(s)&&(u=s);if(t.includeMetadata&&d.conversation.current&&((R=t.externalConversationId)!=null?R:c)===c){let{metadata:z}=d.conversation.current;Object.assign(r,{metadata:z})}let g=Li({attachments:a,transcript:u}),m=yield n.evaluateAssistant(t.assistantCode,h({input:r,transcript:u,externalConversationId:p,threadId:i},g.length>0?{attachments:g}:{}));if(m.evaluationStatus!=="success")return e.rejectWithValue(`Assistant ${t.assistantCode} evaluation failed: ${m.evaluationStatus}`);let y=km(m,t.assistantCode).map(I=>b(h({},I),{name:De(I.name,l),response:De(I.response,l)||""})),v=[];return y.forEach(I=>{if(!I.response)return;let z=Hs(I.response,"reply");z.length!==0&&v.push(...z.map(Me=>({text:Me,type:"text",source:"assistant",assistantCode:I.code,sourceLabel:I.name})))}),v.length>0&&e.dispatch(Pn(v)),b(h({},m),{output:y,externalConversationId:p,currentExternalIdAtRequest:c})}));function md(t){return t!=null&&t.length?t.map(e=>e.response).filter(Boolean).join(`
4
+ `):""}var fd=(0,Pt.createSlice)({name:"assistants",initialState:ud,reducers:{resetCues(t){t.cues=[]},removeCueByCode(t,e){t.cues=t.cues.filter(n=>n.code!==e.payload.code)},removeThreadById(t,e){delete t.threads[e.payload]},receiveChunk(t,e){let{code:n,name:o,payload:s,evaluationId:r}=e.payload,i=t.cues.findIndex(a=>a.code===n);i!==-1?t.cues[i].response+=s.text:t.cues.push({code:n,name:o,evaluationId:r,response:s.text})},userNotification(t,e){let n=t.cues.find(c=>c.code===e.payload.code),o=t.cues.filter(c=>c.code!==e.payload.code),{code:s,name:r,evaluationId:i,payload:a}=e.payload,{callToAction:d}=a,l=a.sources!==void 0?a.sources.filter(c=>!!c.url):n==null?void 0:n.sources;t.cues=[...o,b(h({code:s,name:r,evaluationId:i,response:a.message,editable:a.editableMessage},l!=null&&l.length?{sources:l}:{}),{callToAction:d&&{label:d.displayName,event:d.onClickEvent,value:d.eventPayload}})]}},extraReducers:t=>{t.addCase(he.pending,(e,n)=>{e.pending.includes(n.meta.arg.assistantCode)&&k.warn(`Assistant ${n.meta.arg.assistantCode} already evaluating`),e.pending.push(n.meta.arg.assistantCode)}).addCase(he.rejected,(e,n)=>{var s;k.warn((s=n.error)==null?void 0:s.message);let o=e.pending.indexOf(n.meta.arg.assistantCode);o!==-1&&e.pending.splice(o,1)}).addCase(he.fulfilled,(e,n)=>{let o=e.pending.indexOf(n.meta.arg.assistantCode);if(o!==-1&&e.pending.splice(o,1),n.meta.arg.skipState)return;let{evaluationId:s,output:r,externalConversationId:i,currentExternalIdAtRequest:a}=n.payload;if(i&&a&&i!==a)return;let d=r.map(p=>p.code),l=e.cues.filter(p=>!d.includes(p.code)),c=r.map(p=>h(b(h({},p),{evaluationId:s}),i?{externalConversationId:i}:{}));e.cues=[...l,...c]}).addCase(bo.fulfilled,(e,n)=>{let r=n.payload,{threadId:o}=r,s=O(r,["threadId"]);e.threads[o]=[...e.threads[o]||[],s]}).addCase(Y,()=>ud)}}),{removeCueByCode:Us,resetCues:nb,removeThreadById:hd,receiveChunk:yd,userNotification:vd}=fd.actions,Sd=fd.reducer;var xd=require("@reduxjs/toolkit"),bd=require("react-redux");var Rm={locale:"en-US",deanonymize:!1,fallbackImage:!1,isEmbedded:!1,signInViaPopup:!1,showImages:!1,showSearch:!1,showImageSearch:!1,showStyleSuggestions:!1,showStyleSuggestionList:!1,showMidSentenceSuggestions:!1,showSuggestionsBeforePattern:!1,showSuggestionsAfterPattern:!1,showTabCompletion:!0,showTextSuggestions:!0,showEntitiesCommand:!1,showSummaryCommand:!1,showKnowledgeSearch:!1,textSuggestionsCount:3,recommendTextSuggestions:!0,searchTriggerKey:"k",visible:!0,insertLink:!1,addToPersonalCollection:!1,inlineSuggestions:!1,autoSelectSuggestion:!1,suggestionsPlacement:"above",floatingMenu:!1,detectSubmit:!1,automaticHandlingTime:!1,enableSuggestionFeedback:!1,enableFeedbackForm:!0,adminUrl:void 0,productName:"Deepdesk",hasKeyboardInput:!0},Cd=(0,xd.createSlice)({name:"settings",initialState:Rm,reducers:{set(t,e){Object.entries(e.payload).forEach(n=>{let[o,s]=n;typeof s!="undefined"&&(t[o]=s)})}}}),{set:Ks}=Cd.actions,nn=t=>e=>e.settings[t],E=t=>(0,bd.useSelector)(nn(t)),Td=Cd.reducer;function qe(t){let e=document.createElement("textarea");e.value=t,e.style.position="fixed",e.style.left="-999999px",e.style.top="-999999px",document.body.appendChild(e),e.focus(),e.select(),document.execCommand("copy"),e.remove()}var Co=D(require("classnames")),Md=require("react");var Mi=require("react/jsx-runtime"),Ws=t=>(0,Mi.jsx)("svg",b(h({width:"16",height:"16",fill:"#000000"},t),{viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,Mi.jsx)("path",{fillRule:"evenodd",d:"M6.57086468,14.9173453 C6.38997052,14.9711236 6.19835748,15 6,15 L4,15 C2.8954305,15 2,14.1045695 2,13 L2,4 C2,2.8954305 2.8954305,2 4,2 L6,2 C6.68685475,2 7.29284112,2.34623869 7.65294381,2.87370078 C7.95642355,2.67736738 8.29504785,2.51351337 8.66312366,2.3818197 C9.50544052,2.08044754 10.3408482,1.9879107 10.9989281,1.99971266 C11.0150698,2.00005426 13.3487605,2.00015005 18,2 C20.7551411,2 22,6.05643086 22,12 C22,13.6824804 20.8695981,15 19,15 L15.9269768,15 C15.9359266,15.0245465 15.9451954,15.0497804 15.9547911,15.0757271 C16.007193,15.2174219 16.2391583,15.8256341 16.2970775,15.9810953 C16.4872151,16.4914441 16.6259612,16.9026411 16.7382242,17.3098712 C16.9079007,17.9253665 17,18.4798886 17,19 C17,20.4720069 16.091867,21.3862822 14.748281,21.777514 C14.1422801,21.9539723 13.6147967,22.0000922 13.0076976,22.0000008 L12.5204954,22 L12.2202699,21.6261158 C11.2556275,20.4248034 7.64562469,16.4822788 6.57086468,14.9173453 Z M8,13 C8,13.2401953 8.04443154,13.4528921 8.14171093,13.6800176 C8.40663864,14.2985643 11.914268,18.1371493 13.4599624,19.9848695 C13.7113931,19.9660111 13.9483736,19.9273712 14.1891338,19.8572655 C14.7621788,19.6904035 15,19.4509737 15,19 C15,18.6834183 14.9359344,18.2976852 14.8101464,17.8413935 C14.7161494,17.500423 14.5944107,17.1396301 14.4229225,16.6793379 C14.3689242,16.5344009 14.1358033,15.923159 14.0789589,15.7694517 C13.9489218,15.4178313 13.8632547,15.1589343 13.8046536,14.9236885 C13.5555377,13.9236468 13.8054549,13 15,13 L19,13 C19.6912225,13 20,12.6401099 20,12 C20,7.20925475 19.015127,4 18,4 C15.9322103,4 15.9322103,4 10.9655994,3.99940813 C10.5253746,3.99154158 9.91062406,4.05963657 9.33687634,4.2649175 C8.45196659,4.58152894 8,5.09776992 8,6 L8,13 Z M4,4 L4,13 L6,13 L6,4 L4,4 Z"})}));var Ni=require("react/jsx-runtime"),wd=t=>(0,Ni.jsx)("svg",b(h({width:"16",height:"16",fill:"#000000"},t),{viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,Ni.jsx)("path",{fillRule:"evenodd",d:"M7.65336736,21.1256786 C7.2933164,21.6534897 6.68712411,22 6,22 L4,22 C2.8954305,22 2,21.1045695 2,20 L2,11 C2,9.8954305 2.8954305,9 4,9 L6,9 C6.198171,9 6.38961023,9.02882212 6.57035446,9.08250314 C7.6444817,7.51807482 11.2554748,3.57449216 12.2202699,2.37298955 L12.5204954,1.99910538 L13,1.99910538 C13.6147967,1.99901314 14.1422801,2.04513312 14.748281,2.22159137 C16.091867,2.61282321 17,3.52709845 17,4.99910538 C17,5.51921677 16.9079007,6.07373891 16.7382242,6.68923415 C16.6259612,7.09646424 16.4872151,7.50766133 16.2970775,8.01801005 C16.2391583,8.17347129 16.007193,8.78168345 15.9547911,8.92337824 C15.9451954,8.94932503 15.9359266,8.9745589 15.9269768,8.99910538 L19,8.99910538 C20.8695981,8.99910538 22,10.316625 22,11.9991054 C22,17.9426745 20.7551411,21.9991054 18,21.9991054 L11.0344006,21.9985135 C10.3408482,22.0111947 9.50544052,21.9186578 8.66312366,21.6172857 C8.29521907,21.4856533 7.9567386,21.3218904 7.65336736,21.1256786 Z M8,17.9991054 C8,18.9013355 8.45196659,19.4175764 9.33687634,19.7341879 C9.91062406,19.9394688 10.5253746,20.0075638 10.963066,19.9997143 C10.9703499,19.9995545 10.9703499,19.9995545 11,19.9991054 L18,19.9991054 C19.015127,19.9991054 20,16.7898506 20,11.9991054 C20,11.3589955 19.6912225,10.9991054 19,10.9991054 L15,10.9991054 C13.8054549,10.9991054 13.5555377,10.0754586 13.8046536,9.07541689 C13.8632547,8.84017106 13.9489218,8.5812741 14.0789589,8.22965366 C14.1358033,8.07594642 14.3689242,7.46470447 14.4229225,7.31976744 C14.5944107,6.85947528 14.7161494,6.4986824 14.8101464,6.1577119 C14.9359344,5.70142019 15,5.31568707 15,4.99910538 C15,4.54813166 14.7621788,4.30870189 14.1891338,4.1418399 C13.9483736,4.07173418 13.7113931,4.0330943 13.4599624,4.01423587 C11.914268,5.86195611 8.40663864,9.70054105 8.14171093,10.3190878 C8.04443154,10.5462133 8,10.7589101 8,10.9991054 L8,17.9991054 Z M4,11 L4,20 L6,20 L6,11 L4,11 Z"})}));function It(t,e){var s;let n=t.cloneNode(!0);n.style.top=`${t.offsetTop}px`,n.style.left=`${t.offsetLeft}px`,n.style.position="absolute",e.split(" ").forEach(r=>{n.classList.add(r)}),n.addEventListener("animationend",()=>n.remove()),(s=t.parentElement)==null||s.appendChild(n)}var Oi={};Z(Oi,{enUS:()=>Pm,nlNL:()=>Im});var Pm={thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}]},Im={thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}]};var Ed={thumbs:"dd-5F1zq",fadeup:"dd-eTmY-",fadedown:"dd-sS85z",selected:"dd-rid-f",thumbsUp:"dd-4poEf",thumbsDown:"dd-3KozS"};var kd=({conversationId:t,evaluationId:e,type:n,assistantCode:o,contentType:s},r,i)=>{let a=new URLSearchParams;return t!=null&&a.set("conversationId",String(t)),e&&a.set("evaluationId",e),a.set("type",n),o&&a.set("assistantCode",o),a.set(s,r),i!==void 0&&a.set("data",i),`/admin/feedback?${a.toString()}`},zs=t=>{let e=t.content,n=kd(t,e,t.data),o=encodeURIComponent(n).length;for(;o>3e3&&e.length>0;){let s=Math.max(0,Math.floor(e.length*3e3/o)-1);e=t.content.slice(0,s),n=kd(t,e?`${e}\u2026`:"",t.data),o=encodeURIComponent(n).length}return n};var Ld=require("react-redux");var Vs=require("react"),Ad=require("react/jsx-runtime"),Rd=(0,Vs.createContext)(null),Pd=({handler:t,children:e})=>(0,Ad.jsx)(Rd.Provider,{value:t!=null?t:null,children:e}),Id=()=>(0,Vs.useContext)(Rd);var On=t=>e=>{let{passwordlessToken:{token:n},settings:{isEmbedded:o,adminUrl:s}}=e,r=s||window.location.origin;return o&&!n?null:o&&n?`${r}/apis/admin/session/passwordless/login/?token=${n}&redirect=${encodeURIComponent(t)}`:`${r}${t}`};function js(t){let e=E("enableFeedbackForm"),n=Id(),o=(0,Ld.useSelector)(On(t));return e?n?{mode:"custom-handler",open:()=>n(t)}:o?{mode:"passwordless-link",href:o}:{mode:"disabled"}:{mode:"disabled"}}var Nd=require("react-redux");var Fe=require("react/jsx-runtime"),Am=({assistantCode:t,assistantOutput:e,evaluationId:n,feedbackType:o})=>{let s=C("FeedbackThumbs",Ed),r=(0,Nd.useSelector)($e),i=zs({conversationId:r,evaluationId:n,type:o,assistantCode:t,contentType:"assistantOutput",content:e}),a=js(i),d=P(Oi),l=q(),[c,p]=(0,Md.useState)(null),u=f=>{l("Assistant response feedback",{assistantCode:t,assistantOutput:e,evaluationId:n,rating:f})},g=f=>{f.stopPropagation(),It(f.target,s.fadeup),p("up"),u("up")},m=f=>S(null,null,function*(){f.stopPropagation(),It(f.target,s.fadedown),p("down"),u("down"),a.mode==="custom-handler"&&(yield a.open())});return(0,Fe.jsxs)("div",{className:s.thumbs,children:[(0,Fe.jsx)(M.Button,{title:d("thumbsUp"),onClick:g,icon:(0,Fe.jsx)(wd,{}),className:(0,Co.default)(s.thumbsUp,c==="up"&&s.selected),disabled:!!c}),a.mode==="custom-handler"?(0,Fe.jsx)(M.Button,{title:d("thumbsDown"),onClick:m,icon:(0,Fe.jsx)(Ws,{}),className:(0,Co.default)(s.thumbsDown,c==="down"&&s.selected),disabled:!!c}):a.mode==="passwordless-link"?(0,Fe.jsx)(M.Button,{as:"a",title:d("thumbsDown"),href:a.href,target:"_blank",rel:"noreferrer",onClick:m,icon:(0,Fe.jsx)(Ws,{}),className:(0,Co.default)(s.thumbsDown,c==="down"&&s.selected),disabled:!!c}):(0,Fe.jsx)(M.Button,{title:d("thumbsDown"),onClick:m,icon:(0,Fe.jsx)(Ws,{}),className:(0,Co.default)(s.thumbsDown,c==="down"&&s.selected),disabled:!!c})]})},$s=Am;var $d=D(require("dompurify")),qd=require("marked"),ct=require("react");var Fd=require("react");var U=require("@floating-ui/react"),Ge=D(require("react"));var qs={tooltip:"dd-XpCXd",tooltipTrigger:"dd-8TKeF",arrow:"dd-ZEu2Y"};var ke=require("react/jsx-runtime");function Lm({initialOpen:t=!1,placement:e="bottom",modal:n,tooltip:o,open:s,onOpenChange:r}={}){let[i,a]=Ge.useState(t),d=s!=null?s:i,l=r!=null?r:a,c=(0,U.useFloating)({placement:e,open:d,onOpenChange:l,whileElementsMounted:U.autoUpdate,middleware:[(0,U.offset)(5),(0,U.flip)({crossAxis:e.includes("-"),fallbackAxisSideDirection:"end",padding:5}),(0,U.shift)({padding:10})]}),p=c.context,u=(0,U.useClick)(p,{enabled:s==null}),g=(0,U.useDismiss)(p),m=(0,U.useRole)(p),f=(0,U.useHover)(p,{enabled:o!=null?o:!1,handleClose:(0,U.safePolygon)()}),y=(0,U.useInteractions)([u,g,m,f]);return Ge.useMemo(()=>b(h(h({open:d,setOpen:l},y),c),{modal:n}),[d,l,y,c,n])}var Od=Ge.createContext(null),Di=()=>{let t=Ge.useContext(Od);if(t==null)throw new Error("Popover components must be wrapped in <Popover />");return t},on=o=>{var s=o,{children:t,modal:e=!1}=s,n=O(s,["children","modal"]);let r=Lm(h({modal:e},n));return(0,ke.jsx)(Od.Provider,{value:r,children:t})};function Mm(o){var s=o,{as:t,children:e}=s,n=O(s,["as","children"]);let r=Di(),i=t||"button",a=e.ref,d=(0,U.useMergeRefs)([r.refs.setReference,a]);return(0,ke.jsx)(i,b(h(h({ref:d},i==="button"||t===void 0||t==="button"?{type:"button"}:{}),r.getReferenceProps(n)),{children:e}))}var Nm=Ge.forwardRef(function(s,o){var r=s,{style:e}=r,n=O(r,["style"]);let l=Di(),{context:i}=l,a=O(l,["context"]),d=(0,U.useMergeRefs)([a.refs.setFloating,o]);return i.open?(0,ke.jsx)(U.FloatingPortal,{children:(0,ke.jsx)(U.FloatingFocusManager,{context:i,modal:a.modal,disabled:n.disableFocusManager,children:(0,ke.jsx)("div",b(h({ref:d,style:h(b(h({},a.floatingStyles),{zIndex:1e7}),e)},a.getFloatingProps(n)),{children:n.children}))})}):null});function Om(s){var r=s,{as:t,children:e,onClick:n}=r,o=O(r,["as","children","onClick"]);let{setOpen:i}=Di();return(0,ke.jsx)(t||"button",b(h({type:"button",onClick:l=>{n(l),i(!1),l.stopPropagation()}},o),{children:e}))}function Dd({trigger:t,children:e,placement:n="top"}){return(0,ke.jsxs)(on,{tooltip:!0,placement:n,children:[(0,ke.jsxs)(on.Content,{className:qs.tooltip,children:[e,(0,ke.jsx)("div",{className:qs.arrow})]}),(0,ke.jsx)(on.Trigger,{className:qs.tooltipTrigger,children:t})]})}on.Trigger=Mm;on.Content=Nm;on.Button=Om;var V=on;var _i={};Z(_i,{enUS:()=>Dm,nlNL:()=>_m});var Dm={showMore:[{type:0,value:"Show "},{type:1,value:"amount"},{type:0,value:" more"}]},_m={showMore:[{type:0,value:"Toon "},{type:1,value:"amount"},{type:0,value:" meer"}]};var _d={sources:"dd-cNsGl",source:"dd-LoJ6U",tooltip:"dd-7ZGu9",linkContent:"dd-O2IoN",showMoreSources:"dd-ev8Yr"};var lt=require("react/jsx-runtime"),Fm=3,Hm=({sources:t,onClick:e,sourceTestId:n="assistant-source"})=>{let o=P(_i),s=C("AssistantSources",_d),[r,i]=(0,Fd.useState)(!1),a=t.filter(l=>!!l.url),d=r?a:a.slice(0,Fm);return d.length===0?null:(0,lt.jsxs)("ul",{className:s.sources,children:[d.map(l=>(0,lt.jsx)("li",{className:s.source,"data-testid":n,children:(0,lt.jsxs)(V,{tooltip:!0,placement:"top-start",children:[(0,lt.jsx)(V.Trigger,{as:"a",rel:"noreferrer",target:"_blank",href:l.url,onClick:c=>{c.stopPropagation(),e==null||e(l)},children:(0,lt.jsx)("span",{className:s.linkContent,children:l.name})}),l.url&&(0,lt.jsx)(V.Content,{className:s.tooltip,children:decodeURIComponent(l.url)})]})},l.name)),d.length<t.length&&(0,lt.jsx)("button",{type:"button",className:s.showMoreSources,onClick:()=>i(!0),children:o("showMore",{amount:t.length-d.length})})]})},Hd=Hm;var Hi=D(require("classnames")),Re=require("react");var Gs=require("react"),Bm=["bottom","height","left","right","top","width"],Um=(t={},e={})=>Bm.some(n=>t[n]!==e[n]),dt=new Map,Bd,Ud=()=>{let t=[],e=[];dt.forEach((n,o)=>{if(o instanceof Element&&!o.isConnected){e.push(o);return}let s=o.getBoundingClientRect();Um(s,n.rect)&&(n.rect=s,t.push(n))}),e.forEach(n=>{dt.delete(n)}),t.forEach(n=>{n.callbacks.forEach(o=>o(n.rect))}),Bd=window.requestAnimationFrame(Ud)};function Km(t,e){return{observe(){let n=dt.size===0;if(dt.has(t)){let o=dt.get(t);o.callbacks.push(e),o.rect&&e(o.rect)}else dt.set(t,{rect:void 0,hasRectChanged:!1,callbacks:[e]});n&&Ud()},unobserve(){let n=dt.get(t);if(n){let o=n.callbacks.indexOf(e);o>=0&&n.callbacks.splice(o,1),n.callbacks.length||dt.delete(t),dt.size||cancelAnimationFrame(Bd)}}}}function Fi(t){let[e,n]=(0,Gs.useState)(null);return(0,Gs.useLayoutEffect)(()=>{if(!t.current)return;let o=Km(t.current,s=>{n(s)});return o.observe(),()=>{o.unobserve()}},[t]),e}var Dn=require("react"),zd=require("react-dom");var Kd=require("react");function At(t){(0,Kd.useEffect)(()=>{let e=n=>{n.isWithinRoot||t(n)};return document.body.addEventListener("mouseup",e),()=>{document.body.removeEventListener("mouseup",e)}},[t])}function sn(t){t.addEventListener("mouseup",e=>{e.isWithinRoot=!0},!0)}var Wd={root:"dd-r-dgo"};var Vd=({children:t,parentNode:e})=>{let[n,o]=(0,Dn.useState)(null),s=(0,Dn.useContext)(no);return(0,Dn.useLayoutEffect)(()=>{let r=document.createElement("div");return sn(r),r.classList.add(Wd.root),s!=null&&s.portalRootNode&&r.classList.add(s==null?void 0:s.portalRootNode),(e||document.body).appendChild(r),o(r),()=>{r.isConnected&&r.remove()}},[]),n?(0,zd.createPortal)(t,n):null};var Xe={ref:"dd-iz-KP",root:"dd-vEMon",positionAbove:"dd-mUCxM",positionBelow:"dd-7oZI7",positionLeft:"dd-BiWvD",positionRight:"dd-JIWea",alignStart:"dd-5ivu6",alignCenter:"dd-rnVkP",alignEnd:"dd-gZBp4"};var Xs=require("react/jsx-runtime"),Js=(t=!1)=>{let[e,n]=(0,Re.useState)(t),o=(0,Re.useCallback)(()=>n(!0),[]),s=(0,Re.useCallback)(()=>n(!1),[]),r=(0,Re.useCallback)(()=>n(a=>!a),[]),i=(0,Re.useRef)(null);return{opened:e,open:o,close:s,toggle:r,triggerRef:i}};function Bi(t,e=null,n=0){if(!t)return{display:"none"};let o=e?t.top-e.top<0||t.top<e.top-n?e.top-n:t.top+t.height>e.top+e.height+n?e.top+e.height+n-t.height:t.top:t.top,s=e?t.left<e.left-n?e.left-n:t.left+t.width>e.left+e.width+n?e.left+e.width+n-t.width:t.left:t.left;return{top:o,left:s,height:t.height,width:t.width}}var _n=l=>{var c=l,{className:t,triggerRef:e,boundaryRef:n=(0,Re.createRef)(),position:o="above",align:s="center",children:r,toStyle:i=Bi,parentNode:a}=c,d=O(c,["className","triggerRef","boundaryRef","position","align","children","toStyle","parentNode"]);let p=Fi(e),u=Fi(n),g=(0,Re.useMemo)(()=>i(p,u,0),[p,u]);return(0,Xs.jsx)(Vd,{parentNode:a,children:(0,Xs.jsx)("div",b(h({className:(0,Hi.default)(Xe.ref,{[Xe.positionAbove]:o==="above",[Xe.positionBelow]:o==="below",[Xe.positionLeft]:o==="left",[Xe.positionRight]:o==="right",[Xe.alignStart]:s==="start",[Xe.alignCenter]:s==="center",[Xe.alignEnd]:s==="end"}),style:g},d),{role:"dialog",children:(0,Xs.jsx)("div",{className:(0,Hi.default)(t,Xe.root),children:r})}))})};var jd={root:"dd-L7b3z",popover:"dd-OQOTB",options:"dd-Y12RE",arrow:"dd-cv33T",copyIcon:"dd-6xOsH",option:"dd-9oFX4",divider:"dd-aiZf8",fadeup:"dd-Jq9pd"};var Pe=require("react/jsx-runtime");function Wm(t){return`<button type="button" data-copy-icon class=${t}><svg version="1.1" x="0px" y="0px" viewBox="0 0 115.77 122.88" width="10px" height="10px" fill="black"><g><path d="M89.62,13.96v7.73h12.19h0.01v0.02c3.85,0.01,7.34,1.57,9.86,4.1c2.5,2.51,4.06,5.98,4.07,9.82h0.02v0.02 v73.27v0.01h-0.02c-0.01,3.84-1.57,7.33-4.1,9.86c-2.51,2.5-5.98,4.06-9.82,4.07v0.02h-0.02h-61.7H40.1v-0.02 c-3.84-0.01-7.34-1.57-9.86-4.1c-2.5-2.51-4.06-5.98-4.07-9.82h-0.02v-0.02V92.51H13.96h-0.01v-0.02c-3.84-0.01-7.34-1.57-9.86-4.1 c-2.5-2.51-4.06-5.98-4.07-9.82H0v-0.02V13.96v-0.01h0.02c0.01-3.85,1.58-7.34,4.1-9.86c2.51-2.5,5.98-4.06,9.82-4.07V0h0.02h61.7 h0.01v0.02c3.85,0.01,7.34,1.57,9.86,4.1c2.5,2.51,4.06,5.98,4.07,9.82h0.02V13.96L89.62,13.96z M79.04,21.69v-7.73v-0.02h0.02 c0-0.91-0.39-1.75-1.01-2.37c-0.61-0.61-1.46-1-2.37-1v0.02h-0.01h-61.7h-0.02v-0.02c-0.91,0-1.75,0.39-2.37,1.01 c-0.61,0.61-1,1.46-1,2.37h0.02v0.01v64.59v0.02h-0.02c0,0.91,0.39,1.75,1.01,2.37c0.61,0.61,1.46,1,2.37,1v-0.02h0.01h12.19V35.65 v-0.01h0.02c0.01-3.85,1.58-7.34,4.1-9.86c2.51-2.5,5.98-4.06,9.82-4.07v-0.02h0.02H79.04L79.04,21.69z M105.18,108.92V35.65v-0.02 h0.02c0-0.91-0.39-1.75-1.01-2.37c-0.61-0.61-1.46-1-2.37-1v0.02h-0.01h-61.7h-0.02v-0.02c-0.91,0-1.75,0.39-2.37,1.01 c-0.61,0.61-1,1.46-1,2.37h0.02v0.01v73.27v0.02h-0.02c0,0.91,0.39,1.75,1.01,2.37c0.61,0.61,1.46,1,2.37,1v-0.02h0.01h61.7h0.02 v0.02c0.91,0,1.75-0.39,2.37-1.01c0.61-0.61,1-1.46,1-2.37h-0.02V108.92L105.18,108.92z"/></g></svg></button>`}function Ui(t){var n,o;let e=t.cloneNode(!0);return e.querySelectorAll("div,button").forEach(s=>s.remove()),(o=(n=e.textContent)==null?void 0:n.trim())!=null?o:""}function zm(t){return t.replace(/\r\n/g,`
5
+ `)}var Vm=({content:t,useLabel:e,copyLabel:n,onCopy:o,onUse:s,sources:r,onSourceClick:i})=>{let a=C("Markdown",jd),d=(0,ct.useRef)(null),[l,c]=(0,ct.useState)(null),p=(0,ct.useMemo)(()=>{let v=qd.marked.parse(zm(t));return $d.default.sanitize(v.toString()).replaceAll("</code>",`${Wm(a.copyIcon)}</code>`).replaceAll('<a href="','<a target="_blank" rel="noreferrer noopener" href="')},[t]),u=v=>{var w;let x=v.target,T=!!((w=d.current)!=null&&w.querySelector("code"));if(["A","BUTTON"].includes(x.tagName)){c(null);return}l||T&&x.tagName!=="CODE"||!T&&x!==d.current||(x.addEventListener("mouseleave",()=>c(null),{once:!0}),c(x))},g=()=>{if(!l)return;c(null);let v=l.querySelector("button");v&&(It(v,a.fadeup),o==null||o(Ui(l)))},m=v=>{let x=v.target,T=x instanceof HTMLElement?x:null;if(x instanceof Element?x.closest("a"):null){v.stopPropagation();return}T&&"copyIcon"in T.dataset&&(It(T,a.fadeup),o==null||o(Ui(T.parentElement)))},f=()=>{!l||!s||(c(null),s(Ui(l)))},y=v=>{if(v===null)return;let x=v.getBoundingClientRect();x.left<0?v.style.transform=`translateX(${-x.left+2}px)`:x.right>window.innerWidth&&(v.style.transform=`translateX(${window.innerWidth-x.right-2}px)`)};return(0,Pe.jsxs)(ct.Fragment,{children:[l&&(o||s)&&(0,Pe.jsxs)(_n,{triggerRef:{current:l},className:a.popover,parentNode:l,children:[(0,Pe.jsxs)("div",{className:a.options,ref:y,children:[o&&(l==null?void 0:l.tagName)==="CODE"&&(0,Pe.jsx)("button",{type:"button",className:a.option,onClick:g,children:n}),s&&(0,Pe.jsxs)(ct.Fragment,{children:[(0,Pe.jsx)("div",{className:a.divider}),(0,Pe.jsx)("button",{type:"button",className:a.option,onClick:f,children:e})]})]}),(0,Pe.jsx)("div",{className:a.arrow})]}),(0,Pe.jsx)("div",{ref:d,"data-testid":"widget-markdown-content",className:a.root,dangerouslySetInnerHTML:{__html:p},onMouseOver:u,onClick:m}),r&&r.length>0&&(0,Pe.jsx)(Hd,{sources:r,onClick:i})]})},rn=Vm;var Jd=require("react");var Gd={loadingBar:"dd-6as-V",placeHolderShimmer:"dd-TFYmA"};var Xd=require("react/jsx-runtime"),jm=({width:t})=>{let e=C("LoadingProgressBar",Gd);return(0,Xd.jsx)("div",{className:e.loadingBar,style:{width:t}})},Qs=jm;var ut=require("react/jsx-runtime"),Zs=({title:t})=>{let e=(0,Jd.useRef)(null);return cs(e),(0,ut.jsx)(M,{ref:e,children:(0,ut.jsx)(H,{children:(0,ut.jsxs)(H.Content,{children:[(0,ut.jsx)(H.Title,{children:t}),(0,ut.jsx)(Qs,{width:"60%"}),(0,ut.jsx)(Qs,{width:"90%"}),(0,ut.jsx)(Qs,{width:"50%"})]})})})};var Fn={};Z(Fn,{enUS:()=>$m,nlNL:()=>qm});var $m={inputPlaceholder:[{type:0,value:"What is your question?"}],useCue:[{type:0,value:"Add to message"}],copyCue:[{type:0,value:"Copy"}],removeCue:[{type:0,value:"Close"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}],submitLabel:[{type:0,value:"Submit"}],resetLabel:[{type:0,value:"Reset"}],showMore:[{type:0,value:"Show "},{type:1,value:"amount"},{type:0,value:" more"}]},qm={inputPlaceholder:[{type:0,value:"Wat is je vraag?"}],useCue:[{type:0,value:"Voeg toe aan bericht"}],copyCue:[{type:0,value:"Kopi\xEBren"}],removeCue:[{type:0,value:"Sluiten"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}],submitLabel:[{type:0,value:"Verzend"}],resetLabel:[{type:0,value:"Gesprek wissen"}],showMore:[{type:0,value:"Toon "},{type:1,value:"amount"},{type:0,value:" meer"}]};var Ys={form:"dd-pleCH",formInput:"dd-pGJMY",formSubmit:"dd--gkRg",actionButton:"dd-I2NEH",resetContainer:"dd-qKIDX",sources:"dd-xf9c6",source:"dd-a-vyX",tooltip:"dd-EsgcZ",linkContent:"dd-gARDA",showMoreSources:"dd-uDGi-"};var Zd=require("react");var Qd={error:"dd-CoAuB"};var Ki={};Z(Ki,{enUS:()=>Gm,nlNL:()=>Xm});var Gm={errorPrefix:[{type:0,value:"Error:"}]},Xm={errorPrefix:[{type:0,value:"Foutmelding:"}]};var To=require("react/jsx-runtime"),Yd=({message:t})=>{let e=(0,Zd.useRef)(null),n=C("WidgetCardError",Qd),o=P(Ki);return cs(e),(0,To.jsx)(M,{ref:e,children:(0,To.jsx)(H,{children:(0,To.jsxs)(H.Content,{className:n.error,children:[o("errorPrefix")," ",t]})})})};var _=require("react/jsx-runtime"),Jm=3,Qm=({sources:t,onClick:e})=>{let n=P(Fn),o=C("WidgetKnowledgeAssistant",Ys),[s,r]=(0,G.useState)(!1),i=s?t:t.slice(0,Jm);return i.length===0?null:(0,_.jsxs)("ul",{className:o.sources,children:[i.map(a=>(0,_.jsx)("li",{className:o.source,"data-testid":"knowledge-assist-source",children:(0,_.jsxs)(V,{tooltip:!0,placement:"top-start",children:[(0,_.jsx)(V.Trigger,{as:"a",rel:"noreferrer",target:"_blank",href:a.url,onClick:d=>{d.stopPropagation(),e(a)},children:(0,_.jsx)("span",{className:o.linkContent,children:a.name})}),a.url&&(0,_.jsx)(V.Content,{className:o.tooltip,children:decodeURIComponent(a.url)})]})},a.name)),i<t&&(0,_.jsx)("button",{type:"button",className:o.showMoreSources,onClick:()=>r(!0),children:n("showMore",{amount:t.length-i.length})})]})},Zm=({title:t,description:e})=>(0,_.jsx)(M,{"data-testid":"knowledge-assist-empty-state",children:(0,_.jsx)(H,{children:(0,_.jsxs)(H.Content,{children:[(0,_.jsx)(H.Title,{children:t}),(0,_.jsx)(rn,{content:e})]})})}),Ym=({innerRef:t,item:e,hasKeyboardInput:n,onCopy:o,onUse:s,onSourceClick:r})=>{var d;let i=P(Fn),a=(0,G.useContext)(tr);return(0,_.jsxs)(M,{"data-testid":"knowledge-assist-answer",ref:t,children:[(0,_.jsx)(H,{children:(0,_.jsxs)(H.Content,{children:[(0,_.jsx)(H.Title,{children:e.question}),(0,_.jsx)(rn,{content:e.answer.answer,useLabel:i("useCue"),copyLabel:i("copyCue"),onCopy:o,onUse:n?s:void 0}),(0,_.jsx)(Qm,{sources:(d=e.answer.sources)!=null?d:[],onClick:r})]})}),a.assistantCode&&(0,_.jsxs)(M.ButtonsContainer,{children:[(0,_.jsx)("div",{}),(0,_.jsx)($s,{evaluationId:e.evaluationId,feedbackType:"assistant",assistantCode:a.assistantCode,assistantOutput:e.answer.answer})]})]})},tr=(0,G.createContext)(null),nr=({assistantCode:t,evaluateKnowledgeAssistFn:e,initialQuestion:n,children:o})=>{let[s,r]=(0,G.useState)(null),[i,a]=(0,G.useState)(!1),[d,l]=(0,G.useState)(null),[c,p]=(0,G.useState)(!!n),[u,g]=(0,G.useState)(null),m=(0,er.useDispatch)(),f=q(),y=Is(T=>{if(!t)throw new Error("No knowledge assistant was defined");return l(null),e({assistantCode:t,input:T,threadId:s,onNewThreadId(w){r(w)}})},{onSuccess(T){var w;f("Assistant response displayed",{evaluationId:T.evaluationId,assistantCode:t,assistantOutput:T.answer.answer,input:T.question,sources:(w=T.answer.sources)!=null?w:[]}),p(!1)},onError(T){var w;l((w=T.message)!=null?w:"Unknown error")}}),v=T=>S(null,null,function*(){a(!0),g(T),yield y.call(T),a(!1),g(null)}),x={isEnabled:!!t,assistantCode:t,isSubmitting:i,threadId:s,pendingInput:u,errorMessage:d,onSubmit:v,onReset(){s&&m(hd(s)),l(null),r(null),t&&f("Assistant thread reset",{threadId:s!=null?s:void 0,assistantCode:t})}};return(0,G.useEffect)(()=>{n&&x.isEnabled&&v(n)},[n]),(0,_.jsx)(tr.Provider,{value:x,children:o})},or=()=>{let t=P(Fn),e=C("WidgetKnowledgeAssistant",Ys),n=(0,G.useContext)(tr),o=(0,G.useRef)(null),[s,r]=(0,G.useState)(""),i=d=>{r(d.target.value)},a=d=>{d.preventDefault(),n.onSubmit(s).then(()=>{var l;o.current&&((l=o.current)==null||l.focus(),r(""))})};return n.isEnabled?(0,_.jsxs)("form",{className:e.form,onSubmit:a,children:[(0,_.jsx)("input",{ref:o,className:e.formInput,placeholder:t("inputPlaceholder"),type:"text",disabled:n.isSubmitting,value:s,onChange:i}),(0,_.jsx)("button",{type:"submit",disabled:n.isSubmitting||s==="",className:e.formSubmit,children:t("submitLabel")})]}):null},sr=({title:t,emptyState:e})=>{var m,f;let n=P(Fn),o=q(),s=C("WidgetKnowledgeAssistant",Ys),r=(0,G.useRef)(null),i=(0,G.useContext)(tr),a=(f=(0,er.useSelector)(gd((m=i.threadId)!=null?m:-1)))!=null?f:[],d=E("hasKeyboardInput"),l=fe(),c=(y,v)=>{qe(y),i.assistantCode&&o("Assistant response copied",{assistantCode:i.assistantCode,assistantOutput:y,copiedText:y,evaluationId:v.evaluationId})},p=(y,v)=>{i.assistantCode&&o("Assistant source clicked",{evaluationId:v.evaluationId,assistantCode:i.assistantCode,source:y})},u=y=>{y.preventDefault(),i.onReset()},g=(y,v)=>{l.send(it,{text:y,suggestion:{source:"assistant",sourceText:y}}),i.assistantCode&&o("Assistant response used",{assistantCode:i.assistantCode,evaluationId:v.evaluationId,assistantOutput:v.answer.answer,usedText:y})};return!i.isEnabled||(a==null?void 0:a.length)===0&&!i.isSubmitting&&!e&&!i.errorMessage?null:(0,_.jsxs)(G.Fragment,{children:[(0,_.jsx)(Ve,{type:"knowledge",title:t,"data-testid":"knowledge",children:(0,_.jsxs)(oe,{withDivider:!0,children:[e&&a.length===0&&!i.pendingInput&&(0,_.jsx)(Zm,h({},e)),a.map((y,v)=>(0,_.jsx)(Ym,{innerRef:v===a.length-1?r:void 0,item:y,hasKeyboardInput:d,onCopy:x=>c(x,y),onUse:x=>g(x,y),onSourceClick:x=>p(x,y)},`${y.question}_${y.answer}_${v}`)),i.pendingInput&&(0,_.jsx)(Zs,{title:i.pendingInput}),i.errorMessage&&(0,_.jsx)(Yd,{message:i.errorMessage})]})}),a.length>0&&(0,_.jsx)("div",{className:s.resetContainer,children:(0,_.jsx)(M.Button,{disabled:i.threadId===null||i.isSubmitting,onClick:u,children:n("resetLabel")})})]})};var bt=require("react-dom/client");var Xc=require("react");var Vi=require("react-redux");var ir=D(require("classnames")),He=require("react"),ar=require("react-redux");var rr=require("react");var tc={root:"dd-tvkOF",content:"dd-eXA1D"};var Wi=require("react/jsx-runtime"),ef=({isOpen:t,autoFocus:e,children:n,onClose:o,onBack:s,onKeyDown:r,overlayAriaLabel:i,contentAriaLabel:a})=>{let d=(0,rr.useRef)(null),l=C("Dialog",tc),c=u=>{if(u.key==="Escape"){u.preventDefault(),u.stopPropagation(),s();return}r&&r(u)},p=u=>{u.target===d.current&&t&&o()};return(0,rr.useEffect)(()=>{var u,g;!d.current||!t||!e||(g=(u=d.current)==null?void 0:u.querySelector("input, textarea"))==null||g.focus()},[t,e,d]),t?(0,Wi.jsx)("div",{role:"dialog","data-testid":"dialog",className:l.root,"aria-label":i,ref:d,onKeyDown:c,onMouseDown:p,children:(0,Wi.jsx)("div",{"data-testid":"dialog-content",className:l.content,"aria-label":a,children:n})}):null},Hn=ef;var oc=D(require("classnames"));var nc={root:"dd-ranhW"};var sc=require("react/jsx-runtime"),tf=o=>{var s=o,{className:t,value:e}=s,n=O(s,["className","value"]);let r=C("TextInput",nc);return(0,sc.jsx)("input",h({className:(0,oc.default)(t,r.root),type:"text",value:e},n))},wo=tf;var zi={};Z(zi,{enUS:()=>nf,nlNL:()=>of});var nf={back:[{type:0,value:"Back"}],promptTitle:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],verifyCodeTitle:[{type:0,value:"Paste the code from your email"}],verifyCodeBody:[{type:0,value:"Copy the code from the email you just received and paste it here."}],verifyCodeInputPlaceholder:[{type:0,value:"Paste link or code here"}],verifyCodeSubmitLabel:[{type:0,value:"Sign in"}],verifyCodeError:[{type:0,value:"Sign in failed. The code is probably no longer valid. Please "},{type:8,value:"login",children:[{type:0,value:"request new code"}]},{type:0,value:"."}],requestCodeTitle:[{type:0,value:"Have a code sent to your email"}],requestCodeBody:[{type:0,value:"Enter your email and request a code. If you are an existing "},{type:1,value:"productName"},{type:0,value:" user you will receive an email with a code. If you are a new user you will receive an email asking to request access to "},{type:1,value:"productName"},{type:0,value:" first."}],requestCodeInputPlaceholder:[{type:0,value:"Enter your email"}],requestCodeSubmitLabel:[{type:0,value:"Request code"}]},of={back:[{type:0,value:"Terug"}],promptTitle:[{type:0,value:"Login bij "},{type:1,value:"productName"}],verifyCodeTitle:[{type:0,value:"Plak de code uit je email"}],verifyCodeBody:[{type:0,value:"Kopieer de code uit de email en plak deze hier."}],verifyCodeInputPlaceholder:[{type:0,value:"Plak hier de code"}],verifyCodeSubmitLabel:[{type:0,value:"Inloggen"}],verifyCodeError:[{type:0,value:"Inloggen is niet gelukt. De code is waarschijnlijk niet meer geldig. "},{type:8,value:"login",children:[{type:0,value:"Vraag een nieuwe code aan"}]},{type:0,value:"."}],requestCodeTitle:[{type:0,value:"Verstuur een login code naar je email"}],requestCodeBody:[{type:0,value:"Voer je e-mailadres in en krijg een login code. Als je een bestaande "},{type:1,value:"productName"},{type:0,value:" gebruiker bent krijg je een email met een code. Als je een nieuwe gebruiker bent wordt er een email verstuurd met een toegangsverzoek voor "},{type:1,value:"productName"},{type:0,value:"."}],requestCodeInputPlaceholder:[{type:0,value:"Typ hier je e-mailadres"}],requestCodeSubmitLabel:[{type:0,value:"Code aanvragen"}]};var rc={root:"dd-lWxnE",anchorButton:"dd-TZ4in",errorMessage:"dd-fIsPg",title:"dd-pGhJx",subtitle:"dd-f5l29",text:"dd-iamoD",input:"dd-uhQZ3",actions:"dd-lubvx",button:"dd-CJsNI",primaryButton:"dd-MWBfl"};var J=require("react/jsx-runtime");var sf=t=>{try{let e=new URL(t);return new URLSearchParams(e.search).get("token")||void 0}catch(e){return t}},rf=({agentEmail:t,isOpen:e,origin:n="",onSuccess:o,onDismiss:s})=>{let r=P(zi),i=C("LoginTokenDialog",rc),a=(0,ar.useSelector)(cl),d=(0,ar.useDispatch)(),l=E("productName"),[c,p]=(0,He.useState)(t||""),[u,g]=(0,He.useState)(0),[m,f]=(0,He.useState)(""),y=(0,He.useCallback)(w=>S(null,null,function*(){w.preventDefault(),d(gl({email:c})),g(1)}),[n,c]),v=()=>{f(""),g(0)},x=(0,He.useCallback)(w=>S(null,null,function*(){w.preventDefault();let L=sf(w.target.elements.token.value);if(!L){f(r("verifyCodeError",{login:T}));return}d(so({token:L}))}),[n]),T=(0,He.useMemo)(()=>w=>(0,J.jsx)("button",{type:"button","data-testid":"login-token-dialog-back-button",className:i.anchorButton,onClick:v,children:w},"back-button"),[]);return(0,He.useEffect)(()=>{a==="error"&&f(r("verifyCodeError",{login:T})),a==="done"&&o()},[a]),(0,J.jsx)(Hn,{autoFocus:!0,isOpen:e,contentAriaLabel:r("promptTitle",{productName:l}),overlayAriaLabel:r("promptTitle",{productName:l}),onClose:s,onBack:s,children:(0,J.jsxs)("div",{className:i.root,children:[(0,J.jsx)("h1",{className:i.title,children:r("promptTitle",{productName:l})}),u===0&&(0,J.jsxs)("form",{onSubmit:y,children:[(0,J.jsx)("h2",{className:i.subtitle,children:r("requestCodeTitle")}),(0,J.jsx)("p",{className:i.text,children:r("requestCodeBody",{productName:l})}),(0,J.jsx)(wo,{className:i.input,name:"email",placeholder:r("requestCodeInputPlaceholder"),value:c,onChange:w=>p(w.target.value)}),(0,J.jsx)("div",{className:i.actions,children:(0,J.jsx)("button",{type:"submit",className:(0,ir.default)(i.button,i.primaryButton),children:r("requestCodeSubmitLabel")})})]}),u===1&&(0,J.jsxs)("form",{onSubmit:x,children:[(0,J.jsx)("h2",{className:i.subtitle,children:r("verifyCodeTitle")}),(0,J.jsx)("p",{className:i.text,children:r("verifyCodeBody")}),(0,J.jsx)(wo,{className:i.input,name:"token",placeholder:r("verifyCodeInputPlaceholder"),disabled:["loading","done"].includes(a)}),m&&(0,J.jsx)("div",{className:i.errorMessage,children:m}),(0,J.jsxs)("div",{className:i.actions,children:[(0,J.jsx)("button",{type:"button",className:(0,ir.default)(i.button),onClick:v,children:r("back")}),(0,J.jsx)("button",{type:"submit",className:(0,ir.default)(i.button,i.primaryButton),disabled:["loading","done"].includes(a),children:r("verifyCodeSubmitLabel")})]})]})]})})},ic=rf;var lc=require("react/jsx-runtime"),af=()=>{let t=(0,Vi.useSelector)(ul),e=(0,Vi.useSelector)(In),n=E("adminUrl"),o=fe(),s=()=>o.send(Mn,!1),r=()=>{o.send(Mn,!1),o.send(lo)};return(0,lc.jsx)(ic,{isOpen:t,agentEmail:e==null?void 0:e.agentEmail,origin:n,onDismiss:s,onSuccess:r})},ac=af;var qc=D(require("lodash.debounce")),ye=require("react"),Je=require("react-redux");var lr=require("@reduxjs/toolkit");var lf={data:null,fetchState:"idle"},dc=t=>t.contentTypes.data,Eo=(0,lr.createAsyncThunk)("contentTypes/getContentTypes",(t,e)=>S(null,null,function*(){return e.extra.deepdeskAPI.getContentTypes()})),df=(0,lr.createSlice)({name:"contentTypes",initialState:lf,reducers:{},extraReducers:t=>{t.addCase(Eo.pending,e=>{e.fetchState="loading"}).addCase(Eo.rejected,e=>{e.fetchState="error"}).addCase(Eo.fulfilled,(e,n)=>{e.fetchState="done",e.data=n.payload})}}),cc=df.reducer;var Bn=require("@reduxjs/toolkit");var cf={data:null,fetchState:"idle"},uf=[],Lt=t=>t.profile.data,pf=t=>t.profile.data?t.profile.data.uiConfig.widget.types:uf,Ro=(0,Bn.createSelector)([pf],t=>t.filter(e=>e.isActive)),uc=t=>{var e;return((e=t.profile.data)==null?void 0:e.onDemandAssistants)||[]},pc=t=>e=>Ro(e).find(n=>n.type===t),gc=t=>t.profile.data?!!t.profile.data.uiConfig.widget.types.find(e=>e.type==="custom-data"):!1,mc=t=>{var e,n;return(n=(e=t.profile.data)==null?void 0:e.knowledgeAssistantNew)!=null?n:null},ko=(0,Bn.createAsyncThunk)("profile/getProfile",(t,e)=>S(null,null,function*(){var r;let{deepdeskAPI:n}=e.extra,o=e.getState(),s=o.conversation.current;if(!s||!s.profileCode)throw new Error("No conversation of conversation profileCode found");return((r=o.profile.data)==null?void 0:r.code)===s.profileCode?o.profile.data:n.getProfile(s.profileCode)})),gf=(0,Bn.createSlice)({name:"profile",initialState:cf,reducers:{},extraReducers:t=>{t.addCase(ko.pending,e=>{e.fetchState="loading"}).addCase(ko.rejected,e=>{e.fetchState="error"}).addCase(ko.fulfilled,(e,n)=>{e.fetchState="done",e.data=n.payload})}}),fc=gf.reducer;var gt=require("react");var hc=require("react"),dr=D(require("classnames"));var be={root:"dd-U2SX4",list:"dd-cYTlj",listWrapper:"dd-GLQFR",listHorizontal:"dd-x-knl",page:"dd-1F4vk",search:"dd-nvbxc",pageNav:"dd-sRUuT",pageTitle:"dd-t-MKS",pageBackButton:"dd-cjptm",listHeader:"dd-Fg666",listHeading:"dd-w-xhJ",listMoreButton:"dd--mKep",listItem:"dd-wpvuA",listItemContent:"dd-V-mKo",listItemText:"dd-ukCHL",listItemDescription:"dd-sSyu4",listItemActions:"dd-xelho",listItemTooltip:"dd-SWFsE",listItemTooltipContent:"dd-I7J9N",truncate:"dd-IlopJ",lineClamp:"dd-Twaca",listItemTitle:"dd-lMGHq",listItemAction:"dd-xPLAs",listItemSelected:"dd-jFX0Y",sources:"dd-pZx4v",sourcesTitle:"dd-phYVd",source:"dd-DaR6h",sourceShowMore:"dd-M1-8j",icon:"dd-m6yxD",searchIcon:"dd-0AU-O",searchInputWrapper:"dd-DUFcE",searchInput:"dd-ukrlD",select:"dd--Tifv",selectType:"dd-IkZb2",selectWrapper:"dd-J14mx",image:"dd-RQgsB",imageSrc:"dd-jxh8F",imageSrcHidden:"dd-e20Jk",imageSrcStatus:"dd-j50Tt",imageTitle:"dd-qCjfW",actions:"dd-3mfWc",actionsWrapper:"dd-TjDyI",actionsBar:"dd-LiA35",actionButton:"dd-4wk0u",hasShortKeys:"dd-XilV-",actionShortcut:"dd-s4Mla",actionShortcutFixKerning:"dd-lyh5e"};var pt={};Z(pt,{enUS:()=>mf,nlNL:()=>ff});var mf={visitUrl:[{type:0,value:"Visit"}],back:[{type:0,value:"Back"}],loading:[{type:0,value:"Loading..."}],imageError:[{type:0,value:"Could not load image"}],showAll:[{type:0,value:"Show more"}],sources:[{type:0,value:"Sources"}],showMore:[{type:0,value:"Show "},{type:1,value:"amount"},{type:0,value:" more"}]},ff={visitUrl:[{type:0,value:"Bekijk"}],back:[{type:0,value:"Terug"}],loading:[{type:0,value:"Laden..."}],imageError:[{type:0,value:"Kan afbeelding niet laden"}],showAll:[{type:0,value:"Toon meer"}],sources:[{type:0,value:"Bronnen"}],showMore:[{type:0,value:"Toon "},{type:1,value:"amount"},{type:0,value:" meer"}]};var Mt=require("react/jsx-runtime"),hf=({src:t,title:e})=>{let n=C("CommandPalette",be),[o,s]=(0,hc.useState)("loading"),r=P(pt);return(0,Mt.jsxs)("div",{className:n.image,children:[(0,Mt.jsx)("img",{src:t,alt:e,onLoad:()=>s("done"),onError:()=>s("error"),className:(0,dr.default)(n.imageSrc,{[n.imageSrcHidden]:["loading","error"].includes(o)})}),o==="loading"&&(0,Mt.jsx)("span",{className:(0,dr.default)(n.imageSrc,n.imageSrcStatus),children:r("loading")}),o==="error"&&(0,Mt.jsx)("span",{className:(0,dr.default)(n.imageSrc,n.imageSrcStatus),children:(0,Mt.jsx)(is,{})}),e&&(0,Mt.jsx)("span",{className:n.imageTitle,children:e})]})},yc=hf;var vc=D(require("react")),Sc=D(require("classnames"));var an=require("react/jsx-runtime");function ji({children:t,heading:e,orientation:n,hasMore:o,onShowAll:s}){let r=P(pt),i=C("CommandPalette",be);return vc.default.Children.count(t)===0?null:(0,an.jsxs)("div",{"data-testid":"commandpalette-list",className:i.list,children:[(e||o)&&(0,an.jsxs)("div",{className:i.listHeader,children:[e&&(0,an.jsx)("h4",{className:i.listHeading,children:e}),o&&s&&(0,an.jsx)("button",{onClick:s,className:i.listMoreButton,type:"button",children:r("showAll")})]}),(0,an.jsx)("div",{className:(0,Sc.default)(i.listWrapper,n==="horizontal"&&i.listHorizontal),children:t})]})}var Io=D(require("classnames")),Gi=require("interweave"),Nt=require("react");var yf=/[.*+?^${}()|[\]\\]/g,vf=/[^0-9A-Za-zÀ-ÖØ-öø-ÿ](?=[0-9A-Za-zÀ-ÖØ-öø-ÿ]*$)/;function Sf(t){return t.replace(yf,"\\$&")}function xf(t,e){let n=t.split("").findIndex((o,s)=>o!==e[s]);return n>-1?n:Math.min(t.length,e.length)}function bf(t){return t.search(vf)}function xc(t,e=[]){let n=t;return e.forEach(o=>{if(!o)return;let s=new RegExp(`\\b(${Sf(o)})\\b`,"gi");n=n.replace(s,"<strong>$1</strong>")}),n}function bc(t){return t.replace(ps,'<mark data-type="placeholder">$1</mark>')}function Un(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}function Cf(t,e){return t.split("").map((i,a)=>({char:i,index:a})).filter(({char:i,index:a})=>/\s/.test(i)&&a<=e).map(({index:i})=>i).reverse()[0]}function $i(t,e,n={}){if(e){let o=xf(e.toLowerCase(),t.toLowerCase()),s=Un(t.substring(o,t.length));if(n.stripAgentPart){let d=t.substring(0,o),l=bf(d);return`<span style="opacity: 0.5">${d.substring(l+1)}</span>${s}`}let i=e.split(al).length>3||e.length>30?Cf(e.trim(),o):0;return`${`${i>0?"\u2026":""}${Un(t.substring(i,o))}`}<strong>${s}</strong>`}return t}var Tf=/(<\/[a-zA-Z]+[0-9]?>|<[a-zA-Z]+\s?\/>|<br>)/i;function Po(t){return Tf.test(t)}function qi(t){var n;let e=document.createElement("template");return e.innerHTML=t,(n=e.content.textContent)!=null?n:""}var cr=D(require("react")),wc=require("react/jsx-runtime"),Cc=cr.default.createContext(void 0);function Kn(){let t=cr.default.useContext(Cc);if(t===void 0)throw new Error("useCommandPalette must be used within the CommandPalette component");return t}var Tc=({children:t,page:e,isOpen:n,onChangeOpen:o,selected:s,setSelected:r})=>{let i=cr.default.useMemo(()=>({page:e,isOpen:n,onChangeOpen:o,selected:s,setSelected:r}),[n,e,s]);return(0,wc.jsx)(Cc.Provider,{value:i,children:t})};var ce=require("react/jsx-runtime"),wf=3,Ef=90,Ec=({children:t})=>{let e=C("CommandPalette",be);return(0,ce.jsx)("div",{className:e.listItemActions,children:t})};function Xi(g){var m=g,{closeOnSelect:t=!0,lineClamp:e,tooltip:n,children:o,onClick:s,extra:r,onSourceClick:i,description:a,sources:d,id:l,styles:c,defaultSourcesAmount:p=wf}=m,u=O(m,["closeOnSelect","lineClamp","tooltip","children","onClick","extra","onSourceClick","description","sources","id","styles","defaultSourcesAmount"]);var ot;let f=P(pt),[y,v]=(0,Nt.useState)(!1),{selected:x,onChangeOpen:T}=Kn(),[w,L]=(0,Nt.useState)(!1),R=C("CommandPalette",be);function I(F){s(F),t&&T(!1)}let z=(0,Nt.useMemo)(()=>typeof a!="string"?a:Po(a)?qi(a).trim():a,[a]),Me=(0,Nt.useMemo)(()=>typeof n!="string"?n:Po(n)?qi(n).trim():n,[n]);return(0,Nt.useEffect)(()=>{L(x===l)},[x]),(0,ce.jsxs)("div",{className:(0,Io.default)(R.listItem,l===x&&R.listItemSelected),children:[(0,ce.jsxs)(V,{placement:"right-start",tooltip:!0,onOpenChange:L,open:w,children:[(0,ce.jsx)(V.Trigger,b(h({className:R.listItemAction,"aria-disabled":(ot=u.disabled)!=null?ot:!1,onClick:I,"data-command-palette-item":!0,"data-item-id":l},u),{children:(0,ce.jsxs)("div",{className:R.listItemContent,children:[typeof o=="string"?(0,ce.jsx)("p",{className:(0,Io.default)(R.listItemText,R.truncate,c==null?void 0:c.title),children:o}):o,z&&typeof z=="string"?(0,ce.jsx)(Gi.Interweave,{tagName:"p",allowList:[],content:z,className:(0,Io.default)(R.listItemDescription,c==null?void 0:c.description,e?R.lineClamp:R.truncate)}):a]})})),Me&&Me.length>Ef&&(0,ce.jsx)(V.Content,{className:R.listItemTooltip,disableFocusManager:!0,children:(0,ce.jsx)(Gi.Interweave,{className:R.listItemTooltipContent,allowList:["h1","h2","h3","h4","h5","h6","a","p","br"],tagName:"div",content:Me.replace(/\n/g,"<br />")})})]}),l===x&&r,d&&d.length>0&&(0,ce.jsxs)("div",{className:R.sources,children:[(0,ce.jsx)("span",{className:R.sourcesTitle,children:f("sources")}),d.slice(0,y?d.length:p).map(F=>(0,ce.jsx)("a",{className:R.source,href:F.url,target:"_blank",title:F.url,rel:"noopener noreferrer","data-testid":"source",onClick:()=>i==null?void 0:i(F),children:F.name},F.url)),!y&&d.length>p&&(0,ce.jsx)("button",{className:(0,Io.default)(R.source,R.sourceShowMore),type:"button",onClick:()=>v(!0),children:f("showMore",{amount:d.length-p})})]})]})}var Ao=require("react/jsx-runtime"),kc=()=>(0,Ao.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 256 512","aria-labelledby":"angleLeftTitle",children:[(0,Ao.jsx)("title",{id:"angleLeftTitle",children:"AngleLeft"}),(0,Ao.jsx)("path",{d:"M192 448c-8.188 0-16.38-3.125-22.62-9.375l-160-160c-12.5-12.5-12.5-32.75 0-45.25l160-160c12.5-12.5 32.75-12.5 45.25 0s12.5 32.75 0 45.25L77.25 256l137.4 137.4c12.5 12.5 12.5 32.75 0 45.25C208.4 444.9 200.2 448 192 448z"})]});var ln=require("react/jsx-runtime");function Ji({children:t,title:e,id:n,onDismiss:o}){let s=P(pt),r=C("CommandPalette",be),{page:i}=Kn();return i!==n?null:(0,ln.jsxs)("div",{className:r.page,id:`page_${n}`,tabIndex:-1,children:[o&&(0,ln.jsxs)("div",{className:r.pageNav,children:[(0,ln.jsxs)("button",{className:r.pageBackButton,type:"button",onClick:o,children:[(0,ln.jsx)(kc,{}),s("back")]}),e&&(0,ln.jsx)("h3",{className:r.pageTitle,children:e})]}),t]})}var Rc=require("react");var Lo=require("react/jsx-runtime"),Wn=()=>(0,Lo.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 0 24 24",width:"1em",fill:"currentColor",children:[(0,Lo.jsx)("path",{d:"M0 0h24v24H0z",fill:"none"}),(0,Lo.jsx)("path",{d:"M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"})]});var Be=require("react/jsx-runtime");function kf({onChange:t,onChangeType:e,placeholder:n,typePlaceholder:o,types:s,value:r,selectedType:i},a){let d=C("CommandPalette",be);return(0,Be.jsxs)("div",{className:d.search,children:[(0,Be.jsx)("div",{className:d.searchIcon,children:(0,Be.jsx)(Wn,{})}),(0,Be.jsxs)("div",{className:d.searchInputWrapper,children:[(0,Be.jsx)("input",{ref:a,spellCheck:!1,autoComplete:"off",onChange:l=>{t(l.currentTarget.value)},onFocus:l=>{l.currentTarget.select()},className:d.searchInput,placeholder:n,value:r,type:"text",id:"command-palette-search-input",autoFocus:!0}),s&&s.length>0&&(0,Be.jsx)("div",{className:d.selectWrapper,children:(0,Be.jsxs)("select",{"data-testid":"command-palette-type-select",className:d.select,onChange:l=>e(l.target.value===o?void 0:l.target.value),value:i||o,children:[o&&(0,Be.jsx)("option",{children:o}),s.map(l=>(0,Be.jsx)("option",{value:l.value,children:l.label},l.value))]})})]})]})}var Pc=(0,Rc.forwardRef)(kf);var Qi=D(require("classnames"));var ur=require("react/jsx-runtime"),Rf=s=>{var r=s,{onClick:t,shortKeys:e,children:n}=r,o=O(r,["onClick","shortKeys","children"]);let i=C("CommandPalette",be);return(0,ur.jsxs)("button",b(h({type:"button"},o),{onClick:t,className:(0,Qi.default)(i.actionButton,o.className,{[i.hasShortKeys]:e&&e.length>0}),children:[n,e==null?void 0:e.map(a=>(0,ur.jsx)("span",{className:(0,Qi.default)(i.actionShortcut,a===8629&&i.actionShortcutFixKerning),children:typeof a=="number"?String.fromCharCode(a):a},a))]}))},Ic=Rf;var Mo=require("react/jsx-runtime"),Pf="[data-command-palette-item]";function dn({placeholder:t="Start typing to search...",typePlaceholder:e="All types",defaultPage:n="search",page:o,onChangePage:s,onChangeSearch:r,onChangeType:i,onChangeOpen:a,selectedType:d,types:l,children:c,isOpen:p,search:u,updateDeps:g=[]}){let[m,f]=(0,gt.useState)(),y=(0,gt.useRef)(null),v=()=>{s&&s(n),i(void 0),r(""),a(!1)},x=()=>{var F;if(o!==n&&s){s(n);return}if(d&&i){i(void 0),(F=y.current)==null||F.focus();return}if(u.length>0){r("");return}a(!1)},T=()=>{let F=w();F.length!==0&&f(F[0].dataset.itemId)},w=()=>Array.from(document.querySelectorAll(Pf)||[]),L=F=>document.querySelector(`[data-item-id=${F}]`),R=F=>{let j=L(F);j&&f(j.dataset.itemId)},I=F=>{let j=L(F);j&&j.scrollIntoView({behavior:"smooth"})},z=()=>{if(!m)return;let F=w(),j=L(m);if(!j)return;let ze=F.indexOf(j),ne=F[ze+1];ne!=null&&ne.dataset.itemId?R(ne.dataset.itemId):T()},Me=()=>{if(!m)return;let F=w(),j=L(m);if(!j)return;let ze=F.indexOf(j),ne=F[ze-1];ne!=null&&ne.dataset.itemId?R(ne.dataset.itemId):R(F[F.length-1].dataset.itemId)},ot=(0,gt.useCallback)(F=>{switch(F.key){case"ArrowDown":{F.preventDefault(),z();break}case"ArrowUp":{F.preventDefault(),Me();break}case"Enter":{if(m){let j=L(m);j==null||j.click()}break}}},[m]);return(0,gt.useEffect)(()=>{T()},[u,o,d,p,...g]),(0,gt.useEffect)(()=>{m&&I(m)},[m]),(0,Mo.jsx)(Hn,{autoFocus:!0,contentAriaLabel:"Search Results",overlayAriaLabel:"Command Palette",isOpen:p,onBack:x,onClose:v,onKeyDown:ot,children:(0,Mo.jsxs)(Tc,{selected:m,setSelected:f,isOpen:p,onChangeOpen:a,page:o,children:[o===n&&(0,Mo.jsx)(Pc,{ref:y,onChange:r,onChangeType:i,placeholder:t,value:u,selectedType:d,types:l,typePlaceholder:e}),c]})})}dn.Page=Ji;dn.List=ji;dn.Image=yc;dn.ListItem=Xi;dn.ListItemActions=Ec;dn.Button=Ic;var te=dn;var Ac=require("react");function Lc(t,e){(0,Ac.useEffect)(()=>{let n=o=>{var s;((s=navigator==null?void 0:navigator.platform)!=null&&s.toLowerCase().includes("mac")?o.metaKey:o.ctrlKey)&&o.key===t&&(o.preventDefault(),o.stopPropagation(),e())};return document.addEventListener("keydown",n),()=>{document.removeEventListener("keydown",n)}},[])}var No=require("react"),gr=require("react-redux");var zn=require("@reduxjs/toolkit");var Mc={data:null,fetchState:"idle"},If=t=>{var e;return(e=t.entities.data)!=null?e:null},pr=(0,zn.createSelector)([If,In,_l],(t,e,n)=>{var a;let o=[],{visitorName:s}=n!=null?n:{},{agentName:r,agentNickname:i}=e!=null?e:{};return r&&r!==s&&o.push(r),i&&i!==s&&o.push(i),(a=t==null?void 0:t.filter(d=>!o.includes(d.text)))!=null?a:null}),Ue=(0,zn.createAsyncThunk)("entities/getEntities",(t,e)=>S(null,null,function*(){let{deepdeskAPI:n,dynamicThunkObject:o}=e.extra;if(!o.conversationQuery)return Promise.resolve([]);let s=o.conversationQuery,r=yield s();return r.length===0?Promise.resolve([]):n.getEntities(r)})),Af=t=>t.filter((e,n)=>n===t.findIndex(o=>o.text===e.text)),Lf=(0,zn.createSlice)({name:"entities",initialState:Mc,reducers:{},extraReducers:t=>{t.addCase(Ue.pending,e=>{e.fetchState="loading"}).addCase(Ue.rejected,e=>{e.fetchState="error"}).addCase(Ue.fulfilled,(e,n)=>{e.fetchState="done",e.data=Af(e.data?[...e.data,...n.payload]:n.payload)}).addCase(Y,()=>Mc)}}),Nc=Lf.reducer;var Zi={};Z(Zi,{enUS:()=>Mf,nlNL:()=>Nf});var Mf={noResults:[{type:0,value:"No entities have been found"}],copy:[{type:0,value:"Copy"}],use:[{type:0,value:"Use"}]},Nf={noResults:[{type:0,value:"Er zijn geen entiteiten gevonden"}],copy:[{type:0,value:"Kopieer"}],use:[{type:0,value:"Gebruik"}]};var Oc={root:"dd-TYTKs",empty:"dd-AU7uT"};var Vn=require("react/jsx-runtime"),Of=({onCopy:t})=>{let e=(0,No.useRef)(null),n=C("EntitiesList",Oc),o=(0,gr.useSelector)(pr),{setSelected:s}=Kn(),r=P(Zi),i=(0,gr.useDispatch)();return(0,No.useEffect)(()=>{i(Ue())},[]),(0,No.useEffect)(()=>{e.current&&(e.current.focus(),s("entity-0"))},[e]),(0,Vn.jsxs)("div",{className:n.root,ref:e,tabIndex:-1,children:[o&&o.length>0&&(0,Vn.jsx)(te.List,{children:o.map((a,d)=>(0,Vn.jsx)(te.ListItem,{id:`entity-${d}`,closeOnSelect:!0,onClick:()=>t(a),children:a.text},a.text))},"entities"),o&&o.length===0&&(0,Vn.jsx)("p",{className:n.empty,children:r("noResults")})]})},Dc=Of;var Yi=require("react/jsx-runtime"),mr=t=>(0,Yi.jsx)("svg",b(h({xmlns:"http://www.w3.org/2000/svg",height:"16",width:"14",viewBox:"0 0 448 512"},t),{children:(0,Yi.jsx)("path",{fill:"currentColor",d:"M8 256a56 56 0 1 1 112 0A56 56 0 1 1 8 256zm160 0a56 56 0 1 1 112 0 56 56 0 1 1 -112 0zm216-56a56 56 0 1 1 0 112 56 56 0 1 1 0-112z"})}));var Oo={};Z(Oo,{enUS:()=>Df,nlNL:()=>_f});var Df={preview:[{type:0,value:"Preview"}],useSuggestion:[{type:0,value:"Add"}],sendSuggestion:[{type:0,value:"Send"}],suggestionSent:[{type:0,value:"Sent"}],sendingError:[{type:0,value:"Sending failed"}],tryAgain:[{type:0,value:"Try again"}],editSuggestion:[{type:0,value:"Edit"}],visitUrl:[{type:0,value:"Visit"}],giveFeedback:[{type:0,value:"Give feedback"}],answer:[{type:0,value:"Answer"}]},_f={preview:[{type:0,value:"Preview"}],useSuggestion:[{type:0,value:"Gebruik"}],sendSuggestion:[{type:0,value:"Verzenden"}],suggestionSent:[{type:0,value:"Verzonden"}],sendingError:[{type:0,value:"Verzenden mislukt"}],tryAgain:[{type:0,value:"Probeer opnieuw"}],editSuggestion:[{type:0,value:"Bewerken"}],visitUrl:[{type:0,value:"Bekijk"}],giveFeedback:[{type:0,value:"Geef feedback"}],answer:[{type:0,value:"Antwoord"}]};var _c=require("react-redux");var Do={trigger:"dd-dQ-OH",content:"dd-9k0N3",item:"dd-va6pa"};var Ot=require("react/jsx-runtime"),Ff=({suggestion:t,source:e,context:n})=>{let o=P(Oo),s=(0,_c.useSelector)($e),r=q(),i=E("enableSuggestionFeedback"),a=zs({conversationId:s,type:e,contentType:"text",content:t.text,data:n?JSON.stringify({context:n}):void 0}),d=js(a),l=()=>S(null,null,function*(){r("suggestion feedback",{text:t.text,source:e,context:n}),d.mode==="custom-handler"&&(yield d.open())});return!i||d.mode==="disabled"?null:(0,Ot.jsxs)(V,{placement:"top-end",children:[(0,Ot.jsx)(V.Trigger,{className:Do.trigger,children:(0,Ot.jsx)(mr,{"data-testid":"feedback-dropdown-trigger"})}),(0,Ot.jsx)(V.Content,{className:Do.content,children:d.mode==="custom-handler"?(0,Ot.jsx)(V.Button,{className:Do.item,onClick:l,children:o("giveFeedback")}):(0,Ot.jsx)(V.Button,{className:Do.item,as:"a",onClick:l,target:"_blank",rel:"noreferrer noopener",href:d.href,children:o("giveFeedback")})})]})},fr=Ff;var _o={};Z(_o,{enUS:()=>Hf,nlNL:()=>Bf});var Hf={personalCollectionLink:[{type:0,value:"Go to Personal Collection"}],searchPlaceholder:[{type:0,value:"Start typing to search..."}],urlSuggestions:[{type:0,value:"URL suggestions"}],personalSuggestions:[{type:0,value:"Personal suggestions"}],pinnedMessages:[{type:0,value:"Pinned messages"}],imageSuggestions:[{type:0,value:"Images"}],typePlaceholder:[{type:0,value:"All types"}],navigation:[{type:0,value:"Navigation"}],entitiesClipboard:[{type:0,value:"Conversation clipper"}],entitiesTitle:[{type:0,value:"Copy to your clipboard"}],knowledgeAssist:[{type:0,value:"Knowledge assist"}],commands:[{type:0,value:"Commands"}],use:[{type:0,value:"Use"}],preview:[{type:0,value:"Preview"}],warning:[{type:0,value:"Are you sure you want to discard the message?"}]},Bf={personalCollectionLink:[{type:0,value:"Ga naar persoonlijke collectie"}],searchPlaceholder:[{type:0,value:"Begin met typen om te zoeken..."}],personalSuggestions:[{type:0,value:"Persoonlijke suggesties"}],urlSuggestions:[{type:0,value:"URL suggesties"}],imageSuggestions:[{type:0,value:"Afbeeldingen"}],navigation:[{type:0,value:"Navigatie"}],typePlaceholder:[{type:0,value:"Alle types"}],pinnedMessages:[{type:0,value:"Actueel"}],entitiesClipboard:[{type:0,value:"Klembord"}],entitiesTitle:[{type:0,value:"Kopieer naar klembord"}],knowledgeAssist:[{type:0,value:"Knowledge assist"}],commands:[{type:0,value:"Acties"}],use:[{type:0,value:"Gebruik"}],preview:[{type:0,value:"Bewerk"}],warning:[{type:0,value:"Weet je zeker dat je de wijzigingen wilt weggooien?"}]};var jc=require("react"),vr=require("react-redux");var cn=require("@reduxjs/toolkit");var Uf=["{amount}"," {amount}","{date}","{email}","{iban}","{name}","{postal_code}","{street}","{tarif}","{usage}","{3_digits}","{4_digits}","{5_digits}","{6_digits}","{7_digits}","{8_digits}","{9_digits}","{10_digits}"],Kf=new RegExp(Uf.map(t=>`(?:${t.replace("{","\\{").replace("}","\\}")})`).join("|"));function Fc(t,e){let n=t.split(Kf),o=0,s=[];for(let r=0;r<n.length;r++){let i=n[r];if(s.push(i),r===n.length-1)break;if(e.indexOf(i)===-1)return t;let a=n[r+1],d=r===n.length-2;o+=i.length;let l=o;if(d){let p=a.charAt(0),u=0;do l=p?e.indexOf(p,l+1):-1,u+=1;while(l!==-1&&a.indexOf(e.slice(l))!==0);if(l===-1&&u>2)return t}else l=a&&a!==""?e.indexOf(a,o):-1;let c=l===-1?e.slice(o):e.slice(o,l);s.push(c),o=l}return s.join("")}function Hc(t,e){return typeof e=="boolean"?t:t.slice(0,e)}var Uc={suggestions:[],fetchState:"idle"},Bc={default:Uc},Kc=t=>e=>{var n,o;return(o=(n=e.textSuggestions[t])==null?void 0:n.suggestions)!=null?o:[]},hr=t=>t.textSuggestions,Wc=t=>{let e=t.toLowerCase();return n=>{let o=n.text.toLowerCase();return o.startsWith(e)&&o.length>e.length}},yr=(0,cn.createAction)("textSuggestions/refresh"),Ke=(0,cn.createAsyncThunk)("textSuggestions/recommendations",(t,e)=>S(null,null,function*(){var c,p,u;let{deepdeskAPI:n}=e.extra,o=e.getState(),{platformVariables:s}=o.info,{textSuggestionsCount:r,inlineSuggestions:i}=o.settings,a=Xt(o),d=(c=o.conversation.current)==null?void 0:c.id;if(!d)throw new Error("No current conversation to fetch text suggestions");if(!((p=o.profile.data)!=null&&p.recommendationEngine))return[];let l=[];if(t==="sticky-messages"){let g=(u=o.profile.data)==null?void 0:u.code;if(!g)throw new Error("No current profile to fetch pinned messages");l=yield n.getPinnedMessages(g)}else l=yield n.getTextSuggestions(d,ao(o),t);if(s&&(l=l.map(g=>h(b(h({},g),{text:De(g.text,s)}),g.title?{title:De(g.title,s)}:{}))),t==="default"){let g=i?l.filter(Wc(a)):l;e.dispatch(Rt(g.slice(0,r)))}return l})),Fo=(0,cn.createAsyncThunk)("textSuggestions/autocompletions",(t,e)=>S(null,null,function*(){var c,p;let{deepdeskAPI:n}=e.extra,o=e.getState(),s=(c=o.conversation.current)==null?void 0:c.id,{platformVariables:r}=o.info,{textSuggestionsCount:i,deanonymize:a,inlineSuggestions:d}=o.settings;if(!((p=o.profile.data)!=null&&p.recommendationEngine))return[];if(!s)throw new Error("No current conversation to fetch text suggestions");let l=yield n.getAutocompleteSuggestions(s,b(h({},ao(o)),{input:t}));if(!e.getState().input.text)throw new Error("Abort");return d&&(l=l.filter(Wc(t))),r&&(l=l.map(u=>b(h({},u),{text:De(u.text,r)}))),a&&(l=l.map(u=>b(h({},u),{text:u.source!=="trie-with-typos"?Fc(u.text,t):u.text}))),l=Hc(l,i),e.dispatch(Rt(l)),l})),zc=(0,cn.createSlice)({name:"textSuggestions",initialState:Bc,reducers:{setTextSuggestions:{reducer(t,e){let{contentType:n}=e.payload;t[n].fetchState="done",t[n].suggestions=e.payload.suggestions},prepare(t,e){return{payload:{contentType:t,suggestions:e}}}}},extraReducers:t=>{t.addCase(Ke.pending,(e,n)=>{let o=n.meta.arg,s=e[o]||Uc;return b(h({},e),{[o]:b(h({},s),{fetchState:"loading"})})}).addCase(Ke.rejected,(e,n)=>{let o=n.meta.arg;e[o]&&(e[o].fetchState="error")}).addCase(Ke.fulfilled,(e,n)=>{let o=n.meta.arg;e[o]&&(e[o].fetchState="done",e[o].suggestions=n.payload)}).addCase(Fo.pending,e=>{e.default.fetchState="loading"}).addCase(Fo.rejected,e=>{e.default.fetchState="error"}).addCase(Fo.fulfilled,(e,n)=>{e.default.fetchState="done",e.default.suggestions=n.payload}).addCase(Y,()=>Bc)}}),{setTextSuggestions:DE}=zc.actions,Vc=zc.reducer;var un=require("react/jsx-runtime"),Wf=({types:t,commands:e,onClick:n})=>{let o=(0,vr.useDispatch)(),s=P(_o),r=(0,vr.useSelector)(hr);return(0,jc.useEffect)(()=>{t.forEach(({type:i})=>{(!r[i]||r[i].suggestions.length===0)&&o(Ke(i))})},[]),(0,un.jsxs)("div",{children:[e.length>0&&(0,un.jsx)(te.List,{heading:s("commands"),children:e.map((i,a)=>(0,un.jsx)(te.ListItem,{id:`command-${a}`,closeOnSelect:!1,onClick:i.onClick,children:i.label},i.label))}),t.map(({type:i,title:a})=>{var d;return(0,un.jsx)(te.List,{heading:a,orientation:"vertical",children:(d=r[i])==null?void 0:d.suggestions.map((l,c)=>(0,un.jsx)(te.ListItem,{id:`${i}-${c}`,closeOnSelect:!1,description:l.title&&l.text,onClick:()=>n(l.text,l),"data-testid":"search-overlay-suggestion",children:l.title||l.text},`${l.id}-${l.text}`))},i)})]})},$c=Wf;var ue=require("react/jsx-runtime"),Vf=200,jf=5,$f=4,ea=(t,e,n)=>t.slice(0,n?10:e.toLowerCase()==="image"?$f:jf),qf=(t,e)=>!e||t.toLowerCase().includes(e.toLowerCase()),Gf=()=>{var ze,ne,Wt;let t=(0,Je.useDispatch)(),e=fe(),n=P(_o),[o,s]=(0,ye.useState)(!1),[r,i]=(0,ye.useState)(""),a=(0,Je.useSelector)($l),d=(0,Je.useSelector)(Lt),[l,c]=(0,ye.useState)(),p=(0,Je.useSelector)(se),u=E("showSearch"),g=E("enableSuggestionFeedback"),m=E("showEntitiesCommand"),f=E("showImageSearch"),y=E("searchTriggerKey"),v=(0,Je.useSelector)(dc),x=(0,Je.useSelector)(Si),T=(0,Je.useSelector)(ql),w=(0,Je.useSelector)(jl),L=((Wt=(ne=(ze=d==null?void 0:d.uiConfig)==null?void 0:ze.search)==null?void 0:ne.initialTypes)==null?void 0:Wt.filter(({isActive:N})=>N))||[],R=q(),I=(0,ye.useMemo)(()=>{let N=ge=>ea(x.filter(X=>X.type===ge.toUpperCase()),ge,l),$=(v==null?void 0:v.map(ge=>({value:ge.code.toUpperCase(),label:`${ge.name}s`,list:N(ge.code.toUpperCase()),listOrientation:"vertical",lineClamp:!0})))||[];if($.push({value:"PERSONAL",label:n("personalSuggestions"),list:N("PERSONAL"),lineClamp:!1,listOrientation:"vertical"},{value:"URL",label:n("urlSuggestions"),list:N("URL"),lineClamp:!1,listOrientation:"vertical"},{value:"STICKYMESSAGE",label:n("pinnedMessages"),list:N("STICKYMESSAGE"),lineClamp:!1,listOrientation:"vertical"}),f&&$.push({value:"IMAGE",label:n("imageSuggestions"),lineClamp:!1,list:N("IMAGE"),listOrientation:"horizontal"}),L.length===0)return $;let st=L.map(ge=>$.find(X=>X.value.toLowerCase()===ge.type)).filter(ge=>!!ge),bn=$.filter(ge=>!st.find(X=>X.value===ge.value));return[...st,...bn]},[v,L,f,l]),z=[{label:n("entitiesClipboard"),onClick:()=>t(Ln("entities")),shouldShow:m&&qf(n("entitiesClipboard"),r)}].filter(N=>N.shouldShow).filter(()=>!l),Me=(0,ye.useCallback)((0,qc.default)((N,$)=>{t(en({query:N,type:$,tags:["search-overlay"],size:l?50:20}))},Vf),[l]),ot=(0,ye.useCallback)((N,$)=>{$.type==="IMAGE"?e.send(bi,{suggestion:$}):e.send(it,{text:N,suggestion:$}),t(_e(!1))},[t]),F=N=>{qe(N.text),R("entity copied",{entity:N,type:"copy"}),t(_e(!1))};function j(N){return $=>{o?window.confirm(n("warning"))&&(N($),s(!1)):N($)}}return(0,ye.useEffect)(()=>{r?Me(r,l):t(Es())},[r,l]),(0,ye.useEffect)(()=>{p&&t(Eo())},[p]),Lc(y,()=>{t(_e(!0)),R("open search",{via:"ctrl+k"})}),!u||!d?null:(0,ue.jsxs)(te,{placeholder:n("searchPlaceholder"),typePlaceholder:n("typePlaceholder"),onChangeSearch:i,onChangeOpen:j(N=>t(_e(N))),onChangeType:N=>c(N),onChangePage:j(N=>t(Ln(N))),selectedType:l,search:r,page:a,isOpen:w,types:I,updateDeps:[x],children:[(0,ue.jsxs)(te.Page,{id:"search",children:[r.length===0&&(0,ue.jsx)($c,{types:L,commands:z,onClick:ot}),r.length>0&&(0,ue.jsxs)(ye.Fragment,{children:[z.length>0&&(0,ue.jsx)(te.List,{heading:n("commands"),children:z.map((N,$)=>(0,ue.jsx)(te.ListItem,{closeOnSelect:!1,onClick:N.onClick,id:`commands-${$}`,children:N.label},N.label))}),I.map(({value:N,label:$,list:st,lineClamp:bn,listOrientation:ge})=>(0,ue.jsx)(te.List,{heading:$,orientation:ge==="horizontal"?"horizontal":"vertical",onShowAll:()=>c(N),hasMore:!l&&T[N.toLowerCase()]>ea(st,N,l).length,children:ea(st,N,l).map(X=>(0,ue.jsx)(te.ListItem,{id:`${N}-${X.id}`,closeOnSelect:!1,lineClamp:bn,onClick:()=>ot(X.text,X),description:N!=="IMAGE"?X.title&&X.text:void 0,tooltip:X.text,extra:g&&(0,ue.jsx)(te.ListItemActions,{children:(0,ue.jsx)(fr,{context:r,source:"search",suggestion:X})}),children:N==="IMAGE"?(0,ue.jsx)(te.Image,{title:X.title||X.text,src:X.image}):X.title||X.text},`${X.id}-${X.text}`))},N))]})]}),(0,ue.jsx)(te.Page,{id:"entities",title:n("entitiesTitle"),onDismiss:j(()=>{t(Ln("search"))}),children:(0,ue.jsx)(Dc,{onCopy:F})})]})},Gc=Gf;var Ho=require("react/jsx-runtime"),Xf=()=>{let t=E("showSearch"),e=E("isEmbedded");return(0,Ho.jsxs)(Xc.Fragment,{children:[t&&(0,Ho.jsx)(Gc,{}),e&&(0,Ho.jsx)(ac,{})]})},Jc=Xf;var eu=D(require("classnames")),tu=require("react-redux");var Sr=require("react/jsx-runtime"),Qc=({className:t})=>(0,Sr.jsx)("svg",{version:"1.1",xmlns:"http://www.w3.org/2000/svg",xmlnsXlink:"http://www.w3.org/1999/xlink",x:"0px",y:"0px",viewBox:"0 0 512 512",xmlSpace:"preserve",className:t,children:(0,Sr.jsx)("g",{children:(0,Sr.jsx)("path",{d:`M163.4,233h186v-70c0-25.6-9.4-47.8-27.3-65.7C304.2,79.4,282,70,256.4,70s-47.8,9.4-65.7,27.3
6
6
  c-17.9,17.9-27.3,40.1-27.3,65.7C163.4,163,163.4,233,163.4,233z M465.5,267.9V477c0,9.4-3.4,17.9-10.2,24.7
7
7
  c-6.8,6.8-15.4,10.2-24.7,10.2h-349c-9.4,0-17.9-3.4-24.7-10.2c-6.8-6.8-10.2-15.4-10.2-24.7V267.9c0-9.4,3.4-17.9,10.2-24.7
8
8
  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
9
- 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 na=require("react/jsx-runtime"),zf={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},jc=({className:t,color:e})=>(0,na.jsx)("svg",{className:t,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:(0,na.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:zf[e||"pink"]})});var $c={root:"dd-LbeUM",text:"dd-Dpfn1",isLoggedIn:"dd-XvHAn",isLoggedOut:"dd-21y-z",icon:"dd-8rLqS",logo:"dd-slXhD",lock:"dd-ByzlR"};var oa={};Z(oa,{enUS:()=>Vf,nlNL:()=>jf});var Vf={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},jf={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};var Xc=require("react-redux"),gn=require("react/jsx-runtime"),Jc=({onLogIn:t})=>{let e=P(oa),n=E("floatingMenu"),o=E("productName"),s=(0,Xc.useDispatch)(),r=(0,Gc.useSelector)(se),i=C("FloatingMenu",$c);if(r===null||n===!1)return null;let a=()=>{r===!0?s(_e(!0)):t()};return(0,gn.jsxs)("button",{type:"button",className:(0,qc.default)(i.root,{[i.isLoggedIn]:r,[i.isLoggedOut]:!r}),onClick:a,children:[(0,gn.jsx)("div",{className:i.text,children:e(r?"search":"signin",{productName:o})}),(0,gn.jsxs)("div",{className:i.icon,children:[(0,gn.jsx)(jc,{className:i.logo,color:"pink"}),r===!1&&(0,gn.jsx)(Vc,{className:i.lock})]})]})};var Er=require("react"),Qe=require("react-redux");function Je(t){let{showMidSentenceSuggestions:e,showSuggestionsBeforePattern:n,showSuggestionsAfterPattern:o}=t.settings,{text:s,selection:r}=t.input;return r.end<t.input.suggestionTextStart||r.start!==r.end?!1:r.end>=s.length?!0:e?n&&new RegExp(n).test(s.substring(r.end))||o&&new RegExp(o).test(s.substring(0,r.end))?!0:n===!1&&o===!1:!1}var Qc=require("@reduxjs/toolkit"),$f={showTabHint:!1,inputHasFocus:!1,overlayCollapsed:!1,openOverlayWhenTyping:!1,overlayCollapsedUserOverwrite:!1},yr=({ui:t})=>t.overlayCollapsed,Zc=(0,Qc.createSlice)({name:"ui",initialState:$f,reducers:{setShowTabHint(t,e){t.showTabHint=e.payload},setInputFocus(t,e){t.overlayCollapsedUserOverwrite!==!0&&(e.payload===!0&&(t.overlayCollapsed=!1),t.inputHasFocus=e.payload)},setOverlayCollapsed(t,e){e.payload.collapse===!1&&(t.openOverlayWhenTyping=!1),!(e.payload.skipWhenInputFocus&&t.inputHasFocus)&&(t.overlayCollapsed=e.payload.collapse)},setOpenOverlayWhenTyping(t,e){t.openOverlayWhenTyping=e.payload},setOverlayCollapsedUserOverwrite(t,e){t.overlayCollapsedUserOverwrite=e.payload,t.overlayCollapsed=e.payload}}}),{setShowTabHint:Fo,setInputFocus:vr,setOverlayCollapsed:Dt,setOpenOverlayWhenTyping:Yc,setOverlayCollapsedUserOverwrite:eu}=Zc.actions,tu=Zc.reducer;var nu={styleRow:"dd-prYfH",styleSuggestion:"dd-JTmXy"};var Ho=require("react/jsx-runtime"),qf=({match:t,selected:e,styles:n})=>(0,Ho.jsx)(M,{as:"button",selected:e,className:n.styleRow,"data-testid":"style-suggestion-item",title:t.suggestion,children:(0,Ho.jsx)("span",{className:n.styleSuggestion,children:t.suggestion})}),Gf=({matches:t,selectedIndex:e})=>{let n=C("StyleSuggestionList",nu);return(0,Ho.jsx)(oe,{children:t.map((o,s)=>(0,Ho.jsx)(qf,{match:o,selected:e===s,styles:n},`${o.keyword}-${s}`))})},Sr=Gf;var lu=require("react");var ra=require("interweave"),_t=require("react"),Uo=require("react-redux");var ou=require("react");function su(t,e,n){(0,ou.useEffect)(()=>{let o=t.current;return o?(o.addEventListener(e,n),()=>{o.removeEventListener(e,n)}):()=>{}},[t,e,n])}var ru={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 Bo=require("react/jsx-runtime"),iu=({title:t})=>(0,Bo.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"18px",height:"18px",viewBox:"0 0 24 24","aria-labelledby":"closeTitle",children:[(0,Bo.jsx)("title",{id:"closeTitle",children:t}),(0,Bo.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 sa={};Z(sa,{enUS:()=>Xf,nlNL:()=>Jf});var Xf={assistant:[{type:0,value:"Assistant"}],close:[{type:0,value:"Close"}]},Jf={assistant:[{type:0,value:"Assistent"}],close:[{type:0,value:"Sluiten"}]};var Ce=require("react/jsx-runtime"),Zf=["search","personal-collection-search","search-autocomplete"];function Yf(t,e,n,o={}){var r;let s="";return Zf.includes(e)?s=mc($i(t,n,{stripAgentPart:!0}),(r=o.searchKeywords)!=null?r:[n]):s=$i(t,n,o),o.placeholders===!0&&(s=fc(s)),s}var eh=()=>{},th=({selected:t,suggestion:e})=>{let n=P(sa),o=E("inlineSuggestions"),s=(0,Uo.useSelector)(Xt),[r,i]=(0,_t.useState)(!1),a=E("enableSuggestionFeedback"),d=(0,Uo.useSelector)(y=>y.input.text),l=(0,Uo.useDispatch)(),c=C("TextSuggestion",ru),p=(0,_t.useRef)(null),u=e.source==="assistant",g=a&&!u;(0,_t.useEffect)(()=>{let y=setTimeout(()=>{l(kl({text:e.text,suggestion:e}))},500);return()=>{clearTimeout(y)}},[e]),su(p,"click",()=>{l(Se({suggestion:e,text:e.text,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"}))});let m=()=>{l(Qt({source:e.source,text:e.text,assistantCode:e.assistantCode}))},f=(0,_t.useMemo)(()=>Yf(e.text,e.source,s,{stripAgentPart:o,placeholders:!0,searchKeywords:e.searchKeywords}),[o,e.text,e.source,s,e.searchKeywords]);return e.source==="gpt"&&!o?null:(0,Ce.jsxs)("div",{className:c.root,onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),children:[(0,Ce.jsx)(M,{ref:p,as:"button","data-testid":"suggestions-overlay-item",selected:t,onClick:eh,children:e.source==="assistant"?(0,Ce.jsxs)("div",{className:c.assistantContainer,children:[(0,Ce.jsx)(ra.Interweave,{containerTagName:"div",tagName:"span",className:c.formattedTextTruncated,content:f}),(0,Ce.jsx)("span",{className:c.assistantBadge,children:n("assistant")})]}):(0,Ce.jsx)(ra.Interweave,{containerTagName:"div",tagName:"span",className:c.formattedText,content:f})}),g&&r&&(0,Ce.jsx)("div",{className:c.actions,children:(0,Ce.jsx)(pr,{source:"overlay",context:d,suggestion:e})}),u&&r&&(0,Ce.jsx)("div",{className:c.closeIconContainer,children:(0,Ce.jsx)("button",{type:"button",className:c.closeIcon,onClick:m,title:n("close"),children:(0,Ce.jsx)(iu,{title:n("close")})})})]})},au=th;var du=require("react/jsx-runtime"),nh=({suggestions:t,selectedIndex:e,reverse:n})=>(0,lu.useMemo)(()=>{let s=t.map((r,i)=>(0,du.jsx)(au,{index:i,selected:i===e,suggestion:r},`${r.text}-${r.source}`));return n?s.reverse():s},[t,e,n]),xr=nh;var cu={root:"dd-PfvRI",paper:"dd-HYlyY"};var Cr=require("@reduxjs/toolkit");var br={list:{keywordMatches:[]},fetchState:"idle"},Tr=t=>t.styleSuggestions.list,mn=(0,Cr.createAsyncThunk)("styleSuggestions/getAll",(n,o)=>S(null,[n,o],function*({text:t},e){var d;let{deepdeskAPI:s}=e.extra,r=e.getState(),{showStyleSuggestions:i}=r.settings,a=(d=r.conversation.current)==null?void 0:d.profileCode;if(!i)return br.list;if(!a)throw new Error("No current conversation to fetch pinned messages");return s.getStyleSuggestions({profileCode:a,message:t})})),uu=(0,Cr.createSlice)({name:"styleSuggestions",initialState:br,reducers:{commitStyleSuggestion(t,e){let{keyword:n,suggestion:o}=e.payload;t.list.keywordMatches=t.list.keywordMatches.filter(s=>s.keyword.toLowerCase()!==n.toLowerCase()||s.suggestion!==o)}},extraReducers:t=>{t.addCase(mn.pending,e=>{e.fetchState="loading"}).addCase(mn.rejected,e=>{e.fetchState="error"}).addCase(mn.fulfilled,(e,n)=>{e.fetchState="done",kt(e.list,n.payload)||(e.list=n.payload)}).addCase(Zt,e=>{e.list=br.list}).addCase(Y,()=>br)}}),{commitStyleSuggestion:pu}=uu.actions,gu=uu.reducer;var wr=t=>{let e=new Set;return t.filter(({keyword:n,suggestion:o})=>{let s=JSON.stringify([n.toLowerCase(),o]);return e.has(s)?!1:(e.add(s),!0)})};var fn=require("react/jsx-runtime"),oh=()=>{var y;let t=(0,Er.useRef)(null),e=C("InlineSuggestionsOverlay",cu),n=(0,Qe.useSelector)(Je),o=(0,Qe.useDispatch)(),s=(0,Qe.useSelector)(se),r=(0,Qe.useSelector)(Rn),i=(0,Qe.useSelector)(yr),a=E("showTextSuggestions"),d=(0,Qe.useSelector)(Jt),l=(0,Qe.useSelector)(ro),c=E("showStyleSuggestions"),p=E("showStyleSuggestionList"),u=(0,Qe.useSelector)(Tr),g=c&&p?wr((y=u.keywordMatches)!=null?y:[]):[],m=g.length>0,f=a&&d.length>0;return Lt(()=>{setTimeout(()=>{o(Dt({collapse:!0,skipWhenInputFocus:!0}))})}),(0,Er.useEffect)(()=>{let v=t.current;if(!v||!v.parentElement)return;v.parentElement.style.left="0px";let x=v.getBoundingClientRect();v.parentElement.style.left=`${Math.min(window.innerWidth-4-x.right,0)}px`}),i||s!==!0||r===!1||!n&&!m||!f&&!m?null:(0,fn.jsx)("div",{className:e.root,"data-variant":"inline",children:(0,fn.jsxs)("div",{ref:t,className:e.paper,children:[m&&(0,fn.jsx)(Sr,{matches:g,selectedIndex:-1}),f&&(0,fn.jsx)(oe,{children:(0,fn.jsx)(xr,{suggestions:d,selectedIndex:l})})]})})},mu=oh;var Ft=D(require("react"));var fu={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 hu=require("react-redux");var ia={};Z(ia,{enUS:()=>sh,nlNL:()=>rh});var sh={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."}]},rh={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 ee=require("react/jsx-runtime"),yu=({onClose:t,onSave:e,id:n,error:o})=>{let[s,r]=(0,Ft.useState)(""),[i,a]=(0,Ft.useState)(!1),[d,l]=(0,Ft.useState)(!1),c=C("Nickname",fu),p=Ft.default.useRef(null),u=(0,hu.useSelector)(v=>v.info.showNicknameDialog),g=P(ia),m=E("adminUrl");(0,Ft.useEffect)(()=>{o&&a(!0)},[o]);let f=()=>{if(!p.current)return;s.trim()?p.current.setCustomValidity(""):p.current.setCustomValidity(g("nicknameDialogError")),p.current.reportValidity()},y=v=>{v.preventDefault();let x=s.trim(),T=v.currentTarget.querySelector("#nickname-input");if(!x){T.setCustomValidity(g("nicknameDialogError")),T.reportValidity();return}T.setCustomValidity(""),e(x)};return(0,ee.jsxs)(Hn,{isOpen:u,"datatest-id":n,onClose:t||(()=>{}),onBack:t||(()=>{}),children:[(0,ee.jsx)("div",{className:c.titleWrapper,children:(0,ee.jsx)("h1",{className:c.title,children:g("title")})}),(0,ee.jsxs)("form",{className:c.dialogContent,onSubmit:y,children:[(0,ee.jsx)("p",{children:g("nicknameDialogTitle")}),i&&o&&(0,ee.jsx)("div",{className:c.errorMessage,children:m?(()=>{let v=g("nicknameDialogSaveError",{account:m}),x=`${m}.deepdesk.com/admin/user-settings`,T=v.indexOf(x);if(T!==-1){let w=v.substring(0,T),L=v.substring(T+x.length);return(0,ee.jsxs)(ee.Fragment,{children:[w,(0,ee.jsx)("a",{href:x,target:"_blank",rel:"noopener noreferrer",className:c.errorLink,children:x}),L]})}return v})():g("nicknameDialogSaveErrorWithoutLink")}),(0,ee.jsx)("input",{required:!0,minLength:1,maxLength:20,"data-testid":"nickname-input",id:"nickname-input",className:c.nicknameInput,type:"text",placeholder:g("nicknameDialogInputPlaceholder"),value:s,onChange:v=>{l(new RegExp("\\p{Extended_Pictographic}","u").test(v.target.value)),r(v.target.value)},onBlur:f,ref:p}),d&&(0,ee.jsx)("div",{className:c.errorMessage,role:"alert",children:g("nicknameDialogEmojiError")}),(0,ee.jsxs)("div",{className:c.buttonsWrapper,children:[o?(0,ee.jsx)("div",{className:c.closeButtonWrapper,children:(0,ee.jsx)("button",{type:"button",className:c.closeButton,onClick:()=>t==null?void 0:t(),children:g("close")})}):null,(0,ee.jsx)("div",{className:c.buttonContinueWrapper,children:(0,ee.jsx)("button",{type:"submit",className:c.continueButton,disabled:!s.trim()||new RegExp("\\p{Extended_Pictographic}","u").test(s),children:g("nicknameDialogContinueButton")})})]})]})]})};var vu=require("react-redux");var Ko=require("react/jsx-runtime"),ih=({children:t})=>{let n=E("locale").replace("-","");return(0,Ko.jsx)(Ri.Provider,{value:n,children:t})},ah=({store:t,customStyles:e={},children:n})=>(0,Ko.jsx)(vu.Provider,{store:t,children:(0,Ko.jsx)(ih,{children:(0,Ko.jsx)(no.Provider,{value:e,children:n})})}),mt=ah;var Rr=D(require("classnames")),jn=require("react"),Ie=require("react-redux");var Su=require("react");function xu(t,e){let[n,o]=(0,Su.useState)(()=>{if(typeof window=="undefined")return e;try{let r=window.localStorage.getItem(t);return r?JSON.parse(r):e}catch(r){return k.error(r),e}});return[n,r=>{try{let i=r instanceof Function?r(n):r;o(i),typeof window!="undefined"&&window.localStorage.setItem(t,JSON.stringify(i))}catch(i){k.error(i)}}]}var bu=()=>/Mac/i.test(navigator.platform);var Tu=D(require("classnames")),ft=require("react");var aa={};Z(aa,{enUS:()=>lh,nlNL:()=>dh});var lh={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"}]}]},dh={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 Cu={root:"dd-uTPjX",anchor:"dd-C8lsZ",anchorButton:"dd-IoSx9"};var Ht=require("react/jsx-runtime"),la=(t,e,n)=>o=>(0,Ht.jsx)("button",{className:t.anchorButton,type:"button",value:e,onClick:n,children:o},e),ch=({className:t,loginUrl:e,isEmbedded:n,onSnooze:o,onLogIn:s})=>{let r=P(aa),i=fe(),a=C("Login",Cu),d=E("productName"),l=E("signInViaPopup"),c=n&&!l,p=(0,ft.useCallback)(x=>{x.preventDefault(),o&&o(Number.parseInt(x.target.value,10))},[]),u=(0,ft.useCallback)(x=>{x.preventDefault(),i.send(Nn,!0)},[e]),g=(0,ft.useMemo)(()=>x=>(0,Ht.jsx)("a",{onClick:w=>{w.preventDefault(),s()},href:e,className:a.anchor,target:"_blank",rel:"noreferrer",children:x},"login"),[e]),m=(0,ft.useCallback)(x=>(0,Ht.jsx)("button",{type:"button",className:a.anchorButton,onClick:u,children:x},"prompt"),[u]),{min:f,hour:y,day:v}=(0,ft.useMemo)(()=>({min:la(a,600,p),hour:la(a,3600,p),day:la(a,3600*12,p)}),[]);return(0,Ht.jsxs)("div",{className:(0,Tu.default)(t,a.root),children:[r("loginPlease",{login:c?m:g,productName:d}),o&&(0,Ht.jsxs)(ft.Fragment,{children:[(0,Ht.jsx)("br",{}),r("snooze",{min:f,hour:y,day:v})]})]})},kr=ch;var Eu=require("react-redux");var wu={root:"dd-DoQhb",text:"dd-Jwnev"};var Wo=require("react/jsx-runtime"),uh=({title:t})=>{let e=C("SearchTrigger",wu),n=(0,Eu.useDispatch)(),o=q();return(0,Wo.jsxs)("button",{type:"button",className:e.root,onClick:()=>{n(_e(!0)),o("open search",{via:"autocomplete-overlay"})},children:[(0,Wo.jsx)(Wn,{}),(0,Wo.jsx)("span",{className:e.text,children:t})]})},ku=uh;var da={};Z(da,{enUS:()=>ph,nlNL:()=>gh});var ph={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"}]},gh={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 Ru={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 K=require("react/jsx-runtime"),mh=({onLogIn:t})=>{var $;let e=C("SuggestionsOverlay",Ru),n=P(da),o=(0,Ie.useSelector)(Je),s=(0,Ie.useSelector)(El),r=(0,Ie.useDispatch)(),i=(0,jn.useRef)(null),a=E("searchTriggerKey"),d=E("productName"),l=(0,Ie.useSelector)(yr),c=(0,Ie.useSelector)(se),p=(0,Ie.useSelector)(gl),u=(0,Ie.useSelector)(Rn),[g,m]=(0,jn.useState)(null),f=E("showSearch"),y=E("showTextSuggestions"),v=E("adminUrl"),x=E("isEmbedded"),T=E("suggestionsPlacement"),[w,L]=xu("dd-snooze-until-ms",0),R=l||w>Date.now(),I=(0,Ie.useSelector)(Jt),z=(0,Ie.useSelector)(ro),Me=E("showStyleSuggestions"),nt=E("showStyleSuggestionList"),F=(0,Ie.useSelector)(Tr),V=Me&&nt?wr(($=F.keywordMatches)!=null?$:[]):[],We=V.length>0,ne=I.filter(ot=>ot.source!=="gpt").length,Wt=()=>{R&&L(0),r(eu(!R))},N=ot=>{let Cn=Date.now()+ot*1e3;L(Cn),k.info(`Snooze until: ${new Date(Cn)}`),r(Dt({collapse:!0}))};return(0,jn.useEffect)(()=>{ne===0&&m(null)},[I,ne]),Lt(()=>{r(Dt({collapse:!0,skipWhenInputFocus:!0}))}),c===null||u===!1?null:c===!1?(0,K.jsxs)("div",{ref:i,className:(0,Rr.default)(e.root,{[e.isCollapsed]:R}),children:[!R&&(0,K.jsxs)("div",{className:e.triggers,children:[(0,K.jsx)("div",{style:{flex:1}}),(0,K.jsx)("div",{className:e.triggersRight,children:(0,K.jsx)(jt,{className:e.toggleButton,title:n("collapse"),onClick:Wt,isCollapsed:!1})})]}),(0,K.jsx)("div",{className:e.toggleButtonWrapper,children:(0,K.jsx)(jt,{className:e.toggleButton,title:n("open",{productName:d}),onClick:Wt,isCollapsed:!0})}),(0,K.jsxs)("div",{className:e.collapsible,children:[p&&(0,K.jsxs)("div",{className:e.loginError,children:[(0,K.jsx)("span",{className:e.loginErrorMessage,children:p}),(0,K.jsx)("button",{type:"button",className:e.loginErrorDismiss,onClick:()=>r(gs()),"aria-label":n("dismissError"),children:n("dismiss")})]}),(0,K.jsx)(kr,{loginUrl:v,isEmbedded:x,onLogIn:t,onSnooze:N})]})]}):!s||!o&&!We?null:(0,K.jsxs)("div",{ref:i,className:(0,Rr.default)(e.root,{[e.isCollapsed]:R}),children:[!R&&(0,K.jsxs)("div",{className:e.triggers,children:[(0,K.jsx)("div",{style:{flex:1},children:f&&(0,K.jsx)("div",{style:{display:"inline-block"},onFocus:()=>{},onMouseOver:()=>m(n(bu()?"searchHintMac":"searchHintWindows",{searchTriggerKey:a.toUpperCase()})),onMouseLeave:()=>m(null),children:(0,K.jsx)(ku,{title:n("search")})})}),(0,K.jsxs)("div",{className:e.triggersRight,onFocus:()=>{},children:[(0,K.jsx)("div",{className:(0,Rr.default)(!g&&e.hintsHidden,e.hints),children:g}),(0,K.jsx)(jt,{className:e.toggleButton,title:n("collapse"),onClick:Wt,isCollapsed:!1})]})]}),(0,K.jsx)("div",{className:e.toggleButtonWrapper,children:(0,K.jsx)(jt,{className:e.toggleButton,title:n("open",{productName:d}),onClick:Wt,isCollapsed:!0})}),(We||ne>0&&y)&&(0,K.jsxs)("div",{className:e.collapsible,onFocus:()=>{},children:[We&&(0,K.jsx)(Sr,{matches:V,selectedIndex:-1}),ne>0&&y&&(0,K.jsx)(oe,{children:(0,K.jsx)(xr,{suggestions:I,selectedIndex:z,reverse:T==="above"})})]})]})},Pu=mh;var Kr=D(require("classnames")),$u=require("interweave"),vt=require("react"),qu=require("react-redux");var $n=require("react");function Pr(t){return t.contentEditable==="true"}function fh(t){let e=0,n=0,o=window.getSelection();if(o.rangeCount!==0){let s=o.getRangeAt(0),r=s.cloneRange();r.selectNodeContents(t),r.setEnd(s.endContainer,s.endOffset),n=r.toString().length,r.selectNodeContents(t),r.setEnd(s.startContainer,s.startOffset),e=r.toString().length}return{selectionStart:e,selectionEnd:n}}function Iu(t){let{selectionStart:e,selectionEnd:n}=Pr(t)?fh(t):t;return[e,n]}function Au(t){let[,e]=(0,$n.useState)(),n=(0,$n.useRef)(null);return n.current=Iu(t),(0,$n.useEffect)(()=>{let o=()=>{var a;let[s,r]=(a=n.current)!=null?a:[],i=Iu(t);(!i||s!==i[0]||r!==i[1])&&(n.current=i,e({}))};return t.addEventListener("keyup",o),t.addEventListener("click",o),t.addEventListener("focus",o),document.addEventListener("selectionchange",o),()=>{t.removeEventListener("keyup",o),t.removeEventListener("click",o),t.removeEventListener("focus",o),document.removeEventListener("selectionchange",o)}},[t]),n.current}function Lu(t,e){if(!e)return;let n=t,{value:o}=n,[s,r]=e,i=o.match(cs);if(!i||i.length===0)return;let a=0;i.find(d=>{let l=o.indexOf(d,a);return s>l&&r<l+d.length?(n.selectionStart=l,n.selectionEnd=l+d.length,!0):(a=l+d.length,!1)})}var Mu=require("react"),hh=["div","span","mark","strong","b","i","u","em"];function ca(t,e,n=0){var r;let o=t[t.length-1],s=typeof o=="object"&&o!==null?(r=o.props)==null?void 0:r.tagName:void 0;if(s==="br")return t.pop(),[...t,...e,o];if(hh.includes(s)){let i=Array.isArray(o.props.children)?o.props.children:[o.props.children];return[...t.slice(0,t.length-1),(0,Mu.cloneElement)(o,{children:ca(i,e,n+1)})]}return[...t,...e]}function hn(t){return t.tagName.toLowerCase()==="textarea"}var Nu={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 Fu=D(require("classnames")),Hu=require("interweave"),Dr=require("react");var qn=require("react");function Ou(t,e){let n;return[(...o)=>{window.cancelAnimationFrame(n);let s=e?e(...o):o;n=window.requestAnimationFrame(()=>{t(...s)})},()=>window.cancelAnimationFrame(n)]}function Ir(t){let e=(0,qn.useRef)(null),[n,o]=(0,qn.useState)(!1);return(0,qn.useEffect)(()=>{var c;let s=!1,r=Number.parseFloat((c=window.getComputedStyle(document.body).zoom)!=null?c:"1"),[i,a]=Ou((p,u)=>{let g=e.current;if(!g)return;let m=p/r,f=u/r,y=g.getBoundingClientRect(),v=m>y.x&&m<y.x+y.width&&f>y.y&&f<y.y+y.height;v&&!s?(s=!0,o(!0)):!v&&s&&(s=!1,o(!1))},({clientX:p,clientY:u})=>[p,u]),[d,l]=Ou(()=>{s=!1,o(!1)});return t.addEventListener("mousemove",i),t.addEventListener("mouseleave",d),()=>{a(),l(),t.removeEventListener("mousemove",i),t.removeEventListener("mouseleave",d)}},[e]),[e,n]}function Ar(t){return t.replace(/[.*+^${}()|[\]\\]/g,"\\$&")}function Lr(t){return e=>{t.forEach(n=>{typeof n=="function"?n(e):n!=null&&(n.current=e)})}}function Du(t){return t!=null}var _u=D(require("classnames")),Mr=require("react");var ht={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 ua=require("react/jsx-runtime"),Nr=(0,Mr.forwardRef)((s,o)=>{var r=s,{className:t,children:e}=r,n=O(r,["className","children"]);let i=(0,Mr.useRef)(null),a=C("TabCompletion",ht);return(0,ua.jsx)("div",b(h({ref:Lr([i,o]),className:(0,_u.default)(t,a.popoverContentContainer)},n),{children:(0,ua.jsx)("div",{className:a.popoverContent,children:e})}))});var Bt=require("react/jsx-runtime"),yh=t=>e=>{let n=Bi(e);return"top"in n&&(n.width=t.width-(e.left-t.left)-10),n},vh=({inputElement:t,boundaryRef:e,inputStyle:n,children:o,suggestion:s})=>{let r=C("TabCompletion",ht),i=$s(),a=(0,Dr.useMemo)(()=>yh(t.getBoundingClientRect()),[t]),[d,l]=Ir(t);return(0,Dr.useEffect)(()=>{l?i.open():i.close()},[l]),(0,Bt.jsxs)("span",{children:[(0,Bt.jsx)("mark",{ref:Lr([d,i.triggerRef]),className:(0,Fu.default)(r.matchKeyword,{[r.hover]:l}),"aria-haspopup":"dialog","aria-expanded":i.opened?"true":"false",children:o}),i.opened&&(0,Bt.jsx)(_n,{className:r.popover,triggerRef:i.triggerRef,boundaryRef:e,position:"below",align:"start",toStyle:a,children:(0,Bt.jsx)(Nr,{style:n,children:(0,Bt.jsx)("div",{className:r.hintText,children:s})})})]})},Or=class extends Hu.Matcher{constructor(){super(...arguments);this.keywordMatches=[];this.preparedKeywordMatches=[];this.usedKeywordMatches=new Set}onBeforeParse(n,o){return o.keywordMatches&&o.keywordMatches!==this.keywordMatches&&(this.preparedKeywordMatches=o.keywordMatches.map(s=>b(h({},s),{keywordRegex:new RegExp(`\\b${Ar(s.keyword)}\\b`,"i")})),this.keywordMatches=o.keywordMatches),this.usedKeywordMatches.clear(),n}match(n){let o=this.preparedKeywordMatches.map(r=>{if(this.usedKeywordMatches.has(r))return null;let i=n.match(r.keywordRegex);if(!i)return null;let a=n.charAt(i.index-1),d=n.charAt(i.index+r.keyword.length);return a==="{"&&d==="}"?null:{index:i.index,length:i[0].length,match:i[0],matchString:i[0],suggestion:r.suggestion,preparedKeywordMatch:r,valid:!0}}).filter(Du);if(o.length===0)return null;let s=o.reduce((r,i)=>i.index<r.index?i:r);return this.usedKeywordMatches.add(s.preparedKeywordMatch),s}replaceWith(n,o){return(0,Bt.jsx)(vh,{inputElement:o.inputElement,suggestion:o.suggestion,inputStyle:o.inputStyle,boundaryRef:o.boundaryRef,children:n},`keyword_${o.matchString}_${o.key}`)}asTag(){return"mark"}};var Bu=require("interweave"),Uu=D(require("classnames"));var pa=require("react/jsx-runtime"),Sh=({inputElement:t,children:e})=>{let n=C("TabCompletion",ht),[o,s]=Ir(t);return(0,pa.jsx)("mark",{ref:o,className:(0,Uu.default)(n.matchPlaceholder,{[n.hover]:s}),children:e})},_r=class extends Bu.Matcher{match(e){let n=e.match(/(((\$!\{)|(\{))[a-zA-Z0-9_.]+\}(?!\}))/);return n?{index:n.index,length:n[0].length,match:n[0],matchString:n[0],valid:!0}:null}replaceWith(e,n){return(0,pa.jsx)(Sh,{inputElement:n.inputElement,children:e},`placeholder_${n.matchString}_${n.key}`)}asTag(){return"mark"}};var Hr=D(require("classnames")),ju=require("interweave"),pe=require("react"),Ur=require("react-redux");var ga=require("react/jsx-runtime"),Ku=()=>(0,ga.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,ga.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 Ze=require("react"),zo=require("react-redux"),zu=D(require("lodash.debounce"));var Wu={root:"dd-ky-Bv",content:"dd-kV5e1"};function Fr(t,e,n){var s;let o=((s=t.imageSizes)==null?void 0:s[e])||t.image||n;if(!o)return null;try{return new URL(o).toString()}catch(r){return null}}function ma(t){return t.replace("https://www.","").replace("https://","")}var Ae=require("react/jsx-runtime"),xh=3,bh=t=>({image:t.image||"",text:t.text,id:t.id,title:t.title}),Ch=({onSelectLink:t,onDismiss:e,placeholder:n,visitUrlText:o,linkCount:s=xh})=>{let r=C("LinkSearch",Wu),[i,a]=(0,Ze.useState)(""),d=(0,zo.useDispatch)(),l=(0,zo.useSelector)(Oc("url")),c=(0,zo.useSelector)(Xl("URL")),p=(0,Ze.useMemo)(()=>c.map(bh),[c]),[u,g]=(0,Ze.useState)(p.length-1),m=E("fallbackImage"),f=T=>{let w=T.target;a(w.value)},y=(T,w)=>{T.stopPropagation(),T.preventDefault(),window.open(w,"_blank")},v=T=>{var R;let w=u-1<0?p.length-1:u-1,L=u+1===p.length?0:u+1;T.code==="Escape"&&(a(""),e()),T.code==="ArrowUp"&&g(w),T.code==="ArrowDown"&&g(L),T.code==="Enter"&&t(((R=p[u])==null?void 0:R.text)||i)},x=(0,Ze.useCallback)((0,zu.default)(T=>{d(en({query:T,type:"URL",tags:["link-search"]}))},300),[]);return(0,Ze.useEffect)(()=>{i&&x(i)},[i]),(0,Ze.useEffect)(()=>()=>{d(Ts())},[]),(0,Ae.jsxs)("div",{className:r.root,children:[(0,Ae.jsx)(oe,{withDivider:!0,children:(i?p:l).slice(0,s).map((T,w)=>(0,Ae.jsx)(M,{selected:u===w,onClick:()=>t(T.text),"data-testid":"linksearch-suggestion",children:(0,Ae.jsxs)(H,{children:[(0,Ae.jsx)(H.Image,{src:Fr(T,"small",m||void 0),title:T.title||T.text}),(0,Ae.jsxs)(H.Content,{className:r.content,cropText:!0,children:[(0,Ae.jsx)(H.Title,{children:T.title||ma(T.text)}),T.title&&ma(T.text)]}),(0,Ae.jsx)(M.Actions,{children:(0,Ae.jsx)(M.ActionButton,{label:o,onClick:L=>y(L,T.text)})})]})},T.text))}),(0,Ae.jsx)(To,{value:i,onChange:f,autoFocus:!0,placeholder:n,onKeyUp:v})]})},Vu=Ch;var fa={};Z(fa,{enUS:()=>Th,nlNL:()=>wh});var Th={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"}]},wh={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 re=require("react/jsx-runtime"),Eh=(0,pe.forwardRef)((t,e)=>{let n=C("TabCompletion",ht);return(0,re.jsx)("mark",{ref:e,className:(0,Hr.default)(n.matchSelection)},"selection-start")}),kh=({startRef:t,boundaryRef:e,inputStyle:n,inputElement:o,children:s})=>{let r=P(fa),i=C("TabCompletion",ht),a=E("addToPersonalCollection"),d=(0,Ur.useSelector)(At("/admin/personal-collection/new")),l=(0,pe.useRef)(null),c=(0,pe.useRef)(null),[p,u]=(0,pe.useState)(null),g=(0,Ur.useDispatch)(),m=$s(document.activeElement===o),[f]=(0,pe.useState)(()=>document.createRange());m.triggerRef.current=f,(0,pe.useEffect)(()=>()=>f.detach(),[]),(0,pe.useEffect)(()=>{let v=t.current,x=l.current;!v||!x||(f.setStart(v,0),f.setEnd(x,0))},[t.current,l.current]),Lt(()=>{m.close()});let y=(0,pe.useCallback)(v=>{let x=f.toString(),T=/^http(s?):\/\//.test(v)?v:`https://${v}`,w=`[${x}](${T})`;g(Se({text:w,suggestion:{text:w,source:"search-url",type:"url"},eventMetrics:{inputType:"mouse"},replace:"selection"}))},[]);return(0,re.jsxs)("span",{children:[(0,re.jsx)("mark",{ref:l,className:(0,Hr.default)(i.matchSelection),"aria-haspopup":"dialog","aria-expanded":m.opened?"true":"false",children:s}),m.opened&&(0,re.jsx)(_n,{className:i.popoverRoot,triggerRef:m.triggerRef,boundaryRef:e,position:"above",align:"start",children:(0,re.jsxs)(Nr,{style:n,ref:c,children:[(0,re.jsxs)("div",{className:(0,Hr.default)(i.selectionOptions,{[i.selectionOptionsIsHidden]:p!==null}),children:[(0,re.jsxs)("button",{type:"button",tabIndex:p===null?-1:void 0,className:i.selectionOptionsButton,onClick:()=>u("insertLink"),children:[(0,re.jsx)(Ku,{}),(0,re.jsx)("span",{children:"\xA0"}),(0,re.jsx)("span",{children:r("insertLink")})]}),a&&d&&(0,re.jsx)("button",{type:"button",tabIndex:p===null?-1:void 0,className:i.selectionOptionsButton,onClick:()=>{let v=f.toString(),x=`${d}?text=${encodeURIComponent(v)}`;window.open(x,"_blank")},children:(0,re.jsx)("span",{children:r("addToPersonalCollection")})})]}),p==="insertLink"&&(0,re.jsx)(Vu,{placeholder:r("linkInputPlaceholder"),visitUrlText:r("visitUrl"),onSelectLink:y,onDismiss:()=>{u(null),m.close()}})]})})]},"selection-end")},Br=class extends ju.Matcher{constructor(){super(...arguments);this.charCount=0;this.foundIndex=0;this.startRef=null}onBeforeParse(n,o){return this.props=o,this.charCount=0,this.startRef=(0,pe.createRef)(),this.foundIndex=0,n}match(n){if(!this.props||this.props.selection===null||this.foundIndex===2)return null;let[o,s]=this.props.selection;if(o===s)return null;let r=this.foundIndex===0?o:s,i=r>=this.charCount&&r<=this.charCount+n.length?{index:r-this.charCount,length:0,match:"",valid:!0}:null;i&&this.foundIndex++;let a=this.foundIndex===1;return i&&a?this.charCount+=r-this.charCount:this.charCount+=n.length,i?h({isStart:a},i):null}replaceWith(n,o){return o.isStart?(0,re.jsx)(Eh,{ref:this.startRef}):(0,re.jsx)(kh,{inputElement:o.inputElement,startRef:this.startRef,boundaryRef:o.boundaryRef,inputStyle:o.inputStyle})}asTag(){return"mark"}};var Gu=require("react-redux");var yt=require("react/jsx-runtime"),Rh=({enabled:t,content:e,tabText:n,showTabHint:o,showTabCompletion:s,showStyleSuggestions:r,keywordMatches:i,inputElement:a,source:d})=>{let l=C("TabCompletion",Nu),c=E("insertLink"),p=E("addToPersonalCollection"),u=E("showMidSentenceSuggestions"),g=E("inlineSuggestions"),m=Au(a),f=(0,vt.useRef)(null),y=(0,Gu.useSelector)(se);(0,vt.useEffect)(()=>{hn(a)&&m&&Lu(a,m)},[m]);let v=(0,vt.useCallback)(w=>{if(!s||!n)return w;let L=[(0,yt.jsx)("span",{className:l.resetIndent,children:"\u200B"},"u200B"),(0,yt.jsx)("span",{"data-testid":"tab-completion",className:(0,Kr.default)(l.tabText,l.resetIndent),"data-source":d,children:n},"tabText")];return o&&L.push((0,yt.jsx)("span",{className:(0,Kr.default)(l.hint,l.resetIndent),children:(0,yt.jsx)(as,{keyCode:"tab"},"tabHint")},"tabHint")),ca(w,L)},[s,n,o]),x=(0,vt.useMemo)(()=>{let w=[];return(c||p)&&w.push(new Br("selection")),w.push(new _r("placeholders")),r&&w.push(new Or("keywords")),w},[g,c,p,r]),T=(0,vt.useMemo)(()=>{let w=window.getComputedStyle(a);return{"--dd-color":w.color,"--dd-font-size":w.fontSize,"--dd-font-family":w.fontFamily,"--dd-font-variant":w.fontVariant}},[]);return!t||!y?null:(0,yt.jsxs)("div",{ref:w=>{w!=null&&w.parentElement&&(f.current=w==null?void 0:w.parentElement)},className:l.root,style:T,children:[(0,yt.jsx)($u.Interweave,{tagName:"span",containerTagName:"div",className:(0,Kr.default)(l.container,l.agentText),disableLineBreaks:hn(a),content:e||"\u200B",onAfterParse:v,matchers:x,selection:m,keywordMatches:i,inputElement:a,inputStyle:T,boundaryRef:f,inlineSuggestionsOnlyAtEnd:!u}),(0,yt.jsx)("br",{})]},"tab-completion")},Ph=t=>{var v,x,T;let{input:e,ui:n,settings:o,styleSuggestions:s,conversation:r}=t,i=Pn({input:e}),a=(i==null?void 0:i.text)||"",d=(i==null?void 0:i.source)||"",l=(v=e.html)!=null?v:Un(e.text),c=e.text.slice(e.suggestionTextStart,e.selection.end),p=a.indexOf(c)===0?a.slice(c.length):"",{showTabHint:u}=n,{isSupported:g}=r,{showTabCompletion:m,visible:f,showStyleSuggestions:y}=o;return{showTabHint:u,showStyleSuggestions:y,showTabCompletion:m&&Je(t),content:l,tabText:p,source:d,keywordMatches:(T=(x=s.list)==null?void 0:x.keywordMatches)!=null?T:[],enabled:f&&g!==!1}},Xu=(0,qu.connect)(Ph)(Rh);var Ut=require("react"),Q=require("react-redux");var Vo=require("@reduxjs/toolkit");var Ih={token:null,interval:null},ha=(0,Vo.createAsyncThunk)("passwordlessToken/getTemporaryPasswordlessToken",(t,e)=>S(null,null,function*(){let{deepdeskAPI:n}=e.extra;return{token:yield n.requestPasswordlessToken()}})),ya=(0,Vo.createAsyncThunk)("passwordlessToken/pollPasswordlessToken",(t={},e)=>{let{interval:n=1e3*60*10}=t,{dispatch:o}=e;return o(ha()),setInterval(()=>o(ha()),n)}),Ju=(0,Vo.createSlice)({name:"passwordlessToken",initialState:Ih,reducers:{stopPollPasswordlessToken(t){t.interval&&clearInterval(t.interval),t.interval=null}},extraReducers:t=>{t.addCase(ha.fulfilled,(e,n)=>{e.token=n.payload.token}),t.addCase(ya.fulfilled,(e,n)=>{e.interval=n.payload})}}),{stopPollPasswordlessToken:Qu}=Ju.actions,Zu=Ju.reducer;var Yu=require("@reduxjs/toolkit");function Ah(t){return"buttonText"in t&&"eventName"in t}function ep(t){if(t)return Ah(t)?{label:t.buttonText,event:t.eventName,value:t.payload}:t}function Lh(t){return t==null?void 0:t.map(e=>ep(e))}function Mh(t){let e=0;for(let n=0;n<t.length;n++)e=(e<<5)-e+t.charCodeAt(n),e|=0;return e}var tp=(0,Yu.createSelector)([gd,ms],(t,e)=>(e?t.filter(s=>!s.externalConversationId||s.externalConversationId===e):t).map(s=>{var a;let r=ep(s.callToAction),i=Lh(s.callToActions);return b(h(h(h(h({text:s.response,title:s.name},r?{callToAction:r}:{}),i!=null&&i.length?{callToActions:i}:{}),s.message!==void 0?{message:s.message}:{}),(a=s.sources)!=null&&a.length?{sources:s.sources}:{}),{editable:s.editable,isLoading:s.isLoading,evaluationId:s.evaluationId,rule:{id:Mh(s.code),label:s.code,name:s.name,description:s.name}})}));var Wr=require("react"),Sa=D(require("classnames"));var va=require("react/jsx-runtime"),Gn=()=>(0,va.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",children:(0,va.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 np={root:"dd-WcEru",entity:"dd-LfP8y",entityText:"dd-L-v0f",iconWrapper:"dd-9Deh1",icon:"dd-tM7E2",iconClicked:"dd-EEdDL"};var Ye=require("react/jsx-runtime"),Nh=({entities:t})=>{let e=C("EntitiesWidgetList",np),[n,o]=(0,Wr.useState)(void 0),s=q(),r=()=>{o(void 0)},i=a=>{t&&(o(t.indexOf(a)),$e(a.text),s("entity copied",{entity:a,type:"copy"}))};return(0,Wr.useEffect)(()=>{let a=setTimeout(r,500);return()=>{clearTimeout(a)}},[n]),!t||t.length===0?null:(0,Ye.jsx)("div",{className:e.root,"data-testid":"widget-entities-list",children:t.map((a,d)=>(0,Ye.jsxs)("button",{title:a.text,className:e.entity,type:"button",onClick:()=>i(a),children:[(0,Ye.jsx)("span",{className:e.entityText,children:a.text}),(0,Ye.jsxs)("span",{className:e.iconWrapper,children:[(0,Ye.jsx)("span",{className:(0,Sa.default)(e.icon),children:(0,Ye.jsx)(Gn,{})}),(0,Ye.jsx)("span",{className:(0,Sa.default)(e.icon,n===d&&e.iconClicked),children:(0,Ye.jsx)(Gn,{})})]})]},a.text))})},op=Nh;var xa=require("react/jsx-runtime"),sp=()=>(0,xa.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,xa.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 up=require("react"),zr=require("react-redux");var rp={root:"dd-ohnXe",trigger:"dd-7i-S3",button:"dd-t53Cg",nav:"dd-qZFnm",item:"dd-FZC0F"};var ip={root:"dd-nazq3",rotation:"dd-3EHTv"};var lp=require("react/jsx-runtime"),Oh=({size:t=12})=>{let e=C("LoadingSpinner",ip);return(0,lp.jsx)("span",{"data-testid":"loading-spinner",style:{width:`${t}px`,height:`${t}px`},className:e.root})},ap=Oh;var ba=require("react/jsx-runtime"),dp=()=>(0,ba.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 0 512 512",fill:"currentColor",children:(0,ba.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 jo=require("react/jsx-runtime"),cp=t=>(0,jo.jsxs)("svg",b(h({xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 448 512","aria-labelledby":"checkTitle"},t),{children:[(0,jo.jsx)("title",{id:"checkTitle",children:"Check"}),(0,jo.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 Ca={};Z(Ca,{enUS:()=>Dh,nlNL:()=>_h});var Dh={error:[{type:0,value:"Something went wrong"}]},_h={error:[{type:0,value:"Er ging iets fout"}]};var Te=require("react/jsx-runtime"),Fh=3e3,Hh=({assistantOptions:t})=>{let e=C("OnDemandAssistants",rp),n=P(Ca),o=(0,up.useRef)(),s=(0,zr.useDispatch)(),r=Rs(he),i=(0,zr.useSelector)(rc),a=q(),d=i.filter(u=>u.isPinned),l=i.filter(u=>!u.isPinned),c=()=>S(null,null,function*(){return t.attachments&&t.attachments.length>0?t.attachments:s(((u,g,m)=>S(null,null,function*(){let f;if(t.transcript==="in-memory-transcript"){let y=m.dynamicThunkObject.conversationQuery;if(y){let v=yield y();f=Array.isArray(v)?v:void 0}}else Array.isArray(t.transcript)&&(f=t.transcript);return Pi({transcript:f})})))}),p=u=>S(null,null,function*(){clearTimeout(o.current);let g=yield c();a("trigger on demand assistant",{assistantCode:u}),yield r.call(h(b(h({},t),{assistantCode:u}),g.length>0?{attachments:g}:{})),o.current=setTimeout(()=>r.reset(),Fh)});return i.length===0?null:(0,Te.jsxs)("div",{className:e.root,children:[d.map(({assistant:u,assistantName:g,displayName:m})=>(0,Te.jsx)("button",{type:"button",className:e.button,disabled:r.state==="loading",onClick:()=>p(u),children:m||g},u)),l.length>0&&(0,Te.jsxs)(j,{placement:"top-end",children:[(0,Te.jsx)(j.Trigger,{className:e.trigger,disabled:r.state==="loading",children:(0,Te.jsx)(cr,{"data-testid":"trigger"})}),(0,Te.jsx)(j.Content,{className:e.nav,"data-testid":"popover",children:l.map(({assistant:u,assistantName:g,displayName:m})=>(0,Te.jsx)(j.Button,{className:e.item,disabled:r.state==="loading",onClick:()=>p(u),children:m||g},u))})]}),r.state==="loading"&&(0,Te.jsx)(ap,{}),r.state==="done"&&(0,Te.jsx)(cp,{"data-testid":"trigger-done"}),r.state==="error"&&(0,Te.jsx)(Id,{trigger:(0,Te.jsx)(dp,{}),children:n("error")})]})},pp=Hh;var mp=require("react-redux");var yn=require("react");var $o={};Z($o,{enUS:()=>Bh,nlNL:()=>Uh});var Bh={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"}]},Uh={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 Ta={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 ie=require("react/jsx-runtime"),Kh=500,Wh=100,zh=({content:t,onChange:e,onCopy:n})=>{let o=(0,yn.useRef)(null),s=C("WidgetCue",Ta);return(0,yn.useEffect)(()=>{let r=o.current;if(!r)return;r.style.setProperty("height","0px");let i=Math.min(Math.max(r.scrollHeight,Wh),Kh);r.style.setProperty("height",`${i}px`)},[t]),(0,ie.jsx)("textarea",{ref:o,className:s.editableCue,onCopy:n,onChange:e,value:t})},Vh=({cue:t,onCallToAction:e,onRemove:n,onCopy:o,onUse:s,onSourceClick:r})=>{var y;let i=C("WidgetCue",Ta),a=P($o),d=q(),l=E("hasKeyboardInput"),[c,p]=(0,yn.useState)(t.text),u=v=>{let x=v?b(h({},t),{callToAction:v}):t;e&&e(c,x),n(t)},g=(v,x)=>{o&&o(v,t),x&&It(x,i.fadeup)},m=v=>{s&&s(v,t)},f=v=>{v.preventDefault(),v.stopPropagation(),n(t)};return(0,yn.useEffect)(()=>{d("Assistant response displayed",{evaluationId:t.evaluationId,assistantCode:t.rule.label,assistantOutput:t.text})},[]),(0,ie.jsxs)(M,{"data-testid":"cue",children:[(0,ie.jsx)(H,{children:(0,ie.jsxs)(H.Content,{children:[t.title&&(0,ie.jsx)(H.Title,{className:i.title,"data-testid":"widget-cue-title",children:t.rule.label.startsWith("__")?a(t.rule.label):t.title}),t.message&&(0,ie.jsx)("p",{className:i.ctaMessage,children:t.message}),t.editable?(0,ie.jsx)(zh,{content:c,onCopy:()=>{let v=document.getSelection();v&&g(v.toString())},onChange:v=>{var x;return p((x=v.target.value)!=null?x:"")}}):(0,ie.jsx)(rn,{content:t.text,sources:t.sources,onSourceClick:v=>r==null?void 0:r(v,t),useLabel:a("useCue"),copyLabel:a("copyCue"),onCopy:g,onUse:l?m:void 0})]})}),(0,ie.jsxs)(M.ButtonsContainer,{children:[(0,ie.jsxs)("div",{className:i.actions,children:[(0,ie.jsx)(M.Button,{onClick:v=>{var x;return g((x=_s(c,"reply")[0])!=null?x:c,v.target)},variant:"primary",children:a("copyCue")}),t.callToAction&&(0,ie.jsx)(M.Button,{onClick:()=>u(),variant:"primary",children:t.callToAction.label}),(y=t.callToActions)==null?void 0:y.map((v,x)=>(0,ie.jsx)(M.Button,{onClick:()=>u(v),variant:"primary",children:v.label},`${v.event}-${v.label}-${x}`)),(0,ie.jsx)(M.Button,{onClick:f,variant:"secondary",children:a("removeCue")})]}),(0,ie.jsx)(Ws,{evaluationId:t.evaluationId,assistantCode:t.rule.label,assistantOutput:t.text,feedbackType:"assistant"})]})]})},gp=Vh;var Xn=require("react/jsx-runtime"),jh=({cues:t})=>{let e=(0,mp.useDispatch)(),n=fe(),o=P($o),s=q(),r=c=>{e(Hs({code:c.rule.label})),s("Assistant response closed",{evaluationId:c.evaluationId,assistantCode:c.rule.label,assistantOutput:c.text})},i=(c,p)=>{$e(c),s("Assistant response copied",{evaluationId:p.evaluationId,assistantCode:p.rule.label,assistantOutput:p.text,copiedText:c})},a=(c,p)=>{var u;p.callToAction&&(e(Fs(p)),s("Assistant call to action",{evaluationId:p.evaluationId,assistantCode:p.rule.label,assistantOutput:p.text,eventName:p.callToAction.event,value:(u=p.callToAction.value)!=null?u:c}))},d=(c,p)=>{var u;n.send(rt,{text:c,suggestion:{source:"assistant",assistantCode:(u=p.rule)==null?void 0:u.label,sourceText:c}}),s("Assistant response used",{evaluationId:p.evaluationId,assistantCode:p.rule.label,assistantOutput:p.text,usedText:c})},l=(c,p)=>{s("Assistant source clicked",{evaluationId:p.evaluationId,assistantCode:p.rule.label,source:c})};return(0,Xn.jsx)(Xn.Fragment,{children:t.map(c=>c.isLoading?(0,Xn.jsx)(Gs,{title:c.rule.label.startsWith("__")?o(c.rule.label):c.title},c.rule.id):(0,Xn.jsx)(gp,{cue:c,onCallToAction:a,onRemove:r,onCopy:i,onUse:d,onSourceClick:l},c.evaluationId))})},fp=jh;var Vr=require("react");var hp={root:"dd-cvTAY",label:"dd-QWQxD",value:"dd-WSUHF",copyButton:"dd-67o9H",copyButtonText:"dd-oos-l",isTrue:"dd--1g2O",isFalse:"dd-sz2ir"};var ve=require("react/jsx-runtime");function $h(t,e){return e.split(".").reduce((n,o)=>!n||typeof n!="object"||!(o in n)?null:n[o],t)}var yp=({data:t,schema:e})=>{let n=C("WidgetCustomData",hp),o=s=>{$e(s)};return(0,Vr.useEffect)(()=>{k.info("Custom data",t,e)},[t]),(0,ve.jsx)("dl",{className:n.root,children:e.map(s=>{let r=$h(t,s.path);return(0,ve.jsxs)(Vr.Fragment,{children:[(0,ve.jsx)("dt",{className:n.label,children:s.label}),(0,ve.jsx)("dd",{className:n.value,children:s.type==="boolean"&&r?(0,ve.jsx)("span",{className:n.isTrue,children:s.trueValue}):s.type==="boolean"&&!r?(0,ve.jsx)("span",{className:n.isFalse,children:s.falseValue}):s.type==="array"&&Array.isArray(r)&&r.length>0?(0,ve.jsxs)("button",{type:"button",onClick:()=>o(r.join(", ")),className:n.copyButton,children:[(0,ve.jsx)("span",{className:n.copyButtonText,children:r.join(", ")}),(0,ve.jsx)(Gn,{})]}):typeof r=="string"||typeof r=="number"?(0,ve.jsxs)("button",{type:"button",onClick:()=>o(`${r}`),className:n.copyButton,children:[(0,ve.jsx)("span",{className:n.copyButtonText,children:r}),(0,ve.jsx)(Gn,{})]}):"-"})]},s.label)})})};var Sp=require("react");var qh=/(https?:\/\/[^\s]+)/,vp=t=>t.split(" ").find(e=>qh.test(e));var Le=require("react/jsx-runtime"),Gh=({suggestion:t,lines:e,onUse:n})=>{var p;let o=t.text||t.url||t.message,s=vp(o),r=P(No),i=E("showImages"),a=E("fallbackImage"),d=E("hasKeyboardInput"),l=u=>{u.preventDefault(),u.stopPropagation(),d&&n(o)},c=(0,Sp.useCallback)(u=>{window.open(s,"_blank"),u.stopPropagation(),u.preventDefault()},[s]);return(0,Le.jsxs)(M,{onClick:d?l:void 0,"data-testid":"edit-suggestion",children:[(0,Le.jsxs)(H,{children:[i&&t.image&&(0,Le.jsx)(H.Image,{src:Fr(t,"small",a||void 0),title:t.title}),(0,Le.jsxs)(H.Content,{children:[t.title&&(0,Le.jsx)(H.Title,{"data-testid":"widget-suggestion-title",children:t.title}),t.searchKeywords&&((p=t.searchKeywords)==null?void 0:p.length)>0&&(0,Le.jsx)(M.Labels,{labels:t.searchKeywords}),(0,Le.jsx)(H.Content,{cropText:e==="single",lineClamp:e==="multiple",children:o})]})]}),(0,Le.jsxs)(M.Actions,{children:[s&&(0,Le.jsx)(M.ActionButton,{onClick:c,label:r("visitUrl")}),d&&(0,Le.jsx)(M.ActionButton,{primary:!0,onClick:l,label:r("useSuggestion")})]})]})},xp=Gh;var qo=require("react/jsx-runtime"),Xh=({lines:t,suggestions:e})=>{let n=fe(),o=(s,r)=>{n.send(rt,{text:s,suggestion:b(h({},r),{source:r.source,sourceText:r.text})})};return(0,qo.jsx)(qo.Fragment,{children:e.map(s=>(0,qo.jsx)(xp,{suggestion:s,lines:t,onUse:r=>o(r,s)},s.text||s.url||s.message))})},bp=Xh;var Go={};Z(Go,{enUS:()=>Jh,nlNL:()=>Qh});var Jh={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"}]},Qh={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 Jn={root:"dd-W9VCG",loginText:"dd--dS6t",stateText:"dd-348OC",footer:"dd-tvofr",shortcutList:"dd-MuKK-",shortcut:"dd-5CnK9",footerShortcut:"dd-dH7XJ",link:"dd-DRo0x"};var A=require("react/jsx-runtime"),Cp=(t,e)=>{let n=(0,Q.useSelector)(se);(0,Ut.useEffect)(()=>n?e.every(o=>!!o)?t():()=>{}:()=>{},[...e,n])},Zh=({onLogIn:t})=>{let e=C("Widget",Jn),n=E("isEmbedded"),o=E("adminUrl");return(0,A.jsx)("div",{className:e.loginText,children:(0,A.jsx)("div",{children:(0,A.jsx)(kr,{isEmbedded:n,loginUrl:o,onLogIn:t})})},"login")},wa=({text:t})=>{let e=C("Widget",Jn);return(0,A.jsx)("div",{className:e.stateText,children:(0,A.jsx)("div",{children:(0,A.jsx)("p",{children:t})})},"notification")},Yh=()=>{let t=P(Go),e=(0,Q.useDispatch)(),n=C("Widget",Jn),o=E("showSearch"),s=E("isEmbedded"),r=(0,Q.useSelector)(At("/admin/")),i=fe(),a=E("productName"),d=q();return Cp(()=>{if(s)return e(ya()),()=>{e(Qu())}},[e,s]),!o&&!r?null:(0,A.jsxs)("div",{className:n.shortcutList,children:[o&&(0,A.jsx)(M.Button,{"data-testid":"shortcut-search","aria-label":t("linkSearch"),className:n.shortcut,icon:(0,A.jsx)(Wn,{}),onClick:()=>{i.send("ShowCommandPalette",{isOpen:!0}),d("open search",{via:"widget-shortcut"})},children:t("linkSearch")}),r&&(0,A.jsx)(M.Button,{as:"a",target:"_blank",icon:(0,A.jsx)(sp,{}),href:r,"data-testid":"shortcut-studio-login","aria-label":t("linkStudioLogin",{productName:a}),className:n.shortcut,rel:"noreferrer",onClick:()=>{d("open my deepdesk",{via:"widget-shortcut"})},children:t("linkStudioLogin",{productName:a})})]})},ey=({title:t,content:e})=>{let n=P(Go),[o,s]=(0,Ut.useState)(!0);return o?(0,A.jsx)(ze,{"data-testid":"custom-data-banner",type:"custom-data-banner",title:t,children:(0,A.jsx)(oe,{withDivider:!0,children:(0,A.jsxs)(M,{children:[(0,A.jsx)(H,{children:(0,A.jsx)(H.Content,{children:(0,A.jsx)(rn,{content:e})})}),(0,A.jsx)(M.ButtonsContainer,{children:(0,A.jsx)(M.Button,{onClick:()=>s(!1),children:n("close")})})]})})}):null},ty=()=>{let t=(0,Q.useDispatch)(),e=(0,Q.useSelector)(ko),n=(0,Q.useSelector)(ac),o=(0,Q.useSelector)(tp),s=(0,Q.useSelector)(Hl),r=(0,Q.useSelector)(lr),i=(0,Q.useSelector)(gr),a=(0,Q.useSelector)(Mt),d=(0,Q.useSelector)(je);return(0,Ut.useEffect)(()=>{s&&!n&&k.warn("Custom data provided, but no schema.")},[s,n]),Cp(()=>{e.forEach(({type:l})=>{l==="entities"?t(Be()):us.includes(l)||t(Ue(l))})},[t,d,a]),(0,Ut.useEffect)(()=>{o.length>0&&!e.some(l=>l.type==="cues")&&k.warn("Received cues, but cues are not configured in widget.")},[e,o]),(0,A.jsx)(Ut.Fragment,{children:e.map(({type:l,title:c,amount:p,lines:u,schema:g,property:m})=>{var f,y;switch(l){case"entities":return r&&r.length>0&&(0,A.jsx)(ze,{type:l,title:c,"data-testid":`type-${l}`,children:(0,A.jsx)(op,{entities:r})},l);case"cues":return o&&o.length>0&&(0,A.jsx)(ze,{type:l,title:c,"data-testid":`type-${l}`,children:(0,A.jsx)(oe,{withDivider:!0,children:(0,A.jsx)(fp,{cues:o})})},l);case"custom-data-banner":return s&&m&&s[m]&&(0,A.jsx)(ey,{title:c,content:String(s[m])},l);case"custom-data":return s&&g&&(0,A.jsx)(ze,{type:l,title:c,"data-testid":`type-${l}`,children:(0,A.jsx)(oe,{withDivider:!0,children:(0,A.jsx)(yp,{data:s,schema:g})})},l);default:return((y=(f=i[l])==null?void 0:f.suggestions)==null?void 0:y.length)>0&&(0,A.jsx)(ze,{type:l,title:c,"data-testid":`type-${l}`,children:(0,A.jsx)(oe,{withDivider:!0,children:(0,A.jsx)(bp,{lines:u,contentType:l,suggestions:i[l].suggestions.slice(0,p)||[]})})},l)}})})},Ea=({children:t})=>{let e=C("Widget",Jn);return(0,A.jsx)("div",{className:e.footer,children:t})},ka=({children:t})=>{let e=C("Widget",Jn);return(0,A.jsx)("div",{className:e.root,"data-testid":"widget",children:t})},ny=({onLogIn:t,knowledgeAssistOptions:e={},assistantOptions:n={transcript:"in-memory-transcript"}})=>{let o=P(Go),s=(0,Q.useSelector)(Rn),r=(0,Q.useSelector)(se),i=(0,Q.useSelector)(ms),a=(0,Q.useSelector)(Mt),d=(0,Q.useSelector)(ic("knowledge-assist")),l=(0,Q.useSelector)(lc);return s===!1?(0,A.jsx)(wa,{text:o("notSupported")}):r===!1?(0,A.jsx)(Zh,{onLogIn:t}):r===null?(0,A.jsx)(wa,{text:o("waiting")}):!i||!a?(0,A.jsx)(wa,{text:o("waitingForConversation")}):(0,A.jsx)(ka,{children:(0,A.jsxs)(Zs,{initialQuestion:e.initialQuestion,assistantCode:l!=null?l:void 0,evaluateKnowledgeAssistFn:bo,children:[(0,A.jsxs)(wn,{children:[(0,A.jsx)(Yh,{}),(0,A.jsx)(ty,{}),d&&(0,A.jsx)(er,{title:d.title,emptyState:e.emptyState})]}),(0,A.jsxs)(Ea,{children:[d&&(0,A.jsx)(Ys,{}),(0,A.jsx)(pp,{assistantOptions:n})]})]})})},Tp=ny;function Qn(t){let e=new Range;return e.selectNodeContents(t),e}function wp(t,e,n){try{return Kt(t,e,n),!0}catch(o){return!1}}function jr(t){return"tagName"in t&&(t.tagName==="DIV"||t.tagName==="P")}function $r(t){return"tagName"in t&&t.tagName==="BR"}var Xo=/[\u200B-\u200D\uFEFF]/g;function Kt(t,e,n){let o=new Range;if(t.firstChild===null&&e===0&&n===0)return o.selectNodeContents(t),o;let s=0,r=!1;function i(d,l){let c=-1,p=/[\u200B-\u200D\uFEFF]/;if(!p.test(d))return l;for(let u=0;u<=d.length;u++)if(p.test(d[u])||c++,c===l)return u;throw new Error("Offset out of range")}function a(d){switch(d.nodeType){case Node.TEXT_NODE:{let l=d.textContent,c=l.replace(Xo,""),p=s+c.length,u=e>=s&&e<=p,g=n>=s&&n<=p;if(u){let m=i(l,e-s);m===0&&!g?o.setStartBefore(d):o.setStart(d,m)}g&&(o.setEnd(d,i(l,n-s)),r=!0),s=p;break}case Node.ELEMENT_NODE:{if($r(d)&&(s===e&&o.setStartBefore(d),s++,s===n)){o.setEndAfter(d),r=!0;return}for(let c=0;c<d.childNodes.length&&(a(d.childNodes[c]),!r);c++);let l=d.lastChild;jr(d)&&l&&!jr(l)&&!$r(l)&&s++;break}default:break}}if(a(t),o.startContainer===document)throw new Error("Offsets out of bound");return o}function Jo(t,e){if(!t.contains(e.startContainer)||!t.contains(e.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:o,endContainer:s,endOffset:r,collapsed:i}=e,a,d,l=0;function c(p){let u=p===t,g=p===n,m=p===s;switch(p.nodeType){case Node.TEXT_NODE:{let f=p.textContent;g&&(a=l+f.substring(0,o).replace(Xo,"").length),m&&(d=l+f.substring(0,r).replace(Xo,"").length),l+=f.replace(Xo,"").length;break}case Node.ELEMENT_NODE:{if($r(p)&&p.nextSibling){l++;break}!u&&jr(p)&&p.previousSibling&&l++;for(let f=0;f<p.childNodes.length;f++){let y=g&&f===o,v=m&&f===r;if(y&&(a=l),v&&(d=l),d!==void 0||((!y||!i)&&c(p.childNodes[f]),m&&f===r-1&&(d=l),d!==void 0))break}m&&(d=l);break}default:break}}if(c(t),d===void 0)throw new Error("Could not determine start and end");return{start:a!=null?a:d,end:d}}function Qo(t,e){if(!t.contains(e.startContainer)||!t.contains(e.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:o,endContainer:s,endOffset:r,collapsed:i}=e,a=0,d="";function l(c){let p=c===t,u=c===n,g=c===s;switch(u&&(a=1),c.nodeType){case Node.TEXT_NODE:{if(a!==1)return;let m=u?o:0,f=g?r:void 0;d+=c.textContent.replace(Xo,"").substring(m,f);break}case Node.ELEMENT_NODE:{if(!i&&a===1&&$r(c)&&c.nextSibling){d+=`
10
- `;break}!p&&!i&&a===1&&jr(c)&&c.previousSibling&&(d+=`
11
- `);let m=u?o:0,f=g?Math.min(r,c.childNodes.length):c.childNodes.length;for(let y=m;y<f&&(l(c.childNodes[y]),a!==2);y++);break}default:break}g&&(a=2)}return l(t),d}var Ep=(i=>(i.CUT="Cut",i.BACKSPACE="Backspace",i.DELETE="Delete",i.ERASEEOF="EraseEof",i.UNDO="Undo",i.CLEAR="Clear",i))(Ep||{}),St=class{constructor(e){this.element=e;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(e,n){let o=s=>{n(s)};this.element.addEventListener(e,o),this.disposeHandlers.push(()=>{this.element.removeEventListener(e,o)})}removeEventListener(e,n){this.element.removeEventListener(e,n)}handleInteraction(){let e=this.getText(),n=this.getHTML(),o=this.getSelection(),s=this.getSuggestionTextStart(),r=this.cachedCaretPosition===null;if(!this.isActive)return;e===""&&this.cachedText!==""&&!this.isPossibleClearInputAction&&this.emit("submit");let i=e!==this.cachedText,a=n!==null&&n!==this.cachedHTML,d=s!==this.cachedSuggestionTextStart;if((i||a||d)&&(i?(this.cachedText=e,this.cachedHTML=n):a&&(this.cachedHTML=n),this.cachedSuggestionTextStart=s,r=!0,this.emit("change",{plainText:e,rawHTML:n,suggestionTextStart:s})),(o.start!==this.cachedSelection.start||o.end!==this.cachedSelection.end)&&(this.cachedSelection=o,r=!0,this.emit("selection",o)),!r)return;let l=this.getCaretPosition();kt(l,this.cachedCaretPosition)||(this.cachedCaretPosition=l,this.emit("caretposition",l))}handleClick(){this.handleInteraction()}handleFocus(){let e=!this.isFocused;this.isFocused=!0,e&&this.emit("focus"),this.handleInteraction()}handleBlur(){this.isPossibleClearInputAction=!1;let e=this.isFocused;this.isFocused=!1,e&&this.emit("blur")}handleKeyDown(e){let{key:n,ctrlKey:o,metaKey:s}=e;this.isPossibleClearInputAction=Object.values(Ep).includes(n)||n.toLowerCase()==="z"&&(o||s),this.emit("keydown",e)}handleKeyUp(e){this.handleInteraction(),this.emit("keyup",e)}handleCut(){this.isPossibleClearInputAction=!0,this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(e){var o,s;let n=((o=e.clipboardData)==null?void 0:o.getData("text"))||((s=e.clipboardData)==null?void 0:s.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 e=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});e.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{e.disconnect()})}getSuggestionTextStart(){return 0}focus(){this.element.focus()}emit(e,...n){this.isDisposed||this.eventListeners[e]&&this.eventListeners[e].forEach(o=>{o(...n)})}on(e,n){this.isDisposed||(this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(n))}off(e,n){if(!this.eventListeners[e])return;let o=this.eventListeners[e].indexOf(n);o!==-1&&this.eventListeners[e].splice(o,1)}activate(){let e=this.isActive===!1;this.isActive=!0,e&&this.handleInteraction()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(e=>e()),this.eventListeners={},this.isDisposed=!0}};function kp(t){return t.top!==0||t.left!==0||t.height!==0||t.width!==0}var vn=class extends St{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),Qo(this.element,n)}getHTML(){return this.element.innerHTML||""}getRange(){let n=this.getRootNode();if(n.activeElement!==this.element)return null;let o="getSelection"in n?n.getSelection():window.getSelection();if(!o)return null;let s=o.rangeCount>0?o.getRangeAt(0):null;if(!s)return null;let r=this.element.ownerDocument.createRange();return r.setStart(s==null?void 0:s.startContainer,s==null?void 0:s.startOffset),r.setEnd(s==null?void 0:s.endContainer,s==null?void 0:s.endOffset),!r||!this.element.contains(r.startContainer)||!this.element.contains(r.endContainer)?null:r}getCaretPosition(){let n=this.getRange();if(!n||!n.collapsed||!("getBoundingClientRect"in n))return null;let o=n.getBoundingClientRect();return!kp(o)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),o=n.getBoundingClientRect(),n.deleteContents(),!kp(o))?null:{top:o.top+o.height,left:o.left}}getSelection(){let n=this.getRange();if(n)return Jo(this.element,n);let o=this.lastKnownSelection;if(o&&wp(this.element,o.start,o.end))return o;let s=Qn(this.element);return s.collapse(!1),Jo(this.element,s)}getSelectedText(){let{start:n,end:o}=this.getSelection();return Qo(this.element,Kt(this.element,n,o))}listen(){super.listen();let n=new MutationObserver(r=>{var i,a;r.length===2&&r[0].addedNodes.length===1&&((i=r[0].addedNodes[0])==null?void 0:i.textContent)==="\u2060"&&((a=r[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 o=this.element.isContentEditable,s=new MutationObserver(()=>{this.element.isContentEditable!==o&&(o=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});s.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>s.disconnect())}};var oy=["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 Rp(t,e){let n="mozInnerScreenX"in window,o=document.createElement("div");o.id="input-textarea-caret-position-mirror-div";let s=o.style,r=window.getComputedStyle(t),i=t.ownerDocument.body;s.whiteSpace="pre-wrap",s.wordWrap="break-word",s.position="absolute",s.visibility="hidden",oy.forEach(c=>{s[c]=r[c]}),n?t.scrollHeight>Number.parseInt(r.height)&&(s.overflowY="scroll"):s.overflow="hidden",o.textContent=t.value.substring(0,e);let a=document.createElement("span");a.textContent=t.value.substring(e)||".",o.appendChild(a),i.appendChild(o);let d=t.getBoundingClientRect(),l={top:d.top-t.scrollTop+a.offsetTop+Number.parseInt(r.borderTopWidth)+a.offsetHeight,left:d.left-t.scrollLeft+a.offsetLeft+Number.parseInt(r.borderLeftWidth)};return i.removeChild(o),l}var Sn=class extends St{constructor(){super(...arguments);this.lastKnownSelection=null}getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:n,selectionEnd:o}=this.element;return{start:n,end:o}}getSelectedText(){let n=this.getSelection();return n?this.getText().slice(n.start,n.end):""}getCaretPosition(){return Rp(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 r;return(r=n==null?void 0:n.get)==null?void 0:r.call(this.element)},set:r=>{var i;(i=n==null?void 0:n.set)==null||i.call(this.element,r),this.handleInteraction()}}),this.addEventListener("scroll",()=>{this.emit("caretposition",this.getCaretPosition())});let o=this.element.disabled,s=new MutationObserver(()=>{this.element.disabled!==o&&(o=this.element.disabled,this.emit(o?"disabled":"enabled"))});s.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>s.disconnect())}};function Pp(t,e,n){let o=`deepdesk-iframe-${t}`,s=document.getElementById(o);if(s)return s;let r=document.createElement("iframe"),i=new URL(e);return Object.entries(n).forEach(([a,d])=>{i.searchParams.append(a,d)}),r.style.position="absolute",r.style.left="-999em",r.style.width="0px",r.style.height="0px",r.tabIndex=-1,r.id=o,r.title=`iframe-${t}`,r.src=i.toString(),window.document.body.appendChild(r),r}function sy(t){if(typeof t!="string")return t;try{return JSON.parse(t)}catch(e){return t}}var Ra=class{constructor(e){this.name=e;this.disposeHandlers=[];this.broadcastChannel=new BroadcastChannel(e)}onMessage(e){this.broadcastChannel.addEventListener("message",e),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",e)})}postMessage(e){this.broadcastChannel.postMessage(JSON.stringify(e))}close(){this.disposeHandlers.forEach(e=>e()),this.broadcastChannel.close()}},Pa=class{constructor(e,n,o){this.name=e;this.targetOrigin=n;this.options=o;this.disposeHandlers=[];this.iframe=Pp(e,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}onMessage(e){window.addEventListener("message",e),this.disposeHandlers.push(()=>{window.removeEventListener("message",e)})}postMessage(e){var n;(n=this.iframe.contentWindow)==null||n.postMessage(JSON.stringify(e),this.targetOrigin)}close(){var e;this.disposeHandlers.forEach(n=>n()),(e=this.iframe)==null||e.remove()}},Ia=class{constructor(e){this.params=e;this.deepdeskUrl=e.deepdeskUrl,this.eventMap=e.eventMap,this.externalId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setExternalId(e){this.externalId!==e&&(this.cleanup(),k.info("Set externalId",e),this.externalId=e,this.channel=this.createChannel(e))}createChannel(e){let n=this.params.createCustomChannel?this.params.createCustomChannel(e):this.isCrossOrigin?new Pa(e,this.deepdeskUrl,{debug:!0}):new Ra(e),o=s=>{var i,a;if(s.origin!==this.deepdeskUrl)return;let r=sy(s.data);typeof r!="object"||r.type!=="event"||r.channel!==e||(k.info("Received broadcast event",this.externalId,s),(a=(i=this.eventMap)[r.name])==null||a.call(i,r.payload))};return n.onMessage(o),n}send(e,n,o){var i,a;k.info("Broadcast event",{externalId:this.externalId,name:e,payload:n});let s={type:"event",name:e,payload:n};o!==!1&&((a=(i=this.eventMap)[e])==null||a.call(i,n));let r=this.externalId==="deepdesk-general"?this.defaultChannel:this.channel;r==null||r.postMessage(b(h({},s),{channel:this.externalId}))}cleanup(e=!1){var n,o;(n=this.channel)==null||n.close(),this.channel=void 0,e&&((o=this.defaultChannel)==null||o.close(),this.defaultChannel=void 0)}},Ip=Ia;function ry(t){return t.replace(/(_\w)/g,e=>e[1].toUpperCase())}function W(t){return Array.isArray(t)?t.map(W):typeof t=="object"&&t!==null?Object.keys(t).reduce((e,n)=>b(h({},e),{[ry(n)]:W(t[n])}),{}):t}function iy(t){return t.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}function ae(t){return Array.isArray(t)?t.map(ae):typeof t=="object"&&t!==null?Object.keys(t).reduce((e,n)=>b(h({},e),{[iy(n)]:ae(t[n])}),{}):t}var Zn=class extends Error{constructor(n,o){super(n);this.body=o;this.name="CustomError"}};var Zo=t=>new Promise(e=>{setTimeout(e,t)});var Ke=class extends Zn{constructor(){super(...arguments);this.name="ClientError"}},qr=class extends Zn{constructor(){super(...arguments);this.name="ServerError"}},Aa=new Map;function Ap(t){return S(this,null,function*(){if(t.status===204)return t.text().catch(()=>{}),null;let e=t.headers.get("content-type");if(e!=null&&e.includes("application/json"))return t.json();let n=yield t.text();return n===""?null:(k.warn("Unexpected response body:",n.slice(0,20)),JSON.parse(n))})}var xn=class{constructor(e="",n={}){this.baseUrl=e;this.options=n;this.latestRequestByUrl={};this.refreshingToken=null;this.lastFailedRefreshAt=null;this.failedRefreshCooldown=1e4;var o;this.fetch=(o=n.fetch)!=null?o:window.fetch.bind(window)}patchFetch(e){this.fetch=e(this.fetch)}setCsrfToken(e){this.csrfToken=e}request(e,n={}){return new Promise((o,s)=>{let r={isAborted:!1,reject:s},i=`${this.baseUrl}${e}`,a=this.fetch,d=n.method===void 0||n.method.toLowerCase()==="get",R=n,{useCache:l=!1,abortLatest:c=!1,attempts:p=1,retryDelay:u=500,refreshTokenOn401:g=!0,retryOnError:m=I=>I instanceof TypeError,retryOnResponse:f=I=>I.status>=500,version:y=null}=R,v=O(R,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]);if(l){if(!d)throw new Error(`Can't use 'useCache' for ${n.method}`);if(Aa.has(i)){o(Aa.get(i));return}}let x=b(h({credentials:"include"},v),{headers:h({Accept:"application/json","Content-Type":"application/json"},v.headers)});!d&&this.csrfToken&&(x.headers=b(h({},x.headers),{"X-CSRFToken":this.csrfToken})),typeof y=="string"&&(x.headers=b(h({},x.headers),{"X-Deepdesk-API-Version":y}));let T=p,w=!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]=r;let L=()=>S(this,null,function*(){return T--,a(i,x).then(I=>S(this,null,function*(){return f(I)&&!r.isAborted&&T>0?(yield Zo(u),L()):I.status===401&&g===!0&&w===!1?(w=!0,yield this.refreshToken(),L()):I})).catch(I=>S(this,null,function*(){if(m(I)&&!r.isAborted&&T>0)return yield Zo(u),L();throw I}))});L().then(I=>S(this,null,function*(){let z=yield Ap(I);if(delete this.latestRequestByUrl[i],I.status>=500){s(new qr("Server Error",z));return}if(I.status===401){s(new Ke("Unauthorized",z));return}if(I.status===403){s(new Ke("Forbidden",z));return}if(I.status===404){s(new Ke("Not Found",z));return}if(I.status>=400){s(new Ke("Bad Request",z));return}l&&Aa.set(i,z),o(z)})).catch(I=>{s(I)})})}validateToken(){return S(this,null,function*(){let e,n,o;try{({has_valid_access_token:e,is_logged_in:n,has_valid_refresh_token:o}=yield this.get("/apis/admin/session/validate/",{refreshTokenOn401:!1}))}catch(s){return!1}if(!e){if(!o)return!1;try{yield this.refreshToken();let{is_logged_in:s}=yield this.get("/apis/admin/session/validate/",{refreshTokenOn401:!1});return s}catch(s){return!1}}return n})}refreshToken(){let e=Date.now();return this.lastFailedRefreshAt&&e-this.lastFailedRefreshAt<this.failedRefreshCooldown?Promise.reject(new Ke("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(e,n){return this.request(e,n)}post(e,n,o){return this.request(e,h({method:"POST",body:JSON.stringify(n)},o))}postWithStatus(e,n,o){return this.requestWithStatus(e,h({method:"POST",body:JSON.stringify(n)},o))}requestWithStatus(e,n={}){return new Promise((o,s)=>{let r={isAborted:!1,reject:s},i=`${this.baseUrl}${e}`,a=this.fetch,L=n,{useCache:d=!1,abortLatest:l=!1,attempts:c=1,retryDelay:p=500,refreshTokenOn401:u=!0,retryOnError:g=R=>R instanceof TypeError,retryOnResponse:m=R=>R.status>=500,version:f=null}=L,y=O(L,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]),v=b(h({credentials:"include"},y),{headers:h({Accept:"application/json","Content-Type":"application/json"},y.headers)});this.csrfToken&&(v.headers=b(h({},v.headers),{"X-CSRFToken":this.csrfToken})),typeof f=="string"&&(v.headers=b(h({},v.headers),{"X-Deepdesk-API-Version":f}));let x=c,T=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[i]&&l&&(this.latestRequestByUrl[i].isAborted=!0,this.latestRequestByUrl[i].reject(new Error("Aborted"))),this.latestRequestByUrl[i]=r;let w=()=>S(this,null,function*(){return x--,a(i,v).then(R=>S(this,null,function*(){return m(R)&&!r.isAborted&&x>0?(yield Zo(p),w()):R.status===401&&u===!0&&T===!1?(T=!0,yield this.refreshToken(),w()):R})).catch(R=>S(this,null,function*(){if(g(R)&&!r.isAborted&&x>0)return yield Zo(p),w();throw R}))});w().then(R=>S(this,null,function*(){let I=yield Ap(R);if(delete this.latestRequestByUrl[i],R.status>=500){s(new qr("Server Error",I));return}if(R.status===401){s(new Ke("Unauthorized",I));return}if(R.status===403){s(new Ke("Forbidden",I));return}if(R.status===404){s(new Ke("Not Found",I));return}if(R.status>=400){s(new Ke("Bad Request",I));return}o({status:R.status,data:I})})).catch(R=>{delete this.latestRequestByUrl[i],s(R)})})}patch(e,n,o){return this.request(e,h({method:"PATCH",body:JSON.stringify(n)},o))}put(e,n,o){return this.request(e,h({method:"PUT",body:JSON.stringify(n)},o))}delete(e,n){return this.request(e,h({method:"DELETE"},n))}};var Lp;(e=>{let t;(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"))(t=e.EvaluationStatus||(e.EvaluationStatus={}))})(Lp||(Lp={}));function Gr(t){return b(h({},W(t)),{metadata:t.metadata})}var bn=class bn{constructor(e,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new xn(e,{fetch:n.fetch}),this.client.patchFetch(o=>(s,r)=>S(this,null,function*(){let i=yield o(s,r);return this.handleDeepdeskVersionHeaders(i),i}))}preflight(){return S(this,null,function*(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let e=yield this.getCsrfToken();this.client.setCsrfToken(e)}return this.options.token?(bn.exchangeTokenPromise||(bn.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),bn.exchangeTokenPromise):Promise.resolve()})}createConversation(e){return S(this,null,function*(){var o;yield this.preflight(),k.info(`Creating conversation for session ${e.externalId} and agent ${e.agentId}`);let n=yield this.client.post("/api/v2/conversations",b(h({chat_start_time:new Date().toISOString()},ae(e)),{metadata:(o=e.metadata)!=null?o:{}}));return Gr(n)})}upsertConversation(e){return S(this,null,function*(){var c;yield this.preflight(),k.info(`Upserting conversation for session ${e.externalId} and agent ${e.agentId}`);let{status:n,data:o}=yield this.client.postWithStatus("/api/v2/conversations",b(h({chat_start_time:new Date().toISOString()},ae(e)),{metadata:(c=e.metadata)!=null?c:{}}),{version:"v2"}),s=Gr(o);if(n===201)return s;let{agentId:r,agentName:i,agentEmail:a,agentNickname:d,metadata:l}=e;return this.updateConversation(s.id,{agentId:r,agentEmail:a,agentName:i,agentNickname:d,metadata:l})})}getMe(){return S(this,null,function*(){let e=yield this.client.get("/apis/admin/session/me/");return W(e)})}postIdentity(e){return S(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/me/identities/",ae(e))})}patchMe(e){return S(this,null,function*(){yield this.preflight();let n=yield this.client.patch("/apis/admin/session/me/",ae(e));return W(n)})}getProfile(e){return S(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${e}/`,{useCache:!0});return W(n)})}getKnowledgeAssistant(e){return S(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${e}/`,{useCache:!0});return W(n)})}getContentTypes(){return S(this,null,function*(){let e=yield this.client.get("/apis/admin/content-types/",{useCache:!0});return W(e)})}getAccount(){return S(this,null,function*(){let e=yield this.client.get("/apis/admin/account/",{useCache:!0});return W(e)})}getPlatformConfig(e){return S(this,null,function*(){let n=e!==void 0?`/platform/config/${e}/`:"/platform/config/",{config:o}=yield this.client.get(n,{useCache:!0});return W(o)})}checkUserExists(e){return S(this,null,function*(){let{exists:n}=yield this.client.get(`/apis/admin/users/exists?external_id=${e}`,{version:"v1"});return n})}getConversationByExternalId(o){return S(this,arguments,function*(e,n={}){yield this.preflight(),k.info(`Getting conversation for session ${e}`);let{attempts:s=1,retryDelay:r=1e3}=n,i=yield this.client.get(`/api/v2/conversations/by_external_id/${e}`,{attempts:s,retryDelay:r,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"});return k.info(`Successfully retrieved conversation ${i.id} for session ${e}`),Gr(i)})}isConversationSupported(o){return S(this,arguments,function*(e,n={}){k.info(`Check if conversation for session ${e} is supported`);let{attempts:s=1,retryDelay:r=1e3}=n;return(yield this.client.get(`/api/v2/conversations/by_external_id/${e}/has_active_profile`,{attempts:s,retryDelay:r,retryOnResponse:a=>a.status===404||a.status>=500})).has_active_profile})}updateConversation(e,n){return S(this,null,function*(){var r;yield this.preflight();let o=ae(n);n.metadata&&(o.metadata=(r=n.metadata)!=null?r:{});let s=yield this.client.put(`/api/v2/conversations/${e}`,o);return Gr(s)})}postMessages(e,n){return S(this,null,function*(){yield this.preflight(),yield this.client.post(`/api/v2/conversations/${e}/messages`,n.map(o=>b(h({},ae(o)),{metadata:o.metadata})))})}sendEvent(e,n){return S(this,null,function*(){yield this.preflight();let a=n,{data:o}=a,s=O(a,["data"]),r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((d,[l,c])=>b(h({},d),{[l]:c}),{}),i=["platform","agentId","agentName","agentEmail","conversationId"].reduce((d,l)=>(s[l]&&(d[l]=s[l]),d),{});return this.client.post("/api/v2/events",ae(b(h(h({},r),i),{data:o,name:e})),{version:"v2"})})}getEntities(e){return S(this,null,function*(){return yield this.preflight(),yield this.client.post("/api/v2/entities",{messages:e.filter(o=>o.text)})})}getTemporaryExchangeToken(){return S(this,null,function*(){return(yield this.client.get("/apis/admin/session/exchange-token/")).jwt})}exchangeTokenForAccessCookie(e){return S(this,null,function*(){return this.client.post("/apis/admin/session/jwt/",{jwt:e}).catch(n=>{throw k.warn(`Invalid token '${e}'`),n})})}authenticateWithKey(e,n){return S(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/api-key/",ae(n),{refreshTokenOn401:!1,headers:{apikey:e}})})}getTextSuggestions(s){return S(this,arguments,function*(e,n={},o){if(yield this.preflight(),o==="sticky-messages")throw new Error("Use getPinnedMessages instead");return(yield this.client.post(`/api/v2/conversations/${e}/recommend/${o}`,ae(n),{abortLatest:!0})).map(i=>b(h({},W(i)),{text:i.text||i.url||i.message,source:o,type:o})).filter((i,a,d)=>a===d.findIndex(l=>l.text===i.text))})}isLoggedIn(){return S(this,null,function*(){return yield this.preflight(),this.client.validateToken()})}getAutocompleteSuggestions(e,n){return S(this,null,function*(){return yield this.preflight(),(yield this.client.post(`/api/v2/conversations/${e}/autocomplete`,ae(n),{abortLatest:!0})).map(s=>({score:1,source:s.source,sourceText:s.source_text,text:s.label,trainingJobs:s.training_jobs,searchKeywords:s.search_keywords,type:s.source})).filter((s,r,i)=>r===i.findIndex(a=>a.text===s.text))})}getPinnedMessages(e){return S(this,null,function*(){let n=yield this.client.get(`/api/v2/profiles/${e}/pinned-messages`,{abortLatest:!0});return W(n).map(o=>b(h({},o),{text:o.message,source:"sticky-messages",type:"pinned-message"}))})}getStyleSuggestions(e){return S(this,null,function*(){let n=yield this.client.post("/api/v2/style-suggestions",ae(e),{abortLatest:!0,version:"v2"});return W(n)})}search(e){return S(this,null,function*(){let n=yield this.client.post(`/api/v2/profiles/${e.profile}/search`,ae(e));return W(n)})}loginWithPassword(e,n){return S(this,null,function*(){yield this.preflight();let o=yield this.client.post("/apis/admin/session/login/",{username:e,password:n},{refreshTokenOn401:!1});return W(o)})}logout(){return S(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/logout/",{},{refreshTokenOn401:!1})})}requestLoginByEmail(e){return S(this,null,function*(){yield this.preflight();let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:e});return W(n)})}requestPasswordlessToken(){return S(this,null,function*(){let e=yield this.client.get("/apis/admin/session/passwordless/request/");return W(e.token)})}getCsrfToken(){return S(this,null,function*(){let{token:e}=yield this.client.get("/apis/admin/session/csrf/");return e})}verifyLoginToken(e){return S(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/login/",{token:e});return W(n)})}evaluateAssistant(e,n){return S(this,null,function*(){var d,l,c;yield this.preflight();let o=new URLSearchParams;n!=null&&n.externalConversationId&&o.append("external_conversation_id",n.externalConversationId);let s=n!=null&&n.threadId?`/api/v2/assistants/${e}/threads/${n==null?void 0:n.threadId}/evaluate?${o.toString()}`:`/api/v2/assistants/${e}/evaluate?${o.toString()}`,r=p=>ae(p),i=(d=n==null?void 0:n.transcript)==null?void 0:d.map(p=>{var u;return h({source:p.source,text:p.text},(u=p.attachments)!=null&&u.length?{attachments:p.attachments.map(r)}:{})}),a=yield this.client.post(s,h({input:(l=n==null?void 0:n.input)!=null?l:{},conversation:i},(c=n==null?void 0:n.attachments)!=null&&c.length?{attachments:n.attachments.map(r)}:{}));return W(a)})}createAssistantThread(e){return S(this,null,function*(){yield this.preflight();let{assistantCode:n}=e,o=yield this.client.post(`/apis/admin/assistants/${n}/threads/`,{});return W(o)})}postMessageToAssistantThread(e){return S(this,null,function*(){yield this.preflight();let{assistantCode:n,threadId:o,message:s}=e,r=yield this.client.post(`/apis/admin/assistants/${n}/threads/${o}/messages/`,{content:s,role:"user"});return W(r)})}translateMessages(e){return S(this,null,function*(){yield this.preflight();let n=yield this.client.post("/api/v2/translate",ae(e));return W(n)})}handleDeepdeskVersionHeaders(e){e.headers.forEach((n,o)=>{let s=o.toLowerCase(),r=s.match(dl);if(!n||!r)return;let i=r[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&n&&a!==n&&k.warn(`Overwritten Version header ${s}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[i]=n})}};bn.exchangeTokenPromise=null;var xt=bn;var Xr=class{constructor(e){this.options=e;this.socket=null;this.maxReconnectAttempts=5;this.reconnectInterval=25e3;this.cleanupCallbacks=[];var n,o;this.socket,this.eventListeners=new Map,this.url=e.url,this.maxReconnectAttempts=(n=e.maxReconnectAttempts)!=null?n:this.maxReconnectAttempts,this.reconnectInterval=(o=e.reconnectInterval)!=null?o:this.reconnectInterval,this.shouldReconnect=e.shouldReconnect}connect(){let e=()=>this.cleanup();window.addEventListener("beforeunload",e),this.cleanupCallbacks.push(()=>window.removeEventListener("beforeunload",e)),this.reconnect()}setupListeners(){this.socket&&(this.socket.onmessage=e=>{var n;try{let o=W(JSON.parse(e.data));o.event&&this.eventListeners.has(o.event)&&((n=this.eventListeners.get(o.event))==null||n.forEach(s=>s(o.data)))}catch(o){console.error("Error parsing WebSocket message:",o)}},this.socket.onclose=e=>{console.log("WebSocket connection closed:",e),setTimeout(()=>{this.reconnect()},this.reconnectInterval)},this.socket.onerror=e=>{console.error("WebSocket error:",e)})}reconnect(){var e,n;if(this.maxReconnectAttempts<=0){console.error("Max reconnect attempts reached, closing WebSocket connection."),(e=this.socket)==null||e.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(e,n){if(!this.socket){console.error("WebSocket connection is not open.");return}this.socket.send(JSON.stringify({event:e,data:n}))}on(e,n){this.eventListeners.has(e)||this.eventListeners.set(e,[]);let o=this.eventListeners.get(e);o&&!o.includes(n)&&o.push(n)}close(){var e;(e=this.socket)==null||e.close()}cleanup(){this.close(),this.cleanupCallbacks.forEach(e=>e()),this.cleanupCallbacks=[]}};var Qr=require("@reduxjs/toolkit");var Np=require("@reduxjs/toolkit");var Mp={startTime:null,stopTime:null},Op=t=>t.handlingTime,Dp=(0,Np.createSlice)({name:"handlingTime",initialState:Mp,reducers:{handlingTimeStart(t){if(t.startTime&&!t.stopTime)throw new Error("Timing already started");t.startTime=new Date,t.stopTime=null},handlingTimeStop(t){if(!t.startTime)throw new Error("Timing not started");t.stopTime=new Date},handlingTimeReset(t){t.startTime=null,t.stopTime=null}},extraReducers:t=>{t.addCase(Y,()=>Mp)}}),{handlingTimeStart:_p,handlingTimeStop:Jr,handlingTimeReset:Fp}=Dp.actions,Hp=Dp.reducer;var Bp=(t={})=>{let e=h({onAuthError:kn(!1)},t);return n=>o=>s=>("error"in s&&s.error.message==="Unauthorized"&&n.dispatch(e.onAuthError),o(s))};var Up=(t={})=>{let e,n=!0,o=h({getStyleSuggestions:mn,debounce:500},t);return s=>r=>i=>{var g;let a=s.getState().input.text,d=r(i),l=s.getState();if(l.auth.isLoggedIn!==!0)return d;let{showStyleSuggestions:c}=l.settings;if(!((g=l.conversation.current)==null?void 0:g.id)||!c)return d;let{text:u}=l.input;return u===a&&!n||(clearTimeout(e),u==="")||(e=setTimeout(()=>{n=!1,s.dispatch(o.getStyleSuggestions({text:u}))},t.debounce)),d}};function ay(t,e){return t.text===e.text&&t.selection.start===e.selection.start&&t.selection.end===e.selection.end&&t.suggestionTextStart===e.suggestionTextStart}var Kp=(t={})=>{let e=h({getTextSuggestions:Ue,getAutocompleteSuggestions:Do,debounce:200,check:Je},t),n;return o=>s=>r=>{var f;let{input:i}=o.getState(),a=s(r),d=o.getState();if(d.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:l,showTabCompletion:c}=d.settings,p=(f=d.conversation.current)==null?void 0:f.id,u=r.type===mr.toString();if(!p||!l&&!c)return a;let{input:g}=d;return ay(g,i)&&!u||(clearTimeout(n),!e.check(d))||(n=setTimeout(()=>{let y=Xt(d);y===""?o.dispatch(e.getTextSuggestions("default")):o.dispatch(e.getAutocompleteSuggestions(y))},u?0:e.debounce)),a}};var Wp=mn.fulfilled.toString();function ly(t,e){let n=new Set([...e.keywordMatches.map(s=>s.keyword)]),o=[];return n.forEach(s=>{let r=t.keywordMatches.filter(d=>d.keyword===s),i=e.keywordMatches.filter(d=>d.keyword===s),a=i.length-r.length;a<=0||o.push(...i.slice(0,a))}),o}var zp=t=>e=>n=>o=>{var l;if(o.type!==Wp){n(o);return}let s=e.getState().styleSuggestions.list;n(o);let r=e.getState(),i=r.styleSuggestions.list,a=(l=r.conversation)==null?void 0:l.current;if(s===i)return;let d=ly(s,i);o.type===Wp&&d.length>0&&t.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:d}})};var dy=(0,Qr.combineReducers)({assistants:xd,auth:yl,conversation:Cl,contentTypes:sc,passwordlessToken:Zu,entities:Rc,handlingTime:Hp,info:jl,input:Dl,settings:wd,profile:dc,search:Ql,styleSuggestions:gu,ui:tu,textSuggestions:Fc});function Vp(t){return(0,Qr.configureStore)({reducer:dy,middleware:e=>{var o;let n=e({thunk:{extraArgument:{dynamicThunkObject:t.dynamicThunkObject,deepdeskAPI:t.deepdeskAPI}},serializableCheck:!1}).concat(Bp()).concat(Kp({debounce:200})).concat(Up({debounce:500})).concat(zp(t.deepdeskAPI));return((o=t.middleware)!=null?o:[]).reduce((s,r)=>s.concat(r),n)},preloadedState:t.preloadedState})}function jp(t,e,n){if(e==="")return null;let o=new RegExp(`\\b${Ar(e)}\\b`,"gi"),s,r=null;for(;(s=o.exec(t))!==null&&!(s.index>n);)r={start:s.index,end:s.index+s[0].length};return r}var cy=t=>{var e,n;return(n=(e=t==null?void 0:t.type)==null?void 0:e.toLowerCase())!=null?n:"unknown"},uy=t=>e=>n=>o=>{var d,l,c,p,u,g;let s=e.getState(),r=nn("inlineSuggestions")(s),i=nn("autoSelectSuggestion")(s)||r;switch(o.type){case kn.toString():{!o.payload&&t.emit("logout",void 0);break}case ps.fulfilled.toString():{t.emit("logout",void 0);break}case Be.fulfilled.toString():o.payload.length>0&&t.sendEvent("entities found",{conversationId:(d=s.conversation.current)==null?void 0:d.id,data:{entities:o.payload}});break;case Zt.toString():t.logSendMessage(o.payload);break;case Fs.toString():t.emit("call-to-action",{cue:o.payload});break;case he.fulfilled.toString():if(!o.isBroadcasted){let{externalConversationId:m,currentExternalIdAtRequest:f}=(l=o.payload)!=null?l:{};(!m||!f||m===f)&&t.broadcast(yi,o,!1)}break;case he.rejected.toString():break;default:break}let a=n(o);switch(o.type){case Zt.toString():t.handleAfterSendMessage(o.payload);break;case Fo.toString():t.onUpdateShowTabHint(o.payload);break;case Jr.toString():t.logHandlingTime();break;case In.toString():t.broadcast(Es,o);break;case Qt.toString():t.broadcast(Es,o);break;case Hs.toString():e.dispatch(Qt({source:"assistant",assistantCode:o.payload.code}));break;case"analytics/logEvent/fulfilled":{let m=s.assistants.cues.find(f=>f.code===o.meta.arg.data.assistantCode);t.emit("event",b(h({},o.meta.arg),{cue:m}));break}case Se.toString():{let{start:m,end:f}=s.input.selection;t.emit("select-suggestion",b(h({type:cy(o.payload.suggestion)},o.payload),{replace:o.payload.replace==="selection"?{start:m,end:f}:{start:0,end:f}})),r&&e.dispatch(Rt([]));break}case pu.toString():{let{keyword:m,suggestion:f,eventMetrics:y}=o.payload,{text:v,selection:x}=s.input,T=jp(v,m,(c=x==null?void 0:x.end)!=null?c:v.length);if(!T)break;t.emit("select-suggestion",{text:f,type:"style",replace:T,suggestion:{text:f,source:"style"},eventMetrics:y});break}case vs.toString():t.emit("select-image",o.payload),t.sendEvent("Image attached",{conversationId:(p=s.conversation.current)==null?void 0:p.id,data:{path:o.payload.suggestion.image,title:o.payload.suggestion.title}});break;case Rt.toString():{i&&o.payload.length>0&&e.dispatch(Ss(0));break}case he.fulfilled.toString():{let{evaluationId:m,output:f,externalConversationId:y}=o.payload,v=o.meta.arg.assistantCode;if(t.emit("event",{name:"Assistant evaluation completed",data:{evaluationId:m,assistantCode:v,assistantOutput:fd(f),externalConversationId:y,evaluationStatus:"success"}}),!o.meta.arg.skipState){let x=e.getState().assistants.cues;t.emit("cues",x)}break}case he.rejected.toString():{let m=o.meta.arg.assistantCode,f=(g=o.meta.arg.externalConversationId)!=null?g:(u=e.getState().conversation.current)==null?void 0:u.externalId;t.emit("event",{name:"Assistant evaluation completed",data:{evaluationId:"",assistantCode:m,assistantOutput:"",externalConversationId:f,evaluationStatus:"failed"}});break}default:break}return a},$p=uy;var qp=require("@reduxjs/toolkit");function La(t){return t.toISOString().replace("T"," ").replace("Z","")}var py=(t,e)=>e.version,Gp=(0,qp.createSelector)([An,je,Op,py],(t,e,n,o)=>{if(!e)return k.warn("No conversationId for handling time metrics"),null;let{startTime:s,stopTime:r}=n;return!s||!r?(k.warn("No startTime and stopTime for handling time metrics"),null):{conversationId:e,clientVersion:o,agentId:t==null?void 0:t.agentId,agentName:t==null?void 0:t.agentName,agentEmail:t==null?void 0:t.agentEmail,timeStart:La(s),timeStop:La(r)}});function Xp(t,e){let{text:n,metrics:{numPaste:o,pastes:s,textSuggestions:r}}=t.input,i=n.length;return{source:"agent",clientVersion:e.version,pastes:s,lenTextTotal:i,numPastes:o,suggestions:r}}var Yo=class extends Error{};function gy(){let t,e;return{promise:new Promise((o,s)=>{t=o,e=s}),resolve:t,reject:e}}var Zr=class{constructor(){this.queues={}}push(e,n){let o=()=>{let r=this.queues[e][1];r?(this.queues[e]=[r.promise,null],r.resolve()):delete this.queues[e]};if(!this.queues[e]){let r=n().finally(o);return this.queues[e]=[r,null],r}this.queues[e][1]&&this.queues[e][1].reject(new Yo("Queued async function is outdated"));let s=gy();return this.queues[e][1]=s,s.promise.then(()=>n().finally(o))}};function Ma(t,e){var r;let n=t.closest(e);if(n)return n;let o=t.getRootNode().host;if(o instanceof HTMLElement)return Ma(o,e);let s=(r=t.ownerDocument.defaultView)==null?void 0:r.frameElement;return s?Ma(s,e):null}function Na(t,e){return Ma(t,e)}var my={accepted:"onConversationAcceptedAssistants","new-message":"onConversationNewMessageAssistants",ended:"onConversationEndedAssistants"},Jp=(t,e)=>{var s,r,i;if(!((i=(r=(s=t.uiConfig)==null?void 0:s.widget)==null?void 0:r.types.find(a=>a.type==="cues"))==null?void 0:i.isActive))return k.warn("Triggered a conversation assistant, but cues are not configured in widget."),[];let o=t[my[e]];return o&&o.length>0?o.map(a=>a.code):(k.warn(`No assistant set in profile for conversation event "${e}"`),[])};function Qp(t){return typeof t=="object"&&t!==null&&"name"in t&&"message"in t}function fy(t){return typeof t=="object"&&t!==null&&"tagName"in t}function Yr(t){return fy(t)&&(hn(t)||Pr(t))}var Yp,et=new Map,hy=["bottom","height","left","right","top","width"],Zp=(t,e)=>!t&&!e?!1:t&&!e||!t&&e?!0:hy.some(n=>t[n]!==e[n]);function eg(t){var n,o,s;if(t.ownerDocument===document)return[];let e=(s=(o=(n=t.ownerDocument)==null?void 0:n.defaultView)==null?void 0:o.frameElement)!=null?s:null;return e?[e,...eg(e)]:[]}function tg(t,e){return!t||!e?null:b(h({},t),{top:t.top+e.top,left:t.left+e.left})}var ei=!1,ng=()=>{ei=!0;let t=[];if(et.forEach((e,n)=>{if(!n.isConnected){e.rect=null,t.push(e),et.delete(n);return}let o=n.getBoundingClientRect();Zp(o,e.rect)&&(e.rect=o,t.push(e))}),t.forEach(e=>{let n=e.parentRects?e.parentRects.reduce(tg,e.rect):e.rect;Zp(n,e.totalRect)&&e.callbacks.forEach(o=>o(n)),e.totalRect=n}),et.size===0){ei=!1;return}Yp=window.requestAnimationFrame(ng)};function Oa(t,e){let n=eg(t),o=[],s=n.map((r,i)=>Oa(r,a=>{o[i]=a;let d=et.get(t);if(!d)return;let l=o.reduce(tg,d.rect);d.callbacks.forEach(c=>c(l))}));return{observe(r=!0){if(s.forEach(i=>i.observe(!1)),et.has(t)){let i=et.get(t);i.callbacks.push(e),i.rect&&e(i.rect)}else et.set(t,{rect:void 0,callbacks:[e],parentRects:o});r&&!ei&&ng()},unobserve(){s.forEach(i=>i.unobserve());let r=et.get(t);if(r){let i=r.callbacks.indexOf(e);i>=0&&r.callbacks.splice(i,1),r.callbacks.length||et.delete(t),et.size||(cancelAnimationFrame(Yp),ei=!1)}}}}var og,tt=new Map,sg=()=>{tt.forEach((t,e)=>{if(!e.isConnected){tt.delete(e);return}let{clientHeight:n,scrollHeight:o}=e,s=o>n;t.visible!==s&&(t.visible=s,t.callbacks.forEach(r=>r(t.visible)))}),tt.size!==0&&(og=window.requestAnimationFrame(sg))};function rg(t,e){return{observe(){let n=tt.size===0;tt.has(t)?tt.get(t).callbacks.push(e):tt.set(t,{visible:void 0,callbacks:[e]}),n&&sg()},unobserve(){let n=tt.get(t);if(n){let o=n.callbacks.indexOf(e);o>=0&&n.callbacks.splice(o,1),n.callbacks.length||tt.delete(t),tt.size||cancelAnimationFrame(og)}}}}var Da=["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 _a(t,e,n){return n.forEach(o=>{e.style[o]=t[o]})}function Yn(t){return Number.parseFloat(t)}function ti(t){return Math.round(t*1e6)}function ig(t){return t/1e6}function Fa(t,e,n){if(t.boxSizing==="content-box")return;let{clientWidth:o}=e,s=Yn(t.width),r=Yn(t.borderLeftWidth),i=Yn(t.borderRightWidth),a=Yn(t.paddingRight),d=ig(ti(s)-ti(r)-ti(i)),l=ig(ti(o));if(d-l>2){let c=d-l;n.style.paddingRight=`${a+c}px`}}function es(t,e={}){var c,p;let n=e.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=(c=e.position)!=null?c:"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",sn(n);let o=window.getComputedStyle(t),s=!0,r=()=>{n.scrollTop=t.scrollTop};_a(o,n,Da),Fa(o,t,n),e.mirrorOverflow&&(n.style.overflow="hidden",t.addEventListener("scroll",r));let i=rg(t,()=>{_a(o,n,Da),Fa(o,t,n),r(),setTimeout(r,0)}),a,d=!0,l=Oa(t,u=>{if(u===null){e.onRemove&&e.onRemove(),n.remove();return}if(!d&&e.onMoveStart&&(Promise.resolve().then(()=>e.onMoveStart()),d=!0),clearTimeout(a),a=setTimeout(()=>{e.onMoveEnd&&e.onMoveEnd(),d=!1},200),u.height===0&&u.width===0){if(s===!0)return;e.onHide&&e.onHide(),n.style.display="none",s=!0;return}if(_a(o,n,Da),Fa(o,t,n),r(),e.placement==="below"&&n.classList.add("below"),n.style.top=`${u.top}px`,n.style.left=`${u.left}px`,e.closestScrollElement&&e.closestScrollElement!==t){let g=e.closestScrollElement.getBoundingClientRect(),m=window.getComputedStyle(e.closestScrollElement),f=Yn(m.borderTopWidth),y=Yn(m.borderBottomWidth),v=g.top+f-u.top,x=u.top+u.height+-(g.top+g.height-y);n.style.clipPath=`inset(${v}px 0px ${x}px 0px)`}s&&(n.style.display="block",e.onShow&&e.onShow(),s=!1)});return e.appendTo?e.appendTo.appendChild(n):(p=t.parentElement)==null||p.appendChild(n),l.observe(),i.observe(),[n,()=>{t.removeEventListener("scroll",r),l.unobserve(),i.unobserve(),n.remove()}]}function yy(t){return t.offsetParent!==null}function ag(t){if(!yy(t))return!1;let e=t.getBoundingClientRect();return e.top>=0&&e.left>=0&&e.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&e.right<=(window.innerWidth||document.documentElement.clientWidth)}function ni(t,e,n=100){let o=ag(t);e({isVisible:o});let s=setInterval(()=>{let r=ag(t);r!==o&&(o=r,e({isVisible:o}))},n);return()=>{clearTimeout(s)}}var lg=(t,e)=>({value(){try{let n=sessionStorage.getItem(`dd-${t}`);if(!n)return e;try{return JSON.parse(n)}catch(o){return e}}catch(n){return e}},update(n){try{sessionStorage.setItem(`dd-${t}`,JSON.stringify(n))}catch(o){k.warn("[Deepdesk] SessionStorage is blocked by browser")}}});var B=require("react/jsx-runtime");var dg=lg("showTabHint",!0),eo=class eo{constructor({deepdeskUrl:e,version:n=eo.version||"unknown",locale:o="en-US",token:s,fetch:r,productName:i,createCustomChannel:a,websocketClient:d=Xr}){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 Zr;this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;let l=e.replace(/\/api$/,"");this.deepdeskApi=new xt(l,{token:s,fetch:r}),this.version=n,this.instanceId=eo.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[$p({broadcast:(m,f,y)=>{this.broadcastEvents.send(m,f,y)},emit:(m,f)=>this.emit(m,f),handleAfterSendMessage:m=>this.handleAfterSendMessage(m),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:m=>this.logSendMessage(m),onUpdateShowTabHint:m=>dg.update(m),sendEvent:(m,f)=>this.deepdeskApi.sendEvent(m,f)})]};this.store=Vp(c),this.broadcastEvents=new Ip({debug:!0,deepdeskUrl:l,eventMap:Zl(this.store),createCustomChannel:a}),this.disposeHandlers.push(()=>{this.broadcastEvents.cleanup()}),this.ws=new d({url:`${l}/api/v2/me/realtime`.replace("https","wss"),reconnectInterval:25e3,shouldReconnect:()=>S(this,null,function*(){var m;return(m=se(this.state))!=null?m:!1})}),this.whenLoggedIn(()=>this.ws.connect()),this.store.dispatch(Fo(dg.value())),this.store.dispatch(Bs({locale:o,adminUrl:l,productName:i}));let p=[],u=m=>{if(!m.conversationId)return;let f=()=>{this.conversationId()===m.conversationId&&this.store.dispatch(Sd(m))};this.hasConversation()?f():p.push(f)};this.ws.on("assistants::direct_response",u),this.ws.on("assistants::user_notification",u),this.ws.on("assistants::response_chunk",m=>{if(!m.conversationId)return;let f=()=>{this.conversationId()===m.conversationId&&this.store.dispatch(vd(m))};this.hasConversation()?f():p.push(f)}),this.ws.on("assistants::suggest_as_reply",m=>{if(!m.conversationId)return;let f=()=>{this.conversationId()===m.conversationId&&this.store.dispatch(In([{text:m.payload.message,type:"text",source:"assistant",assistantCode:m.code,sourceLabel:m.name}]))};this.hasConversation()?f():p.push(f)});let g=this.whenConversationLoaded(()=>{var m;this.broadcastEvents.setExternalId((m=this.state.conversation.current)==null?void 0:m.externalId),p.forEach(f=>f()),p.length=0});this.disposeHandlers.push(()=>{this.ws.cleanup(),p.length=0,g()})}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){var e;return(e=Jt(this.state)[this.state.input.selectedSuggestionIndex])!=null?e: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?(k.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(k.warn("Profile has not been loaded (yet)"),!0):(k.warn("No conversation loaded (yet)"),!0)}whenLoggedIn(e){if(se(this.state))e();else{let n=this.subscribe(se,o=>{o&&e()});this.disposeHandlers.push(()=>{n()})}}login(){return this.store.dispatch(kn(null)),this.store.dispatch(st()),new Promise(e=>{this.whenLoggedIn(()=>e())})}isLoggedIn(){return S(this,null,function*(){return(yield this.store.dispatch(st())).payload})}isConversationSupported(e,n){return S(this,null,function*(){return(yield this.store.dispatch(ci({externalId:e,options:n}))).payload})}createConversation(e){return S(this,null,function*(){var o;return this.hasConversation()&&this.externalId()!==e.externalId&&this.resetConversation(),(yield this.store.dispatch(fs(b(h({},e),{metadata:(o=e.metadata)!=null?o:{}})))).payload})}getConversationByExternalId(e,n){return S(this,null,function*(){return this.hasConversation()&&this.externalId()!==e&&this.resetConversation(),(yield this.store.dispatch(hs({externalId:e,options:n}))).payload})}upsertConversation(e){return S(this,null,function*(){var o;return this.hasConversation()&&this.externalId()!==e.externalId&&this.resetConversation(),(yield this.store.dispatch(ui(b(h({},e),{metadata:(o=e.metadata)!=null?o:{}})))).payload})}postMessages(e){return S(this,null,function*(){yield this.store.dispatch(pi(e))})}updateConversation(e){return S(this,null,function*(){return(yield this.store.dispatch(ys(e))).payload})}resetConversation(){this.store.dispatch(Y()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}configure(e){this.store.dispatch(Bs(e))}setVisitorInfo(e){this.store.dispatch(Kl(e))}setCustomData(e){this.store.dispatch(Wl(e))}setAgentInfo(e,n){return S(this,null,function*(){var s;yield this.store.dispatch(io(h(h({},e),n))),(s=this.state.info.agentInfo)!=null&&s.agentNickname||this.broadcastEvents.send(ws,{showNicknameDialog:!0})})}setAgentSettings(e){return S(this,null,function*(){yield this.store.dispatch(mi(e))})}getAgentSettings(){return S(this,null,function*(){return(yield this.store.dispatch(fi())).payload})}refresh(){return S(this,null,function*(){if(this.shouldAbort())return Promise.resolve();let e=[];return e.push(this.refreshTextSuggestions()),e.push(this.refreshWidgetSuggestions()),Promise.all(e).then(()=>{})})}syncInputMediator(){this.inputMediator&&this.store.dispatch(xs({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),suggestionTextStart:this.inputMediator.getSuggestionTextStart()}))}notifyExternalSuggestion(e){this.store.dispatch(Se(e))}evaluateAssistant(e,n){return S(this,null,function*(){var c;let{input:o={},attachments:s=[],transcript:r,showCuesInWidget:i=!0,includeMetadata:a,externalConversationId:d}=n||{},l=yield this.store.dispatch(he({assistantCode:e,attachments:s,transcript:r,includeMetadata:a,input:o,externalConversationId:d,skipState:!i}));if(l.error)throw new Error(`Assistant evaluation failed: ${(c=l.payload)!=null?c:l.error.message}`);return l.payload.output})}evaluateConversationAssistant(e,n){return S(this,null,function*(){var c,p,g;yield this.loadProfileConfig();let o=this.state.profile.data;if(!o&&((c=this.state.conversation.current)!=null&&c.profileCode)&&(yield this.loadProfileConfig(),o=this.state.profile.data),!o){k.warn("Can't evaluate assistant when profile is not loaded yet.");return}let s=Jp(o,e),r=(p=n==null?void 0:n.showCuesInWidget)!=null?p:!0,u=n!=null?n:{},{showCuesInWidget:i}=u,a=O(u,["showCuesInWidget"]),d=(g=n==null?void 0:n.externalConversationId)!=null?g:this.hasConversation()?this.externalId():"",l=yield Promise.all(s.map(m=>this.queues.push(m,()=>S(this,null,function*(){var y,v;let f=yield this.store.dispatch(he(h(b(h({assistantCode:m,includeMetadata:!0},a),{skipState:!r}),n!=null&&n.attachments&&(n==null?void 0:n.attachments.length)>0?{attachments:n==null?void 0:n.attachments}:{})));if(f.error)throw new Error(`Assistant evaluation failed: ${(y=f.payload)!=null?y:f.error.message}`);return{assistantCode:m,evaluationId:f.payload.evaluationId,output:f.payload.output,externalConversationId:(v=f.payload.externalConversationId)!=null?v:d}})).catch(f=>{if(f instanceof Yo)return k.warn(`Queued assistant "${m}" was outdated and dropped`),null;throw f})));if(!r)return l.filter(m=>m!==null)})}handleKeyDown(e){let{overlayCollapsed:n,openOverlayWhenTyping:o}=this.state.ui,{textSuggestions:s,selectedSuggestionIndex:r,selection:i}=this.state.input,{inlineSuggestions:a,autoSelectSuggestion:d,showTextSuggestions:l,suggestionsPlacement:c}=this.settings,p=a||d,u=c==="inline"||c==="below"?"below":"above",g=s.length>0;if(this.store.dispatch(Pl(gi(e))),!Je(this.state)||e.key!=="Tab"&&!l)return;let m=()=>{n||!g||i&&(e.shiftKey||(this.store.dispatch(Ll()),e.preventDefault()))},f=()=>{n||!g||p&&r<=0||i&&(e.shiftKey||(this.store.dispatch(Ml()),e.preventDefault()))};switch(e.key){case"ArrowUp":u==="below"?f():m();break;case"ArrowDown":{u==="below"?m():f();break}case"Escape":{n||(this.store.dispatch(Ss(-1)),this.store.dispatch(Dt({collapse:!0})),this.store.dispatch(Yc(!0)),e.preventDefault());break}case"Tab":{e.preventDefault();let y=Pn(this.state);if(!y)return;this.store.dispatch(Fo(!1)),this.store.dispatch(Se({text:y.text,suggestion:y,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(p||this.state.input.selectedSuggestionIndex===-1)return;let y=Pn(this.state);if(!y)return;this.store.dispatch(Se({text:y.text,suggestion:y,eventMetrics:{inputType:"space"},replace:"until-selection-end"}));break}case"Enter":{if(p||e.shiftKey||this.state.input.selectedSuggestionIndex===-1)return;let y=Pn(this.state);if(!y)return;this.store.dispatch(Se({text:y.text,suggestion:y,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),e.preventDefault();break}default:}n&&o&&this.store.dispatch(Dt({collapse:!1}))}handleAfterSendMessage(e){this.emit("send-message",e),this.store.dispatch(Rt([]))}handlingTimeStart(){this.state.handlingTime.startTime||(k.info("Start handling time"),this.store.dispatch(_p()))}handlingTimeStop(){this.state.handlingTime.startTime&&(k.info("Stop handling time"),this.store.dispatch(Jr()))}logSendMessage(e){let n=Xp(this.state,{version:this.version});n&&(e&&(Object.assign(n,{text:e}),Object.assign(n,{lenTextTotal:e.length})),this.deepdeskApi.sendEvent("Send Message",{conversationId:this.conversationId(),data:n}),this.emit("send-message-event",n))}logHandlingTime(){let e=Gp(this.state,{version:this.version});e&&(this.deepdeskApi.sendEvent("Handling Time",{conversationId:this.conversationId(),data:e}),this.store.dispatch(Fp()))}notifySubmit(e={}){var n;this.shouldAbort()||(this.store.dispatch(Zt((n=e.text)!=null?n:this.state.input.text)),this.store.dispatch(Ol()))}emit(e,n){let o=this.eventListeners[e];o&&o.forEach(s=>{try{s(n)}catch(r){k.warn(`The following error occurred in deepdeskSDK.on('${e}', handler)`),k.error(r)}})}on(e,n){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(n),()=>{this.off(e,n)}}off(e,n){if(!e&&!n){this.eventListeners={};return}let o;this.eventListeners[e]&&(o=this.eventListeners[e].indexOf(n),o>-1&&this.eventListeners[e].splice(o,1))}setConversationQuery(e){this.dynamicThunkObject.conversationQuery=e}setPlatformVariables(e){this.store.dispatch(zl(e))}whenConversationLoaded(e){let n=r=>{var i;return(i=r.conversation.current)==null?void 0:i.id},o=()=>this.loadProfileConfig().then(()=>e());return n(this.state)&&o(),this.subscribe(n,r=>{r&&o()})}overlayContainerFactory(e,n,o,s){let[r,i]=es(n,o);return r.setAttribute("translate","no"),r.dataset.testid=e,s&&r.classList.add(s),[r,i]}createInlineContainer(e,n){var a;let o=document.createElement("div");o.style.position="absolute",o.style.top="0px",o.style.left="0px",o.style.height="0px",o.style.width="0px";let s=document.createElement("div");s.style.display="none",s.style.position="absolute",s.style.height="0px",s.style.width="0px",s.style.backgroundColor="red",o.appendChild(s);let r=(a=e.ownerDocument.defaultView)==null?void 0:a.frameElement,i=r?r.ownerDocument.defaultView:null;if(r&&(i===window||(i==null?void 0:i.parent)===window)){let[d,l]=es(r,{appendTo:document.body,onMoveStart:()=>{s.style.display="none"}});d.dataset.testid=n,d.style.zIndex="2",d.appendChild(o),this.unmountHandlers.push(()=>{l()})}else document.body.appendChild(o);return s}createContainer(e,n=document.body){let o=window.getComputedStyle(n),s=document.createElement("div");return sn(s),s.dataset.testid=e,s.style.color=o.color,s.style.fontSize=o.fontSize,s.style.fontFamily=o.fontFamily,s.style.fontVariant=o.fontVariant,s.setAttribute("translate","no"),n.appendChild(s),s}storeMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,n=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(e,n),k.info(`Stored analytics for ${this.conversationId()}`)}catch(e){}}restoreMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,n=window.sessionStorage.getItem(e);if(!n)return;let o=JSON.parse(n);o.text.trim()===this.state.input.text.trim()?(k.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(Nl(o.metrics))):k.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(e)}catch(e){}}mount(e,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!Yr(e))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let u=n,{customStyles:o,closestScrollSelector:s,floatingMenuParent:r,appendOverlayTo:i,inputMediator:a}=u,d=O(u,["customStyles","closestScrollSelector","floatingMenuParent","appendOverlayTo","inputMediator"]),l={customStyles:o,closestScrollSelector:s,floatingMenuParent:r,appendOverlayTo:i};this.configure(d),this.settings.automaticHandlingTime&&this.setupHandlingTime(e),sn(e),this.inputMediator=a||(hn(e)?new Sn(e):new vn(e)),this.inputMediator.on("change",({plainText:g,rawHTML:m,suggestionTextStart:f})=>{this.store.dispatch(xs({text:g,html:m,suggestionTextStart:f}))}),this.inputMediator.on("keyup",g=>{this.store.dispatch(Il(gi(g)))}),this.inputMediator.on("keydown",g=>{this.handleKeyDown(g)}),this.inputMediator.on("paste",({pastedText:g,selectionText:m})=>{this.store.dispatch(Al({text:g,selectionText:m}))}),this.inputMediator.on("cut",({selectionText:g})=>{this.store.dispatch(Rl(g))});let c;this.inputMediator.on("selection",g=>{clearTimeout(c),g===null?c=setTimeout(()=>{g!==null&&this.store.dispatch(bs(g))},500):this.store.dispatch(bs(g))}),this.unmountHandlers.push(()=>{clearTimeout(c)}),this.inputMediator.on("disabled",()=>{var g;(g=this.inputMediator)==null||g.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(vr(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(vr(!0))}),this.renderSuggestions(e,l),this.subscribe(nn("inlineSuggestions"),()=>{this.renderSuggestions(e,l)}),this.subscribe(nn("suggestionsPlacement"),()=>{this.renderSuggestions(e,l)});let p=this.renderOverlays(n);this.unmountHandlers.push(()=>{p.unmount()}),this.store.dispatch(xs({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),suggestionTextStart:this.inputMediator.getSuggestionTextStart()})),this.store.dispatch(bs(this.inputMediator.getSelection())),this.store.dispatch(vr(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(e){if(this.nicknameDialogUnsubscribe||this.nicknameDialogFailed)return;let n=this.createContainer("nickname-dialog",document.body);document.body.appendChild(n);let o=(0,bt.createRoot)(n),s=null,r=a=>{s=a,i()},i=()=>{o==null||o.render((0,B.jsx)(mt,{store:this.store,children:(0,B.jsx)(it,{broadcastEvents:this.broadcastEvents,children:(0,B.jsx)(yu,{id:"deepdesk-nickname-dialog",error:s,onSave:a=>S(this,null,function*(){try{yield this.store.dispatch(Bl({agentNickname:a})).unwrap(),console.log("setAgentNickname",a),this.broadcastEvents.send(ws,{showNicknameDialog:!1}),this.nicknameDialogUnsubscribe&&this.nicknameDialogUnsubscribe()}catch(d){k.error("Error setting agent nickname",d),r("error"),this.nicknameDialogFailed=!0}})})})}))};i(),this.nicknameDialogUnsubscribe=()=>{o.unmount(),n.remove(),this.nicknameDialogUnsubscribe=null}}subscribe(e,n){let o=e(this.store.getState());return this.store.subscribe(()=>{let s=e(this.store.getState());s!==o&&(o=s,n(o))})}unmount(){var e,n,o,s,r;(e=this.inlineSuggestions)==null||e.unmount(),(n=this.aboveSuggestions)==null||n.unmount(),(o=this.belowSuggestions)==null||o.unmount(),(s=this.floatingMenu)==null||s.unmount(),this.unmountHandlers.forEach(i=>i()),this.unmountHandlers=[],(r=this.inputMediator)==null||r.dispose(),this.nicknameDialogUnsubscribe&&this.nicknameDialogUnsubscribe(),this.isMounted=!1}dispose(){this.unmount(),this.unmountWidget(),this.disposeHandlers.forEach(e=>e()),this.disposeHandlers=[],this.off()}renderSuggestions(e,n){var o,s,r,i;(o=this.floatingMenu)==null||o.unmount(),(s=this.inlineSuggestions)==null||s.unmount(),(r=this.aboveSuggestions)==null||r.unmount(),(i=this.belowSuggestions)==null||i.unmount(),this.settings.floatingMenu&&(this.floatingMenu=this.renderFloatingMenu(e,n)),this.settings.inlineSuggestions||this.settings.suggestionsPlacement==="inline"?this.inlineSuggestions=this.renderInlineSuggestions(e,n):this.settings.suggestionsPlacement==="below"?this.belowSuggestions=this.renderAboveOrBelowSuggestions(e,n,"below"):this.aboveSuggestions=this.renderAboveOrBelowSuggestions(e,n,"above")}renderInlineSuggestions(e,n){let{customStyles:o}=n,s=this.createInlineContainer(e,"deepdesk-caret"),r=(0,bt.createRoot)(s);r.render((0,B.jsx)(mt,{store:this.store,customStyles:o,children:(0,B.jsx)(it,{broadcastEvents:this.broadcastEvents,children:(0,B.jsx)(mu,{})})}));let i=a=>{a?(s.style.display="block",s.style.top=`${a.top}px`,s.style.left=`${a.left}px`):s.style.display="none"};return this.inputMediator.on("caretposition",i),{unmount:()=>{var a;(a=this.inputMediator)==null||a.off("caretposition",i),r.unmount(),s.remove()}}}renderAboveOrBelowSuggestions(e,n,o){let{customStyles:s,closestScrollSelector:r,appendOverlayTo:i}=n,a=r&&Na(e,r)||void 0,[d,l]=this.overlayContainerFactory("deepdesk-tab-completion",a||e,{appendTo:i,closestScrollElement:a,mirrorOverflow:!0,onRemove:()=>this.unmount()},s==null?void 0:s.rootNode),[c,p]=this.overlayContainerFactory("deepdesk-suggestions-overlay",a||e,{appendTo:i,placement:o},s==null?void 0:s.suggestionsRootNode),u=(0,bt.createRoot)(d);u.render((0,B.jsx)(mt,{store:this.store,customStyles:s,children:(0,B.jsx)(it,{broadcastEvents:this.broadcastEvents,children:(0,B.jsx)(Xu,{inputElement:e})})}));let g=(0,bt.createRoot)(c);return g.render((0,B.jsx)(mt,{store:this.store,customStyles:s,children:(0,B.jsx)(it,{broadcastEvents:this.broadcastEvents,children:(0,B.jsx)(Pu,{onLogIn:()=>this.loginViaPopup().catch(m=>k.warn(m.message))})})})),{unmount(){u.unmount(),g.unmount(),l(),p()}}}renderFloatingMenu(e,n){let{customStyles:o,closestScrollSelector:s,appendOverlayTo:r,floatingMenuParent:i}=n,a=s&&Na(e,s)||void 0,[d,l]=this.overlayContainerFactory("floating-menu",a||e,{appendTo:i!=null?i:r},o==null?void 0:o.floatingMenuParent),c=(0,bt.createRoot)(d);return c.render((0,B.jsx)(mt,{store:this.store,customStyles:o,children:(0,B.jsx)(it,{broadcastEvents:this.broadcastEvents,children:(0,B.jsx)(Jc,{onLogIn:()=>this.loginViaPopup().catch(p=>k.warn(p.message))})})})),{unmount(){c.unmount(),l()}}}renderOverlays(e){let{customStyles:n}=e,o=this.createContainer("deepdesk-overlays"),s=(0,bt.createRoot)(o);return s.render((0,B.jsx)(mt,{store:this.store,customStyles:n,children:(0,B.jsx)(it,{broadcastEvents:this.broadcastEvents,children:(0,B.jsx)(zc,{})})})),{unmount(){s.unmount(),o.remove()}}}renderWidget(e,n={}){if(this.widgetElement&&k.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:o,showImages:s,isEmbedded:r,signInViaPopup:i,ssoUrl:a}=n;this.widgetElement=e,this.configure({showImages:s,isEmbedded:r,signInViaPopup:i});let d;if(a)try{d={url:new URL(a,this.settings.adminUrl).toString()}}catch(l){k.warn(`Invalid ssoUrl '${a}' passed to renderWidget`)}this.widgetRoot=(0,bt.createRoot)(e),this.widgetRoot.render((0,B.jsx)(mt,{store:this.store,customStyles:o,children:(0,B.jsx)(it,{broadcastEvents:this.broadcastEvents,children:(0,B.jsx)(Tp,{assistantOptions:n.assistantOptions,knowledgeAssistOptions:n.knowledgeAssist,onLogIn:()=>this.loginViaPopup(d).catch(l=>k.warn(l.message))})})}))}unmountWidget(){var e,n;(n=(e=this.widgetRoot)==null?void 0:e.unmount)==null||n.call(e),this.widgetRoot=null,this.widgetElement=null}renderKnowledgeAssistantWidget(e,n,o={}){let{customStyles:s,initialQuestion:r}=o,i=(0,bt.createRoot)(n);return i.render((0,B.jsx)(mt,{store:this.store,customStyles:s,children:(0,B.jsx)(it,{broadcastEvents:this.broadcastEvents,children:(0,B.jsx)(ka,{children:(0,B.jsxs)(Zs,{assistantCode:e,initialQuestion:r,evaluateKnowledgeAssistFn:bo,children:[(0,B.jsx)(wn,{children:(0,B.jsx)(er,{title:o.title,emptyState:o.emptyState})}),(0,B.jsx)(Ea,{children:(0,B.jsx)(Ys,{})})]})})})})),{unmount(){i.unmount()}}}setupHandlingTime(e){let n=ni(e,({isVisible:o})=>{o?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){Qp(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfig(){var e;return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(e=this.state.conversation.current)!=null&&e.profileCode?(this.loadProfileConfigPromise=Promise.resolve().then(()=>S(this,null,function*(){yield this.store.dispatch(Eo()).unwrap();let n=Mt(this.state);n&&this.store.dispatch(Bs({showSearch:n.search,showImageSearch:n.imageSearch,showEntitiesCommand:n.entitiesCommand,showSummaryCommand:!!n.summarizerAssistantNew,showKnowledgeSearch:!!n.knowledgeAssistantNew||!!n.knowledgeAssistant,recommendTextSuggestions:n.recommendTextSuggestions}))})).finally(()=>{Mt(this.state)||(this.loadProfileConfigPromise=null)}),this.loadProfileConfigPromise):Promise.resolve()}loginViaPopup(e){return S(this,null,function*(){return new Promise((n,o)=>{this.store.dispatch(gs());let s=new MessageChannel,r=s.port1,i=this.settings.adminUrl,a=new URL(e!=null&&e.url?e==null?void 0:e.url:`${i}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let d=!1,l=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",p),clearInterval(u)};r.onmessage=g=>S(this,null,function*(){var m,f;if((m=g.data)!=null&&m.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((f=g.data)==null?void 0:f.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(lo),d=!0,s.port1.close(),n()}catch(y){console.error(y),o(y)}finally{d=!0,l()}});let c=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");c===null&&o(new Error("Popup blocked by browser"));let p=g=>S(this,null,function*(){var m;if(g.origin===a.origin)switch((m=g.data)==null?void 0:m.type){case"deepdesk-popup-request-origin":{try{let f=JSON.stringify({type:"deepdesk-popup-parent-origin"});c==null||c.postMessage(f,a.origin)}catch(f){k.error("Error posting message to popup",f),o(f)}break}case"deepdesk-popup-loaded":{try{let f=JSON.stringify({type:"deepdesk-popup-create-channel"});c==null||c.postMessage(f,a.origin,[s.port2])}catch(f){k.error("Error posting message to popup",f),o(f)}break}case"deepdesk-popup-error":{if(l(),g.data.message==="Platform account url mismatch"){let f=`Please contact your administrator: The platform account url (${g.data.targetOrigin}) is misconfigured as it differs from the origin of the page that opened the popup (${g.data.openerOrigin}).`;k.warn(f),this.store.dispatch(di(f)),o(new Error(f))}if(g.data.message==="Timeout"){let f="Please contact your administrator: Popup timed out. Check if the account's platform url is configured correctly.";k.warn(f),this.store.dispatch(di(f)),o(new Error(f))}o(new Error(g.data.message));break}}});window.addEventListener("message",p);let u=setInterval(()=>{c&&!c.closed||(l(),d||o(new Error("Popup closed by user")))},200);this.disposeHandlers.push(l)})})}translateMessages(e){return this.deepdeskApi.translateMessages(e)}refreshTextSuggestions(){return S(this,null,function*(){this.isMounted&&(yield this.store.dispatch(mr()))})}refreshWidgetSuggestions(){return S(this,null,function*(){if(!this.widgetRoot)return;let{uiConfig:e}=this.state.profile.data;if(!e.widget)return;let n=ko(this.state);try{n.forEach(({type:o})=>{switch(o){case"entities":this.store.dispatch(Be());break;case"pinned-messages":case"sticky-messages":break;default:us.includes(o)||this.store.dispatch(Ue(o))}})}catch(o){this.handleError(o)}})}};eo.version="19.5.1-beta.1",eo.count=0;var ts=eo;function vy(t){return S(this,null,function*(){var s,r,i;let n=yield((s=t.fetch)!=null?s:window.fetch)(t.url),o=yield n.blob();return new File([o],t.name,{type:(i=(r=t.mimeType)!=null?r:n.headers.get("Content-Type"))!=null?i:"image/jpeg"})})}function cg(t,e){return S(this,null,function*(){let n=yield vy(e),o=new Event("change",{bubbles:!0,cancelable:!0});try{Object.defineProperty(t,"files",{configurable:!0,get:()=>[n]}),t.dispatchEvent(o)}finally{Object.hasOwn(t,"files")&&delete t.files}})}function ug(t,e,n){return S(this,null,function*(){yield new xt(t).authenticateWithKey(e,n)})}function pg(t){return t.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function gg(o,s){return S(this,arguments,function*(t,e,n={}){var p,u;let{value:r}=t,{start:i,end:a}=(p=n.replace)!=null?p:{start:0,end:r.length},d=`${r.slice(0,i)}${e}${r.slice(a)}`,l=(u=n.selectionAfter)!=null?u:{start:i+e.length,end:i+e.length},c=()=>{if(n.setValue)return n.setValue(d);t.value=d};return Promise.resolve(c()).then(()=>{t.selectionStart=l.start,t.selectionEnd=l.end,t.blur(),t.focus()})})}function mg(o,s){return S(this,arguments,function*(t,e,n={}){let r=n.replace?Kt(t,n.replace.start,n.replace.end):Qn(t),i,a=()=>{if(n.setRange)return n.setRange(r.cloneRange());r.deleteContents(),i=document.createElement("span"),r.insertNode(i),n.insertBRs!==!1?e.split(`
12
- `).reverse().forEach((d,l)=>{l>0&&r.insertNode(document.createElement("br")),r.insertNode(document.createTextNode(d))}):r.insertNode(document.createTextNode(e))};return Promise.resolve(a()).then(()=>{try{if(n.selectionAfter!==!1){t.focus();let d=n.selectionAfter?Kt(t,n.selectionAfter.start,n.selectionAfter.end):(r.collapse(!1),r),l=window.getSelection();l==null||l.removeAllRanges(),l==null||l.addRange(d)}if(!i)return;i.scrollIntoView&&i.scrollIntoView({block:"nearest",inline:"nearest"})}finally{i&&i.remove()}})})}function Sy(t){let e=document.createElement("template");return e.innerHTML=t.replace(/(\[([^\]]+)])\(([^)]+)\)/g,'<a href="$3" target="_blank" rel="noopener noreferrer">$2</a>'),e.content}function xy(t){let e=document.createDocumentFragment();return t.split(`
13
- `).forEach((n,o)=>{o>0&&e.appendChild(document.createElement("br"));let s={index:0},r=0;for(;s=n.slice(r).match(/(\[([^\]]+)])\(([^)]+)\)/);){let i=document.createElement("a");i.href=s[3],i.setAttribute("target","_blank"),i.setAttribute("rel","noopener noreferrer"),i.appendChild(document.createTextNode(s[2])),e.appendChild(document.createTextNode(n.slice(r,r+s.index))),e.appendChild(i),r=r+s.index+s[0].length}e.appendChild(document.createTextNode(n.slice(r)))}),e}function fg(t,e){let n=t.parentElement;if(!n){console.warn("No insert point found");return}let{display:o}=window.getComputedStyle(n);o.includes("block")||o==="table-cell"?n==null||n.insertBefore(e,t.nextSibling):fg(n,e)}function hg(s,r){return S(this,arguments,function*(t,e,{isBlock:n,isHTML:o}={}){let i;t.dispatchEvent(new InputEvent("beforeinput",{inputType:"insertText",data:e,bubbles:!0,cancelable:!0}));let a=()=>{var u;let d=(u=t.ownerDocument.defaultView)!=null?u:window,l=d.getSelection();if((!l||l.rangeCount===0)&&(t.focus(),l=d.getSelection()),!l||l.rangeCount===0)return;let c=l.getRangeAt(0);if(!c)return;i=document.createElement("span"),c.insertNode(i);let p=o?Sy(e):xy(e);n?fg(c.startContainer,p):(c.insertNode(p),c.collapse(!1))};return Promise.resolve(a()).then(()=>{if(t.dispatchEvent(new InputEvent("input",{inputType:"insertText",data:e,bubbles:!0,cancelable:!0})),t.focus(),!!i)try{i.scrollIntoView&&i.scrollIntoView({block:"nearest",inline:"nearest"})}finally{i&&i.remove()}})})}0&&(module.exports={Card,ContentEditableInput,DeepdeskAPI,DeepdeskSDK,HTTPClient,InputMediator,InputType,KeyboardHint,Label,Locale,Section,SectionList,Sources,Suggestion,SuggestionList,TextAreaInput,ToggleButton,attachFile,authenticateWithKey,createFullRange,createOverlayContainer,createRangeFromOffsets,escapeHTML,formatTextMarkup,getRangeOffsets,getRangeText,insertCKEditor,isHTML,isSupportedInputElement,logEvent,updateContentEditable,updateTextArea,useClickOutsideRoot,useStyles,waitForElementVisibilityChange});
9
+ 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 ta=require("react/jsx-runtime"),Jf={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},Zc=({className:t,color:e})=>(0,ta.jsx)("svg",{className:t,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:(0,ta.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:Jf[e||"pink"]})});var Yc={root:"dd-LbeUM",text:"dd-Dpfn1",isLoggedIn:"dd-XvHAn",isLoggedOut:"dd-21y-z",icon:"dd-8rLqS",logo:"dd-slXhD",lock:"dd-ByzlR"};var na={};Z(na,{enUS:()=>Qf,nlNL:()=>Zf});var Qf={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},Zf={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};var nu=require("react-redux"),pn=require("react/jsx-runtime"),ou=({onLogIn:t})=>{let e=P(na),n=E("floatingMenu"),o=E("productName"),s=(0,nu.useDispatch)(),r=(0,tu.useSelector)(se),i=C("FloatingMenu",Yc);if(r===null||n===!1)return null;let a=()=>{r===!0?s(_e(!0)):t()};return(0,pn.jsxs)("button",{type:"button",className:(0,eu.default)(i.root,{[i.isLoggedIn]:r,[i.isLoggedOut]:!r}),onClick:a,children:[(0,pn.jsx)("div",{className:i.text,children:e(r?"search":"signin",{productName:o})}),(0,pn.jsxs)("div",{className:i.icon,children:[(0,pn.jsx)(Zc,{className:i.logo,color:"pink"}),r===!1&&(0,pn.jsx)(Qc,{className:i.lock})]})]})};var Pr=require("react"),Ze=require("react-redux");function Qe(t){let{showMidSentenceSuggestions:e,showSuggestionsBeforePattern:n,showSuggestionsAfterPattern:o}=t.settings,{text:s,selection:r}=t.input;return r.end<t.input.suggestionTextStart||r.start!==r.end?!1:r.end>=s.length?!0:e?n&&new RegExp(n).test(s.substring(r.end))||o&&new RegExp(o).test(s.substring(0,r.end))?!0:n===!1&&o===!1:!1}var su=require("@reduxjs/toolkit"),Yf={showTabHint:!1,inputHasFocus:!1,overlayCollapsed:!1,openOverlayWhenTyping:!1,overlayCollapsedUserOverwrite:!1},xr=({ui:t})=>t.overlayCollapsed,ru=(0,su.createSlice)({name:"ui",initialState:Yf,reducers:{setShowTabHint(t,e){t.showTabHint=e.payload},setInputFocus(t,e){t.overlayCollapsedUserOverwrite!==!0&&(e.payload===!0&&(t.overlayCollapsed=!1),t.inputHasFocus=e.payload)},setOverlayCollapsed(t,e){e.payload.collapse===!1&&(t.openOverlayWhenTyping=!1),!(e.payload.skipWhenInputFocus&&t.inputHasFocus)&&(t.overlayCollapsed=e.payload.collapse)},setOpenOverlayWhenTyping(t,e){t.openOverlayWhenTyping=e.payload},setOverlayCollapsedUserOverwrite(t,e){t.overlayCollapsedUserOverwrite=e.payload,t.overlayCollapsed=e.payload}}}),{setShowTabHint:Bo,setInputFocus:br,setOverlayCollapsed:Dt,setOpenOverlayWhenTyping:iu,setOverlayCollapsedUserOverwrite:au}=ru.actions,lu=ru.reducer;var du={styleRow:"dd-prYfH",styleSuggestion:"dd-JTmXy"};var Uo=require("react/jsx-runtime"),eh=({match:t,selected:e,styles:n})=>(0,Uo.jsx)(M,{as:"button",selected:e,className:n.styleRow,"data-testid":"style-suggestion-item",title:t.suggestion,children:(0,Uo.jsx)("span",{className:n.styleSuggestion,children:t.suggestion})}),th=({matches:t,selectedIndex:e})=>{let n=C("StyleSuggestionList",du);return(0,Uo.jsx)(oe,{children:t.map((o,s)=>(0,Uo.jsx)(eh,{match:o,selected:e===s,styles:n},`${o.keyword}-${s}`))})},Cr=th;var fu=require("react");var sa=require("interweave"),_t=require("react"),Wo=require("react-redux");var cu=require("react");function uu(t,e,n){(0,cu.useEffect)(()=>{let o=t.current;return o?(o.addEventListener(e,n),()=>{o.removeEventListener(e,n)}):()=>{}},[t,e,n])}var pu={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 Ko=require("react/jsx-runtime"),gu=({title:t})=>(0,Ko.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"18px",height:"18px",viewBox:"0 0 24 24","aria-labelledby":"closeTitle",children:[(0,Ko.jsx)("title",{id:"closeTitle",children:t}),(0,Ko.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 oa={};Z(oa,{enUS:()=>nh,nlNL:()=>oh});var nh={assistant:[{type:0,value:"Assistant"}],close:[{type:0,value:"Close"}]},oh={assistant:[{type:0,value:"Assistent"}],close:[{type:0,value:"Sluiten"}]};var Ce=require("react/jsx-runtime"),rh=["search","personal-collection-search","search-autocomplete"];function ih(t,e,n,o={}){var r;let s="";return rh.includes(e)?s=xc($i(t,n,{stripAgentPart:!0}),(r=o.searchKeywords)!=null?r:[n]):s=$i(t,n,o),o.placeholders===!0&&(s=bc(s)),s}var ah=()=>{},lh=({selected:t,suggestion:e})=>{let n=P(oa),o=E("inlineSuggestions"),s=(0,Wo.useSelector)(Xt),[r,i]=(0,_t.useState)(!1),a=E("enableSuggestionFeedback"),d=(0,Wo.useSelector)(y=>y.input.text),l=(0,Wo.useDispatch)(),c=C("TextSuggestion",pu),p=(0,_t.useRef)(null),u=e.source==="assistant",g=a&&!u;(0,_t.useEffect)(()=>{let y=setTimeout(()=>{l(El({text:e.text,suggestion:e}))},500);return()=>{clearTimeout(y)}},[e]),uu(p,"click",()=>{l(Se({suggestion:e,text:e.text,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"}))});let m=()=>{l(Qt({source:e.source,text:e.text,assistantCode:e.assistantCode}))},f=(0,_t.useMemo)(()=>ih(e.text,e.source,s,{stripAgentPart:o,placeholders:!0,searchKeywords:e.searchKeywords}),[o,e.text,e.source,s,e.searchKeywords]);return e.source==="gpt"&&!o?null:(0,Ce.jsxs)("div",{className:c.root,onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),children:[(0,Ce.jsx)(M,{ref:p,as:"button","data-testid":"suggestions-overlay-item",selected:t,onClick:ah,children:e.source==="assistant"?(0,Ce.jsxs)("div",{className:c.assistantContainer,children:[(0,Ce.jsx)(sa.Interweave,{containerTagName:"div",tagName:"span",className:c.formattedTextTruncated,content:f}),(0,Ce.jsx)("span",{className:c.assistantBadge,children:n("assistant")})]}):(0,Ce.jsx)(sa.Interweave,{containerTagName:"div",tagName:"span",className:c.formattedText,content:f})}),g&&r&&(0,Ce.jsx)("div",{className:c.actions,children:(0,Ce.jsx)(fr,{source:"overlay",context:d,suggestion:e})}),u&&r&&(0,Ce.jsx)("div",{className:c.closeIconContainer,children:(0,Ce.jsx)("button",{type:"button",className:c.closeIcon,onClick:m,title:n("close"),children:(0,Ce.jsx)(gu,{title:n("close")})})})]})},mu=lh;var hu=require("react/jsx-runtime"),dh=({suggestions:t,selectedIndex:e,reverse:n})=>(0,fu.useMemo)(()=>{let s=t.map((r,i)=>(0,hu.jsx)(mu,{index:i,selected:i===e,suggestion:r},`${r.text}-${r.source}`));return n?s.reverse():s},[t,e,n]),Tr=dh;var yu={root:"dd-PfvRI",paper:"dd-HYlyY"};var Er=require("@reduxjs/toolkit");var wr={list:{keywordMatches:[]},fetchState:"idle"},kr=t=>t.styleSuggestions.list,gn=(0,Er.createAsyncThunk)("styleSuggestions/getAll",(n,o)=>S(null,[n,o],function*({text:t},e){var d;let{deepdeskAPI:s}=e.extra,r=e.getState(),{showStyleSuggestions:i}=r.settings,a=(d=r.conversation.current)==null?void 0:d.profileCode;if(!i)return wr.list;if(!a)throw new Error("No current conversation to fetch pinned messages");return s.getStyleSuggestions({profileCode:a,message:t})})),vu=(0,Er.createSlice)({name:"styleSuggestions",initialState:wr,reducers:{commitStyleSuggestion(t,e){let{keyword:n,suggestion:o}=e.payload;t.list.keywordMatches=t.list.keywordMatches.filter(s=>s.keyword.toLowerCase()!==n.toLowerCase()||s.suggestion!==o)}},extraReducers:t=>{t.addCase(gn.pending,e=>{e.fetchState="loading"}).addCase(gn.rejected,e=>{e.fetchState="error"}).addCase(gn.fulfilled,(e,n)=>{e.fetchState="done",kt(e.list,n.payload)||(e.list=n.payload)}).addCase(Zt,e=>{e.list=wr.list}).addCase(Y,()=>wr)}}),{commitStyleSuggestion:Su}=vu.actions,xu=vu.reducer;var Rr=t=>{let e=new Set;return t.filter(({keyword:n,suggestion:o})=>{let s=JSON.stringify([n.toLowerCase(),o]);return e.has(s)?!1:(e.add(s),!0)})};var mn=require("react/jsx-runtime"),ch=()=>{var y;let t=(0,Pr.useRef)(null),e=C("InlineSuggestionsOverlay",yu),n=(0,Ze.useSelector)(Qe),o=(0,Ze.useDispatch)(),s=(0,Ze.useSelector)(se),r=(0,Ze.useSelector)(kn),i=(0,Ze.useSelector)(xr),a=E("showTextSuggestions"),d=(0,Ze.useSelector)(Jt),l=(0,Ze.useSelector)(ro),c=E("showStyleSuggestions"),p=E("showStyleSuggestionList"),u=(0,Ze.useSelector)(kr),g=c&&p?Rr((y=u.keywordMatches)!=null?y:[]):[],m=g.length>0,f=a&&d.length>0;return At(()=>{setTimeout(()=>{o(Dt({collapse:!0,skipWhenInputFocus:!0}))})}),(0,Pr.useEffect)(()=>{let v=t.current;if(!v||!v.parentElement)return;v.parentElement.style.left="0px";let x=v.getBoundingClientRect();v.parentElement.style.left=`${Math.min(window.innerWidth-4-x.right,0)}px`}),i||s!==!0||r===!1||!n&&!m||!f&&!m?null:(0,mn.jsx)("div",{className:e.root,"data-variant":"inline",children:(0,mn.jsxs)("div",{ref:t,className:e.paper,children:[m&&(0,mn.jsx)(Cr,{matches:g,selectedIndex:-1}),f&&(0,mn.jsx)(oe,{children:(0,mn.jsx)(Tr,{suggestions:d,selectedIndex:l})})]})})},bu=ch;var Ft=D(require("react"));var Cu={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 Tu=require("react-redux");var ra={};Z(ra,{enUS:()=>uh,nlNL:()=>ph});var uh={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."}]},ph={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 ee=require("react/jsx-runtime"),wu=({onClose:t,onSave:e,id:n,error:o})=>{let[s,r]=(0,Ft.useState)(""),[i,a]=(0,Ft.useState)(!1),[d,l]=(0,Ft.useState)(!1),c=C("Nickname",Cu),p=Ft.default.useRef(null),u=(0,Tu.useSelector)(v=>v.info.showNicknameDialog),g=P(ra),m=E("adminUrl");(0,Ft.useEffect)(()=>{o&&a(!0)},[o]);let f=()=>{if(!p.current)return;s.trim()?p.current.setCustomValidity(""):p.current.setCustomValidity(g("nicknameDialogError")),p.current.reportValidity()},y=v=>{v.preventDefault();let x=s.trim(),T=v.currentTarget.querySelector("#nickname-input");if(!x){T.setCustomValidity(g("nicknameDialogError")),T.reportValidity();return}T.setCustomValidity(""),e(x)};return(0,ee.jsxs)(Hn,{isOpen:u,"datatest-id":n,onClose:t||(()=>{}),onBack:t||(()=>{}),children:[(0,ee.jsx)("div",{className:c.titleWrapper,children:(0,ee.jsx)("h1",{className:c.title,children:g("title")})}),(0,ee.jsxs)("form",{className:c.dialogContent,onSubmit:y,children:[(0,ee.jsx)("p",{children:g("nicknameDialogTitle")}),i&&o&&(0,ee.jsx)("div",{className:c.errorMessage,children:m?(()=>{let v=g("nicknameDialogSaveError",{account:m}),x=`${m}.deepdesk.com/admin/user-settings`,T=v.indexOf(x);if(T!==-1){let w=v.substring(0,T),L=v.substring(T+x.length);return(0,ee.jsxs)(ee.Fragment,{children:[w,(0,ee.jsx)("a",{href:x,target:"_blank",rel:"noopener noreferrer",className:c.errorLink,children:x}),L]})}return v})():g("nicknameDialogSaveErrorWithoutLink")}),(0,ee.jsx)("input",{required:!0,minLength:1,maxLength:20,"data-testid":"nickname-input",id:"nickname-input",className:c.nicknameInput,type:"text",placeholder:g("nicknameDialogInputPlaceholder"),value:s,onChange:v=>{l(new RegExp("\\p{Extended_Pictographic}","u").test(v.target.value)),r(v.target.value)},onBlur:f,ref:p}),d&&(0,ee.jsx)("div",{className:c.errorMessage,role:"alert",children:g("nicknameDialogEmojiError")}),(0,ee.jsxs)("div",{className:c.buttonsWrapper,children:[o?(0,ee.jsx)("div",{className:c.closeButtonWrapper,children:(0,ee.jsx)("button",{type:"button",className:c.closeButton,onClick:()=>t==null?void 0:t(),children:g("close")})}):null,(0,ee.jsx)("div",{className:c.buttonContinueWrapper,children:(0,ee.jsx)("button",{type:"submit",className:c.continueButton,disabled:!s.trim()||new RegExp("\\p{Extended_Pictographic}","u").test(s),children:g("nicknameDialogContinueButton")})})]})]})]})};var Eu=require("react-redux");var zo=require("react/jsx-runtime"),gh=({children:t})=>{let n=E("locale").replace("-","");return(0,zo.jsx)(Ai.Provider,{value:n,children:t})},mh=({store:t,customStyles:e={},children:n})=>(0,zo.jsx)(Eu.Provider,{store:t,children:(0,zo.jsx)(gh,{children:(0,zo.jsx)(no.Provider,{value:e,children:n})})}),mt=mh;var Ar=D(require("classnames")),jn=require("react"),Ie=require("react-redux");var ku=require("react");function Ru(t,e){let[n,o]=(0,ku.useState)(()=>{if(typeof window=="undefined")return e;try{let r=window.localStorage.getItem(t);return r?JSON.parse(r):e}catch(r){return k.error(r),e}});return[n,r=>{try{let i=r instanceof Function?r(n):r;o(i),typeof window!="undefined"&&window.localStorage.setItem(t,JSON.stringify(i))}catch(i){k.error(i)}}]}var Pu=()=>/Mac/i.test(navigator.platform);var Au=D(require("classnames")),ft=require("react");var ia={};Z(ia,{enUS:()=>fh,nlNL:()=>hh});var fh={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"}]}]},hh={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 Iu={root:"dd-uTPjX",anchor:"dd-C8lsZ",anchorButton:"dd-IoSx9"};var Ht=require("react/jsx-runtime"),aa=(t,e,n)=>o=>(0,Ht.jsx)("button",{className:t.anchorButton,type:"button",value:e,onClick:n,children:o},e),yh=({className:t,loginUrl:e,isEmbedded:n,onSnooze:o,onLogIn:s})=>{let r=P(ia),i=fe(),a=C("Login",Iu),d=E("productName"),l=E("signInViaPopup"),c=n&&!l,p=(0,ft.useCallback)(x=>{x.preventDefault(),o&&o(Number.parseInt(x.target.value,10))},[]),u=(0,ft.useCallback)(x=>{x.preventDefault(),i.send(Mn,!0)},[e]),g=(0,ft.useMemo)(()=>x=>(0,Ht.jsx)("a",{onClick:w=>{w.preventDefault(),s()},href:e,className:a.anchor,target:"_blank",rel:"noreferrer",children:x},"login"),[e]),m=(0,ft.useCallback)(x=>(0,Ht.jsx)("button",{type:"button",className:a.anchorButton,onClick:u,children:x},"prompt"),[u]),{min:f,hour:y,day:v}=(0,ft.useMemo)(()=>({min:aa(a,600,p),hour:aa(a,3600,p),day:aa(a,3600*12,p)}),[]);return(0,Ht.jsxs)("div",{className:(0,Au.default)(t,a.root),children:[r("loginPlease",{login:c?m:g,productName:d}),o&&(0,Ht.jsxs)(ft.Fragment,{children:[(0,Ht.jsx)("br",{}),r("snooze",{min:f,hour:y,day:v})]})]})},Ir=yh;var Mu=require("react-redux");var Lu={root:"dd-DoQhb",text:"dd-Jwnev"};var Vo=require("react/jsx-runtime"),vh=({title:t})=>{let e=C("SearchTrigger",Lu),n=(0,Mu.useDispatch)(),o=q();return(0,Vo.jsxs)("button",{type:"button",className:e.root,onClick:()=>{n(_e(!0)),o("open search",{via:"autocomplete-overlay"})},children:[(0,Vo.jsx)(Wn,{}),(0,Vo.jsx)("span",{className:e.text,children:t})]})},Nu=vh;var la={};Z(la,{enUS:()=>Sh,nlNL:()=>xh});var Sh={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"}]},xh={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 Ou={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 K=require("react/jsx-runtime"),bh=({onLogIn:t})=>{var $;let e=C("SuggestionsOverlay",Ou),n=P(la),o=(0,Ie.useSelector)(Qe),s=(0,Ie.useSelector)(wl),r=(0,Ie.useDispatch)(),i=(0,jn.useRef)(null),a=E("searchTriggerKey"),d=E("productName"),l=(0,Ie.useSelector)(xr),c=(0,Ie.useSelector)(se),p=(0,Ie.useSelector)(pl),u=(0,Ie.useSelector)(kn),[g,m]=(0,jn.useState)(null),f=E("showSearch"),y=E("showTextSuggestions"),v=E("adminUrl"),x=E("isEmbedded"),T=E("suggestionsPlacement"),[w,L]=Ru("dd-snooze-until-ms",0),R=l||w>Date.now(),I=(0,Ie.useSelector)(Jt),z=(0,Ie.useSelector)(ro),Me=E("showStyleSuggestions"),ot=E("showStyleSuggestionList"),F=(0,Ie.useSelector)(kr),j=Me&&ot?Rr(($=F.keywordMatches)!=null?$:[]):[],ze=j.length>0,ne=I.filter(st=>st.source!=="gpt").length,Wt=()=>{R&&L(0),r(au(!R))},N=st=>{let bn=Date.now()+st*1e3;L(bn),k.info(`Snooze until: ${new Date(bn)}`),r(Dt({collapse:!0}))};return(0,jn.useEffect)(()=>{ne===0&&m(null)},[I,ne]),At(()=>{r(Dt({collapse:!0,skipWhenInputFocus:!0}))}),c===null||u===!1?null:c===!1?(0,K.jsxs)("div",{ref:i,className:(0,Ar.default)(e.root,{[e.isCollapsed]:R}),children:[!R&&(0,K.jsxs)("div",{className:e.triggers,children:[(0,K.jsx)("div",{style:{flex:1}}),(0,K.jsx)("div",{className:e.triggersRight,children:(0,K.jsx)(jt,{className:e.toggleButton,title:n("collapse"),onClick:Wt,isCollapsed:!1})})]}),(0,K.jsx)("div",{className:e.toggleButtonWrapper,children:(0,K.jsx)(jt,{className:e.toggleButton,title:n("open",{productName:d}),onClick:Wt,isCollapsed:!0})}),(0,K.jsxs)("div",{className:e.collapsible,children:[p&&(0,K.jsxs)("div",{className:e.loginError,children:[(0,K.jsx)("span",{className:e.loginErrorMessage,children:p}),(0,K.jsx)("button",{type:"button",className:e.loginErrorDismiss,onClick:()=>r(fs()),"aria-label":n("dismissError"),children:n("dismiss")})]}),(0,K.jsx)(Ir,{loginUrl:v,isEmbedded:x,onLogIn:t,onSnooze:N})]})]}):!s||!o&&!ze?null:(0,K.jsxs)("div",{ref:i,className:(0,Ar.default)(e.root,{[e.isCollapsed]:R}),children:[!R&&(0,K.jsxs)("div",{className:e.triggers,children:[(0,K.jsx)("div",{style:{flex:1},children:f&&(0,K.jsx)("div",{style:{display:"inline-block"},onFocus:()=>{},onMouseOver:()=>m(n(Pu()?"searchHintMac":"searchHintWindows",{searchTriggerKey:a.toUpperCase()})),onMouseLeave:()=>m(null),children:(0,K.jsx)(Nu,{title:n("search")})})}),(0,K.jsxs)("div",{className:e.triggersRight,onFocus:()=>{},children:[(0,K.jsx)("div",{className:(0,Ar.default)(!g&&e.hintsHidden,e.hints),children:g}),(0,K.jsx)(jt,{className:e.toggleButton,title:n("collapse"),onClick:Wt,isCollapsed:!1})]})]}),(0,K.jsx)("div",{className:e.toggleButtonWrapper,children:(0,K.jsx)(jt,{className:e.toggleButton,title:n("open",{productName:d}),onClick:Wt,isCollapsed:!0})}),(ze||ne>0&&y)&&(0,K.jsxs)("div",{className:e.collapsible,onFocus:()=>{},children:[ze&&(0,K.jsx)(Cr,{matches:j,selectedIndex:-1}),ne>0&&y&&(0,K.jsx)(oe,{children:(0,K.jsx)(Tr,{suggestions:I,selectedIndex:z,reverse:T==="above"})})]})]})},Du=bh;var Vr=D(require("classnames")),Yu=require("interweave"),vt=require("react"),ep=require("react-redux");var $n=require("react");function Lr(t){return t.contentEditable==="true"}function Ch(t){let e=0,n=0,o=window.getSelection();if(o.rangeCount!==0){let s=o.getRangeAt(0),r=s.cloneRange();r.selectNodeContents(t),r.setEnd(s.endContainer,s.endOffset),n=r.toString().length,r.selectNodeContents(t),r.setEnd(s.startContainer,s.startOffset),e=r.toString().length}return{selectionStart:e,selectionEnd:n}}function _u(t){let{selectionStart:e,selectionEnd:n}=Lr(t)?Ch(t):t;return[e,n]}function Fu(t){let[,e]=(0,$n.useState)(),n=(0,$n.useRef)(null);return n.current=_u(t),(0,$n.useEffect)(()=>{let o=()=>{var a;let[s,r]=(a=n.current)!=null?a:[],i=_u(t);(!i||s!==i[0]||r!==i[1])&&(n.current=i,e({}))};return t.addEventListener("keyup",o),t.addEventListener("click",o),t.addEventListener("focus",o),document.addEventListener("selectionchange",o),()=>{t.removeEventListener("keyup",o),t.removeEventListener("click",o),t.removeEventListener("focus",o),document.removeEventListener("selectionchange",o)}},[t]),n.current}function Hu(t,e){if(!e)return;let n=t,{value:o}=n,[s,r]=e,i=o.match(ps);if(!i||i.length===0)return;let a=0;i.find(d=>{let l=o.indexOf(d,a);return s>l&&r<l+d.length?(n.selectionStart=l,n.selectionEnd=l+d.length,!0):(a=l+d.length,!1)})}var Bu=require("react"),Th=["div","span","mark","strong","b","i","u","em"];function da(t,e,n=0){var r;let o=t[t.length-1],s=typeof o=="object"&&o!==null?(r=o.props)==null?void 0:r.tagName:void 0;if(s==="br")return t.pop(),[...t,...e,o];if(Th.includes(s)){let i=Array.isArray(o.props.children)?o.props.children:[o.props.children];return[...t.slice(0,t.length-1),(0,Bu.cloneElement)(o,{children:da(i,e,n+1)})]}return[...t,...e]}function fn(t){return t.tagName.toLowerCase()==="textarea"}var Uu={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 Vu=D(require("classnames")),ju=require("interweave"),Hr=require("react");var qn=require("react");function Ku(t,e){let n;return[(...o)=>{window.cancelAnimationFrame(n);let s=e?e(...o):o;n=window.requestAnimationFrame(()=>{t(...s)})},()=>window.cancelAnimationFrame(n)]}function Mr(t){let e=(0,qn.useRef)(null),[n,o]=(0,qn.useState)(!1);return(0,qn.useEffect)(()=>{var c;let s=!1,r=Number.parseFloat((c=window.getComputedStyle(document.body).zoom)!=null?c:"1"),[i,a]=Ku((p,u)=>{let g=e.current;if(!g)return;let m=p/r,f=u/r,y=g.getBoundingClientRect(),v=m>y.x&&m<y.x+y.width&&f>y.y&&f<y.y+y.height;v&&!s?(s=!0,o(!0)):!v&&s&&(s=!1,o(!1))},({clientX:p,clientY:u})=>[p,u]),[d,l]=Ku(()=>{s=!1,o(!1)});return t.addEventListener("mousemove",i),t.addEventListener("mouseleave",d),()=>{a(),l(),t.removeEventListener("mousemove",i),t.removeEventListener("mouseleave",d)}},[e]),[e,n]}function Nr(t){return t.replace(/[.*+^${}()|[\]\\]/g,"\\$&")}function Or(t){return e=>{t.forEach(n=>{typeof n=="function"?n(e):n!=null&&(n.current=e)})}}function Wu(t){return t!=null}var zu=D(require("classnames")),Dr=require("react");var ht={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 ca=require("react/jsx-runtime"),_r=(0,Dr.forwardRef)((s,o)=>{var r=s,{className:t,children:e}=r,n=O(r,["className","children"]);let i=(0,Dr.useRef)(null),a=C("TabCompletion",ht);return(0,ca.jsx)("div",b(h({ref:Or([i,o]),className:(0,zu.default)(t,a.popoverContentContainer)},n),{children:(0,ca.jsx)("div",{className:a.popoverContent,children:e})}))});var Bt=require("react/jsx-runtime"),wh=t=>e=>{let n=Bi(e);return"top"in n&&(n.width=t.width-(e.left-t.left)-10),n},Eh=({inputElement:t,boundaryRef:e,inputStyle:n,children:o,suggestion:s})=>{let r=C("TabCompletion",ht),i=Js(),a=(0,Hr.useMemo)(()=>wh(t.getBoundingClientRect()),[t]),[d,l]=Mr(t);return(0,Hr.useEffect)(()=>{l?i.open():i.close()},[l]),(0,Bt.jsxs)("span",{children:[(0,Bt.jsx)("mark",{ref:Or([d,i.triggerRef]),className:(0,Vu.default)(r.matchKeyword,{[r.hover]:l}),"aria-haspopup":"dialog","aria-expanded":i.opened?"true":"false",children:o}),i.opened&&(0,Bt.jsx)(_n,{className:r.popover,triggerRef:i.triggerRef,boundaryRef:e,position:"below",align:"start",toStyle:a,children:(0,Bt.jsx)(_r,{style:n,children:(0,Bt.jsx)("div",{className:r.hintText,children:s})})})]})},Fr=class extends ju.Matcher{constructor(){super(...arguments);this.keywordMatches=[];this.preparedKeywordMatches=[];this.usedKeywordMatches=new Set}onBeforeParse(n,o){return o.keywordMatches&&o.keywordMatches!==this.keywordMatches&&(this.preparedKeywordMatches=o.keywordMatches.map(s=>b(h({},s),{keywordRegex:new RegExp(`\\b${Nr(s.keyword)}\\b`,"i")})),this.keywordMatches=o.keywordMatches),this.usedKeywordMatches.clear(),n}match(n){let o=this.preparedKeywordMatches.map(r=>{if(this.usedKeywordMatches.has(r))return null;let i=n.match(r.keywordRegex);if(!i)return null;let a=n.charAt(i.index-1),d=n.charAt(i.index+r.keyword.length);return a==="{"&&d==="}"?null:{index:i.index,length:i[0].length,match:i[0],matchString:i[0],suggestion:r.suggestion,preparedKeywordMatch:r,valid:!0}}).filter(Wu);if(o.length===0)return null;let s=o.reduce((r,i)=>i.index<r.index?i:r);return this.usedKeywordMatches.add(s.preparedKeywordMatch),s}replaceWith(n,o){return(0,Bt.jsx)(Eh,{inputElement:o.inputElement,suggestion:o.suggestion,inputStyle:o.inputStyle,boundaryRef:o.boundaryRef,children:n},`keyword_${o.matchString}_${o.key}`)}asTag(){return"mark"}};var $u=require("interweave"),qu=D(require("classnames"));var ua=require("react/jsx-runtime"),kh=({inputElement:t,children:e})=>{let n=C("TabCompletion",ht),[o,s]=Mr(t);return(0,ua.jsx)("mark",{ref:o,className:(0,qu.default)(n.matchPlaceholder,{[n.hover]:s}),children:e})},Br=class extends $u.Matcher{match(e){let n=e.match(/(((\$!\{)|(\{))[a-zA-Z0-9_.]+\}(?!\}))/);return n?{index:n.index,length:n[0].length,match:n[0],matchString:n[0],valid:!0}:null}replaceWith(e,n){return(0,ua.jsx)(kh,{inputElement:n.inputElement,children:e},`placeholder_${n.matchString}_${n.key}`)}asTag(){return"mark"}};var Kr=D(require("classnames")),Zu=require("interweave"),pe=require("react"),zr=require("react-redux");var pa=require("react/jsx-runtime"),Gu=()=>(0,pa.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,pa.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 Ye=require("react"),jo=require("react-redux"),Ju=D(require("lodash.debounce"));var Xu={root:"dd-ky-Bv",content:"dd-kV5e1"};function Ur(t,e,n){var s;let o=((s=t.imageSizes)==null?void 0:s[e])||t.image||n;if(!o)return null;try{return new URL(o).toString()}catch(r){return null}}function ga(t){return t.replace("https://www.","").replace("https://","")}var Ae=require("react/jsx-runtime"),Rh=3,Ph=t=>({image:t.image||"",text:t.text,id:t.id,title:t.title}),Ih=({onSelectLink:t,onDismiss:e,placeholder:n,visitUrlText:o,linkCount:s=Rh})=>{let r=C("LinkSearch",Xu),[i,a]=(0,Ye.useState)(""),d=(0,jo.useDispatch)(),l=(0,jo.useSelector)(Kc("url")),c=(0,jo.useSelector)(Gl("URL")),p=(0,Ye.useMemo)(()=>c.map(Ph),[c]),[u,g]=(0,Ye.useState)(p.length-1),m=E("fallbackImage"),f=T=>{let w=T.target;a(w.value)},y=(T,w)=>{T.stopPropagation(),T.preventDefault(),window.open(w,"_blank")},v=T=>{var R;let w=u-1<0?p.length-1:u-1,L=u+1===p.length?0:u+1;T.code==="Escape"&&(a(""),e()),T.code==="ArrowUp"&&g(w),T.code==="ArrowDown"&&g(L),T.code==="Enter"&&t(((R=p[u])==null?void 0:R.text)||i)},x=(0,Ye.useCallback)((0,Ju.default)(T=>{d(en({query:T,type:"URL",tags:["link-search"]}))},300),[]);return(0,Ye.useEffect)(()=>{i&&x(i)},[i]),(0,Ye.useEffect)(()=>()=>{d(Es())},[]),(0,Ae.jsxs)("div",{className:r.root,children:[(0,Ae.jsx)(oe,{withDivider:!0,children:(i?p:l).slice(0,s).map((T,w)=>(0,Ae.jsx)(M,{selected:u===w,onClick:()=>t(T.text),"data-testid":"linksearch-suggestion",children:(0,Ae.jsxs)(H,{children:[(0,Ae.jsx)(H.Image,{src:Ur(T,"small",m||void 0),title:T.title||T.text}),(0,Ae.jsxs)(H.Content,{className:r.content,cropText:!0,children:[(0,Ae.jsx)(H.Title,{children:T.title||ga(T.text)}),T.title&&ga(T.text)]}),(0,Ae.jsx)(M.Actions,{children:(0,Ae.jsx)(M.ActionButton,{label:o,onClick:L=>y(L,T.text)})})]})},T.text))}),(0,Ae.jsx)(wo,{value:i,onChange:f,autoFocus:!0,placeholder:n,onKeyUp:v})]})},Qu=Ih;var ma={};Z(ma,{enUS:()=>Ah,nlNL:()=>Lh});var Ah={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"}]},Lh={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 re=require("react/jsx-runtime"),Mh=(0,pe.forwardRef)((t,e)=>{let n=C("TabCompletion",ht);return(0,re.jsx)("mark",{ref:e,className:(0,Kr.default)(n.matchSelection)},"selection-start")}),Nh=({startRef:t,boundaryRef:e,inputStyle:n,inputElement:o,children:s})=>{let r=P(ma),i=C("TabCompletion",ht),a=E("addToPersonalCollection"),d=(0,zr.useSelector)(On("/admin/personal-collection/new")),l=(0,pe.useRef)(null),c=(0,pe.useRef)(null),[p,u]=(0,pe.useState)(null),g=(0,zr.useDispatch)(),m=Js(document.activeElement===o),[f]=(0,pe.useState)(()=>document.createRange());m.triggerRef.current=f,(0,pe.useEffect)(()=>()=>f.detach(),[]),(0,pe.useEffect)(()=>{let v=t.current,x=l.current;!v||!x||(f.setStart(v,0),f.setEnd(x,0))},[t.current,l.current]),At(()=>{m.close()});let y=(0,pe.useCallback)(v=>{let x=f.toString(),T=/^http(s?):\/\//.test(v)?v:`https://${v}`,w=`[${x}](${T})`;g(Se({text:w,suggestion:{text:w,source:"search-url",type:"url"},eventMetrics:{inputType:"mouse"},replace:"selection"}))},[]);return(0,re.jsxs)("span",{children:[(0,re.jsx)("mark",{ref:l,className:(0,Kr.default)(i.matchSelection),"aria-haspopup":"dialog","aria-expanded":m.opened?"true":"false",children:s}),m.opened&&(0,re.jsx)(_n,{className:i.popoverRoot,triggerRef:m.triggerRef,boundaryRef:e,position:"above",align:"start",children:(0,re.jsxs)(_r,{style:n,ref:c,children:[(0,re.jsxs)("div",{className:(0,Kr.default)(i.selectionOptions,{[i.selectionOptionsIsHidden]:p!==null}),children:[(0,re.jsxs)("button",{type:"button",tabIndex:p===null?-1:void 0,className:i.selectionOptionsButton,onClick:()=>u("insertLink"),children:[(0,re.jsx)(Gu,{}),(0,re.jsx)("span",{children:"\xA0"}),(0,re.jsx)("span",{children:r("insertLink")})]}),a&&d&&(0,re.jsx)("button",{type:"button",tabIndex:p===null?-1:void 0,className:i.selectionOptionsButton,onClick:()=>{let v=f.toString(),x=`${d}?text=${encodeURIComponent(v)}`;window.open(x,"_blank")},children:(0,re.jsx)("span",{children:r("addToPersonalCollection")})})]}),p==="insertLink"&&(0,re.jsx)(Qu,{placeholder:r("linkInputPlaceholder"),visitUrlText:r("visitUrl"),onSelectLink:y,onDismiss:()=>{u(null),m.close()}})]})})]},"selection-end")},Wr=class extends Zu.Matcher{constructor(){super(...arguments);this.charCount=0;this.foundIndex=0;this.startRef=null}onBeforeParse(n,o){return this.props=o,this.charCount=0,this.startRef=(0,pe.createRef)(),this.foundIndex=0,n}match(n){if(!this.props||this.props.selection===null||this.foundIndex===2)return null;let[o,s]=this.props.selection;if(o===s)return null;let r=this.foundIndex===0?o:s,i=r>=this.charCount&&r<=this.charCount+n.length?{index:r-this.charCount,length:0,match:"",valid:!0}:null;i&&this.foundIndex++;let a=this.foundIndex===1;return i&&a?this.charCount+=r-this.charCount:this.charCount+=n.length,i?h({isStart:a},i):null}replaceWith(n,o){return o.isStart?(0,re.jsx)(Mh,{ref:this.startRef}):(0,re.jsx)(Nh,{inputElement:o.inputElement,startRef:this.startRef,boundaryRef:o.boundaryRef,inputStyle:o.inputStyle})}asTag(){return"mark"}};var tp=require("react-redux");var yt=require("react/jsx-runtime"),Oh=({enabled:t,content:e,tabText:n,showTabHint:o,showTabCompletion:s,showStyleSuggestions:r,keywordMatches:i,inputElement:a,source:d})=>{let l=C("TabCompletion",Uu),c=E("insertLink"),p=E("addToPersonalCollection"),u=E("showMidSentenceSuggestions"),g=E("inlineSuggestions"),m=Fu(a),f=(0,vt.useRef)(null),y=(0,tp.useSelector)(se);(0,vt.useEffect)(()=>{fn(a)&&m&&Hu(a,m)},[m]);let v=(0,vt.useCallback)(w=>{if(!s||!n)return w;let L=[(0,yt.jsx)("span",{className:l.resetIndent,children:"\u200B"},"u200B"),(0,yt.jsx)("span",{"data-testid":"tab-completion",className:(0,Vr.default)(l.tabText,l.resetIndent),"data-source":d,children:n},"tabText")];return o&&L.push((0,yt.jsx)("span",{className:(0,Vr.default)(l.hint,l.resetIndent),children:(0,yt.jsx)(ds,{keyCode:"tab"},"tabHint")},"tabHint")),da(w,L)},[s,n,o]),x=(0,vt.useMemo)(()=>{let w=[];return(c||p)&&w.push(new Wr("selection")),w.push(new Br("placeholders")),r&&w.push(new Fr("keywords")),w},[g,c,p,r]),T=(0,vt.useMemo)(()=>{let w=window.getComputedStyle(a);return{"--dd-color":w.color,"--dd-font-size":w.fontSize,"--dd-font-family":w.fontFamily,"--dd-font-variant":w.fontVariant}},[]);return!t||!y?null:(0,yt.jsxs)("div",{ref:w=>{w!=null&&w.parentElement&&(f.current=w==null?void 0:w.parentElement)},className:l.root,style:T,children:[(0,yt.jsx)(Yu.Interweave,{tagName:"span",containerTagName:"div",className:(0,Vr.default)(l.container,l.agentText),disableLineBreaks:fn(a),content:e||"\u200B",onAfterParse:v,matchers:x,selection:m,keywordMatches:i,inputElement:a,inputStyle:T,boundaryRef:f,inlineSuggestionsOnlyAtEnd:!u}),(0,yt.jsx)("br",{})]},"tab-completion")},Dh=t=>{var v,x,T;let{input:e,ui:n,settings:o,styleSuggestions:s,conversation:r}=t,i=Rn({input:e}),a=(i==null?void 0:i.text)||"",d=(i==null?void 0:i.source)||"",l=(v=e.html)!=null?v:Un(e.text),c=e.text.slice(e.suggestionTextStart,e.selection.end),p=a.indexOf(c)===0?a.slice(c.length):"",{showTabHint:u}=n,{isSupported:g}=r,{showTabCompletion:m,visible:f,showStyleSuggestions:y}=o;return{showTabHint:u,showStyleSuggestions:y,showTabCompletion:m&&Qe(t),content:l,tabText:p,source:d,keywordMatches:(T=(x=s.list)==null?void 0:x.keywordMatches)!=null?T:[],enabled:f&&g!==!1}},np=(0,ep.connect)(Dh)(Oh);var Ut=require("react"),Q=require("react-redux");var $o=require("@reduxjs/toolkit");var _h={token:null,interval:null},fa=(0,$o.createAsyncThunk)("passwordlessToken/getTemporaryPasswordlessToken",(t,e)=>S(null,null,function*(){let{deepdeskAPI:n}=e.extra;return{token:yield n.requestPasswordlessToken()}})),ha=(0,$o.createAsyncThunk)("passwordlessToken/pollPasswordlessToken",(t={},e)=>{let{interval:n=1e3*60*10}=t,{dispatch:o}=e;return o(fa()),setInterval(()=>o(fa()),n)}),op=(0,$o.createSlice)({name:"passwordlessToken",initialState:_h,reducers:{stopPollPasswordlessToken(t){t.interval&&clearInterval(t.interval),t.interval=null}},extraReducers:t=>{t.addCase(fa.fulfilled,(e,n)=>{e.token=n.payload.token}),t.addCase(ha.fulfilled,(e,n)=>{e.interval=n.payload})}}),{stopPollPasswordlessToken:sp}=op.actions,rp=op.reducer;var ip=require("@reduxjs/toolkit");function Fh(t){return"buttonText"in t&&"eventName"in t}function ap(t){if(t)return Fh(t)?{label:t.buttonText,event:t.eventName,value:t.payload}:t}function Hh(t){return t==null?void 0:t.map(e=>ap(e))}function Bh(t){let e=0;for(let n=0;n<t.length;n++)e=(e<<5)-e+t.charCodeAt(n),e|=0;return e}var lp=(0,ip.createSelector)([pd,hs],(t,e)=>(e?t.filter(s=>!s.externalConversationId||s.externalConversationId===e):t).map(s=>{var a;let r=ap(s.callToAction),i=Hh(s.callToActions);return b(h(h(h(h({text:s.response,title:s.name},r?{callToAction:r}:{}),i!=null&&i.length?{callToActions:i}:{}),s.message!==void 0?{message:s.message}:{}),(a=s.sources)!=null&&a.length?{sources:s.sources}:{}),{editable:s.editable,isLoading:s.isLoading,evaluationId:s.evaluationId,rule:{id:Bh(s.code),label:s.code,name:s.name,description:s.name}})}));var jr=require("react"),va=D(require("classnames"));var ya=require("react/jsx-runtime"),Gn=()=>(0,ya.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",children:(0,ya.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 dp={root:"dd-WcEru",entity:"dd-LfP8y",entityText:"dd-L-v0f",iconWrapper:"dd-9Deh1",icon:"dd-tM7E2",iconClicked:"dd-EEdDL"};var et=require("react/jsx-runtime"),Uh=({entities:t})=>{let e=C("EntitiesWidgetList",dp),[n,o]=(0,jr.useState)(void 0),s=q(),r=()=>{o(void 0)},i=a=>{t&&(o(t.indexOf(a)),qe(a.text),s("entity copied",{entity:a,type:"copy"}))};return(0,jr.useEffect)(()=>{let a=setTimeout(r,500);return()=>{clearTimeout(a)}},[n]),!t||t.length===0?null:(0,et.jsx)("div",{className:e.root,"data-testid":"widget-entities-list",children:t.map((a,d)=>(0,et.jsxs)("button",{title:a.text,className:e.entity,type:"button",onClick:()=>i(a),children:[(0,et.jsx)("span",{className:e.entityText,children:a.text}),(0,et.jsxs)("span",{className:e.iconWrapper,children:[(0,et.jsx)("span",{className:(0,va.default)(e.icon),children:(0,et.jsx)(Gn,{})}),(0,et.jsx)("span",{className:(0,va.default)(e.icon,n===d&&e.iconClicked),children:(0,et.jsx)(Gn,{})})]})]},a.text))})},cp=Uh;var Sa=require("react/jsx-runtime"),up=()=>(0,Sa.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,Sa.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 vp=require("react"),$r=require("react-redux");var pp={root:"dd-ohnXe",trigger:"dd-7i-S3",button:"dd-t53Cg",nav:"dd-qZFnm",item:"dd-FZC0F"};var gp={root:"dd-nazq3",rotation:"dd-3EHTv"};var fp=require("react/jsx-runtime"),Kh=({size:t=12})=>{let e=C("LoadingSpinner",gp);return(0,fp.jsx)("span",{"data-testid":"loading-spinner",style:{width:`${t}px`,height:`${t}px`},className:e.root})},mp=Kh;var xa=require("react/jsx-runtime"),hp=()=>(0,xa.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 0 512 512",fill:"currentColor",children:(0,xa.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 qo=require("react/jsx-runtime"),yp=t=>(0,qo.jsxs)("svg",b(h({xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 448 512","aria-labelledby":"checkTitle"},t),{children:[(0,qo.jsx)("title",{id:"checkTitle",children:"Check"}),(0,qo.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 ba={};Z(ba,{enUS:()=>Wh,nlNL:()=>zh});var Wh={error:[{type:0,value:"Something went wrong"}]},zh={error:[{type:0,value:"Er ging iets fout"}]};var Te=require("react/jsx-runtime"),Vh=3e3,jh=({assistantOptions:t})=>{let e=C("OnDemandAssistants",pp),n=P(ba),o=(0,vp.useRef)(),s=(0,$r.useDispatch)(),r=Is(he),i=(0,$r.useSelector)(uc),a=q(),d=i.filter(u=>u.isPinned),l=i.filter(u=>!u.isPinned),c=()=>S(null,null,function*(){return t.attachments&&t.attachments.length>0?t.attachments:s(((u,g,m)=>S(null,null,function*(){let f;if(t.transcript==="in-memory-transcript"){let y=m.dynamicThunkObject.conversationQuery;if(y){let v=yield y();f=Array.isArray(v)?v:void 0}}else Array.isArray(t.transcript)&&(f=t.transcript);return Li({transcript:f})})))}),p=u=>S(null,null,function*(){clearTimeout(o.current);let g=yield c();a("trigger on demand assistant",{assistantCode:u}),yield r.call(h(b(h({},t),{assistantCode:u}),g.length>0?{attachments:g}:{})),o.current=setTimeout(()=>r.reset(),Vh)});return i.length===0?null:(0,Te.jsxs)("div",{className:e.root,children:[d.map(({assistant:u,assistantName:g,displayName:m})=>(0,Te.jsx)("button",{type:"button",className:e.button,disabled:r.state==="loading",onClick:()=>p(u),children:m||g},u)),l.length>0&&(0,Te.jsxs)(V,{placement:"top-end",children:[(0,Te.jsx)(V.Trigger,{className:e.trigger,disabled:r.state==="loading",children:(0,Te.jsx)(mr,{"data-testid":"trigger"})}),(0,Te.jsx)(V.Content,{className:e.nav,"data-testid":"popover",children:l.map(({assistant:u,assistantName:g,displayName:m})=>(0,Te.jsx)(V.Button,{className:e.item,disabled:r.state==="loading",onClick:()=>p(u),children:m||g},u))})]}),r.state==="loading"&&(0,Te.jsx)(mp,{}),r.state==="done"&&(0,Te.jsx)(yp,{"data-testid":"trigger-done"}),r.state==="error"&&(0,Te.jsx)(Dd,{trigger:(0,Te.jsx)(hp,{}),children:n("error")})]})},Sp=jh;var bp=require("react-redux");var hn=require("react");var Go={};Z(Go,{enUS:()=>$h,nlNL:()=>qh});var $h={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"}]},qh={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 Ca={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 ie=require("react/jsx-runtime"),Gh=500,Xh=100,Jh=({content:t,onChange:e,onCopy:n})=>{let o=(0,hn.useRef)(null),s=C("WidgetCue",Ca);return(0,hn.useEffect)(()=>{let r=o.current;if(!r)return;r.style.setProperty("height","0px");let i=Math.min(Math.max(r.scrollHeight,Xh),Gh);r.style.setProperty("height",`${i}px`)},[t]),(0,ie.jsx)("textarea",{ref:o,className:s.editableCue,onCopy:n,onChange:e,value:t})},Qh=({cue:t,onCallToAction:e,onRemove:n,onCopy:o,onUse:s,onSourceClick:r})=>{var y;let i=C("WidgetCue",Ca),a=P(Go),d=q(),l=E("hasKeyboardInput"),[c,p]=(0,hn.useState)(t.text),u=v=>{let x=v?b(h({},t),{callToAction:v}):t;e&&e(c,x),n(t)},g=(v,x)=>{o&&o(v,t),x&&It(x,i.fadeup)},m=v=>{s&&s(v,t)},f=v=>{v.preventDefault(),v.stopPropagation(),n(t)};return(0,hn.useEffect)(()=>{d("Assistant response displayed",{evaluationId:t.evaluationId,assistantCode:t.rule.label,assistantOutput:t.text})},[]),(0,ie.jsxs)(M,{"data-testid":"cue",children:[(0,ie.jsx)(H,{children:(0,ie.jsxs)(H.Content,{children:[t.title&&(0,ie.jsx)(H.Title,{className:i.title,"data-testid":"widget-cue-title",children:t.rule.label.startsWith("__")?a(t.rule.label):t.title}),t.message&&(0,ie.jsx)("p",{className:i.ctaMessage,children:t.message}),t.editable?(0,ie.jsx)(Jh,{content:c,onCopy:()=>{let v=document.getSelection();v&&g(v.toString())},onChange:v=>{var x;return p((x=v.target.value)!=null?x:"")}}):(0,ie.jsx)(rn,{content:t.text,sources:t.sources,onSourceClick:v=>r==null?void 0:r(v,t),useLabel:a("useCue"),copyLabel:a("copyCue"),onCopy:g,onUse:l?m:void 0})]})}),(0,ie.jsxs)(M.ButtonsContainer,{children:[(0,ie.jsxs)("div",{className:i.actions,children:[(0,ie.jsx)(M.Button,{onClick:v=>{var x;return g((x=Hs(c,"reply")[0])!=null?x:c,v.target)},variant:"primary",children:a("copyCue")}),t.callToAction&&(0,ie.jsx)(M.Button,{onClick:()=>u(),variant:"primary",children:t.callToAction.label}),(y=t.callToActions)==null?void 0:y.map((v,x)=>(0,ie.jsx)(M.Button,{onClick:()=>u(v),variant:"primary",children:v.label},`${v.event}-${v.label}-${x}`)),(0,ie.jsx)(M.Button,{onClick:f,variant:"secondary",children:a("removeCue")})]}),(0,ie.jsx)($s,{evaluationId:t.evaluationId,assistantCode:t.rule.label,assistantOutput:t.text,feedbackType:"assistant"})]})]})},xp=Qh;var Xn=require("react/jsx-runtime"),Zh=({cues:t})=>{let e=(0,bp.useDispatch)(),n=fe(),o=P(Go),s=q(),r=c=>{e(Us({code:c.rule.label})),s("Assistant response closed",{evaluationId:c.evaluationId,assistantCode:c.rule.label,assistantOutput:c.text})},i=(c,p)=>{qe(c),s("Assistant response copied",{evaluationId:p.evaluationId,assistantCode:p.rule.label,assistantOutput:p.text,copiedText:c})},a=(c,p)=>{var u;p.callToAction&&(e(Bs(p)),s("Assistant call to action",{evaluationId:p.evaluationId,assistantCode:p.rule.label,assistantOutput:p.text,eventName:p.callToAction.event,value:(u=p.callToAction.value)!=null?u:c}))},d=(c,p)=>{var u;n.send(it,{text:c,suggestion:{source:"assistant",assistantCode:(u=p.rule)==null?void 0:u.label,sourceText:c}}),s("Assistant response used",{evaluationId:p.evaluationId,assistantCode:p.rule.label,assistantOutput:p.text,usedText:c})},l=(c,p)=>{s("Assistant source clicked",{evaluationId:p.evaluationId,assistantCode:p.rule.label,source:c})};return(0,Xn.jsx)(Xn.Fragment,{children:t.map(c=>c.isLoading?(0,Xn.jsx)(Zs,{title:c.rule.label.startsWith("__")?o(c.rule.label):c.title},c.rule.id):(0,Xn.jsx)(xp,{cue:c,onCallToAction:a,onRemove:r,onCopy:i,onUse:d,onSourceClick:l},c.evaluationId))})},Cp=Zh;var qr=require("react");var Tp={root:"dd-cvTAY",label:"dd-QWQxD",value:"dd-WSUHF",copyButton:"dd-67o9H",copyButtonText:"dd-oos-l",isTrue:"dd--1g2O",isFalse:"dd-sz2ir"};var ve=require("react/jsx-runtime");function Yh(t,e){return e.split(".").reduce((n,o)=>!n||typeof n!="object"||!(o in n)?null:n[o],t)}var wp=({data:t,schema:e})=>{let n=C("WidgetCustomData",Tp),o=s=>{qe(s)};return(0,qr.useEffect)(()=>{k.info("Custom data",t,e)},[t]),(0,ve.jsx)("dl",{className:n.root,children:e.map(s=>{let r=Yh(t,s.path);return(0,ve.jsxs)(qr.Fragment,{children:[(0,ve.jsx)("dt",{className:n.label,children:s.label}),(0,ve.jsx)("dd",{className:n.value,children:s.type==="boolean"&&r?(0,ve.jsx)("span",{className:n.isTrue,children:s.trueValue}):s.type==="boolean"&&!r?(0,ve.jsx)("span",{className:n.isFalse,children:s.falseValue}):s.type==="array"&&Array.isArray(r)&&r.length>0?(0,ve.jsxs)("button",{type:"button",onClick:()=>o(r.join(", ")),className:n.copyButton,children:[(0,ve.jsx)("span",{className:n.copyButtonText,children:r.join(", ")}),(0,ve.jsx)(Gn,{})]}):typeof r=="string"||typeof r=="number"?(0,ve.jsxs)("button",{type:"button",onClick:()=>o(`${r}`),className:n.copyButton,children:[(0,ve.jsx)("span",{className:n.copyButtonText,children:r}),(0,ve.jsx)(Gn,{})]}):"-"})]},s.label)})})};var kp=require("react");var ey=/(https?:\/\/[^\s]+)/,Ep=t=>t.split(" ").find(e=>ey.test(e));var Le=require("react/jsx-runtime"),ty=({suggestion:t,lines:e,onUse:n})=>{var p;let o=t.text||t.url||t.message,s=Ep(o),r=P(Oo),i=E("showImages"),a=E("fallbackImage"),d=E("hasKeyboardInput"),l=u=>{u.preventDefault(),u.stopPropagation(),d&&n(o)},c=(0,kp.useCallback)(u=>{window.open(s,"_blank"),u.stopPropagation(),u.preventDefault()},[s]);return(0,Le.jsxs)(M,{onClick:d?l:void 0,"data-testid":"edit-suggestion",children:[(0,Le.jsxs)(H,{children:[i&&t.image&&(0,Le.jsx)(H.Image,{src:Ur(t,"small",a||void 0),title:t.title}),(0,Le.jsxs)(H.Content,{children:[t.title&&(0,Le.jsx)(H.Title,{"data-testid":"widget-suggestion-title",children:t.title}),t.searchKeywords&&((p=t.searchKeywords)==null?void 0:p.length)>0&&(0,Le.jsx)(M.Labels,{labels:t.searchKeywords}),(0,Le.jsx)(H.Content,{cropText:e==="single",lineClamp:e==="multiple",children:o})]})]}),(0,Le.jsxs)(M.Actions,{children:[s&&(0,Le.jsx)(M.ActionButton,{onClick:c,label:r("visitUrl")}),d&&(0,Le.jsx)(M.ActionButton,{primary:!0,onClick:l,label:r("useSuggestion")})]})]})},Rp=ty;var Xo=require("react/jsx-runtime"),ny=({lines:t,suggestions:e})=>{let n=fe(),o=(s,r)=>{n.send(it,{text:s,suggestion:b(h({},r),{source:r.source,sourceText:r.text})})};return(0,Xo.jsx)(Xo.Fragment,{children:e.map(s=>(0,Xo.jsx)(Rp,{suggestion:s,lines:t,onUse:r=>o(r,s)},s.text||s.url||s.message))})},Pp=ny;var Jo={};Z(Jo,{enUS:()=>oy,nlNL:()=>sy});var oy={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"}]},sy={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 Jn={root:"dd-W9VCG",loginText:"dd--dS6t",stateText:"dd-348OC",footer:"dd-tvofr",shortcutList:"dd-MuKK-",shortcut:"dd-5CnK9",footerShortcut:"dd-dH7XJ",link:"dd-DRo0x"};var A=require("react/jsx-runtime"),Ip=(t,e)=>{let n=(0,Q.useSelector)(se);(0,Ut.useEffect)(()=>n?e.every(o=>!!o)?t():()=>{}:()=>{},[...e,n])},ry=({onLogIn:t})=>{let e=C("Widget",Jn),n=E("isEmbedded"),o=E("adminUrl");return(0,A.jsx)("div",{className:e.loginText,children:(0,A.jsx)("div",{children:(0,A.jsx)(Ir,{isEmbedded:n,loginUrl:o,onLogIn:t})})},"login")},Ta=({text:t})=>{let e=C("Widget",Jn);return(0,A.jsx)("div",{className:e.stateText,children:(0,A.jsx)("div",{children:(0,A.jsx)("p",{children:t})})},"notification")},iy=()=>{let t=P(Jo),e=(0,Q.useDispatch)(),n=C("Widget",Jn),o=E("showSearch"),s=E("isEmbedded"),r=(0,Q.useSelector)(On("/admin/")),i=fe(),a=E("productName"),d=q();return Ip(()=>{if(s)return e(ha()),()=>{e(sp())}},[e,s]),!o&&!r?null:(0,A.jsxs)("div",{className:n.shortcutList,children:[o&&(0,A.jsx)(M.Button,{"data-testid":"shortcut-search","aria-label":t("linkSearch"),className:n.shortcut,icon:(0,A.jsx)(Wn,{}),onClick:()=>{i.send("ShowCommandPalette",{isOpen:!0}),d("open search",{via:"widget-shortcut"})},children:t("linkSearch")}),r&&(0,A.jsx)(M.Button,{as:"a",target:"_blank",icon:(0,A.jsx)(up,{}),href:r,"data-testid":"shortcut-studio-login","aria-label":t("linkStudioLogin",{productName:a}),className:n.shortcut,rel:"noreferrer",onClick:()=>{d("open my deepdesk",{via:"widget-shortcut"})},children:t("linkStudioLogin",{productName:a})})]})},ay=({title:t,content:e})=>{let n=P(Jo),[o,s]=(0,Ut.useState)(!0);return o?(0,A.jsx)(Ve,{"data-testid":"custom-data-banner",type:"custom-data-banner",title:t,children:(0,A.jsx)(oe,{withDivider:!0,children:(0,A.jsxs)(M,{children:[(0,A.jsx)(H,{children:(0,A.jsx)(H.Content,{children:(0,A.jsx)(rn,{content:e})})}),(0,A.jsx)(M.ButtonsContainer,{children:(0,A.jsx)(M.Button,{onClick:()=>s(!1),children:n("close")})})]})})}):null},ly=()=>{let t=(0,Q.useDispatch)(),e=(0,Q.useSelector)(Ro),n=(0,Q.useSelector)(gc),o=(0,Q.useSelector)(lp),s=(0,Q.useSelector)(Fl),r=(0,Q.useSelector)(pr),i=(0,Q.useSelector)(hr),a=(0,Q.useSelector)(Lt),d=(0,Q.useSelector)($e);return(0,Ut.useEffect)(()=>{s&&!n&&k.warn("Custom data provided, but no schema.")},[s,n]),Ip(()=>{e.forEach(({type:l})=>{l==="entities"?t(Ue()):gs.includes(l)||t(Ke(l))})},[t,d,a]),(0,Ut.useEffect)(()=>{o.length>0&&!e.some(l=>l.type==="cues")&&k.warn("Received cues, but cues are not configured in widget.")},[e,o]),(0,A.jsx)(Ut.Fragment,{children:e.map(({type:l,title:c,amount:p,lines:u,schema:g,property:m})=>{var f,y;switch(l){case"entities":return r&&r.length>0&&(0,A.jsx)(Ve,{type:l,title:c,"data-testid":`type-${l}`,children:(0,A.jsx)(cp,{entities:r})},l);case"cues":return o&&o.length>0&&(0,A.jsx)(Ve,{type:l,title:c,"data-testid":`type-${l}`,children:(0,A.jsx)(oe,{withDivider:!0,children:(0,A.jsx)(Cp,{cues:o})})},l);case"custom-data-banner":return s&&m&&s[m]&&(0,A.jsx)(ay,{title:c,content:String(s[m])},l);case"custom-data":return s&&g&&(0,A.jsx)(Ve,{type:l,title:c,"data-testid":`type-${l}`,children:(0,A.jsx)(oe,{withDivider:!0,children:(0,A.jsx)(wp,{data:s,schema:g})})},l);default:return((y=(f=i[l])==null?void 0:f.suggestions)==null?void 0:y.length)>0&&(0,A.jsx)(Ve,{type:l,title:c,"data-testid":`type-${l}`,children:(0,A.jsx)(oe,{withDivider:!0,children:(0,A.jsx)(Pp,{lines:u,contentType:l,suggestions:i[l].suggestions.slice(0,p)||[]})})},l)}})})},wa=({children:t})=>{let e=C("Widget",Jn);return(0,A.jsx)("div",{className:e.footer,children:t})},Ea=({children:t})=>{let e=C("Widget",Jn);return(0,A.jsx)("div",{className:e.root,"data-testid":"widget",children:t})},dy=({onLogIn:t,knowledgeAssistOptions:e={},assistantOptions:n={transcript:"in-memory-transcript"},openAdminFeedback:o})=>{let s=P(Jo),r=(0,Q.useSelector)(kn),i=(0,Q.useSelector)(se),a=(0,Q.useSelector)(hs),d=(0,Q.useSelector)(Lt),l=(0,Q.useSelector)(pc("knowledge-assist")),c=(0,Q.useSelector)(mc);return r===!1?(0,A.jsx)(Ta,{text:s("notSupported")}):i===!1?(0,A.jsx)(ry,{onLogIn:t}):i===null?(0,A.jsx)(Ta,{text:s("waiting")}):!a||!d?(0,A.jsx)(Ta,{text:s("waitingForConversation")}):(0,A.jsx)(Pd,{handler:o,children:(0,A.jsx)(Ea,{children:(0,A.jsxs)(nr,{initialQuestion:e.initialQuestion,assistantCode:c!=null?c:void 0,evaluateKnowledgeAssistFn:bo,children:[(0,A.jsxs)(Tn,{children:[(0,A.jsx)(iy,{}),(0,A.jsx)(ly,{}),l&&(0,A.jsx)(sr,{title:l.title,emptyState:e.emptyState})]}),(0,A.jsxs)(wa,{children:[l&&(0,A.jsx)(or,{}),(0,A.jsx)(Sp,{assistantOptions:n})]})]})})})},Ap=dy;function Qn(t){let e=new Range;return e.selectNodeContents(t),e}function Lp(t,e,n){try{return Kt(t,e,n),!0}catch(o){return!1}}function Gr(t){return"tagName"in t&&(t.tagName==="DIV"||t.tagName==="P")}function Xr(t){return"tagName"in t&&t.tagName==="BR"}var Qo=/[\u200B-\u200D\uFEFF]/g;function Kt(t,e,n){let o=new Range;if(t.firstChild===null&&e===0&&n===0)return o.selectNodeContents(t),o;let s=0,r=!1;function i(d,l){let c=-1,p=/[\u200B-\u200D\uFEFF]/;if(!p.test(d))return l;for(let u=0;u<=d.length;u++)if(p.test(d[u])||c++,c===l)return u;throw new Error("Offset out of range")}function a(d){switch(d.nodeType){case Node.TEXT_NODE:{let l=d.textContent,c=l.replace(Qo,""),p=s+c.length,u=e>=s&&e<=p,g=n>=s&&n<=p;if(u){let m=i(l,e-s);m===0&&!g?o.setStartBefore(d):o.setStart(d,m)}g&&(o.setEnd(d,i(l,n-s)),r=!0),s=p;break}case Node.ELEMENT_NODE:{if(Xr(d)&&(s===e&&o.setStartBefore(d),s++,s===n)){o.setEndAfter(d),r=!0;return}for(let c=0;c<d.childNodes.length&&(a(d.childNodes[c]),!r);c++);let l=d.lastChild;Gr(d)&&l&&!Gr(l)&&!Xr(l)&&s++;break}default:break}}if(a(t),o.startContainer===document)throw new Error("Offsets out of bound");return o}function Zo(t,e){if(!t.contains(e.startContainer)||!t.contains(e.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:o,endContainer:s,endOffset:r,collapsed:i}=e,a,d,l=0;function c(p){let u=p===t,g=p===n,m=p===s;switch(p.nodeType){case Node.TEXT_NODE:{let f=p.textContent;g&&(a=l+f.substring(0,o).replace(Qo,"").length),m&&(d=l+f.substring(0,r).replace(Qo,"").length),l+=f.replace(Qo,"").length;break}case Node.ELEMENT_NODE:{if(Xr(p)&&p.nextSibling){l++;break}!u&&Gr(p)&&p.previousSibling&&l++;for(let f=0;f<p.childNodes.length;f++){let y=g&&f===o,v=m&&f===r;if(y&&(a=l),v&&(d=l),d!==void 0||((!y||!i)&&c(p.childNodes[f]),m&&f===r-1&&(d=l),d!==void 0))break}m&&(d=l);break}default:break}}if(c(t),d===void 0)throw new Error("Could not determine start and end");return{start:a!=null?a:d,end:d}}function Yo(t,e){if(!t.contains(e.startContainer)||!t.contains(e.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:o,endContainer:s,endOffset:r,collapsed:i}=e,a=0,d="";function l(c){let p=c===t,u=c===n,g=c===s;switch(u&&(a=1),c.nodeType){case Node.TEXT_NODE:{if(a!==1)return;let m=u?o:0,f=g?r:void 0;d+=c.textContent.replace(Qo,"").substring(m,f);break}case Node.ELEMENT_NODE:{if(!i&&a===1&&Xr(c)&&c.nextSibling){d+=`
10
+ `;break}!p&&!i&&a===1&&Gr(c)&&c.previousSibling&&(d+=`
11
+ `);let m=u?o:0,f=g?Math.min(r,c.childNodes.length):c.childNodes.length;for(let y=m;y<f&&(l(c.childNodes[y]),a!==2);y++);break}default:break}g&&(a=2)}return l(t),d}var Mp=(i=>(i.CUT="Cut",i.BACKSPACE="Backspace",i.DELETE="Delete",i.ERASEEOF="EraseEof",i.UNDO="Undo",i.CLEAR="Clear",i))(Mp||{}),St=class{constructor(e){this.element=e;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(e,n){let o=s=>{n(s)};this.element.addEventListener(e,o),this.disposeHandlers.push(()=>{this.element.removeEventListener(e,o)})}removeEventListener(e,n){this.element.removeEventListener(e,n)}handleInteraction(){let e=this.getText(),n=this.getHTML(),o=this.getSelection(),s=this.getSuggestionTextStart(),r=this.cachedCaretPosition===null;if(!this.isActive)return;e===""&&this.cachedText!==""&&!this.isPossibleClearInputAction&&this.emit("submit");let i=e!==this.cachedText,a=n!==null&&n!==this.cachedHTML,d=s!==this.cachedSuggestionTextStart;if((i||a||d)&&(i?(this.cachedText=e,this.cachedHTML=n):a&&(this.cachedHTML=n),this.cachedSuggestionTextStart=s,r=!0,this.emit("change",{plainText:e,rawHTML:n,suggestionTextStart:s})),(o.start!==this.cachedSelection.start||o.end!==this.cachedSelection.end)&&(this.cachedSelection=o,r=!0,this.emit("selection",o)),!r)return;let l=this.getCaretPosition();kt(l,this.cachedCaretPosition)||(this.cachedCaretPosition=l,this.emit("caretposition",l))}handleClick(){this.handleInteraction()}handleFocus(){let e=!this.isFocused;this.isFocused=!0,e&&this.emit("focus"),this.handleInteraction()}handleBlur(){this.isPossibleClearInputAction=!1;let e=this.isFocused;this.isFocused=!1,e&&this.emit("blur")}handleKeyDown(e){let{key:n,ctrlKey:o,metaKey:s}=e;this.isPossibleClearInputAction=Object.values(Mp).includes(n)||n.toLowerCase()==="z"&&(o||s),this.emit("keydown",e)}handleKeyUp(e){this.handleInteraction(),this.emit("keyup",e)}handleCut(){this.isPossibleClearInputAction=!0,this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(e){var o,s;let n=((o=e.clipboardData)==null?void 0:o.getData("text"))||((s=e.clipboardData)==null?void 0:s.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 e=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});e.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{e.disconnect()})}getSuggestionTextStart(){return 0}focus(){this.element.focus()}emit(e,...n){this.isDisposed||this.eventListeners[e]&&this.eventListeners[e].forEach(o=>{o(...n)})}on(e,n){this.isDisposed||(this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(n))}off(e,n){if(!this.eventListeners[e])return;let o=this.eventListeners[e].indexOf(n);o!==-1&&this.eventListeners[e].splice(o,1)}activate(){let e=this.isActive===!1;this.isActive=!0,e&&this.handleInteraction()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(e=>e()),this.eventListeners={},this.isDisposed=!0}};function Np(t){return t.top!==0||t.left!==0||t.height!==0||t.width!==0}var yn=class extends St{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),Yo(this.element,n)}getHTML(){return this.element.innerHTML||""}getRange(){let n=this.getRootNode();if(n.activeElement!==this.element)return null;let o="getSelection"in n?n.getSelection():window.getSelection();if(!o)return null;let s=o.rangeCount>0?o.getRangeAt(0):null;if(!s)return null;let r=this.element.ownerDocument.createRange();return r.setStart(s==null?void 0:s.startContainer,s==null?void 0:s.startOffset),r.setEnd(s==null?void 0:s.endContainer,s==null?void 0:s.endOffset),!r||!this.element.contains(r.startContainer)||!this.element.contains(r.endContainer)?null:r}getCaretPosition(){let n=this.getRange();if(!n||!n.collapsed||!("getBoundingClientRect"in n))return null;let o=n.getBoundingClientRect();return!Np(o)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),o=n.getBoundingClientRect(),n.deleteContents(),!Np(o))?null:{top:o.top+o.height,left:o.left}}getSelection(){let n=this.getRange();if(n)return Zo(this.element,n);let o=this.lastKnownSelection;if(o&&Lp(this.element,o.start,o.end))return o;let s=Qn(this.element);return s.collapse(!1),Zo(this.element,s)}getSelectedText(){let{start:n,end:o}=this.getSelection();return Yo(this.element,Kt(this.element,n,o))}listen(){super.listen();let n=new MutationObserver(r=>{var i,a;r.length===2&&r[0].addedNodes.length===1&&((i=r[0].addedNodes[0])==null?void 0:i.textContent)==="\u2060"&&((a=r[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 o=this.element.isContentEditable,s=new MutationObserver(()=>{this.element.isContentEditable!==o&&(o=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});s.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>s.disconnect())}};var cy=["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 Op(t,e){let n="mozInnerScreenX"in window,o=document.createElement("div");o.id="input-textarea-caret-position-mirror-div";let s=o.style,r=window.getComputedStyle(t),i=t.ownerDocument.body;s.whiteSpace="pre-wrap",s.wordWrap="break-word",s.position="absolute",s.visibility="hidden",cy.forEach(c=>{s[c]=r[c]}),n?t.scrollHeight>Number.parseInt(r.height)&&(s.overflowY="scroll"):s.overflow="hidden",o.textContent=t.value.substring(0,e);let a=document.createElement("span");a.textContent=t.value.substring(e)||".",o.appendChild(a),i.appendChild(o);let d=t.getBoundingClientRect(),l={top:d.top-t.scrollTop+a.offsetTop+Number.parseInt(r.borderTopWidth)+a.offsetHeight,left:d.left-t.scrollLeft+a.offsetLeft+Number.parseInt(r.borderLeftWidth)};return i.removeChild(o),l}var vn=class extends St{constructor(){super(...arguments);this.lastKnownSelection=null}getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:n,selectionEnd:o}=this.element;return{start:n,end:o}}getSelectedText(){let n=this.getSelection();return n?this.getText().slice(n.start,n.end):""}getCaretPosition(){return Op(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 r;return(r=n==null?void 0:n.get)==null?void 0:r.call(this.element)},set:r=>{var i;(i=n==null?void 0:n.set)==null||i.call(this.element,r),this.handleInteraction()}}),this.addEventListener("scroll",()=>{this.emit("caretposition",this.getCaretPosition())});let o=this.element.disabled,s=new MutationObserver(()=>{this.element.disabled!==o&&(o=this.element.disabled,this.emit(o?"disabled":"enabled"))});s.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>s.disconnect())}};function Dp(t,e,n){let o=`deepdesk-iframe-${t}`,s=document.getElementById(o);if(s)return s;let r=document.createElement("iframe"),i=new URL(e);return Object.entries(n).forEach(([a,d])=>{i.searchParams.append(a,d)}),r.style.position="absolute",r.style.left="-999em",r.style.width="0px",r.style.height="0px",r.tabIndex=-1,r.id=o,r.title=`iframe-${t}`,r.src=i.toString(),window.document.body.appendChild(r),r}function uy(t){if(typeof t!="string")return t;try{return JSON.parse(t)}catch(e){return t}}var ka=class{constructor(e){this.name=e;this.disposeHandlers=[];this.broadcastChannel=new BroadcastChannel(e)}onMessage(e){this.broadcastChannel.addEventListener("message",e),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",e)})}postMessage(e){this.broadcastChannel.postMessage(JSON.stringify(e))}close(){this.disposeHandlers.forEach(e=>e()),this.broadcastChannel.close()}},Ra=class{constructor(e,n,o){this.name=e;this.targetOrigin=n;this.options=o;this.disposeHandlers=[];this.iframe=Dp(e,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}onMessage(e){window.addEventListener("message",e),this.disposeHandlers.push(()=>{window.removeEventListener("message",e)})}postMessage(e){var n;(n=this.iframe.contentWindow)==null||n.postMessage(JSON.stringify(e),this.targetOrigin)}close(){var e;this.disposeHandlers.forEach(n=>n()),(e=this.iframe)==null||e.remove()}},Pa=class{constructor(e){this.params=e;this.deepdeskUrl=e.deepdeskUrl,this.eventMap=e.eventMap,this.externalId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setExternalId(e){this.externalId!==e&&(this.cleanup(),k.info("Set externalId",e),this.externalId=e,this.channel=this.createChannel(e))}createChannel(e){let n=this.params.createCustomChannel?this.params.createCustomChannel(e):this.isCrossOrigin?new Ra(e,this.deepdeskUrl,{debug:!0}):new ka(e),o=s=>{var i,a;if(s.origin!==this.deepdeskUrl)return;let r=uy(s.data);typeof r!="object"||r.type!=="event"||r.channel!==e||(k.info("Received broadcast event",this.externalId,s),(a=(i=this.eventMap)[r.name])==null||a.call(i,r.payload))};return n.onMessage(o),n}send(e,n,o){var i,a;k.info("Broadcast event",{externalId:this.externalId,name:e,payload:n});let s={type:"event",name:e,payload:n};o!==!1&&((a=(i=this.eventMap)[e])==null||a.call(i,n));let r=this.externalId==="deepdesk-general"?this.defaultChannel:this.channel;r==null||r.postMessage(b(h({},s),{channel:this.externalId}))}cleanup(e=!1){var n,o;(n=this.channel)==null||n.close(),this.channel=void 0,e&&((o=this.defaultChannel)==null||o.close(),this.defaultChannel=void 0)}},_p=Pa;function py(t){return t.replace(/(_\w)/g,e=>e[1].toUpperCase())}function W(t){return Array.isArray(t)?t.map(W):typeof t=="object"&&t!==null?Object.keys(t).reduce((e,n)=>b(h({},e),{[py(n)]:W(t[n])}),{}):t}function gy(t){return t.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}function ae(t){return Array.isArray(t)?t.map(ae):typeof t=="object"&&t!==null?Object.keys(t).reduce((e,n)=>b(h({},e),{[gy(n)]:ae(t[n])}),{}):t}var Zn=class extends Error{constructor(n,o){super(n);this.body=o;this.name="CustomError"}};var es=t=>new Promise(e=>{setTimeout(e,t)});var We=class extends Zn{constructor(){super(...arguments);this.name="ClientError"}},Jr=class extends Zn{constructor(){super(...arguments);this.name="ServerError"}},Ia=new Map;function Fp(t){return S(this,null,function*(){if(t.status===204)return t.text().catch(()=>{}),null;let e=t.headers.get("content-type");if(e!=null&&e.includes("application/json"))return t.json();let n=yield t.text();return n===""?null:(k.warn("Unexpected response body:",n.slice(0,20)),JSON.parse(n))})}var Sn=class{constructor(e="",n={}){this.baseUrl=e;this.options=n;this.latestRequestByUrl={};this.refreshingToken=null;this.lastFailedRefreshAt=null;this.failedRefreshCooldown=1e4;var o;this.fetch=(o=n.fetch)!=null?o:window.fetch.bind(window)}patchFetch(e){this.fetch=e(this.fetch)}setCsrfToken(e){this.csrfToken=e}request(e,n={}){return new Promise((o,s)=>{let r={isAborted:!1,reject:s},i=`${this.baseUrl}${e}`,a=this.fetch,d=n.method===void 0||n.method.toLowerCase()==="get",R=n,{useCache:l=!1,abortLatest:c=!1,attempts:p=1,retryDelay:u=500,refreshTokenOn401:g=!0,retryOnError:m=I=>I instanceof TypeError,retryOnResponse:f=I=>I.status>=500,version:y=null}=R,v=O(R,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]);if(l){if(!d)throw new Error(`Can't use 'useCache' for ${n.method}`);if(Ia.has(i)){o(Ia.get(i));return}}let x=b(h({credentials:"include"},v),{headers:h({Accept:"application/json","Content-Type":"application/json"},v.headers)});!d&&this.csrfToken&&(x.headers=b(h({},x.headers),{"X-CSRFToken":this.csrfToken})),typeof y=="string"&&(x.headers=b(h({},x.headers),{"X-Deepdesk-API-Version":y}));let T=p,w=!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]=r;let L=()=>S(this,null,function*(){return T--,a(i,x).then(I=>S(this,null,function*(){return f(I)&&!r.isAborted&&T>0?(yield es(u),L()):I.status===401&&g===!0&&w===!1?(w=!0,yield this.refreshToken(),L()):I})).catch(I=>S(this,null,function*(){if(m(I)&&!r.isAborted&&T>0)return yield es(u),L();throw I}))});L().then(I=>S(this,null,function*(){let z=yield Fp(I);if(delete this.latestRequestByUrl[i],I.status>=500){s(new Jr("Server Error",z));return}if(I.status===401){s(new We("Unauthorized",z));return}if(I.status===403){s(new We("Forbidden",z));return}if(I.status===404){s(new We("Not Found",z));return}if(I.status>=400){s(new We("Bad Request",z));return}l&&Ia.set(i,z),o(z)})).catch(I=>{s(I)})})}validateToken(){return S(this,null,function*(){let e,n,o;try{({has_valid_access_token:e,is_logged_in:n,has_valid_refresh_token:o}=yield this.get("/apis/admin/session/validate/",{refreshTokenOn401:!1}))}catch(s){return!1}if(!e){if(!o)return!1;try{yield this.refreshToken();let{is_logged_in:s}=yield this.get("/apis/admin/session/validate/",{refreshTokenOn401:!1});return s}catch(s){return!1}}return n})}refreshToken(){let e=Date.now();return this.lastFailedRefreshAt&&e-this.lastFailedRefreshAt<this.failedRefreshCooldown?Promise.reject(new We("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(e,n){return this.request(e,n)}post(e,n,o){return this.request(e,h({method:"POST",body:JSON.stringify(n)},o))}postWithStatus(e,n,o){return this.requestWithStatus(e,h({method:"POST",body:JSON.stringify(n)},o))}requestWithStatus(e,n={}){return new Promise((o,s)=>{let r={isAborted:!1,reject:s},i=`${this.baseUrl}${e}`,a=this.fetch,L=n,{useCache:d=!1,abortLatest:l=!1,attempts:c=1,retryDelay:p=500,refreshTokenOn401:u=!0,retryOnError:g=R=>R instanceof TypeError,retryOnResponse:m=R=>R.status>=500,version:f=null}=L,y=O(L,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]),v=b(h({credentials:"include"},y),{headers:h({Accept:"application/json","Content-Type":"application/json"},y.headers)});this.csrfToken&&(v.headers=b(h({},v.headers),{"X-CSRFToken":this.csrfToken})),typeof f=="string"&&(v.headers=b(h({},v.headers),{"X-Deepdesk-API-Version":f}));let x=c,T=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[i]&&l&&(this.latestRequestByUrl[i].isAborted=!0,this.latestRequestByUrl[i].reject(new Error("Aborted"))),this.latestRequestByUrl[i]=r;let w=()=>S(this,null,function*(){return x--,a(i,v).then(R=>S(this,null,function*(){return m(R)&&!r.isAborted&&x>0?(yield es(p),w()):R.status===401&&u===!0&&T===!1?(T=!0,yield this.refreshToken(),w()):R})).catch(R=>S(this,null,function*(){if(g(R)&&!r.isAborted&&x>0)return yield es(p),w();throw R}))});w().then(R=>S(this,null,function*(){let I=yield Fp(R);if(delete this.latestRequestByUrl[i],R.status>=500){s(new Jr("Server Error",I));return}if(R.status===401){s(new We("Unauthorized",I));return}if(R.status===403){s(new We("Forbidden",I));return}if(R.status===404){s(new We("Not Found",I));return}if(R.status>=400){s(new We("Bad Request",I));return}o({status:R.status,data:I})})).catch(R=>{delete this.latestRequestByUrl[i],s(R)})})}patch(e,n,o){return this.request(e,h({method:"PATCH",body:JSON.stringify(n)},o))}put(e,n,o){return this.request(e,h({method:"PUT",body:JSON.stringify(n)},o))}delete(e,n){return this.request(e,h({method:"DELETE"},n))}};var Hp;(e=>{let t;(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"))(t=e.EvaluationStatus||(e.EvaluationStatus={}))})(Hp||(Hp={}));function Qr(t){return b(h({},W(t)),{metadata:t.metadata})}var xn=class xn{constructor(e,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new Sn(e,{fetch:n.fetch}),this.client.patchFetch(o=>(s,r)=>S(this,null,function*(){let i=yield o(s,r);return this.handleDeepdeskVersionHeaders(i),i}))}preflight(){return S(this,null,function*(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let e=yield this.getCsrfToken();this.client.setCsrfToken(e)}return this.options.token?(xn.exchangeTokenPromise||(xn.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),xn.exchangeTokenPromise):Promise.resolve()})}createConversation(e){return S(this,null,function*(){var o;yield this.preflight(),k.info(`Creating conversation for session ${e.externalId} and agent ${e.agentId}`);let n=yield this.client.post("/api/v2/conversations",b(h({chat_start_time:new Date().toISOString()},ae(e)),{metadata:(o=e.metadata)!=null?o:{}}));return Qr(n)})}upsertConversation(e){return S(this,null,function*(){var c;yield this.preflight(),k.info(`Upserting conversation for session ${e.externalId} and agent ${e.agentId}`);let{status:n,data:o}=yield this.client.postWithStatus("/api/v2/conversations",b(h({chat_start_time:new Date().toISOString()},ae(e)),{metadata:(c=e.metadata)!=null?c:{}}),{version:"v2"}),s=Qr(o);if(n===201)return s;let{agentId:r,agentName:i,agentEmail:a,agentNickname:d,metadata:l}=e;return this.updateConversation(s.id,{agentId:r,agentEmail:a,agentName:i,agentNickname:d,metadata:l})})}getMe(){return S(this,null,function*(){let e=yield this.client.get("/apis/admin/session/me/");return W(e)})}postIdentity(e){return S(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/me/identities/",ae(e))})}patchMe(e){return S(this,null,function*(){yield this.preflight();let n=yield this.client.patch("/apis/admin/session/me/",ae(e));return W(n)})}getProfile(e){return S(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${e}/`,{useCache:!0});return W(n)})}getKnowledgeAssistant(e){return S(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${e}/`,{useCache:!0});return W(n)})}getContentTypes(){return S(this,null,function*(){let e=yield this.client.get("/apis/admin/content-types/",{useCache:!0});return W(e)})}getAccount(){return S(this,null,function*(){let e=yield this.client.get("/apis/admin/account/",{useCache:!0});return W(e)})}getPlatformConfig(e){return S(this,null,function*(){let n=e!==void 0?`/platform/config/${e}/`:"/platform/config/",{config:o}=yield this.client.get(n,{useCache:!0});return W(o)})}checkUserExists(e){return S(this,null,function*(){let{exists:n}=yield this.client.get(`/apis/admin/users/exists?external_id=${e}`,{version:"v1"});return n})}getConversationByExternalId(o){return S(this,arguments,function*(e,n={}){yield this.preflight(),k.info(`Getting conversation for session ${e}`);let{attempts:s=1,retryDelay:r=1e3}=n,i=yield this.client.get(`/api/v2/conversations/by_external_id/${e}`,{attempts:s,retryDelay:r,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"});return k.info(`Successfully retrieved conversation ${i.id} for session ${e}`),Qr(i)})}isConversationSupported(o){return S(this,arguments,function*(e,n={}){k.info(`Check if conversation for session ${e} is supported`);let{attempts:s=1,retryDelay:r=1e3}=n;return(yield this.client.get(`/api/v2/conversations/by_external_id/${e}/has_active_profile`,{attempts:s,retryDelay:r,retryOnResponse:a=>a.status===404||a.status>=500})).has_active_profile})}updateConversation(e,n){return S(this,null,function*(){var r;yield this.preflight();let o=ae(n);n.metadata&&(o.metadata=(r=n.metadata)!=null?r:{});let s=yield this.client.put(`/api/v2/conversations/${e}`,o);return Qr(s)})}postMessages(e,n){return S(this,null,function*(){yield this.preflight(),yield this.client.post(`/api/v2/conversations/${e}/messages`,n.map(o=>b(h({},ae(o)),{metadata:o.metadata})))})}sendEvent(e,n){return S(this,null,function*(){yield this.preflight();let a=n,{data:o}=a,s=O(a,["data"]),r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((d,[l,c])=>b(h({},d),{[l]:c}),{}),i=["platform","agentId","agentName","agentEmail","conversationId"].reduce((d,l)=>(s[l]&&(d[l]=s[l]),d),{});return this.client.post("/api/v2/events",ae(b(h(h({},r),i),{data:o,name:e})),{version:"v2"})})}getEntities(e){return S(this,null,function*(){return yield this.preflight(),yield this.client.post("/api/v2/entities",{messages:e.filter(o=>o.text)})})}getTemporaryExchangeToken(){return S(this,null,function*(){return(yield this.client.get("/apis/admin/session/exchange-token/")).jwt})}exchangeTokenForAccessCookie(e){return S(this,null,function*(){return this.client.post("/apis/admin/session/jwt/",{jwt:e}).catch(n=>{throw k.warn(`Invalid token '${e}'`),n})})}authenticateWithKey(e,n){return S(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/api-key/",ae(n),{refreshTokenOn401:!1,headers:{apikey:e}})})}getTextSuggestions(s){return S(this,arguments,function*(e,n={},o){if(yield this.preflight(),o==="sticky-messages")throw new Error("Use getPinnedMessages instead");return(yield this.client.post(`/api/v2/conversations/${e}/recommend/${o}`,ae(n),{abortLatest:!0})).map(i=>b(h({},W(i)),{text:i.text||i.url||i.message,source:o,type:o})).filter((i,a,d)=>a===d.findIndex(l=>l.text===i.text))})}isLoggedIn(){return S(this,null,function*(){return yield this.preflight(),this.client.validateToken()})}getAutocompleteSuggestions(e,n){return S(this,null,function*(){return yield this.preflight(),(yield this.client.post(`/api/v2/conversations/${e}/autocomplete`,ae(n),{abortLatest:!0})).map(s=>({score:1,source:s.source,sourceText:s.source_text,text:s.label,trainingJobs:s.training_jobs,searchKeywords:s.search_keywords,type:s.source})).filter((s,r,i)=>r===i.findIndex(a=>a.text===s.text))})}getPinnedMessages(e){return S(this,null,function*(){let n=yield this.client.get(`/api/v2/profiles/${e}/pinned-messages`,{abortLatest:!0});return W(n).map(o=>b(h({},o),{text:o.message,source:"sticky-messages",type:"pinned-message"}))})}getStyleSuggestions(e){return S(this,null,function*(){let n=yield this.client.post("/api/v2/style-suggestions",ae(e),{abortLatest:!0,version:"v2"});return W(n)})}search(e){return S(this,null,function*(){let n=yield this.client.post(`/api/v2/profiles/${e.profile}/search`,ae(e));return W(n)})}loginWithPassword(e,n){return S(this,null,function*(){yield this.preflight();let o=yield this.client.post("/apis/admin/session/login/",{username:e,password:n},{refreshTokenOn401:!1});return W(o)})}logout(){return S(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/logout/",{},{refreshTokenOn401:!1})})}requestLoginByEmail(e){return S(this,null,function*(){yield this.preflight();let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:e});return W(n)})}requestPasswordlessToken(){return S(this,null,function*(){let e=yield this.client.get("/apis/admin/session/passwordless/request/");return W(e.token)})}getCsrfToken(){return S(this,null,function*(){let{token:e}=yield this.client.get("/apis/admin/session/csrf/");return e})}verifyLoginToken(e){return S(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/login/",{token:e});return W(n)})}evaluateAssistant(e,n){return S(this,null,function*(){var d,l,c;yield this.preflight();let o=new URLSearchParams;n!=null&&n.externalConversationId&&o.append("external_conversation_id",n.externalConversationId);let s=n!=null&&n.threadId?`/api/v2/assistants/${e}/threads/${n==null?void 0:n.threadId}/evaluate?${o.toString()}`:`/api/v2/assistants/${e}/evaluate?${o.toString()}`,r=p=>ae(p),i=(d=n==null?void 0:n.transcript)==null?void 0:d.map(p=>{var u;return h({source:p.source,text:p.text},(u=p.attachments)!=null&&u.length?{attachments:p.attachments.map(r)}:{})}),a=yield this.client.post(s,h({input:(l=n==null?void 0:n.input)!=null?l:{},conversation:i},(c=n==null?void 0:n.attachments)!=null&&c.length?{attachments:n.attachments.map(r)}:{}));return W(a)})}createAssistantThread(e){return S(this,null,function*(){yield this.preflight();let{assistantCode:n}=e,o=yield this.client.post(`/apis/admin/assistants/${n}/threads/`,{});return W(o)})}postMessageToAssistantThread(e){return S(this,null,function*(){yield this.preflight();let{assistantCode:n,threadId:o,message:s}=e,r=yield this.client.post(`/apis/admin/assistants/${n}/threads/${o}/messages/`,{content:s,role:"user"});return W(r)})}translateMessages(e){return S(this,null,function*(){yield this.preflight();let n=yield this.client.post("/api/v2/translate",ae(e));return W(n)})}handleDeepdeskVersionHeaders(e){e.headers.forEach((n,o)=>{let s=o.toLowerCase(),r=s.match(ll);if(!n||!r)return;let i=r[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&n&&a!==n&&k.warn(`Overwritten Version header ${s}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[i]=n})}};xn.exchangeTokenPromise=null;var xt=xn;var Zr=class{constructor(e){this.options=e;this.socket=null;this.maxReconnectAttempts=5;this.reconnectInterval=25e3;this.cleanupCallbacks=[];var n,o;this.socket,this.eventListeners=new Map,this.url=e.url,this.maxReconnectAttempts=(n=e.maxReconnectAttempts)!=null?n:this.maxReconnectAttempts,this.reconnectInterval=(o=e.reconnectInterval)!=null?o:this.reconnectInterval,this.shouldReconnect=e.shouldReconnect}connect(){let e=()=>this.cleanup();window.addEventListener("beforeunload",e),this.cleanupCallbacks.push(()=>window.removeEventListener("beforeunload",e)),this.reconnect()}setupListeners(){this.socket&&(this.socket.onmessage=e=>{var n;try{let o=W(JSON.parse(e.data));o.event&&this.eventListeners.has(o.event)&&((n=this.eventListeners.get(o.event))==null||n.forEach(s=>s(o.data)))}catch(o){console.error("Error parsing WebSocket message:",o)}},this.socket.onclose=e=>{console.log("WebSocket connection closed:",e),setTimeout(()=>{this.reconnect()},this.reconnectInterval)},this.socket.onerror=e=>{console.error("WebSocket error:",e)})}reconnect(){var e,n;if(this.maxReconnectAttempts<=0){console.error("Max reconnect attempts reached, closing WebSocket connection."),(e=this.socket)==null||e.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(e,n){if(!this.socket){console.error("WebSocket connection is not open.");return}this.socket.send(JSON.stringify({event:e,data:n}))}on(e,n){this.eventListeners.has(e)||this.eventListeners.set(e,[]);let o=this.eventListeners.get(e);o&&!o.includes(n)&&o.push(n)}close(){var e;(e=this.socket)==null||e.close()}cleanup(){this.close(),this.cleanupCallbacks.forEach(e=>e()),this.cleanupCallbacks=[]}};var ei=require("@reduxjs/toolkit");var Up=require("@reduxjs/toolkit");var Bp={startTime:null,stopTime:null},Kp=t=>t.handlingTime,Wp=(0,Up.createSlice)({name:"handlingTime",initialState:Bp,reducers:{handlingTimeStart(t){if(t.startTime&&!t.stopTime)throw new Error("Timing already started");t.startTime=new Date,t.stopTime=null},handlingTimeStop(t){if(!t.startTime)throw new Error("Timing not started");t.stopTime=new Date},handlingTimeReset(t){t.startTime=null,t.stopTime=null}},extraReducers:t=>{t.addCase(Y,()=>Bp)}}),{handlingTimeStart:zp,handlingTimeStop:Yr,handlingTimeReset:Vp}=Wp.actions,jp=Wp.reducer;var $p=(t={})=>{let e=h({onAuthError:En(!1)},t);return n=>o=>s=>("error"in s&&s.error.message==="Unauthorized"&&n.dispatch(e.onAuthError),o(s))};var qp=(t={})=>{let e,n=!0,o=h({getStyleSuggestions:gn,debounce:500},t);return s=>r=>i=>{var g;let a=s.getState().input.text,d=r(i),l=s.getState();if(l.auth.isLoggedIn!==!0)return d;let{showStyleSuggestions:c}=l.settings;if(!((g=l.conversation.current)==null?void 0:g.id)||!c)return d;let{text:u}=l.input;return u===a&&!n||(clearTimeout(e),u==="")||(e=setTimeout(()=>{n=!1,s.dispatch(o.getStyleSuggestions({text:u}))},t.debounce)),d}};function my(t,e){return t.text===e.text&&t.selection.start===e.selection.start&&t.selection.end===e.selection.end&&t.suggestionTextStart===e.suggestionTextStart}var Gp=(t={})=>{let e=h({getTextSuggestions:Ke,getAutocompleteSuggestions:Fo,debounce:200,check:Qe},t),n;return o=>s=>r=>{var f;let{input:i}=o.getState(),a=s(r),d=o.getState();if(d.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:l,showTabCompletion:c}=d.settings,p=(f=d.conversation.current)==null?void 0:f.id,u=r.type===yr.toString();if(!p||!l&&!c)return a;let{input:g}=d;return my(g,i)&&!u||(clearTimeout(n),!e.check(d))||(n=setTimeout(()=>{let y=Xt(d);y===""?o.dispatch(e.getTextSuggestions("default")):o.dispatch(e.getAutocompleteSuggestions(y))},u?0:e.debounce)),a}};var Xp=gn.fulfilled.toString();function fy(t,e){let n=new Set([...e.keywordMatches.map(s=>s.keyword)]),o=[];return n.forEach(s=>{let r=t.keywordMatches.filter(d=>d.keyword===s),i=e.keywordMatches.filter(d=>d.keyword===s),a=i.length-r.length;a<=0||o.push(...i.slice(0,a))}),o}var Jp=t=>e=>n=>o=>{var l;if(o.type!==Xp){n(o);return}let s=e.getState().styleSuggestions.list;n(o);let r=e.getState(),i=r.styleSuggestions.list,a=(l=r.conversation)==null?void 0:l.current;if(s===i)return;let d=fy(s,i);o.type===Xp&&d.length>0&&t.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:d}})};var hy=(0,ei.combineReducers)({assistants:Sd,auth:hl,conversation:bl,contentTypes:cc,passwordlessToken:rp,entities:Nc,handlingTime:jp,info:Vl,input:Ol,settings:Td,profile:fc,search:Jl,styleSuggestions:xu,ui:lu,textSuggestions:Vc});function Qp(t){return(0,ei.configureStore)({reducer:hy,middleware:e=>{var o;let n=e({thunk:{extraArgument:{dynamicThunkObject:t.dynamicThunkObject,deepdeskAPI:t.deepdeskAPI}},serializableCheck:!1}).concat($p()).concat(Gp({debounce:200})).concat(qp({debounce:500})).concat(Jp(t.deepdeskAPI));return((o=t.middleware)!=null?o:[]).reduce((s,r)=>s.concat(r),n)},preloadedState:t.preloadedState})}function Zp(t,e,n){if(e==="")return null;let o=new RegExp(`\\b${Nr(e)}\\b`,"gi"),s,r=null;for(;(s=o.exec(t))!==null&&!(s.index>n);)r={start:s.index,end:s.index+s[0].length};return r}var yy=t=>{var e,n;return(n=(e=t==null?void 0:t.type)==null?void 0:e.toLowerCase())!=null?n:"unknown"},vy=t=>e=>n=>o=>{var d,l,c,p,u,g;let s=e.getState(),r=nn("inlineSuggestions")(s),i=nn("autoSelectSuggestion")(s)||r;switch(o.type){case En.toString():{!o.payload&&t.emit("logout",void 0);break}case ms.fulfilled.toString():{t.emit("logout",void 0);break}case Ue.fulfilled.toString():o.payload.length>0&&t.sendEvent("entities found",{conversationId:(d=s.conversation.current)==null?void 0:d.id,data:{entities:o.payload}});break;case Zt.toString():t.logSendMessage(o.payload);break;case Bs.toString():t.emit("call-to-action",{cue:o.payload});break;case he.fulfilled.toString():if(!o.isBroadcasted){let{externalConversationId:m,currentExternalIdAtRequest:f}=(l=o.payload)!=null?l:{};(!m||!f||m===f)&&t.broadcast(xi,o,!1)}break;case he.rejected.toString():break;default:break}let a=n(o);switch(o.type){case Zt.toString():t.handleAfterSendMessage(o.payload);break;case Bo.toString():t.onUpdateShowTabHint(o.payload);break;case Yr.toString():t.logHandlingTime();break;case Pn.toString():t.broadcast(Rs,o);break;case Qt.toString():t.broadcast(Rs,o);break;case Us.toString():e.dispatch(Qt({source:"assistant",assistantCode:o.payload.code}));break;case"analytics/logEvent/fulfilled":{let m=s.assistants.cues.find(f=>f.code===o.meta.arg.data.assistantCode);t.emit("event",b(h({},o.meta.arg),{cue:m}));break}case Se.toString():{let{start:m,end:f}=s.input.selection;t.emit("select-suggestion",b(h({type:yy(o.payload.suggestion)},o.payload),{replace:o.payload.replace==="selection"?{start:m,end:f}:{start:0,end:f}})),r&&e.dispatch(Rt([]));break}case Su.toString():{let{keyword:m,suggestion:f,eventMetrics:y}=o.payload,{text:v,selection:x}=s.input,T=Zp(v,m,(c=x==null?void 0:x.end)!=null?c:v.length);if(!T)break;t.emit("select-suggestion",{text:f,type:"style",replace:T,suggestion:{text:f,source:"style"},eventMetrics:y});break}case xs.toString():t.emit("select-image",o.payload),t.sendEvent("Image attached",{conversationId:(p=s.conversation.current)==null?void 0:p.id,data:{path:o.payload.suggestion.image,title:o.payload.suggestion.title}});break;case Rt.toString():{i&&o.payload.length>0&&e.dispatch(bs(0));break}case he.fulfilled.toString():{let{evaluationId:m,output:f,externalConversationId:y}=o.payload,v=o.meta.arg.assistantCode;if(t.emit("event",{name:"Assistant evaluation completed",data:{evaluationId:m,assistantCode:v,assistantOutput:md(f),externalConversationId:y,evaluationStatus:"success"}}),!o.meta.arg.skipState){let x=e.getState().assistants.cues;t.emit("cues",x)}break}case he.rejected.toString():{let m=o.meta.arg.assistantCode,f=(g=o.meta.arg.externalConversationId)!=null?g:(u=e.getState().conversation.current)==null?void 0:u.externalId;t.emit("event",{name:"Assistant evaluation completed",data:{evaluationId:"",assistantCode:m,assistantOutput:"",externalConversationId:f,evaluationStatus:"failed"}});break}default:break}return a},Yp=vy;var eg=require("@reduxjs/toolkit");function Aa(t){return t.toISOString().replace("T"," ").replace("Z","")}var Sy=(t,e)=>e.version,tg=(0,eg.createSelector)([In,$e,Kp,Sy],(t,e,n,o)=>{if(!e)return k.warn("No conversationId for handling time metrics"),null;let{startTime:s,stopTime:r}=n;return!s||!r?(k.warn("No startTime and stopTime for handling time metrics"),null):{conversationId:e,clientVersion:o,agentId:t==null?void 0:t.agentId,agentName:t==null?void 0:t.agentName,agentEmail:t==null?void 0:t.agentEmail,timeStart:Aa(s),timeStop:Aa(r)}});function ng(t,e){let{text:n,metrics:{numPaste:o,pastes:s,textSuggestions:r}}=t.input,i=n.length;return{source:"agent",clientVersion:e.version,pastes:s,lenTextTotal:i,numPastes:o,suggestions:r}}var ts=class extends Error{};function xy(){let t,e;return{promise:new Promise((o,s)=>{t=o,e=s}),resolve:t,reject:e}}var ti=class{constructor(){this.queues={}}push(e,n){let o=()=>{let r=this.queues[e][1];r?(this.queues[e]=[r.promise,null],r.resolve()):delete this.queues[e]};if(!this.queues[e]){let r=n().finally(o);return this.queues[e]=[r,null],r}this.queues[e][1]&&this.queues[e][1].reject(new ts("Queued async function is outdated"));let s=xy();return this.queues[e][1]=s,s.promise.then(()=>n().finally(o))}};function La(t,e){var r;let n=t.closest(e);if(n)return n;let o=t.getRootNode().host;if(o instanceof HTMLElement)return La(o,e);let s=(r=t.ownerDocument.defaultView)==null?void 0:r.frameElement;return s?La(s,e):null}function Ma(t,e){return La(t,e)}var by={accepted:"onConversationAcceptedAssistants","new-message":"onConversationNewMessageAssistants",ended:"onConversationEndedAssistants"},og=(t,e)=>{var s,r,i;if(!((i=(r=(s=t.uiConfig)==null?void 0:s.widget)==null?void 0:r.types.find(a=>a.type==="cues"))==null?void 0:i.isActive))return k.warn("Triggered a conversation assistant, but cues are not configured in widget."),[];let o=t[by[e]];return o&&o.length>0?o.map(a=>a.code):(k.warn(`No assistant set in profile for conversation event "${e}"`),[])};function sg(t){return typeof t=="object"&&t!==null&&"name"in t&&"message"in t}function Cy(t){return typeof t=="object"&&t!==null&&"tagName"in t}function ni(t){return Cy(t)&&(fn(t)||Lr(t))}var ig,tt=new Map,Ty=["bottom","height","left","right","top","width"],rg=(t,e)=>!t&&!e?!1:t&&!e||!t&&e?!0:Ty.some(n=>t[n]!==e[n]);function ag(t){var n,o,s;if(t.ownerDocument===document)return[];let e=(s=(o=(n=t.ownerDocument)==null?void 0:n.defaultView)==null?void 0:o.frameElement)!=null?s:null;return e?[e,...ag(e)]:[]}function lg(t,e){return!t||!e?null:b(h({},t),{top:t.top+e.top,left:t.left+e.left})}var oi=!1,dg=()=>{oi=!0;let t=[];if(tt.forEach((e,n)=>{if(!n.isConnected){e.rect=null,t.push(e),tt.delete(n);return}let o=n.getBoundingClientRect();rg(o,e.rect)&&(e.rect=o,t.push(e))}),t.forEach(e=>{let n=e.parentRects?e.parentRects.reduce(lg,e.rect):e.rect;rg(n,e.totalRect)&&e.callbacks.forEach(o=>o(n)),e.totalRect=n}),tt.size===0){oi=!1;return}ig=window.requestAnimationFrame(dg)};function Na(t,e){let n=ag(t),o=[],s=n.map((r,i)=>Na(r,a=>{o[i]=a;let d=tt.get(t);if(!d)return;let l=o.reduce(lg,d.rect);d.callbacks.forEach(c=>c(l))}));return{observe(r=!0){if(s.forEach(i=>i.observe(!1)),tt.has(t)){let i=tt.get(t);i.callbacks.push(e),i.rect&&e(i.rect)}else tt.set(t,{rect:void 0,callbacks:[e],parentRects:o});r&&!oi&&dg()},unobserve(){s.forEach(i=>i.unobserve());let r=tt.get(t);if(r){let i=r.callbacks.indexOf(e);i>=0&&r.callbacks.splice(i,1),r.callbacks.length||tt.delete(t),tt.size||(cancelAnimationFrame(ig),oi=!1)}}}}var cg,nt=new Map,ug=()=>{nt.forEach((t,e)=>{if(!e.isConnected){nt.delete(e);return}let{clientHeight:n,scrollHeight:o}=e,s=o>n;t.visible!==s&&(t.visible=s,t.callbacks.forEach(r=>r(t.visible)))}),nt.size!==0&&(cg=window.requestAnimationFrame(ug))};function pg(t,e){return{observe(){let n=nt.size===0;nt.has(t)?nt.get(t).callbacks.push(e):nt.set(t,{visible:void 0,callbacks:[e]}),n&&ug()},unobserve(){let n=nt.get(t);if(n){let o=n.callbacks.indexOf(e);o>=0&&n.callbacks.splice(o,1),n.callbacks.length||nt.delete(t),nt.size||cancelAnimationFrame(cg)}}}}var Oa=["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 Da(t,e,n){return n.forEach(o=>{e.style[o]=t[o]})}function Yn(t){return Number.parseFloat(t)}function si(t){return Math.round(t*1e6)}function gg(t){return t/1e6}function _a(t,e,n){if(t.boxSizing==="content-box")return;let{clientWidth:o}=e,s=Yn(t.width),r=Yn(t.borderLeftWidth),i=Yn(t.borderRightWidth),a=Yn(t.paddingRight),d=gg(si(s)-si(r)-si(i)),l=gg(si(o));if(d-l>2){let c=d-l;n.style.paddingRight=`${a+c}px`}}function ns(t,e={}){var c,p;let n=e.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=(c=e.position)!=null?c:"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",sn(n);let o=window.getComputedStyle(t),s=!0,r=()=>{n.scrollTop=t.scrollTop};Da(o,n,Oa),_a(o,t,n),e.mirrorOverflow&&(n.style.overflow="hidden",t.addEventListener("scroll",r));let i=pg(t,()=>{Da(o,n,Oa),_a(o,t,n),r(),setTimeout(r,0)}),a,d=!0,l=Na(t,u=>{if(u===null){e.onRemove&&e.onRemove(),n.remove();return}if(!d&&e.onMoveStart&&(Promise.resolve().then(()=>e.onMoveStart()),d=!0),clearTimeout(a),a=setTimeout(()=>{e.onMoveEnd&&e.onMoveEnd(),d=!1},200),u.height===0&&u.width===0){if(s===!0)return;e.onHide&&e.onHide(),n.style.display="none",s=!0;return}if(Da(o,n,Oa),_a(o,t,n),r(),e.placement==="below"&&n.classList.add("below"),n.style.top=`${u.top}px`,n.style.left=`${u.left}px`,e.closestScrollElement&&e.closestScrollElement!==t){let g=e.closestScrollElement.getBoundingClientRect(),m=window.getComputedStyle(e.closestScrollElement),f=Yn(m.borderTopWidth),y=Yn(m.borderBottomWidth),v=g.top+f-u.top,x=u.top+u.height+-(g.top+g.height-y);n.style.clipPath=`inset(${v}px 0px ${x}px 0px)`}s&&(n.style.display="block",e.onShow&&e.onShow(),s=!1)});return e.appendTo?e.appendTo.appendChild(n):(p=t.parentElement)==null||p.appendChild(n),l.observe(),i.observe(),[n,()=>{t.removeEventListener("scroll",r),l.unobserve(),i.unobserve(),n.remove()}]}function wy(t){return t.offsetParent!==null}function mg(t){if(!wy(t))return!1;let e=t.getBoundingClientRect();return e.top>=0&&e.left>=0&&e.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&e.right<=(window.innerWidth||document.documentElement.clientWidth)}function ri(t,e,n=100){let o=mg(t);e({isVisible:o});let s=setInterval(()=>{let r=mg(t);r!==o&&(o=r,e({isVisible:o}))},n);return()=>{clearTimeout(s)}}var fg=(t,e)=>({value(){try{let n=sessionStorage.getItem(`dd-${t}`);if(!n)return e;try{return JSON.parse(n)}catch(o){return e}}catch(n){return e}},update(n){try{sessionStorage.setItem(`dd-${t}`,JSON.stringify(n))}catch(o){k.warn("[Deepdesk] SessionStorage is blocked by browser")}}});var B=require("react/jsx-runtime");var hg=fg("showTabHint",!0),eo=class eo{constructor({deepdeskUrl:e,version:n=eo.version||"unknown",locale:o="en-US",token:s,fetch:r,productName:i,createCustomChannel:a,websocketClient:d=Zr}){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 ti;this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;let l=e.replace(/\/api$/,"");this.deepdeskApi=new xt(l,{token:s,fetch:r}),this.version=n,this.instanceId=eo.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[Yp({broadcast:(m,f,y)=>{this.broadcastEvents.send(m,f,y)},emit:(m,f)=>this.emit(m,f),handleAfterSendMessage:m=>this.handleAfterSendMessage(m),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:m=>this.logSendMessage(m),onUpdateShowTabHint:m=>hg.update(m),sendEvent:(m,f)=>this.deepdeskApi.sendEvent(m,f)})]};this.store=Qp(c),this.broadcastEvents=new _p({debug:!0,deepdeskUrl:l,eventMap:Ql(this.store),createCustomChannel:a}),this.disposeHandlers.push(()=>{this.broadcastEvents.cleanup()}),this.ws=new d({url:`${l}/api/v2/me/realtime`.replace("https","wss"),reconnectInterval:25e3,shouldReconnect:()=>S(this,null,function*(){var m;return(m=se(this.state))!=null?m:!1})}),this.whenLoggedIn(()=>this.ws.connect()),this.store.dispatch(Bo(hg.value())),this.store.dispatch(Ks({locale:o,adminUrl:l,productName:i}));let p=[],u=m=>{if(!m.conversationId)return;let f=()=>{this.conversationId()===m.conversationId&&this.store.dispatch(vd(m))};this.hasConversation()?f():p.push(f)};this.ws.on("assistants::direct_response",u),this.ws.on("assistants::user_notification",u),this.ws.on("assistants::response_chunk",m=>{if(!m.conversationId)return;let f=()=>{this.conversationId()===m.conversationId&&this.store.dispatch(yd(m))};this.hasConversation()?f():p.push(f)}),this.ws.on("assistants::suggest_as_reply",m=>{if(!m.conversationId)return;let f=()=>{this.conversationId()===m.conversationId&&this.store.dispatch(Pn([{text:m.payload.message,type:"text",source:"assistant",assistantCode:m.code,sourceLabel:m.name}]))};this.hasConversation()?f():p.push(f)});let g=this.whenConversationLoaded(()=>{var m;this.broadcastEvents.setExternalId((m=this.state.conversation.current)==null?void 0:m.externalId),p.forEach(f=>f()),p.length=0});this.disposeHandlers.push(()=>{this.ws.cleanup(),p.length=0,g()})}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){var e;return(e=Jt(this.state)[this.state.input.selectedSuggestionIndex])!=null?e: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?(k.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(k.warn("Profile has not been loaded (yet)"),!0):(k.warn("No conversation loaded (yet)"),!0)}whenLoggedIn(e){if(se(this.state))e();else{let n=this.subscribe(se,o=>{o&&e()});this.disposeHandlers.push(()=>{n()})}}login(){return this.store.dispatch(En(null)),this.store.dispatch(rt()),new Promise(e=>{this.whenLoggedIn(()=>e())})}isLoggedIn(){return S(this,null,function*(){return(yield this.store.dispatch(rt())).payload})}isConversationSupported(e,n){return S(this,null,function*(){return(yield this.store.dispatch(gi({externalId:e,options:n}))).payload})}createConversation(e){return S(this,null,function*(){var o;return this.hasConversation()&&this.externalId()!==e.externalId&&this.resetConversation(),(yield this.store.dispatch(ys(b(h({},e),{metadata:(o=e.metadata)!=null?o:{}})))).payload})}getConversationByExternalId(e,n){return S(this,null,function*(){return this.hasConversation()&&this.externalId()!==e&&this.resetConversation(),(yield this.store.dispatch(vs({externalId:e,options:n}))).payload})}upsertConversation(e){return S(this,null,function*(){var o;return this.hasConversation()&&this.externalId()!==e.externalId&&this.resetConversation(),(yield this.store.dispatch(mi(b(h({},e),{metadata:(o=e.metadata)!=null?o:{}})))).payload})}postMessages(e){return S(this,null,function*(){yield this.store.dispatch(fi(e))})}updateConversation(e){return S(this,null,function*(){return(yield this.store.dispatch(Ss(e))).payload})}resetConversation(){this.store.dispatch(Y()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}configure(e){this.store.dispatch(Ks(e))}setVisitorInfo(e){this.store.dispatch(Ul(e))}setCustomData(e){this.store.dispatch(Kl(e))}setAgentInfo(e,n){return S(this,null,function*(){var s;yield this.store.dispatch(io(h(h({},e),n))),(s=this.state.info.agentInfo)!=null&&s.agentNickname||this.broadcastEvents.send(ks,{showNicknameDialog:!0})})}setAgentSettings(e){return S(this,null,function*(){yield this.store.dispatch(yi(e))})}getAgentSettings(){return S(this,null,function*(){return(yield this.store.dispatch(vi())).payload})}refresh(){return S(this,null,function*(){if(this.shouldAbort())return Promise.resolve();let e=[];return e.push(this.refreshTextSuggestions()),e.push(this.refreshWidgetSuggestions()),Promise.all(e).then(()=>{})})}syncInputMediator(){this.inputMediator&&this.store.dispatch(Cs({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),suggestionTextStart:this.inputMediator.getSuggestionTextStart()}))}notifyExternalSuggestion(e){this.store.dispatch(Se(e))}evaluateAssistant(e,n){return S(this,null,function*(){var c;let{input:o={},attachments:s=[],transcript:r,showCuesInWidget:i=!0,includeMetadata:a,externalConversationId:d}=n||{},l=yield this.store.dispatch(he({assistantCode:e,attachments:s,transcript:r,includeMetadata:a,input:o,externalConversationId:d,skipState:!i}));if(l.error)throw new Error(`Assistant evaluation failed: ${(c=l.payload)!=null?c:l.error.message}`);return l.payload.output})}evaluateConversationAssistant(e,n){return S(this,null,function*(){var c,p,g;yield this.loadProfileConfig();let o=this.state.profile.data;if(!o&&((c=this.state.conversation.current)!=null&&c.profileCode)&&(yield this.loadProfileConfig(),o=this.state.profile.data),!o){k.warn("Can't evaluate assistant when profile is not loaded yet.");return}let s=og(o,e),r=(p=n==null?void 0:n.showCuesInWidget)!=null?p:!0,u=n!=null?n:{},{showCuesInWidget:i}=u,a=O(u,["showCuesInWidget"]),d=(g=n==null?void 0:n.externalConversationId)!=null?g:this.hasConversation()?this.externalId():"",l=yield Promise.all(s.map(m=>this.queues.push(m,()=>S(this,null,function*(){var y,v;let f=yield this.store.dispatch(he(h(b(h({assistantCode:m,includeMetadata:!0},a),{skipState:!r}),n!=null&&n.attachments&&(n==null?void 0:n.attachments.length)>0?{attachments:n==null?void 0:n.attachments}:{})));if(f.error)throw new Error(`Assistant evaluation failed: ${(y=f.payload)!=null?y:f.error.message}`);return{assistantCode:m,evaluationId:f.payload.evaluationId,output:f.payload.output,externalConversationId:(v=f.payload.externalConversationId)!=null?v:d}})).catch(f=>{if(f instanceof ts)return k.warn(`Queued assistant "${m}" was outdated and dropped`),null;throw f})));if(!r)return l.filter(m=>m!==null)})}handleKeyDown(e){let{overlayCollapsed:n,openOverlayWhenTyping:o}=this.state.ui,{textSuggestions:s,selectedSuggestionIndex:r,selection:i}=this.state.input,{inlineSuggestions:a,autoSelectSuggestion:d,showTextSuggestions:l,suggestionsPlacement:c}=this.settings,p=a||d,u=c==="inline"||c==="below"?"below":"above",g=s.length>0;if(this.store.dispatch(Rl(hi(e))),!Qe(this.state)||e.key!=="Tab"&&!l)return;let m=()=>{n||!g||i&&(e.shiftKey||(this.store.dispatch(Al()),e.preventDefault()))},f=()=>{n||!g||p&&r<=0||i&&(e.shiftKey||(this.store.dispatch(Ll()),e.preventDefault()))};switch(e.key){case"ArrowUp":u==="below"?f():m();break;case"ArrowDown":{u==="below"?m():f();break}case"Escape":{n||(this.store.dispatch(bs(-1)),this.store.dispatch(Dt({collapse:!0})),this.store.dispatch(iu(!0)),e.preventDefault());break}case"Tab":{e.preventDefault();let y=Rn(this.state);if(!y)return;this.store.dispatch(Bo(!1)),this.store.dispatch(Se({text:y.text,suggestion:y,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(p||this.state.input.selectedSuggestionIndex===-1)return;let y=Rn(this.state);if(!y)return;this.store.dispatch(Se({text:y.text,suggestion:y,eventMetrics:{inputType:"space"},replace:"until-selection-end"}));break}case"Enter":{if(p||e.shiftKey||this.state.input.selectedSuggestionIndex===-1)return;let y=Rn(this.state);if(!y)return;this.store.dispatch(Se({text:y.text,suggestion:y,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),e.preventDefault();break}default:}n&&o&&this.store.dispatch(Dt({collapse:!1}))}handleAfterSendMessage(e){this.emit("send-message",e),this.store.dispatch(Rt([]))}handlingTimeStart(){this.state.handlingTime.startTime||(k.info("Start handling time"),this.store.dispatch(zp()))}handlingTimeStop(){this.state.handlingTime.startTime&&(k.info("Stop handling time"),this.store.dispatch(Yr()))}logSendMessage(e){let n=ng(this.state,{version:this.version});n&&(e&&(Object.assign(n,{text:e}),Object.assign(n,{lenTextTotal:e.length})),this.deepdeskApi.sendEvent("Send Message",{conversationId:this.conversationId(),data:n}),this.emit("send-message-event",n))}logHandlingTime(){let e=tg(this.state,{version:this.version});e&&(this.deepdeskApi.sendEvent("Handling Time",{conversationId:this.conversationId(),data:e}),this.store.dispatch(Vp()))}notifySubmit(e={}){var n;this.shouldAbort()||(this.store.dispatch(Zt((n=e.text)!=null?n:this.state.input.text)),this.store.dispatch(Nl()))}emit(e,n){let o=this.eventListeners[e];o&&o.forEach(s=>{try{s(n)}catch(r){k.warn(`The following error occurred in deepdeskSDK.on('${e}', handler)`),k.error(r)}})}on(e,n){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(n),()=>{this.off(e,n)}}off(e,n){if(!e&&!n){this.eventListeners={};return}let o;this.eventListeners[e]&&(o=this.eventListeners[e].indexOf(n),o>-1&&this.eventListeners[e].splice(o,1))}setConversationQuery(e){this.dynamicThunkObject.conversationQuery=e}setPlatformVariables(e){this.store.dispatch(Wl(e))}whenConversationLoaded(e){let n=r=>{var i;return(i=r.conversation.current)==null?void 0:i.id},o=()=>this.loadProfileConfig().then(()=>e());return n(this.state)&&o(),this.subscribe(n,r=>{r&&o()})}overlayContainerFactory(e,n,o,s){let[r,i]=ns(n,o);return r.setAttribute("translate","no"),r.dataset.testid=e,s&&r.classList.add(s),[r,i]}createInlineContainer(e,n){var a;let o=document.createElement("div");o.style.position="absolute",o.style.top="0px",o.style.left="0px",o.style.height="0px",o.style.width="0px";let s=document.createElement("div");s.style.display="none",s.style.position="absolute",s.style.height="0px",s.style.width="0px",s.style.backgroundColor="red",o.appendChild(s);let r=(a=e.ownerDocument.defaultView)==null?void 0:a.frameElement,i=r?r.ownerDocument.defaultView:null;if(r&&(i===window||(i==null?void 0:i.parent)===window)){let[d,l]=ns(r,{appendTo:document.body,onMoveStart:()=>{s.style.display="none"}});d.dataset.testid=n,d.style.zIndex="2",d.appendChild(o),this.unmountHandlers.push(()=>{l()})}else document.body.appendChild(o);return s}createContainer(e,n=document.body){let o=window.getComputedStyle(n),s=document.createElement("div");return sn(s),s.dataset.testid=e,s.style.color=o.color,s.style.fontSize=o.fontSize,s.style.fontFamily=o.fontFamily,s.style.fontVariant=o.fontVariant,s.setAttribute("translate","no"),n.appendChild(s),s}storeMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,n=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(e,n),k.info(`Stored analytics for ${this.conversationId()}`)}catch(e){}}restoreMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,n=window.sessionStorage.getItem(e);if(!n)return;let o=JSON.parse(n);o.text.trim()===this.state.input.text.trim()?(k.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(Ml(o.metrics))):k.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(e)}catch(e){}}mount(e,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!ni(e))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let u=n,{customStyles:o,closestScrollSelector:s,floatingMenuParent:r,appendOverlayTo:i,inputMediator:a}=u,d=O(u,["customStyles","closestScrollSelector","floatingMenuParent","appendOverlayTo","inputMediator"]),l={customStyles:o,closestScrollSelector:s,floatingMenuParent:r,appendOverlayTo:i};this.configure(d),this.settings.automaticHandlingTime&&this.setupHandlingTime(e),sn(e),this.inputMediator=a||(fn(e)?new vn(e):new yn(e)),this.inputMediator.on("change",({plainText:g,rawHTML:m,suggestionTextStart:f})=>{this.store.dispatch(Cs({text:g,html:m,suggestionTextStart:f}))}),this.inputMediator.on("keyup",g=>{this.store.dispatch(Pl(hi(g)))}),this.inputMediator.on("keydown",g=>{this.handleKeyDown(g)}),this.inputMediator.on("paste",({pastedText:g,selectionText:m})=>{this.store.dispatch(Il({text:g,selectionText:m}))}),this.inputMediator.on("cut",({selectionText:g})=>{this.store.dispatch(kl(g))});let c;this.inputMediator.on("selection",g=>{clearTimeout(c),g===null?c=setTimeout(()=>{g!==null&&this.store.dispatch(Ts(g))},500):this.store.dispatch(Ts(g))}),this.unmountHandlers.push(()=>{clearTimeout(c)}),this.inputMediator.on("disabled",()=>{var g;(g=this.inputMediator)==null||g.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(br(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(br(!0))}),this.renderSuggestions(e,l),this.subscribe(nn("inlineSuggestions"),()=>{this.renderSuggestions(e,l)}),this.subscribe(nn("suggestionsPlacement"),()=>{this.renderSuggestions(e,l)});let p=this.renderOverlays(n);this.unmountHandlers.push(()=>{p.unmount()}),this.store.dispatch(Cs({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),suggestionTextStart:this.inputMediator.getSuggestionTextStart()})),this.store.dispatch(Ts(this.inputMediator.getSelection())),this.store.dispatch(br(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(e){if(this.nicknameDialogUnsubscribe||this.nicknameDialogFailed)return;let n=this.createContainer("nickname-dialog",document.body);document.body.appendChild(n);let o=(0,bt.createRoot)(n),s=null,r=a=>{s=a,i()},i=()=>{o==null||o.render((0,B.jsx)(mt,{store:this.store,children:(0,B.jsx)(at,{broadcastEvents:this.broadcastEvents,children:(0,B.jsx)(wu,{id:"deepdesk-nickname-dialog",error:s,onSave:a=>S(this,null,function*(){try{yield this.store.dispatch(Hl({agentNickname:a})).unwrap(),console.log("setAgentNickname",a),this.broadcastEvents.send(ks,{showNicknameDialog:!1}),this.nicknameDialogUnsubscribe&&this.nicknameDialogUnsubscribe()}catch(d){k.error("Error setting agent nickname",d),r("error"),this.nicknameDialogFailed=!0}})})})}))};i(),this.nicknameDialogUnsubscribe=()=>{o.unmount(),n.remove(),this.nicknameDialogUnsubscribe=null}}subscribe(e,n){let o=e(this.store.getState());return this.store.subscribe(()=>{let s=e(this.store.getState());s!==o&&(o=s,n(o))})}unmount(){var e,n,o,s,r;(e=this.inlineSuggestions)==null||e.unmount(),(n=this.aboveSuggestions)==null||n.unmount(),(o=this.belowSuggestions)==null||o.unmount(),(s=this.floatingMenu)==null||s.unmount(),this.unmountHandlers.forEach(i=>i()),this.unmountHandlers=[],(r=this.inputMediator)==null||r.dispose(),this.nicknameDialogUnsubscribe&&this.nicknameDialogUnsubscribe(),this.isMounted=!1}dispose(){this.unmount(),this.unmountWidget(),this.disposeHandlers.forEach(e=>e()),this.disposeHandlers=[],this.off()}renderSuggestions(e,n){var o,s,r,i;(o=this.floatingMenu)==null||o.unmount(),(s=this.inlineSuggestions)==null||s.unmount(),(r=this.aboveSuggestions)==null||r.unmount(),(i=this.belowSuggestions)==null||i.unmount(),this.settings.floatingMenu&&(this.floatingMenu=this.renderFloatingMenu(e,n)),this.settings.inlineSuggestions||this.settings.suggestionsPlacement==="inline"?this.inlineSuggestions=this.renderInlineSuggestions(e,n):this.settings.suggestionsPlacement==="below"?this.belowSuggestions=this.renderAboveOrBelowSuggestions(e,n,"below"):this.aboveSuggestions=this.renderAboveOrBelowSuggestions(e,n,"above")}renderInlineSuggestions(e,n){let{customStyles:o}=n,s=this.createInlineContainer(e,"deepdesk-caret"),r=(0,bt.createRoot)(s);r.render((0,B.jsx)(mt,{store:this.store,customStyles:o,children:(0,B.jsx)(at,{broadcastEvents:this.broadcastEvents,children:(0,B.jsx)(bu,{})})}));let i=a=>{a?(s.style.display="block",s.style.top=`${a.top}px`,s.style.left=`${a.left}px`):s.style.display="none"};return this.inputMediator.on("caretposition",i),{unmount:()=>{var a;(a=this.inputMediator)==null||a.off("caretposition",i),r.unmount(),s.remove()}}}renderAboveOrBelowSuggestions(e,n,o){let{customStyles:s,closestScrollSelector:r,appendOverlayTo:i}=n,a=r&&Ma(e,r)||void 0,[d,l]=this.overlayContainerFactory("deepdesk-tab-completion",a||e,{appendTo:i,closestScrollElement:a,mirrorOverflow:!0,onRemove:()=>this.unmount()},s==null?void 0:s.rootNode),[c,p]=this.overlayContainerFactory("deepdesk-suggestions-overlay",a||e,{appendTo:i,placement:o},s==null?void 0:s.suggestionsRootNode),u=(0,bt.createRoot)(d);u.render((0,B.jsx)(mt,{store:this.store,customStyles:s,children:(0,B.jsx)(at,{broadcastEvents:this.broadcastEvents,children:(0,B.jsx)(np,{inputElement:e})})}));let g=(0,bt.createRoot)(c);return g.render((0,B.jsx)(mt,{store:this.store,customStyles:s,children:(0,B.jsx)(at,{broadcastEvents:this.broadcastEvents,children:(0,B.jsx)(Du,{onLogIn:()=>this.loginViaPopup().catch(m=>k.warn(m.message))})})})),{unmount(){u.unmount(),g.unmount(),l(),p()}}}renderFloatingMenu(e,n){let{customStyles:o,closestScrollSelector:s,appendOverlayTo:r,floatingMenuParent:i}=n,a=s&&Ma(e,s)||void 0,[d,l]=this.overlayContainerFactory("floating-menu",a||e,{appendTo:i!=null?i:r},o==null?void 0:o.floatingMenuParent),c=(0,bt.createRoot)(d);return c.render((0,B.jsx)(mt,{store:this.store,customStyles:o,children:(0,B.jsx)(at,{broadcastEvents:this.broadcastEvents,children:(0,B.jsx)(ou,{onLogIn:()=>this.loginViaPopup().catch(p=>k.warn(p.message))})})})),{unmount(){c.unmount(),l()}}}renderOverlays(e){let{customStyles:n}=e,o=this.createContainer("deepdesk-overlays"),s=(0,bt.createRoot)(o);return s.render((0,B.jsx)(mt,{store:this.store,customStyles:n,children:(0,B.jsx)(at,{broadcastEvents:this.broadcastEvents,children:(0,B.jsx)(Jc,{})})})),{unmount(){s.unmount(),o.remove()}}}renderWidget(e,n={}){if(this.widgetElement&&k.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:o,showImages:s,isEmbedded:r,signInViaPopup:i,ssoUrl:a,openAdminFeedback:d}=n;this.widgetElement=e,this.configure({showImages:s,isEmbedded:r,signInViaPopup:i});let l;if(a)try{l={url:new URL(a,this.settings.adminUrl).toString()}}catch(c){k.warn(`Invalid ssoUrl '${a}' passed to renderWidget`)}this.widgetRoot=(0,bt.createRoot)(e),this.widgetRoot.render((0,B.jsx)(mt,{store:this.store,customStyles:o,children:(0,B.jsx)(at,{broadcastEvents:this.broadcastEvents,children:(0,B.jsx)(Ap,{assistantOptions:n.assistantOptions,knowledgeAssistOptions:n.knowledgeAssist,openAdminFeedback:d,onLogIn:()=>this.loginViaPopup(l).catch(c=>k.warn(c.message))})})}))}unmountWidget(){var e,n;(n=(e=this.widgetRoot)==null?void 0:e.unmount)==null||n.call(e),this.widgetRoot=null,this.widgetElement=null}renderKnowledgeAssistantWidget(e,n,o={}){let{customStyles:s,initialQuestion:r}=o,i=(0,bt.createRoot)(n);return i.render((0,B.jsx)(mt,{store:this.store,customStyles:s,children:(0,B.jsx)(at,{broadcastEvents:this.broadcastEvents,children:(0,B.jsx)(Ea,{children:(0,B.jsxs)(nr,{assistantCode:e,initialQuestion:r,evaluateKnowledgeAssistFn:bo,children:[(0,B.jsx)(Tn,{children:(0,B.jsx)(sr,{title:o.title,emptyState:o.emptyState})}),(0,B.jsx)(wa,{children:(0,B.jsx)(or,{})})]})})})})),{unmount(){i.unmount()}}}setupHandlingTime(e){let n=ri(e,({isVisible:o})=>{o?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){sg(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfig(){var e;return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(e=this.state.conversation.current)!=null&&e.profileCode?(this.loadProfileConfigPromise=Promise.resolve().then(()=>S(this,null,function*(){yield this.store.dispatch(ko()).unwrap();let n=Lt(this.state);n&&this.store.dispatch(Ks({showSearch:n.search,showImageSearch:n.imageSearch,showEntitiesCommand:n.entitiesCommand,showSummaryCommand:!!n.summarizerAssistantNew,showKnowledgeSearch:!!n.knowledgeAssistantNew||!!n.knowledgeAssistant,recommendTextSuggestions:n.recommendTextSuggestions}))})).finally(()=>{Lt(this.state)||(this.loadProfileConfigPromise=null)}),this.loadProfileConfigPromise):Promise.resolve()}loginViaPopup(e){return S(this,null,function*(){return new Promise((n,o)=>{this.store.dispatch(fs());let s=new MessageChannel,r=s.port1,i=this.settings.adminUrl,a=new URL(e!=null&&e.url?e==null?void 0:e.url:`${i}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let d=!1,l=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",p),clearInterval(u)};r.onmessage=g=>S(this,null,function*(){var m,f;if((m=g.data)!=null&&m.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((f=g.data)==null?void 0:f.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(lo),d=!0,s.port1.close(),n()}catch(y){console.error(y),o(y)}finally{d=!0,l()}});let c=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");c===null&&o(new Error("Popup blocked by browser"));let p=g=>S(this,null,function*(){var m;if(g.origin===a.origin)switch((m=g.data)==null?void 0:m.type){case"deepdesk-popup-request-origin":{try{let f=JSON.stringify({type:"deepdesk-popup-parent-origin"});c==null||c.postMessage(f,a.origin)}catch(f){k.error("Error posting message to popup",f),o(f)}break}case"deepdesk-popup-loaded":{try{let f=JSON.stringify({type:"deepdesk-popup-create-channel"});c==null||c.postMessage(f,a.origin,[s.port2])}catch(f){k.error("Error posting message to popup",f),o(f)}break}case"deepdesk-popup-error":{if(l(),g.data.message==="Platform account url mismatch"){let f=`Please contact your administrator: The platform account url (${g.data.targetOrigin}) is misconfigured as it differs from the origin of the page that opened the popup (${g.data.openerOrigin}).`;k.warn(f),this.store.dispatch(pi(f)),o(new Error(f))}if(g.data.message==="Timeout"){let f="Please contact your administrator: Popup timed out. Check if the account's platform url is configured correctly.";k.warn(f),this.store.dispatch(pi(f)),o(new Error(f))}o(new Error(g.data.message));break}}});window.addEventListener("message",p);let u=setInterval(()=>{c&&!c.closed||(l(),d||o(new Error("Popup closed by user")))},200);this.disposeHandlers.push(l)})})}translateMessages(e){return this.deepdeskApi.translateMessages(e)}refreshTextSuggestions(){return S(this,null,function*(){this.isMounted&&(yield this.store.dispatch(yr()))})}refreshWidgetSuggestions(){return S(this,null,function*(){if(!this.widgetRoot)return;let{uiConfig:e}=this.state.profile.data;if(!e.widget)return;let n=Ro(this.state);try{n.forEach(({type:o})=>{switch(o){case"entities":this.store.dispatch(Ue());break;case"pinned-messages":case"sticky-messages":break;default:gs.includes(o)||this.store.dispatch(Ke(o))}})}catch(o){this.handleError(o)}})}};eo.version="19.6.0",eo.count=0;var os=eo;function Ey(t){return S(this,null,function*(){var s,r,i;let n=yield((s=t.fetch)!=null?s:window.fetch)(t.url),o=yield n.blob();return new File([o],t.name,{type:(i=(r=t.mimeType)!=null?r:n.headers.get("Content-Type"))!=null?i:"image/jpeg"})})}function yg(t,e){return S(this,null,function*(){let n=yield Ey(e),o=new Event("change",{bubbles:!0,cancelable:!0});try{Object.defineProperty(t,"files",{configurable:!0,get:()=>[n]}),t.dispatchEvent(o)}finally{Object.hasOwn(t,"files")&&delete t.files}})}function vg(t,e,n){return S(this,null,function*(){yield new xt(t).authenticateWithKey(e,n)})}function Sg(t){return t.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function xg(o,s){return S(this,arguments,function*(t,e,n={}){var p,u;let{value:r}=t,{start:i,end:a}=(p=n.replace)!=null?p:{start:0,end:r.length},d=`${r.slice(0,i)}${e}${r.slice(a)}`,l=(u=n.selectionAfter)!=null?u:{start:i+e.length,end:i+e.length},c=()=>{if(n.setValue)return n.setValue(d);t.value=d};return Promise.resolve(c()).then(()=>{t.selectionStart=l.start,t.selectionEnd=l.end,t.blur(),t.focus()})})}function bg(o,s){return S(this,arguments,function*(t,e,n={}){let r=n.replace?Kt(t,n.replace.start,n.replace.end):Qn(t),i,a=()=>{if(n.setRange)return n.setRange(r.cloneRange());r.deleteContents(),i=document.createElement("span"),r.insertNode(i),n.insertBRs!==!1?e.split(`
12
+ `).reverse().forEach((d,l)=>{l>0&&r.insertNode(document.createElement("br")),r.insertNode(document.createTextNode(d))}):r.insertNode(document.createTextNode(e))};return Promise.resolve(a()).then(()=>{try{if(n.selectionAfter!==!1){t.focus();let d=n.selectionAfter?Kt(t,n.selectionAfter.start,n.selectionAfter.end):(r.collapse(!1),r),l=window.getSelection();l==null||l.removeAllRanges(),l==null||l.addRange(d)}if(!i)return;i.scrollIntoView&&i.scrollIntoView({block:"nearest",inline:"nearest"})}finally{i&&i.remove()}})})}function ky(t){let e=document.createElement("template");return e.innerHTML=t.replace(/(\[([^\]]+)])\(([^)]+)\)/g,'<a href="$3" target="_blank" rel="noopener noreferrer">$2</a>'),e.content}function Ry(t){let e=document.createDocumentFragment();return t.split(`
13
+ `).forEach((n,o)=>{o>0&&e.appendChild(document.createElement("br"));let s={index:0},r=0;for(;s=n.slice(r).match(/(\[([^\]]+)])\(([^)]+)\)/);){let i=document.createElement("a");i.href=s[3],i.setAttribute("target","_blank"),i.setAttribute("rel","noopener noreferrer"),i.appendChild(document.createTextNode(s[2])),e.appendChild(document.createTextNode(n.slice(r,r+s.index))),e.appendChild(i),r=r+s.index+s[0].length}e.appendChild(document.createTextNode(n.slice(r)))}),e}function Cg(t,e){let n=t.parentElement;if(!n){console.warn("No insert point found");return}let{display:o}=window.getComputedStyle(n);o.includes("block")||o==="table-cell"?n==null||n.insertBefore(e,t.nextSibling):Cg(n,e)}function Tg(s,r){return S(this,arguments,function*(t,e,{isBlock:n,isHTML:o}={}){let i;t.dispatchEvent(new InputEvent("beforeinput",{inputType:"insertText",data:e,bubbles:!0,cancelable:!0}));let a=()=>{var u;let d=(u=t.ownerDocument.defaultView)!=null?u:window,l=d.getSelection();if((!l||l.rangeCount===0)&&(t.focus(),l=d.getSelection()),!l||l.rangeCount===0)return;let c=l.getRangeAt(0);if(!c)return;i=document.createElement("span"),c.insertNode(i);let p=o?ky(e):Ry(e);n?Cg(c.startContainer,p):(c.insertNode(p),c.collapse(!1))};return Promise.resolve(a()).then(()=>{if(t.dispatchEvent(new InputEvent("input",{inputType:"insertText",data:e,bubbles:!0,cancelable:!0})),t.focus(),!!i)try{i.scrollIntoView&&i.scrollIntoView({block:"nearest",inline:"nearest"})}finally{i&&i.remove()}})})}0&&(module.exports={Card,ContentEditableInput,DeepdeskAPI,DeepdeskSDK,HTTPClient,InputMediator,InputType,KeyboardHint,Label,Locale,Section,SectionList,Sources,Suggestion,SuggestionList,TextAreaInput,ToggleButton,attachFile,authenticateWithKey,createFullRange,createOverlayContainer,createRangeFromOffsets,escapeHTML,formatTextMarkup,getRangeOffsets,getRangeText,insertCKEditor,isHTML,isSupportedInputElement,logEvent,updateContentEditable,updateTextArea,useClickOutsideRoot,useStyles,waitForElementVisibilityChange});