@deepdesk/deepdesk-sdk 11.6.1-beta.4 → 11.6.1-beta.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs.js +2 -2
- package/dist/index.esm.js +2 -2
- package/dist/index.iife.js +2 -2
- package/package.json +1 -1
package/dist/index.iife.js
CHANGED
|
@@ -10,7 +10,7 @@ Add a <Suspense fallback=...> component higher in the tree to provide a loading
|
|
|
10
10
|
The error may be correlated with this previous error:
|
|
11
11
|
${so.current.stack}
|
|
12
12
|
|
|
13
|
-
`),ut}qi(()=>{so.current=void 0,Y.current=void 0,we.current=Qt});let Zt=(0,de.useMemo)(()=>de.default.createElement(m,Vn({},Qt,{ref:_})),[_,m,Qt]);return(0,de.useMemo)(()=>S?de.default.createElement(G.Provider,{value:gr},Zt):Zt,[G,Zt,gr])}let C=de.default.memo(x);if(C.WrappedComponent=m,C.displayName=x.displayName=h,l){let O=de.default.forwardRef(function(D,G){return de.default.createElement(C,Vn({},D,{reactReduxForwardedRef:G}))});return O.displayName=h,O.WrappedComponent=m,(0,Kg.default)(O,m)}return(0,Kg.default)(C,m)}}var Kn=GL;var _a=w(H());function XL({store:e,context:t,children:n,serverState:r,stabilityCheck:o="once",noopCheck:i="once"}){let s=(0,_a.useMemo)(()=>{let u=qc(e);return{store:e,subscription:u,getServerState:r?()=>r:void 0,stabilityCheck:o,noopCheck:i}},[e,r,o,i]),a=(0,_a.useMemo)(()=>e.getState(),[e]);qi(()=>{let{subscription:u}=s;return u.onStateChange=u.notifyNestedSubs,u.trySubscribe(),a!==e.getState()&&u.notifyNestedSubs(),()=>{u.tryUnsubscribe(),u.onStateChange=void 0}},[s,a]);let l=t||Je;return _a.default.createElement(l.Provider,{value:s},n)}var Wg=XL;function Xc(e=Je){let t=e===Je?Cc:Oa(e);return function(){let{store:r}=t();return r}}var $g=Xc();function t1(e=Je){let t=e===Je?$g:Xc(e);return function(){return t().dispatch}}var X=t1();Ax(r1.useSyncExternalStoreWithSelector);e1(n1.useSyncExternalStore);bx(Mg.unstable_batchedUpdates);var Da=(n=>(n.NL_NL="nl-NL",n.EN_US="en-US",n))(Da||{});var YL={locale:"en-US",deanonymize:!1,fallbackImage:!1,isEmbedded:!1,showAutoflows:!1,showCustomMessages:!1,showImages:!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,floatingMenu:!1,enableSuggestionFeedback:!1,enableFeedbackForm:!1,adminUrl:void 0,productName:"Deepdesk"},o1=Q({name:"settings",initialState:YL,reducers:{set(e,t){Object.entries(t.payload).forEach(n=>{let[r,o]=n;typeof o!="undefined"&&(e[r]=o)})}}}),{set:Yc}=o1.actions,qg=e=>t=>t.settings[e],V=e=>M(qg(e)),i1=o1.reducer;var QL={isLoggedIn:!0,loginFetchState:"idle",verifyFetchState:"idle",showLoginOverlay:!1},rt=e=>e.auth.isLoggedIn,s1=e=>e.auth.loginFetchState,a1=e=>e.auth.verifyFetchState,l1=e=>e.auth.showLoginOverlay,Wn=K("auth/validate",(e,t)=>k(void 0,null,function*(){return t.extra.deepdeskAPI.isLoggedIn()})),u1=K("auth/requestLogin",(n,r)=>k(void 0,[n,r],function*({email:e},t){let{deepdeskAPI:o}=t.extra;return o.requestLoginByEmail(e)})),Fa=K("auth/verifyLoginToken",(n,r)=>k(void 0,[n,r],function*({token:e},t){let{deepdeskAPI:o}=t.extra;return o.verifyLoginToken(e)})),c1=Q({name:"auth",initialState:QL,reducers:{setIsLoggedIn(e,t){e.isLoggedIn=t.payload},setShowLoginOverlay(e,t){e.showLoginOverlay=t.payload}},extraReducers:e=>{e.addCase(Wn.pending,t=>{t.loginFetchState="loading"}),e.addCase(Wn.fulfilled,(t,{payload:n})=>{t.isLoggedIn=n,t.loginFetchState="done"}),e.addCase(Wn.rejected,t=>{t.loginFetchState="error",t.isLoggedIn=!1}),e.addCase(Fa.pending,t=>{t.verifyFetchState="loading"}),e.addCase(Fa.rejected,t=>{t.verifyFetchState="error"}),e.addCase(Fa.fulfilled,(t,n)=>{n.payload.isLoggedIn?t.verifyFetchState="done":t.verifyFetchState="error"})}}),{setIsLoggedIn:Xi,setShowLoginOverlay:d1}=c1.actions,f1=c1.reducer;function $n(){}$n.prototype={diff:function(t,n){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},o=r.callback;typeof r=="function"&&(o=r,r={}),this.options=r;var i=this;function s(y){return o?(setTimeout(function(){o(void 0,y)},0),!0):y}t=this.castInput(t),n=this.castInput(n),t=this.removeEmpty(this.tokenize(t)),n=this.removeEmpty(this.tokenize(n));var a=n.length,l=t.length,u=1,c=a+l;r.maxEditLength&&(c=Math.min(c,r.maxEditLength));var p=[{newPos:-1,components:[]}],d=this.extractCommon(p[0],n,t,0);if(p[0].newPos+1>=a&&d+1>=l)return s([{value:this.join(n),count:n.length}]);function g(){for(var y=-1*u;y<=u;y+=2){var m=void 0,f=p[y-1],h=p[y+1],v=(h?h.newPos:0)-y;f&&(p[y-1]=void 0);var x=f&&f.newPos+1<a,T=h&&0<=v&&v<l;if(!x&&!T){p[y]=void 0;continue}if(!x||T&&f.newPos<h.newPos?(m=JL(h),i.pushComponent(m.components,void 0,!0)):(m=f,m.newPos++,i.pushComponent(m.components,!0,void 0)),v=i.extractCommon(m,n,t,y),m.newPos+1>=a&&v+1>=l)return s(ZL(i,m.components,n,t,i.useLongestToken));p[y]=m}u++}if(o)(function y(){setTimeout(function(){if(u>c)return o();g()||y()},0)})();else for(;u<=c;){var S=g();if(S)return S}},pushComponent:function(t,n,r){var o=t[t.length-1];o&&o.added===n&&o.removed===r?t[t.length-1]={count:o.count+1,added:n,removed:r}:t.push({count:1,added:n,removed:r})},extractCommon:function(t,n,r,o){for(var i=n.length,s=r.length,a=t.newPos,l=a-o,u=0;a+1<i&&l+1<s&&this.equals(n[a+1],r[l+1]);)a++,l++,u++;return u&&t.components.push({count:u}),t.newPos=a,l},equals:function(t,n){return this.options.comparator?this.options.comparator(t,n):t===n||this.options.ignoreCase&&t.toLowerCase()===n.toLowerCase()},removeEmpty:function(t){for(var n=[],r=0;r<t.length;r++)t[r]&&n.push(t[r]);return n},castInput:function(t){return t},tokenize:function(t){return t.split("")},join:function(t){return t.join("")}};function ZL(e,t,n,r,o){for(var i=0,s=t.length,a=0,l=0;i<s;i++){var u=t[i];if(u.removed){if(u.value=e.join(r.slice(l,l+u.count)),l+=u.count,i&&t[i-1].added){var p=t[i-1];t[i-1]=t[i],t[i]=p}}else{if(!u.added&&o){var c=n.slice(a,a+u.count);c=c.map(function(g,S){var y=r[l+S];return y.length>g.length?y:g}),u.value=e.join(c)}else u.value=e.join(n.slice(a,a+u.count));a+=u.count,u.added||(l+=u.count)}}var d=t[s-1];return s>1&&typeof d.value=="string"&&(d.added||d.removed)&&e.equals("",d.value)&&(t[s-2].value+=d.value,t.pop()),t}function JL(e){return{newPos:e.newPos,components:e.components.slice(0)}}var eI=new $n;function g1(e,t,n){return eI.diff(e,t,n)}var p1=/^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/,m1=/\S/,h1=new $n;h1.equals=function(e,t){return this.options.ignoreCase&&(e=e.toLowerCase(),t=t.toLowerCase()),e===t||this.options.ignoreWhitespace&&!m1.test(e)&&!m1.test(t)};h1.tokenize=function(e){for(var t=e.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/),n=0;n<t.length-1;n++)!t[n+1]&&t[n+2]&&p1.test(t[n])&&p1.test(t[n+2])&&(t[n]+=t[n+2],t.splice(n+1,2),n--);return t};var y1=new $n;y1.tokenize=function(e){var t=[],n=e.split(/(\n|\r\n)/);n[n.length-1]||n.pop();for(var r=0;r<n.length;r++){var o=n[r];r%2&&!this.options.newlineIsToken?t[t.length-1]+=o:(this.options.ignoreWhitespace&&(o=o.trim()),t.push(o))}return t};var tI=new $n;tI.tokenize=function(e){return e.split(/(\S.+?[.!?])(?=\s+|$)/)};var nI=new $n;nI.tokenize=function(e){return e.split(/([{}:;,]|\s+)/)};function Qc(e){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Qc=function(t){return typeof t}:Qc=function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Qc(e)}var rI=Object.prototype.toString,Ha=new $n;Ha.useLongestToken=!0;Ha.tokenize=y1.tokenize;Ha.castInput=function(e){var t=this.options,n=t.undefinedReplacement,r=t.stringifyReplacer,o=r===void 0?function(i,s){return typeof s=="undefined"?n:s}:r;return typeof e=="string"?e:JSON.stringify(Gg(e,null,null,o),o," ")};Ha.equals=function(e,t){return $n.prototype.equals.call(Ha,e.replace(/,([\r\n])/g,"$1"),t.replace(/,([\r\n])/g,"$1"))};function Gg(e,t,n,r,o){t=t||[],n=n||[],r&&(e=r(o,e));var i;for(i=0;i<t.length;i+=1)if(t[i]===e)return n[i];var s;if(rI.call(e)==="[object Array]"){for(t.push(e),s=new Array(e.length),n.push(s),i=0;i<e.length;i+=1)s[i]=Gg(e[i],t,n,r,o);return t.pop(),n.pop(),s}if(e&&e.toJSON&&(e=e.toJSON()),Qc(e)==="object"&&e!==null){t.push(e),s={},n.push(s);var a=[],l;for(l in e)e.hasOwnProperty(l)&&a.push(l);for(a.sort(),i=0;i<a.length;i+=1)l=a[i],s[l]=Gg(e[l],t,n,r,l);t.pop(),n.pop()}else s=e;return s}var Xg=new $n;Xg.tokenize=function(e){return e.slice()};Xg.join=Xg.removeEmpty=function(e){return e};function v1(e){return typeof e=="object"&&!Array.isArray(e)&&e!==null}function Wr(e,t,n=10){let r=typeof e,o=typeof t;if(n===0)throw new Error("Max depth deepEqual, possible circular references?");return r!==o?!1:e==null||r==="string"||r==="number"||r==="boolean"?e===t:Array.isArray(e)&&Array.isArray(t)?e.length!==t.length?!1:e.every((i,s)=>Wr(i,t[s],n-1)):v1(e)&&v1(t)?Object.keys(e).length!==Object.keys(t).length?!1:Object.keys(e).every(s=>Wr(e[s],t[s],n-1)):!1}function oI(e){return Math.max(...e.map(t=>t.length))}function iI(e,t){let n=e.reduce((r,o)=>{if(o){let i=r[o]?r[o]+1:1;return N(P({},r),{[o]:i})}return r},{});return Object.keys(n).reduce((r,o)=>(n[o]<t&&r.push(o),r),[])}function S1(e,t){let r=[...e.map(({text:o})=>o.split(/\b(\w+)\b/))];for(let o=0;o<oI(r);o++){let i=iI(r.map(a=>a[o]),t),s=r.filter(a=>!i.includes(a[o]));if(s.length>=t)r=s;else return{text:r[0].slice(0,o).join("").replace(/ (\?| |!|\.|,|\n)/g,"$1").trimEnd(),source:"mixed"}}}var sI=2;function w1(e,t=""){if(e.length===0)return;if(e.length===1)return e[0];let n=S1(e,sI);return n&&n.text!==t?n:e[0]}var aI={info(...e){console.info("[Deepdesk]",...e)},warn(...e){console.warn("[Deepdesk]",...e)},error(...e){console.error("[Deepdesk]",...e)}},z=aI;var x1={current:null,isSupported:null},fe=Re("resetConversation"),Yi=e=>{let{current:t}=e.conversation;return(t==null?void 0:t.sessionId)||null},$r=e=>{let{current:t}=e.conversation;return(t==null?void 0:t.id)||null},Qi=e=>e.conversation.isSupported,Yg=K("conversation/isSupported",(e,t)=>{let{deepdeskAPI:n}=t.extra;return n.isConversationSupported(e.sessionId,e.options)}),Zc=K("conversation/create",(e,t)=>{let{deepdeskAPI:n}=t.extra;return n.createConversation(e)}),Jc=K("conversation/bySessionId",(e,t)=>{let{deepdeskAPI:n}=t.extra;return n.getConversationBySessionId(e.sessionId,e.options)}),ed=K("conversation/update",(e,t)=>{let{deepdeskAPI:n}=t.extra,r=$r(t.getState());if(!r)throw new Error("No current conversation to update");return n.updateConversation(r,e)}),Qg=K("conversation/upsert",(e,t)=>{let{deepdeskAPI:n}=t.extra;return n.getConversationBySessionId(e.sessionId).catch(()=>null).then(r=>{if(!r)return n.createConversation(e);let{agentId:o,agentName:i,agentEmail:s,agentNickname:a,tags:l}=e;return n.updateConversation(r.id,{agentId:o,agentEmail:s,agentName:i,agentNickname:a,tags:l})})}),td=K("conversation/postMessages",(e,t)=>{let{deepdeskAPI:n}=t.extra,r=$r(t.getState());if(!r)throw new Error("No current conversation to update messages");return n.postMessages(r,e.map(o=>P({},o)))}),lI=[Zc.rejected,Jc.rejected,ed.rejected,td.rejected].map(e=>e==null?void 0:e.toString()),uI=Q({name:"conversation",initialState:x1,reducers:{},extraReducers:e=>{e.addCase(Yg.fulfilled,(t,n)=>{t.isSupported=n.payload}).addCase(Zc.fulfilled,(t,n)=>{var r,o;t.current=n.payload,t.isSupported=(o=(r=n.payload)==null?void 0:r.hasActiveProfile)!=null?o:null}).addCase(Jc.fulfilled,(t,n)=>{var r,o;t.current=n.payload,t.isSupported=(o=(r=n.payload)==null?void 0:r.hasActiveProfile)!=null?o:null}).addCase(Qg.fulfilled,(t,n)=>{var r,o;t.current=n.payload,t.isSupported=(o=(r=n.payload)==null?void 0:r.hasActiveProfile)!=null?o:null}).addCase(ed.fulfilled,(t,n)=>{var r,o;t.current=n.payload,t.isSupported=(o=(r=n.payload)==null?void 0:r.hasActiveProfile)!=null?o:null}).addCase(td.fulfilled,(t,n)=>{t.current&&(t.current.messages=n.payload)}).addCase(fe,()=>x1).addMatcher(t=>lI.includes(t.type),(t,n)=>{var r;throw z.info("Conversation action rejected",n.type,((r=n.error)==null?void 0:r.message)||"No message"),new Error(n.error.message)})}}),E1=uI.reducer;var Zi={text:"",html:null,selection:{start:0,end:0},beforeKeyUp:null,mixedSuggestion:null,textSuggestions:[],selectedSuggestionIndex:-1,metrics:{numCharsTyped:0,numCharsPasted:0,numCharsCut:0,numCharsDeleted:0,numPaste:0,agentStartedTypingTimestamp:null,externalTimeTotalSeconds:null,pastes:[],deletions:[],offeredTextSuggestions:[],textSuggestions:[],cuts:[]}};function b1(e){let{key:t,shiftKey:n,ctrlKey:r,metaKey:o,altKey:i}=e;return{key:t,shiftKey:n,ctrlKey:r,metaKey:o,altKey:i}}var nd=Re("input/replaceText"),Ao=Re("input/sendMessage"),rd=Re("input/applyImageSuggestion"),ot=Re("input/sendEvent"),C1=Q({name:"input",initialState:Zi,reducers:{setInput(e,t){let{text:n,html:r}=t.payload;e.text=n,e.html=r||null},setSelection(e,t){t.payload!==null&&(Wr(e.selection,t.payload)||(e.selection=t.payload))},commitSuggestion(e,t){let n=t.payload,{text:r,suggestion:{source:o,abVariant:i,abTestName:s,trainingJobs:a,sourceText:l,searchTerm:u,text:c},eventMetrics:{inputType:p},replace:d}=n,g=o==="search"||o==="personal-collection-search",S=r.slice(e.text.substring(0,e.selection.start).length);(g||d==="selection")&&(S=r),n.suggestion.source==="search-overlay"&&(S=c),e.metrics.textSuggestions.push({text:S,source:o,abVariant:i,abTestName:s,inputType:p,sourceText:l,trainingJobs:a||[],searchTerm:g?e.text:u}),e.textSuggestions=[],e.selectedSuggestionIndex=-1},offeredTextSuggestion(e,t){let{text:n,suggestion:{source:r}}=t.payload;e.metrics.offeredTextSuggestions.find(i=>i.text===n)||e.metrics.offeredTextSuggestions.push({text:n,source:r})},registerKeyDown(e,t){e.beforeKeyUp={text:e.text,selection:e.selection}},registerKeyUp(e,t){var l,u;let{beforeKeyUp:n}=e;if(!n)return;let{key:r,shiftKey:o,ctrlKey:i,metaKey:s,altKey:a}=t.payload;if(e.text!==n.text){switch(r){case"Enter":o&&(e.metrics.numCharsTyped+=1);break;case"Backspace":case"Delete":{let{text:c}=e,p=g1(n.text,c);n.text.length-c.length>1&&e.metrics.deletions.push(...p.filter(d=>d.removed).map(d=>d.value)),e.metrics.numCharsDeleted+=n.text.length-c.length;break}case"Shift":break;case"C":case"V":case"X":if(i||s)break;default:if(!i&&!s&&!a){e.metrics.numCharsTyped+=1;let c=((l=n.selection)==null?void 0:l.start)!==void 0&&((u=n.selection)==null?void 0:u.end)!==void 0?n.text.substring(n.selection.start,n.selection.end):null;c&&c.length>0&&(e.metrics.numCharsDeleted+=c.length,e.metrics.deletions.push(c))}}e.metrics.agentStartedTypingTimestamp||(e.metrics.agentStartedTypingTimestamp=Date.now()),e.text===""&&(e.metrics=Zi.metrics,e.textSuggestions=[],e.mixedSuggestion=null),e.beforeKeyUp={text:e.text,selection:e.selection}}},registerCut(e,t){let{metrics:n}=e,r=t.payload;e.metrics=N(P({},e.metrics),{numCharsCut:n.numCharsCut+r.length,cuts:[...n.cuts,r]})},registerPaste(e,t){let{metrics:n}=e,{text:r,selectionText:o}=t.payload,i=n.numCharsDeleted+(o&&o.length?o.length:0),s=o&&o.length?[...n.deletions,o]:n.deletions;e.metrics=N(P({},e.metrics),{numCharsDeleted:i,deletions:s,numCharsPasted:n.numCharsPasted+r.length,numPaste:n.numPaste+1,pastes:[...n.pastes,r]})},selectNextTextSuggestion(e){let t=e.textSuggestions.length;e.selectedSuggestionIndex=e.selectedSuggestionIndex<t-1?e.selectedSuggestionIndex+1:e.selectedSuggestionIndex},selectPreviousTextSuggestion(e){e.selectedSuggestionIndex=e.selectedSuggestionIndex>=0?e.selectedSuggestionIndex-1:e.selectedSuggestionIndex},selectTextSuggestionByIndex(e,t){e.selectedSuggestionIndex=t.payload},setTextSuggestions(e,t){if(e.selectedSuggestionIndex=-1,e.textSuggestions=t.payload,t.payload.length===0){e.mixedSuggestion=null;return}let n=e.text.substring(0,e.selection.end),r=w1(t.payload,n);e.mixedSuggestion=r!=null&&r.text.includes(n)?r:null},setMetrics(e,{payload:t}){e.metrics=t}},extraReducers:e=>{e.addCase(fe,t=>{t.mixedSuggestion=Zi.mixedSuggestion,t.textSuggestions=Zi.textSuggestions,t.selectedSuggestionIndex=Zi.selectedSuggestionIndex,t.metrics=Zi.metrics})}}),Ji=e=>e.input.text.substring(0,e.input.selection.end),cI=e=>e.input.selection,od=e=>{let{mixedSuggestion:t,selectedSuggestionIndex:n,textSuggestions:r}=e.input;return n>-1?r[n]:t},T1=()=>M(cI),{commitSuggestion:qn,offeredTextSuggestion:k1,registerCut:P1,registerKeyDown:R1,registerKeyUp:A1,registerPaste:L1,selectNextTextSuggestion:I1,selectPreviousTextSuggestion:O1,selectTextSuggestionByIndex:id,setInput:sd,setMetrics:N1,setSelection:ad,setTextSuggestions:Gn}=C1.actions,M1=C1.reducer;function dI(e){return e.replace(/(_\w)/g,t=>t[1].toUpperCase())}function re(e){return Array.isArray(e)?e.map(re):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>N(P({},t),{[dI(n)]:re(e[n])}),{}):e}function Zg(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function Oe(e){return Array.isArray(e)?e.map(Oe):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>N(P({},t),{[Zg(n)]:Oe(e[n])}),{}):e}var fI={agentInfo:void 0,agentSettings:{},visitorInfo:void 0,customData:void 0,fetchState:"idle"},za=e=>{var t,n,r;return{timezone:((t=e.info.visitorInfo)==null?void 0:t.visitorTimeZone)||Intl.DateTimeFormat().resolvedOptions().timeZone,agentName:((n=e.info.agentInfo)==null?void 0:n.agentNickname)||"",visitorName:((r=e.info.visitorInfo)==null?void 0:r.visitorName)||""}},Ua=K("info/setAgentInfo",(e,t)=>k(void 0,null,function*(){let{deepdeskAPI:n}=t.extra;if(!e.agentId&&!e.agentNickname)throw new Error("At least provide agentId or agentNickname");let r=yield n.client.get("/apis/admin/session/me/",{version:null}),o={};return r.external_id||(o.external_id=e.agentId),r.nickname||(o.nickname=e.agentNickname),!o.external_id&&!o.nickname?re(r):(yield n.client.patch("/apis/admin/session/me/",o,{version:null}),re(r))})),Jg=K("info/setAgentSettings",(e,t)=>k(void 0,null,function*(){let{deepdeskAPI:n}=t.extra,r=yield n.client.get("/apis/admin/session/me/",{version:null}),o=P(P({},typeof r.ui_config=="object"?r.ui_config:{}),e);return yield n.client.patch("/apis/admin/session/me/",{ui_config:o}),o})),eh=K("info/getAgentSettings",(e,t)=>k(void 0,null,function*(){let{deepdeskAPI:n}=t.extra;return(yield n.client.get("/apis/admin/session/me/",{version:null})).ui_config})),_1=e=>e.info.agentInfo,D1=e=>e.info.customData,F1=Q({name:"info",initialState:fI,reducers:{setVisitorInfo(e,t){e.visitorInfo=P(P({},e.visitorInfo),t.payload)},setCustomData(e,t){e.customData=t.payload}},extraReducers:e=>{e.addCase(Ua.pending,(t,n)=>{t.fetchState="loading",t.agentInfo=P(P({},t.agentInfo),n.meta.arg)}).addCase(Ua.rejected,t=>{t.fetchState="error"}).addCase(Ua.fulfilled,(t,n)=>{t.fetchState="done",t.agentInfo=N(P(P({},t.agentInfo),n.meta.arg),{agentDefaultLocale:n.payload.defaultLocale,agentId:n.payload.externalId||n.meta.arg.agentId||"",agentNickname:n.payload.nickname||n.meta.arg.agentNickname||""})}).addCase(Jg.fulfilled,(t,n)=>{t.agentSettings=n.payload}).addCase(eh.fulfilled,(t,n)=>{t.agentSettings=n.payload}).addCase(fe,t=>{t.visitorInfo=void 0})}}),{setVisitorInfo:H1,setCustomData:U1}=F1.actions,z1=F1.reducer;var ld={list:[],fetchState:"idle",isOpen:!1,page:"search",aggregates:{}},B1=e=>e.search.isOpen,j1=e=>e.search.page,V1=e=>e.search.list,K1=e=>e.search.aggregates;function W1(e,t=n=>n){return n=>n.search.list.filter(r=>r.type===e).map(t)}var Lo=K("search/getAll",(e,t)=>k(void 0,null,function*(){var a;let{deepdeskAPI:n}=t.extra,r=t.getState(),o=(a=r.conversation.current)==null?void 0:a.profileCode;if(!o)throw new Error("Profile should be provided in order to be able to search");let{results:i,aggregates:s}=yield n.search({profile:o,query:e.query,tags:e.tags,size:e.size,current:e.current,filters:{type:e.type},params:za(r)});return{results:i.map(l=>N(P({},l),{source:`search-${l.type.toLowerCase()}`,searchTerm:e.query})),aggregates:s}})),$1=Q({name:"search",initialState:ld,reducers:{setIsOpen(e,t){e.isOpen=t.payload},setPage(e,t){e.page=t.payload},resetSearch(e){e.fetchState=ld.fetchState,e.list=ld.list}},extraReducers:e=>{e.addCase(Lo.pending,t=>{t.fetchState="loading"}).addCase(Lo.rejected,(t,n)=>{t.fetchState="error",z.error(n.error)}).addCase(Lo.fulfilled,(t,n)=>{t.fetchState="done",t.list=n.payload.results,t.aggregates=n.payload.aggregates||{}}).addCase(fe,()=>ld)}}),{resetSearch:ud,setIsOpen:Ct,setPage:rn}=$1.actions,q1=$1.reducer;var th="SetCues",es="ShowLoginOverlay",Ba="UserLoggedIn",pI="UserLoggedOut",qr="ApplySuggestion",nh="ApplyImageSuggestion",mI="ShowCommandPalette",gI=e=>({[th]:t=>{e.dispatch(N(P({},t),{isBroadcasted:!0}))},[mI]:t=>{e.dispatch(Ct(t.isOpen)),t.page&&e.dispatch(rn(t.page))},[es]:t=>{e.dispatch(d1(t))},[Ba]:()=>{e.dispatch(Wn())},[pI]:()=>{e.dispatch(Wn())},[nh]:t=>{e.dispatch(rd({suggestion:t.suggestion}))},[qr]:t=>{e.dispatch(qn(N(P({},t),{eventMetrics:{inputType:"mouse"},replace:"selection"})))}}),G1=gI;var ja=w(H()),Y1=w(b()),X1=ja.default.createContext(null),Io=({broadcastEvents:e,children:t})=>{let n=ja.default.useMemo(()=>e,[]);return(0,Y1.jsx)(X1.Provider,{value:n,children:t})},Wt=()=>{let e=(0,ja.useContext)(X1);if(!e)throw new Error("You should use the useBroadcastEvents within a BroadcastEventsProvider");return e};var kd=w(ie()),sn=w(H());var bd=w(H());var rh=function(e,t){return rh=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[o]=r[o])},rh(e,t)};function Va(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");rh(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}var Tt=function(){return Tt=Object.assign||function(t){for(var n,r=1,o=arguments.length;r<o;r++){n=arguments[r];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t},Tt.apply(this,arguments)};function Q1(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]]);return n}function cd(e,t,n){if(n||arguments.length===2)for(var r=0,o=t.length,i;r<o;r++)(i||!(r in t))&&(i||(i=Array.prototype.slice.call(t,0,r)),i[r]=t[r]);return e.concat(i||Array.prototype.slice.call(t))}var dd;(function(e){e[e.EXPECT_ARGUMENT_CLOSING_BRACE=1]="EXPECT_ARGUMENT_CLOSING_BRACE",e[e.EMPTY_ARGUMENT=2]="EMPTY_ARGUMENT",e[e.MALFORMED_ARGUMENT=3]="MALFORMED_ARGUMENT",e[e.EXPECT_ARGUMENT_TYPE=4]="EXPECT_ARGUMENT_TYPE",e[e.INVALID_ARGUMENT_TYPE=5]="INVALID_ARGUMENT_TYPE",e[e.EXPECT_ARGUMENT_STYLE=6]="EXPECT_ARGUMENT_STYLE",e[e.INVALID_NUMBER_SKELETON=7]="INVALID_NUMBER_SKELETON",e[e.INVALID_DATE_TIME_SKELETON=8]="INVALID_DATE_TIME_SKELETON",e[e.EXPECT_NUMBER_SKELETON=9]="EXPECT_NUMBER_SKELETON",e[e.EXPECT_DATE_TIME_SKELETON=10]="EXPECT_DATE_TIME_SKELETON",e[e.UNCLOSED_QUOTE_IN_ARGUMENT_STYLE=11]="UNCLOSED_QUOTE_IN_ARGUMENT_STYLE",e[e.EXPECT_SELECT_ARGUMENT_OPTIONS=12]="EXPECT_SELECT_ARGUMENT_OPTIONS",e[e.EXPECT_PLURAL_ARGUMENT_OFFSET_VALUE=13]="EXPECT_PLURAL_ARGUMENT_OFFSET_VALUE",e[e.INVALID_PLURAL_ARGUMENT_OFFSET_VALUE=14]="INVALID_PLURAL_ARGUMENT_OFFSET_VALUE",e[e.EXPECT_SELECT_ARGUMENT_SELECTOR=15]="EXPECT_SELECT_ARGUMENT_SELECTOR",e[e.EXPECT_PLURAL_ARGUMENT_SELECTOR=16]="EXPECT_PLURAL_ARGUMENT_SELECTOR",e[e.EXPECT_SELECT_ARGUMENT_SELECTOR_FRAGMENT=17]="EXPECT_SELECT_ARGUMENT_SELECTOR_FRAGMENT",e[e.EXPECT_PLURAL_ARGUMENT_SELECTOR_FRAGMENT=18]="EXPECT_PLURAL_ARGUMENT_SELECTOR_FRAGMENT",e[e.INVALID_PLURAL_ARGUMENT_SELECTOR=19]="INVALID_PLURAL_ARGUMENT_SELECTOR",e[e.DUPLICATE_PLURAL_ARGUMENT_SELECTOR=20]="DUPLICATE_PLURAL_ARGUMENT_SELECTOR",e[e.DUPLICATE_SELECT_ARGUMENT_SELECTOR=21]="DUPLICATE_SELECT_ARGUMENT_SELECTOR",e[e.MISSING_OTHER_CLAUSE=22]="MISSING_OTHER_CLAUSE",e[e.INVALID_TAG=23]="INVALID_TAG",e[e.INVALID_TAG_NAME=25]="INVALID_TAG_NAME",e[e.UNMATCHED_CLOSING_TAG=26]="UNMATCHED_CLOSING_TAG",e[e.UNCLOSED_TAG=27]="UNCLOSED_TAG"})(dd||(dd={}));var fd=class{constructor(t){console.warn(`[vite-messages-plugin]: Message "${t}" was not precompiled. Did you use the correct extenstion *.messages.ts?`)}};var on;(function(e){e[e.literal=0]="literal",e[e.argument=1]="argument",e[e.number=2]="number",e[e.date=3]="date",e[e.time=4]="time",e[e.select=5]="select",e[e.plural=6]="plural",e[e.pound=7]="pound",e[e.tag=8]="tag"})(on||(on={}));var pd;(function(e){e[e.number=0]="number",e[e.dateTime=1]="dateTime"})(pd||(pd={}));function oh(e){return e.type===on.literal}function Z1(e){return e.type===on.argument}function md(e){return e.type===on.number}function gd(e){return e.type===on.date}function hd(e){return e.type===on.time}function yd(e){return e.type===on.select}function vd(e){return e.type===on.plural}function J1(e){return e.type===on.pound}function Sd(e){return e.type===on.tag}function wd(e){return!!(e&&typeof e=="object"&&e.type===pd.number)}function Ka(e){return!!(e&&typeof e=="object"&&e.type===pd.dateTime)}function ih(e){e.forEach(function(t){if(delete t.location,yd(t)||vd(t))for(var n in t.options)delete t.options[n].location,ih(t.options[n].value);else md(t)&&wd(t.style)||(gd(t)||hd(t))&&Ka(t.style)?delete t.style.location:Sd(t)&&ih(t.children)})}function eE(e,t){t===void 0&&(t={}),t=Tt({shouldParseSkeletons:!0,requiresOtherClause:!0},t);var n=new fd(e,t).parse();if(n.err){var r=SyntaxError(dd[n.err.kind]);throw r.location=n.err.location,r.originalMessage=n.err.message,r}return t!=null&&t.captureLocation||ih(n.val),n.val}function xd(e,t){var n=t&&t.cache?t.cache:xI,r=t&&t.serializer?t.serializer:wI,o=t&&t.strategy?t.strategy:yI;return o(e,{cache:n,serializer:r})}function hI(e){return e==null||typeof e=="number"||typeof e=="boolean"}function tE(e,t,n,r){var o=hI(r)?r:n(r),i=t.get(o);return typeof i=="undefined"&&(i=e.call(this,r),t.set(o,i)),i}function nE(e,t,n){var r=Array.prototype.slice.call(arguments,3),o=n(r),i=t.get(o);return typeof i=="undefined"&&(i=e.apply(this,r),t.set(o,i)),i}function sh(e,t,n,r,o){return n.bind(t,e,r,o)}function yI(e,t){var n=e.length===1?tE:nE;return sh(e,this,n,t.cache.create(),t.serializer)}function vI(e,t){return sh(e,this,nE,t.cache.create(),t.serializer)}function SI(e,t){return sh(e,this,tE,t.cache.create(),t.serializer)}var wI=function(){return JSON.stringify(arguments)};function ah(){this.cache=Object.create(null)}ah.prototype.get=function(e){return this.cache[e]};ah.prototype.set=function(e,t){this.cache[e]=t};var xI={create:function(){return new ah}},Ed={variadic:vI,monadic:SI};var Oo;(function(e){e.MISSING_VALUE="MISSING_VALUE",e.INVALID_VALUE="INVALID_VALUE",e.MISSING_INTL_API="MISSING_INTL_API"})(Oo||(Oo={}));var Wa=function(e){Va(t,e);function t(n,r,o){var i=e.call(this,n)||this;return i.code=r,i.originalMessage=o,i}return t.prototype.toString=function(){return"[formatjs Error: ".concat(this.code,"] ").concat(this.message)},t}(Error);var lh=function(e){Va(t,e);function t(n,r,o,i){return e.call(this,'Invalid values for "'.concat(n,'": "').concat(r,'". Options are "').concat(Object.keys(o).join('", "'),'"'),Oo.INVALID_VALUE,i)||this}return t}(Wa);var rE=function(e){Va(t,e);function t(n,r,o){return e.call(this,'Value for "'.concat(n,'" must be of type ').concat(r),Oo.INVALID_VALUE,o)||this}return t}(Wa);var oE=function(e){Va(t,e);function t(n,r){return e.call(this,'The intl string context variable "'.concat(n,'" was not provided to the string "').concat(r,'"'),Oo.MISSING_VALUE,r)||this}return t}(Wa);var et;(function(e){e[e.literal=0]="literal",e[e.object=1]="object"})(et||(et={}));function EI(e){return e.length<2?e:e.reduce(function(t,n){var r=t[t.length-1];return!r||r.type!==et.literal||n.type!==et.literal?t.push(n):r.value+=n.value,t},[])}function bI(e){return typeof e=="function"}function $a(e,t,n,r,o,i,s){if(e.length===1&&oh(e[0]))return[{type:et.literal,value:e[0].value}];for(var a=[],l=0,u=e;l<u.length;l++){var c=u[l];if(oh(c)){a.push({type:et.literal,value:c.value});continue}if(J1(c)){typeof i=="number"&&a.push({type:et.literal,value:n.getNumberFormat(t).format(i)});continue}var p=c.value;if(!(o&&p in o))throw new oE(p,s);var d=o[p];if(Z1(c)){(!d||typeof d=="string"||typeof d=="number")&&(d=typeof d=="string"||typeof d=="number"?String(d):""),a.push({type:typeof d=="string"?et.literal:et.object,value:d});continue}if(gd(c)){var g=typeof c.style=="string"?r.date[c.style]:Ka(c.style)?c.style.parsedOptions:void 0;a.push({type:et.literal,value:n.getDateTimeFormat(t,g).format(d)});continue}if(hd(c)){var g=typeof c.style=="string"?r.time[c.style]:Ka(c.style)?c.style.parsedOptions:r.time.medium;a.push({type:et.literal,value:n.getDateTimeFormat(t,g).format(d)});continue}if(md(c)){var g=typeof c.style=="string"?r.number[c.style]:wd(c.style)?c.style.parsedOptions:void 0;g&&g.scale&&(d=d*(g.scale||1)),a.push({type:et.literal,value:n.getNumberFormat(t,g).format(d)});continue}if(Sd(c)){var S=c.children,y=c.value,m=o[y];if(!bI(m))throw new rE(y,"function",s);var f=$a(S,t,n,r,o,i),h=m(f.map(function(T){return T.value}));Array.isArray(h)||(h=[h]),a.push.apply(a,h.map(function(T){return{type:typeof T=="string"?et.literal:et.object,value:T}}))}if(yd(c)){var v=c.options[d]||c.options.other;if(!v)throw new lh(c.value,d,Object.keys(c.options),s);a.push.apply(a,$a(v.value,t,n,r,o));continue}if(vd(c)){var v=c.options["=".concat(d)];if(!v){if(!Intl.PluralRules)throw new Wa(`Intl.PluralRules is not available in this environment.
|
|
13
|
+
`),ut}qi(()=>{so.current=void 0,Y.current=void 0,we.current=Qt});let Zt=(0,de.useMemo)(()=>de.default.createElement(m,Vn({},Qt,{ref:_})),[_,m,Qt]);return(0,de.useMemo)(()=>S?de.default.createElement(G.Provider,{value:gr},Zt):Zt,[G,Zt,gr])}let C=de.default.memo(x);if(C.WrappedComponent=m,C.displayName=x.displayName=h,l){let O=de.default.forwardRef(function(D,G){return de.default.createElement(C,Vn({},D,{reactReduxForwardedRef:G}))});return O.displayName=h,O.WrappedComponent=m,(0,Kg.default)(O,m)}return(0,Kg.default)(C,m)}}var Kn=GL;var _a=w(H());function XL({store:e,context:t,children:n,serverState:r,stabilityCheck:o="once",noopCheck:i="once"}){let s=(0,_a.useMemo)(()=>{let u=qc(e);return{store:e,subscription:u,getServerState:r?()=>r:void 0,stabilityCheck:o,noopCheck:i}},[e,r,o,i]),a=(0,_a.useMemo)(()=>e.getState(),[e]);qi(()=>{let{subscription:u}=s;return u.onStateChange=u.notifyNestedSubs,u.trySubscribe(),a!==e.getState()&&u.notifyNestedSubs(),()=>{u.tryUnsubscribe(),u.onStateChange=void 0}},[s,a]);let l=t||Je;return _a.default.createElement(l.Provider,{value:s},n)}var Wg=XL;function Xc(e=Je){let t=e===Je?Cc:Oa(e);return function(){let{store:r}=t();return r}}var $g=Xc();function t1(e=Je){let t=e===Je?$g:Xc(e);return function(){return t().dispatch}}var X=t1();Ax(r1.useSyncExternalStoreWithSelector);e1(n1.useSyncExternalStore);bx(Mg.unstable_batchedUpdates);var Da=(n=>(n.NL_NL="nl-NL",n.EN_US="en-US",n))(Da||{});var YL={locale:"en-US",deanonymize:!1,fallbackImage:!1,isEmbedded:!1,showAutoflows:!1,showCustomMessages:!1,showImages:!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,floatingMenu:!1,enableSuggestionFeedback:!1,enableFeedbackForm:!1,adminUrl:void 0,productName:"Deepdesk"},o1=Q({name:"settings",initialState:YL,reducers:{set(e,t){Object.entries(t.payload).forEach(n=>{let[r,o]=n;typeof o!="undefined"&&(e[r]=o)})}}}),{set:Yc}=o1.actions,qg=e=>t=>t.settings[e],V=e=>M(qg(e)),i1=o1.reducer;var QL={isLoggedIn:!0,loginFetchState:"idle",verifyFetchState:"idle",showLoginOverlay:!1},rt=e=>e.auth.isLoggedIn,s1=e=>e.auth.loginFetchState,a1=e=>e.auth.verifyFetchState,l1=e=>e.auth.showLoginOverlay,Wn=K("auth/validate",(e,t)=>k(void 0,null,function*(){return t.extra.deepdeskAPI.isLoggedIn()})),u1=K("auth/requestLogin",(n,r)=>k(void 0,[n,r],function*({email:e},t){let{deepdeskAPI:o}=t.extra;return o.requestLoginByEmail(e)})),Fa=K("auth/verifyLoginToken",(n,r)=>k(void 0,[n,r],function*({token:e},t){let{deepdeskAPI:o}=t.extra;return o.verifyLoginToken(e)})),c1=Q({name:"auth",initialState:QL,reducers:{setIsLoggedIn(e,t){e.isLoggedIn=t.payload},setShowLoginOverlay(e,t){e.showLoginOverlay=t.payload}},extraReducers:e=>{e.addCase(Wn.pending,t=>{t.loginFetchState="loading"}),e.addCase(Wn.fulfilled,(t,{payload:n})=>{t.isLoggedIn=n,t.loginFetchState="done"}),e.addCase(Wn.rejected,t=>{t.loginFetchState="error",t.isLoggedIn=!1}),e.addCase(Fa.pending,t=>{t.verifyFetchState="loading"}),e.addCase(Fa.rejected,t=>{t.verifyFetchState="error"}),e.addCase(Fa.fulfilled,(t,n)=>{n.payload.isLoggedIn?t.verifyFetchState="done":t.verifyFetchState="error"})}}),{setIsLoggedIn:Xi,setShowLoginOverlay:d1}=c1.actions,f1=c1.reducer;function $n(){}$n.prototype={diff:function(t,n){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},o=r.callback;typeof r=="function"&&(o=r,r={}),this.options=r;var i=this;function s(y){return o?(setTimeout(function(){o(void 0,y)},0),!0):y}t=this.castInput(t),n=this.castInput(n),t=this.removeEmpty(this.tokenize(t)),n=this.removeEmpty(this.tokenize(n));var a=n.length,l=t.length,u=1,c=a+l;r.maxEditLength&&(c=Math.min(c,r.maxEditLength));var p=[{newPos:-1,components:[]}],d=this.extractCommon(p[0],n,t,0);if(p[0].newPos+1>=a&&d+1>=l)return s([{value:this.join(n),count:n.length}]);function g(){for(var y=-1*u;y<=u;y+=2){var m=void 0,f=p[y-1],h=p[y+1],v=(h?h.newPos:0)-y;f&&(p[y-1]=void 0);var x=f&&f.newPos+1<a,T=h&&0<=v&&v<l;if(!x&&!T){p[y]=void 0;continue}if(!x||T&&f.newPos<h.newPos?(m=JL(h),i.pushComponent(m.components,void 0,!0)):(m=f,m.newPos++,i.pushComponent(m.components,!0,void 0)),v=i.extractCommon(m,n,t,y),m.newPos+1>=a&&v+1>=l)return s(ZL(i,m.components,n,t,i.useLongestToken));p[y]=m}u++}if(o)(function y(){setTimeout(function(){if(u>c)return o();g()||y()},0)})();else for(;u<=c;){var S=g();if(S)return S}},pushComponent:function(t,n,r){var o=t[t.length-1];o&&o.added===n&&o.removed===r?t[t.length-1]={count:o.count+1,added:n,removed:r}:t.push({count:1,added:n,removed:r})},extractCommon:function(t,n,r,o){for(var i=n.length,s=r.length,a=t.newPos,l=a-o,u=0;a+1<i&&l+1<s&&this.equals(n[a+1],r[l+1]);)a++,l++,u++;return u&&t.components.push({count:u}),t.newPos=a,l},equals:function(t,n){return this.options.comparator?this.options.comparator(t,n):t===n||this.options.ignoreCase&&t.toLowerCase()===n.toLowerCase()},removeEmpty:function(t){for(var n=[],r=0;r<t.length;r++)t[r]&&n.push(t[r]);return n},castInput:function(t){return t},tokenize:function(t){return t.split("")},join:function(t){return t.join("")}};function ZL(e,t,n,r,o){for(var i=0,s=t.length,a=0,l=0;i<s;i++){var u=t[i];if(u.removed){if(u.value=e.join(r.slice(l,l+u.count)),l+=u.count,i&&t[i-1].added){var p=t[i-1];t[i-1]=t[i],t[i]=p}}else{if(!u.added&&o){var c=n.slice(a,a+u.count);c=c.map(function(g,S){var y=r[l+S];return y.length>g.length?y:g}),u.value=e.join(c)}else u.value=e.join(n.slice(a,a+u.count));a+=u.count,u.added||(l+=u.count)}}var d=t[s-1];return s>1&&typeof d.value=="string"&&(d.added||d.removed)&&e.equals("",d.value)&&(t[s-2].value+=d.value,t.pop()),t}function JL(e){return{newPos:e.newPos,components:e.components.slice(0)}}var eI=new $n;function g1(e,t,n){return eI.diff(e,t,n)}var p1=/^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/,m1=/\S/,h1=new $n;h1.equals=function(e,t){return this.options.ignoreCase&&(e=e.toLowerCase(),t=t.toLowerCase()),e===t||this.options.ignoreWhitespace&&!m1.test(e)&&!m1.test(t)};h1.tokenize=function(e){for(var t=e.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/),n=0;n<t.length-1;n++)!t[n+1]&&t[n+2]&&p1.test(t[n])&&p1.test(t[n+2])&&(t[n]+=t[n+2],t.splice(n+1,2),n--);return t};var y1=new $n;y1.tokenize=function(e){var t=[],n=e.split(/(\n|\r\n)/);n[n.length-1]||n.pop();for(var r=0;r<n.length;r++){var o=n[r];r%2&&!this.options.newlineIsToken?t[t.length-1]+=o:(this.options.ignoreWhitespace&&(o=o.trim()),t.push(o))}return t};var tI=new $n;tI.tokenize=function(e){return e.split(/(\S.+?[.!?])(?=\s+|$)/)};var nI=new $n;nI.tokenize=function(e){return e.split(/([{}:;,]|\s+)/)};function Qc(e){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Qc=function(t){return typeof t}:Qc=function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Qc(e)}var rI=Object.prototype.toString,Ha=new $n;Ha.useLongestToken=!0;Ha.tokenize=y1.tokenize;Ha.castInput=function(e){var t=this.options,n=t.undefinedReplacement,r=t.stringifyReplacer,o=r===void 0?function(i,s){return typeof s=="undefined"?n:s}:r;return typeof e=="string"?e:JSON.stringify(Gg(e,null,null,o),o," ")};Ha.equals=function(e,t){return $n.prototype.equals.call(Ha,e.replace(/,([\r\n])/g,"$1"),t.replace(/,([\r\n])/g,"$1"))};function Gg(e,t,n,r,o){t=t||[],n=n||[],r&&(e=r(o,e));var i;for(i=0;i<t.length;i+=1)if(t[i]===e)return n[i];var s;if(rI.call(e)==="[object Array]"){for(t.push(e),s=new Array(e.length),n.push(s),i=0;i<e.length;i+=1)s[i]=Gg(e[i],t,n,r,o);return t.pop(),n.pop(),s}if(e&&e.toJSON&&(e=e.toJSON()),Qc(e)==="object"&&e!==null){t.push(e),s={},n.push(s);var a=[],l;for(l in e)e.hasOwnProperty(l)&&a.push(l);for(a.sort(),i=0;i<a.length;i+=1)l=a[i],s[l]=Gg(e[l],t,n,r,l);t.pop(),n.pop()}else s=e;return s}var Xg=new $n;Xg.tokenize=function(e){return e.slice()};Xg.join=Xg.removeEmpty=function(e){return e};function v1(e){return typeof e=="object"&&!Array.isArray(e)&&e!==null}function Wr(e,t,n=10){let r=typeof e,o=typeof t;if(n===0)throw new Error("Max depth deepEqual, possible circular references?");return r!==o?!1:e==null||r==="string"||r==="number"||r==="boolean"?e===t:Array.isArray(e)&&Array.isArray(t)?e.length!==t.length?!1:e.every((i,s)=>Wr(i,t[s],n-1)):v1(e)&&v1(t)?Object.keys(e).length!==Object.keys(t).length?!1:Object.keys(e).every(s=>Wr(e[s],t[s],n-1)):!1}function oI(e){return Math.max(...e.map(t=>t.length))}function iI(e,t){let n=e.reduce((r,o)=>{if(o){let i=r[o]?r[o]+1:1;return N(P({},r),{[o]:i})}return r},{});return Object.keys(n).reduce((r,o)=>(n[o]<t&&r.push(o),r),[])}function S1(e,t){let r=[...e.map(({text:o})=>o.split(/\b(\w+)\b/))];for(let o=0;o<oI(r);o++){let i=iI(r.map(a=>a[o]),t),s=r.filter(a=>!i.includes(a[o]));if(s.length>=t)r=s;else return{text:r[0].slice(0,o).join("").replace(/ (\?| |!|\.|,|\n)/g,"$1").trimEnd(),source:"mixed"}}}var sI=2;function w1(e,t=""){if(e.length===0)return;if(e.length===1)return e[0];let n=S1(e,sI);return n&&n.text!==t?n:e[0]}var aI={info(...e){console.info("[Deepdesk]",...e)},warn(...e){console.warn("[Deepdesk]",...e)},error(...e){console.error("[Deepdesk]",...e)}},z=aI;var x1={current:null,isSupported:null},fe=Re("resetConversation"),Yi=e=>{let{current:t}=e.conversation;return(t==null?void 0:t.sessionId)||null},$r=e=>{let{current:t}=e.conversation;return(t==null?void 0:t.id)||null},Qi=e=>e.conversation.isSupported,Yg=K("conversation/isSupported",(e,t)=>{let{deepdeskAPI:n}=t.extra;return n.isConversationSupported(e.sessionId,e.options)}),Zc=K("conversation/create",(e,t)=>{let{deepdeskAPI:n}=t.extra;return n.createConversation(e)}),Jc=K("conversation/bySessionId",(e,t)=>{let{deepdeskAPI:n}=t.extra;return n.getConversationBySessionId(e.sessionId,e.options)}),ed=K("conversation/update",(e,t)=>{let{deepdeskAPI:n}=t.extra,r=$r(t.getState());if(!r)throw new Error("No current conversation to update");return n.updateConversation(r,e)}),Qg=K("conversation/upsert",(e,t)=>{let{deepdeskAPI:n}=t.extra;return n.getConversationBySessionId(e.sessionId).catch(()=>null).then(r=>{if(!r)return n.createConversation(e);let{agentId:o,agentName:i,agentEmail:s,agentNickname:a,tags:l}=e;return n.updateConversation(r.id,{agentId:o,agentEmail:s,agentName:i,agentNickname:a,tags:l})})}),td=K("conversation/postMessages",(e,t)=>{let{deepdeskAPI:n}=t.extra,r=$r(t.getState());if(!r)throw new Error("No current conversation to update messages");return n.postMessages(r,e.map(o=>P({},o)))}),lI=[Zc.rejected,Jc.rejected,ed.rejected,td.rejected].map(e=>e==null?void 0:e.toString()),uI=Q({name:"conversation",initialState:x1,reducers:{},extraReducers:e=>{e.addCase(Yg.fulfilled,(t,n)=>{t.isSupported=n.payload}).addCase(Zc.fulfilled,(t,n)=>{var r,o;t.current=n.payload,t.isSupported=(o=(r=n.payload)==null?void 0:r.hasActiveProfile)!=null?o:null}).addCase(Jc.fulfilled,(t,n)=>{var r,o;t.current=n.payload,t.isSupported=(o=(r=n.payload)==null?void 0:r.hasActiveProfile)!=null?o:null}).addCase(Qg.fulfilled,(t,n)=>{var r,o;t.current=n.payload,t.isSupported=(o=(r=n.payload)==null?void 0:r.hasActiveProfile)!=null?o:null}).addCase(ed.fulfilled,(t,n)=>{var r,o;t.current=n.payload,t.isSupported=(o=(r=n.payload)==null?void 0:r.hasActiveProfile)!=null?o:null}).addCase(td.fulfilled,(t,n)=>{t.current&&(t.current.messages=n.payload)}).addCase(fe,()=>x1).addMatcher(t=>lI.includes(t.type),(t,n)=>{var r;throw z.info("Conversation action rejected",n.type,((r=n.error)==null?void 0:r.message)||"No message"),new Error(n.error.message)})}}),E1=uI.reducer;var Zi={text:"",html:null,selection:{start:0,end:0},beforeKeyUp:null,mixedSuggestion:null,textSuggestions:[],selectedSuggestionIndex:-1,metrics:{numCharsTyped:0,numCharsPasted:0,numCharsCut:0,numCharsDeleted:0,numPaste:0,agentStartedTypingTimestamp:null,externalTimeTotalSeconds:null,pastes:[],deletions:[],offeredTextSuggestions:[],textSuggestions:[],cuts:[]}};function b1(e){let{key:t,shiftKey:n,ctrlKey:r,metaKey:o,altKey:i}=e;return{key:t,shiftKey:n,ctrlKey:r,metaKey:o,altKey:i}}var nd=Re("input/replaceText"),Ao=Re("input/sendMessage"),rd=Re("input/applyImageSuggestion"),ot=Re("input/sendEvent"),C1=Q({name:"input",initialState:Zi,reducers:{setInput(e,t){let{text:n,html:r}=t.payload;e.text=n,e.html=r||null},setSelection(e,t){t.payload!==null&&(Wr(e.selection,t.payload)||(e.selection=t.payload))},commitSuggestion(e,t){let n=t.payload,{text:r,suggestion:{source:o,abVariant:i,abTestName:s,trainingJobs:a,sourceText:l,searchTerm:u,text:c},eventMetrics:{inputType:p},replace:d}=n,g=o==="search"||o==="personal-collection-search",S=r.slice(e.text.substring(0,e.selection.start).length);(g||d==="selection")&&(S=r),n.suggestion.source==="search-overlay"&&(S=c),e.metrics.textSuggestions.push({text:S,source:o,abVariant:i,abTestName:s,inputType:p,sourceText:l,trainingJobs:a||[],searchTerm:g?e.text:u}),e.textSuggestions=[],e.selectedSuggestionIndex=-1},offeredTextSuggestion(e,t){let{text:n,suggestion:{source:r}}=t.payload;e.metrics.offeredTextSuggestions.find(i=>i.text===n)||e.metrics.offeredTextSuggestions.push({text:n,source:r})},registerKeyDown(e,t){e.beforeKeyUp={text:e.text,selection:e.selection}},registerKeyUp(e,t){var l,u;let{beforeKeyUp:n}=e;if(!n)return;let{key:r,shiftKey:o,ctrlKey:i,metaKey:s,altKey:a}=t.payload;if(e.text!==n.text){switch(r){case"Enter":o&&(e.metrics.numCharsTyped+=1);break;case"Backspace":case"Delete":{let{text:c}=e,p=g1(n.text,c);n.text.length-c.length>1&&e.metrics.deletions.push(...p.filter(d=>d.removed).map(d=>d.value)),e.metrics.numCharsDeleted+=n.text.length-c.length;break}case"Shift":break;case"Meta":break;case"C":case"V":case"X":case"c":case"v":case"x":if(i||s)break;default:if(!i&&!s&&!a){e.metrics.numCharsTyped+=1;let c=((l=n.selection)==null?void 0:l.start)!==void 0&&((u=n.selection)==null?void 0:u.end)!==void 0?n.text.substring(n.selection.start,n.selection.end):null;c&&c.length>0&&(e.metrics.numCharsDeleted+=c.length,e.metrics.deletions.push(c))}}e.metrics.agentStartedTypingTimestamp||(e.metrics.agentStartedTypingTimestamp=Date.now()),e.text===""&&(e.metrics=Zi.metrics,e.textSuggestions=[],e.mixedSuggestion=null),e.beforeKeyUp={text:e.text,selection:e.selection}}},registerCut(e,t){let{metrics:n}=e,r=t.payload;e.metrics=N(P({},e.metrics),{numCharsCut:n.numCharsCut+r.length,cuts:[...n.cuts,r]})},registerPaste(e,t){let{metrics:n}=e,{text:r,selectionText:o}=t.payload,i=n.numCharsDeleted+(o&&o.length?o.length:0),s=o&&o.length?[...n.deletions,o]:n.deletions;e.metrics=N(P({},e.metrics),{numCharsDeleted:i,deletions:s,numCharsPasted:n.numCharsPasted+r.length,numPaste:n.numPaste+1,pastes:[...n.pastes,r]})},selectNextTextSuggestion(e){let t=e.textSuggestions.length;e.selectedSuggestionIndex=e.selectedSuggestionIndex<t-1?e.selectedSuggestionIndex+1:e.selectedSuggestionIndex},selectPreviousTextSuggestion(e){e.selectedSuggestionIndex=e.selectedSuggestionIndex>=0?e.selectedSuggestionIndex-1:e.selectedSuggestionIndex},selectTextSuggestionByIndex(e,t){e.selectedSuggestionIndex=t.payload},setTextSuggestions(e,t){if(e.selectedSuggestionIndex=-1,e.textSuggestions=t.payload,t.payload.length===0){e.mixedSuggestion=null;return}let n=e.text.substring(0,e.selection.end),r=w1(t.payload,n);e.mixedSuggestion=r!=null&&r.text.includes(n)?r:null},setMetrics(e,{payload:t}){e.metrics=t}},extraReducers:e=>{e.addCase(fe,t=>{t.mixedSuggestion=Zi.mixedSuggestion,t.textSuggestions=Zi.textSuggestions,t.selectedSuggestionIndex=Zi.selectedSuggestionIndex,t.metrics=Zi.metrics})}}),Ji=e=>e.input.text.substring(0,e.input.selection.end),cI=e=>e.input.selection,od=e=>{let{mixedSuggestion:t,selectedSuggestionIndex:n,textSuggestions:r}=e.input;return n>-1?r[n]:t},T1=()=>M(cI),{commitSuggestion:qn,offeredTextSuggestion:k1,registerCut:P1,registerKeyDown:R1,registerKeyUp:A1,registerPaste:L1,selectNextTextSuggestion:I1,selectPreviousTextSuggestion:O1,selectTextSuggestionByIndex:id,setInput:sd,setMetrics:N1,setSelection:ad,setTextSuggestions:Gn}=C1.actions,M1=C1.reducer;function dI(e){return e.replace(/(_\w)/g,t=>t[1].toUpperCase())}function re(e){return Array.isArray(e)?e.map(re):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>N(P({},t),{[dI(n)]:re(e[n])}),{}):e}function Zg(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function Oe(e){return Array.isArray(e)?e.map(Oe):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>N(P({},t),{[Zg(n)]:Oe(e[n])}),{}):e}var fI={agentInfo:void 0,agentSettings:{},visitorInfo:void 0,customData:void 0,fetchState:"idle"},za=e=>{var t,n,r;return{timezone:((t=e.info.visitorInfo)==null?void 0:t.visitorTimeZone)||Intl.DateTimeFormat().resolvedOptions().timeZone,agentName:((n=e.info.agentInfo)==null?void 0:n.agentNickname)||"",visitorName:((r=e.info.visitorInfo)==null?void 0:r.visitorName)||""}},Ua=K("info/setAgentInfo",(e,t)=>k(void 0,null,function*(){let{deepdeskAPI:n}=t.extra;if(!e.agentId&&!e.agentNickname)throw new Error("At least provide agentId or agentNickname");let r=yield n.client.get("/apis/admin/session/me/",{version:null}),o={};return r.external_id||(o.external_id=e.agentId),r.nickname||(o.nickname=e.agentNickname),!o.external_id&&!o.nickname?re(r):(yield n.client.patch("/apis/admin/session/me/",o,{version:null}),re(r))})),Jg=K("info/setAgentSettings",(e,t)=>k(void 0,null,function*(){let{deepdeskAPI:n}=t.extra,r=yield n.client.get("/apis/admin/session/me/",{version:null}),o=P(P({},typeof r.ui_config=="object"?r.ui_config:{}),e);return yield n.client.patch("/apis/admin/session/me/",{ui_config:o}),o})),eh=K("info/getAgentSettings",(e,t)=>k(void 0,null,function*(){let{deepdeskAPI:n}=t.extra;return(yield n.client.get("/apis/admin/session/me/",{version:null})).ui_config})),_1=e=>e.info.agentInfo,D1=e=>e.info.customData,F1=Q({name:"info",initialState:fI,reducers:{setVisitorInfo(e,t){e.visitorInfo=P(P({},e.visitorInfo),t.payload)},setCustomData(e,t){e.customData=t.payload}},extraReducers:e=>{e.addCase(Ua.pending,(t,n)=>{t.fetchState="loading",t.agentInfo=P(P({},t.agentInfo),n.meta.arg)}).addCase(Ua.rejected,t=>{t.fetchState="error"}).addCase(Ua.fulfilled,(t,n)=>{t.fetchState="done",t.agentInfo=N(P(P({},t.agentInfo),n.meta.arg),{agentDefaultLocale:n.payload.defaultLocale,agentId:n.payload.externalId||n.meta.arg.agentId||"",agentNickname:n.payload.nickname||n.meta.arg.agentNickname||""})}).addCase(Jg.fulfilled,(t,n)=>{t.agentSettings=n.payload}).addCase(eh.fulfilled,(t,n)=>{t.agentSettings=n.payload}).addCase(fe,t=>{t.visitorInfo=void 0})}}),{setVisitorInfo:H1,setCustomData:U1}=F1.actions,z1=F1.reducer;var ld={list:[],fetchState:"idle",isOpen:!1,page:"search",aggregates:{}},B1=e=>e.search.isOpen,j1=e=>e.search.page,V1=e=>e.search.list,K1=e=>e.search.aggregates;function W1(e,t=n=>n){return n=>n.search.list.filter(r=>r.type===e).map(t)}var Lo=K("search/getAll",(e,t)=>k(void 0,null,function*(){var a;let{deepdeskAPI:n}=t.extra,r=t.getState(),o=(a=r.conversation.current)==null?void 0:a.profileCode;if(!o)throw new Error("Profile should be provided in order to be able to search");let{results:i,aggregates:s}=yield n.search({profile:o,query:e.query,tags:e.tags,size:e.size,current:e.current,filters:{type:e.type},params:za(r)});return{results:i.map(l=>N(P({},l),{source:`search-${l.type.toLowerCase()}`,searchTerm:e.query})),aggregates:s}})),$1=Q({name:"search",initialState:ld,reducers:{setIsOpen(e,t){e.isOpen=t.payload},setPage(e,t){e.page=t.payload},resetSearch(e){e.fetchState=ld.fetchState,e.list=ld.list}},extraReducers:e=>{e.addCase(Lo.pending,t=>{t.fetchState="loading"}).addCase(Lo.rejected,(t,n)=>{t.fetchState="error",z.error(n.error)}).addCase(Lo.fulfilled,(t,n)=>{t.fetchState="done",t.list=n.payload.results,t.aggregates=n.payload.aggregates||{}}).addCase(fe,()=>ld)}}),{resetSearch:ud,setIsOpen:Ct,setPage:rn}=$1.actions,q1=$1.reducer;var th="SetCues",es="ShowLoginOverlay",Ba="UserLoggedIn",pI="UserLoggedOut",qr="ApplySuggestion",nh="ApplyImageSuggestion",mI="ShowCommandPalette",gI=e=>({[th]:t=>{e.dispatch(N(P({},t),{isBroadcasted:!0}))},[mI]:t=>{e.dispatch(Ct(t.isOpen)),t.page&&e.dispatch(rn(t.page))},[es]:t=>{e.dispatch(d1(t))},[Ba]:()=>{e.dispatch(Wn())},[pI]:()=>{e.dispatch(Wn())},[nh]:t=>{e.dispatch(rd({suggestion:t.suggestion}))},[qr]:t=>{e.dispatch(qn(N(P({},t),{eventMetrics:{inputType:"mouse"},replace:"selection"})))}}),G1=gI;var ja=w(H()),Y1=w(b()),X1=ja.default.createContext(null),Io=({broadcastEvents:e,children:t})=>{let n=ja.default.useMemo(()=>e,[]);return(0,Y1.jsx)(X1.Provider,{value:n,children:t})},Wt=()=>{let e=(0,ja.useContext)(X1);if(!e)throw new Error("You should use the useBroadcastEvents within a BroadcastEventsProvider");return e};var kd=w(ie()),sn=w(H());var bd=w(H());var rh=function(e,t){return rh=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[o]=r[o])},rh(e,t)};function Va(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");rh(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}var Tt=function(){return Tt=Object.assign||function(t){for(var n,r=1,o=arguments.length;r<o;r++){n=arguments[r];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t},Tt.apply(this,arguments)};function Q1(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]]);return n}function cd(e,t,n){if(n||arguments.length===2)for(var r=0,o=t.length,i;r<o;r++)(i||!(r in t))&&(i||(i=Array.prototype.slice.call(t,0,r)),i[r]=t[r]);return e.concat(i||Array.prototype.slice.call(t))}var dd;(function(e){e[e.EXPECT_ARGUMENT_CLOSING_BRACE=1]="EXPECT_ARGUMENT_CLOSING_BRACE",e[e.EMPTY_ARGUMENT=2]="EMPTY_ARGUMENT",e[e.MALFORMED_ARGUMENT=3]="MALFORMED_ARGUMENT",e[e.EXPECT_ARGUMENT_TYPE=4]="EXPECT_ARGUMENT_TYPE",e[e.INVALID_ARGUMENT_TYPE=5]="INVALID_ARGUMENT_TYPE",e[e.EXPECT_ARGUMENT_STYLE=6]="EXPECT_ARGUMENT_STYLE",e[e.INVALID_NUMBER_SKELETON=7]="INVALID_NUMBER_SKELETON",e[e.INVALID_DATE_TIME_SKELETON=8]="INVALID_DATE_TIME_SKELETON",e[e.EXPECT_NUMBER_SKELETON=9]="EXPECT_NUMBER_SKELETON",e[e.EXPECT_DATE_TIME_SKELETON=10]="EXPECT_DATE_TIME_SKELETON",e[e.UNCLOSED_QUOTE_IN_ARGUMENT_STYLE=11]="UNCLOSED_QUOTE_IN_ARGUMENT_STYLE",e[e.EXPECT_SELECT_ARGUMENT_OPTIONS=12]="EXPECT_SELECT_ARGUMENT_OPTIONS",e[e.EXPECT_PLURAL_ARGUMENT_OFFSET_VALUE=13]="EXPECT_PLURAL_ARGUMENT_OFFSET_VALUE",e[e.INVALID_PLURAL_ARGUMENT_OFFSET_VALUE=14]="INVALID_PLURAL_ARGUMENT_OFFSET_VALUE",e[e.EXPECT_SELECT_ARGUMENT_SELECTOR=15]="EXPECT_SELECT_ARGUMENT_SELECTOR",e[e.EXPECT_PLURAL_ARGUMENT_SELECTOR=16]="EXPECT_PLURAL_ARGUMENT_SELECTOR",e[e.EXPECT_SELECT_ARGUMENT_SELECTOR_FRAGMENT=17]="EXPECT_SELECT_ARGUMENT_SELECTOR_FRAGMENT",e[e.EXPECT_PLURAL_ARGUMENT_SELECTOR_FRAGMENT=18]="EXPECT_PLURAL_ARGUMENT_SELECTOR_FRAGMENT",e[e.INVALID_PLURAL_ARGUMENT_SELECTOR=19]="INVALID_PLURAL_ARGUMENT_SELECTOR",e[e.DUPLICATE_PLURAL_ARGUMENT_SELECTOR=20]="DUPLICATE_PLURAL_ARGUMENT_SELECTOR",e[e.DUPLICATE_SELECT_ARGUMENT_SELECTOR=21]="DUPLICATE_SELECT_ARGUMENT_SELECTOR",e[e.MISSING_OTHER_CLAUSE=22]="MISSING_OTHER_CLAUSE",e[e.INVALID_TAG=23]="INVALID_TAG",e[e.INVALID_TAG_NAME=25]="INVALID_TAG_NAME",e[e.UNMATCHED_CLOSING_TAG=26]="UNMATCHED_CLOSING_TAG",e[e.UNCLOSED_TAG=27]="UNCLOSED_TAG"})(dd||(dd={}));var fd=class{constructor(t){console.warn(`[vite-messages-plugin]: Message "${t}" was not precompiled. Did you use the correct extenstion *.messages.ts?`)}};var on;(function(e){e[e.literal=0]="literal",e[e.argument=1]="argument",e[e.number=2]="number",e[e.date=3]="date",e[e.time=4]="time",e[e.select=5]="select",e[e.plural=6]="plural",e[e.pound=7]="pound",e[e.tag=8]="tag"})(on||(on={}));var pd;(function(e){e[e.number=0]="number",e[e.dateTime=1]="dateTime"})(pd||(pd={}));function oh(e){return e.type===on.literal}function Z1(e){return e.type===on.argument}function md(e){return e.type===on.number}function gd(e){return e.type===on.date}function hd(e){return e.type===on.time}function yd(e){return e.type===on.select}function vd(e){return e.type===on.plural}function J1(e){return e.type===on.pound}function Sd(e){return e.type===on.tag}function wd(e){return!!(e&&typeof e=="object"&&e.type===pd.number)}function Ka(e){return!!(e&&typeof e=="object"&&e.type===pd.dateTime)}function ih(e){e.forEach(function(t){if(delete t.location,yd(t)||vd(t))for(var n in t.options)delete t.options[n].location,ih(t.options[n].value);else md(t)&&wd(t.style)||(gd(t)||hd(t))&&Ka(t.style)?delete t.style.location:Sd(t)&&ih(t.children)})}function eE(e,t){t===void 0&&(t={}),t=Tt({shouldParseSkeletons:!0,requiresOtherClause:!0},t);var n=new fd(e,t).parse();if(n.err){var r=SyntaxError(dd[n.err.kind]);throw r.location=n.err.location,r.originalMessage=n.err.message,r}return t!=null&&t.captureLocation||ih(n.val),n.val}function xd(e,t){var n=t&&t.cache?t.cache:xI,r=t&&t.serializer?t.serializer:wI,o=t&&t.strategy?t.strategy:yI;return o(e,{cache:n,serializer:r})}function hI(e){return e==null||typeof e=="number"||typeof e=="boolean"}function tE(e,t,n,r){var o=hI(r)?r:n(r),i=t.get(o);return typeof i=="undefined"&&(i=e.call(this,r),t.set(o,i)),i}function nE(e,t,n){var r=Array.prototype.slice.call(arguments,3),o=n(r),i=t.get(o);return typeof i=="undefined"&&(i=e.apply(this,r),t.set(o,i)),i}function sh(e,t,n,r,o){return n.bind(t,e,r,o)}function yI(e,t){var n=e.length===1?tE:nE;return sh(e,this,n,t.cache.create(),t.serializer)}function vI(e,t){return sh(e,this,nE,t.cache.create(),t.serializer)}function SI(e,t){return sh(e,this,tE,t.cache.create(),t.serializer)}var wI=function(){return JSON.stringify(arguments)};function ah(){this.cache=Object.create(null)}ah.prototype.get=function(e){return this.cache[e]};ah.prototype.set=function(e,t){this.cache[e]=t};var xI={create:function(){return new ah}},Ed={variadic:vI,monadic:SI};var Oo;(function(e){e.MISSING_VALUE="MISSING_VALUE",e.INVALID_VALUE="INVALID_VALUE",e.MISSING_INTL_API="MISSING_INTL_API"})(Oo||(Oo={}));var Wa=function(e){Va(t,e);function t(n,r,o){var i=e.call(this,n)||this;return i.code=r,i.originalMessage=o,i}return t.prototype.toString=function(){return"[formatjs Error: ".concat(this.code,"] ").concat(this.message)},t}(Error);var lh=function(e){Va(t,e);function t(n,r,o,i){return e.call(this,'Invalid values for "'.concat(n,'": "').concat(r,'". Options are "').concat(Object.keys(o).join('", "'),'"'),Oo.INVALID_VALUE,i)||this}return t}(Wa);var rE=function(e){Va(t,e);function t(n,r,o){return e.call(this,'Value for "'.concat(n,'" must be of type ').concat(r),Oo.INVALID_VALUE,o)||this}return t}(Wa);var oE=function(e){Va(t,e);function t(n,r){return e.call(this,'The intl string context variable "'.concat(n,'" was not provided to the string "').concat(r,'"'),Oo.MISSING_VALUE,r)||this}return t}(Wa);var et;(function(e){e[e.literal=0]="literal",e[e.object=1]="object"})(et||(et={}));function EI(e){return e.length<2?e:e.reduce(function(t,n){var r=t[t.length-1];return!r||r.type!==et.literal||n.type!==et.literal?t.push(n):r.value+=n.value,t},[])}function bI(e){return typeof e=="function"}function $a(e,t,n,r,o,i,s){if(e.length===1&&oh(e[0]))return[{type:et.literal,value:e[0].value}];for(var a=[],l=0,u=e;l<u.length;l++){var c=u[l];if(oh(c)){a.push({type:et.literal,value:c.value});continue}if(J1(c)){typeof i=="number"&&a.push({type:et.literal,value:n.getNumberFormat(t).format(i)});continue}var p=c.value;if(!(o&&p in o))throw new oE(p,s);var d=o[p];if(Z1(c)){(!d||typeof d=="string"||typeof d=="number")&&(d=typeof d=="string"||typeof d=="number"?String(d):""),a.push({type:typeof d=="string"?et.literal:et.object,value:d});continue}if(gd(c)){var g=typeof c.style=="string"?r.date[c.style]:Ka(c.style)?c.style.parsedOptions:void 0;a.push({type:et.literal,value:n.getDateTimeFormat(t,g).format(d)});continue}if(hd(c)){var g=typeof c.style=="string"?r.time[c.style]:Ka(c.style)?c.style.parsedOptions:r.time.medium;a.push({type:et.literal,value:n.getDateTimeFormat(t,g).format(d)});continue}if(md(c)){var g=typeof c.style=="string"?r.number[c.style]:wd(c.style)?c.style.parsedOptions:void 0;g&&g.scale&&(d=d*(g.scale||1)),a.push({type:et.literal,value:n.getNumberFormat(t,g).format(d)});continue}if(Sd(c)){var S=c.children,y=c.value,m=o[y];if(!bI(m))throw new rE(y,"function",s);var f=$a(S,t,n,r,o,i),h=m(f.map(function(T){return T.value}));Array.isArray(h)||(h=[h]),a.push.apply(a,h.map(function(T){return{type:typeof T=="string"?et.literal:et.object,value:T}}))}if(yd(c)){var v=c.options[d]||c.options.other;if(!v)throw new lh(c.value,d,Object.keys(c.options),s);a.push.apply(a,$a(v.value,t,n,r,o));continue}if(vd(c)){var v=c.options["=".concat(d)];if(!v){if(!Intl.PluralRules)throw new Wa(`Intl.PluralRules is not available in this environment.
|
|
14
14
|
Try polyfilling it using "@formatjs/intl-pluralrules"
|
|
15
15
|
`,Oo.MISSING_INTL_API,s);var x=n.getPluralRules(t,{type:c.pluralType}).select(d-(c.offset||0));v=c.options[x]||c.options.other}if(!v)throw new lh(c.value,d,Object.keys(c.options),s);a.push.apply(a,$a(v.value,t,n,r,o,d-(c.offset||0)));continue}}return EI(a)}function CI(e,t){return t?Tt(Tt(Tt({},e||{}),t||{}),Object.keys(e).reduce(function(n,r){return n[r]=Tt(Tt({},e[r]),t[r]||{}),n},{})):e}function TI(e,t){return t?Object.keys(e).reduce(function(n,r){return n[r]=CI(e[r],t[r]),n},Tt({},e)):e}function uh(e){return{create:function(){return{get:function(t){return e[t]},set:function(t,n){e[t]=n}}}}}function kI(e){return e===void 0&&(e={number:{},dateTime:{},pluralRules:{}}),{getNumberFormat:xd(function(){for(var t,n=[],r=0;r<arguments.length;r++)n[r]=arguments[r];return new((t=Intl.NumberFormat).bind.apply(t,cd([void 0],n,!1)))},{cache:uh(e.number),strategy:Ed.variadic}),getDateTimeFormat:xd(function(){for(var t,n=[],r=0;r<arguments.length;r++)n[r]=arguments[r];return new((t=Intl.DateTimeFormat).bind.apply(t,cd([void 0],n,!1)))},{cache:uh(e.dateTime),strategy:Ed.variadic}),getPluralRules:xd(function(){for(var t,n=[],r=0;r<arguments.length;r++)n[r]=arguments[r];return new((t=Intl.PluralRules).bind.apply(t,cd([void 0],n,!1)))},{cache:uh(e.pluralRules),strategy:Ed.variadic})}}var iE=function(){function e(t,n,r,o){n===void 0&&(n=e.defaultLocale);var i=this;if(this.formatterCache={number:{},dateTime:{},pluralRules:{}},this.format=function(u){var c=i.formatToParts(u);if(c.length===1)return c[0].value;var p=c.reduce(function(d,g){return!d.length||g.type!==et.literal||typeof d[d.length-1]!="string"?d.push(g.value):d[d.length-1]+=g.value,d},[]);return p.length<=1?p[0]||"":p},this.formatToParts=function(u){return $a(i.ast,i.locales,i.formatters,i.formats,u,void 0,i.message)},this.resolvedOptions=function(){var u;return{locale:((u=i.resolvedLocale)===null||u===void 0?void 0:u.toString())||Intl.NumberFormat.supportedLocalesOf(i.locales)[0]}},this.getAst=function(){return i.ast},this.locales=n,this.resolvedLocale=e.resolveLocale(n),typeof t=="string"){if(this.message=t,!e.__parse)throw new TypeError("IntlMessageFormat.__parse must be set to process `message` of type `string`");var s=o||{},a=s.formatters,l=Q1(s,["formatters"]);this.ast=e.__parse(t,Tt(Tt({},l),{locale:this.resolvedLocale}))}else this.ast=t;if(!Array.isArray(this.ast))throw new TypeError("A message must be provided as a String or AST.");this.formats=TI(e.formats,r),this.formatters=o&&o.formatters||kI(this.formatterCache)}return Object.defineProperty(e,"defaultLocale",{get:function(){return e.memoizedDefaultLocale||(e.memoizedDefaultLocale=new Intl.NumberFormat().resolvedOptions().locale),e.memoizedDefaultLocale},enumerable:!1,configurable:!0}),e.memoizedDefaultLocale=null,e.resolveLocale=function(t){if(typeof Intl.Locale!="undefined"){var n=Intl.NumberFormat.supportedLocalesOf(t);return n.length>0?new Intl.Locale(n[0]):new Intl.Locale(typeof t=="string"?t:t[0])}},e.__parse=eE,e.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"}}},e}();function PI(e,t){return t.split(".").reduce((n,r)=>n?n[r]:void 0,e)}var RI="dummy",ch=(0,bd.createContext)(null);function q(e){var r;let t=(0,bd.useContext)(ch);if(!t)throw new Error("useTranslator() may be used only in the context of a <LocaleContext> component.");let n=(r=e[t])!=null?r:{};return(o,i)=>{let s=PI(n,o);return s?new iE(s).format(i):(t!==RI&&console.warn(`${o} does not exist in messages of ${t}`),`[${o}]`)}}var Cd=w(H());var sE={root:"dd-tvkOF",content:"dd-eXA1D"};var dh=w(b()),AI=({isOpen:e,autoFocus:t,children:n,onClose:r,onBack:o,onKeyDown:i,overlayAriaLabel:s,contentAriaLabel:a})=>{let l=(0,Cd.useRef)(null),u=A("Dialog",sE),c=d=>{if(d.key==="Escape"){d.preventDefault(),d.stopPropagation(),o();return}i&&i(d)},p=d=>{d.target===l.current&&e&&r()};return(0,Cd.useEffect)(()=>{var d,g;!l.current||!e||!t||(g=(d=l.current)==null?void 0:d.querySelector("input, textarea"))==null||g.focus()},[e,t,l]),e?(0,dh.jsx)("div",{role:"dialog","data-testid":"dialog",className:u.root,"aria-label":s,ref:l,onKeyDown:c,onMouseDown:p,children:(0,dh.jsx)("div",{"data-testid":"dialog-content",className:u.content,"aria-label":a,children:n})}):null},Td=AI;var lE=w(ie());var aE={root:"dd-ranhW"};var uE=w(b()),LI=r=>{var o=r,{className:e,value:t}=o,n=te(o,["className","value"]);let i=A("TextInput",aE);return(0,uE.jsx)("input",P({className:(0,lE.default)(e,i.root),type:"text",value:t},n))},qa=LI;var fh={};$e(fh,{enUS:()=>II,nlNL:()=>OI});var II={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"}]},OI={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 cE={root:"dd-lWxnE",anchorButton:"dd-TZ4in",errorMessage:"dd-fIsPg",title:"dd-pGhJx",subtitle:"dd-f5l29",text:"dd-iamoD",input:"dd-uhQZ3",actions:"dd-lubvx",button:"dd-CJsNI",primaryButton:"dd-MWBfl"};var Ae=w(b());var NI=e=>{try{let t=new URL(e);return new URLSearchParams(t.search).get("token")||void 0}catch(t){return e}},MI=({agentEmail:e,isOpen:t,origin:n="",onSuccess:r,onDismiss:o})=>{let i=q(fh),s=A("LoginTokenDialog",cE),a=M(a1),l=X(),u=V("productName"),[c,p]=(0,sn.useState)(e||""),[d,g]=(0,sn.useState)(0),[S,y]=(0,sn.useState)(""),m=(0,sn.useCallback)(x=>k(void 0,null,function*(){x.preventDefault(),l(u1({email:c})),g(1)}),[n,c]),f=()=>{y(""),g(0)},h=(0,sn.useCallback)(x=>k(void 0,null,function*(){x.preventDefault();let T=NI(x.target.elements.token.value);if(!T){y(i("verifyCodeError",{login:v}));return}l(Fa({token:T}))}),[n]),v=(0,sn.useMemo)(()=>x=>(0,Ae.jsx)("button",{type:"button","data-testid":"login-token-dialog-back-button",className:s.anchorButton,onClick:f,children:x},"back-button"),[]);return(0,sn.useEffect)(()=>{a==="error"&&y(i("verifyCodeError",{login:v})),a==="done"&&r()},[a]),(0,Ae.jsx)(Td,{autoFocus:!0,isOpen:t,contentAriaLabel:i("promptTitle",{productName:u}),overlayAriaLabel:i("promptTitle",{productName:u}),onClose:o,onBack:o,children:(0,Ae.jsxs)("div",{className:s.root,children:[(0,Ae.jsx)("h1",{className:s.title,children:i("promptTitle",{productName:u})}),d===0&&(0,Ae.jsxs)("form",{onSubmit:m,children:[(0,Ae.jsx)("h2",{className:s.subtitle,children:i("requestCodeTitle")}),(0,Ae.jsx)("p",{className:s.text,children:i("requestCodeBody",{productName:u})}),(0,Ae.jsx)(qa,{className:s.input,name:"email",placeholder:i("requestCodeInputPlaceholder"),value:c,onChange:x=>p(x.target.value)}),(0,Ae.jsx)("div",{className:s.actions,children:(0,Ae.jsx)("button",{type:"submit",className:(0,kd.default)(s.button,s.primaryButton),children:i("requestCodeSubmitLabel")})})]}),d===1&&(0,Ae.jsxs)("form",{onSubmit:h,children:[(0,Ae.jsx)("h2",{className:s.subtitle,children:i("verifyCodeTitle")}),(0,Ae.jsx)("p",{className:s.text,children:i("verifyCodeBody")}),(0,Ae.jsx)(qa,{className:s.input,name:"token",placeholder:i("verifyCodeInputPlaceholder"),disabled:["loading","done"].includes(a)}),S&&(0,Ae.jsx)("div",{className:s.errorMessage,children:S}),(0,Ae.jsxs)("div",{className:s.actions,children:[(0,Ae.jsx)("button",{type:"button",className:(0,kd.default)(s.button),onClick:f,children:i("back")}),(0,Ae.jsx)("button",{type:"submit",className:(0,kd.default)(s.button,s.primaryButton),disabled:["loading","done"].includes(a),children:i("verifyCodeSubmitLabel")})]})]})]})})},dE=MI;var pE=w(b()),_I=()=>{let e=M(l1),t=M(_1),n=V("adminUrl"),r=Wt(),o=()=>r.send(es,!1),i=()=>{r.send(es,!1),r.send(Ba)};return(0,pE.jsx)(dE,{isOpen:e,agentEmail:t==null?void 0:t.agentEmail,origin:n,onDismiss:o,onSuccess:i})},fE=_I;var Rb=w(gh()),Pt=w(H());var JI={data:null,fetchState:"idle"},yE=e=>e.contentTypes.data,Ga=K("contentTypes/getContentTypes",(e,t)=>k(void 0,null,function*(){return t.extra.deepdeskAPI.getContentTypes()})),eO=Q({name:"contentTypes",initialState:JI,reducers:{},extraReducers:e=>{e.addCase(Ga.pending,t=>{t.fetchState="loading"}).addCase(Ga.rejected,t=>{t.fetchState="error"}).addCase(Ga.fulfilled,(t,n)=>{t.fetchState="done",t.data=n.payload})}}),vE=eO.reducer;function Xn(e){let t=document.createElement("textarea");t.value=e,t.style.position="fixed",t.style.left="-999999px",t.style.top="-999999px",document.body.appendChild(t),t.focus(),t.select(),document.execCommand("copy"),t.remove()}var Jn=w(H());var SE=w(H()),Pd=w(ie());var kt={root:"dd-U2SX4",list:"dd-cYTlj",listWrapper:"dd-GLQFR",listHorizontal:"dd-x-knl",page:"dd-1F4vk",search:"dd-nvbxc",pageNav:"dd-sRUuT",pageTitle:"dd-t-MKS",pageBackButton:"dd-cjptm",listHeader:"dd-Fg666",listHeading:"dd-w-xhJ",listMoreButton:"dd--mKep",listItem:"dd-wpvuA",listItemContent:"dd-V-mKo",listItemText:"dd-ukCHL",listItemDescription:"dd-sSyu4",listItemActions:"dd-xelho",truncate:"dd-IlopJ",lineClamp:"dd-Twaca",listItemTitle:"dd-lMGHq",listItemAction:"dd-xPLAs",listItemPrimaryAction:"dd-LdJ8w",listItemSelected:"dd-jFX0Y",sources:"dd-pZx4v",sourcesTitle:"dd-phYVd",source:"dd-DaR6h",sourceShowMore:"dd-M1-8j",icon:"dd-m6yxD",searchIcon:"dd-0AU-O",searchInputWrapper:"dd-DUFcE",searchInput:"dd-ukrlD",select:"dd--Tifv",selectType:"dd-IkZb2",selectWrapper:"dd-J14mx",image:"dd-RQgsB",imageSrc:"dd-jxh8F",imageSrcHidden:"dd-e20Jk",imageSrcStatus:"dd-j50Tt",imageTitle:"dd-qCjfW",actions:"dd-3mfWc",actionsWrapper:"dd-TjDyI",actionsBar:"dd-LiA35",actionButton:"dd-4wk0u",hasShortKeys:"dd-XilV-",actionShortcut:"dd-s4Mla",actionShortcutFixKerning:"dd-lyh5e"};var Yn={};$e(Yn,{enUS:()=>tO,nlNL:()=>nO});var tO={visitUrl:[{type:0,value:"Visit"}],back:[{type:0,value:"Back"}],loading:[{type:0,value:"Loading..."}],imageError:[{type:0,value:"Could not load image"}],showAll:[{type:0,value:"Show more"}],sources:[{type:0,value:"Sources"}],showMore:[{type:0,value:"Show "},{type:1,value:"amount"},{type:0,value:" more"}]},nO={visitUrl:[{type:0,value:"Bekijk"}],back:[{type:0,value:"Terug"}],loading:[{type:0,value:"Laden..."}],imageError:[{type:0,value:"Kan afbeelding niet laden"}],showAll:[{type:0,value:"Toon meer"}],sources:[{type:0,value:"Bronnen"}],showMore:[{type:0,value:"Toon "},{type:1,value:"amount"},{type:0,value:" meer"}]};var Gr=w(b()),rO=({src:e,title:t})=>{let n=A("CommandPalette",kt),[r,o]=(0,SE.useState)("loading"),i=q(Yn);return(0,Gr.jsxs)("div",{className:n.image,children:[(0,Gr.jsx)("img",{src:e,alt:t,onLoad:()=>o("done"),onError:()=>o("error"),className:(0,Pd.default)(n.imageSrc,{[n.imageSrcHidden]:["loading","error"].includes(r)})}),r==="loading"&&(0,Gr.jsx)("span",{className:(0,Pd.default)(n.imageSrc,n.imageSrcStatus),children:i("loading")}),r==="error"&&(0,Gr.jsx)("span",{className:(0,Pd.default)(n.imageSrc,n.imageSrcStatus),children:(0,Gr.jsx)(ql,{})}),t&&(0,Gr.jsx)("span",{className:n.imageTitle,children:t})]})},wE=rO;var xE=w(H()),EE=w(ie());var No=w(b());function hh({children:e,heading:t,orientation:n,hasMore:r,onShowAll:o}){let i=q(Yn),s=A("CommandPalette",kt);return xE.default.Children.count(e)===0?null:(0,No.jsxs)("div",{"data-testid":"commandpalette-list",className:s.list,children:[(t||r)&&(0,No.jsxs)("div",{className:s.listHeader,children:[t&&(0,No.jsx)("h4",{className:s.listHeading,children:t}),r&&o&&(0,No.jsx)("button",{onClick:o,className:s.listMoreButton,type:"button",children:i("showAll")})]}),(0,No.jsx)("div",{className:(0,EE.default)(s.listWrapper,n==="horizontal"&&s.listHorizontal),children:e})]})}var rs=w(ie());var Rd=w(H());function Xa(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var le=1,vh=2,Sh=4,Ne=8,Ad=16,Ya=32,an=64,yh={a:{content:le|Ne,self:!1,type:le|Ne|Ya|an},address:{invalid:["h1","h2","h3","h4","h5","h6","address","article","aside","section","div","header","footer"],self:!1},audio:{children:["track","source"]},br:{type:le|Ne,void:!0},body:{content:le|vh|Sh|Ne|Ad|Ya|an},button:{content:Ne,type:le|Ne|Ya|an},caption:{content:le,parent:["table"]},col:{parent:["colgroup"],void:!0},colgroup:{children:["col"],parent:["table"]},details:{children:["summary"],type:le|Ya|an},dd:{content:le,parent:["dl"]},dl:{children:["dt","dd"],type:le},dt:{content:le,invalid:["footer","header"],parent:["dl"]},figcaption:{content:le,parent:["figure"]},footer:{invalid:["footer","header"]},header:{invalid:["footer","header"]},hr:{type:le,void:!0},img:{void:!0},li:{content:le,parent:["ul","ol","menu"]},main:{self:!1},ol:{children:["li"],type:le},picture:{children:["source","img"],type:le|Ne|Ad},rb:{parent:["ruby","rtc"]},rp:{parent:["ruby","rtc"]},rt:{content:Ne,parent:["ruby","rtc"]},rtc:{content:Ne,parent:["ruby"]},ruby:{children:["rb","rp","rt","rtc"]},source:{parent:["audio","video","picture"],void:!0},summary:{content:Ne,parent:["details"]},table:{children:["caption","colgroup","thead","tbody","tfoot","tr"],type:le},tbody:{parent:["table"],children:["tr"]},td:{content:le,parent:["tr"]},tfoot:{parent:["table"],children:["tr"]},th:{content:le,parent:["tr"]},thead:{parent:["table"],children:["tr"]},tr:{parent:["table","tbody","thead","tfoot"],children:["th","td"]},track:{parent:["audio","video"],void:!0},ul:{children:["li"],type:le},video:{children:["track","source"]},wbr:{type:le|Ne,void:!0}};function _o(e){return t=>{yh[t]=P(P({},e),yh[t])}}["address","main","div","figure","p","pre"].forEach(_o({content:le,type:le|an}));["abbr","b","bdi","bdo","cite","code","data","dfn","em","i","kbd","mark","q","ruby","samp","strong","sub","sup","time","u","var"].forEach(_o({content:Ne,type:le|Ne|an}));["p","pre"].forEach(_o({content:Ne,type:le|an}));["s","small","span","del","ins"].forEach(_o({content:Ne,type:le|Ne}));["article","aside","footer","header","nav","section","blockquote"].forEach(_o({content:le,type:le|vh|an}));["h1","h2","h3","h4","h5","h6"].forEach(_o({content:Ne,type:le|Sh|an}));["audio","canvas","iframe","img","video"].forEach(_o({type:le|Ne|Ad|an}));var Za=Object.freeze(yh),wh=["applet","base","body","command","embed","frame","frameset","head","html","link","meta","noscript","object","script","style","title"],xh=Object.keys(Za).filter(e=>e!=="canvas"&&e!=="iframe"),pe=1,Eh=2,Mo=3,Xr=4,Id=5,Od=Object.freeze({alt:pe,cite:pe,class:pe,colspan:Mo,controls:Xr,datetime:pe,default:Xr,disabled:Xr,dir:pe,height:pe,href:pe,id:pe,kind:pe,label:pe,lang:pe,loading:pe,loop:Xr,media:pe,muted:Xr,poster:pe,rel:pe,role:pe,rowspan:Mo,scope:pe,sizes:pe,span:Mo,start:Mo,style:Id,src:pe,srclang:pe,srcset:pe,tabindex:pe,target:pe,title:pe,type:pe,width:pe}),bh=Object.freeze({class:"className",colspan:"colSpan",datetime:"dateTime",rowspan:"rowSpan",srclang:"srcLang",srcset:"srcSet",tabindex:"tabIndex"});function Ld(){return Ld=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},Ld.apply(this,arguments)}function Nd({attributes:e={},className:t,children:n=null,selfClose:r=!1,tagName:o}){let i=o;return r?Rd.default.createElement(i,Ld({className:t},e)):Rd.default.createElement(i,Ld({className:t},e),n)}var Qa=class{attribute(t,n){return n}node(t,n){return n}};function bE(e,t,n,r=!1){let o=e.match(t instanceof RegExp?t:new RegExp(t,"i"));return o?N(P({match:o[0],void:r},n(o)),{index:o.index,length:o[0].length,valid:!0}):null}var Qn=class{constructor(t,n,r){Xa(this,"greedy",!1),Xa(this,"options",void 0),Xa(this,"propName",void 0),Xa(this,"inverseName",void 0),Xa(this,"factory",void 0),this.options=P({},n),this.propName=t,this.inverseName=`no${t.charAt(0).toUpperCase()+t.slice(1)}`,this.factory=r!=null?r:null}createElement(t,n){return this.factory?Rd.default.createElement(this.factory,n,t):this.replaceWith(t,n)}doMatch(t,n,r,o=!1){return bE(t,n,r,o)}onBeforeParse(t,n){return t}onAfterParse(t,n){return t}};var Do=w(H()),PE=w(TE());function Zn(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var sO=/(url|image|image-set)\(/i,Ch=class extends Qa{attribute(t,n){return t==="style"&&Object.keys(n).forEach(r=>{String(n[r]).match(sO)&&delete n[r]}),n}},kE=1,aO=3,lO=/^<(!doctype|(html|head|body)(\s|>))/i,uO=/^(aria-|data-|\w+:)/iu,cO=/{{{(\w+)\/?}}}/;function dO(){if(!(typeof window=="undefined"||typeof document=="undefined"))return document.implementation.createHTMLDocument("Interweave")}var Md=class{constructor(t,n={},r=[],o=[]){var i;Zn(this,"allowed",void 0),Zn(this,"banned",void 0),Zn(this,"blocked",void 0),Zn(this,"container",void 0),Zn(this,"content",[]),Zn(this,"props",void 0),Zn(this,"matchers",void 0),Zn(this,"filters",void 0),Zn(this,"keyIndex",void 0),this.props=n,this.matchers=r,this.filters=[...o,new Ch],this.keyIndex=-1,this.container=this.createContainer(t||""),this.allowed=new Set((i=n.allowList)!==null&&i!==void 0?i:xh),this.banned=new Set(wh),this.blocked=new Set(n.blockList)}applyAttributeFilters(t,n){return this.filters.reduce((r,o)=>r!==null&&typeof o.attribute=="function"?o.attribute(t,r):r,n)}applyNodeFilters(t,n){return this.filters.reduce((r,o)=>r!==null&&typeof o.node=="function"?o.node(t,r):r,n)}applyMatchers(t,n){let r={},{props:o}=this,i=t,s=0,a=null;return this.matchers.forEach(l=>{let u=l.asTag().toLowerCase(),c=this.getTagConfig(u);if(o[l.inverseName]||!this.isTagAllowed(u)||!this.canRenderChild(n,c))return;let p="";for(;i&&(a=l.match(i));){let d=a,{index:g,length:S,match:y,valid:m,void:f}=d,h=te(d,["index","length","match","valid","void"]),v=l.propName+String(s);g>0&&(p+=i.slice(0,g)),m?(p+=f?`{{{${v}/}}}`:`{{{${v}}}}${y}{{{/${v}}}}`,this.keyIndex+=1,s+=1,r[v]={children:y,matcher:l,props:N(P(P({},o),h),{key:this.keyIndex})}):p+=y,l.greedy?(i=p+i.slice(g+S),p=""):i=i.slice(g+(S||y.length))}l.greedy||(i=p+i)}),s===0?t:this.replaceTokens(i,r)}canRenderChild(t,n){return!t.tagName||!n.tagName||t.void?!1:t.children.length>0?t.children.includes(n.tagName):t.invalid.length>0&&t.invalid.includes(n.tagName)?!1:n.parent.length>0?n.parent.includes(t.tagName):!t.self&&t.tagName===n.tagName?!1:!!(t&&t.content&n.type)}convertLineBreaks(t){let{noHtml:n,disableLineBreaks:r}=this.props;if(n||r||t.match(/<((?:\/[ a-z]+)|(?:[ a-z]+\/))>/gi))return t;let o=t.replace(/\r\n/g,`
|
|
16
16
|
`);return o=o.replace(/\n{3,}/g,`
|
|
@@ -24,7 +24,7 @@ Try polyfilling it using "@formatjs/intl-pluralrules"
|
|
|
24
24
|
`+ct),Qt&&vf([G,Z,se],lo=>{ct=vl(ct,lo," ")}),v&&Hl?v.createHTML(ct):ct},t.setConfig=function(){let j=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Ff(j),Dl=!0},t.clearConfig=function(){ni=null,Dl=!1},t.isValidAttribute=function(j,E,I){ni||Ff({});let U=De(j),me=De(E);return Yy(U,me,I)},t.addHook=function(j,E){typeof E=="function"&&(D[j]=D[j]||[],yl(D[j],E))},t.removeHook=function(j){if(D[j])return fT(D[j])},t.removeHooks=function(j){D[j]&&(D[j]=[])},t.removeAllHooks=function(){D={}},t}var bT=ET();var ro=w(H());var TM={"":["<em>","</em>"],_:["<strong>","</strong>"],"*":["<strong>","</strong>"],"~":["<s>","</s>"],"\n":["<br />"]," ":["<br />"],"-":["<hr />"]};function CT(e){return e.replace(RegExp("^"+(e.match(/^(\t| )+/)||"")[0],"gm"),"")}function wl(e){return(e+"").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function xl(e,t){var n,r,o,i,s,a=/((?:^|\n+)(?:\n---+|\* \*(?: \*)+)\n)|(?:^``` *(\w*)\n([\s\S]*?)\n```$)|((?:(?:^|\n+)(?:\t| {2,}).+)+\n*)|((?:(?:^|\n)([>*+-]|\d+\.)\s+.*)+)|(?:!\[([^\]]*?)\]\(([^)]+?)\))|(\[)|(\](?:\(([^)]+?)\))?)|(?:(?:^|\n+)([^\s].*)\n(-{3,}|={3,})(?:\n+|$))|(?:(?:^|\n+)(#{1,6})\s*(.+)(?:\n+|$))|(?:`([^`].*?)`)|( \n\n*|\n{2,}|__|\*\*|[_*]|~~)/gm,l=[],u="",c=t||{},p=0;function d(S){var y=TM[S[1]||""],m=l[l.length-1]==S;return y?y[1]?(m?l.pop():l.push(S),y[0|m]):y[0]:S}function g(){for(var S="";l.length;)S+=d(l[l.length-1]);return S}for(e=e.replace(/^\[(.+?)\]:\s*(.+)$/gm,function(S,y,m){return c[y.toLowerCase()]=m,""}).replace(/^\n+|\n+$/g,"");o=a.exec(e);)r=e.substring(p,o.index),p=a.lastIndex,n=o[0],r.match(/[^\\](\\\\)*\\$/)||((s=o[3]||o[4])?n='<pre class="code '+(o[4]?"poetry":o[2].toLowerCase())+'"><code'+(o[2]?' class="language-'+o[2].toLowerCase()+'"':"")+">"+CT(wl(s).replace(/^\n+|\n+$/g,""))+"</code></pre>":(s=o[6])?(s.match(/\./)&&(o[5]=o[5].replace(/^\d+/gm,"")),i=xl(CT(o[5].replace(/^\s*[>*+.-]/gm,""))),s==">"?s="blockquote":(s=s.match(/\./)?"ol":"ul",i=i.replace(/^(.*)(\n|$)/gm,"<li>$1</li>")),n="<"+s+">"+i+"</"+s+">"):o[8]?n='<img src="'+wl(o[8])+'" alt="'+wl(o[7])+'">':o[10]?(u=u.replace("<a>",'<a href="'+wl(o[11]||c[r.toLowerCase()])+'">'),n=g()+"</a>"):o[9]?n="<a>":o[12]||o[14]?n="<"+(s="h"+(o[14]?o[14].length:o[13]>"="?1:2))+">"+xl(o[12]||o[15],c)+"</"+s+">":o[16]?n="<code>"+wl(o[16])+"</code>":(o[17]||o[1])&&(n=d(o[17]||"--"))),u+=r,u+=n;return(u+e.substring(p)+g()).replace(/^\n+|\n+$/g,"")}var TT={root:"dd-L7b3z",popover:"dd-OQOTB",options:"dd-Y12RE",arrow:"dd-cv33T",copyIcon:"dd-6xOsH",option:"dd-9oFX4",divider:"dd-aiZf8",fadeup:"dd-Jq9pd"};var An=w(b());function kM(e){return`<button type="button" class=${e}><svg version="1.1" x="0px" y="0px" viewBox="0 0 115.77 122.88" width="10px" height="10px" fill="black"><g><path d="M89.62,13.96v7.73h12.19h0.01v0.02c3.85,0.01,7.34,1.57,9.86,4.1c2.5,2.51,4.06,5.98,4.07,9.82h0.02v0.02 v73.27v0.01h-0.02c-0.01,3.84-1.57,7.33-4.1,9.86c-2.51,2.5-5.98,4.06-9.82,4.07v0.02h-0.02h-61.7H40.1v-0.02 c-3.84-0.01-7.34-1.57-9.86-4.1c-2.5-2.51-4.06-5.98-4.07-9.82h-0.02v-0.02V92.51H13.96h-0.01v-0.02c-3.84-0.01-7.34-1.57-9.86-4.1 c-2.5-2.51-4.06-5.98-4.07-9.82H0v-0.02V13.96v-0.01h0.02c0.01-3.85,1.58-7.34,4.1-9.86c2.51-2.5,5.98-4.06,9.82-4.07V0h0.02h61.7 h0.01v0.02c3.85,0.01,7.34,1.57,9.86,4.1c2.5,2.51,4.06,5.98,4.07,9.82h0.02V13.96L89.62,13.96z M79.04,21.69v-7.73v-0.02h0.02 c0-0.91-0.39-1.75-1.01-2.37c-0.61-0.61-1.46-1-2.37-1v0.02h-0.01h-61.7h-0.02v-0.02c-0.91,0-1.75,0.39-2.37,1.01 c-0.61,0.61-1,1.46-1,2.37h0.02v0.01v64.59v0.02h-0.02c0,0.91,0.39,1.75,1.01,2.37c0.61,0.61,1.46,1,2.37,1v-0.02h0.01h12.19V35.65 v-0.01h0.02c0.01-3.85,1.58-7.34,4.1-9.86c2.51-2.5,5.98-4.06,9.82-4.07v-0.02h0.02H79.04L79.04,21.69z M105.18,108.92V35.65v-0.02 h0.02c0-0.91-0.39-1.75-1.01-2.37c-0.61-0.61-1.46-1-2.37-1v0.02h-0.01h-61.7h-0.02v-0.02c-0.91,0-1.75,0.39-2.37,1.01 c-0.61,0.61-1,1.46-1,2.37h0.02v0.01v73.27v0.02h-0.02c0,0.91,0.39,1.75,1.01,2.37c0.61,0.61,1.46,1,2.37,1v-0.02h0.01h61.7h0.02 v0.02c0.91,0,1.75-0.39,2.37-1.01c0.61-0.61,1-1.46,1-2.37h-0.02V108.92L105.18,108.92z"/></g></svg></button>`}function xy(e){var n;let t=e.cloneNode(!0);return t.querySelectorAll("div,button").forEach(r=>r.remove()),(n=t.textContent)!=null?n:""}function PM(e){return e.replace(/\r\n/g,`
|
|
25
25
|
`)}var RM=({content:e,useLabel:t,copyLabel:n,onCopy:r,onUse:o})=>{let i=A("Markdown",TT),s=(0,ro.useRef)(null),[a,l]=(0,ro.useState)(null),u=(0,ro.useMemo)(()=>{let y=xl(PM(e));return bT.sanitize(y).replace(/<\/code>/g,`${kM(i.copyIcon)}</code>`)},[e]),c=y=>{var h;let m=y.target,f=!!((h=s.current)!=null&&h.querySelector("code"));a||f&&m.tagName!=="CODE"||!f&&m!==s.current||(m.addEventListener("mouseleave",()=>l(null),{once:!0}),l(m))},p=()=>{if(!a)return;l(null);let y=a.querySelector("button");y&&(ss(y,i.fadeup),r(xy(a)))},d=y=>{y.target.tagName.toLowerCase()==="button"&&(ss(y.target,i.fadeup),r(xy(y.target.parentElement)))},g=()=>{a&&(l(null),o(xy(a)))},S=y=>{if(y===null)return;let m=y.getBoundingClientRect();m.left<0?y.style.transform=`translateX(${-m.left+2}px)`:m.right>window.innerWidth&&(y.style.transform=`translateX(${window.innerWidth-m.right-2}px)`)};return(0,An.jsxs)(ro.Fragment,{children:[a&&(0,An.jsxs)(ys,{triggerRef:{current:a},className:i.popover,parentNode:a,children:[(0,An.jsxs)("div",{className:i.options,ref:S,children:[(0,An.jsx)("button",{type:"button",className:i.option,onClick:p,children:n}),(0,An.jsx)("div",{className:i.divider}),(0,An.jsx)("button",{type:"button",className:i.option,onClick:g,children:t})]}),(0,An.jsx)("div",{className:i.arrow})]}),(0,An.jsx)("div",{ref:s,className:i.root,dangerouslySetInnerHTML:{__html:u},onMouseOver:c,onClick:d})]})},kT=RM;var Ey={};$e(Ey,{enUS:()=>AM,nlNL:()=>LM});var AM={useCue:[{type:0,value:"Add to message"}],copyCue:[{type:0,value:"Copy"}],removeCue:[{type:0,value:"Close"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}]},LM={useCue:[{type:0,value:"Voeg toe aan bericht"}],copyCue:[{type:0,value:"Kopi\xEBren"}],removeCue:[{type:0,value:"Sluiten"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}]};var PT={title:"dd-YBHrC",fadeup:"dd-cRM0K",fadedown:"dd-7D4Pq",selected:"dd-bueui",thumbsUp:"dd-6QwVx",thumbsDown:"dd-d3E8l"};var mn=w(b()),IM=({cue:e,onRemove:t,onCopy:n,onUse:r})=>{let o=A("WidgetCue",PT),i=q(Ey),s=as(),a=c=>{n&&n(c,e)},l=c=>{r&&r(c,e)},u=c=>{c.preventDefault(),c.stopPropagation(),t(e)};return(0,RT.useEffect)(()=>{s("Assistant response displayed",{name:e.rule.name,description:e.rule.description,group:e.rule.label,cueText:e.text})},[]),(0,mn.jsxs)(oe,{"data-testid":"cue",children:[(0,mn.jsx)(ye,{children:(0,mn.jsxs)(ye.Content,{children:[e.title&&(0,mn.jsx)(ye.Title,{className:o.title,"data-testid":"widget-cue-title",children:e.title}),(0,mn.jsx)(kT,{content:e.text,useLabel:i("useCue"),copyLabel:i("copyCue"),onCopy:a,onUse:l})]})}),(0,mn.jsxs)(oe.IconButtonContainer,{children:[(0,mn.jsx)(us,{eventName:"Assistant response feedback",eventData:{name:e.rule.name,group:e.rule.label,description:e.rule.description,cueText:e.text},feedbackText:e.text,feedbackType:"assistant"}),(0,mn.jsx)(oe.IconButton,{title:i("removeCue"),onClick:u,icon:(0,mn.jsx)(cT,{})})]})]})},AT=IM;var El=w(b()),OM=({cues:e})=>{let t=X(),n=Wt(),r=as(),o=a=>{t(WC({id:a.rule.id})),r("Assistant response closed",{name:a.rule.name,group:a.rule.label,description:a.rule.description,cueText:a.text})},i=(a,l)=>{Xn(a),r("Assistant response copied",{name:l.rule.name,group:l.rule.label,description:l.rule.description,copiedText:a})},s=(a,l)=>{n.send(qr,{text:a,suggestion:{source:"cue",sourceText:a}}),r("Assistant response used",{name:l.rule.name,group:l.rule.label,description:l.rule.description,usedText:a})};return(0,El.jsx)(El.Fragment,{children:e.map(a=>(0,El.jsx)(AT,{cue:a,onRemove:o,onCopy:i,onUse:s},a.rule.id))})},LT=OM;var Ef=w(H());var IT={root:"dd-cvTAY",label:"dd-QWQxD",value:"dd-WSUHF",copyButton:"dd-67o9H",isTrue:"dd--1g2O",isFalse:"dd-sz2ir"};var gn=w(b());function NM(e,t){return t.split(".").reduce((n,r)=>!n||typeof n!="object"||!(r in n)?null:n[r],e)}var OT=({data:e,schema:t})=>{let n=A("WidgetCustomData",IT),r=o=>{Xn(o)};return(0,Ef.useEffect)(()=>{z.info("Custom data",e,t)},[e]),(0,gn.jsx)("dl",{className:n.root,children:t.map(o=>{let i=NM(e,o.path);return(0,gn.jsxs)(Ef.Fragment,{children:[(0,gn.jsx)("dt",{className:n.label,children:o.label}),(0,gn.jsx)("dd",{className:n.value,children:o.type==="boolean"&&i?(0,gn.jsx)("span",{className:n.isTrue,children:o.trueValue}):o.type==="boolean"&&!i?(0,gn.jsx)("span",{className:n.isFalse,children:o.falseValue}):i?(0,gn.jsxs)("button",{type:"button",onClick:()=>r(i),className:n.copyButton,children:[(0,gn.jsx)("span",{children:i}),(0,gn.jsx)(gl,{})]}):"-"})]},o.label)})})};var MT=w(H());var MM=/(https?:\/\/[^\s]+)/,NT=e=>e.split(" ").find(t=>MM.test(t));var Xt=w(b()),_M=({suggestion:e,lines:t,onUse:n})=>{var c;let r=e.text||e.url||e.message,o=NT(r),i=q(Bo),s=V("showImages"),a=V("fallbackImage"),l=p=>{p.preventDefault(),p.stopPropagation(),n(r)},u=(0,MT.useCallback)(p=>{window.open(o,"_blank"),p.stopPropagation(),p.preventDefault()},[o]);return(0,Xt.jsxs)(oe,{onClick:l,"data-testid":"edit-suggestion",children:[(0,Xt.jsxs)(ye,{children:[s&&e.image&&(0,Xt.jsx)(ye.Image,{src:df(e,"small",a||void 0),title:e.title}),(0,Xt.jsxs)(ye.Content,{children:[e.title&&(0,Xt.jsx)(ye.Title,{"data-testid":"widget-suggestion-title",children:e.title}),e.searchKeywords&&((c=e.searchKeywords)==null?void 0:c.length)>0&&(0,Xt.jsx)(oe.Labels,{labels:e.searchKeywords}),(0,Xt.jsx)(ye.Content,{cropText:t==="single",lineClamp:t==="multiple",children:r})]})]}),(0,Xt.jsxs)(oe.Actions,{children:[o&&(0,Xt.jsx)(oe.ActionButton,{onClick:u,label:i("visitUrl")}),(0,Xt.jsx)(oe.ActionButton,{primary:!0,onClick:l,label:i("useSuggestion")})]})]})},_T=_M;var bl=w(b()),DM=({lines:e,suggestions:t})=>{let n=Wt(),r=(o,i)=>{n.send(qr,{text:o,suggestion:N(P({},i),{source:i.source,sourceText:i.text})})};return(0,bl.jsx)(bl.Fragment,{children:t.map(o=>(0,bl.jsx)(_T,{suggestion:o,lines:e,onUse:i=>r(i,o)},o.text||o.url||o.message))})},DT=DM;var Cl={};$e(Cl,{enUS:()=>FM,nlNL:()=>HM});var FM={waiting:[{type:0,value:"Loading\u2026"}],notSupported:[{type:0,value:"This conversation is not supported"}],noResults:[{type:0,value:"No results found\u2026"}],titleAutoflows:[{type:0,value:"Autoflows"}],titleCustomMessages:[{type:0,value:"Quick replies"}],titleCues:[{type:0,value:"Assistant updates"}],actions:[{type:0,value:"Shortcuts"}],linkStudioLogin:[{type:0,value:"My "},{type:1,value:"productName"}],linkSummary:[{type:0,value:"Summarize"}],linkKnowledgeSearch:[{type:0,value:"Knowledge Assist"}],linkSearch:[{type:0,value:"Search"}]},HM={waiting:[{type:0,value:"Laden\u2026"}],notSupported:[{type:0,value:"Dit gesprek wordt niet ondersteund"}],noResults:[{type:0,value:"Geen resultaten gevonden\u2026"}],titleAutoflows:[{type:0,value:"Autoflows"}],titleCustomMessages:[{type:0,value:"Quick replies"}],titleCues:[{type:0,value:"Assistant updates"}],actions:[{type:0,value:"Shortcuts"}],linkStudioLogin:[{type:0,value:"Mijn "},{type:1,value:"productName"}],linkSummary:[{type:0,value:"Gesprek samenvatten"}],linkKnowledgeSearch:[{type:0,value:"Knowledge assist"}],linkSearch:[{type:0,value:"Zoeken"}]};var Tl={root:"dd-W9VCG",loginText:"dd--dS6t",stateText:"dd-348OC",sectionList:"dd-bF9pF",shortcutList:"dd-MuKK-",shortcut:"dd-5CnK9",link:"dd-DRo0x"};var $=w(b()),bf=(e,t)=>{let n=M(rt);(0,kl.useEffect)(()=>n?t.every(r=>!!r)?e():()=>{}:()=>{},[...t,n])},UM=({onLogIn:e})=>{let t=A("Widget",Tl),n=V("isEmbedded"),r=V("adminUrl");return(0,$.jsx)("div",{className:t.loginText,children:(0,$.jsx)("div",{children:(0,$.jsx)(Qd,{isEmbedded:n,loginUrl:r,onLogIn:e})})},"login")},FT=({text:e})=>{let t=A("Widget",Tl);return(0,$.jsx)("div",{className:t.stateText,children:(0,$.jsx)("div",{children:(0,$.jsx)("p",{children:e})})},"notification")},zM=()=>{let e=q(Cl),t=X(),n=A("Widget",Tl),r=V("showSearch"),o=V("showSummaryCommand"),i=V("showKnowledgeSearch"),s=M(ls("/admin/")),a=Wt(),l=V("productName"),u=r||o||i||s;return bf(()=>(t(oy()),()=>{t(zC())}),[t]),u?(0,$.jsx)(yn,{title:e("actions"),type:"shortcuts",children:(0,$.jsxs)("div",{className:n.shortcutList,children:[r&&(0,$.jsxs)("button",{type:"button",className:n.shortcut,"data-testid":"shortcut-search","aria-label":e("linkSearch"),onClick:()=>a.send("ShowCommandPalette",{isOpen:!0}),children:[(0,$.jsx)(os,{}),e("linkSearch")]}),o&&(0,$.jsxs)("button",{type:"button",className:n.shortcut,"data-testid":"shortcut-summary","aria-label":e("linkSummary"),onClick:()=>a.send("ShowCommandPalette",{isOpen:!0,page:"summary"}),children:[(0,$.jsx)(uT,{}),e("linkSummary")]}),i&&(0,$.jsxs)("button",{type:"button",className:n.shortcut,"data-testid":"shortcut-knowledge-assist","aria-label":e("linkKnowledgeSearch"),onClick:()=>a.send("ShowCommandPalette",{isOpen:!0,page:"knowledgeAssist"}),children:[(0,$.jsx)(lT,{}),e("linkKnowledgeSearch")]}),s&&(0,$.jsxs)("a",{className:n.shortcut,target:"_blank",href:s,"data-testid":"shortcut-studio-login","aria-label":e("linkStudioLogin",{productName:l}),rel:"noreferrer",children:[(0,$.jsx)(aT,{}),e("linkStudioLogin",{productName:l})]})]})}):null},BM=()=>{let e=X(),t=V("showCustomMessages"),n=M(IC),r=M(Yi);return bf(()=>(e(ml(r)),e(DC(r)),()=>{e(FC(r))}),[e,t,r]),!t||n.length===0?null:(0,$.jsx)(yn,{type:"custom-messages","data-testid":"custom-messages",children:(0,$.jsx)(mt,{withDivider:!0,children:n.map(o=>(0,$.jsx)(oT,{suggestion:o},o.text))})})},jM=()=>{let e=q(Cl),t=X(),n=V("showAutoflows"),r=M(kC),o=M(Yi);return bf(()=>(t(ur(o)),t(PC(o)),()=>{t(RC(o))}),[t,n,o]),!n||r.length===0?null:(0,$.jsx)(yn,{type:"autoflows",title:e("titleAutoflows"),"data-testid":"autoflows",children:(0,$.jsx)(mt,{withDivider:!0,children:(0,$.jsx)(nT,{})})})},VM=()=>{let e=X(),t=M(zd),n=M(db),r=M(VC),o=M(D1),i=M(Hd),s=M(Bd),a=M(rr),l=M($r);return(0,kl.useEffect)(()=>{!!o&&!n&&z.warn("Custom data provided, but no schema.")},[o,n]),bf(()=>{t.forEach(({type:u})=>{u==="entities"?e(un()):tu.includes(u)||e(dn(u))})},[e,l,a]),(0,$.jsx)(kl.Fragment,{children:t.map(({type:u,title:c,amount:p,lines:d,schema:g})=>{var S,y;switch(u){case"entities":return i&&i.length>0&&(0,$.jsx)(yn,{type:u,title:c,"data-testid":`type-${u}`,children:(0,$.jsx)(sT,{entities:i})},u);case"cues":return r&&r.length>0&&(0,$.jsx)(yn,{type:u,title:c,"data-testid":`type-${u}`,children:(0,$.jsx)(mt,{withDivider:!0,children:(0,$.jsx)(LT,{cues:r})})},u);case"custom-data":return o&&g&&(0,$.jsx)(yn,{type:u,title:c,"data-testid":`type-${u}`,children:(0,$.jsx)(mt,{withDivider:!0,children:(0,$.jsx)(OT,{data:o,schema:g})})},u);default:return((y=(S=s[u])==null?void 0:S.suggestions)==null?void 0:y.length)>0&&(0,$.jsx)(yn,{type:u,title:c,"data-testid":`type-${u}`,children:(0,$.jsx)(mt,{withDivider:!0,children:(0,$.jsx)(DT,{lines:d,contentType:u,suggestions:s[u].suggestions.slice(0,p)||[]})})},u)}})})},KM=({onLogIn:e})=>{let t=q(Cl),n=A("Widget",Tl),r=M(Qi),o=M(rt),i=M(Yi),s=M(rr);return r===!1?(0,$.jsx)(FT,{text:t("notSupported")}):o===!1?(0,$.jsx)(UM,{onLogIn:e}):!s||!i||o===null?(0,$.jsx)(FT,{text:t("waiting")}):(0,$.jsx)("div",{className:(0,HT.default)(n.root),"data-testid":"widget",children:(0,$.jsxs)(Zl,{className:n.sectionList,children:[(0,$.jsx)(zM,{}),(0,$.jsx)(BM,{}),(0,$.jsx)(jM,{}),(0,$.jsx)(VM,{})]})})},UT=KM;function vs(e){let t=new Range;return t.selectNodeContents(e),t}function zT(e,t,n){try{return oo(e,t,n),!0}catch(r){return!1}}function Cf(e){return"tagName"in e&&(e.tagName==="DIV"||e.tagName==="P")}function Tf(e){return"tagName"in e&&e.tagName==="BR"}var Pl=/[\u200B-\u200D\uFEFF]/g;function oo(e,t,n){let r=new Range;if(e.firstChild===null&&t===0&&n===0)return r.selectNodeContents(e),r;let o=0,i=!1;function s(l,u){let c=-1,p=/[\u200B-\u200D\uFEFF]/;if(!p.test(l))return u;for(let d=0;d<=l.length;d++)if(p.test(l[d])||c++,c===u)return d;throw new Error("Offset out of range")}function a(l){switch(l.nodeType){case Node.TEXT_NODE:{let u=l.textContent,c=u.replace(Pl,""),p=o+c.length,d=t>=o&&t<=p,g=n>=o&&n<=p;if(d){let S=s(u,t-o);S===0&&!g?r.setStartBefore(l):r.setStart(l,S)}g&&(r.setEnd(l,s(u,n-o)),i=!0),o=p;break}case Node.ELEMENT_NODE:{if(Tf(l)&&(o===t&&r.setStartBefore(l),o++,o===n)){r.setEndAfter(l),i=!0;return}for(let c=0;c<l.childNodes.length&&(a(l.childNodes[c]),!i);c++);let u=l.lastChild;Cf(l)&&u&&!Cf(u)&&!Tf(u)&&o++;break}default:break}}if(a(e),r.startContainer===document)throw new Error("Offsets out of bound");return r}function Rl(e,t){if(!e.contains(t.startContainer)||!e.contains(t.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:r,endContainer:o,endOffset:i,collapsed:s}=t,a,l,u=0;function c(p){let d=p===n,g=p===o;switch(p.nodeType){case Node.TEXT_NODE:{let S=p.textContent;d&&(a=u+S.substring(0,r).replace(Pl,"").length),g&&(l=u+S.substring(0,i).replace(Pl,"").length),u+=S.replace(Pl,"").length;break}case Node.ELEMENT_NODE:{let S=p.nextSibling===null;Tf(p)&&!S&&u++;for(let y=0;y<p.childNodes.length;y++){let m=d&&y===r,f=g&&y===i;if(m&&(a=u),f&&(l=u),l!==void 0||((!m||!s)&&c(p.childNodes[y]),g&&y===i-1&&(l=u),l!==void 0))break}!g&&Cf(p)&&!S&&u++,g&&(l=u);break}default:break}}if(c(e),l===void 0)throw new Error("Could not determine start and end");return{start:a!=null?a:l,end:l}}function Al(e,t){if(!e.contains(t.startContainer)||!e.contains(t.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:r,endContainer:o,endOffset:i}=t,s=-1,a="";function l(u){let c=u===n,p=u===o;switch(c&&s++,u.nodeType){case Node.TEXT_NODE:{if(s!==0)return;let d=c?r:0,g=p?i:void 0,S=u.textContent.replace(Pl,"");d===0&&g===void 0?a+=S:a+=S.substring(d,g);break}case Node.ELEMENT_NODE:{let d=u.nextSibling===null;s===0&&Tf(u)&&!d&&(a+=`
|
|
26
26
|
`);for(let g=c?r:0;g<(p?Math.min(i,u.childNodes.length):u.childNodes.length)&&(l(u.childNodes[g]),s!==1);g++);!p&&s===0&&Cf(u)&&!d&&(a+=`
|
|
27
|
-
`);break}default:break}p&&s++}return l(e),a}var BT=(s=>(s.CUT="Cut",s.BACKSPACE="Backspace",s.DELETE="Delete",s.ERASEEOF="EraseEof",s.UNDO="Undo",s.CLEAR="Clear",s))(BT||{}),dr=class{constructor(t){this.element=t;this.isFocused=!1;this.isActive=!0;this.isDisposed=!1;this.eventListeners={};this.disposeHandlers=[];this.cachedText="";this.cachedCaretPosition=null;this.cachedSelection={start:0,end:0};this.cachedHTML="";this.isSubmitting=!1;this.isPossibleClearInputAction=!1;this.cachedText=this.getText(),this.cachedHTML=this.getHTML(),this.cachedSelection=this.getSelection(),this.listen()}addEventListener(t,n){let r=o=>{n(o)};this.element.addEventListener(t,r),this.disposeHandlers.push(()=>{this.element.removeEventListener(t,r)})}removeEventListener(t,n){this.element.removeEventListener(t,n)}handleInteraction(){let t=this.getText(),n=this.getHTML(),r=this.getSelection(),o=this.getCaretPosition();this.isActive&&(t===""&&this.cachedText!==""&&!this.isPossibleClearInputAction&&this.emit("submit"),t!==this.cachedText&&(this.cachedText=t,this.cachedHTML=n,this.emit("change",{plainText:t,rawHTML:n})),(r.start!==this.cachedSelection.start||r.end!==this.cachedSelection.end)&&(this.cachedSelection=r,this.emit("selection",r)),Wr(o,this.cachedCaretPosition)||(this.cachedCaretPosition=o,this.emit("caretposition",o)))}handleClick(){this.handleInteraction()}handleFocus(){let t=!this.isFocused;this.isFocused=!0,t&&this.emit("focus"),this.handleInteraction()}handleBlur(){this.isPossibleClearInputAction=!1;let t=this.isFocused;this.isFocused=!1,t&&this.emit("blur")}handleKeyDown(t){let{key:n,ctrlKey:r,metaKey:o}=t;this.isPossibleClearInputAction=Object.values(BT).includes(n)||n.toLowerCase()==="z"&&(r||o),this.emit("keydown",t)}handleKeyUp(t){this.handleInteraction(),this.emit("keyup",t)}handleCut(){this.isPossibleClearInputAction=!0,this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(t){var r,o;let n=((r=t.clipboardData)==null?void 0:r.getData("text"))||((o=t.clipboardData)==null?void 0:o.getData("text/plain"))||"";this.emit("paste",{pastedText:n,selectionText:this.getSelectedText()})}listen(){this.addEventListener("keydown",n=>this.handleKeyDown(n)),this.addEventListener("keyup",n=>this.handleKeyUp(n)),this.addEventListener("input",()=>this.handleInteraction()),this.addEventListener("change",()=>this.handleInteraction()),this.addEventListener("focus",()=>this.handleFocus()),this.addEventListener("blur",()=>this.handleBlur()),this.addEventListener("cut",()=>this.handleCut()),this.addEventListener("paste",n=>this.handlePaste(n)),this.addEventListener("click",()=>this.handleInteraction()),document.activeElement===this.element&&(this.isFocused=!0);let t=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});t.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{t.disconnect()})}focus(){this.element.focus()}emit(t,...n){this.isDisposed||this.eventListeners[t]&&this.eventListeners[t].forEach(r=>{r(...n)})}on(t,n){this.isDisposed||(this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n))}activate(){let t=this.isActive===!1;this.isActive=!0,t&&this.handleInteraction()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(t=>t()),this.eventListeners={},this.isDisposed=!0}};function jT(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var Go=class extends dr{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),Al(this.element,n)}getHTML(){return this.element.innerHTML||""}getRange(){var s;let n=this.getRootNode();if(n.activeElement!==this.element)return null;let r="getSelection"in n?n.getSelection():window.getSelection();if(!r)return null;let o="getComposedRanges"in r&&n instanceof ShadowRoot?(s=r.getComposedRanges(n))==null?void 0:s[0]:r.rangeCount>0?r.getRangeAt(0):null;if(!o)return null;let i=this.element.ownerDocument.createRange();return i.setStart(o==null?void 0:o.startContainer,o==null?void 0:o.startOffset),i.setEnd(o==null?void 0:o.endContainer,o==null?void 0:o.endOffset),!i||!this.element.contains(i.startContainer)||!this.element.contains(i.endContainer)?null:i}getCaretPosition(){let n=this.getRange();if(!n||!n.collapsed||!("getBoundingClientRect"in n))return null;let r=n.getBoundingClientRect();return!jT(r)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),r=n.getBoundingClientRect(),n.deleteContents(),!jT(r))?null:{top:r.top+r.height,left:r.left}}getSelection(){let n=this.getRange();if(n)return Rl(this.element,n);let r=this.lastKnownSelection;if(r&&zT(this.element,r.start,r.end))return r;let o=vs(this.element);return o.collapse(!1),Rl(this.element,o)}getSelectedText(){let{start:n,end:r}=this.getSelection();return Al(this.element,oo(this.element,n,r))}listen(){super.listen();let n=new MutationObserver(()=>{setTimeout(()=>{this.handleInteraction()},0)});n.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0}),this.disposeHandlers.push(()=>n.disconnect());let r=this.element.isContentEditable,o=new MutationObserver(()=>{this.element.isContentEditable!==r&&(r=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>o.disconnect())}};var Xo=class extends dr{constructor(){super(...arguments);this.lastKnownSelection=null}getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:n,selectionEnd:r}=this.element;return{start:n,end:r}}getSelectedText(){let n=this.getSelection();return n?this.getText().slice(n.start,n.end):""}getCaretPosition(){return null}listen(){super.listen();let n=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var i;return(i=n==null?void 0:n.get)==null?void 0:i.call(this.element)},set:i=>{var s;(s=n==null?void 0:n.set)==null||s.call(this.element,i),this.handleInteraction()}});let r=this.element.disabled,o=new MutationObserver(()=>{this.element.disabled!==r&&(r=this.element.disabled,this.emit(r?"disabled":"enabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>o.disconnect())}};function VT(e,t,n){let r=`deepdesk-iframe-${e}`,o=document.getElementById(r);if(o)return o;let i=document.createElement("iframe"),s=new URL(t);return Object.entries(n).forEach(([a,l])=>{s.searchParams.append(a,l)}),i.style.position="absolute",i.style.left="-999em",i.style.width="0px",i.style.height="0px",i.tabIndex=-1,i.id=r,i.title=`iframe-${e}`,i.src=s.toString(),window.document.body.appendChild(i),i}function WM(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(t){return e}}var by=class{constructor(t){this.name=t;this.disposeHandlers=[];this.broadcastChannel=new BroadcastChannel(t)}onMessage(t){this.broadcastChannel.addEventListener("message",t),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",t)})}postMessage(t){this.broadcastChannel.postMessage(JSON.stringify(t))}close(){this.disposeHandlers.forEach(t=>t()),this.broadcastChannel.close()}},Cy=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.disposeHandlers=[];this.iframe=VT(t,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}onMessage(t){window.addEventListener("message",t),this.disposeHandlers.push(()=>{window.removeEventListener("message",t)})}postMessage(t){var n;(n=this.iframe.contentWindow)==null||n.postMessage(JSON.stringify(t),this.targetOrigin)}close(){var t;this.disposeHandlers.forEach(n=>n()),(t=this.iframe)==null||t.remove()}},Ty=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.eventMap,this.sessionId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setSessionId(t){this.sessionId!==t&&(this.cleanup(),z.info("Set sessionId",t),this.sessionId=t,this.channel=this.createChannel(t))}createChannel(t){let n=this.params.createCustomChannel?this.params.createCustomChannel(t):this.isCrossOrigin?new Cy(t,this.deepdeskUrl,{debug:!0}):new by(t),r=o=>{var s,a;if(o.origin!==this.deepdeskUrl)return;let i=WM(o.data);typeof i!="object"||i.type!=="event"||i.channel!==t||(z.info("Received broadcast event",this.sessionId,o),(a=(s=this.eventMap)[i.name])==null||a.call(s,i.payload))};return n.onMessage(r),n}send(t,n,r){var s,a;z.info("Broadcast event",{sessionId:this.sessionId,name:t,payload:n});let o={type:"event",name:t,payload:n};r!==!1&&((a=(s=this.eventMap)[t])==null||a.call(s,n));let i=this.sessionId==="deepdesk-general"?this.defaultChannel:this.channel;i==null||i.postMessage(N(P({},o),{channel:this.sessionId}))}cleanup(t=!1){var n,r;(n=this.channel)==null||n.close(),delete this.channel,t&&((r=this.defaultChannel)==null||r.close(),delete this.defaultChannel)}},KT=Ty;var Ss=class extends Error{constructor(n,r){super(n);this.body=r;this.name="CustomError"}};var ky=e=>new Promise(t=>{setTimeout(t,e)});var ws=class extends Ss{constructor(){super(...arguments);this.name="ClientError"}},Ry=class extends Ss{constructor(){super(...arguments);this.name="ServerError"}},Py=new Map;function $M(e){return k(this,null,function*(){if(e.status===204)return e.text().catch(()=>{}),null;let t=e.headers.get("content-type");if(t&&t.includes("application/json"))return e.json();let n=yield e.text();return n===""?null:(z.warn("Unexpected response body:",n.slice(0,20)),JSON.parse(n))})}var io=class io{constructor(t="",n={}){this.baseUrl=t;this.options=n;this.latestRequestByUrl={};this.fetch=window.fetch.bind(window);n.fetch&&(this.fetch=n.fetch)}patchFetch(t){this.fetch=t(this.fetch)}setCsrfToken(t){this.csrfToken=t}request(t,n={}){return new Promise((r,o)=>{let i={isAborted:!1,reject:o},s=`${this.baseUrl}${t}`,a=this.fetch,l=n.method===void 0||n.method.toLowerCase()==="get",C=n,{useCache:u=!1,abortLatest:c=!1,attempts:p=1,retryDelay:d=500,refreshTokenOn401:g=!0,retryOnError:S=R=>R instanceof TypeError,retryOnResponse:y=R=>R.status>=500,version:m="v1"}=C,f=te(C,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]);if(u)if(l){if(Py.has(s)){r(Py.get(s));return}}else throw new Error(`Can't use 'useCache' for ${n.method}`);let h=N(P({credentials:"include"},f),{headers:P({"Content-Type":"application/json"},f.headers)});!l&&this.csrfToken&&(h.headers=N(P({},h.headers),{"X-CSRFToken":this.csrfToken})),typeof m=="string"&&(h.headers=N(P({},h.headers),{"X-Deepdesk-API-Version":m}));let v=p,x=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[s]&&c&&(this.latestRequestByUrl[s].isAborted=!0,this.latestRequestByUrl[s].reject(new Error("Aborted"))),this.latestRequestByUrl[s]=i;let T=()=>k(this,null,function*(){return v--,a(s,h).then(R=>k(this,null,function*(){return y(R)&&!i.isAborted&&v>0?(yield ky(d),T()):R.status===401&&g===!0&&x===!1?(x=!0,yield this.refreshToken(),T()):R})).catch(R=>k(this,null,function*(){if(S(R)&&!i.isAborted&&v>0)return yield ky(d),T();throw R}))});T().then(R=>k(this,null,function*(){let O=yield $M(R);if(delete this.latestRequestByUrl[s],R.status>=500){o(new Ry("Server Error",O));return}else if(R.status===401){o(new ws("Unauthorized",O));return}else if(R.status===403){o(new ws("Forbidden",O));return}else if(R.status===404){o(new ws("Not Found",O));return}else if(R.status>=400){o(new ws("Bad Request",O));return}u&&Py.set(s,O),r(O)})).catch(R=>{o(R)})})}validateToken(){return k(this,null,function*(){let{has_valid_access_token:t}=yield this.get("/auth/validate");if(!t)return!1;let{is_logged_in:n}=yield this.get("/apis/admin/session/validate/",{version:null});return!!n})}refreshToken(){return io.refreshingToken||(io.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{io.refreshingToken=null},1e3*60)})),io.refreshingToken}get(t,n){return this.request(t,n)}post(t,n,r){return this.request(t,P({method:"POST",body:JSON.stringify(n)},r))}patch(t,n,r){return this.request(t,P({method:"PATCH",body:JSON.stringify(n)},r))}put(t,n,r){return this.request(t,P({method:"PUT",body:JSON.stringify(n)},r))}delete(t,n){return this.request(t,P({method:"DELETE"},n))}};io.refreshingToken=null;var hn=io;var WT;(t=>{let e;(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"))(e=t.EventType||(t.EventType={}))})(WT||(WT={}));function kf(e){return N(P({},re(e)),{tags:e.tags})}var Yo=class Yo{constructor(t,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new hn(t,{fetch:n.fetch}),this.client.patchFetch(r=>(o,i)=>k(this,null,function*(){let s=yield r(o,i);return this.handleDeepdeskVersionHeaders(s),s}))}preflight(){return k(this,null,function*(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=yield this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(Yo.exchangeTokenPromise||(Yo.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),Yo.exchangeTokenPromise):Promise.resolve()})}createConversation(t){return k(this,null,function*(){yield this.preflight(),z.info(`Creating conversation for session ${t.sessionId} and agent ${t.agentId}`);let n=yield this.client.post("/api/conversations",N(P({},Oe(t)),{tags:t.tags}),{version:"v2"});return kf(n)})}getProfile(t){return k(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${t}/`,{version:null,useCache:!0});return re(n)})}getKnowledgeAssistant(t){return k(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{version:null,useCache:!0});return re(n)})}getContentTypes(){return k(this,null,function*(){let t=yield this.client.get("/apis/admin/content-types/",{version:null,useCache:!0});return re(t)})}getAccount(){return k(this,null,function*(){let t=yield this.client.get("/apis/admin/account/",{version:null,useCache:!0});return re(t)})}getPlatformConfig(){return k(this,null,function*(){let{config:t}=yield this.client.get("/platform/config/",{version:null,useCache:!0});return re(t)})}checkUserExists(t){return k(this,null,function*(){let{exists:n}=yield this.client.get(`/apis/admin/users/exists?external_id=${t}`);return n})}getConversationBySessionId(r){return k(this,arguments,function*(t,n={}){yield this.preflight(),z.info(`Getting conversation for session ${t}`);let{attempts:o=1,retryDelay:i=1e3}=n,s=yield this.client.get(`/api/conversations/by_session_id/${t}`,{attempts:o,retryDelay:i,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"});return z.info(`Successfully retrieved conversation ${s.id} for session ${t}`),kf(s)})}isConversationSupported(r){return k(this,arguments,function*(t,n={}){z.info(`Check if conversation for session ${t} is supported`);let{attempts:o=1,retryDelay:i=1e3}=n;return(yield this.client.get(`/api/conversations/by_session_id/${t}/active_profile`,{attempts:o,retryDelay:i,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"})).has_active_profile})}updateConversation(t,n){return k(this,null,function*(){let r=Oe(n);n.tags&&(r.tags=n.tags);let o=yield this.client.put(`/api/conversations/${t}`,r,{version:"v2"});return kf(o)})}postMessages(t,n){return k(this,null,function*(){return(yield this.client.post(`/api/conversations/${t}/messages`,n.map(o=>N(P({},Oe(o)),{tags:o.tags})),{version:"v2"})).map(o=>kf(o))})}sendEvent(t,n){return k(this,null,function*(){let s=n,{data:r}=s,o=te(s,["data"]),i=Object.entries(this.latestReceivedDeepdeskVersions).reduce((a,[l,u])=>N(P({},a),{[l]:u}),{});return this.client.post("/api/events",Oe(N(P(P({},i),o),{data:r,name:t})),{version:"v2"})})}sendEventV1(t,n){return k(this,null,function*(){let r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((o,[i,s])=>N(P({},o),{[i]:s}),{});return this.client.post("/api/events",{event:t,data:Oe(P(P({},n),r))})})}getEntities(t){return k(this,null,function*(){return(yield this.client.post("/api/entities",{messages:t.filter(r=>r.text)})).entities})}getSummary(r){return k(this,arguments,function*(t,n={}){let o=yield this.client.post("/api/summary",{conversation:{messages:t.filter(i=>i.text&&i.source),agent_id:n.agentId,id:n.externalConversationId},prompt_instruction:n.promptInstruction,model:n.model});return re(o)})}getTemporaryExchangeToken(){return k(this,null,function*(){return(yield this.client.get("/auth/exchange-token",{version:null})).jwt})}exchangeTokenForAccessCookie(t){return k(this,null,function*(){return this.client.post("/apis/admin/session/jwt/",{jwt:t},{version:null}).catch(n=>{throw z.warn(`Invalid token '${t}'`),n})})}authenticateWithKey(t,n){return k(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/api-key/",Oe(n),{version:null,refreshTokenOn401:!1,headers:{apikey:t}})})}getTextSuggestions(o){return k(this,arguments,function*(t,n={},r){return r==="sticky-messages"?this.getPinnedMessages(t):(yield this.client.post(`/api/conversations/${t}/recommend/${r}`,Oe(n),{abortLatest:!0})).map(s=>N(P({},re(s)),{text:s.text||s.url||s.message,source:r,type:r})).filter((s,a,l)=>a===l.findIndex(u=>u.text===s.text))})}isLoggedIn(){return k(this,null,function*(){return yield this.preflight(),this.client.validateToken()})}getAutocompleteSuggestions(t,n){return k(this,null,function*(){return(yield this.client.post(`/api/conversations/${t}/autocomplete`,Oe(n),{abortLatest:!0})).map(o=>({score:1,source:o.source,sourceText:o.source_text,text:o.label,trainingJobs:o.training_jobs,searchKeywords:o.search_keywords,type:o.source})).filter((o,i,s)=>i===s.findIndex(a=>a.text===o.text))})}getPinnedMessages(t){return k(this,null,function*(){let n=yield this.client.get(`/api/conversations/${t}/sticky-messages`,{abortLatest:!0});return re(n).map(r=>N(P({},r),{text:r.message,source:"sticky-messages",type:"pinned-message"}))})}getStyleSuggestions(t){return k(this,null,function*(){let n=yield this.client.post("/api/style-suggestions",Oe(t),{abortLatest:!0});return re(n)})}search(t){return k(this,null,function*(){let n=yield this.client.post(`/api/profiles/${t.profile}/search`,Oe(t),{version:"v2"});return re(n)})}knowledgeAssist(i,s,a){return k(this,arguments,function*(t,n,r,o={}){let l=yield this.client.post(`/api/knowledge-assist/assistants/${r}/search`,Oe({question:t.question,doNotKnowAnswer:t.doNotKnowAnswer,customerInstruction:t.customerInstruction,chatHistory:n.map(u=>({question:u.question,answer:u.answer.answer})),agentId:o.agentId,conversationId:o.conversationId}),{version:"v2"});return re(l)})}requestLoginByEmail(t){return k(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:t},{version:null});return re(n)})}requestPasswordlessToken(){return k(this,null,function*(){let t=yield this.client.get("/apis/admin/session/passwordless/request/",{version:null});return re(t.token)})}getCsrfToken(){return k(this,null,function*(){let{token:t}=yield this.client.get("/apis/admin/session/csrf/",{version:null});return t})}verifyLoginToken(t){return k(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/login/",{token:t},{version:null});return re(n)})}evaluateRule(i,s,a){return k(this,arguments,function*(t,n,r,o={}){let l=new URLSearchParams;o.raiseForFailingConditions&&l.set("raise_for_failing_conditions","true");let u=yield this.client.post(`/api/conversations/${n}/rules/${t}/evaluate?${l.toString()}`,r,{version:"v2"});return u?re(u.cues):[]})}getRules(){return k(this,null,function*(){let t=new URLSearchParams,n=yield this.client.get(`/apis/admin/rule-engine/rules/?${t.toString()}`,{version:null,useCache:!0});return re(n)})}translateMessages(t){return k(this,null,function*(){let n=yield this.client.post("/api/translate",Oe(t),{version:"v2"});return re(n)})}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),i=o.match($v);if(!n||!i)return;let s=i[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[s];a&&n&&a!==n&&z.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[s]=n})}};Yo.exchangeTokenPromise=null;var fr=Yo;var Ll=class{constructor(t,n){this.url=t;this.eventListeners={};this.options=P({timeout:25e3},n)}proxyEvent(t){this.eventSource.addEventListener(Zg(t),n=>{let{data:r}=n;try{let o=JSON.parse(r);this.emit(t,re(o))}catch(o){z.warn(`Invalid JSON for ${t}: ${r}`)}})}connect(){clearTimeout(this.timeoutTimer);let t=new EventSource(this.url,{withCredentials:!0});this.eventSource=t;let n=!1;t.onopen=()=>{n=!0},t.onerror=()=>{n&&t.readyState===2&&this.connect()},this.timeoutTimer=setTimeout(()=>{t.close(),this.connect()},this.options.timeout),Object.keys(this.eventListeners).forEach(r=>{this.proxyEvent(r)})}disconnect(){var t;clearTimeout(this.timeoutTimer),this.eventListeners={},(t=this.eventSource)==null||t.close()}emit(t,n){this.eventListeners[t]&&this.eventListeners[t].forEach(r=>r(n))}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),this.proxyEvent(t),()=>{this.off(t,n)}}off(t,n){let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}};var $T;(t=>{let e;(i=>(i.Started="Started",i.Aborted="Aborted",i.Completed="Completed"))(e=t.AutoflowSessionState||(t.AutoflowSessionState={}))})($T||($T={}));var Il=class{constructor(t,n={}){this.apiUrl=t;this.streams={};this.logger=z;this.client=new hn(t,n)}getCustomMessages(t){return k(this,null,function*(){let n=yield this.client.get(`/sessions/${t}/suggestions`);return re(n.suggestions)})}sendCustomMessage(t,n){return k(this,null,function*(){let r=yield this.client.post(`/sessions/${t}/messages`,Oe(n));return re(r)})}answerCustomMessage(t,n){return k(this,null,function*(){yield this.client.post(`/sessions/${t}/answers`,Oe(n))})}getAutoflows(t){return k(this,null,function*(){let n=yield this.client.get(`/sessions/${t}/autoflows`);return re(n.autoflows)})}startAutoflowSession(t){return k(this,null,function*(){let n=yield this.client.post("/autoflow-sessions",Oe(t));return re(n)})}stopAutoflowSession(t){return k(this,null,function*(){yield this.client.delete(`/autoflow-sessions/${t}`)})}openStream(t){return this.streams[t]||(this.streams[t]=new Ll(`${this.apiUrl}/sessions/${t}/events`),this.streams[t].connect()),this.streams[t]}closeStream(t){this.streams[t]||(this.streams[t].disconnect(),delete this.streams[t])}};var qT={startTime:null,stopTime:null},GT=Q({name:"handlingTime",initialState:qT,reducers:{handlingTimeStart(e){if(e.startTime&&!e.stopTime)throw new Error("Timing already started");e.startTime=new Date,e.stopTime=null},handlingTimeStop(e){if(!e.startTime)throw new Error("Timing not started");e.stopTime=new Date},handlingTimeReset(e){e.startTime=null,e.stopTime=null}},extraReducers:e=>{e.addCase(fe,()=>qT)}}),{handlingTimeStart:XT,handlingTimeStop:Pf,handlingTimeReset:YT}=GT.actions,QT=GT.reducer;var ZT=(e={})=>{let t=P({onAuthError:Xi(!1)},e);return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var Rf={list:{keywordMatches:[]},fetchState:"idle"};var Qo=K("styleSuggestions/getAll",(n,r)=>k(void 0,[n,r],function*({text:e},t){var l;let{deepdeskAPI:o}=t.extra,i=t.getState(),{showStyleSuggestions:s}=i.settings,a=(l=i.conversation.current)==null?void 0:l.profileCode;if(!s)return Rf.list;if(!a)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:a,message:e})})),qM=Q({name:"styleSuggestions",initialState:Rf,reducers:{},extraReducers:e=>{e.addCase(Qo.pending,t=>{t.fetchState="loading"}).addCase(Qo.rejected,t=>{t.fetchState="error"}).addCase(Qo.fulfilled,(t,n)=>{t.fetchState="done",Wr(t.list,n.payload)||(t.list=n.payload)}).addCase(Ao,t=>{t.list=Rf.list}).addCase(fe,()=>Rf)}}),JT=qM.reducer;var ek=(e={})=>{let t,n=!0,r=P({getStyleSuggestions:Qo,debounce:500},e);return o=>i=>s=>{var g;let a=o.getState().input.text,l=i(s),u=o.getState();if(u.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:c}=u.settings;if(!((g=u.conversation.current)==null?void 0:g.id)||!c)return l;let{text:d}=u.input;return d===a&&!n||(clearTimeout(t),d==="")||(t=setTimeout(()=>{n=!1,o.dispatch(r.getStyleSuggestions({text:d}))},e.debounce)),l}};function GM(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var tk=(e={})=>{let t=P({getTextSuggestions:dn,getAutocompleteSuggestions:ll,debounce:200,check:ds},e),n;return r=>o=>i=>{var y;let{input:s}=r.getState(),a=o(i),l=r.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:u,showTabCompletion:c}=l.settings,p=(y=l.conversation.current)==null?void 0:y.id,d=i.type===jd.toString();if(!p||!u&&!c)return a;let{input:g}=l;return GM(g,s)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let m=Ji(l);m===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(m))},d?0:t.debounce)),a}};var nk=Qo.fulfilled.toString();function XM(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let i=e.keywordMatches.filter(l=>l.keyword===o),s=t.keywordMatches.filter(l=>l.keyword===o),a=s.length-i.length;a<=0||r.push(...s.slice(0,a))}),r}var rk=e=>t=>n=>r=>{var u;if(r.type!==nk){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let i=t.getState(),s=i.styleSuggestions.list,a=(u=i.conversation)==null?void 0:u.current;if(o===s)return;let l=XM(o,s);r.type===nk&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var YM=xc({answer:lb,auth:f1,autoflows:AC,conversation:E1,contentTypes:vE,customMessages:HC,passwordlessToken:BC,entities:VE,knowledgeAssistant:ib,handlingTime:QT,info:z1,input:M1,settings:i1,profile:fb,search:q1,summary:YE,styleSuggestions:JT,ui:Bb,rules:$C,textSuggestions:wb});function ok(e){return dx({reducer:YM,middleware:t=>[...t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI,deepdeskBrokerAPI:e.deepdeskBrokerAPI}},serializableCheck:!1}),ZT(),tk({debounce:200}),ek({debounce:500}),rk(e.deepdeskAPI),...e.middleware?e.middleware:[]],preloadedState:e.preloadedState})}var QM=e=>{var t,n;return(n=(t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())!=null?n:"unknown"},ZM=e=>t=>n=>r=>{var a,l,u,c,p,d;let o=t.getState(),i=qg("inlineSuggestions")(o);switch(r.type){case Xi.toString():{!r.payload&&e.emit("logout",void 0);break}case un.fulfilled.toString():r.payload.length>0&&e.sendEvent("entities found",{conversationId:(a=o.conversation.current)==null?void 0:a.id,data:{entities:r.payload}});break;case ot.toString():e.sendEvent(r.payload.name,{conversationId:((l=r.payload.options)==null?void 0:l.includeConversationData)&&((u=o.conversation.current)==null?void 0:u.id),data:r.payload.data});break;case Ao.toString():e.logSendMessage(r.payload);break;case $o.fulfilled.toString():r.isBroadcasted||e.broadcast(th,r,!1),(c=r.payload.options)!=null&&c.shouldEmit&&e.emit("cues",r.payload.cues);break;default:break}let s=n(r);switch(r.type){case Ao.toString():e.handleAfterSendMessage(r.payload);break;case cl.toString():e.onUpdateShowTabHint(r.payload);break;case Pf.toString():e.logHandlingTime();break;case"analytics/logEvent/fulfilled":{e.emit("event",r.meta.arg);break}case nd.toString():{let{start:g,end:S}=o.input.selection;e.emit("replace",N(P({},r.payload),{replace:r.payload.replace==="selection"?{start:g,end:S}:{start:0,end:S}}));break}case qn.toString():{let{start:g,end:S}=o.input.selection;e.emit("select-suggestion",N(P({type:QM(r.payload.suggestion)},r.payload),{replace:r.payload.replace==="selection"?{start:g,end:S}:{start:0,end:S}})),i&&t.dispatch(Gn([]));break}case rd.toString():e.emit("select-image",r.payload),e.sendEvent("Image attached",{conversationId:(p=o.conversation.current)==null?void 0:p.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case Gn.toString():{i&&r.payload.length>0&&t.dispatch(id(0));break}case er.fulfilled.toString():{e.sendEvent("conversation summarized",{conversationId:(d=o.conversation.current)==null?void 0:d.id,data:{summary:r.payload.summary,model:t.getState().summary.model}});break}default:break}return s},ik=ZM;function Ay(e){return e.toISOString().replace("T"," ").replace("Z","")}function sk(e,t){var i,s,a,l;let n=(i=e.conversation.current)==null?void 0:i.id;if(!n)return z.warn("No conversationId for handling time metrics"),null;let{startTime:r,stopTime:o}=e.handlingTime;return!r||!o?(z.warn("No startTime and stopTime for handling time metrics"),null):{conversationId:n,clientVersion:t.version,agentId:(s=e.info.agentInfo)==null?void 0:s.agentId,agentName:(a=e.info.agentInfo)==null?void 0:a.agentName,agentEmail:(l=e.info.agentInfo)==null?void 0:l.agentEmail,timeStart:Ay(r),timeStop:Ay(o)}}function ak(e,t,n){var O,_,D,G;let r=(O=t.conversation.current)==null?void 0:O.id;if(!r)return z.warn("No conversationId for send message metrics"),null;let{text:o,metrics:{numCharsTyped:i,numCharsPasted:s,numCharsCut:a,numCharsDeleted:l,numPaste:u,agentStartedTypingTimestamp:c,externalTimeTotalSeconds:p,pastes:d,cuts:g,deletions:S,textSuggestions:y,offeredTextSuggestions:m}}=t[e],f=o.length,v=y.reduce((Z,{text:se,searchTerm:pr})=>Z+se.length-(pr?pr.length:0),0),x=c!=null?c:Date.now(),T=(Date.now()-x)/1e3+(p||0),C=i/T,R=y.reduce((Z,{searchTerm:se})=>Z+(se?se.length:0),0);return{conversationId:r,source:"agent",text:o,clientVersion:n.version,pastes:d,cuts:g,deletions:S,lenTextTyped:i+R,lenTextTotal:f,lenTextAssisted:v,lenTextPasted:s,lenTextCut:a,lenTextDeleted:l,timeTotalSeconds:T,charsPerSecond:C,numPastes:u,textSuggestionsV2:y,suggestionsCounters:[{source:"gpt",countOffered:m.filter(Z=>Z.source==="gpt").length}],agentId:(_=t.info.agentInfo)==null?void 0:_.agentId,agentName:(D=t.info.agentInfo)==null?void 0:D.agentName,agentEmail:(G=t.info.agentInfo)==null?void 0:G.agentEmail}}function Ly(e,t){var i;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return Ly(r,t);let o=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;return o?Ly(o,t):null}function lk(e,t){return Ly(e,t)}function uk(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function JM(e){return typeof e=="object"&&e!==null&&"tagName"in e}function Af(e){return JM(e)&&(eo(e)||Jd(e))}var dk,Ln=new Map,e2=["bottom","height","left","right","top","width"],ck=(e,t)=>!e&&!t?!1:e&&!t||!e&&t?!0:e2.some(n=>e[n]!==t[n]);function fk(e){var n,r,o;if(e.ownerDocument===document)return[];let t=(o=(r=(n=e.ownerDocument)==null?void 0:n.defaultView)==null?void 0:r.frameElement)!=null?o:null;return t?[t,...fk(t)]:[]}function pk(e,t){return!e||!t?null:N(P({},e),{top:e.top+t.top,left:e.left+t.left})}var Lf=!1,mk=()=>{Lf=!0;let e=[];if(Ln.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),Ln.delete(n);return}let r=n.getBoundingClientRect();ck(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(pk,t.rect):t.rect;ck(n,t.totalRect)&&t.callbacks.forEach(r=>r(n)),t.totalRect=n}),Ln.size===0){Lf=!1;return}dk=window.requestAnimationFrame(mk)};function Iy(e,t){let n=fk(e),r=[],o=n.map((i,s)=>Iy(i,a=>{r[s]=a;let l=Ln.get(e);if(!l)return;let u=r.reduce(pk,l.rect);l.callbacks.forEach(c=>c(u))}));return{observe(i=!0){if(o.forEach(s=>s.observe(!1)),Ln.has(e)){let s=Ln.get(e);s.callbacks.push(t),s.rect&&t(s.rect)}else Ln.set(e,{rect:void 0,callbacks:[t],parentRects:r});i&&!Lf&&mk()},unobserve(){o.forEach(s=>s.unobserve());let i=Ln.get(e);if(i){let s=i.callbacks.indexOf(t);s>=0&&i.callbacks.splice(s,1),i.callbacks.length||Ln.delete(e),Ln.size||(cancelAnimationFrame(dk),Lf=!1)}}}}var gk,In=new Map,hk=()=>{In.forEach((e,t)=>{if(!t.isConnected){In.delete(t);return}let{clientHeight:n,scrollHeight:r}=t,o=r>n;e.visible!==o&&(e.visible=o,e.callbacks.forEach(i=>i(e.visible)))}),In.size!==0&&(gk=window.requestAnimationFrame(hk))};function yk(e,t){return{observe(){let n=In.size===0;In.has(e)?In.get(e).callbacks.push(t):In.set(e,{visible:void 0,callbacks:[t]}),n&&hk()},unobserve(){let n=In.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||In.delete(e),In.size||cancelAnimationFrame(gk)}}}}var Oy=["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 Ny(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function xs(e){return parseFloat(e)}function If(e){return Math.round(e*1e6)}function vk(e){return e/1e6}function My(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=xs(e.width),i=xs(e.borderLeftWidth),s=xs(e.borderRightWidth),a=xs(e.paddingRight),l=vk(If(o)-If(i)-If(s)),u=vk(If(r));if(l-u>2){let c=l-u;n.style.paddingRight=`${a+c}px`}}function Ol(e,t={}){var c,p;let n=t.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=(c=t.position)!=null?c:"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",Vo(n);let r=window.getComputedStyle(e),o=!0,i=()=>{n.scrollTop=e.scrollTop};Ny(r,n,Oy),My(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",i));let s=yk(e,()=>{Ny(r,n,Oy),My(r,e,n),i(),setTimeout(i,0)}),a,l=!0,u=Iy(e,d=>{if(d===null){t.onRemove&&t.onRemove(),n.remove();return}if(!l&&t.onMoveStart&&(Promise.resolve().then(()=>t.onMoveStart()),l=!0),clearTimeout(a),a=setTimeout(()=>{t.onMoveEnd&&t.onMoveEnd(),l=!1},200),d.height===0&&d.width===0){if(o===!0)return;t.onHide&&t.onHide(),n.style.display="none",o=!0;return}if(Ny(r,n,Oy),My(r,e,n),i(),n.style.top=`${d.top}px`,n.style.left=`${d.left}px`,t.closestScrollElement&&t.closestScrollElement!==e){let g=t.closestScrollElement.getBoundingClientRect(),S=window.getComputedStyle(t.closestScrollElement),y=xs(S.borderTopWidth),m=xs(S.borderBottomWidth),f=g.top+y-d.top,h=d.top+d.height+-(g.top+g.height-m);n.style.clipPath=`inset(${f}px 0px ${h}px 0px)`}o&&(n.style.display="block",t.onShow&&t.onShow(),o=!1)});return t.appendTo?t.appendTo.appendChild(n):(p=e.parentElement)==null||p.appendChild(n),u.observe(),s.observe(),[n,()=>{e.removeEventListener("scroll",i),u.unobserve(),s.unobserve()}]}var Sk=(e,t)=>({value(){try{let n=sessionStorage.getItem(`dd-${e}`);if(!n)return t;try{return JSON.parse(n)}catch(r){return t}}catch(n){return t}},update(n){try{sessionStorage.setItem(`dd-${e}`,JSON.stringify(n))}catch(r){z.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function t2(e){return e.offsetParent!==null}function wk(e){if(!t2(e))return!1;let t=e.getBoundingClientRect();return t.top>=0&&t.left>=0&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&t.right<=(window.innerWidth||document.documentElement.clientWidth)}function Of(e,t,n=100){let r=wk(e);t({isVisible:r});let o=setInterval(()=>{let i=wk(e);i!==r&&(r=i,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var _e=w(b());var xk=Sk("showTabHint",!0),Es=class Es{constructor({deepdeskUrl:t,brokerUrl:n,version:r=Es.version||"unknown",locale:o="en-US",token:i,fetch:s,productName:a,createCustomChannel:l}){this.inputMediator=null;this.eventListeners={};this.unmountHandlers=[];this.widgetRoot=null;this.dynamicThunkObject={};this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;let u=t.replace(/\/api$/,"");this.deepdeskApi=new fr(u,{token:i,fetch:s}),this.version=r,this.instanceId=Es.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[ik({broadcast:(p,d,g)=>{this.broadcastEvents.send(p,d,g)},emit:(p,d)=>this.emit(p,d),handleAfterSendMessage:p=>this.handleAfterSendMessage(p),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:p=>this.logSendMessage(p),onUpdateShowTabHint:p=>xk.update(p),sendEvent:(p,d)=>this.deepdeskApi.sendEvent(p,d)})]};n&&Object.assign(c,{deepdeskBrokerAPI:new Il(n)}),this.store=ok(c),this.broadcastEvents=new KT({debug:!0,deepdeskUrl:u,eventMap:G1(this.store),createCustomChannel:l}),this.store.dispatch(cl(xk.value())),this.store.dispatch(Yc({locale:o,adminUrl:u,productName:a}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){var t;return(t=this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex])!=null?t:null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(z.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(z.warn("Profile has not been loaded (yet)"),!0):(z.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(Xi(null)),this.store.dispatch(Wn()),new Promise(t=>{let n=this.store.subscribe(()=>{let r=this.store.getState();rt(r)&&s1(r)!=="loading"&&(n(),t())});this.unmountHandlers.push(()=>{n()})})}isLoggedIn(){return k(this,null,function*(){return(yield this.store.dispatch(Wn())).payload})}setPlatformAgentId(t){return k(this,null,function*(){try{if((yield this.deepdeskApi.client.get("/apis/admin/session/me/",{version:null})).external_id)return;yield this.deepdeskApi.client.request("/apis/admin/session/me/",{method:"PATCH",body:JSON.stringify({external_id:t}),version:null})}catch(n){z.warn("Failed to attach user:",n)}})}isConversationSupported(t,n){return k(this,null,function*(){return(yield this.store.dispatch(Yg({sessionId:t,options:n}))).payload})}createConversation(t){return k(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(yield this.store.dispatch(Zc(t))).payload})}getConversationBySessionId(t,n){return k(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(yield this.store.dispatch(Jc({sessionId:t,options:n}))).payload})}upsertConversation(t){return k(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(yield this.store.dispatch(Qg(t))).payload})}postMessages(t){return k(this,null,function*(){return(yield this.store.dispatch(td(t))).payload})}updateConversation(t){return k(this,null,function*(){return(yield this.store.dispatch(ed(t))).payload})}resetConversation(){this.store.dispatch(fe()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}getSummary(){return k(this,null,function*(){let t=yield this.store.dispatch(er());if(t.error)throw new Error(t.error.message);return t.payload.summary})}configure(t){this.store.dispatch(Yc(t))}setVisitorInfo(t){this.store.dispatch(H1(t))}setCustomData(t){this.store.dispatch(U1(t))}setAgentInfo(t){return k(this,null,function*(){yield this.store.dispatch(Ua(t))})}setAgentSettings(t){return k(this,null,function*(){yield this.store.dispatch(Jg(t))})}getAgentSettings(){return k(this,null,function*(){return(yield this.store.dispatch(eh())).payload})}refresh(){return k(this,null,function*(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.store.dispatch(sd({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()}));let t=[];return this.store.dispatch(jd()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})})}notifyExternalSuggestion(t){this.store.dispatch(qn(t))}evaluateRule(o){return k(this,arguments,function*(t,n={},r=jC){return(yield this.store.dispatch($o({label:t,params:n,options:r}))).payload.cues})}handleKeyDown(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui,{textSuggestions:o,selectedSuggestionIndex:i,selection:s}=this.state.input,{inlineSuggestions:a,showTextSuggestions:l}=this.state.settings,u=a?"below":"above",c=o.length>0;if(this.store.dispatch(R1(b1(t))),t.key!=="Tab"&&!l)return;let p=()=>{n||!c||s&&(t.shiftKey||(this.store.dispatch(I1()),t.preventDefault()))},d=()=>{n||!c||a&&i<=0||s&&(t.shiftKey||(this.store.dispatch(O1()),t.preventDefault()))};switch(t.key){case"ArrowUp":u==="below"?d():p();break;case"ArrowDown":{u==="below"?p():d();break}case"Escape":{n||(this.store.dispatch(id(-1)),this.store.dispatch(Zr({collapse:!0})),this.store.dispatch(Ub(!0)),t.preventDefault());break}case"Tab":{let{text:g}=this.state.input,S=g.substring(0,s.end),y=od(this.state);this.settings.showTabCompletion&&y&&y.text.startsWith(S)&&(this.store.dispatch(cl(!1)),this.store.dispatch(qn({text:y.text,suggestion:y,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}))),t.preventDefault();break}default:}n&&r&&this.store.dispatch(Zr({collapse:!1}))}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(Gn([]))}handlingTimeStart(){this.state.handlingTime.startTime||(z.info("Start handling time"),this.store.dispatch(XT()))}handlingTimeStop(){this.state.handlingTime.startTime&&(z.info("Stop handling time"),this.store.dispatch(Pf()))}logSendMessage(t){let n=ak("input",this.state,{version:this.version});n&&(t&&(Object.assign(n,{text:t}),Object.assign(n,{lenTextTotal:t.length})),this.deepdeskApi.sendEventV1("Send Message",n),this.emit("send-message-event",n))}logHandlingTime(){let t=sk(this.state,{version:this.version});t&&(this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch(YT()))}notifySubmit(t={}){var n;this.shouldAbort()||this.store.dispatch(Ao((n=t.text)!=null?n:this.state.input.text))}emit(t,n){let r=this.eventListeners[t];r&&r.forEach(o=>{try{o(n)}catch(i){z.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),z.error(i)}})}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),()=>{this.off(t,n)}}off(t,n){if(!t&&!n){this.eventListeners={};return}let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}setConversationQuery(t){this.dynamicThunkObject.conversationQuery=t}whenConversationLoaded(t){let n=()=>this.loadProfileConfig().then(()=>t());this.hasConversation()&&n();let r=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==r&&(r=this.hasConversation(),r&&n())})}overlayContainerFactory(t,n,r,o){let[i,s]=Ol(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),this.unmountHandlers.push(()=>{(0,Yt.unmountComponentAtNode)(i),s(),i.remove()}),i}createInlineContainer(t,n){var s;let r=document.createElement("div");r.style.position="absolute",r.style.top="0px",r.style.left="0px",r.style.height="0px",r.style.width="0px";let o=document.createElement("div");o.style.display="none",o.style.position="absolute",o.style.height="0px",o.style.width="0px",o.style.backgroundColor="red",r.appendChild(o);let i=(s=t.ownerDocument.defaultView)==null?void 0:s.frameElement;if(i){let[a,l]=Ol(i,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});a.dataset.testid=n,a.style.zIndex="2",a.appendChild(r),this.unmountHandlers.push(()=>{(0,Yt.unmountComponentAtNode)(o),l()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return Vo(o),o.dataset.testid=t,o.style.color=r.color,o.style.fontSize=r.fontSize,o.style.fontFamily=r.fontFamily,o.style.fontVariant=r.fontVariant,o.setAttribute("translate","no"),n.appendChild(o),this.unmountHandlers.push(()=>{(0,Yt.unmountComponentAtNode)(o),o.remove()}),o}storeMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(t,n),z.info(`Stored analytics for ${this.conversationId()}`)}catch(t){}}restoreMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=window.sessionStorage.getItem(t);if(!n)return;let r=JSON.parse(n);r.text.trim()===this.state.input.text.trim()?(z.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(N1(r.metrics))):z.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(t)}catch(t){}}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!Af(t))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let{customStyles:r={},showStyleSuggestions:o,showTabCompletion:i,showTextSuggestions:s,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,isEmbedded:p,detectSubmit:d,insertLink:g,inputMediator:S,closestScrollSelector:y,appendOverlayTo:m,inlineSuggestions:f,floatingMenu:h}=n;this.configure({showStyleSuggestions:o,showTabCompletion:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,showTextSuggestions:s,insertLink:g,isEmbedded:p,inlineSuggestions:f,floatingMenu:!!h}),n.automaticHandlingTime&&this.setupHandlingTime(t),Vo(t),this.inputMediator=S||(eo(t)?new Xo(t):new Go(t)),this.inputMediator.on("change",({plainText:T,rawHTML:C})=>{this.store.dispatch(sd({text:T,html:C}))}),this.inputMediator.on("keyup",T=>{this.store.dispatch(A1(T))}),this.inputMediator.on("keydown",T=>{this.handleKeyDown(T)}),this.inputMediator.on("paste",({pastedText:T,selectionText:C})=>{this.store.dispatch(L1({text:T,selectionText:C}))}),this.inputMediator.on("cut",({selectionText:T})=>{this.store.dispatch(P1(T))});let v;this.inputMediator.on("selection",T=>{clearTimeout(v),T===null?v=setTimeout(()=>{T!==null&&this.store.dispatch(ad(T))},500):this.store.dispatch(ad(T))}),this.inputMediator.on("disabled",()=>{var T;(T=this.inputMediator)==null||T.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{d&&this.notifySubmit()}),this.inputMediator.on("blur",()=>{this.store.dispatch(qd(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(qd(!0))});let x=y&&lk(t,y)||void 0;if(f){let{customStyles:T,appendOverlayTo:C}=n;if(eo(t))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let R=this.createInlineContainer(t,"deepdesk-caret");(0,Yt.render)((0,_e.jsx)(Wo,{store:this.store,customStyles:T,children:(0,_e.jsx)(Io,{broadcastEvents:this.broadcastEvents,children:(0,_e.jsx)(qb,{})})}),R),this.inputMediator.on("caretposition",_=>{this.store.dispatch(Gn([])),_?(R.style.display="block",R.style.top=`${_.top}px`,R.style.left=`${_.left}px`):R.style.display="none"});let O=this.overlayContainerFactory("floating-menu",x||t,{appendTo:typeof h=="object"&&"appendOverlayTo"in h?h.appendOverlayTo:C},T==null?void 0:T.floatingMenuRootNode);(0,Yt.render)((0,_e.jsx)(Wo,{store:this.store,customStyles:T,children:(0,_e.jsx)(Io,{broadcastEvents:this.broadcastEvents,children:(0,_e.jsx)(Db,{onLogIn:()=>this.loginViaPopup().catch(_=>z.warn(_.message))})})}),O)}else{let T=this.overlayContainerFactory("deepdesk-tab-completion",x||t,{appendTo:m,closestScrollElement:x,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),C=this.overlayContainerFactory("deepdesk-suggestions-overlay",x||t,{appendTo:m},r==null?void 0:r.suggestionsRootNode);(0,Yt.render)((0,_e.jsx)(Wo,{store:this.store,customStyles:r,children:(0,_e.jsx)(Io,{broadcastEvents:this.broadcastEvents,children:(0,_e.jsx)(bC,{inputElement:t})})}),T),(0,Yt.render)((0,_e.jsx)(Wo,{store:this.store,customStyles:r,children:(0,_e.jsx)(Io,{broadcastEvents:this.broadcastEvents,children:(0,_e.jsx)(nC,{onLogIn:()=>this.loginViaPopup().catch(R=>z.warn(R.message))})})}),C)}(0,Yt.render)((0,_e.jsx)(Wo,{store:this.store,customStyles:r,children:(0,_e.jsx)(Io,{broadcastEvents:this.broadcastEvents,children:(0,_e.jsx)(Ib,{})})}),this.createContainer("deepdesk-overlays")),this.store.dispatch(sd({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()})),this.store.dispatch(ad(this.inputMediator.getSelection())),this.store.dispatch(qd(this.inputMediator.isFocused)),this.unmountHandlers.push(()=>{this.state.input.text!==""&&this.storeMetrics()}),this.whenConversationLoaded(()=>{var T;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((T=this.state.conversation.current)==null?void 0:T.sessionId)}),this.isMounted=!0}unmount(){var t;this.unmountHandlers.forEach(n=>n()),this.unmountHandlers=[],(t=this.inputMediator)==null||t.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(t,n={}){if(this.widgetRoot&&z.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:i}=n;this.widgetRoot=t,this.configure({showImages:o,isEmbedded:i}),(0,Yt.render)((0,_e.jsx)(Wo,{store:this.store,customStyles:r,children:(0,_e.jsx)(Io,{broadcastEvents:this.broadcastEvents,children:(0,_e.jsx)(UT,{onLogIn:()=>this.loginViaPopup().catch(s=>z.warn(s.message))})})}),t),this.whenConversationLoaded(()=>{var s;this.broadcastEvents.setSessionId((s=this.state.conversation.current)==null?void 0:s.sessionId)})}unmountWidget(){this.widgetRoot&&(0,Yt.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(t){let n=Of(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){uk(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(()=>k(this,null,function*(){yield this.store.dispatch(al());let t=rr(this.state);t&&(yield this.store.dispatch(ol()),this.store.dispatch(Yc({showSearch:t.search,showAutoflows:t.autoflows,showCustomMessages:t.customMessages,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:t.summarizer,showKnowledgeSearch:!!t.knowledgeAssistant,recommendTextSuggestions:t.recommendTextSuggestions})))})),this.loadProfileConfigPromise)}loginViaPopup(t){return k(this,null,function*(){return new Promise((n,r)=>{let o=new MessageChannel,i=o.port1,s=this.state.settings.adminUrl,a=new URL(t!=null&&t.url?t==null?void 0:t.url:`${s}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let l=!1,u=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",p),clearInterval(d)};i.onmessage=g=>k(this,null,function*(){var S,y;if((S=g.data)!=null&&S.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((y=g.data)==null?void 0:y.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(Ba),l=!0,o.port1.close(),n()}catch(m){console.error(m),r(m)}finally{l=!0,u()}});let c=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");c===null&&r(new Error("Popup blocked by browser"));let p=g=>k(this,null,function*(){var S;if(g.origin===a.origin)switch((S=g.data)==null?void 0:S.type){case"deepdesk-popup-loaded":{try{let y=JSON.stringify({type:"deepdesk-popup-create-channel"});c==null||c.postMessage(y,a.origin,[o.port2])}catch(y){z.error("Error posting message to popup",y),r(y)}break}case"deepdesk-popup-error":{u(),g.data.message==="Timeout"&&z.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(g.data.message));break}}});window.addEventListener("message",p);let d=setInterval(()=>{c&&!c.closed||(u(),l||r(new Error("Popup closed by user")))},200);this.unmountHandlers.push(u)})})}translateMessages(t){return this.deepdeskApi.translateMessages(t)}checkForTrialMode(t){return k(this,null,function*(){try{let{account:n}=yield this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(z.info("Trial is active"),!(yield this.deepdeskApi.checkUserExists(t)))throw new Error("User is not in trial");this.shouldRender=!0}catch(n){let{message:r}=n;z.info(r),this.shouldRender=!1}})}refreshWidgetSuggestions(){return k(this,null,function*(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=zd(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch(un()):tu.includes(r)||this.store.dispatch(dn(r))})}catch(r){this.handleError(r)}})}};Es.version="11.6.1-beta.4",Es.count=0;var Nl=Es;function Ek(r,o){return k(this,arguments,function*(e,t,n={}){var p,d;let{value:i}=e,{start:s,end:a}=(p=n.replace)!=null?p:{start:0,end:i.length},l=`${i.slice(0,s)}${t}${i.slice(a)}`,u=(d=n.selectionAfter)!=null?d:{start:s+t.length,end:s+t.length},c=()=>{if(n.setValue)return n.setValue(l);e.value=l};return Promise.resolve(c()).then(()=>{e.selectionStart=u.start,e.selectionEnd=u.end,e.blur(),e.focus()})})}function bk(r,o){return k(this,arguments,function*(e,t,n={}){let i=n.replace?oo(e,n.replace.start,n.replace.end):vs(e),s,a=()=>{if(n.setRange)return n.setRange(i.cloneRange());i.deleteContents(),s=document.createElement("span"),i.insertNode(s),n.insertBRs!==!1?t.split(`
|
|
27
|
+
`);break}default:break}p&&s++}return l(e),a}var BT=(s=>(s.CUT="Cut",s.BACKSPACE="Backspace",s.DELETE="Delete",s.ERASEEOF="EraseEof",s.UNDO="Undo",s.CLEAR="Clear",s))(BT||{}),dr=class{constructor(t){this.element=t;this.isFocused=!1;this.isActive=!0;this.isDisposed=!1;this.eventListeners={};this.disposeHandlers=[];this.cachedText="";this.cachedCaretPosition=null;this.cachedSelection={start:0,end:0};this.cachedHTML="";this.isSubmitting=!1;this.isPossibleClearInputAction=!1;this.cachedText=this.getText(),this.cachedHTML=this.getHTML(),this.cachedSelection=this.getSelection(),this.listen()}addEventListener(t,n){let r=o=>{n(o)};this.element.addEventListener(t,r),this.disposeHandlers.push(()=>{this.element.removeEventListener(t,r)})}removeEventListener(t,n){this.element.removeEventListener(t,n)}handleInteraction(){let t=this.getText(),n=this.getHTML(),r=this.getSelection(),o=this.getCaretPosition();this.isActive&&(t===""&&this.cachedText!==""&&!this.isPossibleClearInputAction&&this.emit("submit"),t!==this.cachedText&&(this.cachedText=t,this.cachedHTML=n,this.emit("change",{plainText:t,rawHTML:n})),(r.start!==this.cachedSelection.start||r.end!==this.cachedSelection.end)&&(this.cachedSelection=r,this.emit("selection",r)),Wr(o,this.cachedCaretPosition)||(this.cachedCaretPosition=o,this.emit("caretposition",o)))}handleClick(){this.handleInteraction()}handleFocus(){let t=!this.isFocused;this.isFocused=!0,t&&this.emit("focus"),this.handleInteraction()}handleBlur(){this.isPossibleClearInputAction=!1;let t=this.isFocused;this.isFocused=!1,t&&this.emit("blur")}handleKeyDown(t){let{key:n,ctrlKey:r,metaKey:o}=t;this.isPossibleClearInputAction=Object.values(BT).includes(n)||n.toLowerCase()==="z"&&(r||o),this.emit("keydown",t)}handleKeyUp(t){this.handleInteraction(),this.emit("keyup",t)}handleCut(){this.isPossibleClearInputAction=!0,this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(t){var r,o;let n=((r=t.clipboardData)==null?void 0:r.getData("text"))||((o=t.clipboardData)==null?void 0:o.getData("text/plain"))||"";this.emit("paste",{pastedText:n,selectionText:this.getSelectedText()})}listen(){this.addEventListener("keydown",n=>this.handleKeyDown(n)),this.addEventListener("keyup",n=>this.handleKeyUp(n)),this.addEventListener("input",()=>this.handleInteraction()),this.addEventListener("change",()=>this.handleInteraction()),this.addEventListener("focus",()=>this.handleFocus()),this.addEventListener("blur",()=>this.handleBlur()),this.addEventListener("cut",()=>this.handleCut()),this.addEventListener("paste",n=>this.handlePaste(n)),this.addEventListener("click",()=>this.handleInteraction()),document.activeElement===this.element&&(this.isFocused=!0);let t=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});t.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{t.disconnect()})}focus(){this.element.focus()}emit(t,...n){this.isDisposed||this.eventListeners[t]&&this.eventListeners[t].forEach(r=>{r(...n)})}on(t,n){this.isDisposed||(this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n))}activate(){let t=this.isActive===!1;this.isActive=!0,t&&this.handleInteraction()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(t=>t()),this.eventListeners={},this.isDisposed=!0}};function jT(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var Go=class extends dr{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),Al(this.element,n)}getHTML(){return this.element.innerHTML||""}getRange(){var s;let n=this.getRootNode();if(n.activeElement!==this.element)return null;let r="getSelection"in n?n.getSelection():window.getSelection();if(!r)return null;let o="getComposedRanges"in r&&n instanceof ShadowRoot?(s=r.getComposedRanges(n))==null?void 0:s[0]:r.rangeCount>0?r.getRangeAt(0):null;if(!o)return null;let i=this.element.ownerDocument.createRange();return i.setStart(o==null?void 0:o.startContainer,o==null?void 0:o.startOffset),i.setEnd(o==null?void 0:o.endContainer,o==null?void 0:o.endOffset),!i||!this.element.contains(i.startContainer)||!this.element.contains(i.endContainer)?null:i}getCaretPosition(){let n=this.getRange();if(!n||!n.collapsed||!("getBoundingClientRect"in n))return null;let r=n.getBoundingClientRect();return!jT(r)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),r=n.getBoundingClientRect(),n.deleteContents(),!jT(r))?null:{top:r.top+r.height,left:r.left}}getSelection(){let n=this.getRange();if(n)return Rl(this.element,n);let r=this.lastKnownSelection;if(r&&zT(this.element,r.start,r.end))return r;let o=vs(this.element);return o.collapse(!1),Rl(this.element,o)}getSelectedText(){let{start:n,end:r}=this.getSelection();return Al(this.element,oo(this.element,n,r))}listen(){super.listen();let n=new MutationObserver(()=>{setTimeout(()=>{this.handleInteraction()},0)});n.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0}),this.disposeHandlers.push(()=>n.disconnect());let r=this.element.isContentEditable,o=new MutationObserver(()=>{this.element.isContentEditable!==r&&(r=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>o.disconnect())}};var Xo=class extends dr{constructor(){super(...arguments);this.lastKnownSelection=null}getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:n,selectionEnd:r}=this.element;return{start:n,end:r}}getSelectedText(){let n=this.getSelection();return n?this.getText().slice(n.start,n.end):""}getCaretPosition(){return null}listen(){super.listen();let n=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var i;return(i=n==null?void 0:n.get)==null?void 0:i.call(this.element)},set:i=>{var s;(s=n==null?void 0:n.set)==null||s.call(this.element,i),this.handleInteraction()}});let r=this.element.disabled,o=new MutationObserver(()=>{this.element.disabled!==r&&(r=this.element.disabled,this.emit(r?"disabled":"enabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>o.disconnect())}};function VT(e,t,n){let r=`deepdesk-iframe-${e}`,o=document.getElementById(r);if(o)return o;let i=document.createElement("iframe"),s=new URL(t);return Object.entries(n).forEach(([a,l])=>{s.searchParams.append(a,l)}),i.style.position="absolute",i.style.left="-999em",i.style.width="0px",i.style.height="0px",i.tabIndex=-1,i.id=r,i.title=`iframe-${e}`,i.src=s.toString(),window.document.body.appendChild(i),i}function WM(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(t){return e}}var by=class{constructor(t){this.name=t;this.disposeHandlers=[];this.broadcastChannel=new BroadcastChannel(t)}onMessage(t){this.broadcastChannel.addEventListener("message",t),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",t)})}postMessage(t){this.broadcastChannel.postMessage(JSON.stringify(t))}close(){this.disposeHandlers.forEach(t=>t()),this.broadcastChannel.close()}},Cy=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.disposeHandlers=[];this.iframe=VT(t,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}onMessage(t){window.addEventListener("message",t),this.disposeHandlers.push(()=>{window.removeEventListener("message",t)})}postMessage(t){var n;(n=this.iframe.contentWindow)==null||n.postMessage(JSON.stringify(t),this.targetOrigin)}close(){var t;this.disposeHandlers.forEach(n=>n()),(t=this.iframe)==null||t.remove()}},Ty=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.eventMap,this.sessionId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setSessionId(t){this.sessionId!==t&&(this.cleanup(),z.info("Set sessionId",t),this.sessionId=t,this.channel=this.createChannel(t))}createChannel(t){let n=this.params.createCustomChannel?this.params.createCustomChannel(t):this.isCrossOrigin?new Cy(t,this.deepdeskUrl,{debug:!0}):new by(t),r=o=>{var s,a;if(o.origin!==this.deepdeskUrl)return;let i=WM(o.data);typeof i!="object"||i.type!=="event"||i.channel!==t||(z.info("Received broadcast event",this.sessionId,o),(a=(s=this.eventMap)[i.name])==null||a.call(s,i.payload))};return n.onMessage(r),n}send(t,n,r){var s,a;z.info("Broadcast event",{sessionId:this.sessionId,name:t,payload:n});let o={type:"event",name:t,payload:n};r!==!1&&((a=(s=this.eventMap)[t])==null||a.call(s,n));let i=this.sessionId==="deepdesk-general"?this.defaultChannel:this.channel;i==null||i.postMessage(N(P({},o),{channel:this.sessionId}))}cleanup(t=!1){var n,r;(n=this.channel)==null||n.close(),delete this.channel,t&&((r=this.defaultChannel)==null||r.close(),delete this.defaultChannel)}},KT=Ty;var Ss=class extends Error{constructor(n,r){super(n);this.body=r;this.name="CustomError"}};var ky=e=>new Promise(t=>{setTimeout(t,e)});var ws=class extends Ss{constructor(){super(...arguments);this.name="ClientError"}},Ry=class extends Ss{constructor(){super(...arguments);this.name="ServerError"}},Py=new Map;function $M(e){return k(this,null,function*(){if(e.status===204)return e.text().catch(()=>{}),null;let t=e.headers.get("content-type");if(t&&t.includes("application/json"))return e.json();let n=yield e.text();return n===""?null:(z.warn("Unexpected response body:",n.slice(0,20)),JSON.parse(n))})}var io=class io{constructor(t="",n={}){this.baseUrl=t;this.options=n;this.latestRequestByUrl={};this.fetch=window.fetch.bind(window);n.fetch&&(this.fetch=n.fetch)}patchFetch(t){this.fetch=t(this.fetch)}setCsrfToken(t){this.csrfToken=t}request(t,n={}){return new Promise((r,o)=>{let i={isAborted:!1,reject:o},s=`${this.baseUrl}${t}`,a=this.fetch,l=n.method===void 0||n.method.toLowerCase()==="get",C=n,{useCache:u=!1,abortLatest:c=!1,attempts:p=1,retryDelay:d=500,refreshTokenOn401:g=!0,retryOnError:S=R=>R instanceof TypeError,retryOnResponse:y=R=>R.status>=500,version:m="v1"}=C,f=te(C,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]);if(u)if(l){if(Py.has(s)){r(Py.get(s));return}}else throw new Error(`Can't use 'useCache' for ${n.method}`);let h=N(P({credentials:"include"},f),{headers:P({"Content-Type":"application/json"},f.headers)});!l&&this.csrfToken&&(h.headers=N(P({},h.headers),{"X-CSRFToken":this.csrfToken})),typeof m=="string"&&(h.headers=N(P({},h.headers),{"X-Deepdesk-API-Version":m}));let v=p,x=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[s]&&c&&(this.latestRequestByUrl[s].isAborted=!0,this.latestRequestByUrl[s].reject(new Error("Aborted"))),this.latestRequestByUrl[s]=i;let T=()=>k(this,null,function*(){return v--,a(s,h).then(R=>k(this,null,function*(){return y(R)&&!i.isAborted&&v>0?(yield ky(d),T()):R.status===401&&g===!0&&x===!1?(x=!0,yield this.refreshToken(),T()):R})).catch(R=>k(this,null,function*(){if(S(R)&&!i.isAborted&&v>0)return yield ky(d),T();throw R}))});T().then(R=>k(this,null,function*(){let O=yield $M(R);if(delete this.latestRequestByUrl[s],R.status>=500){o(new Ry("Server Error",O));return}else if(R.status===401){o(new ws("Unauthorized",O));return}else if(R.status===403){o(new ws("Forbidden",O));return}else if(R.status===404){o(new ws("Not Found",O));return}else if(R.status>=400){o(new ws("Bad Request",O));return}u&&Py.set(s,O),r(O)})).catch(R=>{o(R)})})}validateToken(){return k(this,null,function*(){let{has_valid_access_token:t}=yield this.get("/auth/validate");if(!t)return!1;let{is_logged_in:n}=yield this.get("/apis/admin/session/validate/",{version:null});return!!n})}refreshToken(){return io.refreshingToken||(io.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{io.refreshingToken=null},1e3*60)})),io.refreshingToken}get(t,n){return this.request(t,n)}post(t,n,r){return this.request(t,P({method:"POST",body:JSON.stringify(n)},r))}patch(t,n,r){return this.request(t,P({method:"PATCH",body:JSON.stringify(n)},r))}put(t,n,r){return this.request(t,P({method:"PUT",body:JSON.stringify(n)},r))}delete(t,n){return this.request(t,P({method:"DELETE"},n))}};io.refreshingToken=null;var hn=io;var WT;(t=>{let e;(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"))(e=t.EventType||(t.EventType={}))})(WT||(WT={}));function kf(e){return N(P({},re(e)),{tags:e.tags})}var Yo=class Yo{constructor(t,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new hn(t,{fetch:n.fetch}),this.client.patchFetch(r=>(o,i)=>k(this,null,function*(){let s=yield r(o,i);return this.handleDeepdeskVersionHeaders(s),s}))}preflight(){return k(this,null,function*(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=yield this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(Yo.exchangeTokenPromise||(Yo.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),Yo.exchangeTokenPromise):Promise.resolve()})}createConversation(t){return k(this,null,function*(){yield this.preflight(),z.info(`Creating conversation for session ${t.sessionId} and agent ${t.agentId}`);let n=yield this.client.post("/api/conversations",N(P({},Oe(t)),{tags:t.tags}),{version:"v2"});return kf(n)})}getProfile(t){return k(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${t}/`,{version:null,useCache:!0});return re(n)})}getKnowledgeAssistant(t){return k(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{version:null,useCache:!0});return re(n)})}getContentTypes(){return k(this,null,function*(){let t=yield this.client.get("/apis/admin/content-types/",{version:null,useCache:!0});return re(t)})}getAccount(){return k(this,null,function*(){let t=yield this.client.get("/apis/admin/account/",{version:null,useCache:!0});return re(t)})}getPlatformConfig(){return k(this,null,function*(){let{config:t}=yield this.client.get("/platform/config/",{version:null,useCache:!0});return re(t)})}checkUserExists(t){return k(this,null,function*(){let{exists:n}=yield this.client.get(`/apis/admin/users/exists?external_id=${t}`);return n})}getConversationBySessionId(r){return k(this,arguments,function*(t,n={}){yield this.preflight(),z.info(`Getting conversation for session ${t}`);let{attempts:o=1,retryDelay:i=1e3}=n,s=yield this.client.get(`/api/conversations/by_session_id/${t}`,{attempts:o,retryDelay:i,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"});return z.info(`Successfully retrieved conversation ${s.id} for session ${t}`),kf(s)})}isConversationSupported(r){return k(this,arguments,function*(t,n={}){z.info(`Check if conversation for session ${t} is supported`);let{attempts:o=1,retryDelay:i=1e3}=n;return(yield this.client.get(`/api/conversations/by_session_id/${t}/active_profile`,{attempts:o,retryDelay:i,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"})).has_active_profile})}updateConversation(t,n){return k(this,null,function*(){let r=Oe(n);n.tags&&(r.tags=n.tags);let o=yield this.client.put(`/api/conversations/${t}`,r,{version:"v2"});return kf(o)})}postMessages(t,n){return k(this,null,function*(){return(yield this.client.post(`/api/conversations/${t}/messages`,n.map(o=>N(P({},Oe(o)),{tags:o.tags})),{version:"v2"})).map(o=>kf(o))})}sendEvent(t,n){return k(this,null,function*(){let s=n,{data:r}=s,o=te(s,["data"]),i=Object.entries(this.latestReceivedDeepdeskVersions).reduce((a,[l,u])=>N(P({},a),{[l]:u}),{});return this.client.post("/api/events",Oe(N(P(P({},i),o),{data:r,name:t})),{version:"v2"})})}sendEventV1(t,n){return k(this,null,function*(){let r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((o,[i,s])=>N(P({},o),{[i]:s}),{});return this.client.post("/api/events",{event:t,data:Oe(P(P({},n),r))})})}getEntities(t){return k(this,null,function*(){return(yield this.client.post("/api/entities",{messages:t.filter(r=>r.text)})).entities})}getSummary(r){return k(this,arguments,function*(t,n={}){let o=yield this.client.post("/api/summary",{conversation:{messages:t.filter(i=>i.text&&i.source),agent_id:n.agentId,id:n.externalConversationId},prompt_instruction:n.promptInstruction,model:n.model});return re(o)})}getTemporaryExchangeToken(){return k(this,null,function*(){return(yield this.client.get("/auth/exchange-token",{version:null})).jwt})}exchangeTokenForAccessCookie(t){return k(this,null,function*(){return this.client.post("/apis/admin/session/jwt/",{jwt:t},{version:null}).catch(n=>{throw z.warn(`Invalid token '${t}'`),n})})}authenticateWithKey(t,n){return k(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/api-key/",Oe(n),{version:null,refreshTokenOn401:!1,headers:{apikey:t}})})}getTextSuggestions(o){return k(this,arguments,function*(t,n={},r){return r==="sticky-messages"?this.getPinnedMessages(t):(yield this.client.post(`/api/conversations/${t}/recommend/${r}`,Oe(n),{abortLatest:!0})).map(s=>N(P({},re(s)),{text:s.text||s.url||s.message,source:r,type:r})).filter((s,a,l)=>a===l.findIndex(u=>u.text===s.text))})}isLoggedIn(){return k(this,null,function*(){return yield this.preflight(),this.client.validateToken()})}getAutocompleteSuggestions(t,n){return k(this,null,function*(){return(yield this.client.post(`/api/conversations/${t}/autocomplete`,Oe(n),{abortLatest:!0})).map(o=>({score:1,source:o.source,sourceText:o.source_text,text:o.label,trainingJobs:o.training_jobs,searchKeywords:o.search_keywords,type:o.source})).filter((o,i,s)=>i===s.findIndex(a=>a.text===o.text))})}getPinnedMessages(t){return k(this,null,function*(){let n=yield this.client.get(`/api/conversations/${t}/sticky-messages`,{abortLatest:!0});return re(n).map(r=>N(P({},r),{text:r.message,source:"sticky-messages",type:"pinned-message"}))})}getStyleSuggestions(t){return k(this,null,function*(){let n=yield this.client.post("/api/style-suggestions",Oe(t),{abortLatest:!0});return re(n)})}search(t){return k(this,null,function*(){let n=yield this.client.post(`/api/profiles/${t.profile}/search`,Oe(t),{version:"v2"});return re(n)})}knowledgeAssist(i,s,a){return k(this,arguments,function*(t,n,r,o={}){let l=yield this.client.post(`/api/knowledge-assist/assistants/${r}/search`,Oe({question:t.question,doNotKnowAnswer:t.doNotKnowAnswer,customerInstruction:t.customerInstruction,chatHistory:n.map(u=>({question:u.question,answer:u.answer.answer})),agentId:o.agentId,conversationId:o.conversationId}),{version:"v2"});return re(l)})}requestLoginByEmail(t){return k(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:t},{version:null});return re(n)})}requestPasswordlessToken(){return k(this,null,function*(){let t=yield this.client.get("/apis/admin/session/passwordless/request/",{version:null});return re(t.token)})}getCsrfToken(){return k(this,null,function*(){let{token:t}=yield this.client.get("/apis/admin/session/csrf/",{version:null});return t})}verifyLoginToken(t){return k(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/login/",{token:t},{version:null});return re(n)})}evaluateRule(i,s,a){return k(this,arguments,function*(t,n,r,o={}){let l=new URLSearchParams;o.raiseForFailingConditions&&l.set("raise_for_failing_conditions","true");let u=yield this.client.post(`/api/conversations/${n}/rules/${t}/evaluate?${l.toString()}`,r,{version:"v2"});return u?re(u.cues):[]})}getRules(){return k(this,null,function*(){let t=new URLSearchParams,n=yield this.client.get(`/apis/admin/rule-engine/rules/?${t.toString()}`,{version:null,useCache:!0});return re(n)})}translateMessages(t){return k(this,null,function*(){let n=yield this.client.post("/api/translate",Oe(t),{version:"v2"});return re(n)})}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),i=o.match($v);if(!n||!i)return;let s=i[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[s];a&&n&&a!==n&&z.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[s]=n})}};Yo.exchangeTokenPromise=null;var fr=Yo;var Ll=class{constructor(t,n){this.url=t;this.eventListeners={};this.options=P({timeout:25e3},n)}proxyEvent(t){this.eventSource.addEventListener(Zg(t),n=>{let{data:r}=n;try{let o=JSON.parse(r);this.emit(t,re(o))}catch(o){z.warn(`Invalid JSON for ${t}: ${r}`)}})}connect(){clearTimeout(this.timeoutTimer);let t=new EventSource(this.url,{withCredentials:!0});this.eventSource=t;let n=!1;t.onopen=()=>{n=!0},t.onerror=()=>{n&&t.readyState===2&&this.connect()},this.timeoutTimer=setTimeout(()=>{t.close(),this.connect()},this.options.timeout),Object.keys(this.eventListeners).forEach(r=>{this.proxyEvent(r)})}disconnect(){var t;clearTimeout(this.timeoutTimer),this.eventListeners={},(t=this.eventSource)==null||t.close()}emit(t,n){this.eventListeners[t]&&this.eventListeners[t].forEach(r=>r(n))}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),this.proxyEvent(t),()=>{this.off(t,n)}}off(t,n){let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}};var $T;(t=>{let e;(i=>(i.Started="Started",i.Aborted="Aborted",i.Completed="Completed"))(e=t.AutoflowSessionState||(t.AutoflowSessionState={}))})($T||($T={}));var Il=class{constructor(t,n={}){this.apiUrl=t;this.streams={};this.logger=z;this.client=new hn(t,n)}getCustomMessages(t){return k(this,null,function*(){let n=yield this.client.get(`/sessions/${t}/suggestions`);return re(n.suggestions)})}sendCustomMessage(t,n){return k(this,null,function*(){let r=yield this.client.post(`/sessions/${t}/messages`,Oe(n));return re(r)})}answerCustomMessage(t,n){return k(this,null,function*(){yield this.client.post(`/sessions/${t}/answers`,Oe(n))})}getAutoflows(t){return k(this,null,function*(){let n=yield this.client.get(`/sessions/${t}/autoflows`);return re(n.autoflows)})}startAutoflowSession(t){return k(this,null,function*(){let n=yield this.client.post("/autoflow-sessions",Oe(t));return re(n)})}stopAutoflowSession(t){return k(this,null,function*(){yield this.client.delete(`/autoflow-sessions/${t}`)})}openStream(t){return this.streams[t]||(this.streams[t]=new Ll(`${this.apiUrl}/sessions/${t}/events`),this.streams[t].connect()),this.streams[t]}closeStream(t){this.streams[t]||(this.streams[t].disconnect(),delete this.streams[t])}};var qT={startTime:null,stopTime:null},GT=Q({name:"handlingTime",initialState:qT,reducers:{handlingTimeStart(e){if(e.startTime&&!e.stopTime)throw new Error("Timing already started");e.startTime=new Date,e.stopTime=null},handlingTimeStop(e){if(!e.startTime)throw new Error("Timing not started");e.stopTime=new Date},handlingTimeReset(e){e.startTime=null,e.stopTime=null}},extraReducers:e=>{e.addCase(fe,()=>qT)}}),{handlingTimeStart:XT,handlingTimeStop:Pf,handlingTimeReset:YT}=GT.actions,QT=GT.reducer;var ZT=(e={})=>{let t=P({onAuthError:Xi(!1)},e);return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var Rf={list:{keywordMatches:[]},fetchState:"idle"};var Qo=K("styleSuggestions/getAll",(n,r)=>k(void 0,[n,r],function*({text:e},t){var l;let{deepdeskAPI:o}=t.extra,i=t.getState(),{showStyleSuggestions:s}=i.settings,a=(l=i.conversation.current)==null?void 0:l.profileCode;if(!s)return Rf.list;if(!a)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:a,message:e})})),qM=Q({name:"styleSuggestions",initialState:Rf,reducers:{},extraReducers:e=>{e.addCase(Qo.pending,t=>{t.fetchState="loading"}).addCase(Qo.rejected,t=>{t.fetchState="error"}).addCase(Qo.fulfilled,(t,n)=>{t.fetchState="done",Wr(t.list,n.payload)||(t.list=n.payload)}).addCase(Ao,t=>{t.list=Rf.list}).addCase(fe,()=>Rf)}}),JT=qM.reducer;var ek=(e={})=>{let t,n=!0,r=P({getStyleSuggestions:Qo,debounce:500},e);return o=>i=>s=>{var g;let a=o.getState().input.text,l=i(s),u=o.getState();if(u.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:c}=u.settings;if(!((g=u.conversation.current)==null?void 0:g.id)||!c)return l;let{text:d}=u.input;return d===a&&!n||(clearTimeout(t),d==="")||(t=setTimeout(()=>{n=!1,o.dispatch(r.getStyleSuggestions({text:d}))},e.debounce)),l}};function GM(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var tk=(e={})=>{let t=P({getTextSuggestions:dn,getAutocompleteSuggestions:ll,debounce:200,check:ds},e),n;return r=>o=>i=>{var y;let{input:s}=r.getState(),a=o(i),l=r.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:u,showTabCompletion:c}=l.settings,p=(y=l.conversation.current)==null?void 0:y.id,d=i.type===jd.toString();if(!p||!u&&!c)return a;let{input:g}=l;return GM(g,s)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let m=Ji(l);m===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(m))},d?0:t.debounce)),a}};var nk=Qo.fulfilled.toString();function XM(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let i=e.keywordMatches.filter(l=>l.keyword===o),s=t.keywordMatches.filter(l=>l.keyword===o),a=s.length-i.length;a<=0||r.push(...s.slice(0,a))}),r}var rk=e=>t=>n=>r=>{var u;if(r.type!==nk){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let i=t.getState(),s=i.styleSuggestions.list,a=(u=i.conversation)==null?void 0:u.current;if(o===s)return;let l=XM(o,s);r.type===nk&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var YM=xc({answer:lb,auth:f1,autoflows:AC,conversation:E1,contentTypes:vE,customMessages:HC,passwordlessToken:BC,entities:VE,knowledgeAssistant:ib,handlingTime:QT,info:z1,input:M1,settings:i1,profile:fb,search:q1,summary:YE,styleSuggestions:JT,ui:Bb,rules:$C,textSuggestions:wb});function ok(e){return dx({reducer:YM,middleware:t=>[...t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI,deepdeskBrokerAPI:e.deepdeskBrokerAPI}},serializableCheck:!1}),ZT(),tk({debounce:200}),ek({debounce:500}),rk(e.deepdeskAPI),...e.middleware?e.middleware:[]],preloadedState:e.preloadedState})}var QM=e=>{var t,n;return(n=(t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())!=null?n:"unknown"},ZM=e=>t=>n=>r=>{var a,l,u,c,p,d;let o=t.getState(),i=qg("inlineSuggestions")(o);switch(r.type){case Xi.toString():{!r.payload&&e.emit("logout",void 0);break}case un.fulfilled.toString():r.payload.length>0&&e.sendEvent("entities found",{conversationId:(a=o.conversation.current)==null?void 0:a.id,data:{entities:r.payload}});break;case ot.toString():e.sendEvent(r.payload.name,{conversationId:((l=r.payload.options)==null?void 0:l.includeConversationData)&&((u=o.conversation.current)==null?void 0:u.id),data:r.payload.data});break;case Ao.toString():e.logSendMessage(r.payload);break;case $o.fulfilled.toString():r.isBroadcasted||e.broadcast(th,r,!1),(c=r.payload.options)!=null&&c.shouldEmit&&e.emit("cues",r.payload.cues);break;default:break}let s=n(r);switch(r.type){case Ao.toString():e.handleAfterSendMessage(r.payload);break;case cl.toString():e.onUpdateShowTabHint(r.payload);break;case Pf.toString():e.logHandlingTime();break;case"analytics/logEvent/fulfilled":{e.emit("event",r.meta.arg);break}case nd.toString():{let{start:g,end:S}=o.input.selection;e.emit("replace",N(P({},r.payload),{replace:r.payload.replace==="selection"?{start:g,end:S}:{start:0,end:S}}));break}case qn.toString():{let{start:g,end:S}=o.input.selection;e.emit("select-suggestion",N(P({type:QM(r.payload.suggestion)},r.payload),{replace:r.payload.replace==="selection"?{start:g,end:S}:{start:0,end:S}})),i&&t.dispatch(Gn([]));break}case rd.toString():e.emit("select-image",r.payload),e.sendEvent("Image attached",{conversationId:(p=o.conversation.current)==null?void 0:p.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case Gn.toString():{i&&r.payload.length>0&&t.dispatch(id(0));break}case er.fulfilled.toString():{e.sendEvent("conversation summarized",{conversationId:(d=o.conversation.current)==null?void 0:d.id,data:{summary:r.payload.summary,model:t.getState().summary.model}});break}default:break}return s},ik=ZM;function Ay(e){return e.toISOString().replace("T"," ").replace("Z","")}function sk(e,t){var i,s,a,l;let n=(i=e.conversation.current)==null?void 0:i.id;if(!n)return z.warn("No conversationId for handling time metrics"),null;let{startTime:r,stopTime:o}=e.handlingTime;return!r||!o?(z.warn("No startTime and stopTime for handling time metrics"),null):{conversationId:n,clientVersion:t.version,agentId:(s=e.info.agentInfo)==null?void 0:s.agentId,agentName:(a=e.info.agentInfo)==null?void 0:a.agentName,agentEmail:(l=e.info.agentInfo)==null?void 0:l.agentEmail,timeStart:Ay(r),timeStop:Ay(o)}}function ak(e,t,n){var O,_,D,G;let r=(O=t.conversation.current)==null?void 0:O.id;if(!r)return z.warn("No conversationId for send message metrics"),null;let{text:o,metrics:{numCharsTyped:i,numCharsPasted:s,numCharsCut:a,numCharsDeleted:l,numPaste:u,agentStartedTypingTimestamp:c,externalTimeTotalSeconds:p,pastes:d,cuts:g,deletions:S,textSuggestions:y,offeredTextSuggestions:m}}=t[e],f=o.length,v=y.reduce((Z,{text:se,searchTerm:pr})=>Z+se.length-(pr?pr.length:0),0),x=c!=null?c:Date.now(),T=(Date.now()-x)/1e3+(p||0),C=i/T,R=y.reduce((Z,{searchTerm:se})=>Z+(se?se.length:0),0);return{conversationId:r,source:"agent",text:o,clientVersion:n.version,pastes:d,cuts:g,deletions:S,lenTextTyped:i+R,lenTextTotal:f,lenTextAssisted:v,lenTextPasted:s,lenTextCut:a,lenTextDeleted:l,timeTotalSeconds:T,charsPerSecond:C,numPastes:u,textSuggestionsV2:y,suggestionsCounters:[{source:"gpt",countOffered:m.filter(Z=>Z.source==="gpt").length}],agentId:(_=t.info.agentInfo)==null?void 0:_.agentId,agentName:(D=t.info.agentInfo)==null?void 0:D.agentName,agentEmail:(G=t.info.agentInfo)==null?void 0:G.agentEmail}}function Ly(e,t){var i;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return Ly(r,t);let o=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;return o?Ly(o,t):null}function lk(e,t){return Ly(e,t)}function uk(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function JM(e){return typeof e=="object"&&e!==null&&"tagName"in e}function Af(e){return JM(e)&&(eo(e)||Jd(e))}var dk,Ln=new Map,e2=["bottom","height","left","right","top","width"],ck=(e,t)=>!e&&!t?!1:e&&!t||!e&&t?!0:e2.some(n=>e[n]!==t[n]);function fk(e){var n,r,o;if(e.ownerDocument===document)return[];let t=(o=(r=(n=e.ownerDocument)==null?void 0:n.defaultView)==null?void 0:r.frameElement)!=null?o:null;return t?[t,...fk(t)]:[]}function pk(e,t){return!e||!t?null:N(P({},e),{top:e.top+t.top,left:e.left+t.left})}var Lf=!1,mk=()=>{Lf=!0;let e=[];if(Ln.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),Ln.delete(n);return}let r=n.getBoundingClientRect();ck(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(pk,t.rect):t.rect;ck(n,t.totalRect)&&t.callbacks.forEach(r=>r(n)),t.totalRect=n}),Ln.size===0){Lf=!1;return}dk=window.requestAnimationFrame(mk)};function Iy(e,t){let n=fk(e),r=[],o=n.map((i,s)=>Iy(i,a=>{r[s]=a;let l=Ln.get(e);if(!l)return;let u=r.reduce(pk,l.rect);l.callbacks.forEach(c=>c(u))}));return{observe(i=!0){if(o.forEach(s=>s.observe(!1)),Ln.has(e)){let s=Ln.get(e);s.callbacks.push(t),s.rect&&t(s.rect)}else Ln.set(e,{rect:void 0,callbacks:[t],parentRects:r});i&&!Lf&&mk()},unobserve(){o.forEach(s=>s.unobserve());let i=Ln.get(e);if(i){let s=i.callbacks.indexOf(t);s>=0&&i.callbacks.splice(s,1),i.callbacks.length||Ln.delete(e),Ln.size||(cancelAnimationFrame(dk),Lf=!1)}}}}var gk,In=new Map,hk=()=>{In.forEach((e,t)=>{if(!t.isConnected){In.delete(t);return}let{clientHeight:n,scrollHeight:r}=t,o=r>n;e.visible!==o&&(e.visible=o,e.callbacks.forEach(i=>i(e.visible)))}),In.size!==0&&(gk=window.requestAnimationFrame(hk))};function yk(e,t){return{observe(){let n=In.size===0;In.has(e)?In.get(e).callbacks.push(t):In.set(e,{visible:void 0,callbacks:[t]}),n&&hk()},unobserve(){let n=In.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||In.delete(e),In.size||cancelAnimationFrame(gk)}}}}var Oy=["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 Ny(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function xs(e){return parseFloat(e)}function If(e){return Math.round(e*1e6)}function vk(e){return e/1e6}function My(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=xs(e.width),i=xs(e.borderLeftWidth),s=xs(e.borderRightWidth),a=xs(e.paddingRight),l=vk(If(o)-If(i)-If(s)),u=vk(If(r));if(l-u>2){let c=l-u;n.style.paddingRight=`${a+c}px`}}function Ol(e,t={}){var c,p;let n=t.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=(c=t.position)!=null?c:"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",Vo(n);let r=window.getComputedStyle(e),o=!0,i=()=>{n.scrollTop=e.scrollTop};Ny(r,n,Oy),My(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",i));let s=yk(e,()=>{Ny(r,n,Oy),My(r,e,n),i(),setTimeout(i,0)}),a,l=!0,u=Iy(e,d=>{if(d===null){t.onRemove&&t.onRemove(),n.remove();return}if(!l&&t.onMoveStart&&(Promise.resolve().then(()=>t.onMoveStart()),l=!0),clearTimeout(a),a=setTimeout(()=>{t.onMoveEnd&&t.onMoveEnd(),l=!1},200),d.height===0&&d.width===0){if(o===!0)return;t.onHide&&t.onHide(),n.style.display="none",o=!0;return}if(Ny(r,n,Oy),My(r,e,n),i(),n.style.top=`${d.top}px`,n.style.left=`${d.left}px`,t.closestScrollElement&&t.closestScrollElement!==e){let g=t.closestScrollElement.getBoundingClientRect(),S=window.getComputedStyle(t.closestScrollElement),y=xs(S.borderTopWidth),m=xs(S.borderBottomWidth),f=g.top+y-d.top,h=d.top+d.height+-(g.top+g.height-m);n.style.clipPath=`inset(${f}px 0px ${h}px 0px)`}o&&(n.style.display="block",t.onShow&&t.onShow(),o=!1)});return t.appendTo?t.appendTo.appendChild(n):(p=e.parentElement)==null||p.appendChild(n),u.observe(),s.observe(),[n,()=>{e.removeEventListener("scroll",i),u.unobserve(),s.unobserve()}]}var Sk=(e,t)=>({value(){try{let n=sessionStorage.getItem(`dd-${e}`);if(!n)return t;try{return JSON.parse(n)}catch(r){return t}}catch(n){return t}},update(n){try{sessionStorage.setItem(`dd-${e}`,JSON.stringify(n))}catch(r){z.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function t2(e){return e.offsetParent!==null}function wk(e){if(!t2(e))return!1;let t=e.getBoundingClientRect();return t.top>=0&&t.left>=0&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&t.right<=(window.innerWidth||document.documentElement.clientWidth)}function Of(e,t,n=100){let r=wk(e);t({isVisible:r});let o=setInterval(()=>{let i=wk(e);i!==r&&(r=i,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var _e=w(b());var xk=Sk("showTabHint",!0),Es=class Es{constructor({deepdeskUrl:t,brokerUrl:n,version:r=Es.version||"unknown",locale:o="en-US",token:i,fetch:s,productName:a,createCustomChannel:l}){this.inputMediator=null;this.eventListeners={};this.unmountHandlers=[];this.widgetRoot=null;this.dynamicThunkObject={};this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;let u=t.replace(/\/api$/,"");this.deepdeskApi=new fr(u,{token:i,fetch:s}),this.version=r,this.instanceId=Es.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[ik({broadcast:(p,d,g)=>{this.broadcastEvents.send(p,d,g)},emit:(p,d)=>this.emit(p,d),handleAfterSendMessage:p=>this.handleAfterSendMessage(p),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:p=>this.logSendMessage(p),onUpdateShowTabHint:p=>xk.update(p),sendEvent:(p,d)=>this.deepdeskApi.sendEvent(p,d)})]};n&&Object.assign(c,{deepdeskBrokerAPI:new Il(n)}),this.store=ok(c),this.broadcastEvents=new KT({debug:!0,deepdeskUrl:u,eventMap:G1(this.store),createCustomChannel:l}),this.store.dispatch(cl(xk.value())),this.store.dispatch(Yc({locale:o,adminUrl:u,productName:a}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){var t;return(t=this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex])!=null?t:null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(z.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(z.warn("Profile has not been loaded (yet)"),!0):(z.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(Xi(null)),this.store.dispatch(Wn()),new Promise(t=>{let n=this.store.subscribe(()=>{let r=this.store.getState();rt(r)&&s1(r)!=="loading"&&(n(),t())});this.unmountHandlers.push(()=>{n()})})}isLoggedIn(){return k(this,null,function*(){return(yield this.store.dispatch(Wn())).payload})}setPlatformAgentId(t){return k(this,null,function*(){try{if((yield this.deepdeskApi.client.get("/apis/admin/session/me/",{version:null})).external_id)return;yield this.deepdeskApi.client.request("/apis/admin/session/me/",{method:"PATCH",body:JSON.stringify({external_id:t}),version:null})}catch(n){z.warn("Failed to attach user:",n)}})}isConversationSupported(t,n){return k(this,null,function*(){return(yield this.store.dispatch(Yg({sessionId:t,options:n}))).payload})}createConversation(t){return k(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(yield this.store.dispatch(Zc(t))).payload})}getConversationBySessionId(t,n){return k(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(yield this.store.dispatch(Jc({sessionId:t,options:n}))).payload})}upsertConversation(t){return k(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(yield this.store.dispatch(Qg(t))).payload})}postMessages(t){return k(this,null,function*(){return(yield this.store.dispatch(td(t))).payload})}updateConversation(t){return k(this,null,function*(){return(yield this.store.dispatch(ed(t))).payload})}resetConversation(){this.store.dispatch(fe()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}getSummary(){return k(this,null,function*(){let t=yield this.store.dispatch(er());if(t.error)throw new Error(t.error.message);return t.payload.summary})}configure(t){this.store.dispatch(Yc(t))}setVisitorInfo(t){this.store.dispatch(H1(t))}setCustomData(t){this.store.dispatch(U1(t))}setAgentInfo(t){return k(this,null,function*(){yield this.store.dispatch(Ua(t))})}setAgentSettings(t){return k(this,null,function*(){yield this.store.dispatch(Jg(t))})}getAgentSettings(){return k(this,null,function*(){return(yield this.store.dispatch(eh())).payload})}refresh(){return k(this,null,function*(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.store.dispatch(sd({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()}));let t=[];return this.store.dispatch(jd()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})})}notifyExternalSuggestion(t){this.store.dispatch(qn(t))}evaluateRule(o){return k(this,arguments,function*(t,n={},r=jC){return(yield this.store.dispatch($o({label:t,params:n,options:r}))).payload.cues})}handleKeyDown(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui,{textSuggestions:o,selectedSuggestionIndex:i,selection:s}=this.state.input,{inlineSuggestions:a,showTextSuggestions:l}=this.state.settings,u=a?"below":"above",c=o.length>0;if(this.store.dispatch(R1(b1(t))),t.key!=="Tab"&&!l)return;let p=()=>{n||!c||s&&(t.shiftKey||(this.store.dispatch(I1()),t.preventDefault()))},d=()=>{n||!c||a&&i<=0||s&&(t.shiftKey||(this.store.dispatch(O1()),t.preventDefault()))};switch(t.key){case"ArrowUp":u==="below"?d():p();break;case"ArrowDown":{u==="below"?p():d();break}case"Escape":{n||(this.store.dispatch(id(-1)),this.store.dispatch(Zr({collapse:!0})),this.store.dispatch(Ub(!0)),t.preventDefault());break}case"Tab":{let{text:g}=this.state.input,S=g.substring(0,s.end),y=od(this.state);this.settings.showTabCompletion&&y&&y.text.startsWith(S)&&(this.store.dispatch(cl(!1)),this.store.dispatch(qn({text:y.text,suggestion:y,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}))),t.preventDefault();break}default:}n&&r&&this.store.dispatch(Zr({collapse:!1}))}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(Gn([]))}handlingTimeStart(){this.state.handlingTime.startTime||(z.info("Start handling time"),this.store.dispatch(XT()))}handlingTimeStop(){this.state.handlingTime.startTime&&(z.info("Stop handling time"),this.store.dispatch(Pf()))}logSendMessage(t){let n=ak("input",this.state,{version:this.version});n&&(t&&(Object.assign(n,{text:t}),Object.assign(n,{lenTextTotal:t.length})),this.deepdeskApi.sendEventV1("Send Message",n),this.emit("send-message-event",n))}logHandlingTime(){let t=sk(this.state,{version:this.version});t&&(this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch(YT()))}notifySubmit(t={}){var n;this.shouldAbort()||this.store.dispatch(Ao((n=t.text)!=null?n:this.state.input.text))}emit(t,n){let r=this.eventListeners[t];r&&r.forEach(o=>{try{o(n)}catch(i){z.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),z.error(i)}})}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),()=>{this.off(t,n)}}off(t,n){if(!t&&!n){this.eventListeners={};return}let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}setConversationQuery(t){this.dynamicThunkObject.conversationQuery=t}whenConversationLoaded(t){let n=()=>this.loadProfileConfig().then(()=>t());this.hasConversation()&&n();let r=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==r&&(r=this.hasConversation(),r&&n())})}overlayContainerFactory(t,n,r,o){let[i,s]=Ol(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),this.unmountHandlers.push(()=>{(0,Yt.unmountComponentAtNode)(i),s(),i.remove()}),i}createInlineContainer(t,n){var s;let r=document.createElement("div");r.style.position="absolute",r.style.top="0px",r.style.left="0px",r.style.height="0px",r.style.width="0px";let o=document.createElement("div");o.style.display="none",o.style.position="absolute",o.style.height="0px",o.style.width="0px",o.style.backgroundColor="red",r.appendChild(o);let i=(s=t.ownerDocument.defaultView)==null?void 0:s.frameElement;if(i){let[a,l]=Ol(i,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});a.dataset.testid=n,a.style.zIndex="2",a.appendChild(r),this.unmountHandlers.push(()=>{(0,Yt.unmountComponentAtNode)(o),l()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return Vo(o),o.dataset.testid=t,o.style.color=r.color,o.style.fontSize=r.fontSize,o.style.fontFamily=r.fontFamily,o.style.fontVariant=r.fontVariant,o.setAttribute("translate","no"),n.appendChild(o),this.unmountHandlers.push(()=>{(0,Yt.unmountComponentAtNode)(o),o.remove()}),o}storeMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(t,n),z.info(`Stored analytics for ${this.conversationId()}`)}catch(t){}}restoreMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=window.sessionStorage.getItem(t);if(!n)return;let r=JSON.parse(n);r.text.trim()===this.state.input.text.trim()?(z.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(N1(r.metrics))):z.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(t)}catch(t){}}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!Af(t))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let{customStyles:r={},showStyleSuggestions:o,showTabCompletion:i,showTextSuggestions:s,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,isEmbedded:p,detectSubmit:d,insertLink:g,inputMediator:S,closestScrollSelector:y,appendOverlayTo:m,inlineSuggestions:f,floatingMenu:h}=n;this.configure({showStyleSuggestions:o,showTabCompletion:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,showTextSuggestions:s,insertLink:g,isEmbedded:p,inlineSuggestions:f,floatingMenu:!!h}),n.automaticHandlingTime&&this.setupHandlingTime(t),Vo(t),this.inputMediator=S||(eo(t)?new Xo(t):new Go(t)),this.inputMediator.on("change",({plainText:T,rawHTML:C})=>{this.store.dispatch(sd({text:T,html:C}))}),this.inputMediator.on("keyup",T=>{this.store.dispatch(A1(T))}),this.inputMediator.on("keydown",T=>{this.handleKeyDown(T)}),this.inputMediator.on("paste",({pastedText:T,selectionText:C})=>{this.store.dispatch(L1({text:T,selectionText:C}))}),this.inputMediator.on("cut",({selectionText:T})=>{this.store.dispatch(P1(T))});let v;this.inputMediator.on("selection",T=>{clearTimeout(v),T===null?v=setTimeout(()=>{T!==null&&this.store.dispatch(ad(T))},500):this.store.dispatch(ad(T))}),this.inputMediator.on("disabled",()=>{var T;(T=this.inputMediator)==null||T.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{d&&this.notifySubmit()}),this.inputMediator.on("blur",()=>{this.store.dispatch(qd(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(qd(!0))});let x=y&&lk(t,y)||void 0;if(f){let{customStyles:T,appendOverlayTo:C}=n;if(eo(t))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let R=this.createInlineContainer(t,"deepdesk-caret");(0,Yt.render)((0,_e.jsx)(Wo,{store:this.store,customStyles:T,children:(0,_e.jsx)(Io,{broadcastEvents:this.broadcastEvents,children:(0,_e.jsx)(qb,{})})}),R),this.inputMediator.on("caretposition",_=>{this.store.dispatch(Gn([])),_?(R.style.display="block",R.style.top=`${_.top}px`,R.style.left=`${_.left}px`):R.style.display="none"});let O=this.overlayContainerFactory("floating-menu",x||t,{appendTo:typeof h=="object"&&"appendOverlayTo"in h?h.appendOverlayTo:C},T==null?void 0:T.floatingMenuRootNode);(0,Yt.render)((0,_e.jsx)(Wo,{store:this.store,customStyles:T,children:(0,_e.jsx)(Io,{broadcastEvents:this.broadcastEvents,children:(0,_e.jsx)(Db,{onLogIn:()=>this.loginViaPopup().catch(_=>z.warn(_.message))})})}),O)}else{let T=this.overlayContainerFactory("deepdesk-tab-completion",x||t,{appendTo:m,closestScrollElement:x,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),C=this.overlayContainerFactory("deepdesk-suggestions-overlay",x||t,{appendTo:m},r==null?void 0:r.suggestionsRootNode);(0,Yt.render)((0,_e.jsx)(Wo,{store:this.store,customStyles:r,children:(0,_e.jsx)(Io,{broadcastEvents:this.broadcastEvents,children:(0,_e.jsx)(bC,{inputElement:t})})}),T),(0,Yt.render)((0,_e.jsx)(Wo,{store:this.store,customStyles:r,children:(0,_e.jsx)(Io,{broadcastEvents:this.broadcastEvents,children:(0,_e.jsx)(nC,{onLogIn:()=>this.loginViaPopup().catch(R=>z.warn(R.message))})})}),C)}(0,Yt.render)((0,_e.jsx)(Wo,{store:this.store,customStyles:r,children:(0,_e.jsx)(Io,{broadcastEvents:this.broadcastEvents,children:(0,_e.jsx)(Ib,{})})}),this.createContainer("deepdesk-overlays")),this.store.dispatch(sd({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()})),this.store.dispatch(ad(this.inputMediator.getSelection())),this.store.dispatch(qd(this.inputMediator.isFocused)),this.unmountHandlers.push(()=>{this.state.input.text!==""&&this.storeMetrics()}),this.whenConversationLoaded(()=>{var T;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((T=this.state.conversation.current)==null?void 0:T.sessionId)}),this.isMounted=!0}unmount(){var t;this.unmountHandlers.forEach(n=>n()),this.unmountHandlers=[],(t=this.inputMediator)==null||t.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(t,n={}){if(this.widgetRoot&&z.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:i}=n;this.widgetRoot=t,this.configure({showImages:o,isEmbedded:i}),(0,Yt.render)((0,_e.jsx)(Wo,{store:this.store,customStyles:r,children:(0,_e.jsx)(Io,{broadcastEvents:this.broadcastEvents,children:(0,_e.jsx)(UT,{onLogIn:()=>this.loginViaPopup().catch(s=>z.warn(s.message))})})}),t),this.whenConversationLoaded(()=>{var s;this.broadcastEvents.setSessionId((s=this.state.conversation.current)==null?void 0:s.sessionId)})}unmountWidget(){this.widgetRoot&&(0,Yt.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(t){let n=Of(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){uk(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(()=>k(this,null,function*(){yield this.store.dispatch(al());let t=rr(this.state);t&&(yield this.store.dispatch(ol()),this.store.dispatch(Yc({showSearch:t.search,showAutoflows:t.autoflows,showCustomMessages:t.customMessages,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:t.summarizer,showKnowledgeSearch:!!t.knowledgeAssistant,recommendTextSuggestions:t.recommendTextSuggestions})))})),this.loadProfileConfigPromise)}loginViaPopup(t){return k(this,null,function*(){return new Promise((n,r)=>{let o=new MessageChannel,i=o.port1,s=this.state.settings.adminUrl,a=new URL(t!=null&&t.url?t==null?void 0:t.url:`${s}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let l=!1,u=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",p),clearInterval(d)};i.onmessage=g=>k(this,null,function*(){var S,y;if((S=g.data)!=null&&S.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((y=g.data)==null?void 0:y.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(Ba),l=!0,o.port1.close(),n()}catch(m){console.error(m),r(m)}finally{l=!0,u()}});let c=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");c===null&&r(new Error("Popup blocked by browser"));let p=g=>k(this,null,function*(){var S;if(g.origin===a.origin)switch((S=g.data)==null?void 0:S.type){case"deepdesk-popup-loaded":{try{let y=JSON.stringify({type:"deepdesk-popup-create-channel"});c==null||c.postMessage(y,a.origin,[o.port2])}catch(y){z.error("Error posting message to popup",y),r(y)}break}case"deepdesk-popup-error":{u(),g.data.message==="Timeout"&&z.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(g.data.message));break}}});window.addEventListener("message",p);let d=setInterval(()=>{c&&!c.closed||(u(),l||r(new Error("Popup closed by user")))},200);this.unmountHandlers.push(u)})})}translateMessages(t){return this.deepdeskApi.translateMessages(t)}checkForTrialMode(t){return k(this,null,function*(){try{let{account:n}=yield this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(z.info("Trial is active"),!(yield this.deepdeskApi.checkUserExists(t)))throw new Error("User is not in trial");this.shouldRender=!0}catch(n){let{message:r}=n;z.info(r),this.shouldRender=!1}})}refreshWidgetSuggestions(){return k(this,null,function*(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=zd(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch(un()):tu.includes(r)||this.store.dispatch(dn(r))})}catch(r){this.handleError(r)}})}};Es.version="11.6.1-beta.5",Es.count=0;var Nl=Es;function Ek(r,o){return k(this,arguments,function*(e,t,n={}){var p,d;let{value:i}=e,{start:s,end:a}=(p=n.replace)!=null?p:{start:0,end:i.length},l=`${i.slice(0,s)}${t}${i.slice(a)}`,u=(d=n.selectionAfter)!=null?d:{start:s+t.length,end:s+t.length},c=()=>{if(n.setValue)return n.setValue(l);e.value=l};return Promise.resolve(c()).then(()=>{e.selectionStart=u.start,e.selectionEnd=u.end,e.blur(),e.focus()})})}function bk(r,o){return k(this,arguments,function*(e,t,n={}){let i=n.replace?oo(e,n.replace.start,n.replace.end):vs(e),s,a=()=>{if(n.setRange)return n.setRange(i.cloneRange());i.deleteContents(),s=document.createElement("span"),i.insertNode(s),n.insertBRs!==!1?t.split(`
|
|
28
28
|
`).reverse().forEach((l,u)=>{u>0&&i.insertNode(document.createElement("br")),i.insertNode(document.createTextNode(l))}):i.insertNode(document.createTextNode(t))};return Promise.resolve(a()).then(()=>{try{if(n.selectionAfter!==!1){e.focus();let l=n.selectionAfter?oo(e,n.selectionAfter.start,n.selectionAfter.end):(i.collapse(!1),i),u=window.getSelection();u==null||u.removeAllRanges(),u==null||u.addRange(l)}if(!s)return;s.scrollIntoView&&s.scrollIntoView({block:"nearest",inline:"nearest"})}finally{s&&s.remove()}})})}function n2(e){let t=document.createElement("template");return t.innerHTML=e.replace(/(\[([^\]]+)])\(([^)]+)\)/g,'<a href="$3" target="_blank" rel="noopener noreferrer">$2</a>'),t.content}function r2(e){let t=document.createDocumentFragment();return e.split(`
|
|
29
29
|
`).forEach((n,r)=>{r>0&&t.appendChild(document.createElement("br"));let o={index:0},i=0;for(;o=n.slice(i).match(/(\[([^\]]+)])\(([^)]+)\)/);){let s=document.createElement("a");s.href=o[3],s.setAttribute("target","_blank"),s.setAttribute("rel","noopener noreferrer"),s.appendChild(document.createTextNode(o[2])),t.appendChild(document.createTextNode(n.slice(i,i+o.index))),t.appendChild(s),i=i+o.index+o[0].length}t.appendChild(document.createTextNode(n.slice(i)))}),t}function Ck(e,t){let n=e.parentElement;if(!n){console.warn("No insert point found");return}let{display:r}=window.getComputedStyle(n);r.includes("block")||r==="table-cell"?n==null||n.insertBefore(t,e.nextSibling):Ck(n,t)}function Tk(o,i){return k(this,arguments,function*(e,t,{isBlock:n,isHTML:r}={}){let s;e.dispatchEvent(new InputEvent("beforeinput",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0}));let a=()=>{var d;let l=(d=e.ownerDocument.defaultView)!=null?d:window,u=l.getSelection();if((!u||u.rangeCount===0)&&(e.focus(),u=l.getSelection()),!u||u.rangeCount===0)return;let c=u.getRangeAt(0);if(!c)return;s=document.createElement("span"),c.insertNode(s);let p=r?n2(t):r2(t);n?Ck(c.startContainer,p):(c.insertNode(p),c.collapse(!1))};return Promise.resolve(a()).then(()=>{if(e.dispatchEvent(new InputEvent("input",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0})),e.focus(),!!s)try{s.scrollIntoView&&s.scrollIntoView({block:"nearest",inline:"nearest"})}finally{s&&s.remove()}})})}function kk(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function Pk(e,t,n){return k(this,null,function*(){yield new fr(e).authenticateWithKey(t,n)})}function Rk(e){return k(this,null,function*(){let n=yield new hn(e).get("/platform/config/",{version:null,useCache:!0});return re(n)})}function o2(e){return k(this,null,function*(){var o,i,s;let n=yield((o=e.fetch)!=null?o:window.fetch)(e.url),r=yield n.blob();return new File([r],e.name,{type:(s=(i=e.mimeType)!=null?i:n.headers.get("Content-Type"))!=null?s:"image/jpeg"})})}function Ak(e,t){return k(this,null,function*(){let n=yield o2(t),r=new Event("change",{bubbles:!0,cancelable:!0});try{Object.defineProperty(e,"files",{configurable:!0,get:()=>[n]}),e.dispatchEvent(r)}finally{Object.hasOwn(e,"files")&&delete e.files}})}return Wk(i2);})();
|
|
30
30
|
/*! Bundled license information:
|