@deepdesk/deepdesk-sdk 10.0.0 → 10.1.1

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.esm.js CHANGED
@@ -1,6 +1,6 @@
1
- var Du=Object.defineProperty;var B=(t,e)=>{for(var n in e)Du(t,n,{get:e[n],enumerable:!0})};var Hr=/(?:[.,;:!?\\n]|:\\)|:\\(|:-\\)|:-\\()/g,Qe=/(((\$!\{)|(\{))[a-zA-Z0-9_.]+\})/g;var Fr=/x-deepdesk-(([a-z0-9\-_])+-version)/,He=(p=>(p.SEARCH="search",p.TEMPLATE="template",p.ELASTIC_SEARCH="studio-search",p.GPT="gpt",p.TRIE="trie",p.TRIE_WITH_TYPOS="trie-with-typos",p.SEMANTIC="semantic",p.TEXT_RECOMMENDATION="text_recommendation",p.URL_RECOMMENDATION="url_recommendation",p.LINK_RECOMMENDATION="link_recommendation",p.PERSONAL_COLLECTION="personal-collection",p.PERSONAL_COLLECTION_SEARCH="personal-collection-search",p))(He||{}),Fe=(s=>(s.TAB="tab",s.ARROW="arrow",s.HOTKEY="hotkey",s.MOUSE="mouse",s))(Fe||{});import{render as Fo,unmountComponentAtNode as Or}from"react-dom";import{Fragment as tg}from"react";import{createSlice as Hu}from"@reduxjs/toolkit";import{useSelector as Fu}from"react-redux";var dn=(n=>(n.NL_NL="nl-NL",n.EN_US="en-US",n))(dn||{});var Bu={locale:"en-US",deanonymize:!1,fallbackImage:!1,isEmbedded:!1,showAutoflows:!1,showCustomMessages:!1,showImages:!1,showPersonalCollectionLink:!1,showSearch:!1,showImageSearch:!1,showStyleSuggestions:!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,inlineSuggestions:!1,adminUrl:void 0},Br=Hu({name:"settings",initialState:Bu,reducers:{set(t,e){Object.entries(e.payload).forEach(n=>{let[o,s]=n;typeof s>"u"||(t[o]=s)})}}}),{set:_t}=Br.actions,Vo=t=>e=>e.settings[t],E=t=>Fu(Vo(t)),Kr=Br.reducer;import{useState as $d}from"react";import{useDispatch as Xd,useSelector as Rs}from"react-redux";import{createAction as Be,createSlice as Gu}from"@reduxjs/toolkit";import{diffChars as $u}from"diff";import{useSelector as Xu}from"react-redux";function Ur(t){return typeof t=="object"&&!Array.isArray(t)&&t!==null}function be(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)=>be(r,e[i],n-1)):Ur(t)&&Ur(e)?Object.keys(t).length!==Object.keys(e).length?!1:Object.keys(t).every(i=>be(t[i],e[i],n-1)):!1}function Ku(t){return Math.max(...t.map(e=>e.length))}function Uu(t,e){let n=t.reduce((o,s)=>{if(s){let r=o[s]?o[s]+1:1;return{...o,[s]:r}}return o},{});return Object.keys(n).reduce((o,s)=>(n[s]<e&&o.push(s),o),[])}function Vr(t,e){let o=[...t.map(({text:s})=>s.split(/\b(\w+)\b/))];for(let s=0;s<Ku(o);s++){let r=Uu(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 Vu=2;function qo(t,e=""){if(t.length===0)return;if(t.length===1)return t[0];let n=Vr(t,Vu);return n&&n.text!==e?n:t[0]}import{createAction as qu,createAsyncThunk as Ze,createSlice as ju}from"@reduxjs/toolkit";var qr={current:null,isSupported:null},k=qu("resetConversation"),mn=t=>{let{current:e}=t.conversation;return(e==null?void 0:e.sessionId)||null},gn=t=>{let{current:e}=t.conversation;return(e==null?void 0:e.id)||null},fn=t=>t.conversation.isSupported,jo=Ze("conversation/isSupported",(t,e)=>{let{deepdeskAPI:n}=e.extra;return n.isConversationSupported(t.sessionId,t.options)}),hn=Ze("conversation/create",(t,e)=>{let{deepdeskAPI:n}=e.extra;return n.createConversation(t)}),yn=Ze("conversation/bySessionId",(t,e)=>{let{deepdeskAPI:n}=e.extra;return n.getConversationBySessionId(t.sessionId,t.options)}),Sn=Ze("conversation/update",(t,e)=>{let{deepdeskAPI:n}=e.extra,o=gn(e.getState());if(!o)throw new Error("No current conversation to update");return n.updateConversation(o,t)}),zo=Ze("conversation/upsert",(t,e)=>{let{deepdeskAPI:n}=e.extra;return n.getConversationBySessionId(t.sessionId).catch(()=>null).then(o=>{if(!o)return n.createConversation(t);let{agentId:s,agentName:r,agentEmail:i,agentNickname:a,tags:l}=t;return n.updateConversation(o.id,{agentId:s,agentEmail:i,agentName:r,agentNickname:a,tags:l})})}),vn=Ze("conversation/postMessages",(t,e)=>{let{deepdeskAPI:n}=e.extra,o=gn(e.getState());if(!o)throw new Error("No current conversation to update messages");return n.postMessages(o,t.map(s=>({...s})))}),zu=[hn.rejected,yn.rejected,Sn.rejected,vn.rejected].map(t=>t==null?void 0:t.toString()),Wu=ju({name:"conversation",initialState:qr,reducers:{},extraReducers:t=>{t.addCase(jo.fulfilled,(e,n)=>{e.isSupported=n.payload}).addCase(hn.fulfilled,(e,n)=>{var o;e.current=n.payload,e.isSupported=((o=n.payload)==null?void 0:o.hasActiveProfile)??null}).addCase(yn.fulfilled,(e,n)=>{var o;e.current=n.payload,e.isSupported=((o=n.payload)==null?void 0:o.hasActiveProfile)??null}).addCase(zo.fulfilled,(e,n)=>{var o;e.current=n.payload,e.isSupported=((o=n.payload)==null?void 0:o.hasActiveProfile)??null}).addCase(Sn.fulfilled,(e,n)=>{var o;e.current=n.payload,e.isSupported=((o=n.payload)==null?void 0:o.hasActiveProfile)??null}).addCase(vn.fulfilled,(e,n)=>{e.current&&(e.current.messages=n.payload)}).addCase(k,()=>qr).addMatcher(e=>zu.includes(e.type),(e,n)=>{throw new Error(n.error.message)})}}),jr=Wu.reducer;var we={text:"",html:null,selection:{start:0,end:0},stagedSuggestion:null,userCommitted:{text:"",selection:{start:0,end:0}},tabCompletionSuggestion:void 0,previousKeyDownEvent:null,textSuggestions:[],selectedSuggestionIndex:-1,metrics:{numCharsTyped:0,numCharsPasted:0,numCharsCut:0,numCharsDeleted:0,numPaste:0,agentStartedTypingTimestamp:null,pastes:[],deletions:[],offeredTextSuggestions:[],textSuggestions:[],cuts:[]}};function Cn(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 Tn=Be("input/replaceText"),bn=Be("input/keyDown"),Pt=Be("input/sendMessage"),wn=Be("input/sendEditSuggestionMessage"),En=Be("input/uiInputChange"),_n=Be("input/applyImageSuggestion"),ae=Be("input/sendEvent");function xn(t){if(!t.stagedSuggestion)return;let{text:e,suggestion:{source:n,abVariant:o,abTestName:s,trainingJobs:r,sourceText:i},eventMetrics:{inputType:a},replace:l}=t.stagedSuggestion,c=n==="search"||n==="personal-collection-search",u=c||l==="selection"?e:e.slice(t.userCommitted.text.substring(0,t.userCommitted.selection.start).length);t.userCommitted.text=t.text,t.userCommitted.selection=t.selection,t.metrics.textSuggestions=[...t.metrics.textSuggestions,{text:u,source:n,abVariant:o,abTestName:s,inputType:a,sourceText:i,trainingJobs:r||[],searchTerm:c?t.userCommitted.text:null}],t.stagedSuggestion=null,t.textSuggestions=[],t.selectedSuggestionIndex=-1}var zr=t=>Gu({name:t,initialState:we,reducers:{initialInput(e,n){let{text:o,selection:s,html:r}=n.payload;e.text=o,e.selection.start=(s==null?void 0:s.start)??o.length,e.selection.end=(s==null?void 0:s.end)??o.length,e.userCommitted.text=o,e.userCommitted.selection.start=(s==null?void 0:s.start)??o.length,e.userCommitted.selection.end=(s==null?void 0:s.end)??o.length,e.html=r||null},reset(e){Object.assign(e,{...we,selection:e.selection})},resetToCommitted(e){e.text=e.userCommitted.text,e.selection=e.userCommitted.selection,e.stagedSuggestion=null,e.tabCompletionSuggestion=qo(e.textSuggestions,e.userCommitted.text)},setInputHtml(e,n){e.html=n.payload},changeSelection(e,n){n.payload&&(be(e.selection,n.payload)||(e.selection=n.payload,e.userCommitted.selection=e.selection,e.stagedSuggestion&&xn(e)))},userInput(e,n){var i,a,l,c;if(e.previousKeyDownEvent){let{key:u,shiftKey:d,ctrlKey:p,metaKey:m,altKey:g}=e.previousKeyDownEvent;switch(u){case"Enter":d&&(e.metrics.numCharsTyped+=1);break;case"Backspace":case"Delete":{let{text:f}=e,{text:T}=n.payload,b=$u(f,T);f.length-T.length>1&&e.metrics.deletions.push(...b.filter(h=>h.removed).map(h=>h.value)),e.metrics.numCharsDeleted+=f.length-T.length;break}case"C":case"V":case"X":if(!p&&!m){e.metrics.numCharsTyped+=1;let f=((i=e.selection)==null?void 0:i.start)!==void 0&&((a=e.selection)==null?void 0:a.end)!==void 0?e.text.substring(e.selection.start,e.selection.end):null;f&&f.length>0&&(e.metrics.numCharsDeleted+=f.length,e.metrics.deletions.push(f))}break;case"Shift":break;default:if(!p&&!m&&!g){e.metrics.numCharsTyped+=1;let f=((l=e.selection)==null?void 0:l.start)!==void 0&&((c=e.selection)==null?void 0:c.end)!==void 0?e.text.substring(e.selection.start,e.selection.end):null;f&&f.length>0&&(e.metrics.numCharsDeleted+=f.length,e.metrics.deletions.push(f))}}}!e.metrics.agentStartedTypingTimestamp&&n.payload.text!==e.text&&(e.metrics.agentStartedTypingTimestamp=Date.now()),n.payload.text===""&&(e.metrics=we.metrics,e.textSuggestions=[]),e.text!==n.payload.text&&xn(e);let{text:o,html:s,selection:r}=n.payload;r&&(e.selection.start=r.start,e.selection.end=r.end,e.userCommitted.selection.start=r.start,e.userCommitted.selection.end=r.end),e.text=o,e.html=s||null,e.userCommitted.text=o,e.previousKeyDownEvent=null},stageSuggestion(e,n){let{text:o}=n.payload;switch(e.stagedSuggestion=n.payload,e.tabCompletionSuggestion=void 0,n.payload.replace){case"selection":e.text=`${e.text.slice(0,e.selection.start)}${o}${e.text.slice(e.selection.end)}`,e.selection.end=e.selection.start+o.length,e.selection.start+=o.length;break;case"until-selection-end":e.text=`${o}${e.text.slice(e.selection.end)}`,e.selection.start=o.length,e.selection.end=o.length;break;default:throw new Error(`Unknown replace ${n.payload.replace}`)}n.payload.eventMetrics.inputType==="tab"&&xn(e)},commitSuggestion(e){xn(e)},offeredTextSuggestion(e,n){let{text:o,suggestion:{source:s}}=n.payload;e.metrics.offeredTextSuggestions.find(i=>i.text===o)||e.metrics.offeredTextSuggestions.push({text:o,source:s})},registerCut(e,n){let{metrics:o}=e,s=n.payload;e.metrics={...e.metrics,numCharsCut:o.numCharsCut+s.length,cuts:[...o.cuts,s]}},registerPaste(e,n){let{metrics:o}=e,{text:s,selectionText:r}=n.payload,i=o.numCharsDeleted+(r&&r.length?r.length:0),a=r&&r.length?[...o.deletions,r]:o.deletions;e.metrics={...e.metrics,numCharsDeleted:i,deletions:a,numCharsPasted:o.numCharsPasted+s.length,numPaste:o.numPaste+1,pastes:[...o.pastes,s]}},registerKeyDown(e,n){e.previousKeyDownEvent=n.payload},nextTextSuggestionIndex(e){let n=e.textSuggestions.length;e.selectedSuggestionIndex=e.selectedSuggestionIndex<n-1?e.selectedSuggestionIndex+1:e.selectedSuggestionIndex},previousTextSuggestionIndex(e){e.selectedSuggestionIndex=e.selectedSuggestionIndex>=0?e.selectedSuggestionIndex-1:e.selectedSuggestionIndex},setTextSuggestions(e,n){if(e.selectedSuggestionIndex=-1,e.textSuggestions=n.payload,n.payload.length===0)return;let o=e.userCommitted.text.substring(0,e.userCommitted.selection.end),s=qo(n.payload,o);e.tabCompletionSuggestion=s!=null&&s.text.includes(o)?s:void 0},setSelectedTextSuggestionIndex(e,n){e.selectedSuggestionIndex=n.payload},mergeMetrics(e,{payload:n}){e.metrics.numCharsTyped+=n.numCharsTyped,e.metrics.numCharsPasted+=n.numCharsPasted,e.metrics.numCharsCut+=n.numCharsCut,e.metrics.numCharsDeleted+=n.numCharsDeleted,e.metrics.numPaste+=n.numPaste,e.metrics.pastes.push(...n.pastes),e.metrics.deletions.push(...n.deletions)}},extraReducers:e=>{e.addCase(k,n=>{n.tabCompletionSuggestion=we.tabCompletionSuggestion,n.previousKeyDownEvent=we.previousKeyDownEvent,n.textSuggestions=we.textSuggestions,n.selectedSuggestionIndex=we.selectedSuggestionIndex,n.metrics=we.metrics})}}),Wo=zr("input"),Ye=t=>t.input.userCommitted.text.substring(0,t.input.userCommitted.selection.end),Ju=t=>t.input.selection,Wr=()=>Xu(Ju),{userInput:Gr,changeSelection:Go,initialInput:$r,mergeMetrics:Xr,nextTextSuggestionIndex:Jr,offeredTextSuggestion:Qr,previousTextSuggestionIndex:Zr,registerCut:Yr,registerKeyDown:ei,registerPaste:ti,reset:ni,resetToCommitted:kt,setInputHtml:oi,setSelectedTextSuggestionIndex:Pn,setTextSuggestions:Ee,stageSuggestion:ee,commitSuggestion:_e}=Wo.actions,j=zr("overlay");import{useEffect as ri,useRef as ii}from"react";import Qu,{useContext as Zu}from"react";import Yu from"classnames";var Rt=Qu.createContext({});function y(t,e){let o=Zu(Rt)[t];return o?Object.entries(e).reduce((s,[r,i])=>{let a=o[r];return{...s,[r]:Yu(i,a)}},{}):e}var si={root:"_root_1qp5s_1",content:"_content_1qp5s_23"};import{jsx as ai}from"react/jsx-runtime";var ep=({isOpen:t,autoFocus:e,children:n,onClose:o,onBack:s,overlayAriaLabel:r,contentAriaLabel:i})=>{let a=ii(null),l=ii(null),c=y("Dialog",si);return ri(()=>{var p,m;let u=g=>{g.key==="Escape"&&(g.preventDefault(),g.stopPropagation(),s())},d=g=>{let f=window.getSelection();f!=null&&f.toString()||g.target===a.current&&t&&o()};return(p=a.current)==null||p.addEventListener("click",d),(m=a.current)==null||m.addEventListener("keyup",u),()=>{var g,f;(g=a.current)==null||g.removeEventListener("click",d),(f=a.current)==null||f.removeEventListener("keyup",u)}},[a,l,s,o]),ri(()=>{var u,d;!a.current||!t||!e||(d=(u=a.current)==null?void 0:u.querySelector("input, textarea"))==null||d.focus()},[t,e,a]),t?ai("div",{role:"dialog","data-testid":"dialog",className:c.root,"aria-label":r,ref:a,children:ai("div",{ref:l,"data-testid":"dialog-content",className:c.content,"aria-label":i,children:n})}):null},et=ep;import{useEffect as la}from"react";import{useDispatch as Ld,useSelector as Ad}from"react-redux";var $o={};B($o,{enUS:()=>tp,nlNL:()=>np});var tp={dismiss:[{type:0,value:"Close"}],add:[{type:0,value:"Add to message"}],next:[{type:0,value:"Next"}],previous:[{type:0,value:"Previous"}],warning:[{type:0,value:"Are you sure you want to discard the message?"}]},np={dismiss:[{type:0,value:"Sluiten"}],add:[{type:0,value:"Toevoegen"}],next:[{type:0,value:"Volgende"}],previous:[{type:0,value:"Vorige"}],warning:[{type:0,value:"Weet je zeker dat je de wijzigingen wilt weggooien?"}]};var li={root:"_root_l80t9_1",content:"_content_l80t9_3",title:"_title_l80t9_7",actions:"_actions_l80t9_15",pagination:"_pagination_l80t9_20",primaryButton:"_primaryButton_l80t9_51",primaryButtons:"_primaryButtons_l80t9_55"};import{createContext as gp,useContext as fp}from"react";var Xo=function(t,e){return Xo=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])},Xo(t,e)};function It(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");Xo(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}var $=function(){return $=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},$.apply(this,arguments)};function ci(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 kn(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))}var Rn;(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"})(Rn||(Rn={}));var In=class{constructor(e){console.warn(`[vite-messages-plugin]: Message "${e}" was not precompiled. Did you use the correct extenstion *.messages.ts?`)}};var te;(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"})(te||(te={}));var Ln;(function(t){t[t.number=0]="number",t[t.dateTime=1]="dateTime"})(Ln||(Ln={}));function Jo(t){return t.type===te.literal}function ui(t){return t.type===te.argument}function An(t){return t.type===te.number}function Mn(t){return t.type===te.date}function On(t){return t.type===te.time}function Nn(t){return t.type===te.select}function Dn(t){return t.type===te.plural}function pi(t){return t.type===te.pound}function Hn(t){return t.type===te.tag}function Fn(t){return!!(t&&typeof t=="object"&&t.type===Ln.number)}function Lt(t){return!!(t&&typeof t=="object"&&t.type===Ln.dateTime)}function Qo(t){t.forEach(function(e){if(delete e.location,Nn(e)||Dn(e))for(var n in e.options)delete e.options[n].location,Qo(e.options[n].value);else An(e)&&Fn(e.style)||(Mn(e)||On(e))&&Lt(e.style)?delete e.style.location:Hn(e)&&Qo(e.children)})}function di(t,e){e===void 0&&(e={}),e=$({shouldParseSkeletons:!0,requiresOtherClause:!0},e);var n=new In(t,e).parse();if(n.err){var o=SyntaxError(Rn[n.err.kind]);throw o.location=n.err.location,o.originalMessage=n.err.message,o}return e!=null&&e.captureLocation||Qo(n.val),n.val}function Bn(t,e){var n=e&&e.cache?e.cache:lp,o=e&&e.serializer?e.serializer:ap,s=e&&e.strategy?e.strategy:sp;return s(t,{cache:n,serializer:o})}function op(t){return t==null||typeof t=="number"||typeof t=="boolean"}function mi(t,e,n,o){var s=op(o)?o:n(o),r=e.get(s);return typeof r>"u"&&(r=t.call(this,o),e.set(s,r)),r}function gi(t,e,n){var o=Array.prototype.slice.call(arguments,3),s=n(o),r=e.get(s);return typeof r>"u"&&(r=t.apply(this,o),e.set(s,r)),r}function Zo(t,e,n,o,s){return n.bind(e,t,o,s)}function sp(t,e){var n=t.length===1?mi:gi;return Zo(t,this,n,e.cache.create(),e.serializer)}function rp(t,e){return Zo(t,this,gi,e.cache.create(),e.serializer)}function ip(t,e){return Zo(t,this,mi,e.cache.create(),e.serializer)}var ap=function(){return JSON.stringify(arguments)};function Yo(){this.cache=Object.create(null)}Yo.prototype.get=function(t){return this.cache[t]};Yo.prototype.set=function(t,e){this.cache[t]=e};var lp={create:function(){return new Yo}},Kn={variadic:rp,monadic:ip};var Ke;(function(t){t.MISSING_VALUE="MISSING_VALUE",t.INVALID_VALUE="INVALID_VALUE",t.MISSING_INTL_API="MISSING_INTL_API"})(Ke||(Ke={}));var At=function(t){It(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 es=function(t){It(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('", "'),'"'),Ke.INVALID_VALUE,r)||this}return e}(At);var fi=function(t){It(e,t);function e(n,o,s){return t.call(this,'Value for "'.concat(n,'" must be of type ').concat(o),Ke.INVALID_VALUE,s)||this}return e}(At);var hi=function(t){It(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,'"'),Ke.MISSING_VALUE,o)||this}return e}(At);var K;(function(t){t[t.literal=0]="literal",t[t.object=1]="object"})(K||(K={}));function cp(t){return t.length<2?t:t.reduce(function(e,n){var o=e[e.length-1];return!o||o.type!==K.literal||n.type!==K.literal?e.push(n):o.value+=n.value,e},[])}function up(t){return typeof t=="function"}function Mt(t,e,n,o,s,r,i){if(t.length===1&&Jo(t[0]))return[{type:K.literal,value:t[0].value}];for(var a=[],l=0,c=t;l<c.length;l++){var u=c[l];if(Jo(u)){a.push({type:K.literal,value:u.value});continue}if(pi(u)){typeof r=="number"&&a.push({type:K.literal,value:n.getNumberFormat(e).format(r)});continue}var d=u.value;if(!(s&&d in s))throw new hi(d,i);var p=s[d];if(ui(u)){(!p||typeof p=="string"||typeof p=="number")&&(p=typeof p=="string"||typeof p=="number"?String(p):""),a.push({type:typeof p=="string"?K.literal:K.object,value:p});continue}if(Mn(u)){var m=typeof u.style=="string"?o.date[u.style]:Lt(u.style)?u.style.parsedOptions:void 0;a.push({type:K.literal,value:n.getDateTimeFormat(e,m).format(p)});continue}if(On(u)){var m=typeof u.style=="string"?o.time[u.style]:Lt(u.style)?u.style.parsedOptions:o.time.medium;a.push({type:K.literal,value:n.getDateTimeFormat(e,m).format(p)});continue}if(An(u)){var m=typeof u.style=="string"?o.number[u.style]:Fn(u.style)?u.style.parsedOptions:void 0;m&&m.scale&&(p=p*(m.scale||1)),a.push({type:K.literal,value:n.getNumberFormat(e,m).format(p)});continue}if(Hn(u)){var g=u.children,f=u.value,T=s[f];if(!up(T))throw new fi(f,"function",i);var b=Mt(g,e,n,o,s,r),h=T(b.map(function(C){return C.value}));Array.isArray(h)||(h=[h]),a.push.apply(a,h.map(function(C){return{type:typeof C=="string"?K.literal:K.object,value:C}}))}if(Nn(u)){var S=u.options[p]||u.options.other;if(!S)throw new es(u.value,p,Object.keys(u.options),i);a.push.apply(a,Mt(S.value,e,n,o,s));continue}if(Dn(u)){var S=u.options["=".concat(p)];if(!S){if(!Intl.PluralRules)throw new At(`Intl.PluralRules is not available in this environment.
1
+ var qu=Object.defineProperty;var B=(t,e)=>{for(var n in e)qu(t,n,{get:e[n],enumerable:!0})};var Br=/(?:[.,;:!?\\n]|:\\)|:\\(|:-\\)|:-\\()/g,Je=/(((\$!\{)|(\{))[a-zA-Z0-9_.]+\})/g;var Kr=/x-deepdesk-(([a-z0-9\-_])+-version)/,He=(p=>(p.SEARCH="search",p.TEMPLATE="template",p.ELASTIC_SEARCH="studio-search",p.GPT="gpt",p.TRIE="trie",p.TRIE_WITH_TYPOS="trie-with-typos",p.SEMANTIC="semantic",p.TEXT_RECOMMENDATION="text_recommendation",p.URL_RECOMMENDATION="url_recommendation",p.LINK_RECOMMENDATION="link_recommendation",p.PERSONAL_COLLECTION="personal-collection",p.PERSONAL_COLLECTION_SEARCH="personal-collection-search",p))(He||{}),Fe=(s=>(s.TAB="tab",s.ARROW="arrow",s.HOTKEY="hotkey",s.MOUSE="mouse",s))(Fe||{});import{render as Uo,unmountComponentAtNode as Hr}from"react-dom";import{Fragment as dg}from"react";import{createSlice as Vu}from"@reduxjs/toolkit";import{useSelector as ju}from"react-redux";var yn=(n=>(n.NL_NL="nl-NL",n.EN_US="en-US",n))(yn||{});var zu={locale:"en-US",deanonymize:!1,fallbackImage:!1,isEmbedded:!1,showAutoflows:!1,showCustomMessages:!1,showImages:!1,showPersonalCollectionLink:!1,showSearch:!1,showImageSearch:!1,showStyleSuggestions:!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,inlineSuggestions:!1,adminUrl:void 0,productName:"Deepdesk"},Ur=Vu({name:"settings",initialState:zu,reducers:{set(t,e){Object.entries(e.payload).forEach(n=>{let[o,s]=n;typeof s>"u"||(t[o]=s)})}}}),{set:Rt}=Ur.actions,zo=t=>e=>e.settings[t],T=t=>ju(zo(t)),qr=Ur.reducer;import{useState as Yd}from"react";import{useDispatch as em,useSelector as Os}from"react-redux";import{createAction as Be,createSlice as Yu}from"@reduxjs/toolkit";import{diffChars as ep}from"diff";import{useSelector as tp}from"react-redux";function Vr(t){return typeof t=="object"&&!Array.isArray(t)&&t!==null}function ke(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)=>ke(r,e[i],n-1)):Vr(t)&&Vr(e)?Object.keys(t).length!==Object.keys(e).length?!1:Object.keys(t).every(i=>ke(t[i],e[i],n-1)):!1}function Wu(t){return Math.max(...t.map(e=>e.length))}function Gu(t,e){let n=t.reduce((o,s)=>{if(s){let r=o[s]?o[s]+1:1;return{...o,[s]:r}}return o},{});return Object.keys(n).reduce((o,s)=>(n[s]<e&&o.push(s),o),[])}function jr(t,e){let o=[...t.map(({text:s})=>s.split(/\b(\w+)\b/))];for(let s=0;s<Wu(o);s++){let r=Gu(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 $u=2;function Wo(t,e=""){if(t.length===0)return;if(t.length===1)return t[0];let n=jr(t,$u);return n&&n.text!==e?n:t[0]}import{createAction as Xu,createAsyncThunk as Ye,createSlice as Qu}from"@reduxjs/toolkit";var zr={current:null,isSupported:null},R=Xu("resetConversation"),Sn=t=>{let{current:e}=t.conversation;return(e==null?void 0:e.sessionId)||null},vn=t=>{let{current:e}=t.conversation;return(e==null?void 0:e.id)||null},xn=t=>t.conversation.isSupported,Go=Ye("conversation/isSupported",(t,e)=>{let{deepdeskAPI:n}=e.extra;return n.isConversationSupported(t.sessionId,t.options)}),Cn=Ye("conversation/create",(t,e)=>{let{deepdeskAPI:n}=e.extra;return n.createConversation(t)}),Tn=Ye("conversation/bySessionId",(t,e)=>{let{deepdeskAPI:n}=e.extra;return n.getConversationBySessionId(t.sessionId,t.options)}),wn=Ye("conversation/update",(t,e)=>{let{deepdeskAPI:n}=e.extra,o=vn(e.getState());if(!o)throw new Error("No current conversation to update");return n.updateConversation(o,t)}),$o=Ye("conversation/upsert",(t,e)=>{let{deepdeskAPI:n}=e.extra;return n.getConversationBySessionId(t.sessionId).catch(()=>null).then(o=>{if(!o)return n.createConversation(t);let{agentId:s,agentName:r,agentEmail:i,agentNickname:a,tags:l}=t;return n.updateConversation(o.id,{agentId:s,agentEmail:i,agentName:r,agentNickname:a,tags:l})})}),bn=Ye("conversation/postMessages",(t,e)=>{let{deepdeskAPI:n}=e.extra,o=vn(e.getState());if(!o)throw new Error("No current conversation to update messages");return n.postMessages(o,t.map(s=>({...s})))}),Zu=[Cn.rejected,Tn.rejected,wn.rejected,bn.rejected].map(t=>t==null?void 0:t.toString()),Ju=Qu({name:"conversation",initialState:zr,reducers:{},extraReducers:t=>{t.addCase(Go.fulfilled,(e,n)=>{e.isSupported=n.payload}).addCase(Cn.fulfilled,(e,n)=>{var o;e.current=n.payload,e.isSupported=((o=n.payload)==null?void 0:o.hasActiveProfile)??null}).addCase(Tn.fulfilled,(e,n)=>{var o;e.current=n.payload,e.isSupported=((o=n.payload)==null?void 0:o.hasActiveProfile)??null}).addCase($o.fulfilled,(e,n)=>{var o;e.current=n.payload,e.isSupported=((o=n.payload)==null?void 0:o.hasActiveProfile)??null}).addCase(wn.fulfilled,(e,n)=>{var o;e.current=n.payload,e.isSupported=((o=n.payload)==null?void 0:o.hasActiveProfile)??null}).addCase(bn.fulfilled,(e,n)=>{e.current&&(e.current.messages=n.payload)}).addCase(R,()=>zr).addMatcher(e=>Zu.includes(e.type),(e,n)=>{throw new Error(n.error.message)})}}),Wr=Ju.reducer;var Re={text:"",html:null,selection:{start:0,end:0},stagedSuggestion:null,userCommitted:{text:"",selection:{start:0,end:0}},tabCompletionSuggestion:void 0,previousKeyDownEvent:null,textSuggestions:[],selectedSuggestionIndex:-1,metrics:{numCharsTyped:0,numCharsPasted:0,numCharsCut:0,numCharsDeleted:0,numPaste:0,agentStartedTypingTimestamp:null,pastes:[],deletions:[],offeredTextSuggestions:[],textSuggestions:[],cuts:[]}};function _n(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 Pn=Be("input/replaceText"),kn=Be("input/keyDown"),It=Be("input/sendMessage"),Rn=Be("input/sendEditSuggestionMessage"),In=Be("input/uiInputChange"),An=Be("input/applyImageSuggestion"),ae=Be("input/sendEvent");function En(t){if(!t.stagedSuggestion)return;let{text:e,suggestion:{source:n,abVariant:o,abTestName:s,trainingJobs:r,sourceText:i},eventMetrics:{inputType:a},replace:l}=t.stagedSuggestion,c=n==="search"||n==="personal-collection-search",u=c||l==="selection"?e:e.slice(t.userCommitted.text.substring(0,t.userCommitted.selection.start).length);t.userCommitted.text=t.text,t.userCommitted.selection=t.selection,t.metrics.textSuggestions=[...t.metrics.textSuggestions,{text:u,source:n,abVariant:o,abTestName:s,inputType:a,sourceText:i,trainingJobs:r||[],searchTerm:c?t.userCommitted.text:null}],t.stagedSuggestion=null,t.textSuggestions=[],t.selectedSuggestionIndex=-1}var Gr=t=>Yu({name:t,initialState:Re,reducers:{initialInput(e,n){let{text:o,selection:s,html:r}=n.payload;e.text=o,e.selection.start=(s==null?void 0:s.start)??o.length,e.selection.end=(s==null?void 0:s.end)??o.length,e.userCommitted.text=o,e.userCommitted.selection.start=(s==null?void 0:s.start)??o.length,e.userCommitted.selection.end=(s==null?void 0:s.end)??o.length,e.html=r||null},reset(e){Object.assign(e,{...Re,selection:e.selection})},resetToCommitted(e){e.text=e.userCommitted.text,e.selection=e.userCommitted.selection,e.stagedSuggestion=null,e.tabCompletionSuggestion=Wo(e.textSuggestions,e.userCommitted.text)},setInputHtml(e,n){e.html=n.payload},changeSelection(e,n){n.payload&&(ke(e.selection,n.payload)||(e.selection=n.payload,e.userCommitted.selection=e.selection,e.stagedSuggestion&&En(e)))},userInput(e,n){var i,a,l,c;if(e.previousKeyDownEvent){let{key:u,shiftKey:d,ctrlKey:p,metaKey:m,altKey:g}=e.previousKeyDownEvent;switch(u){case"Enter":d&&(e.metrics.numCharsTyped+=1);break;case"Backspace":case"Delete":{let{text:f}=e,{text:x}=n.payload,b=ep(f,x);f.length-x.length>1&&e.metrics.deletions.push(...b.filter(h=>h.removed).map(h=>h.value)),e.metrics.numCharsDeleted+=f.length-x.length;break}case"C":case"V":case"X":if(!p&&!m){e.metrics.numCharsTyped+=1;let f=((i=e.selection)==null?void 0:i.start)!==void 0&&((a=e.selection)==null?void 0:a.end)!==void 0?e.text.substring(e.selection.start,e.selection.end):null;f&&f.length>0&&(e.metrics.numCharsDeleted+=f.length,e.metrics.deletions.push(f))}break;case"Shift":break;default:if(!p&&!m&&!g){e.metrics.numCharsTyped+=1;let f=((l=e.selection)==null?void 0:l.start)!==void 0&&((c=e.selection)==null?void 0:c.end)!==void 0?e.text.substring(e.selection.start,e.selection.end):null;f&&f.length>0&&(e.metrics.numCharsDeleted+=f.length,e.metrics.deletions.push(f))}}}!e.metrics.agentStartedTypingTimestamp&&n.payload.text!==e.text&&(e.metrics.agentStartedTypingTimestamp=Date.now()),n.payload.text===""&&(e.metrics=Re.metrics,e.textSuggestions=[]),e.text!==n.payload.text&&En(e);let{text:o,html:s,selection:r}=n.payload;r&&(e.selection.start=r.start,e.selection.end=r.end,e.userCommitted.selection.start=r.start,e.userCommitted.selection.end=r.end),e.text=o,e.html=s||null,e.userCommitted.text=o,e.previousKeyDownEvent=null},stageSuggestion(e,n){let{text:o}=n.payload;switch(e.stagedSuggestion=n.payload,e.tabCompletionSuggestion=void 0,n.payload.replace){case"selection":e.text=`${e.text.slice(0,e.selection.start)}${o}${e.text.slice(e.selection.end)}`,e.selection.end=e.selection.start+o.length,e.selection.start+=o.length;break;case"until-selection-end":e.text=`${o}${e.text.slice(e.selection.end)}`,e.selection.start=o.length,e.selection.end=o.length;break;default:throw new Error(`Unknown replace ${n.payload.replace}`)}n.payload.eventMetrics.inputType==="tab"&&En(e)},commitSuggestion(e){En(e)},offeredTextSuggestion(e,n){let{text:o,suggestion:{source:s}}=n.payload;e.metrics.offeredTextSuggestions.find(i=>i.text===o)||e.metrics.offeredTextSuggestions.push({text:o,source:s})},registerCut(e,n){let{metrics:o}=e,s=n.payload;e.metrics={...e.metrics,numCharsCut:o.numCharsCut+s.length,cuts:[...o.cuts,s]}},registerPaste(e,n){let{metrics:o}=e,{text:s,selectionText:r}=n.payload,i=o.numCharsDeleted+(r&&r.length?r.length:0),a=r&&r.length?[...o.deletions,r]:o.deletions;e.metrics={...e.metrics,numCharsDeleted:i,deletions:a,numCharsPasted:o.numCharsPasted+s.length,numPaste:o.numPaste+1,pastes:[...o.pastes,s]}},registerKeyDown(e,n){e.previousKeyDownEvent=n.payload},nextTextSuggestionIndex(e){let n=e.textSuggestions.length;e.selectedSuggestionIndex=e.selectedSuggestionIndex<n-1?e.selectedSuggestionIndex+1:e.selectedSuggestionIndex},previousTextSuggestionIndex(e){e.selectedSuggestionIndex=e.selectedSuggestionIndex>=0?e.selectedSuggestionIndex-1:e.selectedSuggestionIndex},setTextSuggestions(e,n){if(e.selectedSuggestionIndex=-1,e.textSuggestions=n.payload,n.payload.length===0)return;let o=e.userCommitted.text.substring(0,e.userCommitted.selection.end),s=Wo(n.payload,o);e.tabCompletionSuggestion=s!=null&&s.text.includes(o)?s:void 0},setSelectedTextSuggestionIndex(e,n){e.selectedSuggestionIndex=n.payload},mergeMetrics(e,{payload:n}){e.metrics.numCharsTyped+=n.numCharsTyped,e.metrics.numCharsPasted+=n.numCharsPasted,e.metrics.numCharsCut+=n.numCharsCut,e.metrics.numCharsDeleted+=n.numCharsDeleted,e.metrics.numPaste+=n.numPaste,e.metrics.pastes.push(...n.pastes),e.metrics.deletions.push(...n.deletions)}},extraReducers:e=>{e.addCase(R,n=>{n.tabCompletionSuggestion=Re.tabCompletionSuggestion,n.previousKeyDownEvent=Re.previousKeyDownEvent,n.textSuggestions=Re.textSuggestions,n.selectedSuggestionIndex=Re.selectedSuggestionIndex,n.metrics=Re.metrics})}}),Xo=Gr("input"),et=t=>t.input.userCommitted.text.substring(0,t.input.userCommitted.selection.end),np=t=>t.input.selection,$r=()=>tp(np),{userInput:Xr,changeSelection:Qo,initialInput:Qr,mergeMetrics:Zr,nextTextSuggestionIndex:Jr,offeredTextSuggestion:Yr,previousTextSuggestionIndex:ei,registerCut:ti,registerKeyDown:ni,registerPaste:oi,reset:si,resetToCommitted:At,setInputHtml:ri,setSelectedTextSuggestionIndex:Ln,setTextSuggestions:Ie,stageSuggestion:oe,commitSuggestion:Ae}=Xo.actions,V=Gr("overlay");import{useEffect as ai,useRef as li}from"react";import op,{useContext as sp}from"react";import rp from"classnames";var Lt=op.createContext({});function y(t,e){let o=sp(Lt)[t];return o?Object.entries(e).reduce((s,[r,i])=>{let a=o[r];return{...s,[r]:rp(i,a)}},{}):e}var ii={root:"_root_1qp5s_1",content:"_content_1qp5s_23"};import{jsx as ci}from"react/jsx-runtime";var ip=({isOpen:t,autoFocus:e,children:n,onClose:o,onBack:s,overlayAriaLabel:r,contentAriaLabel:i})=>{let a=li(null),l=li(null),c=y("Dialog",ii);return ai(()=>{var p,m;let u=g=>{g.key==="Escape"&&(g.preventDefault(),g.stopPropagation(),s())},d=g=>{let f=window.getSelection();f!=null&&f.toString()||g.target===a.current&&t&&o()};return(p=a.current)==null||p.addEventListener("click",d),(m=a.current)==null||m.addEventListener("keyup",u),()=>{var g,f;(g=a.current)==null||g.removeEventListener("click",d),(f=a.current)==null||f.removeEventListener("keyup",u)}},[a,l,s,o]),ai(()=>{var u,d;!a.current||!t||!e||(d=(u=a.current)==null?void 0:u.querySelector("input, textarea"))==null||d.focus()},[t,e,a]),t?ci("div",{role:"dialog","data-testid":"dialog",className:c.root,"aria-label":r,ref:a,children:ci("div",{ref:l,"data-testid":"dialog-content",className:c.content,"aria-label":i,children:n})}):null},tt=ip;import{useEffect as ua}from"react";import{useDispatch as Nd,useSelector as Dd}from"react-redux";var Zo={};B(Zo,{enUS:()=>ap,nlNL:()=>lp});var ap={dismiss:[{type:0,value:"Close"}],add:[{type:0,value:"Add to message"}],next:[{type:0,value:"Next"}],previous:[{type:0,value:"Previous"}],warning:[{type:0,value:"Are you sure you want to discard the message?"}]},lp={dismiss:[{type:0,value:"Sluiten"}],add:[{type:0,value:"Toevoegen"}],next:[{type:0,value:"Volgende"}],previous:[{type:0,value:"Vorige"}],warning:[{type:0,value:"Weet je zeker dat je de wijzigingen wilt weggooien?"}]};var ui={root:"_root_l80t9_1",content:"_content_l80t9_3",title:"_title_l80t9_7",actions:"_actions_l80t9_15",pagination:"_pagination_l80t9_20",primaryButton:"_primaryButton_l80t9_51",primaryButtons:"_primaryButtons_l80t9_55"};import{createContext as xp,useContext as Cp}from"react";var Jo=function(t,e){return Jo=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])},Jo(t,e)};function Mt(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");Jo(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}var Q=function(){return Q=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},Q.apply(this,arguments)};function pi(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 Mn(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))}var On;(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"})(On||(On={}));var Nn=class{constructor(e){console.warn(`[vite-messages-plugin]: Message "${e}" was not precompiled. Did you use the correct extenstion *.messages.ts?`)}};var se;(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"})(se||(se={}));var Dn;(function(t){t[t.number=0]="number",t[t.dateTime=1]="dateTime"})(Dn||(Dn={}));function Yo(t){return t.type===se.literal}function di(t){return t.type===se.argument}function Hn(t){return t.type===se.number}function Fn(t){return t.type===se.date}function Bn(t){return t.type===se.time}function Kn(t){return t.type===se.select}function Un(t){return t.type===se.plural}function mi(t){return t.type===se.pound}function qn(t){return t.type===se.tag}function Vn(t){return!!(t&&typeof t=="object"&&t.type===Dn.number)}function Ot(t){return!!(t&&typeof t=="object"&&t.type===Dn.dateTime)}function es(t){t.forEach(function(e){if(delete e.location,Kn(e)||Un(e))for(var n in e.options)delete e.options[n].location,es(e.options[n].value);else Hn(e)&&Vn(e.style)||(Fn(e)||Bn(e))&&Ot(e.style)?delete e.style.location:qn(e)&&es(e.children)})}function gi(t,e){e===void 0&&(e={}),e=Q({shouldParseSkeletons:!0,requiresOtherClause:!0},e);var n=new Nn(t,e).parse();if(n.err){var o=SyntaxError(On[n.err.kind]);throw o.location=n.err.location,o.originalMessage=n.err.message,o}return e!=null&&e.captureLocation||es(n.val),n.val}function jn(t,e){var n=e&&e.cache?e.cache:gp,o=e&&e.serializer?e.serializer:mp,s=e&&e.strategy?e.strategy:up;return s(t,{cache:n,serializer:o})}function cp(t){return t==null||typeof t=="number"||typeof t=="boolean"}function fi(t,e,n,o){var s=cp(o)?o:n(o),r=e.get(s);return typeof r>"u"&&(r=t.call(this,o),e.set(s,r)),r}function hi(t,e,n){var o=Array.prototype.slice.call(arguments,3),s=n(o),r=e.get(s);return typeof r>"u"&&(r=t.apply(this,o),e.set(s,r)),r}function ts(t,e,n,o,s){return n.bind(e,t,o,s)}function up(t,e){var n=t.length===1?fi:hi;return ts(t,this,n,e.cache.create(),e.serializer)}function pp(t,e){return ts(t,this,hi,e.cache.create(),e.serializer)}function dp(t,e){return ts(t,this,fi,e.cache.create(),e.serializer)}var mp=function(){return JSON.stringify(arguments)};function ns(){this.cache=Object.create(null)}ns.prototype.get=function(t){return this.cache[t]};ns.prototype.set=function(t,e){this.cache[t]=e};var gp={create:function(){return new ns}},zn={variadic:pp,monadic:dp};var Ke;(function(t){t.MISSING_VALUE="MISSING_VALUE",t.INVALID_VALUE="INVALID_VALUE",t.MISSING_INTL_API="MISSING_INTL_API"})(Ke||(Ke={}));var Nt=function(t){Mt(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 os=function(t){Mt(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('", "'),'"'),Ke.INVALID_VALUE,r)||this}return e}(Nt);var yi=function(t){Mt(e,t);function e(n,o,s){return t.call(this,'Value for "'.concat(n,'" must be of type ').concat(o),Ke.INVALID_VALUE,s)||this}return e}(Nt);var Si=function(t){Mt(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,'"'),Ke.MISSING_VALUE,o)||this}return e}(Nt);var K;(function(t){t[t.literal=0]="literal",t[t.object=1]="object"})(K||(K={}));function fp(t){return t.length<2?t:t.reduce(function(e,n){var o=e[e.length-1];return!o||o.type!==K.literal||n.type!==K.literal?e.push(n):o.value+=n.value,e},[])}function hp(t){return typeof t=="function"}function Dt(t,e,n,o,s,r,i){if(t.length===1&&Yo(t[0]))return[{type:K.literal,value:t[0].value}];for(var a=[],l=0,c=t;l<c.length;l++){var u=c[l];if(Yo(u)){a.push({type:K.literal,value:u.value});continue}if(mi(u)){typeof r=="number"&&a.push({type:K.literal,value:n.getNumberFormat(e).format(r)});continue}var d=u.value;if(!(s&&d in s))throw new Si(d,i);var p=s[d];if(di(u)){(!p||typeof p=="string"||typeof p=="number")&&(p=typeof p=="string"||typeof p=="number"?String(p):""),a.push({type:typeof p=="string"?K.literal:K.object,value:p});continue}if(Fn(u)){var m=typeof u.style=="string"?o.date[u.style]:Ot(u.style)?u.style.parsedOptions:void 0;a.push({type:K.literal,value:n.getDateTimeFormat(e,m).format(p)});continue}if(Bn(u)){var m=typeof u.style=="string"?o.time[u.style]:Ot(u.style)?u.style.parsedOptions:o.time.medium;a.push({type:K.literal,value:n.getDateTimeFormat(e,m).format(p)});continue}if(Hn(u)){var m=typeof u.style=="string"?o.number[u.style]:Vn(u.style)?u.style.parsedOptions:void 0;m&&m.scale&&(p=p*(m.scale||1)),a.push({type:K.literal,value:n.getNumberFormat(e,m).format(p)});continue}if(qn(u)){var g=u.children,f=u.value,x=s[f];if(!hp(x))throw new yi(f,"function",i);var b=Dt(g,e,n,o,s,r),h=x(b.map(function(P){return P.value}));Array.isArray(h)||(h=[h]),a.push.apply(a,h.map(function(P){return{type:typeof P=="string"?K.literal:K.object,value:P}}))}if(Kn(u)){var v=u.options[p]||u.options.other;if(!v)throw new os(u.value,p,Object.keys(u.options),i);a.push.apply(a,Dt(v.value,e,n,o,s));continue}if(Un(u)){var v=u.options["=".concat(p)];if(!v){if(!Intl.PluralRules)throw new Nt(`Intl.PluralRules is not available in this environment.
2
2
  Try polyfilling it using "@formatjs/intl-pluralrules"
3
- `,Ke.MISSING_INTL_API,i);var w=n.getPluralRules(e,{type:u.pluralType}).select(p-(u.offset||0));S=u.options[w]||u.options.other}if(!S)throw new es(u.value,p,Object.keys(u.options),i);a.push.apply(a,Mt(S.value,e,n,o,s,p-(u.offset||0)));continue}}return cp(a)}function pp(t,e){return e?$($($({},t||{}),e||{}),Object.keys(t).reduce(function(n,o){return n[o]=$($({},t[o]),e[o]||{}),n},{})):t}function dp(t,e){return e?Object.keys(t).reduce(function(n,o){return n[o]=pp(t[o],e[o]),n},$({},t)):t}function ts(t){return{create:function(){return{get:function(e){return t[e]},set:function(e,n){t[e]=n}}}}}function mp(t){return t===void 0&&(t={number:{},dateTime:{},pluralRules:{}}),{getNumberFormat:Bn(function(){for(var e,n=[],o=0;o<arguments.length;o++)n[o]=arguments[o];return new((e=Intl.NumberFormat).bind.apply(e,kn([void 0],n,!1)))},{cache:ts(t.number),strategy:Kn.variadic}),getDateTimeFormat:Bn(function(){for(var e,n=[],o=0;o<arguments.length;o++)n[o]=arguments[o];return new((e=Intl.DateTimeFormat).bind.apply(e,kn([void 0],n,!1)))},{cache:ts(t.dateTime),strategy:Kn.variadic}),getPluralRules:Bn(function(){for(var e,n=[],o=0;o<arguments.length;o++)n[o]=arguments[o];return new((e=Intl.PluralRules).bind.apply(e,kn([void 0],n,!1)))},{cache:ts(t.pluralRules),strategy:Kn.variadic})}}var yi=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(c){var u=r.formatToParts(c);if(u.length===1)return u[0].value;var d=u.reduce(function(p,m){return!p.length||m.type!==K.literal||typeof p[p.length-1]!="string"?p.push(m.value):p[p.length-1]+=m.value,p},[]);return d.length<=1?d[0]||"":d},this.formatToParts=function(c){return Mt(r.ast,r.locales,r.formatters,r.formats,c,void 0,r.message)},this.resolvedOptions=function(){var c;return{locale:((c=r.resolvedLocale)===null||c===void 0?void 0:c.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,l=ci(i,["formatters"]);this.ast=t.__parse(e,$($({},l),{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=dp(t.formats,o),this.formatters=s&&s.formatters||mp(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>"u")){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=di,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 hp(t,e){return e.split(".").reduce((n,o)=>n?n[o]:void 0,t)}var yp="dummy",ns=gp(null);function _(t){let e=fp(ns);if(!e)throw new Error("useTranslator() may be used only in the context of a <LocaleContext> component.");let n=t[e]??{};return(o,s)=>{let r=hp(n,o);return r?new yi(r).format(s):(e!==yp&&console.warn(`${o} does not exist in messages of ${e}`),`[${o}]`)}}import{jsx as Si,jsxs as Sp}from"react/jsx-runtime";var Un=()=>Sp("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 256 512","aria-labelledby":"angleLeftTitle",children:[Si("title",{id:"angleLeftTitle",children:"AngleLeft"}),Si("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"})]});import{jsx as vi,jsxs as vp}from"react/jsx-runtime";var xi=()=>vp("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 256 512","aria-labelledby":"angleRightTitle",children:[vi("title",{id:"angleRightTitle",children:"AngleRight"}),vi("path",{d:"M64 448c-8.188 0-16.38-3.125-22.62-9.375c-12.5-12.5-12.5-32.75 0-45.25L178.8 256L41.38 118.6c-12.5-12.5-12.5-32.75 0-45.25s32.75-12.5 45.25 0l160 160c12.5 12.5 12.5 32.75 0 45.25l-160 160C80.38 444.9 72.19 448 64 448z"})]});import Vn from"classnames";import xp,{createContext as Cp,useCallback as Tp,useContext as Ot}from"react";var os={root:"_root_9kn3u_10",fadein:"_fadein_9kn3u_1",isClickable:"_isClickable_9kn3u_47",isSelected:"_isSelected_9kn3u_52",actions:"_actions_9kn3u_76",actionsIsFixed:"_actionsIsFixed_9kn3u_98",actionButton:"_actionButton_9kn3u_106",dropdownList:"_dropdownList_9kn3u_127",dropdownButton:"_dropdownButton_9kn3u_142",dropdownItem:"_dropdownItem_9kn3u_152",dropdownItemButton:"_dropdownItemButton_9kn3u_161",actionButtonIsPrimary:"_actionButtonIsPrimary_9kn3u_175",actionButtonIsDisabled:"_actionButtonIsDisabled_9kn3u_179",labels:"_labels_9kn3u_187",label:"_label_9kn3u_187"};import{jsx as le,jsxs as Pp}from"react/jsx-runtime";var tt=Cp(os),bp=({fixed:t,children:e,...n})=>{let o=Ot(tt);return le("div",{...n,className:Vn(o.actions,{[o.actionsIsFixed]:t}),children:e})},wp=({className:t,primary:e,disabled:n,label:o,children:s})=>{let r=Ot(tt);return Pp("div",{className:Vn(t,r.actionButton,r.dropdownButton,{[r.actionButtonIsPrimary]:e,[r.actionButtonIsDisabled]:n}),onMouseDown:i=>i.stopPropagation(),onClick:i=>i.stopPropagation(),children:[o,le("ul",{className:r.dropdownList,children:s})]})},Ep=({index:t,label:e,onClick:n})=>{let o=Ot(tt);return le("li",{className:o.dropdownItem,children:le("button",{className:o.dropdownItemButton,type:"button","data-index":t,onClick:n,children:e})})},_p=({className:t,primary:e,disabled:n,onClick:o,label:s})=>{let r=Ot(tt);return le("button",{type:"button",className:Vn(t,r.actionButton,{[r.actionButtonIsPrimary]:e,[r.actionButtonIsDisabled]:n}),onClick:o??(i=>i.stopPropagation()),disabled:n,"aria-hidden":n,children:s})},ss=({labels:t})=>{let e=Ot(tt);return le("div",{className:e.labels,children:t.map(n=>le("span",{className:e.label,children:n},n))})},nt=xp.forwardRef(({className:t,selected:e,onClick:n,children:o,as:s="div",...r},i)=>{let a=y("Suggestion",os),l=Tp(c=>{c.preventDefault(),n&&n(c)},[n]);return le(s,{...r,ref:i,className:Vn(t,a.root,{[a.isSelected]:e,[a.isClickable]:!!n}),onClick:l,children:le(tt.Provider,{value:a,children:o})})});nt.Labels=ss;nt.Actions=bp;nt.ActionButton=_p;nt.DropdownButton=wp;nt.DropdownItem=Ep;var A=nt;import{useEffect as Dt,useRef as ps,useState as jp}from"react";import{useDispatch as zp}from"react-redux";import{Interweave as Wp}from"interweave";import Di from"classnames";var rs={root:"_root_7hhs4_1",agentText:"_agentText_7hhs4_3",textInput:"_textInput_7hhs4_8",textInputWrapper:"_textInputWrapper_7hhs4_27",alert:"_alert_7hhs4_31",alertText:"_alertText_7hhs4_50",warning:"_warning_7hhs4_60",success:"_success_7hhs4_69"};import{Matcher as Lp}from"interweave";import Ap from"classnames";import{useEffect as kp,useRef as Rp,useState as Ip}from"react";function Ci(t,e){let n;return[(...o)=>{window.cancelAnimationFrame(n);let s=e?e(...o):o;n=window.requestAnimationFrame(()=>{t(...s)})},()=>window.cancelAnimationFrame(n)]}function qn(t){let e=Rp(null),[n,o]=Ip(!1);return kp(()=>{let s=!1,r=parseFloat(window.getComputedStyle(document.body).zoom??"1"),[i,a]=Ci((u,d)=>{let p=e.current;if(!p)return;let m=u/r,g=d/r,f=p.getBoundingClientRect(),T=m>f.x&&m<f.x+f.width&&g>f.y&&g<f.y+f.height;T&&!s?(s=!0,o(!0)):!T&&s&&(s=!1,o(!1))},({clientX:u,clientY:d})=>[u,d]),[l,c]=Ci(()=>{s=!1,o(!1)});return t.addEventListener("mousemove",i),t.addEventListener("mouseleave",l),()=>{a(),c(),t.removeEventListener("mousemove",i),t.removeEventListener("mouseleave",l)}},[e]),[e,n]}var J={root:"_root_kpc8q_1",agentText:"_agentText_kpc8q_4",tabText:"_tabText_kpc8q_9",hint:"_hint_kpc8q_10",matchSelection:"_matchSelection_kpc8q_14",focus:"_focus_kpc8q_20",resetIndent:"_resetIndent_kpc8q_24",matchKeyword:"_matchKeyword_kpc8q_28",matchPlaceholder:"_matchPlaceholder_kpc8q_29",hover:"_hover_kpc8q_35",hintText:"_hintText_kpc8q_67",popover:"_popover_kpc8q_75",popoverRoot:"_popoverRoot_kpc8q_80",popoverContentContainer:"_popoverContentContainer_kpc8q_84",popoverContent:"_popoverContent_kpc8q_84",selectionOptions:"_selectionOptions_kpc8q_110",selectionOptionsIsHidden:"_selectionOptionsIsHidden_kpc8q_115",selectionOptionsButton:"_selectionOptionsButton_kpc8q_119",caret:"_caret_kpc8q_135",popoverSuggestionsRoot:"_popoverSuggestionsRoot_kpc8q_139",suggestionsOverlayInputStyles:"_suggestionsOverlayInputStyles_kpc8q_144"};import{jsx as Ti}from"react/jsx-runtime";var Mp=({inputElement:t,children:e})=>{let n=y("TabCompletion",J),[o,s]=qn(t);return Ti("mark",{ref:o,className:Ap(n.matchPlaceholder,{[n.hover]:s}),children:e})},ot=class extends Lp{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 Ti(Mp,{inputElement:n.inputElement,children:e},`placeholder_${n.matchString}_${n.key}`)}asTag(){return"mark"}};import{useEffect as Op,useRef as Np,useState as Dp}from"react";function jn(t){return t.contentEditable==="true"}function Hp(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 bi(t){let{selectionStart:e,selectionEnd:n}=jn(t)?Hp(t):t;return[e,n]}function zn(t){let[,e]=Dp(),n=Np(null);return n.current=bi(t),Op(()=>{let o=()=>{let[s,r]=n.current??[],i=bi(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 Wn(t,e){if(!e)return;let n=t,{value:o}=n,[s,r]=e,i=o.match(Qe);if(!i||i.length===0)return;let a=0;i.find(l=>{let c=o.indexOf(l,a);return s>c&&r<c+l.length?(n.selectionStart=c,n.selectionEnd=c+l.length,!0):(a=c+l.length,!1)})}import{useEffect as Fp}from"react";function st(t){Fp(()=>{let e=n=>{n.isWithinRoot||t(n)};return document.body.addEventListener("mouseup",e),()=>{document.body.removeEventListener("mouseup",e)}},[t])}function Ue(t){t.addEventListener("mouseup",e=>{e.isWithinRoot=!0},!0)}var wi,oe=new Map,Bp=["bottom","height","left","right","top","width"],Kp=(t={},e={})=>Bp.some(n=>t[n]!==e[n]),Ei=()=>{let t=[];oe.forEach((e,n)=>{if(!n.isConnected){e.rect=null,t.push(e),oe.delete(n);return}let o=n.getBoundingClientRect();Kp(o,e.rect)&&(e.rect=o,t.push(e))}),t.forEach(e=>{e.callbacks.forEach(n=>n(e.rect))}),oe.size!==0&&(wi=window.requestAnimationFrame(Ei))};function _i(t,e){return{observe(){let n=oe.size===0;if(oe.has(t)){let o=oe.get(t);o.callbacks.push(e),o.rect&&e(o.rect)}else oe.set(t,{rect:void 0,callbacks:[e]});n&&Ei()},unobserve(){let n=oe.get(t);if(n){let o=n.callbacks.indexOf(e);o>=0&&n.callbacks.splice(o,1),n.callbacks.length||oe.delete(t),oe.size||cancelAnimationFrame(wi)}}}}var Pi,se=new Map,ki=()=>{se.forEach((t,e)=>{if(!e.isConnected){se.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)))}),se.size!==0&&(Pi=window.requestAnimationFrame(ki))};function Ri(t,e){return{observe(){let n=se.size===0;se.has(t)?se.get(t).callbacks.push(e):se.set(t,{visible:void 0,callbacks:[e]}),n&&ki()},unobserve(){let n=se.get(t);if(n){let o=n.callbacks.indexOf(e);o>=0&&n.callbacks.splice(o,1),n.callbacks.length||se.delete(t),se.size||cancelAnimationFrame(Pi)}}}}var is=["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 as(t,e,n){return n.forEach(o=>{e.style[o]=t[o]})}function rt(t){return parseFloat(t)}function Gn(t){return Math.round(t*1e6)}function Ii(t){return t/1e6}function ls(t,e,n){if(t.boxSizing==="content-box")return;let{clientWidth:o}=e,s=rt(t.width),r=rt(t.borderLeftWidth),i=rt(t.borderRightWidth),a=rt(t.paddingRight),l=Ii(Gn(s)-Gn(r)-Gn(i)),c=Ii(Gn(o));if(l-c>2){let u=l-c;n.style.paddingRight=`${a+u}px`}}function Nt(t,e={}){var l;let n=e.overlayContainer||document.createElement("div");n.style.display="none",n.style.position="fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",Ue(n);let o=window.getComputedStyle(t),s=!0,r=()=>{n.scrollTop=t.scrollTop};as(o,n,is),ls(o,t,n),e.mirrorOverflow&&(n.style.overflow="hidden",t.addEventListener("scroll",r));let i=Ri(t,()=>{as(o,n,is),ls(o,t,n),r(),setTimeout(r,0)}),a=_i(t,c=>{if(c===null){e.onRemove&&e.onRemove(),n.remove();return}if(c.height===0&&c.width===0){if(s===!0)return;e.onHide&&e.onHide(),n.style.display="none",s=!0;return}if(as(o,n,is),ls(o,t,n),r(),n.style.top=`${c.top}px`,n.style.left=`${c.left}px`,e.closestScrollElement&&e.closestScrollElement!==t){let u=e.closestScrollElement.getBoundingClientRect(),d=window.getComputedStyle(e.closestScrollElement),p=rt(d.borderTopWidth),m=rt(d.borderBottomWidth),g=u.top+p-c.top,f=c.top+c.height+-(u.top+u.height-m);n.style.clipPath=`inset(${g}px 0px ${f}px 0px)`}s&&(n.style.display="block",e.onShow&&e.onShow(),s=!1)});return e.appendTo?e.appendTo.appendChild(n):(l=t.parentElement)==null||l.appendChild(n),a.observe(),i.observe(),[n,()=>{t.removeEventListener("scroll",r),a.unobserve(),i.unobserve()}]}var cs={};B(cs,{enUS:()=>Up,nlNL:()=>Vp});var Up={placeholders:[{type:6,value:"placeholderSize",options:{"=0":{value:[{type:0,value:"No placeholders found"}]},one:{value:[{type:0,value:"There is one placeholder in your message"}]},other:{value:[{type:0,value:"There are "},{type:7},{type:0,value:" placeholders in your message"}]}},offset:0,pluralType:"cardinal"}]},Vp={placeholders:[{type:6,value:"placeholderSize",options:{"=0":{value:[{type:0,value:"Alle placeholders zijn uit je bericht"}]},one:{value:[{type:0,value:"Er is 1 placeholder in jouw bericht"}]},other:{value:[{type:0,value:"Er zijn "},{type:7},{type:0,value:" placeholders in jouw bericht"}]}},offset:0,pluralType:"cardinal"}]};import{jsx as Li,jsxs as qp}from"react/jsx-runtime";var Ai=()=>qp("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 512 512","aria-labelledby":"circleCheckTitle",children:[Li("title",{id:"circleCheckTitle",children:"Check"}),Li("path",{d:"M243.8 339.8C232.9 350.7 215.1 350.7 204.2 339.8L140.2 275.8C129.3 264.9 129.3 247.1 140.2 236.2C151.1 225.3 168.9 225.3 179.8 236.2L224 280.4L332.2 172.2C343.1 161.3 360.9 161.3 371.8 172.2C382.7 183.1 382.7 200.9 371.8 211.8L243.8 339.8zM512 256C512 397.4 397.4 512 256 512C114.6 512 0 397.4 0 256C0 114.6 114.6 0 256 0C397.4 0 512 114.6 512 256zM256 48C141.1 48 48 141.1 48 256C48 370.9 141.1 464 256 464C370.9 464 464 370.9 464 256C464 141.1 370.9 48 256 48z"})]});import{jsx as Mi}from"react/jsx-runtime";var Oi=()=>Mi("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",fill:"currentColor",children:Mi("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 Ni=(i=>(i.CUT="Cut",i.BACKSPACE="Backspace",i.DELETE="Delete",i.ERASEEOF="EraseEof",i.UNDO="Undo",i.CLEAR="Clear",i))(Ni||{}),Pe=class{constructor(e){this.element=e;this.currentText=this.getText(),this.currentHTML=this.getHTML(),this.listen()}eventListeners={};disposeHandlers=[];currentText="";currentHTML="";currentSelection=null;isFocused=!1;isActive=!0;isSettingValue=!1;isSubmitting=!1;isPossibleClearInputAction=!1;isDisposed=!1;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)}triggerChange(){let e=this.getText(),n=this.getHTML(),o=e!==this.currentText;this.isActive&&(e===""&&this.currentText!==""&&!this.isSettingValue&&!this.isPossibleClearInputAction&&(this.isSubmitting=!0,this.emit("submit")),!this.isSettingValue&&o&&!this.isSubmitting&&this.emit("change",{plainText:e,rawHtml:n}),this.currentText=e,this.isSubmitting=!1,(this.currentHTML!==n||n===null&&o)&&(this.emit("updated",{plainText:e,rawHtml:n}),this.currentHTML=n))}handleKeyUp(e){let{key:n,shiftKey:o}=e;(n==="Enter"&&o===!0||n==="Backspace")&&this.triggerChange()}handleFocus(){this.isFocused||this.emit("focus"),this.isFocused=!0}handleBlur(){this.isPossibleClearInputAction=!1,this.isFocused&&this.emit("blur"),this.isFocused=!1}handleKeyDown(e){let{key:n,ctrlKey:o,metaKey:s}=e;this.isPossibleClearInputAction=Object.values(Ni).includes(n)||n.toLowerCase()==="z"&&(o||s),this.emit("keydown",e)}handleCut(){let e=this.currentSelection;this.isPossibleClearInputAction=!0,e&&this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(e){let n=(e.clipboardData||window.clipboardData).getData("text");this.emit("paste",{pastedText:n,selectionText:this.getSelectedText()})}listen(){let e=()=>{let o=document.activeElement===this.element?this.getSelection():null;be(this.currentSelection,o)||(this.currentSelection=o,this.emit("selection",o))};document.addEventListener("selectionchange",e),this.disposeHandlers.push(()=>{window.document&&document.removeEventListener("selectionchange",e)}),this.addEventListener("keydown",o=>this.handleKeyDown(o)),this.addEventListener("keyup",o=>this.handleKeyUp(o)),this.addEventListener("input",()=>this.triggerChange()),this.addEventListener("change",()=>this.triggerChange()),this.addEventListener("focus",()=>this.handleFocus()),this.addEventListener("blur",()=>this.handleBlur()),this.addEventListener("cut",()=>this.handleCut()),this.addEventListener("paste",o=>this.handlePaste(o)),document.activeElement===this.element&&setTimeout(()=>{this.handleFocus()},0);let n=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});n.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{n.disconnect()})}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))}activate(){let e=this.isActive===!1;this.isActive=!0,e&&this.triggerChange()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(e=>e()),this.eventListeners={},this.isDisposed=!0}};var ke=class extends Pe{getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:e,selectionEnd:n}=this.element;return{start:e,end:n}}getSelectedText(){return this.currentSelection?this.getText().slice(this.currentSelection.start,this.currentSelection.end):""}applyChanges(e){if(!this.isActive)return;this.isSettingValue=!0;let n=this.getText(),o=e(this.element);Promise.resolve(o).then(()=>{this.currentText=this.getText(),n!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(){super.listen();let e=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var s;return(s=e==null?void 0:e.get)==null?void 0:s.call(this.element)},set:s=>{var r;(r=e==null?void 0:e.set)==null||r.call(this.element,s),this.triggerChange()}});let n=this.element.disabled,o=new MutationObserver(()=>{this.element.disabled!==n&&(n=this.element.disabled,this.emit(n?"disabled":"enabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>o.disconnect())}};import{jsx as ce,jsxs as us}from"react/jsx-runtime";var Gp=({value:t,onUse:e,...n})=>{var u;let o=_(cs),s=zp(),r=y("EditSuggestionTextInput",rs),[i,a]=jp(null),l=ps(null),c=((u=t.match(Qe))==null?void 0:u.length)||0;return Dt(()=>{let d;return l.current&&(a(l.current),d=new ke(l.current),d.on("change",({plainText:p})=>{s(j.actions.userInput({text:p,selection:d.getSelection()}))}),d.on("keydown",p=>{s(j.actions.registerKeyDown(Cn(p))),p.code==="Enter"&&p.shiftKey&&e(d.getText())}),d.on("paste",({pastedText:p,selectionText:m})=>{s(j.actions.registerPaste({text:p,selectionText:m}))}),d.on("cut",({selectionText:p})=>{s(j.actions.registerCut(p))})),()=>{s(j.actions.reset()),d.dispose(),d.deactivate()}},[l]),Dt(()=>{t&&l.current&&(l.current.value=t)},[t,l]),Dt(()=>{l.current&&setTimeout(()=>{if(!l.current)return;let d=l.current.value.length;l.current.setSelectionRange(d,d),l.current.focus()},0)},[l]),us("div",{className:r.textInputWrapper,children:[ce("textarea",{...n,ref:l,"data-testid":"edit-suggestion-dialog-textarea",className:r.textInput,defaultValue:t,onChange:()=>{}}),i&&ce($p,{inputElement:l.current,value:t}),us("div",{className:Di(r.alert,c===0?r.success:r.warning),children:[ce("div",{className:r.alertText,children:o("placeholders",{placeholderSize:c})}),c===0?ce(Ai,{}):ce(Oi,{})]})]})},$p=({inputElement:t,value:e})=>{let n=y("EditSuggestionTextInput",rs),o=ps(null),s=zn(t);return Dt(()=>{Wn(t,s)},[s,t]),ce(Xp,{inputElement:t,children:us("div",{ref:o,className:Di(n.root,n.agentText),children:[ce(Wp,{noWrap:!0,disableLineBreaks:!0,content:e,matchers:[new ot("placeholders")],inputElement:t,boundaryRef:o}),ce("br",{})]})})},Xp=({inputElement:t,children:e})=>{let n=ps(null);return Dt(()=>{if(!n.current)return()=>{};let[o,s]=Nt(t,{overlayContainer:n.current,mirrorOverflow:!0});return()=>{s()}},[n.current]),ce("div",{ref:n,children:e})},Hi=Gp;import{useEffect as Pd,useState as kd,useRef as Rd}from"react";var z={root:"_root_1vexi_1",list:"_list_1vexi_2",listWrapper:"_listWrapper_1vexi_6",listHorizontal:"_listHorizontal_1vexi_10",page:"_page_1vexi_19",search:"_search_1vexi_25",pageNav:"_pageNav_1vexi_33",pageBackButton:"_pageBackButton_1vexi_38",listHeading:"_listHeading_1vexi_52",listItem:"_listItem_1vexi_60",listItemContent:"_listItemContent_1vexi_69",listItemText:"_listItemText_1vexi_87",listItemDescription:"_listItemDescription_1vexi_95",truncate:"_truncate_1vexi_102",lineClamp:"_lineClamp_1vexi_108",listItemTitle:"_listItemTitle_1vexi_115",listItemAction:"_listItemAction_1vexi_122",listItemPrimaryAction:"_listItemPrimaryAction_1vexi_136",listItemSelected:"_listItemSelected_1vexi_141",sources:"_sources_1vexi_145",sourcesTitle:"_sourcesTitle_1vexi_152",source:"_source_1vexi_145",icon:"_icon_1vexi_167",searchIcon:"_searchIcon_1vexi_184",searchInputWrapper:"_searchInputWrapper_1vexi_189",searchInput:"_searchInput_1vexi_189",select:"_select_1vexi_210",selectType:"_selectType_1vexi_227",selectWrapper:"_selectWrapper_1vexi_231",image:"_image_1vexi_261",imageSrc:"_imageSrc_1vexi_268",imageTitle:"_imageTitle_1vexi_279",actions:"_actions_1vexi_284",actionsWrapper:"_actionsWrapper_1vexi_286",actionsBar:"_actionsBar_1vexi_292",actionButton:"_actionButton_1vexi_301",actionShortcut:"_actionShortcut_1vexi_319",actionShortcutFixKerning:"_actionShortcutFixKerning_1vexi_326"};import{jsx as Fi,jsxs as Qp}from"react/jsx-runtime";var Jp=({src:t,title:e})=>{let n=y("CommandPalette",z);return Qp("div",{className:n.image,children:[Fi("img",{src:t,alt:e,className:n.imageSrc}),e&&Fi("span",{className:n.imageTitle,children:e})]})},Bi=Jp;import Zp from"react";import Yp from"classnames";import{jsx as Ki,jsxs as ed}from"react/jsx-runtime";function ds({children:t,heading:e,orientation:n}){let o=y("CommandPalette",z);return Zp.Children.count(t)===0?null:ed("div",{"data-testid":"commandpalette-list",className:o.list,children:[e&&Ki("h4",{className:o.listHeading,children:e}),Ki("div",{className:Yp(o.listWrapper,n==="horizontal"&&o.listHorizontal),children:t})]})}import $n from"classnames";var Ui={root:"_root_nkim0_1"};var ms={};B(ms,{enUS:()=>td,nlNL:()=>nd});var td={experimental:[{type:0,value:"Experimental"}]},nd={experimental:[{type:0,value:"Experimenteel"}]};import{jsx as qi}from"react/jsx-runtime";var Vi=({children:t})=>{let e=y("Chip",Ui);return qi("span",{className:e.root,children:t})},Re=()=>{let t=_(ms);return qi(Vi,{children:t("experimental")})},od=Vi;import gs from"react";import{jsx as sd}from"react/jsx-runtime";var ji=gs.createContext(void 0);function Ie(){let t=gs.useContext(ji);if(t===void 0)throw new Error("useCommandPalette must be used within the CommandPalette component");return t}var zi=({children:t,page:e,isOpen:n,onChangeOpen:o,selected:s,setSelected:r})=>{let i=gs.useMemo(()=>({page:e,isOpen:n,onChangeOpen:o,selected:s,setSelected:r}),[n,e,s]);return sd(ji.Provider,{value:i,children:t})};import{jsx as it,jsxs as Xn}from"react/jsx-runtime";function fs({closeOnSelect:t=!0,lineClamp:e,children:n,onClick:o,index:s,isExperimental:r,description:i,sources:a,styles:l,...c}){let{selected:u,onChangeOpen:d}=Ie(),p=y("CommandPalette",z);function m(g){o(g),t&&d(!1)}return Xn("div",{className:$n(p.listItem,u===s&&p.listItemSelected),children:[Xn("button",{type:"button",className:$n("command-palette-list-item",p.listItemAction,p.listItemPrimaryAction),"aria-disabled":c.disabled??!1,onClick:m,...c,children:[Xn("div",{className:p.listItemContent,children:[typeof n=="string"?it("p",{className:$n(p.listItemText,p.truncate,l==null?void 0:l.title),children:n}):n,i&&it("p",{className:$n(p.listItemDescription,l==null?void 0:l.description,e?p.lineClamp:p.truncate),children:i})]}),r&&it(Re,{})]}),a&&Xn("div",{className:p.sources,children:[it("span",{className:p.sourcesTitle,children:"Sources"}),a.map(g=>g.url?it("a",{className:p.source,href:g.url,target:"_blank",title:g.url,rel:"noopener noreferrer",children:g.name},g.url):it("span",{className:p.source,children:g.name},g.name))]})]})}var Ht={};B(Ht,{enUS:()=>rd,nlNL:()=>id});var rd={visitUrl:[{type:0,value:"Visit"}],back:[{type:0,value:"Back"}]},id={visitUrl:[{type:0,value:"Bekijk"}],back:[{type:0,value:"Terug"}]};import{jsx as Wi,jsxs as Gi}from"react/jsx-runtime";function hs({children:t,id:e,onDismiss:n}){let o=_(Ht),s=y("CommandPalette",z),{page:r}=Ie();return r!==e?null:Gi("div",{className:s.page,id:`page_${e}`,tabIndex:-1,children:[n&&Wi("div",{className:s.pageNav,children:Gi("button",{className:s.pageBackButton,type:"button",onClick:n,children:[Wi(Un,{}),o("back")]})}),t]})}import{Fragment as vd,useCallback as xd,useEffect as Cd,useRef as Td}from"react";var Jn=()=>/Mac/i.test(navigator.platform);import{createAction as pd,createAsyncThunk as dd,createSlice as md}from"@reduxjs/toolkit";var ad={info(...t){console.info("[Deepdesk]",...t)},warn(...t){console.warn("[Deepdesk]",...t)},error(...t){console.error("[Deepdesk]",...t)}},P=ad;import{createAsyncThunk as Ss,createSlice as cd}from"@reduxjs/toolkit";function ld(t){return t.replace(/(_\w)/g,e=>e[1].toUpperCase())}function L(t){return Array.isArray(t)?t.map(L):typeof t=="object"&&t!==null?Object.keys(t).reduce((e,n)=>({...e,[ld(n)]:L(t[n])}),{}):t}function ys(t){return t.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}function H(t){return Array.isArray(t)?t.map(H):typeof t=="object"&&t!==null?Object.keys(t).reduce((e,n)=>({...e,[ys(n)]:H(t[n])}),{}):t}var ud={agentInfo:void 0,agentSettings:{},visitorInfo:void 0,fetchState:"idle"},Bt=t=>{var e,n,o;return{timezone:((e=t.info.visitorInfo)==null?void 0:e.visitorTimeZone)||Intl.DateTimeFormat().resolvedOptions().timeZone,agentName:((n=t.info.agentInfo)==null?void 0:n.agentNickname)||"",visitorName:((o=t.info.visitorInfo)==null?void 0:o.visitorName)||""}},Ft=Ss("info/setAgentInfo",async(t,e)=>{let{deepdeskAPI:n}=e.extra;if(!t.agentId&&!t.agentNickname)throw new Error("At least provide agentId or agentNickname");let o=await n.client.get("/apis/admin/session/me/",{version:null}),s={};return o.external_id||(s.external_id=t.agentId),o.nickname||(s.nickname=t.agentNickname),!s.external_id&&!s.nickname?L(o):(await n.client.patch("/apis/admin/session/me/",s,{version:null}),L(o))}),vs=Ss("info/setAgentSettings",async(t,e)=>{let{deepdeskAPI:n}=e.extra,o=await n.client.get("/apis/admin/session/me/",{version:null}),s={...typeof o.ui_config=="object"?o.ui_config:{},...t};return await n.client.patch("/apis/admin/session/me/",{ui_config:s}),s}),xs=Ss("info/getAgentSettings",async(t,e)=>{let{deepdeskAPI:n}=e.extra;return(await n.client.get("/apis/admin/session/me/",{version:null})).ui_config}),$i=t=>t.info.agentInfo,Xi=cd({name:"info",initialState:ud,reducers:{setVisitorInfo(t,e){t.visitorInfo={...t.visitorInfo,...e.payload}}},extraReducers:t=>{t.addCase(Ft.pending,(e,n)=>{e.fetchState="loading",e.agentInfo={...e.agentInfo,...n.meta.arg}}).addCase(Ft.rejected,e=>{e.fetchState="error"}).addCase(Ft.fulfilled,(e,n)=>{e.fetchState="done",e.agentInfo={...e.agentInfo,...n.meta.arg,agentId:n.payload.externalId||n.meta.arg.agentId||"",agentNickname:n.payload.nickname||n.meta.arg.agentNickname||""}}).addCase(vs.fulfilled,(e,n)=>{e.agentSettings=n.payload}).addCase(xs.fulfilled,(e,n)=>{e.agentSettings=n.payload}).addCase(k,e=>{e.visitorInfo=void 0})}}),{setVisitorInfo:Ji}=Xi.actions,Qi=Xi.reducer;var Qn={list:[],fetchState:"idle",isOpen:!1},Zi=t=>t.search.isOpen,Yi=t=>t.search.list;function ea(t,e=n=>n){return n=>n.search.list.filter(o=>o.type===t).map(e)}var Ve=dd("search/getAll",async(t,e)=>{var i;let{deepdeskAPI:n}=e.extra,o=e.getState(),s=(i=o.conversation.current)==null?void 0:i.profileCode;if(!s)throw new Error("Profile should be provided in order to be able to search");let{results:r}=await n.search({profile:s,query:t.query,filters:{type:t.type},params:Bt(o),tags:t.tags});return r}),Q=pd("search/setIsOpen"),ta=md({name:"search",initialState:Qn,reducers:{resetSearch(t){t.fetchState=Qn.fetchState,t.list=Qn.list}},extraReducers:t=>{t.addCase(Ve.pending,e=>{e.fetchState="loading"}).addCase(Ve.rejected,(e,n)=>{e.fetchState="error",P.error(n.error)}).addCase(Ve.fulfilled,(e,n)=>{e.fetchState="done",e.list=n.payload}).addCase(Q,(e,n)=>{e.isOpen=n.payload}).addCase(k,()=>Qn)}}),{resetSearch:Zn}=ta.actions,na=ta.reducer;var gd=/(https?:\/\/[^\s]+)/,Yn=t=>t.split(" ").find(e=>gd.test(e));import fd from"classnames";import{jsx as yd,jsxs as Sd}from"react/jsx-runtime";var hd=({onClick:t,shortKeys:e,children:n,...o})=>{let s=y("CommandPalette",z);return Sd("button",{type:"button",...o,onClick:t,className:s.actionButton,children:[n,e&&e.map(r=>yd("span",{className:fd(s.actionShortcut,r===8629&&s.actionShortcutFixKerning),children:typeof r=="number"?String.fromCharCode(r):r},r))]})},at=hd;import{jsx as eo,jsxs as Cs}from"react/jsx-runtime";var bd=({children:t,primaryLabel:e,secondaryLabel:n,onPrimary:o,onSecondary:s,list:r})=>{let i=y("CommandPalette",z),a=_(Ht),{selected:l,setSelected:c}=Ie(),u=r[l],d=u&&typeof u.text=="string"&&Yn(u.text),p=Td(null);function m(S){if(!p.current)return;let w=p.current.querySelectorAll(".command-palette-list-item"),C=0,x=0;S==="down"?(w.forEach((q,D)=>{D===l&&(C=D)}),x=C===w.length-1?0:C+1):S==="up"?(w.forEach((q,D)=>{D===l&&(C=D)}),x=C?C-1:w.length-1):c(0);let N=w[x];N&&typeof x=="number"&&(c(x),N.scrollIntoView&&N.scrollIntoView({behavior:"smooth",block:x?"center":"end"}))}function g(){if(!p.current)return;let S=p.current.querySelectorAll(".command-palette-list-item"),w=0;S.forEach((x,N)=>{N===l&&(w=N)});let C=S[w];C&&C.click()}let f=()=>{d&&window.open(d,"_blank")},T=()=>{u&&o(u,l)},b=()=>{!u.type||["IMAGE","command"].includes(u.type)||s&&s(u,l)},h=xd(S=>{if(S.key==="Enter"&&S.altKey&&d){f();return}if(S.key==="Enter"&&S.shiftKey){b();return}if(S.key==="ArrowDown"){S.preventDefault(),S.stopPropagation(),m("down");return}if(S.key==="ArrowUp"){S.preventDefault(),S.stopPropagation(),m("up");return}S.key==="Enter"&&l!==-1&&(S.preventDefault(),S.stopPropagation(),g())},[l]);return Cd(()=>(window.addEventListener("keyup",h),()=>{window.removeEventListener("keyup",h)}),[h]),Cs("div",{className:i.actions,children:[eo("div",{className:i.actionsWrapper,ref:p,children:t}),Cs("div",{className:i.actionsBar,children:[d&&eo(at,{onClick:f,shortKeys:[Jn()?8997:"ALT",8629],children:a("visitUrl")}),u&&Cs(vd,{children:[s&&u.type&&!["command","image"].includes(u.type.toLowerCase())&&eo(at,{onClick:b,shortKeys:[8679,8629],children:n}),eo(at,{onClick:T,shortKeys:[8629],children:e})]})]})]})},sa=bd;import{forwardRef as Ed}from"react";import{jsx as ra,jsxs as wd}from"react/jsx-runtime";var to=()=>wd("svg",{xmlns:"http://www.w3.org/2000/svg",height:"24px",viewBox:"0 0 24 24",width:"24px",fill:"currentColor",children:[ra("path",{d:"M0 0h24v24H0z",fill:"none"}),ra("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"})]});import{jsx as lt,jsxs as Ts}from"react/jsx-runtime";function _d({onChange:t,onChangeType:e,placeholder:n,typePlaceholder:o,types:s,value:r,selectedType:i},a){let l=y("CommandPalette",z);return Ts("div",{className:l.search,children:[lt("div",{className:l.searchIcon,children:lt(to,{})}),Ts("div",{className:l.searchInputWrapper,children:[lt("input",{ref:a,spellCheck:!1,onChange:c=>{t(c.currentTarget.value)},onFocus:c=>{c.currentTarget.select()},className:l.searchInput,placeholder:n,value:r,type:"text",id:"command-palette-search-input",autoFocus:!0}),s&&s.length>0&&lt("div",{className:l.selectWrapper,children:Ts("select",{"data-testid":"command-palette-type-select",className:l.select,onChange:c=>e(c.target.value===o?void 0:c.target.value),value:i||o,children:[o&&lt("option",{children:o}),s.map(c=>lt("option",{value:c.value,children:c.label},c.value))]})})]})]})}var ia=Ed(_d);import{jsx as aa,jsxs as Id}from"react/jsx-runtime";function qe({placeholder:t="Start typing to search...",typePlaceholder:e="All types",defaultPage:n="search",page:o,onChangePage:s,onChangeSearch:r,onChangeType:i,onChangeOpen:a,selectedType:l,types:c,children:u,isOpen:d,search:p}){let[m,g]=kd(0),f=Rd(null),T=()=>{s&&s(n),i(void 0),r(""),a(!1)},b=()=>{var h;if(o!==n&&s){s(n);return}if(l&&i){i(void 0),(h=f.current)==null||h.focus();return}if(p.length>0){r("");return}a(!1)};return Pd(()=>{g(0)},[p,o]),aa(et,{autoFocus:!0,contentAriaLabel:"Search Results",overlayAriaLabel:"Command Palette",isOpen:d,onBack:b,onClose:T,children:Id(zi,{selected:m,setSelected:g,isOpen:d,onChangeOpen:a,page:o,children:[o===n&&aa(ia,{ref:f,onChange:r,onChangeType:i,placeholder:t,value:p,selectedType:l,types:c,typePlaceholder:e}),u]})})}qe.Page=hs;qe.List=ds;qe.Image=Bi;qe.ListItem=fs;qe.ActionsBar=sa;qe.Button=at;var R=qe;import{jsx as ue,jsxs as Kt}from"react/jsx-runtime";var Md=({suggestion:t,onUse:e,onDismiss:n,onTouched:o,onNext:s,onPrevious:r})=>{let i=t.text||t.url||t.message,a=y("EditSuggestionForm",li),l=Ld(),c=_($o),u=Ad(g=>g.overlayInput.text);la(()=>{t&&(l(j.actions.reset()),l(j.actions.stageSuggestion({text:i,suggestion:t,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"})),l(j.actions.commitSuggestion()))},[t]);let d=g=>{g.preventDefault(),p(u)},p=g=>{l(wn(g)),e(g)},m=g=>f=>{u!==i?window.confirm(c("warning"))&&g(f):g(f)};return la(()=>{o&&o(u!==i)},[o,t,u]),Kt("div",{className:a.root,children:[Kt("div",{className:a.content,children:[t.title&&ue("h3",{className:a.title,children:t.title}),t.searchKeywords&&t.searchKeywords.length>0&&ue(ss,{labels:t.searchKeywords}),ue(Hi,{onUse:p,value:u})]}),Kt("form",{className:a.actions,onSubmit:d,children:[Kt("div",{children:[ue("button",{disabled:!r,className:a.pagination,type:"button",onClick:r&&m(r),children:ue(Un,{})}),ue("button",{disabled:!s,className:a.pagination,type:"button",onClick:s&&m(s),children:ue(xi,{})})]}),Kt("div",{className:a.primaryButtons,children:[ue(R.Button,{onClick:m(n),shortKeys:["esc"],children:c("dismiss")}),ue(R.Button,{shortKeys:[8679,8629],type:"submit",children:c("add")})]})]})]})},no=Md;import{createAction as Dd,createAsyncThunk as da,createSlice as Hd}from"@reduxjs/toolkit";var Od=["{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}"],Nd=new RegExp(Od.map(t=>`(?:${t.replace("{","\\{").replace("}","\\}")})`).join("|"));function ca(t,e){let n=t.split(Nd),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],l=r===n.length-2;o+=i.length;let c=o;if(l){let d=a.charAt(0),p=0;do c=d?e.indexOf(d,c+1):-1,p+=1;while(c!==-1&&a.indexOf(e.slice(c))!==0);if(c===-1&&p>2)return t}else c=a&&a!==""?e.indexOf(a,o):-1;let u=c===-1?e.slice(o):e.slice(o,c);s.push(u),o=c}return s.join("")}function ua(t,e){return typeof e=="boolean"?t:t.slice(0,e)}var ma={suggestions:[],fetchState:"idle",isInitialRequest:null},pa={default:ma},ga=t=>e=>e.textSuggestions[t].suggestions,fa=t=>e=>{var n;return((n=e.textSuggestions[t])==null?void 0:n.suggestions)??[]},ha=t=>{let e=Object.keys(t.textSuggestions).map(n=>{var o;return(o=t.textSuggestions[n])==null?void 0:o.fetchState});return e.length===0?!0:e.every(n=>n!=="done")},ct=t=>t.textSuggestions,ya=t=>e=>e.text.startsWith(t),oo=Dd("textSuggestions/refresh"),pe=da("textSuggestions/recommendations",async(t,e)=>{var c;let{deepdeskAPI:n}=e.extra,o=e.getState(),s=(c=o.conversation.current)==null?void 0:c.id,{textSuggestionsCount:r,inlineSuggestions:i}=o.settings,a=Ye(o);if(!s)throw new Error("No current conversation to fetch text suggestions");let l=await n.getTextSuggestions(s,Bt(o),t);if(t==="default"){let u=i?l.filter(ya(a)):l;e.dispatch(Ee(u.slice(0,r)))}return l}),Ut=da("textSuggestions/autocompletions",async(t,e)=>{var c;let{deepdeskAPI:n}=e.extra,o=e.getState(),s=(c=o.conversation.current)==null?void 0:c.id,{textSuggestionsCount:r,deanonymize:i,inlineSuggestions:a}=o.settings;if(!s)throw new Error("No current conversation to fetch text suggestions");let l=await n.getAutocompleteSuggestions(s,{...Bt(o),input:t});if(!e.getState().input.text)throw new Error("Abort");return a&&(l=l.filter(ya(t))),i&&(l=l.map(u=>({...u,text:u.source!=="trie-with-typos"?ca(u.text,t):u.text}))),l=ua(l,r),e.dispatch(Ee(l)),l}),Sa=Hd({name:"textSuggestions",initialState:pa,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}}}},setSuggestionState(t,e){return e.payload}},extraReducers:t=>{t.addCase(pe.pending,(e,n)=>{let o=n.meta.arg,s=e[o]||ma;return{...e,[o]:{...s,fetchState:"loading",isInitialRequest:s.isInitialRequest===null}}}).addCase(pe.rejected,(e,n)=>{let o=n.meta.arg;e[o].fetchState="error"}).addCase(pe.fulfilled,(e,n)=>{let o=n.meta.arg;e[o].fetchState="done",e[o].suggestions=n.payload}).addCase(Ut.pending,e=>{e.default.fetchState="loading"}).addCase(Ut.rejected,e=>{e.default.fetchState="error"}).addCase(Ut.fulfilled,(e,n)=>{e.default.fetchState="done",e.default.suggestions=n.payload}).addCase(k,()=>pa)}}),{setTextSuggestions:va,setSuggestionState:xa}=Sa.actions,Ca=Sa.reducer;import{createSlice as Fd}from"@reduxjs/toolkit";var Ta={contentType:null,suggestion:null},ba=t=>t.activeSuggestion.suggestion,wa=t=>t.activeSuggestion.contentType,Ea=Fd({name:"activeSuggestion",initialState:Ta,reducers:{setActiveSuggestion(t,e){let{contentType:n,suggestion:o}=e.payload;t.contentType=n,t.suggestion=o},resetActiveSuggestion(t){t.contentType=null,t.suggestion=null}},extraReducers:t=>{t.addCase(k,()=>Ta)}}),{setActiveSuggestion:de,resetActiveSuggestion:bs}=Ea.actions,_a=Ea.reducer;var ws={};B(ws,{enUS:()=>Bd,nlNL:()=>Kd});var Bd={warning:[{type:0,value:"Are you sure you want to discard the message?"}],editContentLabel:[{type:0,value:"Edit and view suggestion"}],overlayLabel:[{type:0,value:"Close dialog"}]},Kd={warning:[{type:0,value:"Weet je zeker dat je de wijzigingen wilt weggooien?"}],editContentLabel:[{type:0,value:"Bewerk en bekijk suggestie"}],overlayLabel:[{type:0,value:"Sluit"}]};import{createSlice as Ud}from"@reduxjs/toolkit";var Vd={showTabHint:!1,inputHasFocus:!1,overlayCollapsed:!1,openOverlayWhenTyping:!1,overlayCollapsedUserOverwrite:!1};var Pa=({ui:t})=>t.overlayCollapsed;var ka=Ud({name:"ui",initialState:Vd,reducers:{setShowTabHint(t,e){t.showTabHint=e.payload},setInputHasFocus(t,e){t.overlayCollapsedUserOverwrite!==!0&&(e.payload===!0&&(t.overlayCollapsed=!1),t.inputHasFocus=e.payload)},setOverlayCollapsed(t,e){e.payload.collapse===!1&&(t.openOverlayWhenTyping=!1),!(e.payload.skipWhenInputFocus&&t.inputHasFocus)&&(t.overlayCollapsed=e.payload.collapse)},setOpenOverlayWhenTyping(t,e){t.openOverlayWhenTyping=e.payload},setOverlayCollapsedUserOverwrite(t,e){t.overlayCollapsedUserOverwrite=e.payload,t.overlayCollapsed=e.payload}}}),{setShowTabHint:Vt,setInputHasFocus:ut,setOverlayCollapsed:pt,setOpenOverlayWhenTyping:Ra,setOverlayCollapsedUserOverwrite:Ia}=ka.actions,La=ka.reducer;import Aa,{useContext as qd}from"react";import{jsx as jd}from"react/jsx-runtime";var Ma=Aa.createContext(null),qt=({broadcastEvents:t,children:e})=>{let n=Aa.useMemo(()=>t,[]);return jd(Ma.Provider,{value:n,children:e})},re=()=>{let t=qd(Ma);if(!t)throw new Error("You should use the useBroadcastEvents within a BroadcastEventsProvider");return t};import{createAsyncThunk as Es,createSlice as zd}from"@reduxjs/toolkit";var Wd={isLoggedIn:!0,loginFetchState:"idle",verifyFetchState:"idle",showLoginOverlay:!1},me=t=>t.auth.isLoggedIn,Oa=t=>t.auth.loginFetchState,Na=t=>t.auth.verifyFetchState,Da=t=>t.auth.showLoginOverlay,je=Es("auth/validate",async(t,e)=>e.extra.deepdeskAPI.isLoggedIn()),Ha=Es("auth/requestLogin",async({email:t},e)=>{let{deepdeskAPI:n}=e.extra;return n.requestLoginByEmail(t)}),jt=Es("auth/verifyLoginToken",async({token:t},e)=>{let{deepdeskAPI:n}=e.extra;return n.verifyLoginToken(t)}),Fa=zd({name:"auth",initialState:Wd,reducers:{setIsLoggedIn(t,e){t.isLoggedIn=e.payload},setShowLoginOverlay(t,e){t.showLoginOverlay=e.payload}},extraReducers:t=>{t.addCase(je.pending,e=>{e.loginFetchState="loading"}),t.addCase(je.fulfilled,(e,{payload:n})=>{e.isLoggedIn=n,e.loginFetchState="done"}),t.addCase(je.rejected,e=>{e.loginFetchState="error",e.isLoggedIn=!1}),t.addCase(jt.pending,e=>{e.verifyFetchState="loading"}),t.addCase(jt.rejected,e=>{e.verifyFetchState="error"}),t.addCase(jt.fulfilled,(e,n)=>{n.payload.isLoggedIn?e.verifyFetchState="done":e.verifyFetchState="error"})}}),{setIsLoggedIn:Ba,setShowLoginOverlay:Ka}=Fa.actions,Ua=Fa.reducer;var _s="SetActiveSuggestion",dt="ShowLoginOverlay",Ps="UserLoggedIn",ge="ApplySuggestion",ks="ApplyImageSuggestion",Gd=t=>({[_s]:e=>{t.dispatch(xa(e.state)),t.dispatch(de({contentType:e.contentType,suggestion:e.suggestion}))},[dt]:e=>{t.dispatch(Ka(e))},[Ps]:()=>{t.dispatch(je())},[ks]:e=>{t.dispatch(_n({suggestion:e.suggestion}))},[ge]:e=>{t.dispatch(ee({...e,eventMetrics:{inputType:"mouse"},replace:"selection"})),t.dispatch(_e())}}),Va=Gd;import{jsx as qa}from"react/jsx-runtime";var Jd=()=>{var g;let[t,e]=$d(!1),n=Rs(ba),o=Rs(wa),s=Rs(ct),r=Xd(),i=re(),a=_(ws),l=()=>{n!==null&&t?window.confirm(a("warning"))&&c():c()},c=()=>{r(bs()),r(ut(!0)),r(j.actions.reset())},u=(f,T)=>{r(bs()),r(ut(!0)),i.send(ge,{text:f,suggestion:T})};if(n===null||o===null)return null;let d=(g=s[o])==null?void 0:g.suggestions.indexOf(n),p=d===0||d===null?void 0:()=>r(de({contentType:o,suggestion:s[o].suggestions[d-1]})),m=d===s[o].suggestions.length-1||d===null?void 0:()=>r(de({contentType:o,suggestion:s[o].suggestions[d+1]}));return qa(et,{autoFocus:!0,isOpen:d!==null,onClose:l,onBack:l,contentAriaLabel:a("editContentLabel"),overlayAriaLabel:a("overlayLabel"),children:qa(no,{onTouched:e,onDismiss:c,onUse:f=>u(f,n),suggestion:n,onNext:m,onPrevious:p})})},ja=Jd;import{useSelector as Xa}from"react-redux";import Ls from"classnames";import{useCallback as Ga,useEffect as nm,useMemo as om,useState as As}from"react";import{useDispatch as sm,useSelector as rm}from"react-redux";import Qd from"classnames";var za={root:"_root_1ukx5_1"};import{jsx as Yd}from"react/jsx-runtime";var Zd=({className:t,value:e,...n})=>{let o=y("TextInput",za);return Yd("input",{className:Qd(t,o.root),type:"text",value:e,...n})},zt=Zd;var Is={};B(Is,{enUS:()=>em,nlNL:()=>tm});var em={back:[{type:0,value:"Back"}],promptTitle:[{type:0,value:"Sign in to Deepdesk"}],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 Deepdesk 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 Deepdesk first."}],requestCodeInputPlaceholder:[{type:0,value:"Enter your email"}],requestCodeSubmitLabel:[{type:0,value:"Request code"}]},tm={back:[{type:0,value:"Terug"}],promptTitle:[{type:0,value:"Login bij Deepdesk"}],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 Deepdesk gebruiker bent krijg je een email met een code. Als je een nieuwe gebruiker bent wordt er een email verstuurd met een toegangsverzoek voor Deepdesk."}],requestCodeInputPlaceholder:[{type:0,value:"Typ hier je e-mailadres"}],requestCodeSubmitLabel:[{type:0,value:"Code aanvragen"}]};var Wa={root:"_root_1edpl_1",anchorButton:"_anchorButton_1edpl_5",errorMessage:"_errorMessage_1edpl_19",title:"_title_1edpl_25",subtitle:"_subtitle_1edpl_31",text:"_text_1edpl_38",input:"_input_1edpl_43",actions:"_actions_1edpl_48",button:"_button_1edpl_55",primaryButton:"_primaryButton_1edpl_70"};import{jsx as W,jsxs as so}from"react/jsx-runtime";var im=t=>{try{let e=new URL(t);return new URLSearchParams(e.search).get("token")||void 0}catch{return t}},am=({agentEmail:t,isOpen:e,origin:n="",onSuccess:o,onDismiss:s})=>{let r=_(Is),i=y("LoginTokenDialog",Wa),a=rm(Na),l=sm(),[c,u]=As(t||""),[d,p]=As(0),[m,g]=As(""),f=Ga(async S=>{S.preventDefault(),l(Ha({email:c})),p(1)},[n,c]),T=()=>{g(""),p(0)},b=Ga(async S=>{S.preventDefault();let w=im(S.target.elements.token.value);if(!w){g(r("verifyCodeError",{login:h}));return}l(jt({token:w}))},[n]),h=om(()=>S=>W("button",{type:"button","data-testid":"login-token-dialog-back-button",className:i.anchorButton,onClick:T,children:S},"back-button"),[]);return nm(()=>{a==="error"&&g(r("verifyCodeError",{login:h})),a==="done"&&o()},[a]),W(et,{autoFocus:!0,isOpen:e,contentAriaLabel:r("promptTitle"),overlayAriaLabel:r("promptTitle"),onClose:s,onBack:s,children:so("div",{className:i.root,children:[W("h1",{className:i.title,children:r("promptTitle")}),d===0&&so("form",{onSubmit:f,children:[W("h2",{className:i.subtitle,children:r("requestCodeTitle")}),W("p",{className:i.text,children:r("requestCodeBody")}),W(zt,{className:i.input,name:"email",placeholder:r("requestCodeInputPlaceholder"),value:c,onChange:S=>u(S.target.value)}),W("div",{className:i.actions,children:W("button",{type:"submit",className:Ls(i.button,i.primaryButton),children:r("requestCodeSubmitLabel")})})]}),d===1&&so("form",{onSubmit:b,children:[W("h2",{className:i.subtitle,children:r("verifyCodeTitle")}),W("p",{className:i.text,children:r("verifyCodeBody")}),W(zt,{className:i.input,name:"token",placeholder:r("verifyCodeInputPlaceholder"),disabled:["loading","done"].includes(a)}),m&&W("div",{className:i.errorMessage,children:m}),so("div",{className:i.actions,children:[W("button",{type:"button",className:Ls(i.button),onClick:T,children:r("back")}),W("button",{type:"submit",className:Ls(i.button,i.primaryButton),disabled:["loading","done"].includes(a),children:r("verifyCodeSubmitLabel")})]})]})]})})},$a=am;import{jsx as cm}from"react/jsx-runtime";var lm=()=>{let t=Xa(Da),e=Xa($i),n=E("adminUrl"),o=re(),s=()=>o.send(dt,!1),r=()=>{o.send(dt,!1),o.send(Ps)};return cm($a,{isOpen:t,agentEmail:e==null?void 0:e.agentEmail,origin:n,onDismiss:s,onSuccess:r})},Ja=lm;import $m from"lodash.debounce";import{useCallback as Ks,useEffect as Cl,useState as ft}from"react";import{useDispatch as Xm,useSelector as co}from"react-redux";import{createAsyncThunk as um,createSlice as pm}from"@reduxjs/toolkit";var dm={data:null,fetchState:"idle"},Qa=t=>t.contentTypes.data,Wt=um("contentTypes/getContentTypes",async(t,e)=>e.extra.deepdeskAPI.getContentTypes()),mm=pm({name:"contentTypes",initialState:dm,reducers:{},extraReducers:t=>{t.addCase(Wt.pending,e=>{e.fetchState="loading"}).addCase(Wt.rejected,e=>{e.fetchState="error"}).addCase(Wt.fulfilled,(e,n)=>{e.fetchState="done",e.data=n.payload})}}),Za=mm.reducer;function Gt(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()}import{useEffect as gm}from"react";function Ya(t,e){gm(()=>{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)}},[])}import{useEffect as ol,useRef as Cm}from"react";import{useSelector as Tm,useDispatch as bm}from"react-redux";import{createAsyncThunk as fm,createSlice as hm}from"@reduxjs/toolkit";var el={data:null,fetchState:"idle"},ro=t=>{var r;let e=[],{visitorName:n}=t.info.visitorInfo??{},{agentName:o,agentNickname:s}=t.info.agentInfo??{};return o&&o!==n&&e.push(o),s&&s!==n&&e.push(s),((r=t.entities.data)==null?void 0:r.filter(i=>!e.includes(i.text)))??null},ne=fm("entities/getEntities",async(t,e)=>{let{deepdeskAPI:n,dynamicThunkObject:o}=e.extra;if(!o.conversationQuery)return Promise.resolve([]);let s=o.conversationQuery,r=await s();return r.length===0?Promise.resolve([]):n.getEntities(r)}),ym=t=>t.filter((e,n)=>n===t.findIndex(o=>o.text===e.text)),Sm=hm({name:"entities",initialState:el,reducers:{},extraReducers:t=>{t.addCase(ne.pending,e=>{e.fetchState="loading"}).addCase(ne.rejected,e=>{e.fetchState="error"}).addCase(ne.fulfilled,(e,n)=>{e.fetchState="done",e.data=ym(e.data?[...e.data,...n.payload]:n.payload)}).addCase(k,()=>el)}}),tl=Sm.reducer;var Ms={};B(Ms,{enUS:()=>vm,nlNL:()=>xm});var vm={title:[{type:0,value:"Copy to your clipboard"}],noResults:[{type:0,value:"No entities have been found"}],copy:[{type:0,value:"Copy"}],use:[{type:0,value:"Use"}]},xm={title:[{type:0,value:"Kopieer naar klembord"}],noResults:[{type:0,value:"Er zijn geen entiteiten gevonden"}],copy:[{type:0,value:"Kopieer"}],use:[{type:0,value:"Gebruik"}]};var nl={root:"_root_313jm_1",title:"_title_313jm_5",empty:"_empty_313jm_16"};import{jsx as $t,jsxs as sl}from"react/jsx-runtime";var wm=({onCopy:t,onUse:e})=>{let n=Cm(null),o=y("EntitiesList",nl),s=_(Ms),r=Tm(ro),i=bm();return ol(()=>{i(ne())},[]),ol(()=>{n.current&&n.current.focus()},[n]),sl("div",{className:o.root,ref:n,tabIndex:-1,children:[sl("h3",{className:o.title,children:[s("title")," ",$t(Re,{})]}),r&&r.length>0&&$t(R.ActionsBar,{primaryLabel:s("copy"),secondaryLabel:s("use"),onPrimary:(a,l)=>t(r[l]),onSecondary:(a,l)=>e(r[l]),list:r.map(a=>({text:a.text,type:a.label,primaryAction:"copy",secondaryAction:"use"})),children:$t(R.List,{children:r.map((a,l)=>$t(R.ListItem,{index:l,closeOnSelect:!0,onClick:()=>t(a),children:a.text},a.text))},"entities")}),r&&r.length===0&&$t("p",{className:o.empty,children:s("noResults")})]})},rl=wm;import{Fragment as Im,useEffect as io,useRef as Lm,useState as Am}from"react";import{useSelector as pl,useDispatch as Mm}from"react-redux";import{createAsyncThunk as Em,createSlice as _m}from"@reduxjs/toolkit";var il={data:null,fetchState:"idle"},al=t=>t.summary.data,ll=t=>t.summary.fetchState==="error",fe=Em("summary/getSummary",async(t,e)=>{let{deepdeskAPI:n,dynamicThunkObject:o}=e.extra;if(!o.conversationQuery)return Promise.reject(new Error("setConversationQuery method is not defined"));let s=o.conversationQuery,r=await s();if(r.length===0)return Promise.reject(new Error("No messages are included"));let i=await n.getSummary(r);return{original:r,summary:i}}),Pm=_m({name:"summary",initialState:il,reducers:{},extraReducers:t=>{t.addCase(fe.pending,e=>{e.data=null,e.fetchState="loading"}).addCase(fe.rejected,e=>{e.data=null,e.fetchState="error"}).addCase(fe.fulfilled,(e,n)=>{e.fetchState="done",n.payload&&(e.data=n.payload.summary)}).addCase(k,()=>il)}}),cl=Pm.reducer;var Os={};B(Os,{enUS:()=>km,nlNL:()=>Rm});var km={title:[{type:0,value:"Conversation summary"}],copy:[{type:0,value:"Copy"}],error:[{type:0,value:"Could not generate a summary"}],loading:[{type:0,value:"Generating summary, this may take a few moments."}]},Rm={title:[{type:0,value:"Gesprek samenvatting"}],copy:[{type:0,value:"Kopieer"}],error:[{type:0,value:"Kon helaas geen samenvatting genereren."}],loading:[{type:0,value:"Samenvatting wordt gemaakt, dit kan even duren."}]};var ul={root:"_root_gn7se_1",title:"_title_gn7se_5",actions:"_actions_gn7se_16",main:"_main_gn7se_22",textInput:"_textInput_gn7se_26",loading:"_loading_gn7se_45",error:"_error_gn7se_49"};import{jsx as mt,jsxs as Ns}from"react/jsx-runtime";var Om=({onCopy:t})=>{let e=Lm(null),n=y("SummaryForm",ul),[o,s]=Am(""),r=_(Os),i=pl(al),a=pl(ll),l=Mm(),c=()=>{l(ae({name:"summary copied to clipboard",data:{originalText:i,finalText:o},options:{includeConversationData:!0}})),t(o)};return io(()=>{l(fe())},[]),io(()=>{s(i||"")},[i]),io(()=>{e.current&&i&&e.current.focus()},[e,i]),io(()=>{let u=d=>{d.key==="Enter"&&d.shiftKey&&c()};return document.addEventListener("keydown",u),()=>{document.removeEventListener("keydown",u)}},[o]),Ns("div",{className:n.root,tabIndex:-1,children:[Ns("h3",{className:n.title,children:[r("title")," ",mt(Re,{})]}),a?mt("p",{className:n.error,children:r("error")}):Ns(Im,{children:[mt("div",{className:n.main,children:mt("textarea",{placeholder:i?void 0:r("loading"),disabled:!i,className:n.textInput,ref:e,value:o,onChange:u=>s(u.target.value)})}),mt("div",{className:n.actions,children:mt(R.Button,{shortKeys:[8679,8629],onClick:c,children:r("copy")})})]})]})},Ds=Om;var Hs={};B(Hs,{enUS:()=>Nm,nlNL:()=>Dm});var Nm={personalCollectionLink:[{type:0,value:"Go to Personal Collection"}],tutorialLink:[{type:0,value:"Go to Deepdesk tutorial"}],dashboardLink:[{type:0,value:"Go to Deepdesk dashboard"}],searchPlaceholder:[{type:0,value:"Start typing to search..."}],urlSuggestions:[{type:0,value:"Link 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"}],summaryClipboard:[{type:0,value:"Summarize conversation"}],knowledgeSearch:[{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?"}]},Dm={personalCollectionLink:[{type:0,value:"Ga naar persoonlijke collectie"}],tutorialLink:[{type:0,value:"Ga naar Deepdesk tutorial"}],dashboardLink:[{type:0,value:"Ga naar Deepdesk dashboard"}],searchPlaceholder:[{type:0,value:"Begin met typen om te zoeken..."}],personalSuggestions:[{type:0,value:"Persoonlijke suggesties"}],urlSuggestions:[{type:0,value:"Link 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"}],summaryClipboard:[{type:0,value:"Vat gesprek samen"}],knowledgeSearch:[{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?"}]};import jm,{useEffect as Sl,useRef as zm}from"react";import{useDispatch as Wm,useSelector as vl}from"react-redux";var Fs={};B(Fs,{enUS:()=>Hm,nlNL:()=>Fm});var Hm={title:[{type:0,value:"Knowledge Search"}],use:[{type:0,value:"Use"}],loading:[{type:0,value:"Loading..."}],error:[{type:0,value:"Something went wrong, please try again later."}],anotherQuestion:[{type:0,value:"Send a message..."}]},Fm={title:[{type:0,value:"Knowledge Search"}],use:[{type:0,value:"Gebruik"}],loading:[{type:0,value:"Laden..."}],error:[{type:0,value:"Er ging iets mis, probeer het later opnieuw."}],anotherQuestion:[{type:0,value:"Stuur een bericht..."}]};var dl={root:"_root_1qchz_1",title:"_title_1qchz_5",empty:"_empty_1qchz_16",status:"_status_1qchz_20",form:"_form_1qchz_26",input:"_input_1qchz_39",submit:"_submit_1qchz_51",question:"_question_1qchz_59",answer:"_answer_1qchz_63"};import{createAction as Bm,createAsyncThunk as Km,createSlice as Um}from"@reduxjs/toolkit";var Bs={data:[],fetchState:"idle"},ml=t=>{var e;return(e=t.answer)==null?void 0:e.data},gl=t=>t.answer.fetchState,ao=Bm("answer/resetKnowledgeSearch"),gt=Km("answer/getAnswer",async(t,e)=>{var i;let{deepdeskAPI:n}=e.extra,o=e.getState().answer.data;if(!((i=e.getState().profile.data)==null?void 0:i.code))throw new Error("Profile is not defined");let r=await n.knowledgeSearch(t,o);return{question:t,answer:r}}),Vm=Um({name:"answer",initialState:Bs,reducers:{},extraReducers:t=>{t.addCase(gt.pending,e=>{e.fetchState="loading"}).addCase(gt.rejected,e=>{e.fetchState="error"}).addCase(gt.fulfilled,(e,n)=>{e.fetchState="done",e.data=[...e.data,n.payload]}).addCase(k,()=>Bs).addCase(ao,()=>Bs)}}),fl=Vm.reducer;import{jsx as hl,jsxs as qm}from"react/jsx-runtime";var yl=()=>qm("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 512 512","aria-labelledby":"paperPlaneTitle",children:[hl("title",{id:"paperPlaneTitle",children:"PaperPlane"}),hl("path",{d:"M498.1 5.6c10.1 7 15.4 19.1 13.5 31.2l-64 416c-1.5 9.7-7.4 18.2-16 23s-18.9 5.4-28 1.6L284 427.7l-68.5 74.1c-8.9 9.7-22.9 12.9-35.2 8.1S160 493.2 160 480V396.4c0-4 1.5-7.8 4.2-10.7L331.8 202.8c5.8-6.3 5.6-16-.4-22s-15.7-6.4-22-.7L106 360.8 17.7 316.6C7.1 311.3 .3 300.7 0 288.9s5.9-22.8 16.1-28.7l448-256c10.7-6.1 23.9-5.5 34 1.4z"})]});import{jsx as Le,jsxs as lo}from"react/jsx-runtime";var Gm=({onUse:t,question:e})=>{let[n,o]=jm.useState(""),{setSelected:s}=Ie(),r=zm(null),i=y("EntitiesList",dl),a=_(Fs),l=Wm(),c=vl(ml),u=vl(gl),d=async p=>{p.preventDefault(),p.stopPropagation(),n!==""&&l(gt(n))};return Sl(()=>{var p;e&&u==="idle"?l(gt(e)):(p=r.current)==null||p.focus()},[r,u]),Sl(()=>{u==="done"&&(s(0),o(""))},[u,c]),lo("div",{className:i.root,children:[lo("h3",{className:i.title,children:[a("title")," ",Le(Re,{})]}),lo(R.ActionsBar,{list:c.map(({answer:p})=>({text:p.answer,type:"answer"})),primaryLabel:a("use"),onPrimary:p=>t(p.text),children:[c.map(({question:p,answer:m},g)=>Le(R.List,{children:Le(R.ListItem,{index:g,description:m.answer,lineClamp:!0,closeOnSelect:!0,onClick:()=>t(m.answer),sources:m.sources,styles:{title:i.question,description:i.answer},children:p})},`${m.answer}_${g}`)),u==="loading"&&Le("p",{className:i.status,children:a("loading")}),u==="error"&&Le("p",{className:i.status,children:a("error")}),lo("form",{className:i.form,onSubmit:d,children:[Le("input",{ref:r,placeholder:a("anotherQuestion"),className:i.input,type:"text",value:n,onFocus:()=>{s(-1)},onChange:p=>{s(-1),o(p.target.value)}}),Le("button",{type:"submit",className:i.submit,children:Le(yl,{})})]})]})]})},xl=Gm;import{jsx as V,jsxs as bl}from"react/jsx-runtime";var Jm=200,Qm=5,Zm=4,Ym=t=>t.reduce((e,n)=>[...e,...n.list.map(o=>({...o,type:n.value}))],[]),Tl=(t,e)=>!e||t.toLowerCase().includes(e.toLowerCase()),eg=()=>{let t=Xm(),e=re(),n=_(Hs),[o,s]=ft(!1),[r,i]=ft(""),[a,l]=ft("search"),[c,u]=ft(null),[d,p]=ft([]),[m,g]=ft(),f=co(me),T=E("showSearch"),b=E("showEntitiesCommand"),h=E("showSummaryCommand"),S=E("showKnowledgeSearch"),w=E("showImageSearch"),C=E("searchTriggerKey"),x=co(Qa),N=co(Yi),q=co(Zi),D=v=>Uo(N.filter(I=>I.type===v.toUpperCase()),v),X=[{value:"PERSONAL",label:n("personalSuggestions"),list:D("PERSONAL"),lineClamp:!1,listOrientation:"vertical",shouldShow:!0},{value:"URL",label:n("urlSuggestions"),list:D("URL"),lineClamp:!1,listOrientation:"vertical",shouldShow:!0},{value:"STICKYMESSAGE",label:n("pinnedMessages"),list:D("STICKYMESSAGE"),lineClamp:!1,listOrientation:"vertical",shouldShow:!0},{value:"IMAGE",label:n("imageSuggestions"),lineClamp:!1,list:D("IMAGE"),listOrientation:"horizontal",shouldShow:w}].filter(v=>v.shouldShow),Ne=[{label:n("entitiesClipboard"),onClick:()=>l("entities"),shouldShow:b&&Tl(n("entitiesClipboard"),r),experimental:!0},{label:n("summaryClipboard"),onClick:()=>l("summary"),shouldShow:h&&Tl(n("summaryClipboard"),r),experimental:!0},{label:r?`${n("knowledgeSearch")}: ${r}`:n("knowledgeSearch"),onClick:()=>l("knowledgeSearch"),shouldShow:S,experimental:!0}].filter(v=>v.shouldShow),Xe=(x==null?void 0:x.map(v=>({value:v.code.toUpperCase(),label:`${v.name}s`,list:D(v.code.toUpperCase()),listOrientation:"vertical",lineClamp:!0})))||[],_u=Ks($m((v,I)=>{t(Ve({query:v,type:I,tags:["search-overlay"]}))},Jm),[]),un=Ym([...Xe,...X]),Pu=Ks((v,I)=>{if(!I)return;let Te=[...X,...Xe].find(({value:Je})=>Je===I);Te&&(l("edit"),u(v),p(Te.list))},[l,c,Xe]),Ko=Ks((v,I)=>{switch(I.type){case"IMAGE":e.send(ks,{suggestion:I});break;default:e.send(ge,{text:v,suggestion:I})}t(Q(!1))},[t]),ku=v=>{Gt(v.text),t(ae({name:"entity copied",data:{entity:v,type:"copy"}})),t(Q(!1))},Ru=v=>{e.send(ge,{text:v,suggestion:{source:"knowledge-search",text:v}}),t(ae({name:"answer used",data:{originalText:v},options:{includeConversationData:!0}})),t(ao()),t(Q(!1))},Nr=v=>{Gt(v),t(Q(!1))},Iu=v=>{e.send(ge,{text:v.text,suggestion:{source:"entity",text:v.text}}),t(Q(!1))},Lu=c===null||d.indexOf(c)-1<0?void 0:()=>u(d[d.indexOf(c)-1]),Au=c===null||d.indexOf(c)===d.length-1?void 0:()=>u(d[d.indexOf(c)+1]);function Uo(v,I){return v.slice(0,m?10:I.toLowerCase()==="image"?Zm:Qm)}function Dr(v,I,Te){return I.reduce((Je,pn)=>Te&&m===Te?pn.length+Je:Uo(pn,Te).length+Je,v)}function De(v){return I=>{o?window.confirm(n("warning"))&&(v(I),s(!1)):v(I)}}return Cl(()=>{r?_u(r,m):t(Zn())},[r,m]),Cl(()=>{f&&t(Wt())},[f]),Ya(C,()=>t(Q(!0))),T?bl(R,{placeholder:n("searchPlaceholder"),typePlaceholder:n("typePlaceholder"),onChangeSearch:i,onChangeOpen:De(v=>t(Q(v))),onChangeType:v=>g(v),onChangePage:De(l),selectedType:m,search:r,page:a,isOpen:q,types:[...Xe,...X],children:[V(R.Page,{id:"search",children:bl(R.ActionsBar,{list:[...Ne.map(v=>({text:v.label,type:"command"})),...un.map(v=>({text:v.text||v.url||v.message,type:v.type}))],primaryLabel:n("use"),secondaryLabel:n("preview"),onPrimary:({text:v},I)=>Ko(v,un[I]),onSecondary:(v,I)=>Pu(un[I],un[I].type),children:[Ne.length>0&&V(R.List,{heading:n("commands"),children:Ne.map((v,I)=>V(R.ListItem,{index:Dr(I,[],"commands"),closeOnSelect:!1,onClick:v.onClick,isExperimental:v.experimental,children:v.label},v.label))}),[...Xe,...X].map(({value:v,label:I,list:Te,lineClamp:Je,listOrientation:pn},Mu)=>V(R.List,{heading:I,orientation:pn==="horizontal"?"horizontal":"vertical",children:Uo(Te,v).map((Y,Ou)=>V(R.ListItem,{index:Dr(Ne.length+Ou,[...Xe,...X].slice(0,Mu).map(({list:Nu})=>Nu),v),closeOnSelect:!1,lineClamp:Je,onClick:()=>Ko(Y.text,Y),description:v!=="IMAGE"?Y.title&&Y.text:void 0,children:v==="IMAGE"?V(R.Image,{title:Y.title||Y.text,src:Y.image}):Y.title||Y.text},`${Y.id}-${Y.text}`))},v))]})}),V(R.Page,{id:"edit",onDismiss:De(()=>{l("search"),u(null)}),children:c&&V(no,{suggestion:c,onTouched:s,onDismiss:()=>{s(!1),l("search"),u(null),p([])},onNext:Au,onPrevious:Lu,onUse:v=>{l("search"),Ko(v,c),t(Q(!1)),p([]),u(null)}})}),V(R.Page,{id:"entities",onDismiss:De(()=>{l("search")}),children:V(rl,{onUse:Iu,onCopy:ku})}),V(R.Page,{id:"summary",onDismiss:De(()=>{l("search")}),children:V(Ds,{onCopy:Nr})}),V(R.Page,{id:"generate",onDismiss:De(()=>{l("search")}),children:V(Ds,{onCopy:Nr})}),V(R.Page,{id:"knowledgeSearch",onDismiss:De(()=>{t(ao()),l("search")}),children:V(xl,{question:r,onUse:Ru})})]}):null},wl=eg;import{jsx as Us,jsxs as og}from"react/jsx-runtime";var ng=()=>{let t=E("showSearch"),e=E("isEmbedded");return og(tg,{children:[t&&Us(wl,{}),Us(ja,{}),e&&Us(Ja,{})]})},El=ng;import{Provider as sg}from"react-redux";import{jsx as uo}from"react/jsx-runtime";var rg=({children:t})=>{let n=E("locale").replace("-","");return uo(ns.Provider,{value:n,children:t})},ig=({store:t,customStyles:e={},children:n})=>uo(sg,{store:t,children:uo(rg,{children:uo(Rt.Provider,{value:e,children:n})})}),Xt=ig;import Xs from"classnames";import{useEffect as Vg,useRef as qg,useState as jg}from"react";import{connect as zg,useDispatch as Wg,useSelector as fo}from"react-redux";import{useState as ag}from"react";function _l(t,e){let[n,o]=ag(()=>{if(typeof window>"u")return e;try{let r=window.localStorage.getItem(t);return r?JSON.parse(r):e}catch(r){return P.error(r),e}});return[n,r=>{try{let i=r instanceof Function?r(n):r;o(i),typeof window<"u"&&window.localStorage.setItem(t,JSON.stringify(i))}catch(i){P.error(i)}}]}function po(t){let{showMidSentenceSuggestions:e,showSuggestionsBeforePattern:n,showSuggestionsAfterPattern:o}=t.settings,{text:s,selection:r}=t.input.userCommitted;return 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}import ug from"classnames";import{Fragment as pg,useCallback as qs,useMemo as kl}from"react";var Vs={};B(Vs,{enUS:()=>lg,nlNL:()=>cg});var lg={loginPlease:[{type:8,value:"login",children:[{type:0,value:"Sign in"}]},{type:0,value:" to enable Deepdesk."}],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"}]}]},cg={loginPlease:[{type:8,value:"login",children:[{type:0,value:"Log in"}]},{type:0,value:" bij Deepdesk."}],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 Pl={root:"_root_1vfca_1",anchor:"_anchor_1vfca_6",anchorButton:"_anchorButton_1vfca_11"};import{jsx as mo,jsxs as Rl}from"react/jsx-runtime";var js=(t,e,n)=>o=>mo("button",{className:t.anchorButton,type:"button",value:e,onClick:n,children:o},e),dg=({className:t,loginUrl:e,isEmbedded:n,onSnooze:o})=>{let s=_(Vs),r=re(),i=y("Login",Pl),a=qs(g=>{g.preventDefault(),o&&o(parseInt(g.target.value,10))},[]),l=qs(g=>{g.preventDefault(),r.send(dt,!0)},[e]),c=kl(()=>g=>mo("a",{href:e,className:i.anchor,target:"_blank",rel:"noreferrer",children:g},"login"),[e]),u=qs(g=>mo("button",{type:"button",className:i.anchorButton,onClick:l,children:g},"prompt"),[l]),{min:d,hour:p,day:m}=kl(()=>({min:js(i,60*10,a),hour:js(i,60*60,a),day:js(i,60*60*12,a)}),[]);return Rl("div",{className:ug(t,i.root),children:[s("loginPlease",{login:n?u:c}),o&&Rl(pg,{children:[mo("br",{}),s("snooze",{min:d,hour:p,day:m})]})]})},go=dg;import{useDispatch as mg}from"react-redux";var Il={root:"_root_1g8fi_1",text:"_text_1g8fi_19"};import{jsx as Ll,jsxs as fg}from"react/jsx-runtime";var gg=({title:t})=>{let e=y("SearchTrigger",Il),n=mg();return fg("button",{type:"button",className:e.root,onClick:()=>n(Q(!0)),children:[Ll(to,{}),Ll("span",{className:e.text,children:t})]})},Al=gg;import hg from"classnames";var Ml={root:"_root_fp74r_1",isWithDivider:"_isWithDivider_fp74r_9"};import{jsx as Sg}from"react/jsx-runtime";var yg=({withDivider:t,children:e})=>{let n=y("SuggestionList",Ml);return Sg("div",{className:hg(n.root,{[n.isWithDivider]:t}),children:e})},he=yg;import{Fragment as Dg}from"react";import{Interweave as _g}from"interweave";import{useEffect as Pg,useMemo as kg,useRef as Rg}from"react";import{useDispatch as Ig,useSelector as Lg}from"react-redux";import{useEffect as vg}from"react";function Ol(t,e,n){vg(()=>{let o=t.current;return o?(o.addEventListener(e,n),()=>{o.removeEventListener(e,n)}):()=>{}},[t,e,n])}var xg=/[.*+?^${}()|[\]\\]/g,Cg=/[^0-9A-Za-zÀ-ÖØ-öø-ÿ](?=[0-9A-Za-zÀ-ÖØ-öø-ÿ]*$)/;function Tg(t){return t.replace(xg,"\\$&")}function bg(t,e){let n=t.split("").findIndex((o,s)=>o!==e[s]);return n>-1?n:Math.min(t.length,e.length)}function zs(t){return t.search(Cg)}function Nl(t,e=[]){let n=t;return e.forEach(o=>{if(!o)return;let s=new RegExp(`\\b(${Tg(o)})\\b`,"gi");n=n.replace(s,"<strong>$1</strong>")}),n}function Dl(t){return t.replace(Qe,'<mark data-type="placeholder">$1</mark>')}function Jt(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}function wg(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 Ws(t,e,n={}){if(e){let o=bg(e.toLowerCase(),t.toLowerCase()),s=Jt(t.substring(o,t.length));if(n.stripAgentPart){let l=t.substring(0,o),c=zs(l);return`<span style="opacity: 0.5">${l.substring(c+1)}</span>${s}`}let i=e.split(Hr).length>3||e.length>30?wg(e.trim(),o):0;return`${`${i>0?"\u2026":""}${Jt(t.substring(i,o))}`}<strong>${s}</strong>`}return t}var Hl={badge:"_badge_8rv7b_1",formattedText:"_formattedText_8rv7b_5"};import{jsx as Fl}from"react/jsx-runtime";var Ag=["search","personal-collection-search","studio-search"];function Mg(t,e,n,o={}){let s="";return Ag.includes(e)?s=Nl(Ws(t,n,{stripAgentPart:!0}),o.searchKeywords??[n]):s=Ws(t,n,o),o.placeholders===!0&&(s=Dl(s)),s}var Og=()=>{},Ng=({index:t,selected:e,suggestion:n})=>{let o=E("inlineSuggestions"),s=Lg(Ye),r=Ig(),i=y("TextSuggestion",Hl),a=Rg(null);Pg(()=>{let c=setTimeout(()=>{r(Qr({text:n.text,suggestion:n}))},500);return()=>{clearTimeout(c)}},[n]),Ol(a,"click",()=>{r(Pn(t)),r(ee({suggestion:n,text:n.text,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"}))});let l=kg(()=>Mg(n.text,n.source,s,{stripAgentPart:o,placeholders:!0,searchKeywords:n.searchKeywords}),[o,n.text,n.source,s,n.searchKeywords]);return n.source==="gpt"?null:Fl(A,{ref:a,as:"button",selected:e,onClick:Og,children:Fl(_g,{className:i.formattedText,content:l})})},Bl=Ng;import{jsx as Kl}from"react/jsx-runtime";var Hg=({suggestions:t,selectedIndex:e})=>Kl(Dg,{children:t.slice().map((n,o)=>Kl(Bl,{index:o,selected:o===e,suggestion:n},`${n.text}-${n.source}`)).reverse()}),Ul=Hg;import Fg from"classnames";var Vl={root:"_root_1wpmq_1",isCollapsed:"_isCollapsed_1wpmq_17"};import{jsx as Gs}from"react/jsx-runtime";var Bg=({className:t,isCollapsed:e,title:n,onClick:o})=>{let s=y("ToggleButton",Vl);return Gs("button",{type:"button",className:Fg(s.root,t,{[s.isCollapsed]:e}),onClick:o,title:n,children:Gs("svg",{width:"14",height:"8",viewBox:"-2.5 -5 75 60",preserveAspectRatio:"none",children:Gs("path",{d:"M0,0 l35,50 l35,-50",fill:"none",stroke:"grey",strokeLinecap:"round",strokeWidth:"6"})})})},ht=Bg;var $s={};B($s,{enUS:()=>Kg,nlNL:()=>Ug});var Kg={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 Deepdesk"}],collapse:[{type:0,value:"Close"}],search:[{type:0,value:"Search"}]},Ug={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 Deepdesk"}],collapse:[{type:0,value:"Sluiten"}],search:[{type:0,value:"Zoeken"}]};var ql={root:"_root_4kcme_1",isInline:"_isInline_4kcme_14",toggleButton:"_toggleButton_4kcme_18",toggleButtonWrapper:"_toggleButtonWrapper_4kcme_22",toggleButtonWrapperHidden:"_toggleButtonWrapperHidden_4kcme_29",isCollapsed:"_isCollapsed_4kcme_33",collapsible:"_collapsible_4kcme_33",hints:"_hints_4kcme_41",hintsHidden:"_hintsHidden_4kcme_48",triggers:"_triggers_4kcme_53",triggersRight:"_triggersRight_4kcme_68"};import{jsx as F,jsxs as Qt}from"react/jsx-runtime";var Gg=({inline:t=!1,textSuggestions:e,selectedIndex:n})=>{let o=y("SuggestionsOverlay",ql),s=_($s),r=E("inlineSuggestions"),i=fo(po),a=Wr(),l=Wg(),c=qg(null),u=E("searchTriggerKey"),d=fo(Pa),p=fo(me),m=fo(fn),[g,f]=jg(null),T=E("showSearch"),b=E("showTextSuggestions"),h=E("adminUrl"),S=E("isEmbedded"),[w,C]=_l("dd-snooze-until-ms",0),x=d||w>Date.now(),N=e.filter(X=>X.source!=="gpt").length,q=()=>{x&&C(0),l(Ia(!x))},D=X=>{let Ne=Date.now()+X*1e3;C(Ne),P.info(`Snooze until: ${new Date(Ne)}`),l(pt({collapse:!0}))};return Vg(()=>{N===0&&f(null)},[e,N]),st(()=>{l(pt({collapse:!0,skipWhenInputFocus:!0}))}),r!==t||p===null||m===!1?null:p===!1?Qt("div",{ref:c,className:Xs(o.root,{[o.isCollapsed]:x,[o.isInline]:t}),"data-inline":t,children:[!x&&Qt("div",{className:o.triggers,children:[F("div",{style:{flex:1}}),F("div",{className:o.triggersRight,children:F(ht,{className:o.toggleButton,title:s("collapse"),onClick:q,isCollapsed:!1})})]}),F("div",{className:o.toggleButtonWrapper,children:F(ht,{className:o.toggleButton,title:s("open"),onClick:q,isCollapsed:!0})}),F("div",{className:o.collapsible,children:F(go,{loginUrl:h,isEmbedded:S,onSnooze:D})})]}):!a||!i?null:Qt("div",{ref:c,className:Xs(o.root,{[o.isCollapsed]:x,[o.isInline]:t}),"data-inline":t,children:[!x&&Qt("div",{className:o.triggers,children:[F("div",{style:{flex:1},children:T&&F("div",{style:{display:"inline-block"},onFocus:()=>{},onMouseOver:()=>f(s(Jn()?"searchHintMac":"searchHintWindows",{searchTriggerKey:u.toUpperCase()})),onMouseLeave:()=>f(null),children:F(Al,{title:s("search")})})}),Qt("div",{className:o.triggersRight,onFocus:()=>{},children:[F("div",{className:Xs(!g&&o.hintsHidden,o.hints),children:g}),F(ht,{className:o.toggleButton,title:s("collapse"),onClick:q,isCollapsed:!1})]})]}),F("div",{className:o.toggleButtonWrapper,children:F(ht,{className:o.toggleButton,title:s("open"),onClick:q,isCollapsed:!0})}),N>0&&b&&F("div",{className:o.collapsible,onFocus:()=>{},children:F(he,{children:F(Ul,{suggestions:e,selectedIndex:n})})})]})},$g=({input:t})=>({selectedIndex:t.selectedSuggestionIndex,textSuggestions:t.textSuggestions}),ho=zg($g)(Gg);import ur from"classnames";import{Interweave as eh}from"interweave";import{useCallback as th,useEffect as nh,useMemo as dc,useRef as oh}from"react";import{connect as sh}from"react-redux";import{cloneElement as Xg}from"react";var Jg=["div","span","mark","strong","b","i","u","em"];function Js(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(Jg.includes(s)){let i=Array.isArray(o.props.children)?o.props.children:[o.props.children];return[...t.slice(0,t.length-1),Xg(o,{children:Js(i,e,n+1)})]}return[...t,...e]}function ye(t){return t.tagName.toLowerCase()==="textarea"}import Qg from"classnames";var jl={root:"_root_1s73o_1",isArrowUp:"_isArrowUp_1s73o_22",isArrowDown:"_isArrowDown_1s73o_23",isTab:"_isTab_1s73o_39",isEsc:"_isEsc_1s73o_44",isEnter:"_isEnter_1s73o_49"};import{jsx as Yg}from"react/jsx-runtime";var Zg=({className:t,keyCode:e,children:n,...o})=>{let s=y("KeyboardHint",jl);return Yg("span",{className:Qg(t,s.root,{[s.isArrowUp]:e==="arrow-up",[s.isArrowDown]:e==="arrow-down",[s.isTab]:e==="tab",[s.isEsc]:e==="esc",[s.isEnter]:e==="enter"}),...o,children:n})},Qs=Zg;import{Matcher as gf}from"interweave";import{Fragment as ff,useEffect as hf}from"react";import Xl from"classnames";import{createRef as uf,useCallback as Ys,useMemo as pf,useRef as df,useState as mf}from"react";import{useState as ef,useLayoutEffect as tf}from"react";var nf=["bottom","height","left","right","top","width"],of=(t={},e={})=>nf.some(n=>t[n]!==e[n]),Se=new Map,zl,Wl=()=>{let t=[],e=[];Se.forEach((n,o)=>{if(o instanceof Element&&!o.isConnected){e.push(o);return}let s=o.getBoundingClientRect();of(s,n.rect)&&(n.rect=s,t.push(n))}),e.forEach(n=>{Se.delete(n)}),t.forEach(n=>{n.callbacks.forEach(o=>o(n.rect))}),zl=window.requestAnimationFrame(Wl)};function sf(t,e){return{observe(){let n=Se.size===0;if(Se.has(t)){let o=Se.get(t);o.callbacks.push(e),o.rect&&e(o.rect)}else Se.set(t,{rect:void 0,hasRectChanged:!1,callbacks:[e]});n&&Wl()},unobserve(){let n=Se.get(t);if(n){let o=n.callbacks.indexOf(e);o>=0&&n.callbacks.splice(o,1),n.callbacks.length||Se.delete(t),Se.size||cancelAnimationFrame(zl)}}}}function Zs(t){let[e,n]=ef(null);return tf(()=>{if(!t.current)return;let o=sf(t.current,s=>{n(s)});return o.observe(),()=>{o.unobserve()}},[t]),e}import{useContext as rf,useLayoutEffect as af,useState as lf}from"react";import{createPortal as cf}from"react-dom";var Gl={root:"_root_1jq08_1"};var $l=({children:t})=>{let[e,n]=lf(null),o=rf(Rt);return af(()=>{let s=document.createElement("div");return Ue(s),s.classList.add(Gl.root),o!=null&&o.rootNode&&s.classList.add(o==null?void 0:o.rootNode),document.body.appendChild(s),n(s),()=>{s.isConnected&&document.body.removeChild(s)}},[]),e?cf(t,e):null};var ie={ref:"_ref_1rcyi_1",root:"_root_1rcyi_7",positionAbove:"_positionAbove_1rcyi_13",positionBelow:"_positionBelow_1rcyi_17",positionLeft:"_positionLeft_1rcyi_21",positionRight:"_positionRight_1rcyi_25",alignStart:"_alignStart_1rcyi_29",alignCenter:"_alignCenter_1rcyi_34",alignEnd:"_alignEnd_1rcyi_40"};import{jsx as er}from"react/jsx-runtime";var yt=(t=!1)=>{let[e,n]=mf(t),o=Ys(()=>n(!0),[]),s=Ys(()=>n(!1),[]),r=Ys(()=>n(a=>!a),[]),i=df(null);return{opened:e,open:o,close:s,toggle:r,triggerRef:i}};function tr(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 St=({className:t,triggerRef:e,boundaryRef:n=uf(),position:o="above",align:s="center",children:r,toStyle:i=tr,...a})=>{let l=Zs(e),c=Zs(n),u=pf(()=>i(l,c,0),[l,c]);return er($l,{children:er("div",{className:Xl(ie.ref,{[ie.positionAbove]:o==="above",[ie.positionBelow]:o==="below",[ie.positionLeft]:o==="left",[ie.positionRight]:o==="right",[ie.alignStart]:s==="start",[ie.alignCenter]:s==="center",[ie.alignEnd]:s==="end"}),style:u,...a,role:"dialog",children:er("div",{className:Xl(t,ie.root),children:r})})})};import{jsx as Zt,jsxs as Sf}from"react/jsx-runtime";var yf=({inputStyle:t,inputElement:e})=>{let n=y("TabCompletion",J),o=yt(document.activeElement===e);return st(()=>o.close()),hf(()=>{let s=()=>o.open();return e.addEventListener("focus",s),()=>{e.removeEventListener("focus",s)}},[]),Sf(ff,{children:[Zt("mark",{className:J.caret,ref:o.triggerRef}),o.opened&&Zt(St,{className:n.popoverSuggestionsRoot,triggerRef:o.triggerRef,position:"above",align:"start",children:Zt("div",{style:t,className:n.suggestionsOverlayInputStyles,children:Zt(ho,{inline:!0})})})]})},yo=class extends gf{charCounter=0;charLength=0;found=!1;onlyAtEnd=!1;props;onBeforeParse(e,n){var o;return this.props=n,this.charCounter=0,this.onlyAtEnd=n.inlineSuggestionsOnlyAtEnd??!1,this.charLength=(ye(n.inputElement)?n.inputElement.value.length:(o=n.inputElement.textContent)==null?void 0:o.length)??0,this.found=!1,e}match(e){if(this.found||!this.props||this.props.selection===null)return null;let[n,o]=this.props.selection;if(n!==o||this.onlyAtEnd&&n!==this.charLength)return null;let s=n,i=s>=this.charCounter&&s<=this.charCounter+e.length?{index:zs(e.slice(0,s))+1-this.charCounter,length:0,match:"",valid:!0}:null;return i&&(this.found=!0),this.charCounter+=e.length,i??null}replaceWith(e,n){return Zt(yf,{inputStyle:n.inputStyle,inputElement:n.inputElement},"caret")}asTag(){return"mark"}};import Tf from"classnames";import{Matcher as bf}from"interweave";import{Fragment as wf,useEffect as Ef,useMemo as _f}from"react";function Jl(t){return t.replace(/[.*+^${}()|[\]\\]/g,"\\$&")}function So(t){return e=>{t.forEach(n=>{typeof n=="function"?n(e):n!=null&&(n.current=e)})}}function Ql(t){return t!=null}import vf from"classnames";import{forwardRef as xf,useRef as Cf}from"react";import{jsx as Zl}from"react/jsx-runtime";var vo=xf(({className:t,children:e,...n},o)=>{let s=Cf(null),r=y("TabCompletion",J);return Zl("div",{ref:So([s,o]),className:vf(t,r.popoverContentContainer),...n,children:Zl("div",{className:r.popoverContent,children:e})})});import{jsx as Yt,jsxs as Rf}from"react/jsx-runtime";var Pf=t=>e=>{let n=tr(e);return"top"in n&&(n.width=t.width-(e.left-t.left)-10),n},kf=({inputElement:t,boundaryRef:e,inputStyle:n,children:o,suggestion:s})=>{let r=y("TabCompletion",J),i=yt(),a=_f(()=>Pf(t.getBoundingClientRect()),[t]),[l,c]=qn(t);return Ef(()=>{c?i.open():i.close()},[c]),Rf(wf,{children:[Yt("mark",{ref:So([l,i.triggerRef]),className:Tf(r.matchKeyword,{[r.hover]:c}),"aria-haspopup":"dialog","aria-expanded":i.opened?"true":"false",children:o}),i.opened&&Yt(St,{className:r.popover,triggerRef:i.triggerRef,boundaryRef:e,position:"below",align:"start",toStyle:a,children:Yt(vo,{style:n,children:Yt("div",{className:r.hintText,children:s})})})]})},xo=class extends bf{keywordMatches=[];preparedKeywordMatches=[];usedKeywordMatches=new Set;onBeforeParse(e,n){return n.keywordMatches&&n.keywordMatches!==this.keywordMatches&&(this.preparedKeywordMatches=n.keywordMatches.map(o=>({...o,keywordRegex:new RegExp(`\\b${Jl(o.keyword)}\\b`,"i")})),this.keywordMatches=n.keywordMatches),this.usedKeywordMatches.clear(),e}match(e){let n=this.preparedKeywordMatches.map(s=>{if(this.usedKeywordMatches.has(s))return null;let r=e.match(s.keywordRegex);if(!r)return null;let i=e.charAt(r.index-1),a=e.charAt(r.index+s.keyword.length);return i==="{"&&a==="}"?null:{index:r.index,length:r[0].length,match:r[0],matchString:r[0],suggestion:s.suggestion,preparedKeywordMatch:s,valid:!0}}).filter(Ql);if(n.length===0)return null;let o=n.reduce((s,r)=>r.index<s.index?r:s);return this.usedKeywordMatches.add(o.preparedKeywordMatch),o}replaceWith(e,n){return Yt(kf,{inputElement:n.inputElement,suggestion:n.suggestion,inputStyle:n.inputStyle,boundaryRef:n.boundaryRef,children:e},`keyword_${n.matchString}_${n.key}`)}asTag(){return"mark"}};import cr from"classnames";import{Matcher as Wf}from"interweave";import{createRef as Gf,forwardRef as $f,Fragment as Xf,useCallback as Jf,useEffect as lc,useRef as cc,useState as uc}from"react";import{useDispatch as Qf}from"react-redux";import{jsx as Yl}from"react/jsx-runtime";var ec=()=>Yl("svg",{width:"1.3em",height:"1.3em",focusable:"false","aria-hidden":"true",viewBox:"0 0 24 24","data-testid":"InsertLinkIcon",tabIndex:-1,children:Yl("path",{fill:"currentColor",d:"M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76 0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71 0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71 0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76 0 5-2.24 5-5s-2.24-5-5-5z"})});import{useCallback as Ff,useEffect as sc,useState as rc}from"react";import{useDispatch as Bf,useSelector as ic}from"react-redux";import Kf from"lodash.debounce";import or from"classnames";import Lf,{createContext as Af,useContext as sr,useEffect as Mf,useState as Of}from"react";var tc={root:"_root_vr71j_1"};import{jsx as Co,jsxs as If}from"react/jsx-runtime";var nc=()=>If("svg",{className:tc.root,width:"185",height:"170",viewBox:"0 0 185 170",xmlns:"http://www.w3.org/2000/svg",children:[Co("defs",{children:Co("style",{children:".cls-1 { fill: #b3b3b3; }"})}),Co("title",{children:"Failed loading image"}),Co("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 nr={root:"_root_4e7lf_1",imageWrapper:"_imageWrapper_4e7lf_7",image:"_image_4e7lf_7",content:"_content_4e7lf_24",title:"_title_4e7lf_35",contentIsCropped:"_contentIsCropped_4e7lf_45",lineClamp:"_lineClamp_4e7lf_51"};import{jsx as vt}from"react/jsx-runtime";var To=Af(nr),Nf=({title:t,src:e})=>{let n=sr(To),[o,s]=Of(!1);return Mf(()=>{s(!1)},[e]),vt("div",{className:n.imageWrapper,children:e&&!o?vt("img",{className:n.image,alt:t,src:e,onError:()=>s(!0)}):vt(nc,{})})},Df=({className:t,lineClamp:e=!1,cropText:n=!1,children:o})=>{let s=sr(To);return vt("div",{className:or(s.content,t,{[s.contentIsCropped]:n,[s.lineClamp]:e}),children:o})},Hf=({as:t="h1",cropText:e=!1,className:n,children:o})=>{let s=sr(To);return Lf.createElement(t,{className:or(s.title,n,{[s.contentIsCropped]:e})},o)},bo=({children:t})=>{let e=y("Card",nr);return vt("div",{className:or(e.root),children:vt(To.Provider,{value:e,children:t})})};bo.Image=Nf;bo.Content=Df;bo.Title=Hf;var O=bo;var oc={root:"_root_1muu8_1",content:"_content_1muu8_7"};function wo(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{return null}}function rr(t){return t.replace("https://www.","").replace("https://","")}import{jsx as ze,jsxs as ir}from"react/jsx-runtime";var Uf=3,Vf=t=>({image:t.image||"",text:`https://${t.text}`,id:t.id,title:t.title}),qf=({onSelectLink:t,onDismiss:e,placeholder:n,visitUrlText:o,linkCount:s=Uf})=>{let r=y("LinkSearch",oc),[i,a]=rc(""),l=Bf(),c=ic(ga("url")),u=ic(ea("URL",Vf)),[d,p]=rc(u.length-1),m=E("fallbackImage"),g=h=>{let S=h.target;a(S.value)},f=(h,S)=>{h.stopPropagation(),h.preventDefault(),window.open(S,"_blank")},T=h=>{var C;let S=d-1<0?u.length-1:d-1,w=d+1===u.length?0:d+1;h.code==="Escape"&&(a(""),e()),h.code==="ArrowUp"&&p(S),h.code==="ArrowDown"&&p(w),h.code==="Enter"&&t(((C=u[d])==null?void 0:C.text)||i)},b=Ff(Kf(h=>{l(Ve({query:h,type:"URL",tags:["link-search"]}))},300),[]);return sc(()=>{i&&b(i)},[i]),sc(()=>()=>{l(Zn())},[]),ir("div",{className:r.root,children:[ze(he,{withDivider:!0,children:(i?u:c).slice(0,s).map((h,S)=>ze(A,{selected:d===S,onClick:()=>t(h.text),"data-testid":"linksearch-suggestion",children:ir(O,{children:[ze(O.Image,{src:wo(h,"small",m||void 0),title:h.title||h.text}),ir(O.Content,{className:r.content,cropText:!0,children:[ze(O.Title,{children:h.title||rr(h.text)}),h.title&&rr(h.text)]}),ze(A.Actions,{children:ze(A.ActionButton,{label:o,onClick:w=>f(w,h.text)})})]})},h.text))}),ze(zt,{value:i,onChange:g,autoFocus:!0,placeholder:n,onKeyUp:T})]})},ac=qf;var ar={};B(ar,{enUS:()=>jf,nlNL:()=>zf});var jf={insertLink:[{type:0,value:"Insert link"}],linkInputPlaceholder:[{type:0,value:"Search, type or paste link"}],visitUrl:[{type:0,value:"Visit"}]},zf={insertLink:[{type:0,value:"Voeg link toe"}],linkInputPlaceholder:[{type:0,value:"Zoek, typ of plak link"}],visitUrl:[{type:0,value:"Bekijk"}]};import{jsx as Ae,jsxs as lr}from"react/jsx-runtime";var Zf=$f((t,e)=>{let n=y("TabCompletion",J);return Ae("mark",{ref:e,className:cr(n.matchSelection)},"selection-start")}),Yf=({startRef:t,boundaryRef:e,inputStyle:n,inputElement:o,children:s})=>{let r=_(ar),i=y("TabCompletion",J),a=cc(null),l=cc(null),[c,u]=uc(null),d=Qf(),p=yt(document.activeElement===o),[m]=uc(()=>document.createRange());p.triggerRef.current=m,lc(()=>()=>m.detach(),[]),lc(()=>{let f=t.current,T=a.current;!f||!T||(m.setStart(f,0),m.setEnd(T,0))},[t.current,a.current]),st(()=>{p.close()});let g=Jf(f=>{let T=m.toString(),b=/^http(s?):\/\//.test(f)?f:`https://${f}`;d(Tn({text:`[${T}](${b})`}))},[]);return lr(Xf,{children:[Ae("mark",{ref:a,className:cr(i.matchSelection),"aria-haspopup":"dialog","aria-expanded":p.opened?"true":"false",children:s}),p.opened&&Ae(St,{className:i.popoverRoot,triggerRef:p.triggerRef,boundaryRef:e,position:"above",align:"start",children:lr(vo,{style:n,ref:l,children:[Ae("div",{className:cr(i.selectionOptions,{[i.selectionOptionsIsHidden]:c!==null}),children:lr("button",{type:"button",tabIndex:c===null?-1:void 0,className:i.selectionOptionsButton,onClick:()=>u("insertLink"),children:[Ae(ec,{}),"\xA0",r("insertLink")]})}),c==="insertLink"&&Ae(ac,{placeholder:r("linkInputPlaceholder"),visitUrlText:r("visitUrl"),onSelectLink:g,onDismiss:()=>{u(null),p.close()}})]})})]},"selection-end")},Eo=class extends Wf{charCount=0;foundIndex=0;startRef=null;props;onBeforeParse(e,n){return this.props=n,this.charCount=0,this.startRef=Gf(),this.foundIndex=0,e}match(e){if(!this.props||this.props.selection===null||this.foundIndex===2)return null;let[n,o]=this.props.selection;if(n===o)return null;let s=this.foundIndex===0?n:o,r=s>=this.charCount&&s<=this.charCount+e.length?{index:s-this.charCount,length:0,match:"",valid:!0}:null;r&&this.foundIndex++;let i=this.foundIndex===1;return r&&i?this.charCount+=s-this.charCount:this.charCount+=e.length,r?{isStart:i,...r}:null}replaceWith(e,n){return n.isStart?Ae(Zf,{ref:this.startRef}):Ae(Yf,{inputElement:n.inputElement,startRef:this.startRef,boundaryRef:n.boundaryRef,inputStyle:n.inputStyle})}asTag(){return"mark"}};var pc={root:"_root_kpc8q_1",agentText:"_agentText_kpc8q_4",tabText:"_tabText_kpc8q_9",hint:"_hint_kpc8q_10",matchSelection:"_matchSelection_kpc8q_14",focus:"_focus_kpc8q_20",resetIndent:"_resetIndent_kpc8q_24",matchKeyword:"_matchKeyword_kpc8q_28",matchPlaceholder:"_matchPlaceholder_kpc8q_29",hover:"_hover_kpc8q_35",hintText:"_hintText_kpc8q_67",popover:"_popover_kpc8q_75",popoverRoot:"_popoverRoot_kpc8q_80",popoverContentContainer:"_popoverContentContainer_kpc8q_84",popoverContent:"_popoverContent_kpc8q_84",selectionOptions:"_selectionOptions_kpc8q_110",selectionOptionsIsHidden:"_selectionOptionsIsHidden_kpc8q_115",selectionOptionsButton:"_selectionOptionsButton_kpc8q_119",caret:"_caret_kpc8q_135",popoverSuggestionsRoot:"_popoverSuggestionsRoot_kpc8q_139",suggestionsOverlayInputStyles:"_suggestionsOverlayInputStyles_kpc8q_144"};import{jsx as en,jsxs as ah}from"react/jsx-runtime";var rh=({enabled:t,content:e,tabText:n,showTabHint:o,showTabCompletion:s,showStyleSuggestions:r,keywordMatches:i,inputElement:a,source:l})=>{let c=y("TabCompletion",pc),u=E("insertLink"),d=E("showMidSentenceSuggestions"),p=E("inlineSuggestions"),m=zn(a),g=oh(null);nh(()=>{ye(a)&&m&&Wn(a,m)},[m]);let f=th(h=>{if(!s||!n)return h;let S=[en("span",{className:c.resetIndent,children:"\u200B"},"u200B"),en("span",{className:ur(c.tabText,c.resetIndent),"data-source":l,children:n},"tabText")];return o&&S.push(en(Qs,{className:ur(c.hint,c.resetIndent),keyCode:"tab"},"tabHint")),Js(h,S)},[s,n,o]),T=dc(()=>{let h=[];return p&&h.push(new yo("inline")),u&&h.push(new Eo("selection")),h.push(new ot("placeholders")),r&&h.push(new xo("keywords")),h},[p,u,r]),b=dc(()=>{let h=window.getComputedStyle(a);return{"--dd-color":h.color,"--dd-font-size":h.fontSize,"--dd-font-family":h.fontFamily,"--dd-font-variant":h.fontVariant}},[]);return t?ah("div",{ref:h=>{h!=null&&h.parentElement&&(g.current=h==null?void 0:h.parentElement)},className:ur(c.root,c.agentText),style:b,children:[en(eh,{noWrap:!0,disableLineBreaks:ye(a),content:e||"\u200B",onAfterParse:f,matchers:T,selection:m,keywordMatches:i,inputElement:a,inputStyle:b,boundaryRef:g,inlineSuggestionsOnlyAtEnd:!d}),en("br",{})]}):null},ih=({input:t,ui:e,settings:n,styleSuggestions:o,conversation:s})=>{var f;let{tabCompletionSuggestion:r}=t,i=(r==null?void 0:r.text)||"",a=(r==null?void 0:r.source)||"",l=t.html??Jt(t.text),c=i.indexOf(t.text)===0?i.slice(t.text.length):"",{showTabHint:u}=e,{isSupported:d}=s,{showTabCompletion:p,visible:m,showStyleSuggestions:g}=n;return{showTabHint:u,showStyleSuggestions:g,showTabCompletion:p,content:l,tabText:c,source:a,keywordMatches:((f=o.list)==null?void 0:f.keywordMatches)??[],enabled:m&&d!==!1}},mc=sh(ih)(rh);import oy from"classnames";import{useEffect as sy}from"react";import{useDispatch as ry,useSelector as G}from"react-redux";import{createAsyncThunk as tn,createSlice as lh}from"@reduxjs/toolkit";var gc={list:[],fetchState:"idle",isInitialRequest:null},hc=t=>t.autoflows.list||[],fc=t=>e=>{var n;return(n=e.list)==null?void 0:n.find(o=>o.triggerPayload===t)},ve=tn("autoflows/getAll",async(t,e)=>{let{deepdeskBrokerAPI:n}=e.extra;if(!n)throw new Error("Deepdesk Broker not initialized");return n.getAutoflows(t)}),pr=tn("autoflows/start",async(t,e)=>{let{dispatch:n}=e,{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");await o.startAutoflowSession(t),await n(ve(t.platformSessionId))}),dr=tn("autoflows/stop",async(t,e)=>{let{dispatch:n}=e,{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");await o.stopAutoflowSession(t.platformSessionId),await n(ve(t.platformSessionId))}),ch=lh({name:"autoflows",initialState:gc,reducers:{},extraReducers:t=>{t.addCase(pr.pending,(e,n)=>{let o=fc(n.meta.arg.triggerPayload)(e);o.state="Started",o.isBusy=!0}),t.addCase(dr.pending,(e,n)=>{let o=fc(n.meta.arg.triggerPayload)(e);o.state="Aborted",o.isBusy=!0}),t.addCase(ve.pending,e=>{e.isInitialRequest=e.isInitialRequest===null,e.fetchState="loading"}),t.addCase(ve.rejected,e=>{e.fetchState="error"}),t.addCase(ve.fulfilled,(e,n)=>{e.list=n.payload,e.fetchState="done"}),t.addCase(k,()=>gc)}}),yc=tn("autoflows/openStream",(t,e)=>{let{dispatch:n}=e,{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");let s=o.openStream(t);s.on("sessionAborted",()=>{n(ve(t))}),s.on("sessionCompleted",()=>{n(ve(t))})}),Sc=tn("autoflows/closeStream",(t,e)=>{let{deepdeskBrokerAPI:n}=e.extra;if(!n)throw new Error("Deepdesk Broker not initialized");n.closeStream(t)}),vc=ch.reducer;import{createAsyncThunk as on,createSlice as uh}from"@reduxjs/toolkit";var xc={list:[],fetchState:"idle",isInitialRequest:null,sentSuggestions:[],errorSuggestions:[],answeredSuggestions:[]},Cc=t=>t.customMessages.list,Tc=t=>e=>!!e.customMessages.sentSuggestions.find(n=>n===t),bc=t=>e=>!!e.customMessages.answeredSuggestions.find(n=>n===t),wc=t=>e=>!!e.customMessages.errorSuggestions.find(n=>n===t),nn=on("customMessages/getAll",async(t,e)=>{let{deepdeskBrokerAPI:n}=e.extra;if(!n)throw new Error("Deepdesk Broker not initialized");return n.getCustomMessages(t)}),_o=on("customMessages/send",async(t,e)=>{let{platformSessionId:n,suggestion:o}=t,{deepdeskBrokerAPI:s}=e.extra;if(!s)throw new Error("Deepdesk Broker not initialized");await s.sendCustomMessage(n,o)}),Po=on("customMessages/answer",async(t,e)=>{let{platformSessionId:n,reply:o}=t,{deepdeskBrokerAPI:s}=e.extra;if(!s)throw new Error("Deepdesk Broker not initialized");await s.answerCustomMessage(n,o)}),Ec=uh({name:"customMessages",initialState:xc,reducers:{onCustomMessage(t,e){Array.isArray(e.payload)?t.list=e.payload:t.list=[e.payload]}},extraReducers:t=>{t.addCase(nn.pending,e=>{e.isInitialRequest=e.isInitialRequest===null,e.fetchState="loading"}).addCase(nn.rejected,e=>{e.fetchState="error"}).addCase(nn.fulfilled,(e,n)=>{e.fetchState="done",e.list=n.payload||[]}).addCase(_o.pending,(e,n)=>{e.sentSuggestions.push(n.meta.arg.suggestion.text),e.errorSuggestions=e.errorSuggestions.filter(o=>n.meta.arg.suggestion.text!==o)}).addCase(_o.rejected,(e,n)=>{let o=e.sentSuggestions.indexOf(n.meta.arg.suggestion.text);e.errorSuggestions.push(...e.sentSuggestions.splice(o,1))}).addCase(Po.pending,(e,n)=>{e.sentSuggestions.push(n.meta.arg.suggestion.text),e.answeredSuggestions.push(n.meta.arg.suggestion.text)}).addCase(Po.rejected,(e,n)=>{let o=e.answeredSuggestions.indexOf(n.meta.arg.suggestion.text);e.errorSuggestions.push(...e.sentSuggestions.splice(o,1)),e.answeredSuggestions.splice(o,1)}).addCase(k,()=>xc)}}),_c=on("customMessages/openStream",(t,e)=>{let{dispatch:n}=e,{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");o.openStream(t).on("customMessageSuggestion",r=>{n(Ec.actions.onCustomMessage(r))})}),Pc=on("customMessages/closeStream",(t,e)=>{let{deepdeskBrokerAPI:n}=e.extra;if(!n)throw new Error("Deepdesk Broker not initialized");n.closeStream(t)}),kc=Ec.reducer;import{createAsyncThunk as Rc,createSlice as ph}from"@reduxjs/toolkit";var dh={jwt:null,accountUrl:null,interval:null},Ic=t=>e=>{let{exchangeToken:{jwt:n,accountUrl:o}}=e;return n&&o?`${o}/apis/admin/session/jwt/?jwt=${n}&redirect=${t}`:null},mr=Rc("exchangeToken/getTemporaryExchangeToken",async(t,e)=>{let{deepdeskAPI:n}=e.extra,o=await n.getTemporaryExchangeToken();return{accountUrl:n.client.baseUrl,jwt:o}}),gr=Rc("exchangeToken/pollExchangeToken",(t={},e)=>{let{interval:n=1e3*60*30}=t,{dispatch:o}=e;return o(mr()),setInterval(()=>o(mr()),n)}),Lc=ph({name:"exchangeToken",initialState:dh,reducers:{stopPollExchangeToken(t){t.interval&&clearInterval(t.interval),t.interval=null}},extraReducers:t=>{t.addCase(mr.fulfilled,(e,n)=>{e.jwt=n.payload.jwt,e.accountUrl=n.payload.accountUrl}),t.addCase(gr.fulfilled,(e,n)=>{e.interval=n.payload})}}),{stopPollExchangeToken:Ac}=Lc.actions,Mc=Lc.reducer;import{createAsyncThunk as mh,createSlice as gh}from"@reduxjs/toolkit";var fh={data:null,fetchState:"idle"},ko=t=>t.profile.data,Ro=t=>t.profile.data?t.profile.data.uiConfig.widget.types.filter(e=>e.isActive):[],sn=mh("profile/getProfile",async(t,e)=>{let{deepdeskAPI:n}=e.extra,s=e.getState().conversation.current;if(!s||!s.profileCode)throw new Error("No conversation of conversation profileCode found");return n.getProfile(s.profileCode)}),hh=gh({name:"profile",initialState:fh,reducers:{},extraReducers:t=>{t.addCase(sn.pending,e=>{e.fetchState="loading"}).addCase(sn.rejected,e=>{e.fetchState="error"}).addCase(sn.fulfilled,(e,n)=>{e.fetchState="done",e.data=n.payload})}}),Oc=hh.reducer;function Nc(t){let{customMessages:e,autoflows:n}=t;return n.fetchState==="loading"&&n.isInitialRequest===!0||e.fetchState==="loading"&&e.isInitialRequest===!0}import{Fragment as _h}from"react";import{connect as Ph}from"react-redux";import bh from"classnames";import{Fragment as wh}from"react";import yh from"classnames";var Dc={root:"_root_838fd_1"};import{jsx as vh}from"react/jsx-runtime";var Sh=({className:t,children:e})=>{let n=y("Unicode",Dc);return vh("span",{className:yh(t,n.root),children:e})},Hc=Sh;var Fc={isDisabled:"_isDisabled_1rmfm_1",buttonStart:"_buttonStart_1rmfm_5",root:"_root_1rmfm_8",buttonStop:"_buttonStop_1rmfm_8",stateBadge:"_stateBadge_1rmfm_19",isCompleted:"_isCompleted_1rmfm_26",isStarted:"_isStarted_1rmfm_30",isAborted:"_isAborted_1rmfm_34"};var fr={};B(fr,{enUS:()=>xh,nlNL:()=>Ch});var xh={start:[{type:0,value:"Start"}],stop:[{type:0,value:"Stop"}],aborted:[{type:0,value:"Stopped"}],completed:[{type:0,value:"Completed"}],Aborted:[{type:0,value:"Stopped"}],Started:[{type:0,value:"Running"}],Completed:[{type:0,value:"Completed"}]},Ch={start:[{type:0,value:"Start"}],stop:[{type:0,value:"Stop"}],aborted:[{type:0,value:"Stopped"}],completed:[{type:0,value:"Completed"}],Aborted:[{type:0,value:"Stopped"}],Started:[{type:0,value:"Running"}],Completed:[{type:0,value:"Completed"}]};import{jsx as We,jsxs as Io}from"react/jsx-runtime";var Eh=({disabled:t,state:e,displayName:n,description:o,onStartAutoflow:s,onStopAutoflow:r})=>{let i=y("Autoflow",Fc),a=_(fr),l=e==="Started"?"stop":"start",c=l==="start"?"\u25B6":l==="stop"?"\u25FC":"";return Io(A,{className:bh(i.root,{[i.isDisabled]:t,[i.isCompleted]:e==="Completed",[i.isAborted]:e==="Aborted",[i.isStarted]:e==="Started"}),children:[We(O,{children:Io(O.Content,{children:[Io(O.Title,{children:[e&&We("span",{className:i.stateBadge,children:a(e)}),n]}),We("span",{children:o})]})}),We(A.Actions,{fixed:e==="Started",children:We(A.ActionButton,{primary:!0,className:l==="start"?i.buttonStart:i.buttonStop,onClick:e==="Started"?r:s,disabled:t,label:Io(wh,{children:[We(Hc,{children:c})," ",We("span",{children:a(l)})]})})})]})},Bc=Eh;import{jsx as Kc}from"react/jsx-runtime";var kh=(t,e)=>{let n=e.filter(o=>o.state==="Started");return n.length>0?n.indexOf(t)===-1:!1},Rh=({autoflows:t,onStartAutoflow:e,onStopAutoflow:n,platformSessionId:o})=>Kc(_h,{children:t.map(s=>Kc(Bc,{displayName:s.displayName,description:s.description,disabled:s.isBusy||kh(s,t),state:s.state,onStartAutoflow:()=>e({platformSessionId:o,triggerPayload:s.triggerPayload}),onStopAutoflow:()=>n({platformSessionId:o,triggerPayload:s.triggerPayload})},s.displayName))}),Ih=({autoflows:t,conversation:e})=>{var n;return{autoflows:t.list,platformSessionId:(n=e.current)==null?void 0:n.sessionId}},Lh={onStartAutoflow:pr,onStopAutoflow:dr},Uc=Ph(Ih,Lh)(Rh);import{useEffect as Ah,useState as Mh}from"react";import{useDispatch as Oh}from"react-redux";import jc from"classnames";import{jsx as Vc}from"react/jsx-runtime";var hr=()=>Vc("svg",{width:"1em",height:"1em",viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",children:Vc("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 qc={root:"_root_rjdyr_1",entity:"_entity_rjdyr_10",entityText:"_entityText_rjdyr_46",iconWrapper:"_iconWrapper_rjdyr_53",icon:"_icon_rjdyr_53",iconClicked:"_iconClicked_rjdyr_67"};import{jsx as xt,jsxs as zc}from"react/jsx-runtime";var Nh=({entities:t})=>{let e=y("EntitiesWidgetList",qc),[n,o]=Mh(void 0),s=Oh(),r=()=>{o(void 0)},i=a=>{t&&(o(t.indexOf(a)),Gt(a.text),s(ae({name:"entity copied",data:{entity:a,type:"copy"}})))};return Ah(()=>{let a=setTimeout(r,500);return()=>{clearTimeout(a)}},[n]),!t||t.length===0?null:xt("div",{className:e.root,"data-testid":"widget-entities-list",children:t.map((a,l)=>zc("button",{title:a.text,className:e.entity,type:"button",onClick:()=>i(a),children:[xt("span",{className:e.entityText,children:a.text}),zc("span",{className:e.iconWrapper,children:[xt("span",{className:jc(e.icon),children:xt(hr,{})}),xt("span",{className:jc(e.icon,n===l&&e.iconClicked),children:xt(hr,{})})]})]},a.text))})},Wc=Nh;import Uh from"classnames";import{useCallback as $c}from"react";import{useDispatch as Vh,useSelector as Lo}from"react-redux";import Dh from"classnames";var Gc={root:"_root_4a08n_1"};import{jsx as Fh}from"react/jsx-runtime";var Hh=({className:t,children:e,...n})=>{let o=y("Label",Gc);return Fh("span",{...n,className:Dh(t,o.root),children:e})},yr=Hh;var rn={};B(rn,{enUS:()=>Bh,nlNL:()=>Kh});var Bh={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"}],answer:[{type:0,value:"Answer"}]},Kh={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"}],answer:[{type:0,value:"Antwoord"}]};var xe={root:"_root_1e6ej_1",title:"_title_1e6ej_8",isUsed:"_isUsed_1e6ej_13",quickReplies:"_quickReplies_1e6ej_22",quickReply:"_quickReply_1e6ej_29",hasError:"_hasError_1e6ej_39",label:"_label_1e6ej_43",errorIcon:"_errorIcon_1e6ej_48"};import{jsx as Me,jsxs as Ao}from"react/jsx-runtime";var qh=({suggestion:t})=>{let e=_(rn),n=Vh(),o=Lo(Tc(t.text)),s=Lo(bc(t.text)),r=Lo(wc(t.text)),i=Lo(mn),{replyOptions:a}=t,l=$c(u=>{u.preventDefault(),u.stopPropagation(),!(o||!i)&&n(_o({platformSessionId:i,suggestion:t}))},[t,o,n,i]),c=$c(u=>{if(u.preventDefault(),u.stopPropagation(),!i||!a)return;let d=parseInt(u.target.dataset.index,10),p=a[d];n(Po({platformSessionId:i,reply:p,suggestion:t}))},[t,o,n,i]);return Ao(A,{onClick:l,className:Uh(xe.root,{[xe.isUsed]:o,[xe.hasError]:r}),children:[Me(O,{children:Ao(O.Content,{children:[Ao(O.Title,{className:xe.title,children:[t.text," ",Me(yr,{className:xe.label,children:"analyse tool"})," ",r&&Me("span",{className:xe.errorIcon,role:"img","aria-label":e("sendingError"),title:e("sendingError"),children:"!"})]}),a&&a.length>0&&Me("ul",{className:xe.quickReplies,children:a.map(u=>Me("li",{className:xe.quickReply,children:u.title},u.title))})]})}),Ao(A.Actions,{fixed:r||o,children:[a&&a.length>0&&Me(A.DropdownButton,{label:e("answer"),disabled:s,children:a.map((u,d)=>Me(A.DropdownItem,{index:d,label:u.title,onClick:c},u.title))}),Me(A.ActionButton,{primary:!0,disabled:o,onClick:l,label:e(o?"suggestionSent":r?"tryAgain":"sendSuggestion")})]})]})},Xc=qh;import{jsx as Jc}from"react/jsx-runtime";var Qc=()=>Jc("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:Jc("path",{d:"M17 13.5v6H5v-12h6m3-3h6v6m0-6-9 9",stroke:"currentColor",strokeWidth:"1.5",fill:"none",fillRule:"evenodd",strokeLinecap:"round",strokeLinejoin:"round"})});var Zc={root:"_root_jlggj_1",subTitleContainer:"_subTitleContainer_jlggj_5",subtitle:"_subtitle_jlggj_9",suggestions:"_suggestions_jlggj_17"};import{jsx as Sr,jsxs as zh}from"react/jsx-runtime";var jh=({title:t,children:e,...n})=>{let o=y("Section",Zc);return zh("section",{...n,className:o.root,children:[t&&Sr("div",{className:o.subTitleContainer,children:Sr("span",{className:o.subtitle,children:t})}),Sr("div",{className:o.suggestions,children:e})]})},Ct=jh;import Wh from"classnames";import Gh from"react";var Yc={root:"_root_19wxp_1"};import{jsx as Xh}from"react/jsx-runtime";var $h=Gh.forwardRef(({className:t,children:e},n)=>{let o=y("SectionList",Yc);return Xh("div",{ref:n,className:Wh(o.root,t),children:e})}),vr=$h;import{useSelector as Zh}from"react-redux";import{useCallback as Jh}from"react";import{jsx as Ge,jsxs as Mo}from"react/jsx-runtime";var Qh=({suggestion:t,lines:e,onEdit:n,onUse:o})=>{var p;let s=t.text||t.url||t.message,r=Yn(s),i=_(rn),a=E("showImages"),l=E("fallbackImage"),c=m=>{m.preventDefault(),m.stopPropagation(),o(s)},u=m=>{m.preventDefault(),m.stopPropagation(),n(t)},d=Jh(m=>{window.open(r,"_blank"),m.stopPropagation(),m.preventDefault()},[r]);return Mo(A,{onClick:c,"data-testid":"edit-suggestion",children:[Mo(O,{children:[a&&t.image&&Ge(O.Image,{src:wo(t,"small",l||void 0),title:t.title}),Mo(O.Content,{children:[t.title&&Ge(O.Title,{children:t.title}),t.searchKeywords&&((p=t.searchKeywords)==null?void 0:p.length)>0&&Ge(A.Labels,{labels:t.searchKeywords}),Ge(O.Content,{cropText:e==="single",lineClamp:e==="multiple",children:s})]})]}),Mo(A.Actions,{children:[r&&Ge(A.ActionButton,{onClick:d,label:i("visitUrl")}),Ge(A.ActionButton,{primary:!0,onClick:u,label:i("preview")}),Ge(A.ActionButton,{primary:!0,onClick:c,label:i("useSuggestion")})]})]})},eu=Qh;import{Fragment as ey,jsx as tu}from"react/jsx-runtime";var Yh=({contentType:t,lines:e,suggestions:n})=>{let o=re(),s=Zh(ct),r=a=>{o.send(_s,{state:s,suggestion:a,contentType:t})},i=(a,l)=>{o.send(ge,{text:a,suggestion:{...l,source:l.source,sourceText:l.text}})};return tu(ey,{children:n.map(a=>tu(eu,{suggestion:a,lines:e,onEdit:l=>r(l),onUse:l=>i(l,a)},a.text||a.url||a.message))})},nu=Yh;var xr={};B(xr,{enUS:()=>ty,nlNL:()=>ny});var ty={waiting:[{type:0,value:"Loading\u2026"}],notSupported:[{type:0,value:"This conversation is not supported"}],noResults:[{type:0,value:"No results found\u2026"}],titleAutoflows:[{type:0,value:"Autoflows"}],titleCustomMessages:[{type:0,value:"Quick replies"}],linkPersonalcollection:[{type:0,value:"Open Personal Collection"}],loginPlease:[{type:0,value:"Sign in to enable Deepdesk"}]},ny={waiting:[{type:0,value:"Laden\u2026"}],notSupported:[{type:0,value:"Dit gesprek wordt niet ondersteund"}],noResults:[{type:0,value:"Geen resultaten gevonden\u2026"}],titleAutoflows:[{type:0,value:"Autoflows"}],titleCustomMessages:[{type:0,value:"Quick replies"}],linkPersonalcollection:[{type:0,value:"Open Personal Collection"}],loginPlease:[{type:0,value:"Log in om Deepdesk te gebruiken"}]};var ou={root:"_root_1cw95_1",loginText:"_loginText_1cw95_7",stateText:"_stateText_1cw95_8",sectionList:"_sectionList_1cw95_20",links:"_links_1cw95_24",link:"_link_1cw95_24"};import{jsx as M,jsxs as Cr}from"react/jsx-runtime";var Oo=(t,e)=>{let n=G(me);sy(()=>n?e.every(o=>!!o)?t():()=>{}:()=>{},[...e,n])},iy=()=>{let t=_(xr),e=ry(),n=E("isEmbedded"),o=y("Widget",ou),s=E("showAutoflows"),r=E("showCustomMessages"),i=E("showPersonalCollectionLink"),a=G(ko),l=G(Ro),c=G(hc),u=G(ro),d=G(Cc),p=G(gn),m=G(fn),g=G(me),f=G(mn),T=G(Nc),b=G(ct),h=G(ha),S=G(Ic("/admin/personal-collection")),w=E("adminUrl");return Oo(()=>(e(nn(f)),e(_c(f)),()=>{e(Pc(f))}),[e,m,r,f]),Oo(()=>(e(ve(f)),e(yc(f)),()=>{e(Sc(f))}),[e,m,s,f]),Oo(()=>{l.forEach(({type:C})=>{e(C==="entities"?ne():pe(C))})},[e,m,p,a]),Oo(()=>(e(gr()),()=>{e(Ac())}),[e,m,i,p]),m===!1?M("div",{className:o.stateText,children:M("div",{children:M("p",{children:t("notSupported")})})},"supported"):g===!1?M("div",{className:o.loginText,children:M("div",{children:M(go,{isEmbedded:n,loginUrl:w})})},"login"):!a||!f||g===null||h||T?M("div",{className:o.stateText,children:M("div",{children:M("p",{children:t("waiting")})})},"waiting"):Cr("div",{className:oy(o.root),"data-testid":"widget",children:[S&&M("div",{className:o.links,children:Cr("a",{className:o.link,target:"_blank",href:S,rel:"noreferrer",children:[t("linkPersonalcollection"),M(Qc,{})]})}),Cr(vr,{className:o.sectionList,children:[r&&d.length>0&&M(Ct,{"data-testid":"custom-messages",children:M(he,{withDivider:!0,children:d.map(C=>M(Xc,{suggestion:C},C.text))})}),s&&c.length>0&&M(Ct,{title:t("titleAutoflows"),"data-testid":"autoflows",children:M(he,{withDivider:!0,children:M(Uc,{})})}),l.map(({type:C,title:x,amount:N,lines:q})=>{var D;switch(C){case"entities":return u&&u.length>0&&M(Ct,{title:x,"data-testid":`type-${C}`,children:M(Wc,{entities:u})},C);default:return((D=b[C])==null?void 0:D.fetchState)==="done"&&b[C].suggestions.length>0&&M(Ct,{title:x,"data-testid":`type-${C}`,children:M(he,{withDivider:!0,children:M(nu,{lines:q,contentType:C,suggestions:b[C].suggestions.slice(0,N)||[]})})},C)}})]})]})},su=iy;function ru(t){let e=new Range;return e.selectNodeContents(t),e}var an=/[\u200B-\u200D\uFEFF]/g;function Tt(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(l,c){let u=-1,d=/[\u200B-\u200D\uFEFF]/;if(!d.test(l))return c;for(let p=0;p<=l.length;p++)if(d.test(l[p])||u++,u===c)return p;throw new Error("Offset out of range")}function a(l){var c;switch(l.nodeType){case Node.TEXT_NODE:{let u=l.textContent,d=u.replace(an,""),p=s+d.length,m=e>=s&&e<=p,g=n>=s&&n<=p;if(m){let f=i(u,e-s);f===0&&!g?o.setStartBefore(l):o.setStart(l,f)}g&&(o.setEnd(l,i(u,n-s)),r=!0),s=p;break}case Node.ELEMENT_NODE:{if(l.tagName==="BR"&&(s===e&&o.setStartBefore(l),s++,s===n)){o.setEndAfter(l),r=!0;return}for(let d=0;d<l.childNodes.length&&(a(l.childNodes[d]),!r);d++);let u=(c=l.lastChild)==null?void 0:c.tagName;l.tagName==="DIV"&&u!=="DIV"&&u!=="BR"&&s++;break}default:break}}if(a(t),o.startContainer===document)throw new Error("Offsets out of bound");return o}function Tr(t,e){if(!t.contains(e.commonAncestorContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:o,endContainer:s,endOffset:r}=e,i,a,l=0;function c(u){let d=u===n,p=u===s;switch(u.nodeType){case Node.TEXT_NODE:{let m=u.textContent;d&&(i=l+m.substring(0,o).replace(an,"").length),p&&(a=l+m.substring(0,r).replace(an,"").length),l+=m.replace(an,"").length;break}case Node.ELEMENT_NODE:{let{tagName:m}=u,g=u.nextSibling===null;m==="BR"&&!g&&l++;for(let f=0;f<u.childNodes.length&&(d&&f===o&&(i=l),c(u.childNodes[f]),p&&f===r-1&&(a=l),a===void 0);f++);!p&&m==="DIV"&&!g&&l++,p&&(a=l);break}default:break}}if(c(t),a===void 0)throw new Error("Could not determine start and end");return{start:i??a,end:a}}function No(t,e){if(!t.contains(e.commonAncestorContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:o,endContainer:s,endOffset:r}=e,i=-1,a="";function l(c){let u=c===n,d=c===s;switch(u&&i++,c.nodeType){case Node.TEXT_NODE:{if(i!==0)return;let p=u?o:0,m=d?r:void 0,g=c.textContent.replace(an,"");p===0&&m===void 0?a+=g:a+=g.substring(p,m);break}case Node.ELEMENT_NODE:{let{tagName:p}=c,m=c.nextSibling===null;i===0&&p==="BR"&&!m&&(a+=`
3
+ `,Ke.MISSING_INTL_API,i);var C=n.getPluralRules(e,{type:u.pluralType}).select(p-(u.offset||0));v=u.options[C]||u.options.other}if(!v)throw new os(u.value,p,Object.keys(u.options),i);a.push.apply(a,Dt(v.value,e,n,o,s,p-(u.offset||0)));continue}}return fp(a)}function yp(t,e){return e?Q(Q(Q({},t||{}),e||{}),Object.keys(t).reduce(function(n,o){return n[o]=Q(Q({},t[o]),e[o]||{}),n},{})):t}function Sp(t,e){return e?Object.keys(t).reduce(function(n,o){return n[o]=yp(t[o],e[o]),n},Q({},t)):t}function ss(t){return{create:function(){return{get:function(e){return t[e]},set:function(e,n){t[e]=n}}}}}function vp(t){return t===void 0&&(t={number:{},dateTime:{},pluralRules:{}}),{getNumberFormat:jn(function(){for(var e,n=[],o=0;o<arguments.length;o++)n[o]=arguments[o];return new((e=Intl.NumberFormat).bind.apply(e,Mn([void 0],n,!1)))},{cache:ss(t.number),strategy:zn.variadic}),getDateTimeFormat:jn(function(){for(var e,n=[],o=0;o<arguments.length;o++)n[o]=arguments[o];return new((e=Intl.DateTimeFormat).bind.apply(e,Mn([void 0],n,!1)))},{cache:ss(t.dateTime),strategy:zn.variadic}),getPluralRules:jn(function(){for(var e,n=[],o=0;o<arguments.length;o++)n[o]=arguments[o];return new((e=Intl.PluralRules).bind.apply(e,Mn([void 0],n,!1)))},{cache:ss(t.pluralRules),strategy:zn.variadic})}}var vi=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(c){var u=r.formatToParts(c);if(u.length===1)return u[0].value;var d=u.reduce(function(p,m){return!p.length||m.type!==K.literal||typeof p[p.length-1]!="string"?p.push(m.value):p[p.length-1]+=m.value,p},[]);return d.length<=1?d[0]||"":d},this.formatToParts=function(c){return Dt(r.ast,r.locales,r.formatters,r.formats,c,void 0,r.message)},this.resolvedOptions=function(){var c;return{locale:((c=r.resolvedLocale)===null||c===void 0?void 0:c.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,l=pi(i,["formatters"]);this.ast=t.__parse(e,Q(Q({},l),{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=Sp(t.formats,o),this.formatters=s&&s.formatters||vp(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>"u")){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=gi,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 Tp(t,e){return e.split(".").reduce((n,o)=>n?n[o]:void 0,t)}var wp="dummy",rs=xp(null);function E(t){let e=Cp(rs);if(!e)throw new Error("useTranslator() may be used only in the context of a <LocaleContext> component.");let n=t[e]??{};return(o,s)=>{let r=Tp(n,o);return r?new vi(r).format(s):(e!==wp&&console.warn(`${o} does not exist in messages of ${e}`),`[${o}]`)}}import{jsx as xi,jsxs as bp}from"react/jsx-runtime";var Wn=()=>bp("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 256 512","aria-labelledby":"angleLeftTitle",children:[xi("title",{id:"angleLeftTitle",children:"AngleLeft"}),xi("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"})]});import{jsx as Ci,jsxs as Ep}from"react/jsx-runtime";var Ti=()=>Ep("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 256 512","aria-labelledby":"angleRightTitle",children:[Ci("title",{id:"angleRightTitle",children:"AngleRight"}),Ci("path",{d:"M64 448c-8.188 0-16.38-3.125-22.62-9.375c-12.5-12.5-12.5-32.75 0-45.25L178.8 256L41.38 118.6c-12.5-12.5-12.5-32.75 0-45.25s32.75-12.5 45.25 0l160 160c12.5 12.5 12.5 32.75 0 45.25l-160 160C80.38 444.9 72.19 448 64 448z"})]});import Gn from"classnames";import _p,{createContext as Pp,useCallback as kp,useContext as Ht}from"react";var is={root:"_root_9kn3u_10",fadein:"_fadein_9kn3u_1",isClickable:"_isClickable_9kn3u_47",isSelected:"_isSelected_9kn3u_52",actions:"_actions_9kn3u_76",actionsIsFixed:"_actionsIsFixed_9kn3u_98",actionButton:"_actionButton_9kn3u_106",dropdownList:"_dropdownList_9kn3u_127",dropdownButton:"_dropdownButton_9kn3u_142",dropdownItem:"_dropdownItem_9kn3u_152",dropdownItemButton:"_dropdownItemButton_9kn3u_161",actionButtonIsPrimary:"_actionButtonIsPrimary_9kn3u_175",actionButtonIsDisabled:"_actionButtonIsDisabled_9kn3u_179",labels:"_labels_9kn3u_187",label:"_label_9kn3u_187"};import{jsx as de,jsxs as Mp}from"react/jsx-runtime";var nt=Pp(is),Rp=({fixed:t,children:e,...n})=>{let o=Ht(nt);return de("div",{...n,className:Gn(o.actions,{[o.actionsIsFixed]:t}),children:e})},Ip=({className:t,primary:e,disabled:n,label:o,children:s})=>{let r=Ht(nt);return Mp("div",{className:Gn(t,r.actionButton,r.dropdownButton,{[r.actionButtonIsPrimary]:e,[r.actionButtonIsDisabled]:n}),onMouseDown:i=>i.stopPropagation(),onClick:i=>i.stopPropagation(),children:[o,de("ul",{className:r.dropdownList,children:s})]})},Ap=({index:t,label:e,onClick:n})=>{let o=Ht(nt);return de("li",{className:o.dropdownItem,children:de("button",{className:o.dropdownItemButton,type:"button","data-index":t,onClick:n,children:e})})},Lp=({className:t,primary:e,disabled:n,onClick:o,label:s})=>{let r=Ht(nt);return de("button",{type:"button",className:Gn(t,r.actionButton,{[r.actionButtonIsPrimary]:e,[r.actionButtonIsDisabled]:n}),onClick:o??(i=>i.stopPropagation()),disabled:n,"aria-hidden":n,children:s})},as=({labels:t})=>{let e=Ht(nt);return de("div",{className:e.labels,children:t.map(n=>de("span",{className:e.label,children:n},n))})},ot=_p.forwardRef(({className:t,selected:e,onClick:n,children:o,as:s="div",...r},i)=>{let a=y("Suggestion",is),l=kp(c=>{c.preventDefault(),n&&n(c)},[n]);return de(s,{...r,ref:i,className:Gn(t,a.root,{[a.isSelected]:e,[a.isClickable]:!!n}),onClick:l,children:de(nt.Provider,{value:a,children:o})})});ot.Labels=as;ot.Actions=Rp;ot.ActionButton=Lp;ot.DropdownButton=Ip;ot.DropdownItem=Ap;var O=ot;import{useEffect as Bt,useRef as gs,useState as Qp}from"react";import{useDispatch as Zp}from"react-redux";import{Interweave as Jp}from"interweave";import Fi from"classnames";var ls={root:"_root_7hhs4_1",agentText:"_agentText_7hhs4_3",textInput:"_textInput_7hhs4_8",textInputWrapper:"_textInputWrapper_7hhs4_27",alert:"_alert_7hhs4_31",alertText:"_alertText_7hhs4_50",warning:"_warning_7hhs4_60",success:"_success_7hhs4_69"};import{Matcher as Hp}from"interweave";import Fp from"classnames";import{useEffect as Op,useRef as Np,useState as Dp}from"react";function wi(t,e){let n;return[(...o)=>{window.cancelAnimationFrame(n);let s=e?e(...o):o;n=window.requestAnimationFrame(()=>{t(...s)})},()=>window.cancelAnimationFrame(n)]}function $n(t){let e=Np(null),[n,o]=Dp(!1);return Op(()=>{let s=!1,r=parseFloat(window.getComputedStyle(document.body).zoom??"1"),[i,a]=wi((u,d)=>{let p=e.current;if(!p)return;let m=u/r,g=d/r,f=p.getBoundingClientRect(),x=m>f.x&&m<f.x+f.width&&g>f.y&&g<f.y+f.height;x&&!s?(s=!0,o(!0)):!x&&s&&(s=!1,o(!1))},({clientX:u,clientY:d})=>[u,d]),[l,c]=wi(()=>{s=!1,o(!1)});return t.addEventListener("mousemove",i),t.addEventListener("mouseleave",l),()=>{a(),c(),t.removeEventListener("mousemove",i),t.removeEventListener("mouseleave",l)}},[e]),[e,n]}var J={root:"_root_kpc8q_1",agentText:"_agentText_kpc8q_4",tabText:"_tabText_kpc8q_9",hint:"_hint_kpc8q_10",matchSelection:"_matchSelection_kpc8q_14",focus:"_focus_kpc8q_20",resetIndent:"_resetIndent_kpc8q_24",matchKeyword:"_matchKeyword_kpc8q_28",matchPlaceholder:"_matchPlaceholder_kpc8q_29",hover:"_hover_kpc8q_35",hintText:"_hintText_kpc8q_67",popover:"_popover_kpc8q_75",popoverRoot:"_popoverRoot_kpc8q_80",popoverContentContainer:"_popoverContentContainer_kpc8q_84",popoverContent:"_popoverContent_kpc8q_84",selectionOptions:"_selectionOptions_kpc8q_110",selectionOptionsIsHidden:"_selectionOptionsIsHidden_kpc8q_115",selectionOptionsButton:"_selectionOptionsButton_kpc8q_119",caret:"_caret_kpc8q_135",popoverSuggestionsRoot:"_popoverSuggestionsRoot_kpc8q_139",suggestionsOverlayInputStyles:"_suggestionsOverlayInputStyles_kpc8q_144"};import{jsx as bi}from"react/jsx-runtime";var Bp=({inputElement:t,children:e})=>{let n=y("TabCompletion",J),[o,s]=$n(t);return bi("mark",{ref:o,className:Fp(n.matchPlaceholder,{[n.hover]:s}),children:e})},st=class extends Hp{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 bi(Bp,{inputElement:n.inputElement,children:e},`placeholder_${n.matchString}_${n.key}`)}asTag(){return"mark"}};import{useEffect as Kp,useRef as Up,useState as qp}from"react";function Xn(t){return t.contentEditable==="true"}function Vp(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 Ei(t){let{selectionStart:e,selectionEnd:n}=Xn(t)?Vp(t):t;return[e,n]}function Qn(t){let[,e]=qp(),n=Up(null);return n.current=Ei(t),Kp(()=>{let o=()=>{let[s,r]=n.current??[],i=Ei(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 Zn(t,e){if(!e)return;let n=t,{value:o}=n,[s,r]=e,i=o.match(Je);if(!i||i.length===0)return;let a=0;i.find(l=>{let c=o.indexOf(l,a);return s>c&&r<c+l.length?(n.selectionStart=c,n.selectionEnd=c+l.length,!0):(a=c+l.length,!1)})}import{useEffect as jp}from"react";function rt(t){jp(()=>{let e=n=>{n.isWithinRoot||t(n)};return document.body.addEventListener("mouseup",e),()=>{document.body.removeEventListener("mouseup",e)}},[t])}function Ue(t){t.addEventListener("mouseup",e=>{e.isWithinRoot=!0},!0)}var _i,le=new Map,zp=["bottom","height","left","right","top","width"],Wp=(t={},e={})=>zp.some(n=>t[n]!==e[n]),Pi=()=>{let t=[];le.forEach((e,n)=>{if(!n.isConnected){e.rect=null,t.push(e),le.delete(n);return}let o=n.getBoundingClientRect();Wp(o,e.rect)&&(e.rect=o,t.push(e))}),t.forEach(e=>{e.callbacks.forEach(n=>n(e.rect))}),le.size!==0&&(_i=window.requestAnimationFrame(Pi))};function ki(t,e){return{observe(){let n=le.size===0;if(le.has(t)){let o=le.get(t);o.callbacks.push(e),o.rect&&e(o.rect)}else le.set(t,{rect:void 0,callbacks:[e]});n&&Pi()},unobserve(){let n=le.get(t);if(n){let o=n.callbacks.indexOf(e);o>=0&&n.callbacks.splice(o,1),n.callbacks.length||le.delete(t),le.size||cancelAnimationFrame(_i)}}}}var Ri,ce=new Map,Ii=()=>{ce.forEach((t,e)=>{if(!e.isConnected){ce.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)))}),ce.size!==0&&(Ri=window.requestAnimationFrame(Ii))};function Ai(t,e){return{observe(){let n=ce.size===0;ce.has(t)?ce.get(t).callbacks.push(e):ce.set(t,{visible:void 0,callbacks:[e]}),n&&Ii()},unobserve(){let n=ce.get(t);if(n){let o=n.callbacks.indexOf(e);o>=0&&n.callbacks.splice(o,1),n.callbacks.length||ce.delete(t),ce.size||cancelAnimationFrame(Ri)}}}}var cs=["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 us(t,e,n){return n.forEach(o=>{e.style[o]=t[o]})}function it(t){return parseFloat(t)}function Jn(t){return Math.round(t*1e6)}function Li(t){return t/1e6}function ps(t,e,n){if(t.boxSizing==="content-box")return;let{clientWidth:o}=e,s=it(t.width),r=it(t.borderLeftWidth),i=it(t.borderRightWidth),a=it(t.paddingRight),l=Li(Jn(s)-Jn(r)-Jn(i)),c=Li(Jn(o));if(l-c>2){let u=l-c;n.style.paddingRight=`${a+u}px`}}function Ft(t,e={}){var l;let n=e.overlayContainer||document.createElement("div");n.style.display="none",n.style.position="fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",Ue(n);let o=window.getComputedStyle(t),s=!0,r=()=>{n.scrollTop=t.scrollTop};us(o,n,cs),ps(o,t,n),e.mirrorOverflow&&(n.style.overflow="hidden",t.addEventListener("scroll",r));let i=Ai(t,()=>{us(o,n,cs),ps(o,t,n),r(),setTimeout(r,0)}),a=ki(t,c=>{if(c===null){e.onRemove&&e.onRemove(),n.remove();return}if(c.height===0&&c.width===0){if(s===!0)return;e.onHide&&e.onHide(),n.style.display="none",s=!0;return}if(us(o,n,cs),ps(o,t,n),r(),n.style.top=`${c.top}px`,n.style.left=`${c.left}px`,e.closestScrollElement&&e.closestScrollElement!==t){let u=e.closestScrollElement.getBoundingClientRect(),d=window.getComputedStyle(e.closestScrollElement),p=it(d.borderTopWidth),m=it(d.borderBottomWidth),g=u.top+p-c.top,f=c.top+c.height+-(u.top+u.height-m);n.style.clipPath=`inset(${g}px 0px ${f}px 0px)`}s&&(n.style.display="block",e.onShow&&e.onShow(),s=!1)});return e.appendTo?e.appendTo.appendChild(n):(l=t.parentElement)==null||l.appendChild(n),a.observe(),i.observe(),[n,()=>{t.removeEventListener("scroll",r),a.unobserve(),i.unobserve()}]}var ds={};B(ds,{enUS:()=>Gp,nlNL:()=>$p});var Gp={placeholders:[{type:6,value:"placeholderSize",options:{"=0":{value:[{type:0,value:"No placeholders found"}]},one:{value:[{type:0,value:"There is one placeholder in your message"}]},other:{value:[{type:0,value:"There are "},{type:7},{type:0,value:" placeholders in your message"}]}},offset:0,pluralType:"cardinal"}]},$p={placeholders:[{type:6,value:"placeholderSize",options:{"=0":{value:[{type:0,value:"Alle placeholders zijn uit je bericht"}]},one:{value:[{type:0,value:"Er is 1 placeholder in jouw bericht"}]},other:{value:[{type:0,value:"Er zijn "},{type:7},{type:0,value:" placeholders in jouw bericht"}]}},offset:0,pluralType:"cardinal"}]};import{jsx as Mi,jsxs as Xp}from"react/jsx-runtime";var Oi=()=>Xp("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 512 512","aria-labelledby":"circleCheckTitle",children:[Mi("title",{id:"circleCheckTitle",children:"Check"}),Mi("path",{d:"M243.8 339.8C232.9 350.7 215.1 350.7 204.2 339.8L140.2 275.8C129.3 264.9 129.3 247.1 140.2 236.2C151.1 225.3 168.9 225.3 179.8 236.2L224 280.4L332.2 172.2C343.1 161.3 360.9 161.3 371.8 172.2C382.7 183.1 382.7 200.9 371.8 211.8L243.8 339.8zM512 256C512 397.4 397.4 512 256 512C114.6 512 0 397.4 0 256C0 114.6 114.6 0 256 0C397.4 0 512 114.6 512 256zM256 48C141.1 48 48 141.1 48 256C48 370.9 141.1 464 256 464C370.9 464 464 370.9 464 256C464 141.1 370.9 48 256 48z"})]});import{jsx as Ni}from"react/jsx-runtime";var Di=()=>Ni("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",fill:"currentColor",children:Ni("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 Hi=(i=>(i.CUT="Cut",i.BACKSPACE="Backspace",i.DELETE="Delete",i.ERASEEOF="EraseEof",i.UNDO="Undo",i.CLEAR="Clear",i))(Hi||{}),Le=class{constructor(e){this.element=e;this.currentText=this.getText(),this.currentHTML=this.getHTML(),this.listen()}eventListeners={};disposeHandlers=[];currentText="";currentHTML="";currentSelection=null;isFocused=!1;isActive=!0;isSettingValue=!1;isSubmitting=!1;isPossibleClearInputAction=!1;isDisposed=!1;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)}triggerChange(){let e=this.getText(),n=this.getHTML(),o=e!==this.currentText;this.isActive&&(e===""&&this.currentText!==""&&!this.isSettingValue&&!this.isPossibleClearInputAction&&(this.isSubmitting=!0,this.emit("submit")),!this.isSettingValue&&o&&!this.isSubmitting&&this.emit("change",{plainText:e,rawHtml:n}),this.currentText=e,this.isSubmitting=!1,(this.currentHTML!==n||n===null&&o)&&(this.emit("updated",{plainText:e,rawHtml:n}),this.currentHTML=n))}handleKeyUp(e){let{key:n,shiftKey:o}=e;(n==="Enter"&&o===!0||n==="Backspace")&&this.triggerChange()}handleFocus(){this.isFocused||this.emit("focus"),this.isFocused=!0}handleBlur(){this.isPossibleClearInputAction=!1,this.isFocused&&this.emit("blur"),this.isFocused=!1}handleKeyDown(e){let{key:n,ctrlKey:o,metaKey:s}=e;this.isPossibleClearInputAction=Object.values(Hi).includes(n)||n.toLowerCase()==="z"&&(o||s),this.emit("keydown",e)}handleCut(){let e=this.currentSelection;this.isPossibleClearInputAction=!0,e&&this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(e){let n=(e.clipboardData||window.clipboardData).getData("text");this.emit("paste",{pastedText:n,selectionText:this.getSelectedText()})}listen(){let e=()=>{let o=document.activeElement===this.element?this.getSelection():null;ke(this.currentSelection,o)||(this.currentSelection=o,this.emit("selection",o))};document.addEventListener("selectionchange",e),this.disposeHandlers.push(()=>{window.document&&document.removeEventListener("selectionchange",e)}),this.addEventListener("keydown",o=>this.handleKeyDown(o)),this.addEventListener("keyup",o=>this.handleKeyUp(o)),this.addEventListener("input",()=>this.triggerChange()),this.addEventListener("change",()=>this.triggerChange()),this.addEventListener("focus",()=>this.handleFocus()),this.addEventListener("blur",()=>this.handleBlur()),this.addEventListener("cut",()=>this.handleCut()),this.addEventListener("paste",o=>this.handlePaste(o)),document.activeElement===this.element&&setTimeout(()=>{this.handleFocus()},0);let n=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});n.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{n.disconnect()})}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))}activate(){let e=this.isActive===!1;this.isActive=!0,e&&this.triggerChange()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(e=>e()),this.eventListeners={},this.isDisposed=!0}};var Me=class extends Le{getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:e,selectionEnd:n}=this.element;return{start:e,end:n}}getSelectedText(){return this.currentSelection?this.getText().slice(this.currentSelection.start,this.currentSelection.end):""}applyChanges(e){if(!this.isActive)return;this.isSettingValue=!0;let n=this.getText(),o=e(this.element);Promise.resolve(o).then(()=>{this.currentText=this.getText(),n!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(){super.listen();let e=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var s;return(s=e==null?void 0:e.get)==null?void 0:s.call(this.element)},set:s=>{var r;(r=e==null?void 0:e.set)==null||r.call(this.element,s),this.triggerChange()}});let n=this.element.disabled,o=new MutationObserver(()=>{this.element.disabled!==n&&(n=this.element.disabled,this.emit(n?"disabled":"enabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>o.disconnect())}};import{jsx as me,jsxs as ms}from"react/jsx-runtime";var Yp=({value:t,onUse:e,...n})=>{var u;let o=E(ds),s=Zp(),r=y("EditSuggestionTextInput",ls),[i,a]=Qp(null),l=gs(null),c=((u=t.match(Je))==null?void 0:u.length)||0;return Bt(()=>{let d;return l.current&&(a(l.current),d=new Me(l.current),d.on("change",({plainText:p})=>{s(V.actions.userInput({text:p,selection:d.getSelection()}))}),d.on("keydown",p=>{s(V.actions.registerKeyDown(_n(p))),p.code==="Enter"&&p.shiftKey&&e(d.getText())}),d.on("paste",({pastedText:p,selectionText:m})=>{s(V.actions.registerPaste({text:p,selectionText:m}))}),d.on("cut",({selectionText:p})=>{s(V.actions.registerCut(p))})),()=>{s(V.actions.reset()),d.dispose(),d.deactivate()}},[l]),Bt(()=>{t&&l.current&&(l.current.value=t)},[t,l]),Bt(()=>{l.current&&setTimeout(()=>{if(!l.current)return;let d=l.current.value.length;l.current.setSelectionRange(d,d),l.current.focus()},0)},[l]),ms("div",{className:r.textInputWrapper,children:[me("textarea",{...n,ref:l,"data-testid":"edit-suggestion-dialog-textarea",className:r.textInput,defaultValue:t,onChange:()=>{}}),i&&me(ed,{inputElement:l.current,value:t}),ms("div",{className:Fi(r.alert,c===0?r.success:r.warning),children:[me("div",{className:r.alertText,children:o("placeholders",{placeholderSize:c})}),c===0?me(Oi,{}):me(Di,{})]})]})},ed=({inputElement:t,value:e})=>{let n=y("EditSuggestionTextInput",ls),o=gs(null),s=Qn(t);return Bt(()=>{Zn(t,s)},[s,t]),me(td,{inputElement:t,children:ms("div",{ref:o,className:Fi(n.root,n.agentText),children:[me(Jp,{tagName:"span",disableLineBreaks:!0,content:e,matchers:[new st("placeholders")],inputElement:t,boundaryRef:o}),me("br",{})]})})},td=({inputElement:t,children:e})=>{let n=gs(null);return Bt(()=>{if(!n.current)return()=>{};let[o,s]=Ft(t,{overlayContainer:n.current,mirrorOverflow:!0});return()=>{s()}},[n.current]),me("div",{ref:n,children:e})},Bi=Yp;import{useEffect as Ad,useState as Ld,useRef as Md}from"react";var j={root:"_root_m5usm_1",list:"_list_m5usm_2",listWrapper:"_listWrapper_m5usm_6",listHorizontal:"_listHorizontal_m5usm_10",page:"_page_m5usm_19",search:"_search_m5usm_25",pageNav:"_pageNav_m5usm_33",pageTitle:"_pageTitle_m5usm_41",pageBackButton:"_pageBackButton_m5usm_48",listHeading:"_listHeading_m5usm_62",listItem:"_listItem_m5usm_70",listItemContent:"_listItemContent_m5usm_79",listItemText:"_listItemText_m5usm_97",listItemDescription:"_listItemDescription_m5usm_105",truncate:"_truncate_m5usm_112",lineClamp:"_lineClamp_m5usm_118",listItemTitle:"_listItemTitle_m5usm_125",listItemAction:"_listItemAction_m5usm_132",listItemPrimaryAction:"_listItemPrimaryAction_m5usm_146",listItemSelected:"_listItemSelected_m5usm_151",sources:"_sources_m5usm_155",sourcesTitle:"_sourcesTitle_m5usm_162",source:"_source_m5usm_155",icon:"_icon_m5usm_177",searchIcon:"_searchIcon_m5usm_194",searchInputWrapper:"_searchInputWrapper_m5usm_199",searchInput:"_searchInput_m5usm_199",select:"_select_m5usm_220",selectType:"_selectType_m5usm_237",selectWrapper:"_selectWrapper_m5usm_241",image:"_image_m5usm_271",imageSrc:"_imageSrc_m5usm_278",imageTitle:"_imageTitle_m5usm_289",actions:"_actions_m5usm_294",actionsWrapper:"_actionsWrapper_m5usm_298",actionsBar:"_actionsBar_m5usm_304",actionButton:"_actionButton_m5usm_313",actionShortcut:"_actionShortcut_m5usm_331",actionShortcutFixKerning:"_actionShortcutFixKerning_m5usm_338"};import{jsx as Ki,jsxs as od}from"react/jsx-runtime";var nd=({src:t,title:e})=>{let n=y("CommandPalette",j);return od("div",{className:n.image,children:[Ki("img",{src:t,alt:e,className:n.imageSrc}),e&&Ki("span",{className:n.imageTitle,children:e})]})},Ui=nd;import sd from"react";import rd from"classnames";import{jsx as qi,jsxs as id}from"react/jsx-runtime";function fs({children:t,heading:e,orientation:n}){let o=y("CommandPalette",j);return sd.Children.count(t)===0?null:id("div",{"data-testid":"commandpalette-list",className:o.list,children:[e&&qi("h4",{className:o.listHeading,children:e}),qi("div",{className:rd(o.listWrapper,n==="horizontal"&&o.listHorizontal),children:t})]})}import eo from"classnames";var Vi={root:"_root_nkim0_1"};var hs={};B(hs,{enUS:()=>ad,nlNL:()=>ld});var ad={experimental:[{type:0,value:"Experimental"}]},ld={experimental:[{type:0,value:"Experimenteel"}]};import{jsx as zi}from"react/jsx-runtime";var ji=({children:t})=>{let e=y("Chip",Vi);return zi("span",{className:e.root,children:t})},Yn=()=>{let t=E(hs);return zi(ji,{children:t("experimental")})},cd=ji;import ys from"react";import{jsx as ud}from"react/jsx-runtime";var Wi=ys.createContext(void 0);function Oe(){let t=ys.useContext(Wi);if(t===void 0)throw new Error("useCommandPalette must be used within the CommandPalette component");return t}var Gi=({children:t,page:e,isOpen:n,onChangeOpen:o,selected:s,setSelected:r})=>{let i=ys.useMemo(()=>({page:e,isOpen:n,onChangeOpen:o,selected:s,setSelected:r}),[n,e,s]);return ud(Wi.Provider,{value:i,children:t})};import{jsx as at,jsxs as to}from"react/jsx-runtime";function Ss({closeOnSelect:t=!0,lineClamp:e,children:n,onClick:o,index:s,isExperimental:r,description:i,sources:a,styles:l,...c}){let{selected:u,onChangeOpen:d}=Oe(),p=y("CommandPalette",j);function m(g){o(g),t&&d(!1)}return to("div",{className:eo(p.listItem,u===s&&p.listItemSelected),children:[to("button",{type:"button",className:eo("command-palette-list-item",p.listItemAction,p.listItemPrimaryAction),"aria-disabled":c.disabled??!1,onClick:m,...c,children:[to("div",{className:p.listItemContent,children:[typeof n=="string"?at("p",{className:eo(p.listItemText,p.truncate,l==null?void 0:l.title),children:n}):n,i&&at("p",{className:eo(p.listItemDescription,l==null?void 0:l.description,e?p.lineClamp:p.truncate),children:i})]}),r&&at(Yn,{})]}),a&&to("div",{className:p.sources,children:[at("span",{className:p.sourcesTitle,children:"Sources"}),a.map(g=>g.url?at("a",{className:p.source,href:g.url,target:"_blank",title:g.url,rel:"noopener noreferrer",children:g.name},g.url):at("span",{className:p.source,children:g.name},g.name))]})]})}var Kt={};B(Kt,{enUS:()=>pd,nlNL:()=>dd});var pd={visitUrl:[{type:0,value:"Visit"}],back:[{type:0,value:"Back"}]},dd={visitUrl:[{type:0,value:"Bekijk"}],back:[{type:0,value:"Terug"}]};import{jsx as vs,jsxs as xs}from"react/jsx-runtime";function Cs({children:t,title:e,id:n,onDismiss:o,isExperimental:s}){let r=E(Kt),i=y("CommandPalette",j),{page:a}=Oe();return a!==n?null:xs("div",{className:i.page,id:`page_${n}`,tabIndex:-1,children:[o&&xs("div",{className:i.pageNav,children:[xs("button",{className:i.pageBackButton,type:"button",onClick:o,children:[vs(Wn,{}),r("back")]}),e&&vs("h3",{className:i.pageTitle,children:e}),s&&vs(Yn,{})]}),t]})}import{Fragment as wd,useCallback as bd,useEffect as Ed,useRef as _d}from"react";var no=()=>/Mac/i.test(navigator.platform);import{createAsyncThunk as yd,createSlice as Sd}from"@reduxjs/toolkit";var md={info(...t){console.info("[Deepdesk]",...t)},warn(...t){console.warn("[Deepdesk]",...t)},error(...t){console.error("[Deepdesk]",...t)}},_=md;import{createAsyncThunk as ws,createSlice as fd}from"@reduxjs/toolkit";function gd(t){return t.replace(/(_\w)/g,e=>e[1].toUpperCase())}function L(t){return Array.isArray(t)?t.map(L):typeof t=="object"&&t!==null?Object.keys(t).reduce((e,n)=>({...e,[gd(n)]:L(t[n])}),{}):t}function Ts(t){return t.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}function H(t){return Array.isArray(t)?t.map(H):typeof t=="object"&&t!==null?Object.keys(t).reduce((e,n)=>({...e,[Ts(n)]:H(t[n])}),{}):t}var hd={agentInfo:void 0,agentSettings:{},visitorInfo:void 0,fetchState:"idle"},qt=t=>{var e,n,o;return{timezone:((e=t.info.visitorInfo)==null?void 0:e.visitorTimeZone)||Intl.DateTimeFormat().resolvedOptions().timeZone,agentName:((n=t.info.agentInfo)==null?void 0:n.agentNickname)||"",visitorName:((o=t.info.visitorInfo)==null?void 0:o.visitorName)||""}},Ut=ws("info/setAgentInfo",async(t,e)=>{let{deepdeskAPI:n}=e.extra;if(!t.agentId&&!t.agentNickname)throw new Error("At least provide agentId or agentNickname");let o=await n.client.get("/apis/admin/session/me/",{version:null}),s={};return o.external_id||(s.external_id=t.agentId),o.nickname||(s.nickname=t.agentNickname),!s.external_id&&!s.nickname?L(o):(await n.client.patch("/apis/admin/session/me/",s,{version:null}),L(o))}),bs=ws("info/setAgentSettings",async(t,e)=>{let{deepdeskAPI:n}=e.extra,o=await n.client.get("/apis/admin/session/me/",{version:null}),s={...typeof o.ui_config=="object"?o.ui_config:{},...t};return await n.client.patch("/apis/admin/session/me/",{ui_config:s}),s}),Es=ws("info/getAgentSettings",async(t,e)=>{let{deepdeskAPI:n}=e.extra;return(await n.client.get("/apis/admin/session/me/",{version:null})).ui_config}),$i=t=>t.info.agentInfo,Xi=fd({name:"info",initialState:hd,reducers:{setVisitorInfo(t,e){t.visitorInfo={...t.visitorInfo,...e.payload}}},extraReducers:t=>{t.addCase(Ut.pending,(e,n)=>{e.fetchState="loading",e.agentInfo={...e.agentInfo,...n.meta.arg}}).addCase(Ut.rejected,e=>{e.fetchState="error"}).addCase(Ut.fulfilled,(e,n)=>{e.fetchState="done",e.agentInfo={...e.agentInfo,...n.meta.arg,agentId:n.payload.externalId||n.meta.arg.agentId||"",agentNickname:n.payload.nickname||n.meta.arg.agentNickname||""}}).addCase(bs.fulfilled,(e,n)=>{e.agentSettings=n.payload}).addCase(Es.fulfilled,(e,n)=>{e.agentSettings=n.payload}).addCase(R,e=>{e.visitorInfo=void 0})}}),{setVisitorInfo:Qi}=Xi.actions,Zi=Xi.reducer;var oo={list:[],fetchState:"idle",isOpen:!1,page:"search"},Ji=t=>t.search.isOpen,Yi=t=>t.search.page,ea=t=>t.search.list;function ta(t,e=n=>n){return n=>n.search.list.filter(o=>o.type===t).map(e)}var qe=yd("search/getAll",async(t,e)=>{var i;let{deepdeskAPI:n}=e.extra,o=e.getState(),s=(i=o.conversation.current)==null?void 0:i.profileCode;if(!s)throw new Error("Profile should be provided in order to be able to search");let{results:r}=await n.search({profile:s,query:t.query,filters:{type:t.type},params:qt(o),tags:t.tags});return r}),na=Sd({name:"search",initialState:oo,reducers:{setIsOpen(t,e){t.isOpen=e.payload},setPage(t,e){t.page=e.payload},resetSearch(t){t.fetchState=oo.fetchState,t.list=oo.list}},extraReducers:t=>{t.addCase(qe.pending,e=>{e.fetchState="loading"}).addCase(qe.rejected,(e,n)=>{e.fetchState="error",_.error(n.error)}).addCase(qe.fulfilled,(e,n)=>{e.fetchState="done",e.list=n.payload}).addCase(R,()=>oo)}}),{resetSearch:so,setIsOpen:Z,setPage:q}=na.actions,oa=na.reducer;var vd=/(https?:\/\/[^\s]+)/,ro=t=>t.split(" ").find(e=>vd.test(e));import sa from"classnames";import{jsx as Cd,jsxs as Td}from"react/jsx-runtime";var xd=({onClick:t,shortKeys:e,children:n,...o})=>{let s=y("CommandPalette",j);return Td("button",{type:"button",...o,onClick:t,className:sa(s.actionButton,o.className),children:[n,e&&e.map(r=>Cd("span",{className:sa(s.actionShortcut,r===8629&&s.actionShortcutFixKerning),children:typeof r=="number"?String.fromCharCode(r):r},r))]})},lt=xd;import{jsx as io,jsxs as _s}from"react/jsx-runtime";var Pd=({children:t,primaryLabel:e,secondaryLabel:n,onPrimary:o,onSecondary:s,list:r})=>{let i=y("CommandPalette",j),a=E(Kt),{selected:l,setSelected:c}=Oe(),u=r[l],d=u&&typeof u.text=="string"&&ro(u.text),p=_d(null);function m(v){if(!p.current)return;let C=p.current.querySelectorAll(".command-palette-list-item"),P=0,w=0;v==="down"?(C.forEach(($,k)=>{k===l&&(P=k)}),w=P===C.length-1?0:P+1):v==="up"?(C.forEach(($,k)=>{k===l&&(P=k)}),w=P?P-1:C.length-1):c(0);let N=C[w];N&&typeof w=="number"&&(c(w),N.scrollIntoView&&N.scrollIntoView({behavior:"smooth",block:w?"center":"end"}))}function g(){if(!p.current)return;let v=p.current.querySelectorAll(".command-palette-list-item"),C=0;v.forEach((w,N)=>{N===l&&(C=N)});let P=v[C];P&&P.click()}let f=()=>{d&&window.open(d,"_blank")},x=()=>{u&&o(u,l)},b=()=>{!u.type||["IMAGE","command"].includes(u.type)||s&&s(u,l)},h=bd(v=>{if(v.key==="Enter"&&v.altKey&&d){f();return}if(v.key==="Enter"&&v.shiftKey){b();return}if(v.key==="ArrowDown"){v.preventDefault(),v.stopPropagation(),m("down");return}if(v.key==="ArrowUp"){v.preventDefault(),v.stopPropagation(),m("up");return}v.key==="Enter"&&l!==-1&&(v.preventDefault(),v.stopPropagation(),g())},[l]);return Ed(()=>(window.addEventListener("keyup",h),()=>{window.removeEventListener("keyup",h)}),[h]),_s("div",{className:i.actions,children:[io("div",{className:i.actionsWrapper,ref:p,children:t}),_s("div",{className:i.actionsBar,children:[d&&io(lt,{onClick:f,shortKeys:[no()?8997:"ALT",8629],children:a("visitUrl")}),u&&_s(wd,{children:[s&&u.type&&!["command","image"].includes(u.type.toLowerCase())&&io(lt,{onClick:b,shortKeys:[8679,8629],children:n}),io(lt,{onClick:x,shortKeys:[8629],children:e})]})]})]})},ia=Pd;import{forwardRef as Rd}from"react";import{jsx as aa,jsxs as kd}from"react/jsx-runtime";var ct=()=>kd("svg",{xmlns:"http://www.w3.org/2000/svg",height:"24px",viewBox:"0 0 24 24",width:"24px",fill:"currentColor",children:[aa("path",{d:"M0 0h24v24H0z",fill:"none"}),aa("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"})]});import{jsx as ut,jsxs as Ps}from"react/jsx-runtime";function Id({onChange:t,onChangeType:e,placeholder:n,typePlaceholder:o,types:s,value:r,selectedType:i},a){let l=y("CommandPalette",j);return Ps("div",{className:l.search,children:[ut("div",{className:l.searchIcon,children:ut(ct,{})}),Ps("div",{className:l.searchInputWrapper,children:[ut("input",{ref:a,spellCheck:!1,onChange:c=>{t(c.currentTarget.value)},onFocus:c=>{c.currentTarget.select()},className:l.searchInput,placeholder:n,value:r,type:"text",id:"command-palette-search-input",autoFocus:!0}),s&&s.length>0&&ut("div",{className:l.selectWrapper,children:Ps("select",{"data-testid":"command-palette-type-select",className:l.select,onChange:c=>e(c.target.value===o?void 0:c.target.value),value:i||o,children:[o&&ut("option",{children:o}),s.map(c=>ut("option",{value:c.value,children:c.label},c.value))]})})]})]})}var la=Rd(Id);import{jsx as ca,jsxs as Od}from"react/jsx-runtime";function Ve({placeholder:t="Start typing to search...",typePlaceholder:e="All types",defaultPage:n="search",page:o,onChangePage:s,onChangeSearch:r,onChangeType:i,onChangeOpen:a,selectedType:l,types:c,children:u,isOpen:d,search:p}){let[m,g]=Ld(0),f=Md(null),x=()=>{s&&s(n),i(void 0),r(""),a(!1)},b=()=>{var h;if(o!==n&&s){s(n);return}if(l&&i){i(void 0),(h=f.current)==null||h.focus();return}if(p.length>0){r("");return}a(!1)};return Ad(()=>{g(0)},[p,o]),ca(tt,{autoFocus:!0,contentAriaLabel:"Search Results",overlayAriaLabel:"Command Palette",isOpen:d,onBack:b,onClose:x,children:Od(Gi,{selected:m,setSelected:g,isOpen:d,onChangeOpen:a,page:o,children:[o===n&&ca(la,{ref:f,onChange:r,onChangeType:i,placeholder:t,value:p,selectedType:l,types:c,typePlaceholder:e}),u]})})}Ve.Page=Cs;Ve.List=fs;Ve.Image=Ui;Ve.ListItem=Ss;Ve.ActionsBar=ia;Ve.Button=lt;var I=Ve;import{jsx as ge,jsxs as Vt}from"react/jsx-runtime";var Hd=({suggestion:t,onUse:e,onDismiss:n,onTouched:o,onNext:s,onPrevious:r})=>{let i=t.text||t.url||t.message,a=y("EditSuggestionForm",ui),l=Nd(),c=E(Zo),u=Dd(g=>g.overlayInput.text);ua(()=>{t&&(l(V.actions.reset()),l(V.actions.stageSuggestion({text:i,suggestion:t,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"})),l(V.actions.commitSuggestion()))},[t]);let d=g=>{g.preventDefault(),p(u)},p=g=>{l(Rn(g)),e(g)},m=g=>f=>{u!==i?window.confirm(c("warning"))&&g(f):g(f)};return ua(()=>{o&&o(u!==i)},[o,t,u]),Vt("div",{className:a.root,children:[Vt("div",{className:a.content,children:[t.title&&ge("h3",{className:a.title,children:t.title}),t.searchKeywords&&t.searchKeywords.length>0&&ge(as,{labels:t.searchKeywords}),ge(Bi,{onUse:p,value:u})]}),Vt("form",{className:a.actions,onSubmit:d,children:[Vt("div",{children:[ge("button",{disabled:!r,className:a.pagination,type:"button",onClick:r&&m(r),children:ge(Wn,{})}),ge("button",{disabled:!s,className:a.pagination,type:"button",onClick:s&&m(s),children:ge(Ti,{})})]}),Vt("div",{className:a.primaryButtons,children:[ge(I.Button,{onClick:m(n),shortKeys:["esc"],children:c("dismiss")}),ge(I.Button,{shortKeys:[8679,8629],type:"submit",children:c("add")})]})]})]})},ao=Hd;import{createAction as Kd,createAsyncThunk as ga,createSlice as Ud}from"@reduxjs/toolkit";var Fd=["{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}"],Bd=new RegExp(Fd.map(t=>`(?:${t.replace("{","\\{").replace("}","\\}")})`).join("|"));function pa(t,e){let n=t.split(Bd),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],l=r===n.length-2;o+=i.length;let c=o;if(l){let d=a.charAt(0),p=0;do c=d?e.indexOf(d,c+1):-1,p+=1;while(c!==-1&&a.indexOf(e.slice(c))!==0);if(c===-1&&p>2)return t}else c=a&&a!==""?e.indexOf(a,o):-1;let u=c===-1?e.slice(o):e.slice(o,c);s.push(u),o=c}return s.join("")}function da(t,e){return typeof e=="boolean"?t:t.slice(0,e)}var fa={suggestions:[],fetchState:"idle",isInitialRequest:null},ma={default:fa},ha=t=>e=>{var n;return((n=e.textSuggestions[t])==null?void 0:n.suggestions)??[]},ya=t=>e=>{var n;return((n=e.textSuggestions[t])==null?void 0:n.suggestions)??[]},Sa=t=>{let e=Object.keys(t.textSuggestions).map(n=>{var o;return(o=t.textSuggestions[n])==null?void 0:o.fetchState});return e.length===0?!0:e.every(n=>n!=="done")},pt=t=>t.textSuggestions,va=t=>e=>e.text.startsWith(t),lo=Kd("textSuggestions/refresh"),fe=ga("textSuggestions/recommendations",async(t,e)=>{var c;let{deepdeskAPI:n}=e.extra,o=e.getState(),s=(c=o.conversation.current)==null?void 0:c.id,{textSuggestionsCount:r,inlineSuggestions:i}=o.settings,a=et(o);if(!s)throw new Error("No current conversation to fetch text suggestions");let l=await n.getTextSuggestions(s,qt(o),t);if(t==="default"){let u=i?l.filter(va(a)):l;e.dispatch(Ie(u.slice(0,r)))}return l}),jt=ga("textSuggestions/autocompletions",async(t,e)=>{var c;let{deepdeskAPI:n}=e.extra,o=e.getState(),s=(c=o.conversation.current)==null?void 0:c.id,{textSuggestionsCount:r,deanonymize:i,inlineSuggestions:a}=o.settings;if(!s)throw new Error("No current conversation to fetch text suggestions");let l=await n.getAutocompleteSuggestions(s,{...qt(o),input:t});if(!e.getState().input.text)throw new Error("Abort");return a&&(l=l.filter(va(t))),i&&(l=l.map(u=>({...u,text:u.source!=="trie-with-typos"?pa(u.text,t):u.text}))),l=da(l,r),e.dispatch(Ie(l)),l}),xa=Ud({name:"textSuggestions",initialState:ma,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}}}},setSuggestionState(t,e){return e.payload}},extraReducers:t=>{t.addCase(fe.pending,(e,n)=>{let o=n.meta.arg,s=e[o]||fa;return{...e,[o]:{...s,fetchState:"loading",isInitialRequest:s.isInitialRequest===null}}}).addCase(fe.rejected,(e,n)=>{let o=n.meta.arg;e[o].fetchState="error"}).addCase(fe.fulfilled,(e,n)=>{let o=n.meta.arg;e[o].fetchState="done",e[o].suggestions=n.payload}).addCase(jt.pending,e=>{e.default.fetchState="loading"}).addCase(jt.rejected,e=>{e.default.fetchState="error"}).addCase(jt.fulfilled,(e,n)=>{e.default.fetchState="done",e.default.suggestions=n.payload}).addCase(R,()=>ma)}}),{setTextSuggestions:Ca,setSuggestionState:Ta}=xa.actions,wa=xa.reducer;import{createSlice as qd}from"@reduxjs/toolkit";var ba={contentType:null,suggestion:null},Ea=t=>t.activeSuggestion.suggestion,_a=t=>t.activeSuggestion.contentType,Pa=qd({name:"activeSuggestion",initialState:ba,reducers:{setActiveSuggestion(t,e){let{contentType:n,suggestion:o}=e.payload;t.contentType=n,t.suggestion=o},resetActiveSuggestion(t){t.contentType=null,t.suggestion=null}},extraReducers:t=>{t.addCase(R,()=>ba)}}),{setActiveSuggestion:he,resetActiveSuggestion:ks}=Pa.actions,ka=Pa.reducer;var Rs={};B(Rs,{enUS:()=>Vd,nlNL:()=>jd});var Vd={warning:[{type:0,value:"Are you sure you want to discard the message?"}],editContentLabel:[{type:0,value:"Edit and view suggestion"}],overlayLabel:[{type:0,value:"Close dialog"}]},jd={warning:[{type:0,value:"Weet je zeker dat je de wijzigingen wilt weggooien?"}],editContentLabel:[{type:0,value:"Bewerk en bekijk suggestie"}],overlayLabel:[{type:0,value:"Sluit"}]};import{createSlice as zd}from"@reduxjs/toolkit";var Wd={showTabHint:!1,inputHasFocus:!1,overlayCollapsed:!1,openOverlayWhenTyping:!1,overlayCollapsedUserOverwrite:!1};var Ra=({ui:t})=>t.overlayCollapsed;var Ia=zd({name:"ui",initialState:Wd,reducers:{setShowTabHint(t,e){t.showTabHint=e.payload},setInputHasFocus(t,e){t.overlayCollapsedUserOverwrite!==!0&&(e.payload===!0&&(t.overlayCollapsed=!1),t.inputHasFocus=e.payload)},setOverlayCollapsed(t,e){e.payload.collapse===!1&&(t.openOverlayWhenTyping=!1),!(e.payload.skipWhenInputFocus&&t.inputHasFocus)&&(t.overlayCollapsed=e.payload.collapse)},setOpenOverlayWhenTyping(t,e){t.openOverlayWhenTyping=e.payload},setOverlayCollapsedUserOverwrite(t,e){t.overlayCollapsedUserOverwrite=e.payload,t.overlayCollapsed=e.payload}}}),{setShowTabHint:zt,setInputHasFocus:dt,setOverlayCollapsed:mt,setOpenOverlayWhenTyping:Aa,setOverlayCollapsedUserOverwrite:La}=Ia.actions,Ma=Ia.reducer;import Oa,{useContext as Gd}from"react";import{jsx as $d}from"react/jsx-runtime";var Na=Oa.createContext(null),Wt=({broadcastEvents:t,children:e})=>{let n=Oa.useMemo(()=>t,[]);return $d(Na.Provider,{value:n,children:e})},Y=()=>{let t=Gd(Na);if(!t)throw new Error("You should use the useBroadcastEvents within a BroadcastEventsProvider");return t};import{createAsyncThunk as Is,createSlice as Xd}from"@reduxjs/toolkit";var Qd={isLoggedIn:!0,loginFetchState:"idle",verifyFetchState:"idle",showLoginOverlay:!1},ye=t=>t.auth.isLoggedIn,Da=t=>t.auth.loginFetchState,Ha=t=>t.auth.verifyFetchState,Fa=t=>t.auth.showLoginOverlay,je=Is("auth/validate",async(t,e)=>e.extra.deepdeskAPI.isLoggedIn()),Ba=Is("auth/requestLogin",async({email:t},e)=>{let{deepdeskAPI:n}=e.extra;return n.requestLoginByEmail(t)}),Gt=Is("auth/verifyLoginToken",async({token:t},e)=>{let{deepdeskAPI:n}=e.extra;return n.verifyLoginToken(t)}),Ka=Xd({name:"auth",initialState:Qd,reducers:{setIsLoggedIn(t,e){t.isLoggedIn=e.payload},setShowLoginOverlay(t,e){t.showLoginOverlay=e.payload}},extraReducers:t=>{t.addCase(je.pending,e=>{e.loginFetchState="loading"}),t.addCase(je.fulfilled,(e,{payload:n})=>{e.isLoggedIn=n,e.loginFetchState="done"}),t.addCase(je.rejected,e=>{e.loginFetchState="error",e.isLoggedIn=!1}),t.addCase(Gt.pending,e=>{e.verifyFetchState="loading"}),t.addCase(Gt.rejected,e=>{e.verifyFetchState="error"}),t.addCase(Gt.fulfilled,(e,n)=>{n.payload.isLoggedIn?e.verifyFetchState="done":e.verifyFetchState="error"})}}),{setIsLoggedIn:co,setShowLoginOverlay:Ua}=Ka.actions,qa=Ka.reducer;var As="SetActiveSuggestion",gt="ShowLoginOverlay",Ls="UserLoggedIn",Se="ApplySuggestion",Ms="ApplyImageSuggestion",Zd="ShowCommandPalette",Jd=t=>({[As]:e=>{t.dispatch(Ta(e.state)),t.dispatch(he({contentType:e.contentType,suggestion:e.suggestion}))},[Zd]:e=>{t.dispatch(Z(e.isOpen)),e.page&&t.dispatch(q(e.page))},[gt]:e=>{t.dispatch(Ua(e))},[Ls]:()=>{t.dispatch(je())},[Ms]:e=>{t.dispatch(An({suggestion:e.suggestion}))},[Se]:e=>{t.dispatch(oe({...e,eventMetrics:{inputType:"mouse"},replace:"selection"})),t.dispatch(Ae())}}),Va=Jd;import{jsx as ja}from"react/jsx-runtime";var tm=()=>{var g;let[t,e]=Yd(!1),n=Os(Ea),o=Os(_a),s=Os(pt),r=em(),i=Y(),a=E(Rs),l=()=>{n!==null&&t?window.confirm(a("warning"))&&c():c()},c=()=>{r(ks()),r(dt(!0)),r(V.actions.reset())},u=(f,x)=>{r(ks()),r(dt(!0)),i.send(Se,{text:f,suggestion:x})};if(n===null||o===null)return null;let d=(g=s[o])==null?void 0:g.suggestions.indexOf(n),p=d===0||d===null?void 0:()=>r(he({contentType:o,suggestion:s[o].suggestions[d-1]})),m=d===s[o].suggestions.length-1||d===null?void 0:()=>r(he({contentType:o,suggestion:s[o].suggestions[d+1]}));return ja(tt,{autoFocus:!0,isOpen:d!==null,onClose:l,onBack:l,contentAriaLabel:a("editContentLabel"),overlayAriaLabel:a("overlayLabel"),children:ja(ao,{onTouched:e,onDismiss:c,onUse:f=>u(f,n),suggestion:n,onNext:m,onPrevious:p})})},za=tm;import{useSelector as Qa}from"react-redux";import Ds from"classnames";import{useCallback as $a,useEffect as am,useMemo as lm,useState as Hs}from"react";import{useDispatch as cm,useSelector as um}from"react-redux";import nm from"classnames";var Wa={root:"_root_1ukx5_1"};import{jsx as sm}from"react/jsx-runtime";var om=({className:t,value:e,...n})=>{let o=y("TextInput",Wa);return sm("input",{className:nm(t,o.root),type:"text",value:e,...n})},$t=om;var Ns={};B(Ns,{enUS:()=>rm,nlNL:()=>im});var rm={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"}]},im={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 Ga={root:"_root_1edpl_1",anchorButton:"_anchorButton_1edpl_5",errorMessage:"_errorMessage_1edpl_19",title:"_title_1edpl_25",subtitle:"_subtitle_1edpl_31",text:"_text_1edpl_38",input:"_input_1edpl_43",actions:"_actions_1edpl_48",button:"_button_1edpl_55",primaryButton:"_primaryButton_1edpl_70"};import{jsx as z,jsxs as uo}from"react/jsx-runtime";var pm=t=>{try{let e=new URL(t);return new URLSearchParams(e.search).get("token")||void 0}catch{return t}},dm=({agentEmail:t,isOpen:e,origin:n="",onSuccess:o,onDismiss:s})=>{let r=E(Ns),i=y("LoginTokenDialog",Ga),a=um(Ha),l=cm(),c=T("productName"),[u,d]=Hs(t||""),[p,m]=Hs(0),[g,f]=Hs(""),x=$a(async C=>{C.preventDefault(),l(Ba({email:u})),m(1)},[n,u]),b=()=>{f(""),m(0)},h=$a(async C=>{C.preventDefault();let P=pm(C.target.elements.token.value);if(!P){f(r("verifyCodeError",{login:v}));return}l(Gt({token:P}))},[n]),v=lm(()=>C=>z("button",{type:"button","data-testid":"login-token-dialog-back-button",className:i.anchorButton,onClick:b,children:C},"back-button"),[]);return am(()=>{a==="error"&&f(r("verifyCodeError",{login:v})),a==="done"&&o()},[a]),z(tt,{autoFocus:!0,isOpen:e,contentAriaLabel:r("promptTitle",{productName:c}),overlayAriaLabel:r("promptTitle",{productName:c}),onClose:s,onBack:s,children:uo("div",{className:i.root,children:[z("h1",{className:i.title,children:r("promptTitle",{productName:c})}),p===0&&uo("form",{onSubmit:x,children:[z("h2",{className:i.subtitle,children:r("requestCodeTitle")}),z("p",{className:i.text,children:r("requestCodeBody",{productName:c})}),z($t,{className:i.input,name:"email",placeholder:r("requestCodeInputPlaceholder"),value:u,onChange:C=>d(C.target.value)}),z("div",{className:i.actions,children:z("button",{type:"submit",className:Ds(i.button,i.primaryButton),children:r("requestCodeSubmitLabel")})})]}),p===1&&uo("form",{onSubmit:h,children:[z("h2",{className:i.subtitle,children:r("verifyCodeTitle")}),z("p",{className:i.text,children:r("verifyCodeBody")}),z($t,{className:i.input,name:"token",placeholder:r("verifyCodeInputPlaceholder"),disabled:["loading","done"].includes(a)}),g&&z("div",{className:i.errorMessage,children:g}),uo("div",{className:i.actions,children:[z("button",{type:"button",className:Ds(i.button),onClick:b,children:r("back")}),z("button",{type:"submit",className:Ds(i.button,i.primaryButton),disabled:["loading","done"].includes(a),children:r("verifyCodeSubmitLabel")})]})]})]})})},Xa=dm;import{jsx as gm}from"react/jsx-runtime";var mm=()=>{let t=Qa(Fa),e=Qa($i),n=T("adminUrl"),o=Y(),s=()=>o.send(gt,!1),r=()=>{o.send(gt,!1),o.send(Ls)};return gm(Xa,{isOpen:t,agentEmail:e==null?void 0:e.agentEmail,origin:n,onDismiss:s,onSuccess:r})},Za=mm;import rg from"lodash.debounce";import{useCallback as js,useEffect as wl,useState as Yt}from"react";import{useDispatch as ig,useSelector as St}from"react-redux";import{createAsyncThunk as fm,createSlice as hm}from"@reduxjs/toolkit";var ym={data:null,fetchState:"idle"},Ja=t=>t.contentTypes.data,Xt=fm("contentTypes/getContentTypes",async(t,e)=>e.extra.deepdeskAPI.getContentTypes()),Sm=hm({name:"contentTypes",initialState:ym,reducers:{},extraReducers:t=>{t.addCase(Xt.pending,e=>{e.fetchState="loading"}).addCase(Xt.rejected,e=>{e.fetchState="error"}).addCase(Xt.fulfilled,(e,n)=>{e.fetchState="done",e.data=n.payload})}}),Ya=Sm.reducer;function Qt(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()}import{useEffect as vm}from"react";function el(t,e){vm(()=>{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)}},[])}import{useEffect as sl,useRef as _m}from"react";import{useSelector as Pm,useDispatch as km}from"react-redux";import{createAsyncThunk as xm,createSlice as Cm}from"@reduxjs/toolkit";var tl={data:null,fetchState:"idle"},po=t=>{var r;let e=[],{visitorName:n}=t.info.visitorInfo??{},{agentName:o,agentNickname:s}=t.info.agentInfo??{};return o&&o!==n&&e.push(o),s&&s!==n&&e.push(s),((r=t.entities.data)==null?void 0:r.filter(i=>!e.includes(i.text)))??null},re=xm("entities/getEntities",async(t,e)=>{let{deepdeskAPI:n,dynamicThunkObject:o}=e.extra;if(!o.conversationQuery)return Promise.resolve([]);let s=o.conversationQuery,r=await s();return r.length===0?Promise.resolve([]):n.getEntities(r)}),Tm=t=>t.filter((e,n)=>n===t.findIndex(o=>o.text===e.text)),wm=Cm({name:"entities",initialState:tl,reducers:{},extraReducers:t=>{t.addCase(re.pending,e=>{e.fetchState="loading"}).addCase(re.rejected,e=>{e.fetchState="error"}).addCase(re.fulfilled,(e,n)=>{e.fetchState="done",e.data=Tm(e.data?[...e.data,...n.payload]:n.payload)}).addCase(R,()=>tl)}}),nl=wm.reducer;var Fs={};B(Fs,{enUS:()=>bm,nlNL:()=>Em});var bm={noResults:[{type:0,value:"No entities have been found"}],copy:[{type:0,value:"Copy"}],use:[{type:0,value:"Use"}]},Em={noResults:[{type:0,value:"Er zijn geen entiteiten gevonden"}],copy:[{type:0,value:"Kopieer"}],use:[{type:0,value:"Gebruik"}]};var ol={root:"_root_17kae_1",empty:"_empty_17kae_5"};import{jsx as mo,jsxs as Im}from"react/jsx-runtime";var Rm=({onCopy:t,onUse:e})=>{let n=_m(null),o=y("EntitiesList",ol),s=E(Fs),r=Pm(po),i=km();return sl(()=>{i(re())},[]),sl(()=>{n.current&&n.current.focus()},[n]),Im("div",{className:o.root,ref:n,tabIndex:-1,children:[r&&r.length>0&&mo(I.ActionsBar,{primaryLabel:s("copy"),secondaryLabel:s("use"),onPrimary:(a,l)=>t(r[l]),onSecondary:(a,l)=>e(r[l]),list:r.map(a=>({text:a.text,type:a.label,primaryAction:"copy",secondaryAction:"use"})),children:mo(I.List,{children:r.map((a,l)=>mo(I.ListItem,{index:l,closeOnSelect:!0,onClick:()=>t(a),children:a.text},a.text))},"entities")}),r&&r.length===0&&mo("p",{className:o.empty,children:s("noResults")})]})},rl=Rm;import{Fragment as Dm,useEffect as go,useRef as Hm,useState as Fm}from"react";import{useSelector as pl,useDispatch as Bm}from"react-redux";import{createAsyncThunk as Am,createSlice as Lm}from"@reduxjs/toolkit";var il={data:null,fetchState:"idle"},al=t=>t.summary.data,ll=t=>t.summary.fetchState==="error",ve=Am("summary/getSummary",async(t,e)=>{let{deepdeskAPI:n,dynamicThunkObject:o}=e.extra;if(!o.conversationQuery)return Promise.reject(new Error("setConversationQuery method is not defined"));let s=o.conversationQuery,r=await s();if(r.length===0)return Promise.reject(new Error("No messages are included"));let i=await n.getSummary(r);return{original:r,summary:i}}),Mm=Lm({name:"summary",initialState:il,reducers:{},extraReducers:t=>{t.addCase(ve.pending,e=>{e.data=null,e.fetchState="loading"}).addCase(ve.rejected,e=>{e.data=null,e.fetchState="error"}).addCase(ve.fulfilled,(e,n)=>{e.fetchState="done",n.payload&&(e.data=n.payload.summary)}).addCase(R,()=>il)}}),cl=Mm.reducer;var Bs={};B(Bs,{enUS:()=>Om,nlNL:()=>Nm});var Om={copy:[{type:0,value:"Copy"}],error:[{type:0,value:"Could not generate a summary"}],loading:[{type:0,value:"Generating summary, this may take a few moments."}]},Nm={copy:[{type:0,value:"Kopieer"}],error:[{type:0,value:"Kon helaas geen samenvatting genereren."}],loading:[{type:0,value:"Samenvatting wordt gemaakt, dit kan even duren."}]};var ul={root:"_root_18y7z_1",actions:"_actions_18y7z_5",main:"_main_18y7z_11",textInput:"_textInput_18y7z_15",loading:"_loading_18y7z_34",error:"_error_18y7z_38"};import{jsx as ft,jsxs as Um}from"react/jsx-runtime";var Km=({onCopy:t})=>{let e=Hm(null),n=y("SummaryForm",ul),[o,s]=Fm(""),r=E(Bs),i=pl(al),a=pl(ll),l=Bm(),c=()=>{l(ae({name:"summary copied to clipboard",data:{originalText:i,finalText:o},options:{includeConversationData:!0}})),t(o)},u=()=>{let d=document.getSelection();d&&l(ae({name:"summary copied to clipboard",data:{originalText:i,finalText:d==null?void 0:d.toString()},options:{includeConversationData:!0}}))};return go(()=>{l(ve())},[]),go(()=>{s(i||"")},[i]),go(()=>{e.current&&i&&e.current.focus()},[e,i]),go(()=>{let d=p=>{p.key==="Enter"&&p.shiftKey&&c()};return document.addEventListener("keydown",d),()=>{document.removeEventListener("keydown",d)}},[o]),ft("div",{className:n.root,tabIndex:-1,children:a?ft("p",{className:n.error,children:r("error")}):Um(Dm,{children:[ft("div",{className:n.main,children:ft("textarea",{placeholder:i?void 0:r("loading"),disabled:!i,className:n.textInput,ref:e,value:o,onCopy:u,onChange:d=>s(d.target.value)})}),ft("div",{className:n.actions,children:ft(I.Button,{shortKeys:[8679,8629],onClick:c,children:r("copy")})})]})})},dl=Km;var Ks={};B(Ks,{enUS:()=>qm,nlNL:()=>Vm});var qm={personalCollectionLink:[{type:0,value:"Go to Personal Collection"}],searchPlaceholder:[{type:0,value:"Start typing to search..."}],urlSuggestions:[{type:0,value:"Link 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"}],summaryClipboard:[{type:0,value:"Summarize conversation"}],summaryTitle:[{type:0,value:"Conversation summary"}],knowledgeSearch:[{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?"}]},Vm={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:"Link 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"}],summaryClipboard:[{type:0,value:"Vat gesprek samen"}],summaryTitle:[{type:0,value:"Gesprek samenvatting"}],knowledgeSearch:[{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?"}]};import Zm,{useEffect as vl,useRef as Jm}from"react";import{useDispatch as Ym,useSelector as xl}from"react-redux";var Us={};B(Us,{enUS:()=>jm,nlNL:()=>zm});var jm={use:[{type:0,value:"Use"}],loading:[{type:0,value:"Loading..."}],error:[{type:0,value:"Something went wrong, please try again later."}],anotherQuestion:[{type:0,value:"Send a message..."}],reset:[{type:0,value:"Reset conversation"}]},zm={use:[{type:0,value:"Gebruik"}],loading:[{type:0,value:"Laden..."}],error:[{type:0,value:"Er ging iets mis, probeer het later opnieuw."}],anotherQuestion:[{type:0,value:"Stuur een bericht..."}],reset:[{type:0,value:"Reset gesprek"}]};var ml={root:"_root_cnaw4_1",title:"_title_cnaw4_9",empty:"_empty_cnaw4_20",status:"_status_cnaw4_24",form:"_form_cnaw4_30",input:"_input_cnaw4_43",submit:"_submit_cnaw4_55",question:"_question_cnaw4_63",answer:"_answer_cnaw4_67",alignRight:"_alignRight_cnaw4_73"};import{createAction as Wm,createAsyncThunk as Gm,createSlice as $m}from"@reduxjs/toolkit";var qs={data:[],fetchState:"idle"},gl=t=>{var e;return(e=t.answer)==null?void 0:e.data},fl=t=>t.answer.fetchState,Zt=Wm("answer/resetKnowledgeSearch"),ht=Gm("answer/getAnswer",async(t,e)=>{var i;let{deepdeskAPI:n}=e.extra,o=e.getState().answer.data,s=(i=e.getState().profile.data)==null?void 0:i.code;if(!s)throw new Error("Profile is not defined");let r=await n.knowledgeSearch({promptInstruction:t.promptInstruction,question:t.question},o,s);return{question:t.question,answer:r}}),Xm=$m({name:"answer",initialState:qs,reducers:{},extraReducers:t=>{t.addCase(ht.pending,e=>{e.fetchState="loading"}).addCase(ht.rejected,e=>{e.fetchState="error"}).addCase(ht.fulfilled,(e,n)=>{e.fetchState="done",e.data=[...e.data,n.payload]}).addCase(R,()=>qs).addCase(Zt,()=>qs)}}),hl=Xm.reducer;import{jsx as yl,jsxs as Qm}from"react/jsx-runtime";var Sl=()=>Qm("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 512 512","aria-labelledby":"paperPlaneTitle",children:[yl("title",{id:"paperPlaneTitle",children:"PaperPlane"}),yl("path",{d:"M498.1 5.6c10.1 7 15.4 19.1 13.5 31.2l-64 416c-1.5 9.7-7.4 18.2-16 23s-18.9 5.4-28 1.6L284 427.7l-68.5 74.1c-8.9 9.7-22.9 12.9-35.2 8.1S160 493.2 160 480V396.4c0-4 1.5-7.8 4.2-10.7L331.8 202.8c5.8-6.3 5.6-16-.4-22s-15.7-6.4-22-.7L106 360.8 17.7 316.6C7.1 311.3 .3 300.7 0 288.9s5.9-22.8 16.1-28.7l448-256c10.7-6.1 23.9-5.5 34 1.4z"})]});import{jsx as xe,jsxs as Vs}from"react/jsx-runtime";var eg=({onUse:t,onResetQuestion:e,question:n,promptInstruction:o})=>{let[s,r]=Zm.useState(""),{setSelected:i}=Oe(),a=Jm(null),l=y("EntitiesList",ml),c=E(Us),u=Ym(),d=xl(gl),p=xl(fl),m=async g=>{g.preventDefault(),g.stopPropagation(),s!==""&&u(ht({question:s,promptInstruction:o}))};return vl(()=>{var g;n&&p==="idle"?u(ht({question:n,promptInstruction:o})):(g=a.current)==null||g.focus()},[a,p]),vl(()=>{p==="done"&&(i(0),r(""))},[p,d]),Vs("div",{className:l.root,children:[d.length>0&&xe("div",{className:l.alignRight,children:xe(I.Button,{onClick:e,children:c("reset")})}),Vs(I.ActionsBar,{list:d.map(({answer:g})=>({text:g.answer,type:"answer"})),primaryLabel:c("use"),onPrimary:g=>t(g.text),children:[d.map(({question:g,answer:f},x)=>xe(I.List,{children:xe(I.ListItem,{"data-testid":"knowledge-search-answer",index:x,description:f.answer,closeOnSelect:!0,onClick:()=>t(f.answer),sources:f.sources,styles:{title:l.question,description:l.answer},children:g})},`${f.answer}_${x}`)),p==="loading"&&xe("p",{className:l.status,children:c("loading")}),p==="error"&&xe("p",{className:l.status,children:c("error")}),Vs("form",{className:l.form,onSubmit:m,children:[xe("input",{ref:a,placeholder:c("anotherQuestion"),className:l.input,type:"text",value:s,onFocus:()=>{i(-1)},onChange:g=>{i(-1),r(g.target.value)}}),xe("button",{type:"submit",className:l.submit,children:xe(Sl,{})})]})]})]})},Cl=eg;import{createAsyncThunk as tg,createSlice as ng}from"@reduxjs/toolkit";var og={data:null,fetchState:"idle"},yt=t=>t.profile.data,fo=t=>t.profile.data?t.profile.data.uiConfig.widget.types.filter(e=>e.isActive):[],Jt=tg("profile/getProfile",async(t,e)=>{let{deepdeskAPI:n}=e.extra,s=e.getState().conversation.current;if(!s||!s.profileCode)throw new Error("No conversation of conversation profileCode found");return n.getProfile(s.profileCode)}),sg=ng({name:"profile",initialState:og,reducers:{},extraReducers:t=>{t.addCase(Jt.pending,e=>{e.fetchState="loading"}).addCase(Jt.rejected,e=>{e.fetchState="error"}).addCase(Jt.fulfilled,(e,n)=>{e.fetchState="done",e.data=n.payload})}}),Tl=sg.reducer;import{jsx as W,jsxs as El}from"react/jsx-runtime";var ag=200,lg=5,cg=4,ug=t=>t.reduce((e,n)=>[...e,...n.list.map(o=>({...o,type:n.value}))],[]),bl=(t,e)=>!e||t.toLowerCase().includes(e.toLowerCase()),pg=()=>{let t=ig(),e=Y(),n=E(Ks),[o,s]=Yt(!1),[r,i]=Yt(""),a=St(Yi),l=St(yt),[c,u]=Yt(null),[d,p]=Yt([]),[m,g]=Yt(),f=St(ye),x=T("showSearch"),b=T("showEntitiesCommand"),h=T("showSummaryCommand"),v=T("showKnowledgeSearch"),C=T("showImageSearch"),P=T("searchTriggerKey"),w=St(Ja),N=St(ea),$=St(Ji),k=S=>jo(N.filter(A=>A.type===S.toUpperCase()),S),X=[{value:"PERSONAL",label:n("personalSuggestions"),list:k("PERSONAL"),lineClamp:!1,listOrientation:"vertical",shouldShow:!0},{value:"URL",label:n("urlSuggestions"),list:k("URL"),lineClamp:!1,listOrientation:"vertical",shouldShow:!0},{value:"STICKYMESSAGE",label:n("pinnedMessages"),list:k("STICKYMESSAGE"),lineClamp:!1,listOrientation:"vertical",shouldShow:!0},{value:"IMAGE",label:n("imageSuggestions"),lineClamp:!1,list:k("IMAGE"),listOrientation:"horizontal",shouldShow:C}].filter(S=>S.shouldShow),ie=[{label:n("entitiesClipboard"),onClick:()=>t(q("entities")),shouldShow:b&&bl(n("entitiesClipboard"),r),experimental:!0},{label:n("summaryClipboard"),onClick:()=>t(q("summary")),shouldShow:h&&bl(n("summaryClipboard"),r),experimental:!0},{label:r?`${n("knowledgeSearch")}: ${r}`:n("knowledgeSearch"),onClick:()=>t(q("knowledgeSearch")),shouldShow:v,experimental:!0}].filter(S=>S.shouldShow),te=(w==null?void 0:w.map(S=>({value:S.code.toUpperCase(),label:`${S.name}s`,list:k(S.code.toUpperCase()),listOrientation:"vertical",lineClamp:!0})))||[],gn=js(rg((S,A)=>{t(qe({query:S,type:A,tags:["search-overlay"]}))},ag),[]),fn=ug([...te,...X]),Lu=js((S,A)=>{if(!A)return;let Pe=[...X,...te].find(({value:Ze})=>Ze===A);Pe&&(t(q("edit")),u(S),p(Pe.list))},[t,c,te]),Vo=js((S,A)=>{switch(A.type){case"IMAGE":e.send(Ms,{suggestion:A});break;default:e.send(Se,{text:S,suggestion:A})}t(Z(!1))},[t]),Mu=S=>{Qt(S.text),t(ae({name:"entity copied",data:{entity:S,type:"copy"}})),t(Z(!1))},Ou=S=>{e.send(Se,{text:S,suggestion:{source:"knowledge-search",text:S}}),t(ae({name:"answer used",data:{originalText:S},options:{includeConversationData:!0}})),i(""),t(q("search")),t(Zt()),t(Z(!1))},Nu=S=>{Qt(S),t(Z(!1))},Du=S=>{e.send(Se,{text:S.text,suggestion:{source:"entity",text:S.text}}),t(Z(!1))},Hu=c===null||d.indexOf(c)-1<0?void 0:()=>u(d[d.indexOf(c)-1]),Fu=c===null||d.indexOf(c)===d.length-1?void 0:()=>u(d[d.indexOf(c)+1]);function jo(S,A){return S.slice(0,m?10:A.toLowerCase()==="image"?cg:lg)}function Fr(S,A,Pe){return A.reduce((Ze,hn)=>Pe&&m===Pe?hn.length+Ze:jo(hn,Pe).length+Ze,S)}function Qe(S){return A=>{o?window.confirm(n("warning"))&&(S(A),s(!1)):S(A)}}return wl(()=>{r?gn(r,m):t(so())},[r,m]),wl(()=>{f&&t(Xt())},[f]),el(P,()=>t(Z(!0))),!x||!l?null:El(I,{placeholder:n("searchPlaceholder"),typePlaceholder:n("typePlaceholder"),onChangeSearch:i,onChangeOpen:Qe(S=>t(Z(S))),onChangeType:S=>g(S),onChangePage:Qe(S=>t(q(S))),selectedType:m,search:r,page:a,isOpen:$,types:[...te,...X],children:[W(I.Page,{id:"search",children:El(I.ActionsBar,{list:[...ie.map(S=>({text:S.label,type:"command"})),...fn.map(S=>({text:S.text||S.url||S.message,type:S.type}))],primaryLabel:n("use"),secondaryLabel:n("preview"),onPrimary:({text:S},A)=>Vo(S,fn[A]),onSecondary:(S,A)=>Lu(fn[A],fn[A].type),children:[ie.length>0&&W(I.List,{heading:n("commands"),children:ie.map((S,A)=>W(I.ListItem,{index:Fr(A,[],"commands"),closeOnSelect:!1,onClick:S.onClick,isExperimental:S.experimental,children:S.label},S.label))}),[...te,...X].map(({value:S,label:A,list:Pe,lineClamp:Ze,listOrientation:hn},Bu)=>W(I.List,{heading:A,orientation:hn==="horizontal"?"horizontal":"vertical",children:jo(Pe,S).map((ne,Ku)=>W(I.ListItem,{index:Fr(ie.length+Ku,[...te,...X].slice(0,Bu).map(({list:Uu})=>Uu),S),closeOnSelect:!1,lineClamp:Ze,onClick:()=>Vo(ne.text,ne),description:S!=="IMAGE"?ne.title&&ne.text:void 0,children:S==="IMAGE"?W(I.Image,{title:ne.title||ne.text,src:ne.image}):ne.title||ne.text},`${ne.id}-${ne.text}`))},S))]})}),W(I.Page,{id:"edit",onDismiss:Qe(()=>{t(q("search")),u(null)}),children:c&&W(ao,{suggestion:c,onTouched:s,onDismiss:()=>{s(!1),t(q("search")),u(null),p([])},onNext:Fu,onPrevious:Hu,onUse:S=>{t(q("search")),Vo(S,c),t(Z(!1)),p([]),u(null)}})}),W(I.Page,{id:"entities",title:n("entitiesTitle"),isExperimental:!0,onDismiss:Qe(()=>{t(q("search"))}),children:W(rl,{onUse:Du,onCopy:Mu})}),W(I.Page,{id:"summary",title:n("summaryTitle"),isExperimental:!0,onDismiss:Qe(()=>{t(q("search"))}),children:W(dl,{onCopy:Nu})}),W(I.Page,{id:"knowledgeSearch",title:n("knowledgeSearch"),isExperimental:!0,onDismiss:Qe(()=>{t(Zt()),t(q("search"))}),children:W(Cl,{promptInstruction:l.knowledgeSearchPromptInstruction,question:r,onUse:Ou,onResetQuestion:()=>{t(Zt()),i("")}})})]})},_l=pg;import{jsx as zs,jsxs as gg}from"react/jsx-runtime";var mg=()=>{let t=T("showSearch"),e=T("isEmbedded");return gg(dg,{children:[t&&zs(_l,{}),zs(za,{}),e&&zs(Za,{})]})},Pl=mg;import{Provider as fg}from"react-redux";import{jsx as ho}from"react/jsx-runtime";var hg=({children:t})=>{let n=T("locale").replace("-","");return ho(rs.Provider,{value:n,children:t})},yg=({store:t,customStyles:e={},children:n})=>ho(fg,{store:t,children:ho(hg,{children:ho(Lt.Provider,{value:e,children:n})})}),en=yg;import Ys from"classnames";import{useEffect as Yg,useRef as ef,useState as tf}from"react";import{connect as nf,useDispatch as of,useSelector as xo}from"react-redux";import{useState as Sg}from"react";function kl(t,e){let[n,o]=Sg(()=>{if(typeof window>"u")return e;try{let r=window.localStorage.getItem(t);return r?JSON.parse(r):e}catch(r){return _.error(r),e}});return[n,r=>{try{let i=r instanceof Function?r(n):r;o(i),typeof window<"u"&&window.localStorage.setItem(t,JSON.stringify(i))}catch(i){_.error(i)}}]}function yo(t){let{showMidSentenceSuggestions:e,showSuggestionsBeforePattern:n,showSuggestionsAfterPattern:o}=t.settings,{text:s,selection:r}=t.input.userCommitted;return 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}import Cg from"classnames";import{Fragment as Tg,useCallback as Gs,useMemo as Il}from"react";var Ws={};B(Ws,{enUS:()=>vg,nlNL:()=>xg});var vg={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"}]}]},xg={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 Rl={root:"_root_1vfca_1",anchor:"_anchor_1vfca_6",anchorButton:"_anchorButton_1vfca_11"};import{jsx as So,jsxs as Al}from"react/jsx-runtime";var $s=(t,e,n)=>o=>So("button",{className:t.anchorButton,type:"button",value:e,onClick:n,children:o},e),wg=({className:t,loginUrl:e,isEmbedded:n,onSnooze:o})=>{let s=E(Ws),r=Y(),i=y("Login",Rl),a=T("productName"),l=Gs(f=>{f.preventDefault(),o&&o(parseInt(f.target.value,10))},[]),c=Gs(f=>{f.preventDefault(),r.send(gt,!0)},[e]),u=Il(()=>f=>So("a",{href:e,className:i.anchor,target:"_blank",rel:"noreferrer",children:f},"login"),[e]),d=Gs(f=>So("button",{type:"button",className:i.anchorButton,onClick:c,children:f},"prompt"),[c]),{min:p,hour:m,day:g}=Il(()=>({min:$s(i,60*10,l),hour:$s(i,60*60,l),day:$s(i,60*60*12,l)}),[]);return Al("div",{className:Cg(t,i.root),children:[s("loginPlease",{login:n?d:u,productName:a}),o&&Al(Tg,{children:[So("br",{}),s("snooze",{min:p,hour:m,day:g})]})]})},vo=wg;import{useDispatch as bg}from"react-redux";var Ll={root:"_root_1g8fi_1",text:"_text_1g8fi_19"};import{jsx as Ml,jsxs as _g}from"react/jsx-runtime";var Eg=({title:t})=>{let e=y("SearchTrigger",Ll),n=bg();return _g("button",{type:"button",className:e.root,onClick:()=>n(Z(!0)),children:[Ml(ct,{}),Ml("span",{className:e.text,children:t})]})},Ol=Eg;import Pg from"classnames";var Nl={root:"_root_fp74r_1",isWithDivider:"_isWithDivider_fp74r_9"};import{jsx as Rg}from"react/jsx-runtime";var kg=({withDivider:t,children:e})=>{let n=y("SuggestionList",Nl);return Rg("div",{className:Pg(n.root,{[n.isWithDivider]:t}),children:e})},Ce=kg;import{Fragment as Gg}from"react";import{Interweave as Hg}from"interweave";import{useEffect as Fg,useMemo as Bg,useRef as Kg}from"react";import{useDispatch as Ug,useSelector as qg}from"react-redux";import{useEffect as Ig}from"react";function Dl(t,e,n){Ig(()=>{let o=t.current;return o?(o.addEventListener(e,n),()=>{o.removeEventListener(e,n)}):()=>{}},[t,e,n])}var Ag=/[.*+?^${}()|[\]\\]/g,Lg=/[^0-9A-Za-zÀ-ÖØ-öø-ÿ](?=[0-9A-Za-zÀ-ÖØ-öø-ÿ]*$)/;function Mg(t){return t.replace(Ag,"\\$&")}function Og(t,e){let n=t.split("").findIndex((o,s)=>o!==e[s]);return n>-1?n:Math.min(t.length,e.length)}function Xs(t){return t.search(Lg)}function Hl(t,e=[]){let n=t;return e.forEach(o=>{if(!o)return;let s=new RegExp(`\\b(${Mg(o)})\\b`,"gi");n=n.replace(s,"<strong>$1</strong>")}),n}function Fl(t){return t.replace(Je,'<mark data-type="placeholder">$1</mark>')}function tn(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}function Ng(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 Qs(t,e,n={}){if(e){let o=Og(e.toLowerCase(),t.toLowerCase()),s=tn(t.substring(o,t.length));if(n.stripAgentPart){let l=t.substring(0,o),c=Xs(l);return`<span style="opacity: 0.5">${l.substring(c+1)}</span>${s}`}let i=e.split(Br).length>3||e.length>30?Ng(e.trim(),o):0;return`${`${i>0?"\u2026":""}${tn(t.substring(i,o))}`}<strong>${s}</strong>`}return t}var Bl={badge:"_badge_8rv7b_1",formattedText:"_formattedText_8rv7b_5"};import{jsx as Kl}from"react/jsx-runtime";var Vg=["search","personal-collection-search","studio-search"];function jg(t,e,n,o={}){let s="";return Vg.includes(e)?s=Hl(Qs(t,n,{stripAgentPart:!0}),o.searchKeywords??[n]):s=Qs(t,n,o),o.placeholders===!0&&(s=Fl(s)),s}var zg=()=>{},Wg=({index:t,selected:e,suggestion:n})=>{let o=T("inlineSuggestions"),s=qg(et),r=Ug(),i=y("TextSuggestion",Bl),a=Kg(null);Fg(()=>{let c=setTimeout(()=>{r(Yr({text:n.text,suggestion:n}))},500);return()=>{clearTimeout(c)}},[n]),Dl(a,"click",()=>{r(Ln(t)),r(oe({suggestion:n,text:n.text,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"}))});let l=Bg(()=>jg(n.text,n.source,s,{stripAgentPart:o,placeholders:!0,searchKeywords:n.searchKeywords}),[o,n.text,n.source,s,n.searchKeywords]);return n.source==="gpt"?null:Kl(O,{ref:a,as:"button",selected:e,onClick:zg,children:Kl(Hg,{containerTagName:"div",noWrap:!1,tagName:"span",className:i.formattedText,content:l})})},Ul=Wg;import{jsx as ql}from"react/jsx-runtime";var $g=({suggestions:t,selectedIndex:e})=>ql(Gg,{children:t.slice().map((n,o)=>ql(Ul,{index:o,selected:o===e,suggestion:n},`${n.text}-${n.source}`)).reverse()}),Vl=$g;import Xg from"classnames";var jl={root:"_root_1wpmq_1",isCollapsed:"_isCollapsed_1wpmq_17"};import{jsx as Zs}from"react/jsx-runtime";var Qg=({className:t,isCollapsed:e,title:n,onClick:o})=>{let s=y("ToggleButton",jl);return Zs("button",{type:"button",className:Xg(s.root,t,{[s.isCollapsed]:e}),onClick:o,title:n,children:Zs("svg",{width:"14",height:"8",viewBox:"-2.5 -5 75 60",preserveAspectRatio:"none",children:Zs("path",{d:"M0,0 l35,50 l35,-50",fill:"none",stroke:"grey",strokeLinecap:"round",strokeWidth:"6"})})})},vt=Qg;var Js={};B(Js,{enUS:()=>Zg,nlNL:()=>Jg});var Zg={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"}]},Jg={arrowHint:[{type:0,value:"Tip: Selecteer suggesties met pijltoetsen"}],searchHintWindows:[{type:0,value:"Druk CTRL+"},{type:1,value:"searchTriggerKey"},{type:0,value:" om te zoeken"}],searchHintMac:[{type:0,value:"Druk CMD+"},{type:1,value:"searchTriggerKey"},{type:0,value:" om te zoeken"}],open:[{type:0,value:"Open "},{type:1,value:"productName"}],collapse:[{type:0,value:"Sluiten"}],search:[{type:0,value:"Zoeken"}]};var zl={root:"_root_4kcme_1",isInline:"_isInline_4kcme_14",toggleButton:"_toggleButton_4kcme_18",toggleButtonWrapper:"_toggleButtonWrapper_4kcme_22",toggleButtonWrapperHidden:"_toggleButtonWrapperHidden_4kcme_29",isCollapsed:"_isCollapsed_4kcme_33",collapsible:"_collapsible_4kcme_33",hints:"_hints_4kcme_41",hintsHidden:"_hintsHidden_4kcme_48",triggers:"_triggers_4kcme_53",triggersRight:"_triggersRight_4kcme_68"};import{jsx as F,jsxs as nn}from"react/jsx-runtime";var sf=({inline:t=!1,textSuggestions:e,selectedIndex:n})=>{let o=y("SuggestionsOverlay",zl),s=E(Js),r=T("inlineSuggestions"),i=xo(yo),a=$r(),l=of(),c=ef(null),u=T("searchTriggerKey"),d=T("productName"),p=xo(Ra),m=xo(ye),g=xo(xn),[f,x]=tf(null),b=T("showSearch"),h=T("showTextSuggestions"),v=T("adminUrl"),C=T("isEmbedded"),[P,w]=kl("dd-snooze-until-ms",0),N=p||P>Date.now(),$=e.filter(ie=>ie.source!=="gpt").length,k=()=>{N&&w(0),l(La(!N))},X=ie=>{let te=Date.now()+ie*1e3;w(te),_.info(`Snooze until: ${new Date(te)}`),l(mt({collapse:!0}))};return Yg(()=>{$===0&&x(null)},[e,$]),rt(()=>{l(mt({collapse:!0,skipWhenInputFocus:!0}))}),r!==t||m===null||g===!1?null:m===!1?nn("div",{ref:c,className:Ys(o.root,{[o.isCollapsed]:N,[o.isInline]:t}),"data-inline":t,children:[!N&&nn("div",{className:o.triggers,children:[F("div",{style:{flex:1}}),F("div",{className:o.triggersRight,children:F(vt,{className:o.toggleButton,title:s("collapse"),onClick:k,isCollapsed:!1})})]}),F("div",{className:o.toggleButtonWrapper,children:F(vt,{className:o.toggleButton,title:s("open",{productName:d}),onClick:k,isCollapsed:!0})}),F("div",{className:o.collapsible,children:F(vo,{loginUrl:v,isEmbedded:C,onSnooze:X})})]}):!a||!i?null:nn("div",{ref:c,className:Ys(o.root,{[o.isCollapsed]:N,[o.isInline]:t}),"data-inline":t,children:[!N&&nn("div",{className:o.triggers,children:[F("div",{style:{flex:1},children:b&&F("div",{style:{display:"inline-block"},onFocus:()=>{},onMouseOver:()=>x(s(no()?"searchHintMac":"searchHintWindows",{searchTriggerKey:u.toUpperCase()})),onMouseLeave:()=>x(null),children:F(Ol,{title:s("search")})})}),nn("div",{className:o.triggersRight,onFocus:()=>{},children:[F("div",{className:Ys(!f&&o.hintsHidden,o.hints),children:f}),F(vt,{className:o.toggleButton,title:s("collapse"),onClick:k,isCollapsed:!1})]})]}),F("div",{className:o.toggleButtonWrapper,children:F(vt,{className:o.toggleButton,title:s("open",{productName:d}),onClick:k,isCollapsed:!0})}),$>0&&h&&F("div",{className:o.collapsible,onFocus:()=>{},children:F(Ce,{children:F(Vl,{suggestions:e,selectedIndex:n})})})]})},rf=({input:t})=>({selectedIndex:t.selectedSuggestionIndex,textSuggestions:t.textSuggestions}),Co=nf(rf)(sf);import gr from"classnames";import{Interweave as ch}from"interweave";import{useCallback as uh,useEffect as ph,useMemo as gc,useRef as dh}from"react";import{connect as mh}from"react-redux";import{cloneElement as af}from"react";var lf=["div","span","mark","strong","b","i","u","em"];function er(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(lf.includes(s)){let i=Array.isArray(o.props.children)?o.props.children:[o.props.children];return[...t.slice(0,t.length-1),af(o,{children:er(i,e,n+1)})]}return[...t,...e]}function Te(t){return t.tagName.toLowerCase()==="textarea"}import cf from"classnames";var Wl={root:"_root_1s73o_1",isArrowUp:"_isArrowUp_1s73o_22",isArrowDown:"_isArrowDown_1s73o_23",isTab:"_isTab_1s73o_39",isEsc:"_isEsc_1s73o_44",isEnter:"_isEnter_1s73o_49"};import{jsx as pf}from"react/jsx-runtime";var uf=({className:t,keyCode:e,children:n,...o})=>{let s=y("KeyboardHint",Wl);return pf("span",{className:cf(t,s.root,{[s.isArrowUp]:e==="arrow-up",[s.isArrowDown]:e==="arrow-down",[s.isTab]:e==="tab",[s.isEsc]:e==="esc",[s.isEnter]:e==="enter"}),...o,children:n})},tr=uf;import{Matcher as Ef}from"interweave";import{Fragment as _f,useEffect as Pf}from"react";import Zl from"classnames";import{createRef as Cf,useCallback as or,useMemo as Tf,useRef as wf,useState as bf}from"react";import{useState as df,useLayoutEffect as mf}from"react";var gf=["bottom","height","left","right","top","width"],ff=(t={},e={})=>gf.some(n=>t[n]!==e[n]),we=new Map,Gl,$l=()=>{let t=[],e=[];we.forEach((n,o)=>{if(o instanceof Element&&!o.isConnected){e.push(o);return}let s=o.getBoundingClientRect();ff(s,n.rect)&&(n.rect=s,t.push(n))}),e.forEach(n=>{we.delete(n)}),t.forEach(n=>{n.callbacks.forEach(o=>o(n.rect))}),Gl=window.requestAnimationFrame($l)};function hf(t,e){return{observe(){let n=we.size===0;if(we.has(t)){let o=we.get(t);o.callbacks.push(e),o.rect&&e(o.rect)}else we.set(t,{rect:void 0,hasRectChanged:!1,callbacks:[e]});n&&$l()},unobserve(){let n=we.get(t);if(n){let o=n.callbacks.indexOf(e);o>=0&&n.callbacks.splice(o,1),n.callbacks.length||we.delete(t),we.size||cancelAnimationFrame(Gl)}}}}function nr(t){let[e,n]=df(null);return mf(()=>{if(!t.current)return;let o=hf(t.current,s=>{n(s)});return o.observe(),()=>{o.unobserve()}},[t]),e}import{useContext as yf,useLayoutEffect as Sf,useState as vf}from"react";import{createPortal as xf}from"react-dom";var Xl={root:"_root_1jq08_1"};var Ql=({children:t})=>{let[e,n]=vf(null),o=yf(Lt);return Sf(()=>{let s=document.createElement("div");return Ue(s),s.classList.add(Xl.root),o!=null&&o.rootNode&&s.classList.add(o==null?void 0:o.rootNode),document.body.appendChild(s),n(s),()=>{s.isConnected&&document.body.removeChild(s)}},[]),e?xf(t,e):null};var ue={ref:"_ref_1rcyi_1",root:"_root_1rcyi_7",positionAbove:"_positionAbove_1rcyi_13",positionBelow:"_positionBelow_1rcyi_17",positionLeft:"_positionLeft_1rcyi_21",positionRight:"_positionRight_1rcyi_25",alignStart:"_alignStart_1rcyi_29",alignCenter:"_alignCenter_1rcyi_34",alignEnd:"_alignEnd_1rcyi_40"};import{jsx as sr}from"react/jsx-runtime";var xt=(t=!1)=>{let[e,n]=bf(t),o=or(()=>n(!0),[]),s=or(()=>n(!1),[]),r=or(()=>n(a=>!a),[]),i=wf(null);return{opened:e,open:o,close:s,toggle:r,triggerRef:i}};function rr(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 Ct=({className:t,triggerRef:e,boundaryRef:n=Cf(),position:o="above",align:s="center",children:r,toStyle:i=rr,...a})=>{let l=nr(e),c=nr(n),u=Tf(()=>i(l,c,0),[l,c]);return sr(Ql,{children:sr("div",{className:Zl(ue.ref,{[ue.positionAbove]:o==="above",[ue.positionBelow]:o==="below",[ue.positionLeft]:o==="left",[ue.positionRight]:o==="right",[ue.alignStart]:s==="start",[ue.alignCenter]:s==="center",[ue.alignEnd]:s==="end"}),style:u,...a,role:"dialog",children:sr("div",{className:Zl(t,ue.root),children:r})})})};import{jsx as on,jsxs as Rf}from"react/jsx-runtime";var kf=({inputStyle:t,inputElement:e})=>{let n=y("TabCompletion",J),o=xt(document.activeElement===e);return rt(()=>o.close()),Pf(()=>{let s=()=>o.open();return e.addEventListener("focus",s),()=>{e.removeEventListener("focus",s)}},[]),Rf(_f,{children:[on("mark",{className:J.caret,ref:o.triggerRef}),o.opened&&on(Ct,{className:n.popoverSuggestionsRoot,triggerRef:o.triggerRef,position:"above",align:"start",children:on("div",{style:t,className:n.suggestionsOverlayInputStyles,children:on(Co,{inline:!0})})})]})},To=class extends Ef{charCounter=0;charLength=0;found=!1;onlyAtEnd=!1;props;onBeforeParse(e,n){var o;return this.props=n,this.charCounter=0,this.onlyAtEnd=n.inlineSuggestionsOnlyAtEnd??!1,this.charLength=(Te(n.inputElement)?n.inputElement.value.length:(o=n.inputElement.textContent)==null?void 0:o.length)??0,this.found=!1,e}match(e){if(this.found||!this.props||this.props.selection===null)return null;let[n,o]=this.props.selection;if(n!==o||this.onlyAtEnd&&n!==this.charLength)return null;let s=n,i=s>=this.charCounter&&s<=this.charCounter+e.length?{index:Xs(e.slice(0,s))+1-this.charCounter,length:0,match:"",valid:!0}:null;return i&&(this.found=!0),this.charCounter+=e.length,i??null}replaceWith(e,n){return on(kf,{inputStyle:n.inputStyle,inputElement:n.inputElement},"caret")}asTag(){return"mark"}};import Mf from"classnames";import{Matcher as Of}from"interweave";import{useEffect as Nf,useMemo as Df}from"react";function Jl(t){return t.replace(/[.*+^${}()|[\]\\]/g,"\\$&")}function wo(t){return e=>{t.forEach(n=>{typeof n=="function"?n(e):n!=null&&(n.current=e)})}}function Yl(t){return t!=null}import If from"classnames";import{forwardRef as Af,useRef as Lf}from"react";import{jsx as ec}from"react/jsx-runtime";var bo=Af(({className:t,children:e,...n},o)=>{let s=Lf(null),r=y("TabCompletion",J);return ec("div",{ref:wo([s,o]),className:If(t,r.popoverContentContainer),...n,children:ec("div",{className:r.popoverContent,children:e})})});import{jsx as sn,jsxs as Bf}from"react/jsx-runtime";var Hf=t=>e=>{let n=rr(e);return"top"in n&&(n.width=t.width-(e.left-t.left)-10),n},Ff=({inputElement:t,boundaryRef:e,inputStyle:n,children:o,suggestion:s})=>{let r=y("TabCompletion",J),i=xt(),a=Df(()=>Hf(t.getBoundingClientRect()),[t]),[l,c]=$n(t);return Nf(()=>{c?i.open():i.close()},[c]),Bf("span",{children:[sn("mark",{ref:wo([l,i.triggerRef]),className:Mf(r.matchKeyword,{[r.hover]:c}),"aria-haspopup":"dialog","aria-expanded":i.opened?"true":"false",children:o}),i.opened&&sn(Ct,{className:r.popover,triggerRef:i.triggerRef,boundaryRef:e,position:"below",align:"start",toStyle:a,children:sn(bo,{style:n,children:sn("div",{className:r.hintText,children:s})})})]})},Eo=class extends Of{keywordMatches=[];preparedKeywordMatches=[];usedKeywordMatches=new Set;onBeforeParse(e,n){return n.keywordMatches&&n.keywordMatches!==this.keywordMatches&&(this.preparedKeywordMatches=n.keywordMatches.map(o=>({...o,keywordRegex:new RegExp(`\\b${Jl(o.keyword)}\\b`,"i")})),this.keywordMatches=n.keywordMatches),this.usedKeywordMatches.clear(),e}match(e){let n=this.preparedKeywordMatches.map(s=>{if(this.usedKeywordMatches.has(s))return null;let r=e.match(s.keywordRegex);if(!r)return null;let i=e.charAt(r.index-1),a=e.charAt(r.index+s.keyword.length);return i==="{"&&a==="}"?null:{index:r.index,length:r[0].length,match:r[0],matchString:r[0],suggestion:s.suggestion,preparedKeywordMatch:s,valid:!0}}).filter(Yl);if(n.length===0)return null;let o=n.reduce((s,r)=>r.index<s.index?r:s);return this.usedKeywordMatches.add(o.preparedKeywordMatch),o}replaceWith(e,n){return sn(Ff,{inputElement:n.inputElement,suggestion:n.suggestion,inputStyle:n.inputStyle,boundaryRef:n.boundaryRef,children:e},`keyword_${n.matchString}_${n.key}`)}asTag(){return"mark"}};import mr from"classnames";import{Matcher as nh}from"interweave";import{createRef as oh,forwardRef as sh,useCallback as rh,useEffect as uc,useRef as pc,useState as dc}from"react";import{useDispatch as ih}from"react-redux";import{jsx as tc}from"react/jsx-runtime";var nc=()=>tc("svg",{width:"1.3em",height:"1.3em",focusable:"false","aria-hidden":"true",viewBox:"0 0 24 24","data-testid":"InsertLinkIcon",tabIndex:-1,children:tc("path",{fill:"currentColor",d:"M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76 0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71 0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71 0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76 0 5-2.24 5-5s-2.24-5-5-5z"})});import{useCallback as $f,useEffect as ic,useState as ac}from"react";import{useDispatch as Xf,useSelector as lc}from"react-redux";import Qf from"lodash.debounce";import ar from"classnames";import Uf,{createContext as qf,useContext as lr,useEffect as Vf,useState as jf}from"react";var oc={root:"_root_vr71j_1"};import{jsx as _o,jsxs as Kf}from"react/jsx-runtime";var sc=()=>Kf("svg",{className:oc.root,width:"185",height:"170",viewBox:"0 0 185 170",xmlns:"http://www.w3.org/2000/svg",children:[_o("defs",{children:_o("style",{children:".cls-1 { fill: #b3b3b3; }"})}),_o("title",{children:"Failed loading image"}),_o("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 ir={root:"_root_4e7lf_1",imageWrapper:"_imageWrapper_4e7lf_7",image:"_image_4e7lf_7",content:"_content_4e7lf_24",title:"_title_4e7lf_35",contentIsCropped:"_contentIsCropped_4e7lf_45",lineClamp:"_lineClamp_4e7lf_51"};import{jsx as Tt}from"react/jsx-runtime";var Po=qf(ir),zf=({title:t,src:e})=>{let n=lr(Po),[o,s]=jf(!1);return Vf(()=>{s(!1)},[e]),Tt("div",{className:n.imageWrapper,children:e&&!o?Tt("img",{className:n.image,alt:t,src:e,onError:()=>s(!0)}):Tt(sc,{})})},Wf=({className:t,lineClamp:e=!1,cropText:n=!1,children:o})=>{let s=lr(Po);return Tt("div",{className:ar(s.content,t,{[s.contentIsCropped]:n,[s.lineClamp]:e}),children:o})},Gf=({as:t="h1",cropText:e=!1,className:n,children:o})=>{let s=lr(Po);return Uf.createElement(t,{className:ar(s.title,n,{[s.contentIsCropped]:e})},o)},ko=({children:t})=>{let e=y("Card",ir);return Tt("div",{className:ar(e.root),children:Tt(Po.Provider,{value:e,children:t})})};ko.Image=zf;ko.Content=Wf;ko.Title=Gf;var D=ko;var rc={root:"_root_1muu8_1",content:"_content_1muu8_7"};function Ro(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{return null}}function cr(t){return t.replace("https://www.","").replace("https://","")}import{jsx as ze,jsxs as ur}from"react/jsx-runtime";var Zf=3,Jf=t=>({image:t.image||"",text:`https://${t.text}`,id:t.id,title:t.title}),Yf=({onSelectLink:t,onDismiss:e,placeholder:n,visitUrlText:o,linkCount:s=Zf})=>{let r=y("LinkSearch",rc),[i,a]=ac(""),l=Xf(),c=lc(ha("url")),u=lc(ta("URL",Jf)),[d,p]=ac(u.length-1),m=T("fallbackImage"),g=h=>{let v=h.target;a(v.value)},f=(h,v)=>{h.stopPropagation(),h.preventDefault(),window.open(v,"_blank")},x=h=>{var P;let v=d-1<0?u.length-1:d-1,C=d+1===u.length?0:d+1;h.code==="Escape"&&(a(""),e()),h.code==="ArrowUp"&&p(v),h.code==="ArrowDown"&&p(C),h.code==="Enter"&&t(((P=u[d])==null?void 0:P.text)||i)},b=$f(Qf(h=>{l(qe({query:h,type:"URL",tags:["link-search"]}))},300),[]);return ic(()=>{i&&b(i)},[i]),ic(()=>()=>{l(so())},[]),ur("div",{className:r.root,children:[ze(Ce,{withDivider:!0,children:(i?u:c).slice(0,s).map((h,v)=>ze(O,{selected:d===v,onClick:()=>t(h.text),"data-testid":"linksearch-suggestion",children:ur(D,{children:[ze(D.Image,{src:Ro(h,"small",m||void 0),title:h.title||h.text}),ur(D.Content,{className:r.content,cropText:!0,children:[ze(D.Title,{children:h.title||cr(h.text)}),h.title&&cr(h.text)]}),ze(O.Actions,{children:ze(O.ActionButton,{label:o,onClick:C=>f(C,h.text)})})]})},h.text))}),ze($t,{value:i,onChange:g,autoFocus:!0,placeholder:n,onKeyUp:x})]})},cc=Yf;var pr={};B(pr,{enUS:()=>eh,nlNL:()=>th});var eh={insertLink:[{type:0,value:"Insert link"}],linkInputPlaceholder:[{type:0,value:"Search, type or paste link"}],visitUrl:[{type:0,value:"Visit"}]},th={insertLink:[{type:0,value:"Voeg link toe"}],linkInputPlaceholder:[{type:0,value:"Zoek, typ of plak link"}],visitUrl:[{type:0,value:"Bekijk"}]};import{jsx as pe,jsxs as dr}from"react/jsx-runtime";var ah=sh((t,e)=>{let n=y("TabCompletion",J);return pe("mark",{ref:e,className:mr(n.matchSelection)},"selection-start")}),lh=({startRef:t,boundaryRef:e,inputStyle:n,inputElement:o,children:s})=>{let r=E(pr),i=y("TabCompletion",J),a=pc(null),l=pc(null),[c,u]=dc(null),d=ih(),p=xt(document.activeElement===o),[m]=dc(()=>document.createRange());p.triggerRef.current=m,uc(()=>()=>m.detach(),[]),uc(()=>{let f=t.current,x=a.current;!f||!x||(m.setStart(f,0),m.setEnd(x,0))},[t.current,a.current]),rt(()=>{p.close()});let g=rh(f=>{let x=m.toString(),b=/^http(s?):\/\//.test(f)?f:`https://${f}`;d(Pn({text:`[${x}](${b})`}))},[]);return dr("span",{children:[pe("mark",{ref:a,className:mr(i.matchSelection),"aria-haspopup":"dialog","aria-expanded":p.opened?"true":"false",children:s}),p.opened&&pe(Ct,{className:i.popoverRoot,triggerRef:p.triggerRef,boundaryRef:e,position:"above",align:"start",children:dr(bo,{style:n,ref:l,children:[pe("div",{className:mr(i.selectionOptions,{[i.selectionOptionsIsHidden]:c!==null}),children:dr("button",{type:"button",tabIndex:c===null?-1:void 0,className:i.selectionOptionsButton,onClick:()=>u("insertLink"),children:[pe(nc,{}),pe("span",{children:"\xA0"}),pe("span",{children:r("insertLink")})]})}),c==="insertLink"&&pe(cc,{placeholder:r("linkInputPlaceholder"),visitUrlText:r("visitUrl"),onSelectLink:g,onDismiss:()=>{u(null),p.close()}})]})})]},"selection-end")},Io=class extends nh{charCount=0;foundIndex=0;startRef=null;props;onBeforeParse(e,n){return this.props=n,this.charCount=0,this.startRef=oh(),this.foundIndex=0,e}match(e){if(!this.props||this.props.selection===null||this.foundIndex===2)return null;let[n,o]=this.props.selection;if(n===o)return null;let s=this.foundIndex===0?n:o,r=s>=this.charCount&&s<=this.charCount+e.length?{index:s-this.charCount,length:0,match:"",valid:!0}:null;r&&this.foundIndex++;let i=this.foundIndex===1;return r&&i?this.charCount+=s-this.charCount:this.charCount+=e.length,r?{isStart:i,...r}:null}replaceWith(e,n){return n.isStart?pe(ah,{ref:this.startRef}):pe(lh,{inputElement:n.inputElement,startRef:this.startRef,boundaryRef:n.boundaryRef,inputStyle:n.inputStyle})}asTag(){return"mark"}};var mc={root:"_root_kpc8q_1",agentText:"_agentText_kpc8q_4",tabText:"_tabText_kpc8q_9",hint:"_hint_kpc8q_10",matchSelection:"_matchSelection_kpc8q_14",focus:"_focus_kpc8q_20",resetIndent:"_resetIndent_kpc8q_24",matchKeyword:"_matchKeyword_kpc8q_28",matchPlaceholder:"_matchPlaceholder_kpc8q_29",hover:"_hover_kpc8q_35",hintText:"_hintText_kpc8q_67",popover:"_popover_kpc8q_75",popoverRoot:"_popoverRoot_kpc8q_80",popoverContentContainer:"_popoverContentContainer_kpc8q_84",popoverContent:"_popoverContent_kpc8q_84",selectionOptions:"_selectionOptions_kpc8q_110",selectionOptionsIsHidden:"_selectionOptionsIsHidden_kpc8q_115",selectionOptionsButton:"_selectionOptionsButton_kpc8q_119",caret:"_caret_kpc8q_135",popoverSuggestionsRoot:"_popoverSuggestionsRoot_kpc8q_139",suggestionsOverlayInputStyles:"_suggestionsOverlayInputStyles_kpc8q_144"};import{jsx as rn,jsxs as hh}from"react/jsx-runtime";var gh=({enabled:t,content:e,tabText:n,showTabHint:o,showTabCompletion:s,showStyleSuggestions:r,keywordMatches:i,inputElement:a,source:l})=>{let c=y("TabCompletion",mc),u=T("insertLink"),d=T("showMidSentenceSuggestions"),p=T("inlineSuggestions"),m=Qn(a),g=dh(null);ph(()=>{Te(a)&&m&&Zn(a,m)},[m]);let f=uh(h=>{if(!s||!n)return h;let v=[rn("span",{className:c.resetIndent,children:"\u200B"},"u200B"),rn("span",{className:gr(c.tabText,c.resetIndent),"data-source":l,children:n},"tabText")];return o&&v.push(rn(tr,{className:gr(c.hint,c.resetIndent),keyCode:"tab"},"tabHint")),er(h,v)},[s,n,o]),x=gc(()=>{let h=[];return p&&h.push(new To("inline")),u&&h.push(new Io("selection")),h.push(new st("placeholders")),r&&h.push(new Eo("keywords")),h},[p,u,r]),b=gc(()=>{let h=window.getComputedStyle(a);return{"--dd-color":h.color,"--dd-font-size":h.fontSize,"--dd-font-family":h.fontFamily,"--dd-font-variant":h.fontVariant}},[]);return t?hh("div",{ref:h=>{h!=null&&h.parentElement&&(g.current=h==null?void 0:h.parentElement)},className:gr(c.root,c.agentText),style:b,children:[rn(ch,{tagName:"span",noWrap:!1,containerTagName:"div",disableLineBreaks:Te(a),content:e||"\u200B",onAfterParse:f,matchers:x,selection:m,keywordMatches:i,inputElement:a,inputStyle:b,boundaryRef:g,inlineSuggestionsOnlyAtEnd:!d}),rn("br",{})]}):null},fh=({input:t,ui:e,settings:n,styleSuggestions:o,conversation:s})=>{var f;let{tabCompletionSuggestion:r}=t,i=(r==null?void 0:r.text)||"",a=(r==null?void 0:r.source)||"",l=t.html??tn(t.text),c=i.indexOf(t.text)===0?i.slice(t.text.length):"",{showTabHint:u}=e,{isSupported:d}=s,{showTabCompletion:p,visible:m,showStyleSuggestions:g}=n;return{showTabHint:u,showStyleSuggestions:g,showTabCompletion:p,content:l,tabText:c,source:a,keywordMatches:((f=o.list)==null?void 0:f.keywordMatches)??[],enabled:m&&d!==!1}},fc=mh(fh)(gh);import ly from"classnames";import{useEffect as cy}from"react";import{useDispatch as uy,useSelector as G}from"react-redux";import{createAsyncThunk as an,createSlice as yh}from"@reduxjs/toolkit";var hc={list:[],fetchState:"idle",isInitialRequest:null},Sc=t=>t.autoflows.list||[],yc=t=>e=>{var n;return(n=e.list)==null?void 0:n.find(o=>o.triggerPayload===t)},be=an("autoflows/getAll",async(t,e)=>{let{deepdeskBrokerAPI:n}=e.extra;if(!n)throw new Error("Deepdesk Broker not initialized");return n.getAutoflows(t)}),fr=an("autoflows/start",async(t,e)=>{let{dispatch:n}=e,{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");await o.startAutoflowSession(t),await n(be(t.platformSessionId))}),hr=an("autoflows/stop",async(t,e)=>{let{dispatch:n}=e,{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");await o.stopAutoflowSession(t.platformSessionId),await n(be(t.platformSessionId))}),Sh=yh({name:"autoflows",initialState:hc,reducers:{},extraReducers:t=>{t.addCase(fr.pending,(e,n)=>{let o=yc(n.meta.arg.triggerPayload)(e);o.state="Started",o.isBusy=!0}),t.addCase(hr.pending,(e,n)=>{let o=yc(n.meta.arg.triggerPayload)(e);o.state="Aborted",o.isBusy=!0}),t.addCase(be.pending,e=>{e.isInitialRequest=e.isInitialRequest===null,e.fetchState="loading"}),t.addCase(be.rejected,e=>{e.fetchState="error"}),t.addCase(be.fulfilled,(e,n)=>{e.list=n.payload,e.fetchState="done"}),t.addCase(R,()=>hc)}}),vc=an("autoflows/openStream",(t,e)=>{let{dispatch:n}=e,{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");let s=o.openStream(t);s.on("sessionAborted",()=>{n(be(t))}),s.on("sessionCompleted",()=>{n(be(t))})}),xc=an("autoflows/closeStream",(t,e)=>{let{deepdeskBrokerAPI:n}=e.extra;if(!n)throw new Error("Deepdesk Broker not initialized");n.closeStream(t)}),Cc=Sh.reducer;import{createAsyncThunk as cn,createSlice as vh}from"@reduxjs/toolkit";var Tc={list:[],fetchState:"idle",isInitialRequest:null,sentSuggestions:[],errorSuggestions:[],answeredSuggestions:[]},wc=t=>t.customMessages.list,bc=t=>e=>!!e.customMessages.sentSuggestions.find(n=>n===t),Ec=t=>e=>!!e.customMessages.answeredSuggestions.find(n=>n===t),_c=t=>e=>!!e.customMessages.errorSuggestions.find(n=>n===t),ln=cn("customMessages/getAll",async(t,e)=>{let{deepdeskBrokerAPI:n}=e.extra;if(!n)throw new Error("Deepdesk Broker not initialized");return n.getCustomMessages(t)}),Ao=cn("customMessages/send",async(t,e)=>{let{platformSessionId:n,suggestion:o}=t,{deepdeskBrokerAPI:s}=e.extra;if(!s)throw new Error("Deepdesk Broker not initialized");await s.sendCustomMessage(n,o)}),Lo=cn("customMessages/answer",async(t,e)=>{let{platformSessionId:n,reply:o}=t,{deepdeskBrokerAPI:s}=e.extra;if(!s)throw new Error("Deepdesk Broker not initialized");await s.answerCustomMessage(n,o)}),Pc=vh({name:"customMessages",initialState:Tc,reducers:{onCustomMessage(t,e){Array.isArray(e.payload)?t.list=e.payload:t.list=[e.payload]}},extraReducers:t=>{t.addCase(ln.pending,e=>{e.isInitialRequest=e.isInitialRequest===null,e.fetchState="loading"}).addCase(ln.rejected,e=>{e.fetchState="error"}).addCase(ln.fulfilled,(e,n)=>{e.fetchState="done",e.list=n.payload||[]}).addCase(Ao.pending,(e,n)=>{e.sentSuggestions.push(n.meta.arg.suggestion.text),e.errorSuggestions=e.errorSuggestions.filter(o=>n.meta.arg.suggestion.text!==o)}).addCase(Ao.rejected,(e,n)=>{let o=e.sentSuggestions.indexOf(n.meta.arg.suggestion.text);e.errorSuggestions.push(...e.sentSuggestions.splice(o,1))}).addCase(Lo.pending,(e,n)=>{e.sentSuggestions.push(n.meta.arg.suggestion.text),e.answeredSuggestions.push(n.meta.arg.suggestion.text)}).addCase(Lo.rejected,(e,n)=>{let o=e.answeredSuggestions.indexOf(n.meta.arg.suggestion.text);e.errorSuggestions.push(...e.sentSuggestions.splice(o,1)),e.answeredSuggestions.splice(o,1)}).addCase(R,()=>Tc)}}),kc=cn("customMessages/openStream",(t,e)=>{let{dispatch:n}=e,{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");o.openStream(t).on("customMessageSuggestion",r=>{n(Pc.actions.onCustomMessage(r))})}),Rc=cn("customMessages/closeStream",(t,e)=>{let{deepdeskBrokerAPI:n}=e.extra;if(!n)throw new Error("Deepdesk Broker not initialized");n.closeStream(t)}),Ic=Pc.reducer;import{createAsyncThunk as Ac,createSlice as xh}from"@reduxjs/toolkit";var Ch={jwt:null,accountUrl:null,interval:null},Lc=t=>e=>{let{exchangeToken:{jwt:n,accountUrl:o}}=e;return n&&o?`${o}/apis/admin/session/jwt/?jwt=${n}&redirect=${t}`:null},yr=Ac("exchangeToken/getTemporaryExchangeToken",async(t,e)=>{let{deepdeskAPI:n}=e.extra,o=await n.getTemporaryExchangeToken();return{accountUrl:n.client.baseUrl,jwt:o}}),Sr=Ac("exchangeToken/pollExchangeToken",(t={},e)=>{let{interval:n=1e3*60*30}=t,{dispatch:o}=e;return o(yr()),setInterval(()=>o(yr()),n)}),Mc=xh({name:"exchangeToken",initialState:Ch,reducers:{stopPollExchangeToken(t){t.interval&&clearInterval(t.interval),t.interval=null}},extraReducers:t=>{t.addCase(yr.fulfilled,(e,n)=>{e.jwt=n.payload.jwt,e.accountUrl=n.payload.accountUrl}),t.addCase(Sr.fulfilled,(e,n)=>{e.interval=n.payload})}}),{stopPollExchangeToken:Oc}=Mc.actions,Nc=Mc.reducer;function Dc(t){let{customMessages:e,autoflows:n}=t;return n.fetchState==="loading"&&n.isInitialRequest===!0||e.fetchState==="loading"&&e.isInitialRequest===!0}import{Fragment as Ah}from"react";import{connect as Lh}from"react-redux";import kh from"classnames";import{Fragment as Rh}from"react";import Th from"classnames";var Hc={root:"_root_838fd_1"};import{jsx as bh}from"react/jsx-runtime";var wh=({className:t,children:e})=>{let n=y("Unicode",Hc);return bh("span",{className:Th(t,n.root),children:e})},Fc=wh;var Bc={isDisabled:"_isDisabled_1rmfm_1",buttonStart:"_buttonStart_1rmfm_5",root:"_root_1rmfm_8",buttonStop:"_buttonStop_1rmfm_8",stateBadge:"_stateBadge_1rmfm_19",isCompleted:"_isCompleted_1rmfm_26",isStarted:"_isStarted_1rmfm_30",isAborted:"_isAborted_1rmfm_34"};var vr={};B(vr,{enUS:()=>Eh,nlNL:()=>_h});var Eh={start:[{type:0,value:"Start"}],stop:[{type:0,value:"Stop"}],aborted:[{type:0,value:"Stopped"}],completed:[{type:0,value:"Completed"}],Aborted:[{type:0,value:"Stopped"}],Started:[{type:0,value:"Running"}],Completed:[{type:0,value:"Completed"}]},_h={start:[{type:0,value:"Start"}],stop:[{type:0,value:"Stop"}],aborted:[{type:0,value:"Stopped"}],completed:[{type:0,value:"Completed"}],Aborted:[{type:0,value:"Stopped"}],Started:[{type:0,value:"Running"}],Completed:[{type:0,value:"Completed"}]};import{jsx as We,jsxs as Mo}from"react/jsx-runtime";var Ih=({disabled:t,state:e,displayName:n,description:o,onStartAutoflow:s,onStopAutoflow:r})=>{let i=y("Autoflow",Bc),a=E(vr),l=e==="Started"?"stop":"start",c=l==="start"?"\u25B6":l==="stop"?"\u25FC":"";return Mo(O,{className:kh(i.root,{[i.isDisabled]:t,[i.isCompleted]:e==="Completed",[i.isAborted]:e==="Aborted",[i.isStarted]:e==="Started"}),children:[We(D,{children:Mo(D.Content,{children:[Mo(D.Title,{children:[e&&We("span",{className:i.stateBadge,children:a(e)}),n]}),We("span",{children:o})]})}),We(O.Actions,{fixed:e==="Started",children:We(O.ActionButton,{primary:!0,className:l==="start"?i.buttonStart:i.buttonStop,onClick:e==="Started"?r:s,disabled:t,label:Mo(Rh,{children:[We(Fc,{children:c})," ",We("span",{children:a(l)})]})})})]})},Kc=Ih;import{jsx as Uc}from"react/jsx-runtime";var Mh=(t,e)=>{let n=e.filter(o=>o.state==="Started");return n.length>0?n.indexOf(t)===-1:!1},Oh=({autoflows:t,onStartAutoflow:e,onStopAutoflow:n,platformSessionId:o})=>Uc(Ah,{children:t.map(s=>Uc(Kc,{displayName:s.displayName,description:s.description,disabled:s.isBusy||Mh(s,t),state:s.state,onStartAutoflow:()=>e({platformSessionId:o,triggerPayload:s.triggerPayload}),onStopAutoflow:()=>n({platformSessionId:o,triggerPayload:s.triggerPayload})},s.displayName))}),Nh=({autoflows:t,conversation:e})=>{var n;return{autoflows:t.list,platformSessionId:(n=e.current)==null?void 0:n.sessionId}},Dh={onStartAutoflow:fr,onStopAutoflow:hr},qc=Lh(Nh,Dh)(Oh);import{useEffect as Hh,useState as Fh}from"react";import{useDispatch as Bh}from"react-redux";import zc from"classnames";import{jsx as Vc}from"react/jsx-runtime";var xr=()=>Vc("svg",{width:"1em",height:"1em",viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",children:Vc("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 jc={root:"_root_rjdyr_1",entity:"_entity_rjdyr_10",entityText:"_entityText_rjdyr_46",iconWrapper:"_iconWrapper_rjdyr_53",icon:"_icon_rjdyr_53",iconClicked:"_iconClicked_rjdyr_67"};import{jsx as wt,jsxs as Wc}from"react/jsx-runtime";var Kh=({entities:t})=>{let e=y("EntitiesWidgetList",jc),[n,o]=Fh(void 0),s=Bh(),r=()=>{o(void 0)},i=a=>{t&&(o(t.indexOf(a)),Qt(a.text),s(ae({name:"entity copied",data:{entity:a,type:"copy"}})))};return Hh(()=>{let a=setTimeout(r,500);return()=>{clearTimeout(a)}},[n]),!t||t.length===0?null:wt("div",{className:e.root,"data-testid":"widget-entities-list",children:t.map((a,l)=>Wc("button",{title:a.text,className:e.entity,type:"button",onClick:()=>i(a),children:[wt("span",{className:e.entityText,children:a.text}),Wc("span",{className:e.iconWrapper,children:[wt("span",{className:zc(e.icon),children:wt(xr,{})}),wt("span",{className:zc(e.icon,n===l&&e.iconClicked),children:wt(xr,{})})]})]},a.text))})},Gc=Kh;import Wh from"classnames";import{useCallback as Xc}from"react";import{useDispatch as Gh,useSelector as Oo}from"react-redux";import Uh from"classnames";var $c={root:"_root_4a08n_1"};import{jsx as Vh}from"react/jsx-runtime";var qh=({className:t,children:e,...n})=>{let o=y("Label",$c);return Vh("span",{...n,className:Uh(t,o.root),children:e})},Cr=qh;var un={};B(un,{enUS:()=>jh,nlNL:()=>zh});var jh={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"}],answer:[{type:0,value:"Answer"}]},zh={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"}],answer:[{type:0,value:"Antwoord"}]};var Ee={root:"_root_1e6ej_1",title:"_title_1e6ej_8",isUsed:"_isUsed_1e6ej_13",quickReplies:"_quickReplies_1e6ej_22",quickReply:"_quickReply_1e6ej_29",hasError:"_hasError_1e6ej_39",label:"_label_1e6ej_43",errorIcon:"_errorIcon_1e6ej_48"};import{jsx as Ne,jsxs as No}from"react/jsx-runtime";var $h=({suggestion:t})=>{let e=E(un),n=Gh(),o=Oo(bc(t.text)),s=Oo(Ec(t.text)),r=Oo(_c(t.text)),i=Oo(Sn),{replyOptions:a}=t,l=Xc(u=>{u.preventDefault(),u.stopPropagation(),!(o||!i)&&n(Ao({platformSessionId:i,suggestion:t}))},[t,o,n,i]),c=Xc(u=>{if(u.preventDefault(),u.stopPropagation(),!i||!a)return;let d=parseInt(u.target.dataset.index,10),p=a[d];n(Lo({platformSessionId:i,reply:p,suggestion:t}))},[t,o,n,i]);return No(O,{onClick:l,className:Wh(Ee.root,{[Ee.isUsed]:o,[Ee.hasError]:r}),children:[Ne(D,{children:No(D.Content,{children:[No(D.Title,{className:Ee.title,children:[t.text," ",Ne(Cr,{className:Ee.label,children:"analyse tool"})," ",r&&Ne("span",{className:Ee.errorIcon,role:"img","aria-label":e("sendingError"),title:e("sendingError"),children:"!"})]}),a&&a.length>0&&Ne("ul",{className:Ee.quickReplies,children:a.map(u=>Ne("li",{className:Ee.quickReply,children:u.title},u.title))})]})}),No(O.Actions,{fixed:r||o,children:[a&&a.length>0&&Ne(O.DropdownButton,{label:e("answer"),disabled:s,children:a.map((u,d)=>Ne(O.DropdownItem,{index:d,label:u.title,onClick:c},u.title))}),Ne(O.ActionButton,{primary:!0,disabled:o,onClick:l,label:e(o?"suggestionSent":r?"tryAgain":"sendSuggestion")})]})]})},Qc=$h;import{jsx as Zc}from"react/jsx-runtime";var Jc=()=>Zc("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:Zc("path",{d:"M17 13.5v6H5v-12h6m3-3h6v6m0-6-9 9",stroke:"currentColor",strokeWidth:"1.5",fill:"none",fillRule:"evenodd",strokeLinecap:"round",strokeLinejoin:"round"})});var Yc={root:"_root_jlggj_1",subTitleContainer:"_subTitleContainer_jlggj_5",subtitle:"_subtitle_jlggj_9",suggestions:"_suggestions_jlggj_17"};import{jsx as Tr,jsxs as Qh}from"react/jsx-runtime";var Xh=({title:t,children:e,...n})=>{let o=y("Section",Yc);return Qh("section",{...n,className:o.root,children:[t&&Tr("div",{className:o.subTitleContainer,children:Tr("span",{className:o.subtitle,children:t})}),Tr("div",{className:o.suggestions,children:e})]})},Ge=Xh;import Zh from"classnames";import Jh from"react";var eu={root:"_root_19wxp_1"};import{jsx as ey}from"react/jsx-runtime";var Yh=Jh.forwardRef(({className:t,children:e},n)=>{let o=y("SectionList",eu);return ey("div",{ref:n,className:Zh(o.root,t),children:e})}),wr=Yh;import{useSelector as oy}from"react-redux";import{useCallback as ty}from"react";import{jsx as $e,jsxs as Do}from"react/jsx-runtime";var ny=({suggestion:t,lines:e,onEdit:n,onUse:o})=>{var p;let s=t.text||t.url||t.message,r=ro(s),i=E(un),a=T("showImages"),l=T("fallbackImage"),c=m=>{m.preventDefault(),m.stopPropagation(),o(s)},u=m=>{m.preventDefault(),m.stopPropagation(),n(t)},d=ty(m=>{window.open(r,"_blank"),m.stopPropagation(),m.preventDefault()},[r]);return Do(O,{onClick:c,"data-testid":"edit-suggestion",children:[Do(D,{children:[a&&t.image&&$e(D.Image,{src:Ro(t,"small",l||void 0),title:t.title}),Do(D.Content,{children:[t.title&&$e(D.Title,{children:t.title}),t.searchKeywords&&((p=t.searchKeywords)==null?void 0:p.length)>0&&$e(O.Labels,{labels:t.searchKeywords}),$e(D.Content,{cropText:e==="single",lineClamp:e==="multiple",children:s})]})]}),Do(O.Actions,{children:[r&&$e(O.ActionButton,{onClick:d,label:i("visitUrl")}),$e(O.ActionButton,{primary:!0,onClick:u,label:i("preview")}),$e(O.ActionButton,{primary:!0,onClick:c,label:i("useSuggestion")})]})]})},tu=ny;import{Fragment as ry,jsx as nu}from"react/jsx-runtime";var sy=({contentType:t,lines:e,suggestions:n})=>{let o=Y(),s=oy(pt),r=a=>{o.send(As,{state:s,suggestion:a,contentType:t})},i=(a,l)=>{o.send(Se,{text:a,suggestion:{...l,source:l.source,sourceText:l.text}})};return nu(ry,{children:n.map(a=>nu(tu,{suggestion:a,lines:e,onEdit:l=>r(l),onUse:l=>i(l,a)},a.text||a.url||a.message))})},ou=sy;var br={};B(br,{enUS:()=>iy,nlNL:()=>ay});var iy={waiting:[{type:0,value:"Loading\u2026"}],notSupported:[{type:0,value:"This conversation is not supported"}],noResults:[{type:0,value:"No results found\u2026"}],titleAutoflows:[{type:0,value:"Autoflows"}],titleCustomMessages:[{type:0,value:"Quick replies"}],actions:[{type:0,value:"Shortcuts"}],linkPersonalcollection:[{type:0,value:"Personal Collection"}],linkSummary:[{type:0,value:"Summarize"}],linkKnowledgeSearch:[{type:0,value:"Knowledge Assist"}],linkSearch:[{type:0,value:"Search"}]},ay={waiting:[{type:0,value:"Laden\u2026"}],notSupported:[{type:0,value:"Dit gesprek wordt niet ondersteund"}],noResults:[{type:0,value:"Geen resultaten gevonden\u2026"}],titleAutoflows:[{type:0,value:"Autoflows"}],titleCustomMessages:[{type:0,value:"Quick replies"}],actions:[{type:0,value:"Shortcuts"}],linkPersonalcollection:[{type:0,value:"Personal Collection"}],linkSummary:[{type:0,value:"Vat gesprek samen"}],linkKnowledgeSearch:[{type:0,value:"Knowledge assist"}],linkSearch:[{type:0,value:"Zoeken"}]};var su={root:"_root_oym4o_1",loginText:"_loginText_oym4o_7",stateText:"_stateText_oym4o_8",sectionList:"_sectionList_oym4o_20",links:"_links_oym4o_24",link:"_link_oym4o_24"};import{jsx as ru}from"react/jsx-runtime";var iu=()=>ru("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:ru("path",{d:"M543-340q16.595 0 28.798-12.202Q584-364.405 584-381t-12.202-28.798Q559.595-422 543-422t-28.798 12.202Q502-397.595 502-381t12.202 28.798Q526.405-340 543-340Zm-25-126h47q2-29 8.5-43t32.5-39q27-26 37.5-45.395Q654-612.79 654-639q0-45.882-31.5-74.941Q591-743 540-743q-38 0-68 20.5T428-665l45 19q11-25 27.5-38t39.5-13q29.778 0 48.389 17Q607-663 607-637q0 20-9 35t-32 32q-32 29-40 46.5t-8 57.5ZM260-200q-24 0-42-18t-18-42v-560q0-24 18-42t42-18h560q24 0 42 18t18 42v560q0 24-18 42t-42 18H260Zm0-60h560v-560H260v560ZM140-80q-24 0-42-18t-18-42v-620h60v620h620v60H140Zm120-740v560-560Z"})});import{jsx as au}from"react/jsx-runtime";var lu=()=>au("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:au("path",{d:"M319-250h322v-60H319v60Zm0-170h322v-60H319v60ZM220-80q-24 0-42-18t-18-42v-680q0-24 18-42t42-18h361l219 219v521q0 24-18 42t-42 18H220Zm331-554v-186H220v680h520v-494H551ZM220-820v186-186 680-680Z"})});import{jsx as M,jsxs as bt}from"react/jsx-runtime";var Ho=(t,e)=>{let n=G(ye);cy(()=>n?e.every(o=>!!o)?t():()=>{}:()=>{},[...e,n])},py=()=>{let t=E(br),e=uy(),n=T("isEmbedded"),o=y("Widget",su),s=T("showAutoflows"),r=T("showCustomMessages"),i=T("showPersonalCollectionLink"),a=T("showSummaryCommand"),l=T("showKnowledgeSearch"),c=T("showSearch"),u=G(yt),d=G(fo),p=G(Sc),m=G(po),g=G(wc),f=G(vn),x=G(xn),b=G(ye),h=G(Sn),v=G(Dc),C=G(pt),P=Y(),w=G(Sa),N=G(Lc("/admin/personal-collection")),$=T("adminUrl");return Ho(()=>(e(ln(h)),e(kc(h)),()=>{e(Rc(h))}),[e,x,r,h]),Ho(()=>(e(be(h)),e(vc(h)),()=>{e(xc(h))}),[e,x,s,h]),Ho(()=>{d.forEach(({type:k})=>{e(k==="entities"?re():fe(k))})},[e,x,f,u]),Ho(()=>(e(Sr()),()=>{e(Oc())}),[e,x,i,f]),x===!1?M("div",{className:o.stateText,children:M("div",{children:M("p",{children:t("notSupported")})})},"supported"):b===!1?M("div",{className:o.loginText,children:M("div",{children:M(vo,{isEmbedded:n,loginUrl:$})})},"login"):!u||!h||b===null||w||v?M("div",{className:o.stateText,children:M("div",{children:M("p",{children:t("waiting")})})},"waiting"):M("div",{className:ly(o.root),"data-testid":"widget",children:bt(wr,{className:o.sectionList,children:[M(Ge,{title:t("actions"),children:bt("div",{className:o.links,children:[c&&bt("button",{className:o.link,onClick:()=>P.send("ShowCommandPalette",{isOpen:!0}),children:[M(ct,{}),t("linkSearch")]}),a&&bt("button",{className:o.link,onClick:()=>P.send("ShowCommandPalette",{isOpen:!0,page:"summary"}),children:[M(lu,{}),t("linkSummary")]}),l&&bt("button",{className:o.link,onClick:()=>P.send("ShowCommandPalette",{isOpen:!0,page:"knowledgeSearch"}),children:[M(iu,{}),t("linkKnowledgeSearch")]}),N&&bt("a",{className:o.link,target:"_blank",href:N,rel:"noreferrer",children:[M(Jc,{}),t("linkPersonalcollection")]})]})}),r&&g.length>0&&M(Ge,{"data-testid":"custom-messages",children:M(Ce,{withDivider:!0,children:g.map(k=>M(Qc,{suggestion:k},k.text))})}),s&&p.length>0&&M(Ge,{title:t("titleAutoflows"),"data-testid":"autoflows",children:M(Ce,{withDivider:!0,children:M(qc,{})})}),d.map(({type:k,title:X,amount:ie,lines:te})=>{var gn;switch(k){case"entities":return m&&m.length>0&&M(Ge,{title:X,"data-testid":`type-${k}`,children:M(Gc,{entities:m})},k);default:return((gn=C[k])==null?void 0:gn.fetchState)==="done"&&C[k].suggestions.length>0&&M(Ge,{title:X,"data-testid":`type-${k}`,children:M(Ce,{withDivider:!0,children:M(ou,{lines:te,contentType:k,suggestions:C[k].suggestions.slice(0,ie)||[]})})},k)}})]})})},cu=py;function uu(t){let e=new Range;return e.selectNodeContents(t),e}var pn=/[\u200B-\u200D\uFEFF]/g;function Et(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(l,c){let u=-1,d=/[\u200B-\u200D\uFEFF]/;if(!d.test(l))return c;for(let p=0;p<=l.length;p++)if(d.test(l[p])||u++,u===c)return p;throw new Error("Offset out of range")}function a(l){var c;switch(l.nodeType){case Node.TEXT_NODE:{let u=l.textContent,d=u.replace(pn,""),p=s+d.length,m=e>=s&&e<=p,g=n>=s&&n<=p;if(m){let f=i(u,e-s);f===0&&!g?o.setStartBefore(l):o.setStart(l,f)}g&&(o.setEnd(l,i(u,n-s)),r=!0),s=p;break}case Node.ELEMENT_NODE:{if(l.tagName==="BR"&&(s===e&&o.setStartBefore(l),s++,s===n)){o.setEndAfter(l),r=!0;return}for(let d=0;d<l.childNodes.length&&(a(l.childNodes[d]),!r);d++);let u=(c=l.lastChild)==null?void 0:c.tagName;l.tagName==="DIV"&&u!=="DIV"&&u!=="BR"&&s++;break}default:break}}if(a(t),o.startContainer===document)throw new Error("Offsets out of bound");return o}function Er(t,e){if(!t.contains(e.commonAncestorContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:o,endContainer:s,endOffset:r}=e,i,a,l=0;function c(u){let d=u===n,p=u===s;switch(u.nodeType){case Node.TEXT_NODE:{let m=u.textContent;d&&(i=l+m.substring(0,o).replace(pn,"").length),p&&(a=l+m.substring(0,r).replace(pn,"").length),l+=m.replace(pn,"").length;break}case Node.ELEMENT_NODE:{let{tagName:m}=u,g=u.nextSibling===null;m==="BR"&&!g&&l++;for(let f=0;f<u.childNodes.length&&(d&&f===o&&(i=l),c(u.childNodes[f]),p&&f===r-1&&(a=l),a===void 0);f++);!p&&m==="DIV"&&!g&&l++,p&&(a=l);break}default:break}}if(c(t),a===void 0)throw new Error("Could not determine start and end");return{start:i??a,end:a}}function Fo(t,e){if(!t.contains(e.commonAncestorContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:o,endContainer:s,endOffset:r}=e,i=-1,a="";function l(c){let u=c===n,d=c===s;switch(u&&i++,c.nodeType){case Node.TEXT_NODE:{if(i!==0)return;let p=u?o:0,m=d?r:void 0,g=c.textContent.replace(pn,"");p===0&&m===void 0?a+=g:a+=g.substring(p,m);break}case Node.ELEMENT_NODE:{let{tagName:p}=c,m=c.nextSibling===null;i===0&&p==="BR"&&!m&&(a+=`
4
4
  `);for(let g=u?o:0;g<(d?Math.min(r,c.childNodes.length):c.childNodes.length)&&(l(c.childNodes[g]),i!==1);g++);!d&&i===0&&p==="DIV"&&!m&&(a+=`
5
- `);break}default:break}d&&i++}return l(t),a}var bt=class extends Pe{observer;getText(){let e=new Range;return e.selectNodeContents(this.element),No(this.element,e)}getHTML(){return this.element.innerHTML||""}getSelection(){if(document.activeElement!==this.element)return null;let e=window.getSelection();if(!e||e.rangeCount===0)return null;let n=e.getRangeAt(0);return!n||!this.element.contains(n.commonAncestorContainer)?null:Tr(this.element,n)}getSelectedText(){if(!this.currentSelection)return"";let{start:e,end:n}=this.currentSelection;return No(this.element,Tt(this.element,e,n))}applyChanges(e){var s;if(!this.isActive)return;this.isSettingValue=!0;let n=this.getText(),o=e(this.element);(s=this.observer)==null||s.takeRecords(),Promise.resolve(o).then(()=>{this.currentText=this.getText(),n!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(){super.listen(),this.observer=new MutationObserver(()=>{setTimeout(()=>{this.triggerChange()},0)}),this.observer.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0});let e=this.element.isContentEditable,n=new MutationObserver(()=>{this.element.isContentEditable!==e&&(e=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});n.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>n.disconnect())}dispose(){super.dispose(),this.observer&&this.observer.disconnect()}};var br=class{constructor(e){this.name=e;P.warn("BroadcastChannel is not supported")}postMessage(){}addEventListener(){}removeEventListener(){}close(){}},wr=class{constructor(e,n){this.name=e;this.options=n;this.broadcastChannel=new this.options.broadcastChannelConstructor(e)}broadcastChannel;disposeHandlers=[];onMessage(e){this.broadcastChannel.addEventListener("message",e),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",e)})}postMessage(e){this.broadcastChannel.postMessage(e)}close(){this.disposeHandlers.forEach(e=>e()),this.broadcastChannel.close()}},Er=class{constructor(e,n,o){this.name=e;this.targetOrigin=n;this.options=o;this.iframe=this.createIframe(),document.body.appendChild(this.iframe)}iframe;disposeHandlers=[];createIframe(){let e=`deepdesk-iframe-${this.name}`,n=document.getElementById(e);if(n)return n;let o=document.createElement("iframe"),s=`${this.targetOrigin}/v2/widget/liveengage/channel.html`,r=new URLSearchParams({channel:this.name,host:window.location.origin});return this.options.debug&&r.set("debug","1"),o.style.position="absolute",o.style.left="-999em",o.style.width="0px",o.style.height="0px",o.tabIndex=-1,o.id=e,o.title=`iframe-${this.name}`,o.src=`${s}?${r.toString()}`,o}onMessage(e){window.addEventListener("message",e),this.disposeHandlers.push(()=>{window.removeEventListener("message",e)})}postMessage(e){var n;(n=this.iframe.contentWindow)==null||n.postMessage(e,this.targetOrigin)}close(){var e;this.disposeHandlers.forEach(n=>n()),(e=this.iframe)==null||e.remove()}},_r=class{sessionId;deepdeskUrl;channel;broadcastChannelConstructor;eventMap;isIntegration;constructor(e){this.deepdeskUrl=e.deepdeskUrl,this.broadcastChannelConstructor=e.broadcastChannelConstructor||window.BroadcastChannel||br,this.isIntegration=e.deepdeskUrl!==(e.origin||window.location.origin),this.eventMap=e.eventMap,this.setSessionId("deepdesk-general")}setSessionId(e){if(this.sessionId===e)return;this.cleanup(),P.info("Set sessionId",e),this.sessionId=e,this.channel=this.isIntegration?new Er(e,this.deepdeskUrl,{debug:!0}):new wr(e,{broadcastChannelConstructor:this.broadcastChannelConstructor});let n=o=>{var s,r;o.origin===this.deepdeskUrl&&o.data.type==="event"&&(P.info("Received broadcast event",this.sessionId,o),(r=(s=this.eventMap)[o.data.name])==null||r.call(s,o.data.payload))};this.channel.onMessage(n)}send(e,n){var s,r,i;if(!this.sessionId)return;P.info("broadcast event",{sessionId:this.sessionId,name:e,payload:n});let o={type:"event",name:e,payload:n};(r=(s=this.eventMap)[e])==null||r.call(s,n),(i=this.channel)==null||i.postMessage(o)}cleanup(){var e;(e=this.channel)==null||e.close(),delete this.channel}},iu=_r;var wt=class extends Error{constructor(n,o){super(n);this.body=o}name="CustomError"};var Pr=t=>new Promise(e=>{setTimeout(e,t)});var Et=class extends wt{name="ClientError"},kr=class extends wt{name="ServerError"},Ce=class t{constructor(e="",n={}){this.baseUrl=e;this.options=n;n.fetch&&(this.fetch=n.fetch)}latestRequestByUrl={};csrfToken;fetch=window.fetch.bind(window);static refreshingToken=null;patchFetch(e){this.fetch=e(this.fetch)}setCsrfToken(e){this.csrfToken=e}async request(e,n={}){let o={isStale:!1},s=`${this.baseUrl}${e}`,r=this.fetch,{abortLatest:i=!1,attempts:a=1,retryDelay:l=500,refreshTokenOn401:c=!0,retryOnError:u=w=>w instanceof TypeError,retryOnResponse:d=w=>w.status>=500,version:p="v1",...m}=n,g={credentials:"include",...m,headers:{"Content-Type":"application/json",...m.headers}};n.method!==void 0&&n.method!=="GET"&&this.csrfToken&&(g.headers={...g.headers,"X-CSRFToken":this.csrfToken}),typeof p=="string"&&(g.headers={...g.headers,"X-Deepdesk-API-Version":p});let f=a,T=!1;if(!r)throw new Error("fetch is not set");this.latestRequestByUrl[s]&&i&&(this.latestRequestByUrl[s].isStale=!0),this.latestRequestByUrl[s]=o;let b=async()=>(f--,r(s,g).then(async w=>d(w)&&!o.isStale&&f>0?(await Pr(l),b()):w.status===401&&c===!0&&T===!1?(T=!0,await this.refreshToken(),b()):w).catch(async w=>{if(u(w)&&!o.isStale&&f>0)return await Pr(l),b();throw w})),h=await b(),S=await h.json().catch(()=>null);if(o.isStale)throw new Error("Aborted");if(h.status>=500)throw new kr("Server Error",S);if(h.status===401)throw new Et("Unauthorized",S);if(h.status===403)throw new Et("Forbidden",S);if(h.status===404)throw new Et("Not Found",S);if(h.status>=400)throw new Et("Bad Request",S);return delete this.latestRequestByUrl[s],S}async validateToken(){let{has_valid_access_token:e}=await this.get("/auth/validate");if(!e)return!1;let{is_logged_in:n}=await this.get("/apis/admin/session/validate/",{version:null});return!!n}refreshToken(){return t.refreshingToken||(t.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{t.refreshingToken=null},1e3*60)})),t.refreshingToken}get(e,n){return this.request(e,n)}post(e,n,o){return this.request(e,{method:"POST",body:JSON.stringify(n),...o})}patch(e,n,o){return this.request(e,{method:"PATCH",body:JSON.stringify(n),...o})}put(e,n,o){return this.request(e,{method:"PUT",body:JSON.stringify(n),...o})}delete(e,n){return this.request(e,{method:"DELETE",...n})}};var ay;(e=>{let t;(l=>(l.SEND_MESSAGE="Send Message",l.HANDLING_TIME="Handling Time",l.START_AUTOFLOW="Start Autoflow",l.ABORT_AUTOFLOW="Abort Autoflow",l.ADD_TO_PERSONAL_COLLECTION="Add to personal collection",l.DELETE_FROM_PERSONAL_COLLECTION="Delete from personal collection"))(t=e.EventType||={})})(ay||={});function Do(t){return{...L(t),tags:t.tags}}var Oe=class t{constructor(e,n={}){this.options=n;this.client=new Ce(e,{fetch:n.fetch}),this.account=new URL(e).hostname.split(".").shift(),this.client.patchFetch(o=>async(s,r)=>{let i=await o(s,r);return this.handleDeepdeskVersionHeaders(i),i})}latestReceivedDeepdeskVersions={};client;account;shouldFetchCsrfToken=!0;static exchangeTokenPromise=null;async preflight(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let e=await this.getCsrfToken();this.client.setCsrfToken(e)}return this.options.token?(t.exchangeTokenPromise||(t.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),t.exchangeTokenPromise):Promise.resolve()}async createConversation(e){await this.preflight(),P.info(`Creating conversation for session ${e.sessionId} and agent ${e.agentId}`);let n=await this.client.post("/api/conversations",{...H(e),tags:e.tags},{version:"v2"});return Do(n)}async getProfile(e){let n=await this.client.get(`/apis/admin/accounts/${this.account}/profiles/${e}/`,{version:null});return L(n)}async getContentTypes(){let e=await this.client.get("/apis/admin/content-types/",{version:null});return L(e)}async getPlatformConfig(){let{config:e}=await this.client.get("/platform/config/",{version:null});return L(e)}async checkUserExists(e){let{exists:n}=await this.client.get(`/apis/admin/accounts/${this.account}/users/exists?external_id=${e}`);return n}async getConversationBySessionId(e,n={}){await this.preflight(),P.info(`Getting conversation for session ${e}`);let{attempts:o=1,retryDelay:s=1e3}=n,r=await this.client.get(`/api/conversations/by_session_id/${e}`,{attempts:o,retryDelay:s,retryOnResponse:i=>i.status===404||i.status>=500,version:"v2"});return Do(r)}async isConversationSupported(e,n={}){P.info(`Check if conversation for session ${e} is supported`);let{attempts:o=1,retryDelay:s=1e3}=n;return(await this.client.get(`/api/conversations/by_session_id/${e}/active_profile`,{attempts:o,retryDelay:s,retryOnResponse:i=>i.status===404||i.status>=500,version:"v2"})).has_active_profile}async updateConversation(e,n){let o=H(n);n.tags&&(o.tags=n.tags);let s=await this.client.put(`/api/conversations/${e}`,o,{version:"v2"});return Do(s)}async postMessages(e,n){return(await this.client.post(`/api/conversations/${e}/messages`,n.map(s=>({...H(s),tags:s.tags})),{version:"v2"})).map(s=>Do(s))}async sendEvent(e,n){let{data:o,...s}=n,r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((i,[a,l])=>({...i,[a]:l}),{});return this.client.post("/api/events",H({...r,...s,data:o,name:e}),{version:"v2"})}async sendEventV1(e,n){let o=Object.entries(this.latestReceivedDeepdeskVersions).reduce((s,[r,i])=>({...s,[r]:i}),{});return this.client.post("/api/events",{event:e,data:H({...n,...o})})}async getEntities(e){return(await this.client.post("/api/entities",{messages:e})).entities}async getSummary(e){return(await this.client.post("/api/summary",{conversation:{messages:e}})).summary}async getTemporaryExchangeToken(){return(await this.client.get("/auth/exchange-token",{version:null})).jwt}async exchangeTokenForAccessCookie(e){return this.client.get(`/apis/admin/session/jwt/?jwt=${e}`,{version:null}).catch(n=>{throw P.warn(`Invalid token '${e}'`),n})}async authenticateWithKey(e,n){await this.client.post("/apis/admin/session/api-key/",H(n),{version:null,refreshTokenOn401:!1,headers:{apikey:e}})}async getTextSuggestions(e,n={},o){return o==="sticky-messages"?this.getPinnedMessages(e):(await this.client.post(`/api/conversations/${e}/recommend/${o}`,H(n),{abortLatest:!0})).map(r=>({...L(r),text:r.text||r.url||r.message,source:o,type:o})).filter((r,i,a)=>i===a.findIndex(l=>l.text===r.text))}async isLoggedIn(){return await this.preflight(),this.client.validateToken()}async getAutocompleteSuggestions(e,n){return(await this.client.post(`/api/conversations/${e}/autocomplete`,H(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))}async getPinnedMessages(e){let n=await this.client.get(`/api/conversations/${e}/sticky-messages`,{abortLatest:!0});return L(n).map(o=>({...o,text:o.message,source:"sticky-messages",type:"pinned-message"}))}async getStyleSuggestions(e){let n=await this.client.post("/api/style-suggestions",H(e),{abortLatest:!0});return L(n)}async search(e){let n=await this.client.post(`/api/profiles/${e.profile}/search`,H(e),{version:"v2"});return L(n)}async knowledgeSearch(e,n,o){let s=await this.client.post("/api/knowledge-search/search",H({question:e,profile:o,chatHistory:n.map(r=>({question:r.question,answer:r.answer.answer,timestamp:r.answer.timestamp}))}),{version:"v2"});return L(s)}async requestLoginByEmail(e){let n=await this.client.post("/apis/admin/session/passwordless/request/",{email:e},{version:null});return L(n)}async getCsrfToken(){let{token:e}=await this.client.get("/apis/admin/session/csrf/",{version:null});return e}async verifyLoginToken(e){let n=await this.client.post("/apis/admin/session/passwordless/login/",{token:e},{version:null});return L(n)}handleDeepdeskVersionHeaders(e){e.headers.forEach((n,o)=>{let s=o.toLowerCase(),r=s.match(Fr);if(!n||!r)return;let i=r[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&n&&a!==n&&P.warn(`Overwritten Version header ${s}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[i]=n})}};var ln=class{constructor(e,n){this.url=e;this.options={timeout:25e3,...n}}eventListeners={};options;timeoutTimer;eventSource;proxyEvent(e){this.eventSource.addEventListener(ys(e),n=>{let{data:o}=n;try{let s=JSON.parse(o);this.emit(e,L(s))}catch{P.warn(`Invalid JSON for ${e}: ${o}`)}})}connect(){clearTimeout(this.timeoutTimer);let e=new EventSource(this.url,{withCredentials:!0});this.eventSource=e;let n=!1;e.onopen=()=>{n=!0},e.onerror=()=>{n&&e.readyState===2&&this.connect()},this.timeoutTimer=setTimeout(()=>{e.close(),this.connect()},this.options.timeout),Object.keys(this.eventListeners).forEach(o=>{this.proxyEvent(o)})}disconnect(){var e;clearTimeout(this.timeoutTimer),this.eventListeners={},(e=this.eventSource)==null||e.close()}emit(e,n){this.eventListeners[e]&&this.eventListeners[e].forEach(o=>o(n))}on(e,n){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(n),this.proxyEvent(e),()=>{this.off(e,n)}}off(e,n){let o;this.eventListeners[e]&&(o=this.eventListeners[e].indexOf(n),o>-1&&this.eventListeners[e].splice(o,1))}};var ly;(e=>{let t;(r=>(r.Started="Started",r.Aborted="Aborted",r.Completed="Completed"))(t=e.AutoflowSessionState||={})})(ly||={});var cn=class{constructor(e,n={}){this.apiUrl=e;this.client=new Ce(e,n)}client;streams={};logger=P;async getCustomMessages(e){let n=await this.client.get(`/sessions/${e}/suggestions`);return L(n.suggestions)}async sendCustomMessage(e,n){let o=await this.client.post(`/sessions/${e}/messages`,H(n));return L(o)}async answerCustomMessage(e,n){await this.client.post(`/sessions/${e}/answers`,H(n))}async getAutoflows(e){let n=await this.client.get(`/sessions/${e}/autoflows`);return L(n.autoflows)}async startAutoflowSession(e){let n=await this.client.post("/autoflow-sessions",H(e));return L(n)}async stopAutoflowSession(e){await this.client.delete(`/autoflow-sessions/${e}`)}openStream(e){return this.streams[e]||(this.streams[e]=new ln(`${this.apiUrl}/sessions/${e}/events`),this.streams[e].connect()),this.streams[e]}closeStream(e){this.streams[e]||(this.streams[e].disconnect(),delete this.streams[e])}};import{combineReducers as fy,configureStore as hy}from"@reduxjs/toolkit";import{createSlice as cy}from"@reduxjs/toolkit";var au={startTime:null,stopTime:null},lu=cy({name:"handlingTime",initialState:au,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(k,()=>au)}}),{handlingTimeStart:cu,handlingTimeStop:Ho,handlingTimeReset:uu}=lu.actions,pu=lu.reducer;import{createAsyncThunk as uy,createSlice as py}from"@reduxjs/toolkit";var Rr={list:{keywordMatches:[]},fetchState:"idle",isInitialRequest:null};var $e=uy("styleSuggestions/getAll",async({text:t},e)=>{var i;let{deepdeskAPI:n}=e.extra,o=e.getState(),{showStyleSuggestions:s}=o.settings,r=(i=o.conversation.current)==null?void 0:i.profileCode;if(!s)return Rr.list;if(!r)throw new Error("No current conversation to fetch pinned messages");return n.getStyleSuggestions({profileCode:r,message:t})}),dy=py({name:"styleSuggestions",initialState:Rr,reducers:{},extraReducers:t=>{t.addCase($e.pending,e=>{e.isInitialRequest=e.isInitialRequest===null,e.fetchState="loading"}).addCase($e.rejected,e=>{e.fetchState="error"}).addCase($e.fulfilled,(e,n)=>{e.fetchState="done",be(e.list,n.payload)||(e.list=n.payload)}).addCase(k,()=>Rr)}}),du=dy.reducer;var mu=(t={})=>{let e,n=!0,o={getStyleSuggestions:$e,debounce:500,...t};return s=>r=>i=>{var m;let a=s.getState().input.text,l=r(i),c=s.getState(),{showStyleSuggestions:u}=c.settings;if(!((m=c.conversation.current)==null?void 0:m.id)||!u)return l;let{text:p}=c.input;return p===a&&!n||(clearTimeout(e),p==="")||(e=setTimeout(()=>{n=!1,s.dispatch(o.getStyleSuggestions({text:p}))},t.debounce)),l}};function my(t,e){return t.text===e.text&&t.selection.start===e.selection.start&&t.selection.end===e.selection.end}var gu=(t={})=>{let e={getTextSuggestions:pe,getAutocompleteSuggestions:Ut,debounce:200,check:po,...t},n,o=!0;return s=>r=>i=>{var T;let{input:{userCommitted:a}}=s.getState(),l=r(i),c=s.getState(),{recommendTextSuggestions:u,showTabCompletion:d}=c.settings,p=(T=c.conversation.current)==null?void 0:T.id,m=i.type===oo.toString();if(!p||!u&&!d)return l;let{input:{userCommitted:g}}=c;return my(g,a)&&!o&&!m||(clearTimeout(n),!e.check(c))||(n=setTimeout(()=>{o=!1;let b=Ye(c);b===""?s.dispatch(e.getTextSuggestions("default")):s.dispatch(e.getAutocompleteSuggestions(b))},m?0:e.debounce)),l}};var fu=$e.fulfilled.toString();function gy(t,e){let n=new Set([...e.keywordMatches.map(s=>s.keyword)]),o=[];return n.forEach(s=>{let r=t.keywordMatches.filter(l=>l.keyword===s),i=e.keywordMatches.filter(l=>l.keyword===s),a=i.length-r.length;a<=0||o.push(...i.slice(0,a))}),o}var hu=t=>e=>n=>o=>{var u;if(o.type!==fu){n(o);return}let s=e.getState().styleSuggestions.list;n(o);let r=e.getState(),i=r.styleSuggestions.list,a=(u=r.conversation)==null?void 0:u.current,{agentInfo:l}=r.info;if(s===i)return;let c=gy(s,i);o.type===fu&&c.length>0&&t.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,agentId:l.agentId??(a==null?void 0:a.agentId),agentName:l.agentName??(a==null?void 0:a.agentName),agentEmail:l.agentEmail??(a==null?void 0:a.agentEmail),data:{keywordMatches:c}})};var yy=fy({activeSuggestion:_a,answer:fl,auth:Ua,autoflows:vc,conversation:jr,contentTypes:Za,customMessages:kc,exchangeToken:Mc,entities:tl,handlingTime:pu,info:Qi,input:Wo.reducer,overlayInput:j.reducer,settings:Kr,profile:Oc,search:na,summary:cl,styleSuggestions:du,ui:La,textSuggestions:Ca});function yu(t){return hy({reducer:yy,middleware:e=>[...e({thunk:{extraArgument:{dynamicThunkObject:t.dynamicThunkObject,deepdeskAPI:t.deepdeskAPI,deepdeskBrokerAPI:t.deepdeskBrokerAPI}},serializableCheck:!1}),gu({debounce:200}),mu({debounce:500}),hu(t.deepdeskAPI),...t.middleware?t.middleware:[]],preloadedState:t.preloadedState})}var Sy=t=>{var e;return((e=t==null?void 0:t.type)==null?void 0:e.toLowerCase())??"unknown"},vy=t=>e=>n=>o=>{var a;let s=e.getState(),r=Vo("inlineSuggestions")(s);switch(o.type){case de.toString():{let l=fa(o.payload.contentType)(e.getState()),c=l.indexOf(o.payload.suggestion);t.emit("edit-suggestion",{contentType:o.payload.contentType,index:c,suggestions:l});break}case ee.toString():{let{start:l,end:c}=s.input.selection;t.emit("select-suggestion",{type:Sy(o.payload.suggestion),...o.payload,replace:o.payload.replace==="selection"?{start:l,end:c}:{start:0,end:c}},{mayApplyChanges:!0});break}case Tn.toString():{let{start:l,end:c}=s.input.selection;t.emit("replace",{...o.payload,replace:o.payload.replace==="selection"?{start:l,end:c}:{start:0,end:c}},{mayApplyChanges:!0});break}case kt.toString():{let l=e.getState(),{text:c,selection:u}=l.input.userCommitted;t.emit("reset",{text:c,selectionAfter:u},{mayApplyChanges:!0});break}case _n.toString():t.emit("select-image",o.payload,{mayApplyChanges:!0}),t.sendEvent("Image attached",{conversationId:s.conversation.current.id,data:{path:o.payload.suggestion.image,title:o.payload.suggestion.title}});break;case ne.fulfilled.toString():o.payload.length>0&&t.sendEvent("entities found",{conversationId:s.conversation.current.id,data:{entities:o.payload}});break;case fe.fulfilled.toString():t.sendEvent("conversation summarized",{conversationId:s.conversation.current.id,data:{inputText:JSON.stringify(o.payload.original),summary:o.payload.summary}});break;case ae.toString():t.sendEvent(o.payload.name,{conversationId:((a=o.payload.options)==null?void 0:a.includeConversationData)&&s.conversation.current.id,data:o.payload.data});break;case bn.toString():t.handleKeyDown(o.payload);break;case Pt.toString():t.logSendMessage(o.payload);break;case wn.toString():t.logSendEditSuggestionMessage(o.payload);break;case En.toString():t.handleInputChanged(o.payload);break;default:break}let i=n(o);switch(o.type){case Pt.toString():t.handleAfterSendMessage(o.payload);break;case Vt.toString():t.onUpdateShowTabHint(o.payload);break;case Ho.toString():t.logHandlingTime();break;case ee.toString():{r&&(e.dispatch(Ee([])),e.dispatch(_e()));break}default:break}return i},Su=vy;function Ir(t){return t.toISOString().replace("T"," ").replace("Z","")}function vu(t,e){var s,r,i;let{startTime:n,stopTime:o}=t.handlingTime;if(!n||!o)throw new Error("No startTime and stopTime for handling time metrics");return{conversationId:t.conversation.current.id,clientVersion:e.version,agentId:(s=t.info.agentInfo)==null?void 0:s.agentId,agentName:(r=t.info.agentInfo)==null?void 0:r.agentName,agentEmail:(i=t.info.agentInfo)==null?void 0:i.agentEmail,timeStart:Ir(n),timeStop:Ir(o)}}function Lr(t,e,n){var C,x,N;let{text:o,metrics:{numCharsTyped:s,numCharsPasted:r,numCharsCut:i,numCharsDeleted:a,numPaste:l,agentStartedTypingTimestamp:c,pastes:u,cuts:d,deletions:p,textSuggestions:m,offeredTextSuggestions:g}}=e[t],f=o.length,b=m.reduce((q,{text:D,searchTerm:X})=>q+D.length-(X?X.length:0),0),h=c??Date.now(),S=(Date.now()-h)/1e3,w=s/S;return{conversationId:e.conversation.current.id,source:"agent",text:o,clientVersion:n.version,pastes:u,cuts:d,deletions:p,lenTextTyped:s,lenTextTotal:f,lenTextAssisted:b,lenTextPasted:r,lenTextCut:i,lenTextDeleted:a,timeTotalSeconds:S,charsPerSecond:w,numPastes:l,textSuggestionsV2:m,suggestionsCounters:[{source:"gpt",countOffered:g.filter(q=>q.source==="gpt").length}],agentId:(C=e.info.agentInfo)==null?void 0:C.agentId,agentName:(x=e.info.agentInfo)==null?void 0:x.agentName,agentEmail:(N=e.info.agentInfo)==null?void 0:N.agentEmail}}function xu(t,e){let n=t.closest(e);if(n)return n;let o=t.getRootNode().host;return o instanceof HTMLElement?xu(o,e):null}function Cu(t,e){return xu(t,e)}function Tu(t){return typeof t=="object"&&t!==null&&"name"in t&&"message"in t}function Ar(t){return t instanceof HTMLElement&&(ye(t)||jn(t))}var bu=(t,e)=>({value(){try{let n=sessionStorage.getItem(`dd-${t}`);if(!n)return e;try{return JSON.parse(n)}catch{return e}}catch{return e}},update(n){try{sessionStorage.setItem(`dd-${t}`,JSON.stringify(n))}catch{P.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function xy(t){return t.offsetParent!==null}function wu(t){if(!xy(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 Mr(t,e,n=100){let o=wu(t);e({isVisible:o});let s=setInterval(()=>{let r=wu(t);r!==o&&(o=r,e({isVisible:o}))},n);return()=>{clearTimeout(s)}}import{jsx as Z}from"react/jsx-runtime";var Eu=bu("showTabHint",!0),Bo=class t{static version="10.0.0";static count=0;deepdeskApi;inputMediator=null;version;broadcastEvents;eventListeners={};unmountHandlers=[];widgetRoot=null;dynamicThunkObject={};isMounted=!1;instanceId;shouldRender=!0;store;constructor({deepdeskUrl:e,brokerUrl:n,version:o=t.version||"unknown",locale:s="en-US",token:r,fetch:i}){let a=e.replace(/\/api$/,"");this.deepdeskApi=new Oe(a,{token:r,fetch:i}),this.version=o,this.instanceId=t.count++;let l={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[Su({emit:(c,u,d)=>this.emit(c,u,d),handleAfterSendMessage:c=>this.handleAfterSendMessage(c),handleInputChanged:c=>this.handleInputChanged(c),handleKeyDown:c=>this.handleKeyDown(c),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:c=>this.logSendMessage(c),logSendEditSuggestionMessage:c=>this.logSendEditMessage(c),onUpdateShowTabHint:c=>Eu.update(c),sendEvent:(c,u)=>this.deepdeskApi.sendEvent(c,u)})]};n&&Object.assign(l,{deepdeskBrokerAPI:new cn(n)}),this.store=yu(l),this.broadcastEvents=new iu({debug:!0,deepdeskUrl:a,eventMap:Va(this.store)}),this.store.dispatch(_t),this.store.dispatch(Vt(Eu.value())),this.store.dispatch(_t({locale:s,adminUrl:a}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){return this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex]??null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(P.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(P.warn("Profile has not been loaded (yet)"),!0):(P.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(Ba(null)),this.store.dispatch(je()),new Promise(e=>{let n=this.store.subscribe(()=>{let o=this.store.getState();me(o)&&Oa(o)!=="loading"&&e()});this.unmountHandlers.push(()=>{n()})})}isLoggedIn(){return this.deepdeskApi.isLoggedIn()}async setPlatformAgentId(e){try{if((await this.deepdeskApi.client.get("/apis/admin/session/me/",{version:null})).external_id)return;await this.deepdeskApi.client.request("/apis/admin/session/me/",{method:"PATCH",body:JSON.stringify({external_id:e}),version:null})}catch(n){P.warn("Failed to attach user:",n)}}async isConversationSupported(e,n){return(await this.store.dispatch(jo({sessionId:e,options:n}))).payload}async createConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(hn(e))).payload}async getConversationBySessionId(e,n){return this.hasConversation()&&this.sessionId()!==e&&this.resetConversation(),(await this.store.dispatch(yn({sessionId:e,options:n}))).payload}async upsertConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(zo(e))).payload}async postMessages(e){return(await this.store.dispatch(vn(e))).payload}async updateConversation(e){return(await this.store.dispatch(Sn(e))).payload}resetConversation(){this.store.dispatch(k()),this.dynamicThunkObject.conversationQuery=null}async getSummary(){let e=await this.store.dispatch(fe());if(e.error)throw new Error(e.error.message);return e.payload.summary}configure(e){this.store.dispatch(_t(e))}setVisitorInfo(e){this.store.dispatch(Ji(e))}async setAgentInfo(e){await this.store.dispatch(Ft(e))}async setAgentSettings(e){await this.store.dispatch(vs(e))}async getAgentSettings(){return(await this.store.dispatch(xs())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();let e=[];return this.store.dispatch(oo()),e.push(this.refreshWidgetSuggestions()),Promise.all(e).then(()=>{})}notifyInputChanged(e){this.store.dispatch(En(e))}syncInputHtml(e){this.store.dispatch(oi(e))}notifyKeyDown(e){this.store.dispatch(bn(e))}notifyPaste(e,n){this.store.dispatch(ti({text:e,selectionText:n}))}notifyCut(e){this.store.dispatch(Yr(e))}notifyExternalSuggestion(e){this.store.dispatch(ee(e)),this.store.dispatch(_e())}notifyEditSuggestion(e){this.store.dispatch(va(e.contentType,e.suggestions)),this.store.dispatch(de({contentType:e.contentType,suggestion:typeof e.index=="number"?e.suggestions[e.index]:null}))}handleInputChanged(e){let{overlayCollapsed:n,openOverlayWhenTyping:o}=this.state.ui;n&&o&&this.store.dispatch(pt({collapse:!1})),this.inputMediator&&this.store.dispatch(Gr({text:e,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(Ee([])))}handleKeyDown(e){let{overlayCollapsed:n}=this.state.ui,{textSuggestions:o,selectedSuggestionIndex:s,selection:r}=this.state.input,{inlineSuggestions:i}=this.state.settings,a=o.length>0,l=s!==-1;if(this.store.dispatch(ei(Cn(e))),!(e.key!=="Tab"&&!this.settings.showTextSuggestions))switch(e.key){case"Up":case"ArrowUp":if(n||!a||!r||e.shiftKey)return;this.store.dispatch(Jr()),i||this.stageSelectedSuggestion({inputType:"arrow"}),e.preventDefault();return;case"Down":case"ArrowDown":{if(n||!a||!r||e.shiftKey)return;this.store.dispatch(Zr());let{selectedSuggestionIndex:c}=this.state.input;c===-1?this.store.dispatch(kt()):i||this.stageSelectedSuggestion({inputType:"arrow"}),e.preventDefault();return}case"Esc":case"Escape":{l?(this.store.dispatch(Pn(-1)),this.store.dispatch(kt()),e.preventDefault()):n||(this.store.dispatch(pt({collapse:!0})),this.store.dispatch(Ra(!0)),e.preventDefault());return}case"Tab":{let{userCommitted:c}=this.state.input,u=c.text.substring(0,c.selection.end),{tabCompletionSuggestion:d}=this.state.input;this.store.dispatch(Vt(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):this.settings.showTabCompletion&&d&&d.text.startsWith(u)&&(this.store.dispatch(ee({text:d.text,suggestion:d,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch(_e())),e.preventDefault();break}default:}}handleAfterSendMessage(e){this.emit("send-message",e),this.store.dispatch(ni()),this.store.dispatch(Ee([]))}handlingTimeStart(){this.state.handlingTime.startTime||(P.info("Start handling time"),this.store.dispatch(cu()))}handlingTimeStop(){this.state.handlingTime.startTime&&(P.info("Stop handling time"),this.store.dispatch(Ho()))}logSendMessage(e){let n=Lr("input",this.state,{version:this.version});e&&Object.assign(n,{text:e}),this.deepdeskApi.sendEventV1("Send Message",n),this.emit("send-message-event",n)}logSendEditMessage(e){let n=Lr("overlayInput",this.state,{version:"v2"});e&&Object.assign(n,{text:e}),this.store.dispatch(Xr(this.state.overlayInput.metrics)),this.deepdeskApi.sendEvent("suggestion edited",{data:n})}logHandlingTime(){let e=vu(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",e),this.store.dispatch(uu())}notifySubmit(e={}){this.shouldAbort()||(this.store.dispatch(_e()),this.store.dispatch(Pt(e.text??this.state.input.text)))}stageSelectedSuggestion(e){let n=this.state.input.selectedSuggestionIndex,{textSuggestions:o}=this.state.input;this.store.dispatch(ee({text:o[n].text,suggestion:o[n],eventMetrics:e,replace:"until-selection-end"}))}emit(e,n,o={}){let s=()=>{this.eventListeners[e]&&this.eventListeners[e].forEach(r=>{try{r(n)}catch(i){P.warn(`The following error occurred in deepdeskSDK.on('${e}', handler)`),P.error(i)}})};this.inputMediator&&o.mayApplyChanges?this.inputMediator.applyChanges(s):s()}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}whenConversationLoaded(e){let n=()=>this.loadProfileConfig().then(()=>e());this.hasConversation()&&n();let o=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==o&&(o=this.hasConversation(),o&&n())})}overlayContainerFactory(e,n,o,s){let[r,i]=Nt(o,s);return r.dataset.testid=e,n!=null&&n.rootNode&&r.classList.add(n.rootNode),this.unmountHandlers.push(()=>{Or(r),i(),r.remove()}),r}createContainer(e,n=document.body){let o=window.getComputedStyle(n),s=document.createElement("div");return Ue(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,n.appendChild(s),this.unmountHandlers.push(()=>{Or(s),s.remove()}),s}mount(e,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!Ar(e))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let{customStyles:o={},showStyleSuggestions:s,showTabCompletion:r,showTextSuggestions:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:c,showSuggestionsAfterPattern:u,isEmbedded:d,detectSubmit:p,insertLink:m,inputMediator:g,closestScrollSelector:f,appendOverlayTo:T,inlineSuggestions:b}=n;this.configure({showStyleSuggestions:s,showTabCompletion:r,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:c,showSuggestionsAfterPattern:u,showTextSuggestions:i,insertLink:m,isEmbedded:d,inlineSuggestions:b});let h=f&&Cu(e,f)||void 0,S=this.overlayContainerFactory("deepdesk-tab-completion",o,e,{appendTo:T,closestScrollElement:h,mirrorOverflow:!0,onRemove:()=>this.unmount()}),w=this.overlayContainerFactory("deepdesk-suggestions-overlay",o,h||e,{appendTo:T});n.automaticHandlingTime&&this.setupHandlingTime(e),Fo(Z(Xt,{store:this.store,customStyles:o,children:Z(qt,{broadcastEvents:this.broadcastEvents,children:Z(mc,{inputElement:e})})}),S),Fo(Z(Xt,{store:this.store,customStyles:o,children:Z(qt,{broadcastEvents:this.broadcastEvents,children:Z(ho,{})})}),w),Fo(Z(Xt,{store:this.store,customStyles:o,children:Z(qt,{broadcastEvents:this.broadcastEvents,children:Z(El,{})})}),this.createContainer("deepdesk-overlays")),Ue(e),this.inputMediator=g||(ye(e)?new ke(e):new bt(e)),this.inputMediator.on("change",({plainText:x})=>{this.notifyInputChanged(x)}),this.inputMediator.on("updated",({rawHtml:x})=>{x!=null&&this.syncInputHtml(x)}),this.inputMediator.on("keydown",x=>{this.notifyKeyDown(x)}),this.inputMediator.on("paste",({pastedText:x,selectionText:N})=>{this.notifyPaste(x,N)}),this.inputMediator.on("cut",({selectionText:x})=>{this.notifyCut(x)});let C;this.inputMediator.on("selection",x=>{clearTimeout(C),x===null?C=setTimeout(()=>{x!==null&&this.store.dispatch(Go(x))},500):this.store.dispatch(Go(x))}),this.inputMediator.on("disabled",()=>{var x;(x=this.inputMediator)==null||x.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{p&&this.notifySubmit()}),this.inputMediator.on("blur",()=>this.store.dispatch(ut(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(ut(!0))),this.store.dispatch($r({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.whenConversationLoaded(()=>{var x;this.broadcastEvents.setSessionId((x=this.state.conversation.current)==null?void 0:x.sessionId)}),this.isMounted=!0}unmount(){var e;this.unmountHandlers.forEach(n=>n()),this.unmountHandlers=[],(e=this.inputMediator)==null||e.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(e,n={}){if(this.widgetRoot&&P.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:o,showImages:s,showPersonalCollectionLink:r,isEmbedded:i}=n;this.widgetRoot=e,this.configure({showImages:s,showPersonalCollectionLink:r,isEmbedded:i}),Fo(Z(Xt,{store:this.store,customStyles:o,children:Z(qt,{broadcastEvents:this.broadcastEvents,children:Z(su,{})})}),e),this.whenConversationLoaded(()=>{var a;this.broadcastEvents.setSessionId((a=this.state.conversation.current)==null?void 0:a.sessionId)})}unmountWidget(){this.widgetRoot&&Or(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(e){let n=Mr(e,({isVisible:o})=>{o?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){Tu(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(sn());let e=ko(this.state);e&&this.store.dispatch(_t({showSearch:e.search,showAutoflows:e.autoflows,showCustomMessages:e.customMessages,showImageSearch:e.imageSearch,showEntitiesCommand:e.entitiesCommand,showSummaryCommand:e.summarizer,showKnowledgeSearch:e.knowledgeSearch,recommendTextSuggestions:e.recommendTextSuggestions}))}),this.loadProfileConfigPromise)}async checkForTrialMode(e){try{let{account:n}=await this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(P.info("Trial is active"),!await this.deepdeskApi.checkUserExists(e))throw new Error("User is not in trial");this.shouldRender=!0}catch(n){let{message:o}=n;P.info(o),this.shouldRender=!1}}async refreshWidgetSuggestions(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:e}=this.state.profile.data;if(!e.widget)return;let n=Ro(this.state);try{n.forEach(({type:o})=>{o==="entities"?this.store.dispatch(ne()):this.store.dispatch(pe(o))})}catch(o){this.handleError(o)}}};async function Cy(t,e,n={}){let{value:o}=t,{start:s,end:r}=n.replace??{start:0,end:o.length},i=`${o.slice(0,s)}${e}${o.slice(r)}`,a=n.selectionAfter??{start:s+e.length,end:s+e.length},l=()=>{if(n.setValue)return n.setValue(i);t.value=i};return Promise.resolve(l()).then(()=>{t.selectionStart=a.start,t.selectionEnd=a.end,t.blur(),t.focus()})}async function Ty(t,e,n={}){let o=n.replace?Tt(t,n.replace.start,n.replace.end):ru(t),s,r=()=>{if(n.setRange)return n.setRange(o.cloneRange());o.deleteContents(),s=document.createElement("span"),o.insertNode(s),e.split(`
6
- `).reverse().forEach((i,a)=>{a>0&&o.insertNode(document.createElement("br")),o.insertNode(document.createTextNode(i))}),o.commonAncestorContainer===t&&o.surroundContents(document.createElement("div"))};return Promise.resolve(r()).then(()=>{try{if(n.selectionAfter!==!1){t.focus();let i=n.selectionAfter?Tt(t,n.selectionAfter.start,n.selectionAfter.end):(o.collapse(!1),o),a=window.getSelection();a==null||a.removeAllRanges(),a==null||a.addRange(i)}if(!s)return;s.scrollIntoView&&s.scrollIntoView({block:"nearest",inline:"nearest"})}finally{s&&s.remove()}})}function by(t){return t.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}async function wy(t,e,n){await new Oe(t).authenticateWithKey(e,n)}async function Ey(t){let n=await new Ce(t).get("/platform/config/",{version:null});return L(n)}async function _y(t){let n=await(t.fetch??window.fetch)(t.url),o=await n.blob();return new File([o],t.name,{type:t.mimeType??n.headers.get("Content-Type")??"image/jpeg"})}async function Py(t,e){let n=await _y(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}}export{O as Card,od as Chip,bt as ContentEditableInput,Oe as DeepdeskAPI,Bo as DeepdeskSDK,Pe as InputMediator,Fe as InputType,Qs as KeyboardHint,yr as Label,dn as Locale,Ct as Section,vr as SectionList,He as Sources,A as Suggestion,he as SuggestionList,ke as TextAreaInput,ht as ToggleButton,Py as attachFile,wy as authenticateWithKey,Nt as createOverlayContainer,Tt as createRangeFromOffsets,Jt as escapeHTML,Ey as fetchPlatformConfig,by as formatTextMarkup,Tr as getRangeOffsets,No as getRangeText,Ar as isSupportedInputElement,Ty as updateContentEditable,Cy as updateTextArea,y as useStyles,Mr as waitForElementVisibilityChange};
5
+ `);break}default:break}d&&i++}return l(t),a}var _t=class extends Le{observer;getText(){let e=new Range;return e.selectNodeContents(this.element),Fo(this.element,e)}getHTML(){return this.element.innerHTML||""}getSelection(){if(document.activeElement!==this.element)return null;let e=window.getSelection();if(!e||e.rangeCount===0)return null;let n=e.getRangeAt(0);return!n||!this.element.contains(n.commonAncestorContainer)?null:Er(this.element,n)}getSelectedText(){if(!this.currentSelection)return"";let{start:e,end:n}=this.currentSelection;return Fo(this.element,Et(this.element,e,n))}applyChanges(e){var s;if(!this.isActive)return;this.isSettingValue=!0;let n=this.getText(),o=e(this.element);(s=this.observer)==null||s.takeRecords(),Promise.resolve(o).then(()=>{this.currentText=this.getText(),n!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(){super.listen(),this.observer=new MutationObserver(()=>{setTimeout(()=>{this.triggerChange()},0)}),this.observer.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0});let e=this.element.isContentEditable,n=new MutationObserver(()=>{this.element.isContentEditable!==e&&(e=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});n.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>n.disconnect())}dispose(){super.dispose(),this.observer&&this.observer.disconnect()}};var _r=class{constructor(e){this.name=e;_.warn("BroadcastChannel is not supported")}postMessage(){}addEventListener(){}removeEventListener(){}close(){}},Pr=class{constructor(e,n){this.name=e;this.options=n;this.broadcastChannel=new this.options.broadcastChannelConstructor(e)}broadcastChannel;disposeHandlers=[];onMessage(e){this.broadcastChannel.addEventListener("message",e),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",e)})}postMessage(e){this.broadcastChannel.postMessage(e)}close(){this.disposeHandlers.forEach(e=>e()),this.broadcastChannel.close()}},kr=class{constructor(e,n,o){this.name=e;this.targetOrigin=n;this.options=o;this.iframe=this.createIframe(),document.body.appendChild(this.iframe)}iframe;disposeHandlers=[];createIframe(){let e=`deepdesk-iframe-${this.name}`,n=document.getElementById(e);if(n)return n;let o=document.createElement("iframe"),s=`${this.targetOrigin}/v2/widget/liveengage/channel.html`,r=new URLSearchParams({channel:this.name,host:window.location.origin});return this.options.debug&&r.set("debug","1"),o.style.position="absolute",o.style.left="-999em",o.style.width="0px",o.style.height="0px",o.tabIndex=-1,o.id=e,o.title=`iframe-${this.name}`,o.src=`${s}?${r.toString()}`,o}onMessage(e){window.addEventListener("message",e),this.disposeHandlers.push(()=>{window.removeEventListener("message",e)})}postMessage(e){var n;(n=this.iframe.contentWindow)==null||n.postMessage(e,this.targetOrigin)}close(){var e;this.disposeHandlers.forEach(n=>n()),(e=this.iframe)==null||e.remove()}},Rr=class{sessionId;deepdeskUrl;channel;broadcastChannelConstructor;eventMap;isIntegration;constructor(e){this.deepdeskUrl=e.deepdeskUrl,this.broadcastChannelConstructor=e.broadcastChannelConstructor||window.BroadcastChannel||_r,this.isIntegration=e.deepdeskUrl!==(e.origin||window.location.origin),this.eventMap=e.eventMap,this.setSessionId("deepdesk-general")}setSessionId(e){if(this.sessionId===e)return;this.cleanup(),_.info("Set sessionId",e),this.sessionId=e,this.channel=this.isIntegration?new kr(e,this.deepdeskUrl,{debug:!0}):new Pr(e,{broadcastChannelConstructor:this.broadcastChannelConstructor});let n=o=>{var s,r;o.origin===this.deepdeskUrl&&o.data.type==="event"&&(_.info("Received broadcast event",this.sessionId,o),(r=(s=this.eventMap)[o.data.name])==null||r.call(s,o.data.payload))};this.channel.onMessage(n)}send(e,n){var s,r,i;if(!this.sessionId)return;_.info("broadcast event",{sessionId:this.sessionId,name:e,payload:n});let o={type:"event",name:e,payload:n};(r=(s=this.eventMap)[e])==null||r.call(s,n),(i=this.channel)==null||i.postMessage(o)}cleanup(){var e;(e=this.channel)==null||e.close(),delete this.channel}},pu=Rr;var Pt=class extends Error{constructor(n,o){super(n);this.body=o}name="CustomError"};var Ir=t=>new Promise(e=>{setTimeout(e,t)});var kt=class extends Pt{name="ClientError"},Ar=class extends Pt{name="ServerError"},_e=class t{constructor(e="",n={}){this.baseUrl=e;this.options=n;n.fetch&&(this.fetch=n.fetch)}latestRequestByUrl={};csrfToken;fetch=window.fetch.bind(window);static refreshingToken=null;patchFetch(e){this.fetch=e(this.fetch)}setCsrfToken(e){this.csrfToken=e}async request(e,n={}){let o={isStale:!1},s=`${this.baseUrl}${e}`,r=this.fetch,{abortLatest:i=!1,attempts:a=1,retryDelay:l=500,refreshTokenOn401:c=!0,retryOnError:u=C=>C instanceof TypeError,retryOnResponse:d=C=>C.status>=500,version:p="v1",...m}=n,g={credentials:"include",...m,headers:{"Content-Type":"application/json",...m.headers}};n.method!==void 0&&n.method!=="GET"&&this.csrfToken&&(g.headers={...g.headers,"X-CSRFToken":this.csrfToken}),typeof p=="string"&&(g.headers={...g.headers,"X-Deepdesk-API-Version":p});let f=a,x=!1;if(!r)throw new Error("fetch is not set");this.latestRequestByUrl[s]&&i&&(this.latestRequestByUrl[s].isStale=!0),this.latestRequestByUrl[s]=o;let b=async()=>(f--,r(s,g).then(async C=>d(C)&&!o.isStale&&f>0?(await Ir(l),b()):C.status===401&&c===!0&&x===!1?(x=!0,await this.refreshToken(),b()):C).catch(async C=>{if(u(C)&&!o.isStale&&f>0)return await Ir(l),b();throw C})),h=await b(),v=await h.json().catch(()=>null);if(o.isStale)throw new Error("Aborted");if(h.status>=500)throw new Ar("Server Error",v);if(h.status===401)throw new kt("Unauthorized",v);if(h.status===403)throw new kt("Forbidden",v);if(h.status===404)throw new kt("Not Found",v);if(h.status>=400)throw new kt("Bad Request",v);return delete this.latestRequestByUrl[s],v}async validateToken(){let{has_valid_access_token:e}=await this.get("/auth/validate");if(!e)return!1;let{is_logged_in:n}=await this.get("/apis/admin/session/validate/",{version:null});return!!n}refreshToken(){return t.refreshingToken||(t.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{t.refreshingToken=null},1e3*60)})),t.refreshingToken}get(e,n){return this.request(e,n)}post(e,n,o){return this.request(e,{method:"POST",body:JSON.stringify(n),...o})}patch(e,n,o){return this.request(e,{method:"PATCH",body:JSON.stringify(n),...o})}put(e,n,o){return this.request(e,{method:"PUT",body:JSON.stringify(n),...o})}delete(e,n){return this.request(e,{method:"DELETE",...n})}};var dy;(e=>{let t;(l=>(l.SEND_MESSAGE="Send Message",l.HANDLING_TIME="Handling Time",l.START_AUTOFLOW="Start Autoflow",l.ABORT_AUTOFLOW="Abort Autoflow",l.ADD_TO_PERSONAL_COLLECTION="Add to personal collection",l.DELETE_FROM_PERSONAL_COLLECTION="Delete from personal collection"))(t=e.EventType||={})})(dy||={});function Bo(t){return{...L(t),tags:t.tags}}var De=class t{constructor(e,n={}){this.options=n;this.client=new _e(e,{fetch:n.fetch}),this.client.patchFetch(o=>async(s,r)=>{let i=await o(s,r);return this.handleDeepdeskVersionHeaders(i),i})}latestReceivedDeepdeskVersions={};client;shouldFetchCsrfToken=!0;static exchangeTokenPromise=null;async preflight(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let e=await this.getCsrfToken();this.client.setCsrfToken(e)}return this.options.token?(t.exchangeTokenPromise||(t.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),t.exchangeTokenPromise):Promise.resolve()}async createConversation(e){await this.preflight(),_.info(`Creating conversation for session ${e.sessionId} and agent ${e.agentId}`);let n=await this.client.post("/api/conversations",{...H(e),tags:e.tags},{version:"v2"});return Bo(n)}async getProfile(e){let n=await this.client.get(`/apis/admin/profiles/${e}/`,{version:null});return L(n)}async getContentTypes(){let e=await this.client.get("/apis/admin/content-types/",{version:null});return L(e)}async getPlatformConfig(){let{config:e}=await this.client.get("/platform/config/",{version:null});return L(e)}async checkUserExists(e){let{exists:n}=await this.client.get(`/apis/admin/users/exists?external_id=${e}`);return n}async getConversationBySessionId(e,n={}){await this.preflight(),_.info(`Getting conversation for session ${e}`);let{attempts:o=1,retryDelay:s=1e3}=n,r=await this.client.get(`/api/conversations/by_session_id/${e}`,{attempts:o,retryDelay:s,retryOnResponse:i=>i.status===404||i.status>=500,version:"v2"});return Bo(r)}async isConversationSupported(e,n={}){_.info(`Check if conversation for session ${e} is supported`);let{attempts:o=1,retryDelay:s=1e3}=n;return(await this.client.get(`/api/conversations/by_session_id/${e}/active_profile`,{attempts:o,retryDelay:s,retryOnResponse:i=>i.status===404||i.status>=500,version:"v2"})).has_active_profile}async updateConversation(e,n){let o=H(n);n.tags&&(o.tags=n.tags);let s=await this.client.put(`/api/conversations/${e}`,o,{version:"v2"});return Bo(s)}async postMessages(e,n){return(await this.client.post(`/api/conversations/${e}/messages`,n.map(s=>({...H(s),tags:s.tags})),{version:"v2"})).map(s=>Bo(s))}async sendEvent(e,n){let{data:o,...s}=n,r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((i,[a,l])=>({...i,[a]:l}),{});return this.client.post("/api/events",H({...r,...s,data:o,name:e}),{version:"v2"})}async sendEventV1(e,n){let o=Object.entries(this.latestReceivedDeepdeskVersions).reduce((s,[r,i])=>({...s,[r]:i}),{});return this.client.post("/api/events",{event:e,data:H({...n,...o})})}async getEntities(e){return(await this.client.post("/api/entities",{messages:e.filter(o=>o.text)})).entities}async getSummary(e){return(await this.client.post("/api/summary",{conversation:{messages:e.filter(o=>o.text&&o.source)}})).summary}async getTemporaryExchangeToken(){return(await this.client.get("/auth/exchange-token",{version:null})).jwt}async exchangeTokenForAccessCookie(e){return this.client.get(`/apis/admin/session/jwt/?jwt=${e}`,{version:null}).catch(n=>{throw _.warn(`Invalid token '${e}'`),n})}async authenticateWithKey(e,n){await this.client.post("/apis/admin/session/api-key/",H(n),{version:null,refreshTokenOn401:!1,headers:{apikey:e}})}async getTextSuggestions(e,n={},o){return o==="sticky-messages"?this.getPinnedMessages(e):(await this.client.post(`/api/conversations/${e}/recommend/${o}`,H(n),{abortLatest:!0})).map(r=>({...L(r),text:r.text||r.url||r.message,source:o,type:o})).filter((r,i,a)=>i===a.findIndex(l=>l.text===r.text))}async isLoggedIn(){return await this.preflight(),this.client.validateToken()}async getAutocompleteSuggestions(e,n){return(await this.client.post(`/api/conversations/${e}/autocomplete`,H(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))}async getPinnedMessages(e){let n=await this.client.get(`/api/conversations/${e}/sticky-messages`,{abortLatest:!0});return L(n).map(o=>({...o,text:o.message,source:"sticky-messages",type:"pinned-message"}))}async getStyleSuggestions(e){let n=await this.client.post("/api/style-suggestions",H(e),{abortLatest:!0});return L(n)}async search(e){let n=await this.client.post(`/api/profiles/${e.profile}/search`,H(e),{version:"v2"});return L(n)}async knowledgeSearch(e,n,o){let s=await this.client.post("/api/knowledge-search/search",H({question:e.question,promptInstruction:e.promptInstruction,profile:o,chatHistory:n.map(r=>({question:r.question,answer:r.answer.answer}))}),{version:"v2"});return L(s)}async requestLoginByEmail(e){let n=await this.client.post("/apis/admin/session/passwordless/request/",{email:e},{version:null});return L(n)}async getCsrfToken(){let{token:e}=await this.client.get("/apis/admin/session/csrf/",{version:null});return e}async verifyLoginToken(e){let n=await this.client.post("/apis/admin/session/passwordless/login/",{token:e},{version:null});return L(n)}handleDeepdeskVersionHeaders(e){e.headers.forEach((n,o)=>{let s=o.toLowerCase(),r=s.match(Kr);if(!n||!r)return;let i=r[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&n&&a!==n&&_.warn(`Overwritten Version header ${s}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[i]=n})}};var dn=class{constructor(e,n){this.url=e;this.options={timeout:25e3,...n}}eventListeners={};options;timeoutTimer;eventSource;proxyEvent(e){this.eventSource.addEventListener(Ts(e),n=>{let{data:o}=n;try{let s=JSON.parse(o);this.emit(e,L(s))}catch{_.warn(`Invalid JSON for ${e}: ${o}`)}})}connect(){clearTimeout(this.timeoutTimer);let e=new EventSource(this.url,{withCredentials:!0});this.eventSource=e;let n=!1;e.onopen=()=>{n=!0},e.onerror=()=>{n&&e.readyState===2&&this.connect()},this.timeoutTimer=setTimeout(()=>{e.close(),this.connect()},this.options.timeout),Object.keys(this.eventListeners).forEach(o=>{this.proxyEvent(o)})}disconnect(){var e;clearTimeout(this.timeoutTimer),this.eventListeners={},(e=this.eventSource)==null||e.close()}emit(e,n){this.eventListeners[e]&&this.eventListeners[e].forEach(o=>o(n))}on(e,n){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(n),this.proxyEvent(e),()=>{this.off(e,n)}}off(e,n){let o;this.eventListeners[e]&&(o=this.eventListeners[e].indexOf(n),o>-1&&this.eventListeners[e].splice(o,1))}};var my;(e=>{let t;(r=>(r.Started="Started",r.Aborted="Aborted",r.Completed="Completed"))(t=e.AutoflowSessionState||={})})(my||={});var mn=class{constructor(e,n={}){this.apiUrl=e;this.client=new _e(e,n)}client;streams={};logger=_;async getCustomMessages(e){let n=await this.client.get(`/sessions/${e}/suggestions`);return L(n.suggestions)}async sendCustomMessage(e,n){let o=await this.client.post(`/sessions/${e}/messages`,H(n));return L(o)}async answerCustomMessage(e,n){await this.client.post(`/sessions/${e}/answers`,H(n))}async getAutoflows(e){let n=await this.client.get(`/sessions/${e}/autoflows`);return L(n.autoflows)}async startAutoflowSession(e){let n=await this.client.post("/autoflow-sessions",H(e));return L(n)}async stopAutoflowSession(e){await this.client.delete(`/autoflow-sessions/${e}`)}openStream(e){return this.streams[e]||(this.streams[e]=new dn(`${this.apiUrl}/sessions/${e}/events`),this.streams[e].connect()),this.streams[e]}closeStream(e){this.streams[e]||(this.streams[e].disconnect(),delete this.streams[e])}};import{combineReducers as xy,configureStore as Cy}from"@reduxjs/toolkit";import{createSlice as gy}from"@reduxjs/toolkit";var du={startTime:null,stopTime:null},mu=gy({name:"handlingTime",initialState:du,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(R,()=>du)}}),{handlingTimeStart:gu,handlingTimeStop:Ko,handlingTimeReset:fu}=mu.actions,hu=mu.reducer;var yu=(t={})=>{let e={onAuthError:co(!1),...t};return n=>o=>s=>("error"in s&&s.error.message==="Unauthorized"&&n.dispatch(e.onAuthError),o(s))};import{createAsyncThunk as fy,createSlice as hy}from"@reduxjs/toolkit";var Lr={list:{keywordMatches:[]},fetchState:"idle",isInitialRequest:null};var Xe=fy("styleSuggestions/getAll",async({text:t},e)=>{var i;let{deepdeskAPI:n}=e.extra,o=e.getState(),{showStyleSuggestions:s}=o.settings,r=(i=o.conversation.current)==null?void 0:i.profileCode;if(!s)return Lr.list;if(!r)throw new Error("No current conversation to fetch pinned messages");return n.getStyleSuggestions({profileCode:r,message:t})}),yy=hy({name:"styleSuggestions",initialState:Lr,reducers:{},extraReducers:t=>{t.addCase(Xe.pending,e=>{e.isInitialRequest=e.isInitialRequest===null,e.fetchState="loading"}).addCase(Xe.rejected,e=>{e.fetchState="error"}).addCase(Xe.fulfilled,(e,n)=>{e.fetchState="done",ke(e.list,n.payload)||(e.list=n.payload)}).addCase(R,()=>Lr)}}),Su=yy.reducer;var vu=(t={})=>{let e,n=!0,o={getStyleSuggestions:Xe,debounce:500,...t};return s=>r=>i=>{var m;let a=s.getState().input.text,l=r(i),c=s.getState();if(c.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:u}=c.settings;if(!((m=c.conversation.current)==null?void 0:m.id)||!u)return l;let{text:p}=c.input;return p===a&&!n||(clearTimeout(e),p==="")||(e=setTimeout(()=>{n=!1,s.dispatch(o.getStyleSuggestions({text:p}))},t.debounce)),l}};function Sy(t,e){return t.text===e.text&&t.selection.start===e.selection.start&&t.selection.end===e.selection.end}var xu=(t={})=>{let e={getTextSuggestions:fe,getAutocompleteSuggestions:jt,debounce:200,check:yo,...t},n,o=!0;return s=>r=>i=>{var x;let{input:{userCommitted:a}}=s.getState(),l=r(i),c=s.getState();if(c.auth.isLoggedIn!==!0)return l;let{recommendTextSuggestions:u,showTabCompletion:d}=c.settings,p=(x=c.conversation.current)==null?void 0:x.id,m=i.type===lo.toString();if(!p||!u&&!d)return l;let{input:{userCommitted:g}}=c;return Sy(g,a)&&!o&&!m||(clearTimeout(n),!e.check(c))||(n=setTimeout(()=>{o=!1;let b=et(c);b===""?s.dispatch(e.getTextSuggestions("default")):s.dispatch(e.getAutocompleteSuggestions(b))},m?0:e.debounce)),l}};var Cu=Xe.fulfilled.toString();function vy(t,e){let n=new Set([...e.keywordMatches.map(s=>s.keyword)]),o=[];return n.forEach(s=>{let r=t.keywordMatches.filter(l=>l.keyword===s),i=e.keywordMatches.filter(l=>l.keyword===s),a=i.length-r.length;a<=0||o.push(...i.slice(0,a))}),o}var Tu=t=>e=>n=>o=>{var u;if(o.type!==Cu){n(o);return}let s=e.getState().styleSuggestions.list;n(o);let r=e.getState(),i=r.styleSuggestions.list,a=(u=r.conversation)==null?void 0:u.current,{agentInfo:l}=r.info;if(s===i)return;let c=vy(s,i);o.type===Cu&&c.length>0&&t.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,agentId:l.agentId??(a==null?void 0:a.agentId),agentName:l.agentName??(a==null?void 0:a.agentName),agentEmail:l.agentEmail??(a==null?void 0:a.agentEmail),data:{keywordMatches:c}})};var Ty=xy({activeSuggestion:ka,answer:hl,auth:qa,autoflows:Cc,conversation:Wr,contentTypes:Ya,customMessages:Ic,exchangeToken:Nc,entities:nl,handlingTime:hu,info:Zi,input:Xo.reducer,overlayInput:V.reducer,settings:qr,profile:Tl,search:oa,summary:cl,styleSuggestions:Su,ui:Ma,textSuggestions:wa});function wu(t){return Cy({reducer:Ty,middleware:e=>[...e({thunk:{extraArgument:{dynamicThunkObject:t.dynamicThunkObject,deepdeskAPI:t.deepdeskAPI,deepdeskBrokerAPI:t.deepdeskBrokerAPI}},serializableCheck:!1}),yu(),xu({debounce:200}),vu({debounce:500}),Tu(t.deepdeskAPI),...t.middleware?t.middleware:[]],preloadedState:t.preloadedState})}var wy=t=>{var e;return((e=t==null?void 0:t.type)==null?void 0:e.toLowerCase())??"unknown"},by=t=>e=>n=>o=>{var a;let s=e.getState(),r=zo("inlineSuggestions")(s);switch(o.type){case he.toString():{let l=ya(o.payload.contentType)(e.getState()),c=l.indexOf(o.payload.suggestion);t.emit("edit-suggestion",{contentType:o.payload.contentType,index:c,suggestions:l});break}case oe.toString():{let{start:l,end:c}=s.input.selection;t.emit("select-suggestion",{type:wy(o.payload.suggestion),...o.payload,replace:o.payload.replace==="selection"?{start:l,end:c}:{start:0,end:c}},{mayApplyChanges:!0});break}case Pn.toString():{let{start:l,end:c}=s.input.selection;t.emit("replace",{...o.payload,replace:o.payload.replace==="selection"?{start:l,end:c}:{start:0,end:c}},{mayApplyChanges:!0});break}case At.toString():{let l=e.getState(),{text:c,selection:u}=l.input.userCommitted;t.emit("reset",{text:c,selectionAfter:u},{mayApplyChanges:!0});break}case An.toString():t.emit("select-image",o.payload,{mayApplyChanges:!0}),t.sendEvent("Image attached",{conversationId:s.conversation.current.id,data:{path:o.payload.suggestion.image,title:o.payload.suggestion.title}});break;case re.fulfilled.toString():o.payload.length>0&&t.sendEvent("entities found",{conversationId:s.conversation.current.id,data:{entities:o.payload}});break;case ve.fulfilled.toString():t.sendEvent("conversation summarized",{conversationId:s.conversation.current.id,data:{inputText:JSON.stringify(o.payload.original),summary:o.payload.summary}});break;case ae.toString():t.sendEvent(o.payload.name,{conversationId:((a=o.payload.options)==null?void 0:a.includeConversationData)&&s.conversation.current.id,data:o.payload.data});break;case kn.toString():t.handleKeyDown(o.payload);break;case It.toString():t.logSendMessage(o.payload);break;case Rn.toString():t.logSendEditSuggestionMessage(o.payload);break;case In.toString():t.handleInputChanged(o.payload);break;default:break}let i=n(o);switch(o.type){case It.toString():t.handleAfterSendMessage(o.payload);break;case zt.toString():t.onUpdateShowTabHint(o.payload);break;case Ko.toString():t.logHandlingTime();break;case oe.toString():{r&&(e.dispatch(Ie([])),e.dispatch(Ae()));break}default:break}return i},bu=by;function Mr(t){return t.toISOString().replace("T"," ").replace("Z","")}function Eu(t,e){var s,r,i;let{startTime:n,stopTime:o}=t.handlingTime;if(!n||!o)throw new Error("No startTime and stopTime for handling time metrics");return{conversationId:t.conversation.current.id,clientVersion:e.version,agentId:(s=t.info.agentInfo)==null?void 0:s.agentId,agentName:(r=t.info.agentInfo)==null?void 0:r.agentName,agentEmail:(i=t.info.agentInfo)==null?void 0:i.agentEmail,timeStart:Mr(n),timeStop:Mr(o)}}function Or(t,e,n){var P,w,N;let{text:o,metrics:{numCharsTyped:s,numCharsPasted:r,numCharsCut:i,numCharsDeleted:a,numPaste:l,agentStartedTypingTimestamp:c,pastes:u,cuts:d,deletions:p,textSuggestions:m,offeredTextSuggestions:g}}=e[t],f=o.length,b=m.reduce(($,{text:k,searchTerm:X})=>$+k.length-(X?X.length:0),0),h=c??Date.now(),v=(Date.now()-h)/1e3,C=s/v;return{conversationId:e.conversation.current.id,source:"agent",text:o,clientVersion:n.version,pastes:u,cuts:d,deletions:p,lenTextTyped:s,lenTextTotal:f,lenTextAssisted:b,lenTextPasted:r,lenTextCut:i,lenTextDeleted:a,timeTotalSeconds:v,charsPerSecond:C,numPastes:l,textSuggestionsV2:m,suggestionsCounters:[{source:"gpt",countOffered:g.filter($=>$.source==="gpt").length}],agentId:(P=e.info.agentInfo)==null?void 0:P.agentId,agentName:(w=e.info.agentInfo)==null?void 0:w.agentName,agentEmail:(N=e.info.agentInfo)==null?void 0:N.agentEmail}}function _u(t,e){let n=t.closest(e);if(n)return n;let o=t.getRootNode().host;return o instanceof HTMLElement?_u(o,e):null}function Pu(t,e){return _u(t,e)}function ku(t){return typeof t=="object"&&t!==null&&"name"in t&&"message"in t}function Nr(t){return t instanceof HTMLElement&&(Te(t)||Xn(t))}var Ru=(t,e)=>({value(){try{let n=sessionStorage.getItem(`dd-${t}`);if(!n)return e;try{return JSON.parse(n)}catch{return e}}catch{return e}},update(n){try{sessionStorage.setItem(`dd-${t}`,JSON.stringify(n))}catch{_.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function Ey(t){return t.offsetParent!==null}function Iu(t){if(!Ey(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 Dr(t,e,n=100){let o=Iu(t);e({isVisible:o});let s=setInterval(()=>{let r=Iu(t);r!==o&&(o=r,e({isVisible:o}))},n);return()=>{clearTimeout(s)}}import{jsx as ee}from"react/jsx-runtime";var Au=Ru("showTabHint",!0),qo=class t{static version="10.1.1";static count=0;deepdeskApi;inputMediator=null;version;broadcastEvents;eventListeners={};unmountHandlers=[];widgetRoot=null;dynamicThunkObject={};isMounted=!1;instanceId;shouldRender=!0;store;constructor({deepdeskUrl:e,brokerUrl:n,version:o=t.version||"unknown",locale:s="en-US",token:r,fetch:i,productName:a}){let l=e.replace(/\/api$/,"");this.deepdeskApi=new De(l,{token:r,fetch:i}),this.version=o,this.instanceId=t.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[bu({emit:(u,d,p)=>this.emit(u,d,p),handleAfterSendMessage:u=>this.handleAfterSendMessage(u),handleInputChanged:u=>this.handleInputChanged(u),handleKeyDown:u=>this.handleKeyDown(u),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:u=>this.logSendMessage(u),logSendEditSuggestionMessage:u=>this.logSendEditMessage(u),onUpdateShowTabHint:u=>Au.update(u),sendEvent:(u,d)=>this.deepdeskApi.sendEvent(u,d)})]};n&&Object.assign(c,{deepdeskBrokerAPI:new mn(n)}),this.store=wu(c),this.broadcastEvents=new pu({debug:!0,deepdeskUrl:l,eventMap:Va(this.store)}),this.store.dispatch(Rt),this.store.dispatch(zt(Au.value())),this.store.dispatch(Rt({locale:s,adminUrl:l,productName:a}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){return this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex]??null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(_.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(_.warn("Profile has not been loaded (yet)"),!0):(_.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(co(null)),this.store.dispatch(je()),new Promise(e=>{let n=this.store.subscribe(()=>{let o=this.store.getState();ye(o)&&Da(o)!=="loading"&&e()});this.unmountHandlers.push(()=>{n()})})}isLoggedIn(){return this.deepdeskApi.isLoggedIn()}async setPlatformAgentId(e){try{if((await this.deepdeskApi.client.get("/apis/admin/session/me/",{version:null})).external_id)return;await this.deepdeskApi.client.request("/apis/admin/session/me/",{method:"PATCH",body:JSON.stringify({external_id:e}),version:null})}catch(n){_.warn("Failed to attach user:",n)}}async isConversationSupported(e,n){return(await this.store.dispatch(Go({sessionId:e,options:n}))).payload}async createConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(Cn(e))).payload}async getConversationBySessionId(e,n){return this.hasConversation()&&this.sessionId()!==e&&this.resetConversation(),(await this.store.dispatch(Tn({sessionId:e,options:n}))).payload}async upsertConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch($o(e))).payload}async postMessages(e){return(await this.store.dispatch(bn(e))).payload}async updateConversation(e){return(await this.store.dispatch(wn(e))).payload}resetConversation(){this.store.dispatch(R()),this.dynamicThunkObject.conversationQuery=null}async getSummary(){let e=await this.store.dispatch(ve());if(e.error)throw new Error(e.error.message);return e.payload.summary}configure(e){this.store.dispatch(Rt(e))}setVisitorInfo(e){this.store.dispatch(Qi(e))}async setAgentInfo(e){await this.store.dispatch(Ut(e))}async setAgentSettings(e){await this.store.dispatch(bs(e))}async getAgentSettings(){return(await this.store.dispatch(Es())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();let e=[];return this.store.dispatch(lo()),e.push(this.refreshWidgetSuggestions()),Promise.all(e).then(()=>{})}notifyInputChanged(e){this.store.dispatch(In(e))}syncInputHtml(e){this.store.dispatch(ri(e))}notifyKeyDown(e){this.store.dispatch(kn(e))}notifyPaste(e,n){this.store.dispatch(oi({text:e,selectionText:n}))}notifyCut(e){this.store.dispatch(ti(e))}notifyExternalSuggestion(e){this.store.dispatch(oe(e)),this.store.dispatch(Ae())}notifyEditSuggestion(e){this.store.dispatch(Ca(e.contentType,e.suggestions)),this.store.dispatch(he({contentType:e.contentType,suggestion:typeof e.index=="number"?e.suggestions[e.index]:null}))}handleInputChanged(e){let{overlayCollapsed:n,openOverlayWhenTyping:o}=this.state.ui;n&&o&&this.store.dispatch(mt({collapse:!1})),this.inputMediator&&this.store.dispatch(Xr({text:e,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(Ie([])))}handleKeyDown(e){let{overlayCollapsed:n}=this.state.ui,{textSuggestions:o,selectedSuggestionIndex:s,selection:r}=this.state.input,{inlineSuggestions:i}=this.state.settings,a=o.length>0,l=s!==-1;if(this.store.dispatch(ni(_n(e))),!(e.key!=="Tab"&&!this.settings.showTextSuggestions))switch(e.key){case"Up":case"ArrowUp":if(n||!a||!r||e.shiftKey)return;this.store.dispatch(Jr()),i||this.stageSelectedSuggestion({inputType:"arrow"}),e.preventDefault();return;case"Down":case"ArrowDown":{if(n||!a||!r||e.shiftKey)return;this.store.dispatch(ei());let{selectedSuggestionIndex:c}=this.state.input;c===-1?this.store.dispatch(At()):i||this.stageSelectedSuggestion({inputType:"arrow"}),e.preventDefault();return}case"Esc":case"Escape":{l?(this.store.dispatch(Ln(-1)),this.store.dispatch(At()),e.preventDefault()):n||(this.store.dispatch(mt({collapse:!0})),this.store.dispatch(Aa(!0)),e.preventDefault());return}case"Tab":{let{userCommitted:c}=this.state.input,u=c.text.substring(0,c.selection.end),{tabCompletionSuggestion:d}=this.state.input;this.store.dispatch(zt(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):this.settings.showTabCompletion&&d&&d.text.startsWith(u)&&(this.store.dispatch(oe({text:d.text,suggestion:d,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch(Ae())),e.preventDefault();break}default:}}handleAfterSendMessage(e){this.emit("send-message",e),this.store.dispatch(si()),this.store.dispatch(Ie([]))}handlingTimeStart(){this.state.handlingTime.startTime||(_.info("Start handling time"),this.store.dispatch(gu()))}handlingTimeStop(){this.state.handlingTime.startTime&&(_.info("Stop handling time"),this.store.dispatch(Ko()))}logSendMessage(e){let n=Or("input",this.state,{version:this.version});e&&Object.assign(n,{text:e}),this.deepdeskApi.sendEventV1("Send Message",n),this.emit("send-message-event",n)}logSendEditMessage(e){let n=Or("overlayInput",this.state,{version:"v2"});e&&Object.assign(n,{text:e}),this.store.dispatch(Zr(this.state.overlayInput.metrics)),this.deepdeskApi.sendEvent("suggestion edited",{data:n})}logHandlingTime(){let e=Eu(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",e),this.store.dispatch(fu())}notifySubmit(e={}){this.shouldAbort()||(this.store.dispatch(Ae()),this.store.dispatch(It(e.text??this.state.input.text)))}stageSelectedSuggestion(e){let n=this.state.input.selectedSuggestionIndex,{textSuggestions:o}=this.state.input;this.store.dispatch(oe({text:o[n].text,suggestion:o[n],eventMetrics:e,replace:"until-selection-end"}))}emit(e,n,o={}){let s=()=>{this.eventListeners[e]&&this.eventListeners[e].forEach(r=>{try{r(n)}catch(i){_.warn(`The following error occurred in deepdeskSDK.on('${e}', handler)`),_.error(i)}})};this.inputMediator&&o.mayApplyChanges?this.inputMediator.applyChanges(s):s()}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}whenConversationLoaded(e){let n=()=>this.loadProfileConfig().then(()=>e());this.hasConversation()&&n();let o=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==o&&(o=this.hasConversation(),o&&n())})}overlayContainerFactory(e,n,o,s){let[r,i]=Ft(o,s);return r.dataset.testid=e,n!=null&&n.rootNode&&r.classList.add(n.rootNode),this.unmountHandlers.push(()=>{Hr(r),i(),r.remove()}),r}createContainer(e,n=document.body){let o=window.getComputedStyle(n),s=document.createElement("div");return Ue(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,n.appendChild(s),this.unmountHandlers.push(()=>{Hr(s),s.remove()}),s}mount(e,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!Nr(e))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let{customStyles:o={},showStyleSuggestions:s,showTabCompletion:r,showTextSuggestions:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:c,showSuggestionsAfterPattern:u,isEmbedded:d,detectSubmit:p,insertLink:m,inputMediator:g,closestScrollSelector:f,appendOverlayTo:x,inlineSuggestions:b}=n;this.configure({showStyleSuggestions:s,showTabCompletion:r,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:c,showSuggestionsAfterPattern:u,showTextSuggestions:i,insertLink:m,isEmbedded:d,inlineSuggestions:b});let h=f&&Pu(e,f)||void 0,v=this.overlayContainerFactory("deepdesk-tab-completion",o,e,{appendTo:x,closestScrollElement:h,mirrorOverflow:!0,onRemove:()=>this.unmount()}),C=this.overlayContainerFactory("deepdesk-suggestions-overlay",o,h||e,{appendTo:x});n.automaticHandlingTime&&this.setupHandlingTime(e),Uo(ee(en,{store:this.store,customStyles:o,children:ee(Wt,{broadcastEvents:this.broadcastEvents,children:ee(fc,{inputElement:e})})}),v),Uo(ee(en,{store:this.store,customStyles:o,children:ee(Wt,{broadcastEvents:this.broadcastEvents,children:ee(Co,{})})}),C),Uo(ee(en,{store:this.store,customStyles:o,children:ee(Wt,{broadcastEvents:this.broadcastEvents,children:ee(Pl,{})})}),this.createContainer("deepdesk-overlays")),Ue(e),this.inputMediator=g||(Te(e)?new Me(e):new _t(e)),this.inputMediator.on("change",({plainText:w})=>{this.notifyInputChanged(w)}),this.inputMediator.on("updated",({rawHtml:w})=>{w!=null&&this.syncInputHtml(w)}),this.inputMediator.on("keydown",w=>{this.notifyKeyDown(w)}),this.inputMediator.on("paste",({pastedText:w,selectionText:N})=>{this.notifyPaste(w,N)}),this.inputMediator.on("cut",({selectionText:w})=>{this.notifyCut(w)});let P;this.inputMediator.on("selection",w=>{clearTimeout(P),w===null?P=setTimeout(()=>{w!==null&&this.store.dispatch(Qo(w))},500):this.store.dispatch(Qo(w))}),this.inputMediator.on("disabled",()=>{var w;(w=this.inputMediator)==null||w.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{p&&this.notifySubmit()}),this.inputMediator.on("blur",()=>this.store.dispatch(dt(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(dt(!0))),this.store.dispatch(Qr({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.whenConversationLoaded(()=>{var w;this.broadcastEvents.setSessionId((w=this.state.conversation.current)==null?void 0:w.sessionId)}),this.isMounted=!0}unmount(){var e;this.unmountHandlers.forEach(n=>n()),this.unmountHandlers=[],(e=this.inputMediator)==null||e.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(e,n={}){if(this.widgetRoot&&_.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:o,showImages:s,showPersonalCollectionLink:r,isEmbedded:i}=n;this.widgetRoot=e,this.configure({showImages:s,showPersonalCollectionLink:r,isEmbedded:i}),Uo(ee(en,{store:this.store,customStyles:o,children:ee(Wt,{broadcastEvents:this.broadcastEvents,children:ee(cu,{})})}),e),this.whenConversationLoaded(()=>{var a;this.broadcastEvents.setSessionId((a=this.state.conversation.current)==null?void 0:a.sessionId)})}unmountWidget(){this.widgetRoot&&Hr(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(e){let n=Dr(e,({isVisible:o})=>{o?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){ku(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(Jt());let e=yt(this.state);e&&this.store.dispatch(Rt({showSearch:e.search,showAutoflows:e.autoflows,showCustomMessages:e.customMessages,showImageSearch:e.imageSearch,showEntitiesCommand:e.entitiesCommand,showSummaryCommand:e.summarizer,showKnowledgeSearch:e.knowledgeSearch,recommendTextSuggestions:e.recommendTextSuggestions}))}),this.loadProfileConfigPromise)}async checkForTrialMode(e){try{let{account:n}=await this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(_.info("Trial is active"),!await this.deepdeskApi.checkUserExists(e))throw new Error("User is not in trial");this.shouldRender=!0}catch(n){let{message:o}=n;_.info(o),this.shouldRender=!1}}async refreshWidgetSuggestions(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:e}=this.state.profile.data;if(!e.widget)return;let n=fo(this.state);try{n.forEach(({type:o})=>{o==="entities"?this.store.dispatch(re()):this.store.dispatch(fe(o))})}catch(o){this.handleError(o)}}};async function _y(t,e,n={}){let{value:o}=t,{start:s,end:r}=n.replace??{start:0,end:o.length},i=`${o.slice(0,s)}${e}${o.slice(r)}`,a=n.selectionAfter??{start:s+e.length,end:s+e.length},l=()=>{if(n.setValue)return n.setValue(i);t.value=i};return Promise.resolve(l()).then(()=>{t.selectionStart=a.start,t.selectionEnd=a.end,t.blur(),t.focus()})}async function Py(t,e,n={}){let o=n.replace?Et(t,n.replace.start,n.replace.end):uu(t),s,r=()=>{if(n.setRange)return n.setRange(o.cloneRange());o.deleteContents(),s=document.createElement("span"),o.insertNode(s),e.split(`
6
+ `).reverse().forEach((i,a)=>{a>0&&o.insertNode(document.createElement("br")),o.insertNode(document.createTextNode(i))}),o.commonAncestorContainer===t&&o.surroundContents(document.createElement("div"))};return Promise.resolve(r()).then(()=>{try{if(n.selectionAfter!==!1){t.focus();let i=n.selectionAfter?Et(t,n.selectionAfter.start,n.selectionAfter.end):(o.collapse(!1),o),a=window.getSelection();a==null||a.removeAllRanges(),a==null||a.addRange(i)}if(!s)return;s.scrollIntoView&&s.scrollIntoView({block:"nearest",inline:"nearest"})}finally{s&&s.remove()}})}function ky(t){return t.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}async function Ry(t,e,n){await new De(t).authenticateWithKey(e,n)}async function Iy(t){let n=await new _e(t).get("/platform/config/",{version:null});return L(n)}async function Ay(t){let n=await(t.fetch??window.fetch)(t.url),o=await n.blob();return new File([o],t.name,{type:t.mimeType??n.headers.get("Content-Type")??"image/jpeg"})}async function Ly(t,e){let n=await Ay(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}}export{D as Card,cd as Chip,_t as ContentEditableInput,De as DeepdeskAPI,qo as DeepdeskSDK,Le as InputMediator,Fe as InputType,tr as KeyboardHint,Cr as Label,yn as Locale,Ge as Section,wr as SectionList,He as Sources,O as Suggestion,Ce as SuggestionList,Me as TextAreaInput,vt as ToggleButton,Ly as attachFile,Ry as authenticateWithKey,Ft as createOverlayContainer,Et as createRangeFromOffsets,tn as escapeHTML,Iy as fetchPlatformConfig,ky as formatTextMarkup,Er as getRangeOffsets,Fo as getRangeText,Nr as isSupportedInputElement,Py as updateContentEditable,_y as updateTextArea,y as useStyles,Dr as waitForElementVisibilityChange};