@deepdesk/deepdesk-sdk 10.9.3-beta.1 → 10.9.3-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs.js +1 -1
- package/dist/index.esm.js +1 -1
- package/dist/index.iife.js +1 -1
- package/package.json +1 -1
package/dist/index.cjs.js
CHANGED
|
@@ -6,6 +6,6 @@ Try polyfilling it using "@formatjs/intl-pluralrules"
|
|
|
6
6
|
c-17.9,17.9-27.3,40.1-27.3,65.7C163.4,163,163.4,233,163.4,233z M465.5,267.9V477c0,9.4-3.4,17.9-10.2,24.7
|
|
7
7
|
c-6.8,6.8-15.4,10.2-24.7,10.2h-349c-9.4,0-17.9-3.4-24.7-10.2c-6.8-6.8-10.2-15.4-10.2-24.7V267.9c0-9.4,3.4-17.9,10.2-24.7
|
|
8
8
|
c6.8-6.8,15.4-10.2,24.7-10.2h11.9v-70c0-44.4,16.2-82.8,47.8-115.2S212.1,0,256.4,0s82.8,16.2,115.2,47.8
|
|
9
|
-
c32.4,32.4,47.8,70,47.8,115.2v70h11.9c9.4,0,17.9,3.4,24.7,10.2C462.1,250,465.5,257.7,465.5,267.9z`})})});var sa=require("react/jsx-runtime"),rh={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},yu=({className:t,color:e})=>(0,sa.jsx)("svg",{className:t,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:(0,sa.jsx)("path",{d:"M172.03 0.0199966H0V86.03C47.5 86.03 86 124.54 86 172.04C86 124.54 124.51 86.03 172.01 86.03C219.51 86.03 258.03 124.54 258.03 172.04C258.03 219.54 219.52 258.05 172.01 258.05C124.5 258.05 86 219.54 86 172.04C86 219.54 47.5 258.05 0 258.05V344.06H172.03C267.04 344.06 344.06 267.04 344.06 172.03C344.06 77.02 267.04 0 172.03 0V0.0199966Z",fill:rh[e||"pink"]})});var vu={root:"_root_bgd7a_1",text:"_text_bgd7a_18",icon:"_icon_bgd7a_33",logo:"_logo_bgd7a_38",lock:"_lock_bgd7a_43"};var ra={};V(ra,{enUS:()=>ih,nlNL:()=>ah});var ih={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"}]},ah={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"}]};var _u=require("react-redux"),Wt=require("react/jsx-runtime"),xu=({onLogIn:t})=>{let e=k(ra),o=C("productName"),n=(0,_u.useDispatch)(),s=(0,Su.useSelector)(ue),r=y("FloatingMenu",vu);if(s===null)return null;let i=()=>{s===!0?n(ee(!0)):t()};return(0,Wt.jsxs)("button",{className:r.root,onClick:i,children:[(0,Wt.jsx)("div",{className:r.text,children:e(s?"search":"signin",{productName:o})}),(0,Wt.jsxs)("div",{className:r.icon,children:[(0,Wt.jsx)(yu,{className:r.logo,color:"pink"}),s===!1&&(0,Wt.jsx)(hu,{className:r.lock})]})]})};async function xr(t){let o=await new Me(t).get("/platform/config/",{version:null});return M(o)}var z=require("react/jsx-runtime");var bu=mu("showTabHint",!0),wn=class t{static version="10.9.3-beta.1";static count=0;deepdeskApi;inputMediator=null;version;broadcastEvents;eventListeners={};unmountHandlers=[];widgetRoot=null;dynamicThunkObject={};isMounted=!1;instanceId;shouldRender=!0;store;constructor({deepdeskUrl:e,brokerUrl:o,version:n=t.version||"unknown",locale:s="en-US",token:r,fetch:i,productName:a,createCustomChannel:l}){let c=e.replace(/\/api$/,"");this.deepdeskApi=new it(c,{token:r,fetch:i}),this.version=n,this.instanceId=t.count++;let p={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[pu({emit:(d,u,g)=>this.emit(d,u,g),handleAfterSendMessage:d=>this.handleAfterSendMessage(d),handleInputChanged:d=>this.handleInputChanged(d),handleKeyDown:d=>this.handleKeyDown(d),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:d=>this.logSendMessage(d),logSendEditSuggestionMessage:d=>this.logSendEditMessage(d),onUpdateShowTabHint:d=>bu.update(d),sendEvent:(d,u)=>this.deepdeskApi.sendEvent(d,u)})]};o&&Object.assign(p,{deepdeskBrokerAPI:new Cn(o)}),this.store=cu(p),this.broadcastEvents=new Qd({debug:!0,deepdeskUrl:c,eventMap:Nc(this.store),createCustomChannel:l}),this.store.dispatch(Ho),this.store.dispatch(Yo(bu.value())),this.store.dispatch(Ho({locale:s,adminUrl:c,productName:a}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){return this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex]??null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(T.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(T.warn("Profile has not been loaded (yet)"),!0):(T.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(So(null)),this.store.dispatch($e()),new Promise(e=>{let o=this.store.subscribe(()=>{let n=this.store.getState();ue(n)&&kc(n)!=="loading"&&(o(),e())});this.unmountHandlers.push(()=>{o()})})}async isLoggedIn(){return(await this.store.dispatch($e())).payload}async setPlatformAgentId(e){try{if((await this.deepdeskApi.client.get("/apis/admin/session/me/",{version:null})).external_id)return;await this.deepdeskApi.client.request("/apis/admin/session/me/",{method:"PATCH",body:JSON.stringify({external_id:e}),version:null})}catch(o){T.warn("Failed to attach user:",o)}}async isConversationSupported(e,o){return(await this.store.dispatch(Ir({sessionId:e,options:o}))).payload}async createConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(Fn(e))).payload}async getConversationBySessionId(e,o){return this.hasConversation()&&this.sessionId()!==e&&this.resetConversation(),(await this.store.dispatch(Kn({sessionId:e,options:o}))).payload}async upsertConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(Pr(e))).payload}async postMessages(e){return(await this.store.dispatch(zn(e))).payload}async updateConversation(e){return(await this.store.dispatch(Un(e))).payload}resetConversation(){this.store.dispatch(L()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}async getSummary(){let e=await this.store.dispatch(Qe());if(e.error)throw new Error(e.error.message);return e.payload.summary}configure(e){this.store.dispatch(Ho(e))}setVisitorInfo(e){this.store.dispatch(ql(e))}async setAgentInfo(e){await this.store.dispatch($o(e))}async setAgentSettings(e){await this.store.dispatch(li(e))}async getAgentSettings(){return(await this.store.dispatch(ci())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let e=[];return this.store.dispatch(As()),e.push(this.refreshWidgetSuggestions()),Promise.all(e).then(()=>{})}notifyInputChanged(e){this.store.dispatch($n(e))}notifyKeyDown(e){this.store.dispatch(Wn(e))}notifyPaste(e,o){this.store.dispatch($a({text:e,selectionText:o}))}notifyCut(e){this.store.dispatch(Wa(e))}notifyExternalSuggestion(e){this.store.dispatch(ke(e)),this.store.dispatch(Ue())}notifyEditSuggestion(e){this.store.dispatch(dc(e.contentType,e.suggestions)),this.store.dispatch(Ge({contentType:e.contentType,suggestion:typeof e.index=="number"?e.suggestions[e.index]:null}))}handleInputChanged(e){let{overlayCollapsed:o,openOverlayWhenTyping:n}=this.state.ui;o&&n&&this.store.dispatch(ht({collapse:!1})),this.inputMediator&&this.store.dispatch(Ka({text:e,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(Oe([])))}handleKeyDown(e){let{overlayCollapsed:o}=this.state.ui,{textSuggestions:n,selectedSuggestionIndex:s,selection:r}=this.state.input,{inlineSuggestions:i}=this.state.settings,a=n.length>0,l=s!==-1;if(this.store.dispatch(Ga(qn(e))),e.key!=="Tab"&&!this.settings.showTextSuggestions)return;let c=()=>{o||!a||r&&(e.shiftKey||(this.store.dispatch(ja()),i||this.stageSelectedSuggestion({inputType:"arrow"}),e.preventDefault()))},p=()=>{if(o||!a||!r||e.shiftKey)return;this.store.dispatch(Va());let{selectedSuggestionIndex:d}=this.state.input;e.preventDefault(),!i&&(d===-1?this.store.dispatch(Bo()):this.stageSelectedSuggestion({inputType:"arrow"}))};switch(e.key){case"Up":case"ArrowUp":i?p():c();return;case"Down":case"ArrowDown":{i?c():p();return}case"Esc":case"Escape":{i&&l&&this.store.dispatch(ut(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(ut(-1)),this.store.dispatch(Bo()),e.preventDefault()):o||(this.store.dispatch(ht({collapse:!0})),this.store.dispatch(bc(!0)),e.preventDefault());return}case"Tab":{let{userCommitted:d}=this.state.input,u=d.text.substring(0,d.selection.end),{tabCompletionSuggestion:g}=this.state.input;this.store.dispatch(Yo(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!i&&this.settings.showTabCompletion&&g&&g.text.startsWith(u)&&(this.store.dispatch(ke({text:g.text,suggestion:g,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch(Ue())),e.preventDefault();break}default:}}handleAfterSendMessage(e){this.emit("send-message",e),this.store.dispatch(Xa()),this.store.dispatch(Oe([]))}handlingTimeStart(){this.state.handlingTime.startTime||(T.info("Start handling time"),this.store.dispatch(eu()))}handlingTimeStop(){this.state.handlingTime.startTime&&(T.info("Stop handling time"),this.store.dispatch(mr()))}logSendMessage(e){let o=oa("input",this.state,{version:this.version});e&&(Object.assign(o,{text:e}),Object.assign(o,{lenTextTotal:e.length})),this.deepdeskApi.sendEventV1("Send Message",o),this.emit("send-message-event",o)}logSendEditMessage(e){let o=oa("overlayInput",this.state,{version:this.version});e&&Object.assign(o,{text:e}),this.store.dispatch(za(this.state.overlayInput.metrics))}logHandlingTime(){let e=du(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",e),this.store.dispatch(tu())}notifySubmit(e={}){this.shouldAbort()||(this.store.dispatch(Ue()),this.store.dispatch(Rt(e.text??this.state.input.text)))}stageSelectedSuggestion(e){let o=this.state.input.selectedSuggestionIndex,{textSuggestions:n}=this.state.input;this.store.dispatch(ke({text:n[o].text,suggestion:n[o],eventMetrics:e,replace:"until-selection-end"}))}emit(e,o,n={}){let s=()=>{this.eventListeners[e]&&this.eventListeners[e].forEach(r=>{try{r(o)}catch(i){T.warn(`The following error occurred in deepdeskSDK.on('${e}', handler)`),T.error(i)}})};this.inputMediator&&n.mayApplyChanges?this.inputMediator.applyChanges(s):s()}on(e,o){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(o),()=>{this.off(e,o)}}off(e,o){if(!e&&!o){this.eventListeners={};return}let n;this.eventListeners[e]&&(n=this.eventListeners[e].indexOf(o),n>-1&&this.eventListeners[e].splice(n,1))}setConversationQuery(e){this.dynamicThunkObject.conversationQuery=e}whenConversationLoaded(e){let o=()=>this.loadProfileConfig().then(()=>e());this.hasConversation()&&o();let n=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==n&&(n=this.hasConversation(),n&&o())})}overlayContainerFactory(e,o,n,s){let[r,i]=At(o,n);return r.setAttribute("translate","no"),r.dataset.testid=e,s&&r.classList.add(s),this.unmountHandlers.push(()=>{(0,we.unmountComponentAtNode)(r),i(),r.remove()}),r}createInlineContainer(e,o){var i;let n=document.createElement("div");n.style.position="absolute",n.style.top="0px",n.style.left="0px",n.style.height="0px",n.style.width="0px";let s=document.createElement("div");s.style.display="none",s.style.position="absolute",s.style.height="0px",s.style.width="0px",s.style.backgroundColor="red",n.appendChild(s);let r=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;if(r){let[a,l]=At(r,{appendTo:document.body});a.dataset.testid=o,a.style.zIndex="2",a.appendChild(n),this.unmountHandlers.push(()=>{(0,we.unmountComponentAtNode)(s),l()})}else document.body.appendChild(n);return s}createContainer(e,o=document.body){let n=window.getComputedStyle(o),s=document.createElement("div");return Pt(s),s.dataset.testid=e,s.style.color=n.color,s.style.fontSize=n.fontSize,s.style.fontFamily=n.fontFamily,s.style.fontVariant=n.fontVariant,s.setAttribute("translate","no"),o.appendChild(s),this.unmountHandlers.push(()=>{(0,we.unmountComponentAtNode)(s),s.remove()}),s}storeMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,o=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(e,o),T.info(`Stored analytics for ${this.conversationId()}`)}catch{}}restoreMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,o=window.sessionStorage.getItem(e);if(!o)return;let n=JSON.parse(o);n.text.trim()===this.state.input.text.trim()?(T.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(Za(n.metrics))):T.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(e)}catch{}}mount(e,o={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!vr(e))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let{customStyles:n={},showStyleSuggestions:s,showTabCompletion:r,showTextSuggestions:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:c,showSuggestionsAfterPattern:p,isEmbedded:d,detectSubmit:u,insertLink:g,inputMediator:f,closestScrollSelector:m,appendOverlayTo:v,inlineSuggestions:w,floatingMenu:h}=o;this.configure({showStyleSuggestions:s,showTabCompletion:r,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:c,showSuggestionsAfterPattern:p,showTextSuggestions:i,insertLink:g,isEmbedded:d,inlineSuggestions:w,floatingMenu:!!h}),o.automaticHandlingTime&&this.setupHandlingTime(e),Pt(e),this.inputMediator=f||(St(e)?new qe(e):new qt(e)),this.inputMediator.on("change",({plainText:_})=>{this.notifyInputChanged(_)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(Qa({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",_=>{this.notifyKeyDown(_)}),this.inputMediator.on("paste",({pastedText:_,selectionText:P})=>{this.notifyPaste(_,P)}),this.inputMediator.on("cut",({selectionText:_})=>{this.notifyCut(_)});let x=m&&uu(e,m)||void 0;if(w){let{customStyles:_,appendOverlayTo:P}=o;if(St(e))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let D=this.createInlineContainer(e,"deepdesk-caret");(0,we.render)((0,z.jsx)(zt,{store:this.store,customStyles:_,children:(0,z.jsx)(Ft,{broadcastEvents:this.broadcastEvents,children:(0,z.jsx)(bp,{})})}),D),this.inputMediator.on("caret",A=>{this.store.dispatch(Oe([])),A?(D.style.display="block",D.style.top=`${A.top}px`,D.style.left=`${A.left}px`):D.style.display="none"});let re=this.overlayContainerFactory("floating-menu",x||e,{appendTo:typeof h=="object"&&"appendOverlayTo"in h?h.appendOverlayTo:P},_==null?void 0:_.floatingMenuRootNode);(0,we.render)((0,z.jsx)(zt,{store:this.store,customStyles:_,children:(0,z.jsx)(Ft,{broadcastEvents:this.broadcastEvents,children:(0,z.jsx)(xu,{onLogIn:()=>this.loginViaPopup().catch(A=>T.warn(A.message))})})}),re)}else{let _=this.overlayContainerFactory("deepdesk-tab-completion",x||e,{appendTo:v,closestScrollElement:x,mirrorOverflow:!0,onRemove:()=>this.unmount()},n==null?void 0:n.rootNode),P=this.overlayContainerFactory("deepdesk-suggestions-overlay",x||e,{appendTo:v},n==null?void 0:n.suggestionsRootNode);(0,we.render)((0,z.jsx)(zt,{store:this.store,customStyles:n,children:(0,z.jsx)(Ft,{broadcastEvents:this.broadcastEvents,children:(0,z.jsx)(Yp,{inputElement:e})})}),_),(0,we.render)((0,z.jsx)(zt,{store:this.store,customStyles:n,children:(0,z.jsx)(Ft,{broadcastEvents:this.broadcastEvents,children:(0,z.jsx)(Ap,{onLogIn:()=>this.loginViaPopup().catch(D=>T.warn(D.message))})})}),P)}(0,we.render)((0,z.jsx)(zt,{store:this.store,customStyles:n,children:(0,z.jsx)(Ft,{broadcastEvents:this.broadcastEvents,children:(0,z.jsx)(fp,{})})}),this.createContainer("deepdesk-overlays"));let b;this.inputMediator.on("selection",_=>{clearTimeout(b),_===null?b=setTimeout(()=>{_!==null&&this.store.dispatch(Lr(_))},500):this.store.dispatch(Lr(_))}),this.inputMediator.on("disabled",()=>{var _;(_=this.inputMediator)==null||_.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{u&&this.notifySubmit()}),this.inputMediator.on("blur",()=>this.store.dispatch(yo(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(yo(!0))),this.store.dispatch(Ua({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.unmountHandlers.push(()=>{this.state.input.text!==""&&(this.store.dispatch(Ue()),this.storeMetrics())}),this.whenConversationLoaded(()=>{var _;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((_=this.state.conversation.current)==null?void 0:_.sessionId)}),this.isMounted=!0}unmount(){var e;this.unmountHandlers.forEach(o=>o()),this.unmountHandlers=[],(e=this.inputMediator)==null||e.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(e,o={}){if(this.widgetRoot&&T.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:n,showImages:s,isEmbedded:r}=o;this.widgetRoot=e,this.configure({showImages:s,isEmbedded:r}),(0,we.render)((0,z.jsx)(zt,{store:this.store,customStyles:n,children:(0,z.jsx)(Ft,{broadcastEvents:this.broadcastEvents,children:(0,z.jsx)(Wd,{onLogIn:()=>this.loginViaPopup().catch(i=>T.warn(i.message))})})}),e),this.whenConversationLoaded(()=>{var i;this.broadcastEvents.setSessionId((i=this.state.conversation.current)==null?void 0:i.sessionId)})}unmountWidget(){this.widgetRoot&&(0,we.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(e){let o=Sr(e,({isVisible:n})=>{n?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),o()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){gu(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(dn());let e=To(this.state);e&&this.store.dispatch(Ho({showSearch:e.search,showAutoflows:e.autoflows,showCustomMessages:e.customMessages,showImageSearch:e.imageSearch,showEntitiesCommand:e.entitiesCommand,showSummaryCommand:e.summarizer,showKnowledgeSearch:e.knowledgeAssistForAgents,recommendTextSuggestions:e.recommendTextSuggestions}))}),this.loadProfileConfigPromise)}async loginViaPopup(){let e=this.state.settings.adminUrl,o=new URL(e),n=await xr(o.origin);return new Promise((s,r)=>{let i=new MessageChannel,a=i.port1,l=new URL(n.config.platform.hasSso?`${e}/platform/sso/`:`${e}/admin/`);l.searchParams.append("redirect","/sdk/popup/close.html");let c=!1,p=()=>{d&&!d.closed&&d.close(),window.removeEventListener("message",u),clearInterval(g)};a.onmessage=async f=>{var m,v;if((m=f.data)!=null&&m.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((v=f.data)==null?void 0:v.jwt),await this.isLoggedIn(),this.broadcastEvents.send(on),p(),c=!0,i.port1.close(),s()}catch(w){r(w)}};let d=window.open(l.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");d===null&&r(new Error("Popup blocked by browser"));let u=async f=>{var m;if(f.origin===l.origin)switch((m=f.data)==null?void 0:m.type){case"deepdesk-popup-loaded":{d==null||d.postMessage({type:"deepdesk-popup-create-channel"},l.origin,[i.port2]);break}case"deepdesk-popup-error":{p(),f.data.message==="Timeout"&&T.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(f.data.message));break}}};window.addEventListener("message",u);let g=setInterval(()=>{d&&!d.closed||(p(),c||r(new Error("Popup closed by user")))},200);this.unmountHandlers.push(p)})}async checkForTrialMode(e){try{let{account:o}=await this.deepdeskApi.getPlatformConfig();if(!o.isTrial){this.shouldRender=!0;return}if(T.info("Trial is active"),!await this.deepdeskApi.checkUserExists(e))throw new Error("User is not in trial");this.shouldRender=!0}catch(o){let{message:n}=o;T.info(n),this.shouldRender=!1}}async refreshWidgetSuggestions(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:e}=this.state.profile.data;if(!e.widget)return;let o=Us(this.state);try{o.forEach(({type:n})=>{n==="entities"?this.store.dispatch(Ae()):this.store.dispatch(We(n))})}catch(n){this.handleError(n)}}};async function Cu(t,e,o={}){let{value:n}=t,{start:s,end:r}=o.replace??{start:0,end:n.length},i=`${n.slice(0,s)}${e}${n.slice(r)}`,a=o.selectionAfter??{start:s+e.length,end:s+e.length},l=()=>{if(o.setValue)return o.setValue(i);t.value=i};return Promise.resolve(l()).then(()=>{t.selectionStart=a.start,t.selectionEnd=a.end,t.blur(),t.focus()})}async function wu(t,e,o={}){let n=o.replace?wt(t,o.replace.start,o.replace.end):Ao(t),s,r=()=>{if(o.setRange)return o.setRange(n.cloneRange());n.deleteContents(),s=document.createElement("span"),n.insertNode(s),o.insertBRs!==!1?e.split(`
|
|
9
|
+
c32.4,32.4,47.8,70,47.8,115.2v70h11.9c9.4,0,17.9,3.4,24.7,10.2C462.1,250,465.5,257.7,465.5,267.9z`})})});var sa=require("react/jsx-runtime"),rh={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},yu=({className:t,color:e})=>(0,sa.jsx)("svg",{className:t,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:(0,sa.jsx)("path",{d:"M172.03 0.0199966H0V86.03C47.5 86.03 86 124.54 86 172.04C86 124.54 124.51 86.03 172.01 86.03C219.51 86.03 258.03 124.54 258.03 172.04C258.03 219.54 219.52 258.05 172.01 258.05C124.5 258.05 86 219.54 86 172.04C86 219.54 47.5 258.05 0 258.05V344.06H172.03C267.04 344.06 344.06 267.04 344.06 172.03C344.06 77.02 267.04 0 172.03 0V0.0199966Z",fill:rh[e||"pink"]})});var vu={root:"_root_bgd7a_1",text:"_text_bgd7a_18",icon:"_icon_bgd7a_33",logo:"_logo_bgd7a_38",lock:"_lock_bgd7a_43"};var ra={};V(ra,{enUS:()=>ih,nlNL:()=>ah});var ih={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"}]},ah={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"}]};var _u=require("react-redux"),Wt=require("react/jsx-runtime"),xu=({onLogIn:t})=>{let e=k(ra),o=C("productName"),n=(0,_u.useDispatch)(),s=(0,Su.useSelector)(ue),r=y("FloatingMenu",vu);if(s===null)return null;let i=()=>{s===!0?n(ee(!0)):t()};return(0,Wt.jsxs)("button",{className:r.root,onClick:i,children:[(0,Wt.jsx)("div",{className:r.text,children:e(s?"search":"signin",{productName:o})}),(0,Wt.jsxs)("div",{className:r.icon,children:[(0,Wt.jsx)(yu,{className:r.logo,color:"pink"}),s===!1&&(0,Wt.jsx)(hu,{className:r.lock})]})]})};async function xr(t){let o=await new Me(t).get("/platform/config/",{version:null});return M(o)}var z=require("react/jsx-runtime");var bu=mu("showTabHint",!0),wn=class t{static version="10.9.3-beta.2";static count=0;deepdeskApi;inputMediator=null;version;broadcastEvents;eventListeners={};unmountHandlers=[];widgetRoot=null;dynamicThunkObject={};isMounted=!1;instanceId;shouldRender=!0;store;constructor({deepdeskUrl:e,brokerUrl:o,version:n=t.version||"unknown",locale:s="en-US",token:r,fetch:i,productName:a,createCustomChannel:l}){let c=e.replace(/\/api$/,"");this.deepdeskApi=new it(c,{token:r,fetch:i}),this.version=n,this.instanceId=t.count++;let p={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[pu({emit:(d,u,g)=>this.emit(d,u,g),handleAfterSendMessage:d=>this.handleAfterSendMessage(d),handleInputChanged:d=>this.handleInputChanged(d),handleKeyDown:d=>this.handleKeyDown(d),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:d=>this.logSendMessage(d),logSendEditSuggestionMessage:d=>this.logSendEditMessage(d),onUpdateShowTabHint:d=>bu.update(d),sendEvent:(d,u)=>this.deepdeskApi.sendEvent(d,u)})]};o&&Object.assign(p,{deepdeskBrokerAPI:new Cn(o)}),this.store=cu(p),this.broadcastEvents=new Qd({debug:!0,deepdeskUrl:c,eventMap:Nc(this.store),createCustomChannel:l}),this.store.dispatch(Ho),this.store.dispatch(Yo(bu.value())),this.store.dispatch(Ho({locale:s,adminUrl:c,productName:a}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){return this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex]??null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(T.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(T.warn("Profile has not been loaded (yet)"),!0):(T.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(So(null)),this.store.dispatch($e()),new Promise(e=>{let o=this.store.subscribe(()=>{let n=this.store.getState();ue(n)&&kc(n)!=="loading"&&(o(),e())});this.unmountHandlers.push(()=>{o()})})}async isLoggedIn(){return(await this.store.dispatch($e())).payload}async setPlatformAgentId(e){try{if((await this.deepdeskApi.client.get("/apis/admin/session/me/",{version:null})).external_id)return;await this.deepdeskApi.client.request("/apis/admin/session/me/",{method:"PATCH",body:JSON.stringify({external_id:e}),version:null})}catch(o){T.warn("Failed to attach user:",o)}}async isConversationSupported(e,o){return(await this.store.dispatch(Ir({sessionId:e,options:o}))).payload}async createConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(Fn(e))).payload}async getConversationBySessionId(e,o){return this.hasConversation()&&this.sessionId()!==e&&this.resetConversation(),(await this.store.dispatch(Kn({sessionId:e,options:o}))).payload}async upsertConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(Pr(e))).payload}async postMessages(e){return(await this.store.dispatch(zn(e))).payload}async updateConversation(e){return(await this.store.dispatch(Un(e))).payload}resetConversation(){this.store.dispatch(L()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}async getSummary(){let e=await this.store.dispatch(Qe());if(e.error)throw new Error(e.error.message);return e.payload.summary}configure(e){this.store.dispatch(Ho(e))}setVisitorInfo(e){this.store.dispatch(ql(e))}async setAgentInfo(e){await this.store.dispatch($o(e))}async setAgentSettings(e){await this.store.dispatch(li(e))}async getAgentSettings(){return(await this.store.dispatch(ci())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let e=[];return this.store.dispatch(As()),e.push(this.refreshWidgetSuggestions()),Promise.all(e).then(()=>{})}notifyInputChanged(e){this.store.dispatch($n(e))}notifyKeyDown(e){this.store.dispatch(Wn(e))}notifyPaste(e,o){this.store.dispatch($a({text:e,selectionText:o}))}notifyCut(e){this.store.dispatch(Wa(e))}notifyExternalSuggestion(e){this.store.dispatch(ke(e)),this.store.dispatch(Ue())}notifyEditSuggestion(e){this.store.dispatch(dc(e.contentType,e.suggestions)),this.store.dispatch(Ge({contentType:e.contentType,suggestion:typeof e.index=="number"?e.suggestions[e.index]:null}))}handleInputChanged(e){let{overlayCollapsed:o,openOverlayWhenTyping:n}=this.state.ui;o&&n&&this.store.dispatch(ht({collapse:!1})),this.inputMediator&&this.store.dispatch(Ka({text:e,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(Oe([])))}handleKeyDown(e){let{overlayCollapsed:o}=this.state.ui,{textSuggestions:n,selectedSuggestionIndex:s,selection:r}=this.state.input,{inlineSuggestions:i}=this.state.settings,a=n.length>0,l=s!==-1;if(this.store.dispatch(Ga(qn(e))),e.key!=="Tab"&&!this.settings.showTextSuggestions)return;let c=()=>{o||!a||r&&(e.shiftKey||(this.store.dispatch(ja()),i||this.stageSelectedSuggestion({inputType:"arrow"}),e.preventDefault()))},p=()=>{if(o||!a||!r||e.shiftKey)return;this.store.dispatch(Va());let{selectedSuggestionIndex:d}=this.state.input;e.preventDefault(),!i&&(d===-1?this.store.dispatch(Bo()):this.stageSelectedSuggestion({inputType:"arrow"}))};switch(e.key){case"Up":case"ArrowUp":i?p():c();return;case"Down":case"ArrowDown":{i?c():p();return}case"Esc":case"Escape":{i&&l&&this.store.dispatch(ut(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(ut(-1)),this.store.dispatch(Bo()),e.preventDefault()):o||(this.store.dispatch(ht({collapse:!0})),this.store.dispatch(bc(!0)),e.preventDefault());return}case"Tab":{let{userCommitted:d}=this.state.input,u=d.text.substring(0,d.selection.end),{tabCompletionSuggestion:g}=this.state.input;this.store.dispatch(Yo(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!i&&this.settings.showTabCompletion&&g&&g.text.startsWith(u)&&(this.store.dispatch(ke({text:g.text,suggestion:g,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch(Ue())),e.preventDefault();break}default:}}handleAfterSendMessage(e){this.emit("send-message",e),this.store.dispatch(Xa()),this.store.dispatch(Oe([]))}handlingTimeStart(){this.state.handlingTime.startTime||(T.info("Start handling time"),this.store.dispatch(eu()))}handlingTimeStop(){this.state.handlingTime.startTime&&(T.info("Stop handling time"),this.store.dispatch(mr()))}logSendMessage(e){let o=oa("input",this.state,{version:this.version});e&&(Object.assign(o,{text:e}),Object.assign(o,{lenTextTotal:e.length})),this.deepdeskApi.sendEventV1("Send Message",o),this.emit("send-message-event",o)}logSendEditMessage(e){let o=oa("overlayInput",this.state,{version:this.version});e&&Object.assign(o,{text:e}),this.store.dispatch(za(this.state.overlayInput.metrics))}logHandlingTime(){let e=du(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",e),this.store.dispatch(tu())}notifySubmit(e={}){this.shouldAbort()||(this.store.dispatch(Ue()),this.store.dispatch(Rt(e.text??this.state.input.text)))}stageSelectedSuggestion(e){let o=this.state.input.selectedSuggestionIndex,{textSuggestions:n}=this.state.input;this.store.dispatch(ke({text:n[o].text,suggestion:n[o],eventMetrics:e,replace:"until-selection-end"}))}emit(e,o,n={}){let s=()=>{this.eventListeners[e]&&this.eventListeners[e].forEach(r=>{try{r(o)}catch(i){T.warn(`The following error occurred in deepdeskSDK.on('${e}', handler)`),T.error(i)}})};this.inputMediator&&n.mayApplyChanges?this.inputMediator.applyChanges(s):s()}on(e,o){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(o),()=>{this.off(e,o)}}off(e,o){if(!e&&!o){this.eventListeners={};return}let n;this.eventListeners[e]&&(n=this.eventListeners[e].indexOf(o),n>-1&&this.eventListeners[e].splice(n,1))}setConversationQuery(e){this.dynamicThunkObject.conversationQuery=e}whenConversationLoaded(e){let o=()=>this.loadProfileConfig().then(()=>e());this.hasConversation()&&o();let n=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==n&&(n=this.hasConversation(),n&&o())})}overlayContainerFactory(e,o,n,s){let[r,i]=At(o,n);return r.setAttribute("translate","no"),r.dataset.testid=e,s&&r.classList.add(s),this.unmountHandlers.push(()=>{(0,we.unmountComponentAtNode)(r),i(),r.remove()}),r}createInlineContainer(e,o){var i;let n=document.createElement("div");n.style.position="absolute",n.style.top="0px",n.style.left="0px",n.style.height="0px",n.style.width="0px";let s=document.createElement("div");s.style.display="none",s.style.position="absolute",s.style.height="0px",s.style.width="0px",s.style.backgroundColor="red",n.appendChild(s);let r=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;if(r){let[a,l]=At(r,{appendTo:document.body});a.dataset.testid=o,a.style.zIndex="2",a.appendChild(n),this.unmountHandlers.push(()=>{(0,we.unmountComponentAtNode)(s),l()})}else document.body.appendChild(n);return s}createContainer(e,o=document.body){let n=window.getComputedStyle(o),s=document.createElement("div");return Pt(s),s.dataset.testid=e,s.style.color=n.color,s.style.fontSize=n.fontSize,s.style.fontFamily=n.fontFamily,s.style.fontVariant=n.fontVariant,s.setAttribute("translate","no"),o.appendChild(s),this.unmountHandlers.push(()=>{(0,we.unmountComponentAtNode)(s),s.remove()}),s}storeMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,o=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(e,o),T.info(`Stored analytics for ${this.conversationId()}`)}catch{}}restoreMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,o=window.sessionStorage.getItem(e);if(!o)return;let n=JSON.parse(o);n.text.trim()===this.state.input.text.trim()?(T.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(Za(n.metrics))):T.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(e)}catch{}}mount(e,o={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!vr(e))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let{customStyles:n={},showStyleSuggestions:s,showTabCompletion:r,showTextSuggestions:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:c,showSuggestionsAfterPattern:p,isEmbedded:d,detectSubmit:u,insertLink:g,inputMediator:f,closestScrollSelector:m,appendOverlayTo:v,inlineSuggestions:w,floatingMenu:h}=o;this.configure({showStyleSuggestions:s,showTabCompletion:r,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:c,showSuggestionsAfterPattern:p,showTextSuggestions:i,insertLink:g,isEmbedded:d,inlineSuggestions:w,floatingMenu:!!h}),o.automaticHandlingTime&&this.setupHandlingTime(e),Pt(e),this.inputMediator=f||(St(e)?new qe(e):new qt(e)),this.inputMediator.on("change",({plainText:_})=>{this.notifyInputChanged(_)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(Qa({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",_=>{this.notifyKeyDown(_)}),this.inputMediator.on("paste",({pastedText:_,selectionText:P})=>{this.notifyPaste(_,P)}),this.inputMediator.on("cut",({selectionText:_})=>{this.notifyCut(_)});let x=m&&uu(e,m)||void 0;if(w){let{customStyles:_,appendOverlayTo:P}=o;if(St(e))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let D=this.createInlineContainer(e,"deepdesk-caret");(0,we.render)((0,z.jsx)(zt,{store:this.store,customStyles:_,children:(0,z.jsx)(Ft,{broadcastEvents:this.broadcastEvents,children:(0,z.jsx)(bp,{})})}),D),this.inputMediator.on("caret",A=>{this.store.dispatch(Oe([])),A?(D.style.display="block",D.style.top=`${A.top}px`,D.style.left=`${A.left}px`):D.style.display="none"});let re=this.overlayContainerFactory("floating-menu",x||e,{appendTo:typeof h=="object"&&"appendOverlayTo"in h?h.appendOverlayTo:P},_==null?void 0:_.floatingMenuRootNode);(0,we.render)((0,z.jsx)(zt,{store:this.store,customStyles:_,children:(0,z.jsx)(Ft,{broadcastEvents:this.broadcastEvents,children:(0,z.jsx)(xu,{onLogIn:()=>this.loginViaPopup().catch(A=>T.warn(A.message))})})}),re)}else{let _=this.overlayContainerFactory("deepdesk-tab-completion",x||e,{appendTo:v,closestScrollElement:x,mirrorOverflow:!0,onRemove:()=>this.unmount()},n==null?void 0:n.rootNode),P=this.overlayContainerFactory("deepdesk-suggestions-overlay",x||e,{appendTo:v},n==null?void 0:n.suggestionsRootNode);(0,we.render)((0,z.jsx)(zt,{store:this.store,customStyles:n,children:(0,z.jsx)(Ft,{broadcastEvents:this.broadcastEvents,children:(0,z.jsx)(Yp,{inputElement:e})})}),_),(0,we.render)((0,z.jsx)(zt,{store:this.store,customStyles:n,children:(0,z.jsx)(Ft,{broadcastEvents:this.broadcastEvents,children:(0,z.jsx)(Ap,{onLogIn:()=>this.loginViaPopup().catch(D=>T.warn(D.message))})})}),P)}(0,we.render)((0,z.jsx)(zt,{store:this.store,customStyles:n,children:(0,z.jsx)(Ft,{broadcastEvents:this.broadcastEvents,children:(0,z.jsx)(fp,{})})}),this.createContainer("deepdesk-overlays"));let b;this.inputMediator.on("selection",_=>{clearTimeout(b),_===null?b=setTimeout(()=>{_!==null&&this.store.dispatch(Lr(_))},500):this.store.dispatch(Lr(_))}),this.inputMediator.on("disabled",()=>{var _;(_=this.inputMediator)==null||_.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{u&&this.notifySubmit()}),this.inputMediator.on("blur",()=>this.store.dispatch(yo(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(yo(!0))),this.store.dispatch(Ua({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.unmountHandlers.push(()=>{this.state.input.text!==""&&(this.store.dispatch(Ue()),this.storeMetrics())}),this.whenConversationLoaded(()=>{var _;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((_=this.state.conversation.current)==null?void 0:_.sessionId)}),this.isMounted=!0}unmount(){var e;this.unmountHandlers.forEach(o=>o()),this.unmountHandlers=[],(e=this.inputMediator)==null||e.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(e,o={}){if(this.widgetRoot&&T.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:n,showImages:s,isEmbedded:r}=o;this.widgetRoot=e,this.configure({showImages:s,isEmbedded:r}),(0,we.render)((0,z.jsx)(zt,{store:this.store,customStyles:n,children:(0,z.jsx)(Ft,{broadcastEvents:this.broadcastEvents,children:(0,z.jsx)(Wd,{onLogIn:()=>this.loginViaPopup().catch(i=>T.warn(i.message))})})}),e),this.whenConversationLoaded(()=>{var i;this.broadcastEvents.setSessionId((i=this.state.conversation.current)==null?void 0:i.sessionId)})}unmountWidget(){this.widgetRoot&&(0,we.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(e){let o=Sr(e,({isVisible:n})=>{n?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),o()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){gu(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(dn());let e=To(this.state);e&&this.store.dispatch(Ho({showSearch:e.search,showAutoflows:e.autoflows,showCustomMessages:e.customMessages,showImageSearch:e.imageSearch,showEntitiesCommand:e.entitiesCommand,showSummaryCommand:e.summarizer,showKnowledgeSearch:e.knowledgeAssistForAgents,recommendTextSuggestions:e.recommendTextSuggestions}))}),this.loadProfileConfigPromise)}async loginViaPopup(){let e=this.state.settings.adminUrl,o=new URL(e),n=await xr(o.origin);return new Promise((s,r)=>{let i=new MessageChannel,a=i.port1,l=new URL(n.config.platform.hasSso?`${e}/platform/sso/`:`${e}/admin/`);l.searchParams.append("redirect","/sdk/popup/close.html");let c=!1,p=()=>{d&&!d.closed&&d.close(),window.removeEventListener("message",u),clearInterval(g)};a.onmessage=async f=>{var m,v;if((m=f.data)!=null&&m.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((v=f.data)==null?void 0:v.jwt),await this.isLoggedIn(),this.broadcastEvents.send(on),p(),c=!0,i.port1.close(),s()}catch(w){r(w)}};let d=window.open(l.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");d===null&&r(new Error("Popup blocked by browser"));let u=async f=>{var m;if(f.origin===l.origin)switch((m=f.data)==null?void 0:m.type){case"deepdesk-popup-loaded":{d==null||d.postMessage({type:"deepdesk-popup-create-channel"},l.origin,[i.port2]);break}case"deepdesk-popup-error":{p(),f.data.message==="Timeout"&&T.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(f.data.message));break}}};window.addEventListener("message",u);let g=setInterval(()=>{d&&!d.closed||(p(),c||r(new Error("Popup closed by user")))},200);this.unmountHandlers.push(p)})}async checkForTrialMode(e){try{let{account:o}=await this.deepdeskApi.getPlatformConfig();if(!o.isTrial){this.shouldRender=!0;return}if(T.info("Trial is active"),!await this.deepdeskApi.checkUserExists(e))throw new Error("User is not in trial");this.shouldRender=!0}catch(o){let{message:n}=o;T.info(n),this.shouldRender=!1}}async refreshWidgetSuggestions(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:e}=this.state.profile.data;if(!e.widget)return;let o=Us(this.state);try{o.forEach(({type:n})=>{n==="entities"?this.store.dispatch(Ae()):this.store.dispatch(We(n))})}catch(n){this.handleError(n)}}};async function Cu(t,e,o={}){let{value:n}=t,{start:s,end:r}=o.replace??{start:0,end:n.length},i=`${n.slice(0,s)}${e}${n.slice(r)}`,a=o.selectionAfter??{start:s+e.length,end:s+e.length},l=()=>{if(o.setValue)return o.setValue(i);t.value=i};return Promise.resolve(l()).then(()=>{t.selectionStart=a.start,t.selectionEnd=a.end,t.blur(),t.focus()})}async function wu(t,e,o={}){let n=o.replace?wt(t,o.replace.start,o.replace.end):Ao(t),s,r=()=>{if(o.setRange)return o.setRange(n.cloneRange());n.deleteContents(),s=document.createElement("span"),n.insertNode(s),o.insertBRs!==!1?e.split(`
|
|
10
10
|
`).reverse().forEach((i,a)=>{a>0&&n.insertNode(document.createElement("br")),n.insertNode(document.createTextNode(i))}):n.insertNode(document.createTextNode(e))};return Promise.resolve(r()).then(()=>{try{if(o.selectionAfter!==!1){t.focus();let i=o.selectionAfter?wt(t,o.selectionAfter.start,o.selectionAfter.end):(n.collapse(!1),n),a=window.getSelection();a==null||a.removeAllRanges(),a==null||a.addRange(i)}if(!s)return;s.scrollIntoView&&s.scrollIntoView({block:"nearest",inline:"nearest"})}finally{s&&s.remove()}})}function lh(t){let e=document.createElement("template");return e.innerHTML=t,e.content}function ch(t){let e=document.createDocumentFragment();return t.split(`
|
|
11
11
|
`).reverse().forEach((o,n)=>{n>0&&e.appendChild(document.createElement("br")),e.appendChild(document.createTextNode(o))}),e}function Tu(t,e){return!t.contains(e)||e===t?null:e.parentNode===t?e:Tu(t,e.parentNode)}async function Eu(t,e,{isBlock:o,isHTML:n}={}){let s;t.dispatchEvent(new InputEvent("beforeinput",{inputType:"insertText",data:e,bubbles:!0,cancelable:!0}));let r=()=>{let i=t.ownerDocument.defaultView??window,a=i.getSelection();if((!a||a.rangeCount===0)&&(t.focus(),a=i.getSelection()),!a||a.rangeCount===0)return;let l=a.getRangeAt(0);if(!l)return;s=document.createElement("span"),l.insertNode(s);let c=n?lh(e):ch(e);if(o){let p=Tu(t,l.startContainer)??t.firstChild;t.insertBefore(c,(p==null?void 0:p.nextSibling)??null)}else l.insertNode(c),l.collapse(!1)};return Promise.resolve(r()).then(()=>{if(t.dispatchEvent(new InputEvent("input",{inputType:"insertText",data:e,bubbles:!0,cancelable:!0})),t.focus(),!!s)try{s.scrollIntoView&&s.scrollIntoView({block:"nearest",inline:"nearest"})}finally{s&&s.remove()}})}function ku(t){return t.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}async function Ru(t,e,o){await new it(t).authenticateWithKey(e,o)}async function ph(t){let o=await(t.fetch??window.fetch)(t.url),n=await o.blob();return new File([n],t.name,{type:t.mimeType??o.headers.get("Content-Type")??"image/jpeg"})}async function Iu(t,e){let o=await ph(e),n=new Event("change",{bubbles:!0,cancelable:!0});try{Object.defineProperty(t,"files",{configurable:!0,get:()=>[o]}),t.dispatchEvent(n)}finally{Object.hasOwn(t,"files")&&delete t.files}}0&&(module.exports={Card,ContentEditableInput,DeepdeskAPI,DeepdeskSDK,HTTPClient,InputMediator,InputType,KeyboardHint,Label,Locale,Section,SectionList,Sources,Suggestion,SuggestionList,TextAreaInput,ToggleButton,attachFile,authenticateWithKey,createFullRange,createOverlayContainer,createRangeFromOffsets,escapeHTML,fetchPlatformConfig,formatTextMarkup,getRangeOffsets,getRangeText,insertCKEditor,isSupportedInputElement,updateContentEditable,updateTextArea,useStyles,waitForElementVisibilityChange});
|
package/dist/index.esm.js
CHANGED
|
@@ -6,6 +6,6 @@ Try polyfilling it using "@formatjs/intl-pluralrules"
|
|
|
6
6
|
c-17.9,17.9-27.3,40.1-27.3,65.7C163.4,163,163.4,233,163.4,233z M465.5,267.9V477c0,9.4-3.4,17.9-10.2,24.7
|
|
7
7
|
c-6.8,6.8-15.4,10.2-24.7,10.2h-349c-9.4,0-17.9-3.4-24.7-10.2c-6.8-6.8-10.2-15.4-10.2-24.7V267.9c0-9.4,3.4-17.9,10.2-24.7
|
|
8
8
|
c6.8-6.8,15.4-10.2,24.7-10.2h11.9v-70c0-44.4,16.2-82.8,47.8-115.2S212.1,0,256.4,0s82.8,16.2,115.2,47.8
|
|
9
|
-
c32.4,32.4,47.8,70,47.8,115.2v70h11.9c9.4,0,17.9,3.4,24.7,10.2C462.1,250,465.5,257.7,465.5,267.9z`})})});import{jsx as sd}from"react/jsx-runtime";var Cv={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},rd=({className:t,color:e})=>sd("svg",{className:t,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:sd("path",{d:"M172.03 0.0199966H0V86.03C47.5 86.03 86 124.54 86 172.04C86 124.54 124.51 86.03 172.01 86.03C219.51 86.03 258.03 124.54 258.03 172.04C258.03 219.54 219.52 258.05 172.01 258.05C124.5 258.05 86 219.54 86 172.04C86 219.54 47.5 258.05 0 258.05V344.06H172.03C267.04 344.06 344.06 267.04 344.06 172.03C344.06 77.02 267.04 0 172.03 0V0.0199966Z",fill:Cv[e||"pink"]})});var id={root:"_root_bgd7a_1",text:"_text_bgd7a_18",icon:"_icon_bgd7a_33",logo:"_logo_bgd7a_38",lock:"_lock_bgd7a_43"};var oi={};j(oi,{enUS:()=>wv,nlNL:()=>Tv});var wv={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"}]},Tv={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"}]};import{useDispatch as kv}from"react-redux";import{jsx as ni,jsxs as ad}from"react/jsx-runtime";var ld=({onLogIn:t})=>{let e=E(oi),o=C("productName"),n=kv(),s=Ev(oe),r=y("FloatingMenu",id);if(s===null)return null;let i=()=>{s===!0?n(G(!0)):t()};return ad("button",{className:r.root,onClick:i,children:[ni("div",{className:r.text,children:e(s?"search":"signin",{productName:o})}),ad("div",{className:r.icon,children:[ni(rd,{className:r.logo,color:"pink"}),s===!1&&ni(nd,{className:r.lock})]})]})};async function si(t){let o=await new he(t).get("/platform/config/",{version:null});return A(o)}import{jsx as K}from"react/jsx-runtime";var cd=td("showTabHint",!0),ss=class t{static version="10.9.3-beta.1";static count=0;deepdeskApi;inputMediator=null;version;broadcastEvents;eventListeners={};unmountHandlers=[];widgetRoot=null;dynamicThunkObject={};isMounted=!1;instanceId;shouldRender=!0;store;constructor({deepdeskUrl:e,brokerUrl:o,version:n=t.version||"unknown",locale:s="en-US",token:r,fetch:i,productName:a,createCustomChannel:l}){let c=e.replace(/\/api$/,"");this.deepdeskApi=new Ue(c,{token:r,fetch:i}),this.version=n,this.instanceId=t.count++;let p={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[Zp({emit:(d,u,g)=>this.emit(d,u,g),handleAfterSendMessage:d=>this.handleAfterSendMessage(d),handleInputChanged:d=>this.handleInputChanged(d),handleKeyDown:d=>this.handleKeyDown(d),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:d=>this.logSendMessage(d),logSendEditSuggestionMessage:d=>this.logSendEditMessage(d),onUpdateShowTabHint:d=>cd.update(d),sendEvent:(d,u)=>this.deepdeskApi.sendEvent(d,u)})]};o&&Object.assign(p,{deepdeskBrokerAPI:new xo(o)}),this.store=Qp(p),this.broadcastEvents=new Bp({debug:!0,deepdeskUrl:c,eventMap:Tl(this.store),createCustomChannel:l}),this.store.dispatch(qt),this.store.dispatch(no(cd.value())),this.store.dispatch(qt({locale:s,adminUrl:c,productName:a}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){return this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex]??null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(T.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(T.warn("Profile has not been loaded (yet)"),!0):(T.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(kt(null)),this.store.dispatch(Ce()),new Promise(e=>{let o=this.store.subscribe(()=>{let n=this.store.getState();oe(n)&&vl(n)!=="loading"&&(o(),e())});this.unmountHandlers.push(()=>{o()})})}async isLoggedIn(){return(await this.store.dispatch(Ce())).payload}async setPlatformAgentId(e){try{if((await this.deepdeskApi.client.get("/apis/admin/session/me/",{version:null})).external_id)return;await this.deepdeskApi.client.request("/apis/admin/session/me/",{method:"PATCH",body:JSON.stringify({external_id:e}),version:null})}catch(o){T.warn("Failed to attach user:",o)}}async isConversationSupported(e,o){return(await this.store.dispatch(Ss({sessionId:e,options:o}))).payload}async createConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(Lo(e))).payload}async getConversationBySessionId(e,o){return this.hasConversation()&&this.sessionId()!==e&&this.resetConversation(),(await this.store.dispatch(Mo({sessionId:e,options:o}))).payload}async upsertConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(_s(e))).payload}async postMessages(e){return(await this.store.dispatch(Oo(e))).payload}async updateConversation(e){return(await this.store.dispatch(No(e))).payload}resetConversation(){this.store.dispatch(P()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}async getSummary(){let e=await this.store.dispatch(Te());if(e.error)throw new Error(e.error.message);return e.payload.summary}configure(e){this.store.dispatch(qt(e))}setVisitorInfo(e){this.store.dispatch(Ma(e))}async setAgentInfo(e){await this.store.dispatch(Yt(e))}async setAgentSettings(e){await this.store.dispatch(er(e))}async getAgentSettings(){return(await this.store.dispatch(tr())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let e=[];return this.store.dispatch(xn()),e.push(this.refreshWidgetSuggestions()),Promise.all(e).then(()=>{})}notifyInputChanged(e){this.store.dispatch(Uo(e))}notifyKeyDown(e){this.store.dispatch(Fo(e))}notifyPaste(e,o){this.store.dispatch(Ai({text:e,selectionText:o}))}notifyCut(e){this.store.dispatch(Ii(e))}notifyExternalSuggestion(e){this.store.dispatch(ie(e)),this.store.dispatch(ve())}notifyEditSuggestion(e){this.store.dispatch(sl(e.contentType,e.suggestions)),this.store.dispatch(be({contentType:e.contentType,suggestion:typeof e.index=="number"?e.suggestions[e.index]:null}))}handleInputChanged(e){let{overlayCollapsed:o,openOverlayWhenTyping:n}=this.state.ui;o&&n&&this.store.dispatch(Be({collapse:!1})),this.inputMediator&&this.store.dispatch(Ci({text:e,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(de([])))}handleKeyDown(e){let{overlayCollapsed:o}=this.state.ui,{textSuggestions:n,selectedSuggestionIndex:s,selection:r}=this.state.input,{inlineSuggestions:i}=this.state.settings,a=n.length>0,l=s!==-1;if(this.store.dispatch(Pi(Ho(e))),e.key!=="Tab"&&!this.settings.showTextSuggestions)return;let c=()=>{o||!a||r&&(e.shiftKey||(this.store.dispatch(Ei()),i||this.stageSelectedSuggestion({inputType:"arrow"}),e.preventDefault()))},p=()=>{if(o||!a||!r||e.shiftKey)return;this.store.dispatch(Ri());let{selectedSuggestionIndex:d}=this.state.input;e.preventDefault(),!i&&(d===-1?this.store.dispatch(Vt()):this.stageSelectedSuggestion({inputType:"arrow"}))};switch(e.key){case"Up":case"ArrowUp":i?p():c();return;case"Down":case"ArrowDown":{i?c():p();return}case"Esc":case"Escape":{i&&l&&this.store.dispatch(Me(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(Me(-1)),this.store.dispatch(Vt()),e.preventDefault()):o||(this.store.dispatch(Be({collapse:!0})),this.store.dispatch(gl(!0)),e.preventDefault());return}case"Tab":{let{userCommitted:d}=this.state.input,u=d.text.substring(0,d.selection.end),{tabCompletionSuggestion:g}=this.state.input;this.store.dispatch(no(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!i&&this.settings.showTabCompletion&&g&&g.text.startsWith(u)&&(this.store.dispatch(ie({text:g.text,suggestion:g,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch(ve())),e.preventDefault();break}default:}}handleAfterSendMessage(e){this.emit("send-message",e),this.store.dispatch(Li()),this.store.dispatch(de([]))}handlingTimeStart(){this.state.handlingTime.startTime||(T.info("Start handling time"),this.store.dispatch(Up()))}handlingTimeStop(){this.state.handlingTime.startTime&&(T.info("Stop handling time"),this.store.dispatch(ts()))}logSendMessage(e){let o=Zr("input",this.state,{version:this.version});e&&(Object.assign(o,{text:e}),Object.assign(o,{lenTextTotal:e.length})),this.deepdeskApi.sendEventV1("Send Message",o),this.emit("send-message-event",o)}logSendEditMessage(e){let o=Zr("overlayInput",this.state,{version:this.version});e&&Object.assign(o,{text:e}),this.store.dispatch(Ti(this.state.overlayInput.metrics))}logHandlingTime(){let e=Jp(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",e),this.store.dispatch(zp())}notifySubmit(e={}){this.shouldAbort()||(this.store.dispatch(ve()),this.store.dispatch(Ve(e.text??this.state.input.text)))}stageSelectedSuggestion(e){let o=this.state.input.selectedSuggestionIndex,{textSuggestions:n}=this.state.input;this.store.dispatch(ie({text:n[o].text,suggestion:n[o],eventMetrics:e,replace:"until-selection-end"}))}emit(e,o,n={}){let s=()=>{this.eventListeners[e]&&this.eventListeners[e].forEach(r=>{try{r(o)}catch(i){T.warn(`The following error occurred in deepdeskSDK.on('${e}', handler)`),T.error(i)}})};this.inputMediator&&n.mayApplyChanges?this.inputMediator.applyChanges(s):s()}on(e,o){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(o),()=>{this.off(e,o)}}off(e,o){if(!e&&!o){this.eventListeners={};return}let n;this.eventListeners[e]&&(n=this.eventListeners[e].indexOf(o),n>-1&&this.eventListeners[e].splice(n,1))}setConversationQuery(e){this.dynamicThunkObject.conversationQuery=e}whenConversationLoaded(e){let o=()=>this.loadProfileConfig().then(()=>e());this.hasConversation()&&o();let n=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==n&&(n=this.hasConversation(),n&&o())})}overlayContainerFactory(e,o,n,s){let[r,i]=xt(o,n);return r.setAttribute("translate","no"),r.dataset.testid=e,s&&r.classList.add(s),this.unmountHandlers.push(()=>{ns(r),i(),r.remove()}),r}createInlineContainer(e,o){var i;let n=document.createElement("div");n.style.position="absolute",n.style.top="0px",n.style.left="0px",n.style.height="0px",n.style.width="0px";let s=document.createElement("div");s.style.display="none",s.style.position="absolute",s.style.height="0px",s.style.width="0px",s.style.backgroundColor="red",n.appendChild(s);let r=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;if(r){let[a,l]=xt(r,{appendTo:document.body});a.dataset.testid=o,a.style.zIndex="2",a.appendChild(n),this.unmountHandlers.push(()=>{ns(s),l()})}else document.body.appendChild(n);return s}createContainer(e,o=document.body){let n=window.getComputedStyle(o),s=document.createElement("div");return Ge(s),s.dataset.testid=e,s.style.color=n.color,s.style.fontSize=n.fontSize,s.style.fontFamily=n.fontFamily,s.style.fontVariant=n.fontVariant,s.setAttribute("translate","no"),o.appendChild(s),this.unmountHandlers.push(()=>{ns(s),s.remove()}),s}storeMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,o=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(e,o),T.info(`Stored analytics for ${this.conversationId()}`)}catch{}}restoreMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,o=window.sessionStorage.getItem(e);if(!o)return;let n=JSON.parse(o);n.text.trim()===this.state.input.text.trim()?(T.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(Ni(n.metrics))):T.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(e)}catch{}}mount(e,o={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!Yr(e))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let{customStyles:n={},showStyleSuggestions:s,showTabCompletion:r,showTextSuggestions:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:c,showSuggestionsAfterPattern:p,isEmbedded:d,detectSubmit:u,insertLink:g,inputMediator:f,closestScrollSelector:m,appendOverlayTo:v,inlineSuggestions:w,floatingMenu:h}=o;this.configure({showStyleSuggestions:s,showTabCompletion:r,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:c,showSuggestionsAfterPattern:p,showTextSuggestions:i,insertLink:g,isEmbedded:d,inlineSuggestions:w,floatingMenu:!!h}),o.automaticHandlingTime&&this.setupHandlingTime(e),Ge(e),this.inputMediator=f||(Fe(e)?new Oe(e):new Bt(e)),this.inputMediator.on("change",({plainText:_})=>{this.notifyInputChanged(_)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(Mi({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",_=>{this.notifyKeyDown(_)}),this.inputMediator.on("paste",({pastedText:_,selectionText:R})=>{this.notifyPaste(_,R)}),this.inputMediator.on("cut",({selectionText:_})=>{this.notifyCut(_)});let x=m&&Yp(e,m)||void 0;if(w){let{customStyles:_,appendOverlayTo:R}=o;if(Fe(e))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let O=this.createInlineContainer(e,"deepdesk-caret");Ut(K(Ye,{store:this.store,customStyles:_,children:K(Je,{broadcastEvents:this.broadcastEvents,children:K(gc,{})})}),O),this.inputMediator.on("caret",I=>{this.store.dispatch(de([])),I?(O.style.display="block",O.style.top=`${I.top}px`,O.style.left=`${I.left}px`):O.style.display="none"});let X=this.overlayContainerFactory("floating-menu",x||e,{appendTo:typeof h=="object"&&"appendOverlayTo"in h?h.appendOverlayTo:R},_==null?void 0:_.floatingMenuRootNode);Ut(K(Ye,{store:this.store,customStyles:_,children:K(Je,{broadcastEvents:this.broadcastEvents,children:K(ld,{onLogIn:()=>this.loginViaPopup().catch(I=>T.warn(I.message))})})}),X)}else{let _=this.overlayContainerFactory("deepdesk-tab-completion",x||e,{appendTo:v,closestScrollElement:x,mirrorOverflow:!0,onRemove:()=>this.unmount()},n==null?void 0:n.rootNode),R=this.overlayContainerFactory("deepdesk-suggestions-overlay",x||e,{appendTo:v},n==null?void 0:n.suggestionsRootNode);Ut(K(Ye,{store:this.store,customStyles:n,children:K(Je,{broadcastEvents:this.broadcastEvents,children:K(jc,{inputElement:e})})}),_),Ut(K(Ye,{store:this.store,customStyles:n,children:K(Je,{broadcastEvents:this.broadcastEvents,children:K(bc,{onLogIn:()=>this.loginViaPopup().catch(O=>T.warn(O.message))})})}),R)}Ut(K(Ye,{store:this.store,customStyles:n,children:K(Je,{broadcastEvents:this.broadcastEvents,children:K(ac,{})})}),this.createContainer("deepdesk-overlays"));let b;this.inputMediator.on("selection",_=>{clearTimeout(b),_===null?b=setTimeout(()=>{_!==null&&this.store.dispatch(bs(_))},500):this.store.dispatch(bs(_))}),this.inputMediator.on("disabled",()=>{var _;(_=this.inputMediator)==null||_.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{u&&this.notifySubmit()}),this.inputMediator.on("blur",()=>this.store.dispatch(Et(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(Et(!0))),this.store.dispatch(wi({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.unmountHandlers.push(()=>{this.state.input.text!==""&&(this.store.dispatch(ve()),this.storeMetrics())}),this.whenConversationLoaded(()=>{var _;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((_=this.state.conversation.current)==null?void 0:_.sessionId)}),this.isMounted=!0}unmount(){var e;this.unmountHandlers.forEach(o=>o()),this.unmountHandlers=[],(e=this.inputMediator)==null||e.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(e,o={}){if(this.widgetRoot&&T.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:n,showImages:s,isEmbedded:r}=o;this.widgetRoot=e,this.configure({showImages:s,isEmbedded:r}),Ut(K(Ye,{store:this.store,customStyles:n,children:K(Je,{broadcastEvents:this.broadcastEvents,children:K(Np,{onLogIn:()=>this.loginViaPopup().catch(i=>T.warn(i.message))})})}),e),this.whenConversationLoaded(()=>{var i;this.broadcastEvents.setSessionId((i=this.state.conversation.current)==null?void 0:i.sessionId)})}unmountWidget(){this.widgetRoot&&ns(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(e){let o=ei(e,({isVisible:n})=>{n?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),o()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){ed(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(co());let e=Lt(this.state);e&&this.store.dispatch(qt({showSearch:e.search,showAutoflows:e.autoflows,showCustomMessages:e.customMessages,showImageSearch:e.imageSearch,showEntitiesCommand:e.entitiesCommand,showSummaryCommand:e.summarizer,showKnowledgeSearch:e.knowledgeAssistForAgents,recommendTextSuggestions:e.recommendTextSuggestions}))}),this.loadProfileConfigPromise)}async loginViaPopup(){let e=this.state.settings.adminUrl,o=new URL(e),n=await si(o.origin);return new Promise((s,r)=>{let i=new MessageChannel,a=i.port1,l=new URL(n.config.platform.hasSso?`${e}/platform/sso/`:`${e}/admin/`);l.searchParams.append("redirect","/sdk/popup/close.html");let c=!1,p=()=>{d&&!d.closed&&d.close(),window.removeEventListener("message",u),clearInterval(g)};a.onmessage=async f=>{var m,v;if((m=f.data)!=null&&m.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((v=f.data)==null?void 0:v.jwt),await this.isLoggedIn(),this.broadcastEvents.send(ro),p(),c=!0,i.port1.close(),s()}catch(w){r(w)}};let d=window.open(l.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");d===null&&r(new Error("Popup blocked by browser"));let u=async f=>{var m;if(f.origin===l.origin)switch((m=f.data)==null?void 0:m.type){case"deepdesk-popup-loaded":{d==null||d.postMessage({type:"deepdesk-popup-create-channel"},l.origin,[i.port2]);break}case"deepdesk-popup-error":{p(),f.data.message==="Timeout"&&T.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(f.data.message));break}}};window.addEventListener("message",u);let g=setInterval(()=>{d&&!d.closed||(p(),c||r(new Error("Popup closed by user")))},200);this.unmountHandlers.push(p)})}async checkForTrialMode(e){try{let{account:o}=await this.deepdeskApi.getPlatformConfig();if(!o.isTrial){this.shouldRender=!0;return}if(T.info("Trial is active"),!await this.deepdeskApi.checkUserExists(e))throw new Error("User is not in trial");this.shouldRender=!0}catch(o){let{message:n}=o;T.info(n),this.shouldRender=!1}}async refreshWidgetSuggestions(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:e}=this.state.profile.data;if(!e.widget)return;let o=kn(this.state);try{o.forEach(({type:n})=>{n==="entities"?this.store.dispatch(ce()):this.store.dispatch(xe(n))})}catch(n){this.handleError(n)}}};async function Rv(t,e,o={}){let{value:n}=t,{start:s,end:r}=o.replace??{start:0,end:n.length},i=`${n.slice(0,s)}${e}${n.slice(r)}`,a=o.selectionAfter??{start:s+e.length,end:s+e.length},l=()=>{if(o.setValue)return o.setValue(i);t.value=i};return Promise.resolve(l()).then(()=>{t.selectionStart=a.start,t.selectionEnd=a.end,t.blur(),t.focus()})}async function Iv(t,e,o={}){let n=o.replace?nt(t,o.replace.start,o.replace.end):So(t),s,r=()=>{if(o.setRange)return o.setRange(n.cloneRange());n.deleteContents(),s=document.createElement("span"),n.insertNode(s),o.insertBRs!==!1?e.split(`
|
|
9
|
+
c32.4,32.4,47.8,70,47.8,115.2v70h11.9c9.4,0,17.9,3.4,24.7,10.2C462.1,250,465.5,257.7,465.5,267.9z`})})});import{jsx as sd}from"react/jsx-runtime";var Cv={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},rd=({className:t,color:e})=>sd("svg",{className:t,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:sd("path",{d:"M172.03 0.0199966H0V86.03C47.5 86.03 86 124.54 86 172.04C86 124.54 124.51 86.03 172.01 86.03C219.51 86.03 258.03 124.54 258.03 172.04C258.03 219.54 219.52 258.05 172.01 258.05C124.5 258.05 86 219.54 86 172.04C86 219.54 47.5 258.05 0 258.05V344.06H172.03C267.04 344.06 344.06 267.04 344.06 172.03C344.06 77.02 267.04 0 172.03 0V0.0199966Z",fill:Cv[e||"pink"]})});var id={root:"_root_bgd7a_1",text:"_text_bgd7a_18",icon:"_icon_bgd7a_33",logo:"_logo_bgd7a_38",lock:"_lock_bgd7a_43"};var oi={};j(oi,{enUS:()=>wv,nlNL:()=>Tv});var wv={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"}]},Tv={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"}]};import{useDispatch as kv}from"react-redux";import{jsx as ni,jsxs as ad}from"react/jsx-runtime";var ld=({onLogIn:t})=>{let e=E(oi),o=C("productName"),n=kv(),s=Ev(oe),r=y("FloatingMenu",id);if(s===null)return null;let i=()=>{s===!0?n(G(!0)):t()};return ad("button",{className:r.root,onClick:i,children:[ni("div",{className:r.text,children:e(s?"search":"signin",{productName:o})}),ad("div",{className:r.icon,children:[ni(rd,{className:r.logo,color:"pink"}),s===!1&&ni(nd,{className:r.lock})]})]})};async function si(t){let o=await new he(t).get("/platform/config/",{version:null});return A(o)}import{jsx as K}from"react/jsx-runtime";var cd=td("showTabHint",!0),ss=class t{static version="10.9.3-beta.2";static count=0;deepdeskApi;inputMediator=null;version;broadcastEvents;eventListeners={};unmountHandlers=[];widgetRoot=null;dynamicThunkObject={};isMounted=!1;instanceId;shouldRender=!0;store;constructor({deepdeskUrl:e,brokerUrl:o,version:n=t.version||"unknown",locale:s="en-US",token:r,fetch:i,productName:a,createCustomChannel:l}){let c=e.replace(/\/api$/,"");this.deepdeskApi=new Ue(c,{token:r,fetch:i}),this.version=n,this.instanceId=t.count++;let p={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[Zp({emit:(d,u,g)=>this.emit(d,u,g),handleAfterSendMessage:d=>this.handleAfterSendMessage(d),handleInputChanged:d=>this.handleInputChanged(d),handleKeyDown:d=>this.handleKeyDown(d),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:d=>this.logSendMessage(d),logSendEditSuggestionMessage:d=>this.logSendEditMessage(d),onUpdateShowTabHint:d=>cd.update(d),sendEvent:(d,u)=>this.deepdeskApi.sendEvent(d,u)})]};o&&Object.assign(p,{deepdeskBrokerAPI:new xo(o)}),this.store=Qp(p),this.broadcastEvents=new Bp({debug:!0,deepdeskUrl:c,eventMap:Tl(this.store),createCustomChannel:l}),this.store.dispatch(qt),this.store.dispatch(no(cd.value())),this.store.dispatch(qt({locale:s,adminUrl:c,productName:a}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){return this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex]??null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(T.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(T.warn("Profile has not been loaded (yet)"),!0):(T.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(kt(null)),this.store.dispatch(Ce()),new Promise(e=>{let o=this.store.subscribe(()=>{let n=this.store.getState();oe(n)&&vl(n)!=="loading"&&(o(),e())});this.unmountHandlers.push(()=>{o()})})}async isLoggedIn(){return(await this.store.dispatch(Ce())).payload}async setPlatformAgentId(e){try{if((await this.deepdeskApi.client.get("/apis/admin/session/me/",{version:null})).external_id)return;await this.deepdeskApi.client.request("/apis/admin/session/me/",{method:"PATCH",body:JSON.stringify({external_id:e}),version:null})}catch(o){T.warn("Failed to attach user:",o)}}async isConversationSupported(e,o){return(await this.store.dispatch(Ss({sessionId:e,options:o}))).payload}async createConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(Lo(e))).payload}async getConversationBySessionId(e,o){return this.hasConversation()&&this.sessionId()!==e&&this.resetConversation(),(await this.store.dispatch(Mo({sessionId:e,options:o}))).payload}async upsertConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(_s(e))).payload}async postMessages(e){return(await this.store.dispatch(Oo(e))).payload}async updateConversation(e){return(await this.store.dispatch(No(e))).payload}resetConversation(){this.store.dispatch(P()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}async getSummary(){let e=await this.store.dispatch(Te());if(e.error)throw new Error(e.error.message);return e.payload.summary}configure(e){this.store.dispatch(qt(e))}setVisitorInfo(e){this.store.dispatch(Ma(e))}async setAgentInfo(e){await this.store.dispatch(Yt(e))}async setAgentSettings(e){await this.store.dispatch(er(e))}async getAgentSettings(){return(await this.store.dispatch(tr())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let e=[];return this.store.dispatch(xn()),e.push(this.refreshWidgetSuggestions()),Promise.all(e).then(()=>{})}notifyInputChanged(e){this.store.dispatch(Uo(e))}notifyKeyDown(e){this.store.dispatch(Fo(e))}notifyPaste(e,o){this.store.dispatch(Ai({text:e,selectionText:o}))}notifyCut(e){this.store.dispatch(Ii(e))}notifyExternalSuggestion(e){this.store.dispatch(ie(e)),this.store.dispatch(ve())}notifyEditSuggestion(e){this.store.dispatch(sl(e.contentType,e.suggestions)),this.store.dispatch(be({contentType:e.contentType,suggestion:typeof e.index=="number"?e.suggestions[e.index]:null}))}handleInputChanged(e){let{overlayCollapsed:o,openOverlayWhenTyping:n}=this.state.ui;o&&n&&this.store.dispatch(Be({collapse:!1})),this.inputMediator&&this.store.dispatch(Ci({text:e,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(de([])))}handleKeyDown(e){let{overlayCollapsed:o}=this.state.ui,{textSuggestions:n,selectedSuggestionIndex:s,selection:r}=this.state.input,{inlineSuggestions:i}=this.state.settings,a=n.length>0,l=s!==-1;if(this.store.dispatch(Pi(Ho(e))),e.key!=="Tab"&&!this.settings.showTextSuggestions)return;let c=()=>{o||!a||r&&(e.shiftKey||(this.store.dispatch(Ei()),i||this.stageSelectedSuggestion({inputType:"arrow"}),e.preventDefault()))},p=()=>{if(o||!a||!r||e.shiftKey)return;this.store.dispatch(Ri());let{selectedSuggestionIndex:d}=this.state.input;e.preventDefault(),!i&&(d===-1?this.store.dispatch(Vt()):this.stageSelectedSuggestion({inputType:"arrow"}))};switch(e.key){case"Up":case"ArrowUp":i?p():c();return;case"Down":case"ArrowDown":{i?c():p();return}case"Esc":case"Escape":{i&&l&&this.store.dispatch(Me(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(Me(-1)),this.store.dispatch(Vt()),e.preventDefault()):o||(this.store.dispatch(Be({collapse:!0})),this.store.dispatch(gl(!0)),e.preventDefault());return}case"Tab":{let{userCommitted:d}=this.state.input,u=d.text.substring(0,d.selection.end),{tabCompletionSuggestion:g}=this.state.input;this.store.dispatch(no(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!i&&this.settings.showTabCompletion&&g&&g.text.startsWith(u)&&(this.store.dispatch(ie({text:g.text,suggestion:g,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch(ve())),e.preventDefault();break}default:}}handleAfterSendMessage(e){this.emit("send-message",e),this.store.dispatch(Li()),this.store.dispatch(de([]))}handlingTimeStart(){this.state.handlingTime.startTime||(T.info("Start handling time"),this.store.dispatch(Up()))}handlingTimeStop(){this.state.handlingTime.startTime&&(T.info("Stop handling time"),this.store.dispatch(ts()))}logSendMessage(e){let o=Zr("input",this.state,{version:this.version});e&&(Object.assign(o,{text:e}),Object.assign(o,{lenTextTotal:e.length})),this.deepdeskApi.sendEventV1("Send Message",o),this.emit("send-message-event",o)}logSendEditMessage(e){let o=Zr("overlayInput",this.state,{version:this.version});e&&Object.assign(o,{text:e}),this.store.dispatch(Ti(this.state.overlayInput.metrics))}logHandlingTime(){let e=Jp(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",e),this.store.dispatch(zp())}notifySubmit(e={}){this.shouldAbort()||(this.store.dispatch(ve()),this.store.dispatch(Ve(e.text??this.state.input.text)))}stageSelectedSuggestion(e){let o=this.state.input.selectedSuggestionIndex,{textSuggestions:n}=this.state.input;this.store.dispatch(ie({text:n[o].text,suggestion:n[o],eventMetrics:e,replace:"until-selection-end"}))}emit(e,o,n={}){let s=()=>{this.eventListeners[e]&&this.eventListeners[e].forEach(r=>{try{r(o)}catch(i){T.warn(`The following error occurred in deepdeskSDK.on('${e}', handler)`),T.error(i)}})};this.inputMediator&&n.mayApplyChanges?this.inputMediator.applyChanges(s):s()}on(e,o){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(o),()=>{this.off(e,o)}}off(e,o){if(!e&&!o){this.eventListeners={};return}let n;this.eventListeners[e]&&(n=this.eventListeners[e].indexOf(o),n>-1&&this.eventListeners[e].splice(n,1))}setConversationQuery(e){this.dynamicThunkObject.conversationQuery=e}whenConversationLoaded(e){let o=()=>this.loadProfileConfig().then(()=>e());this.hasConversation()&&o();let n=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==n&&(n=this.hasConversation(),n&&o())})}overlayContainerFactory(e,o,n,s){let[r,i]=xt(o,n);return r.setAttribute("translate","no"),r.dataset.testid=e,s&&r.classList.add(s),this.unmountHandlers.push(()=>{ns(r),i(),r.remove()}),r}createInlineContainer(e,o){var i;let n=document.createElement("div");n.style.position="absolute",n.style.top="0px",n.style.left="0px",n.style.height="0px",n.style.width="0px";let s=document.createElement("div");s.style.display="none",s.style.position="absolute",s.style.height="0px",s.style.width="0px",s.style.backgroundColor="red",n.appendChild(s);let r=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;if(r){let[a,l]=xt(r,{appendTo:document.body});a.dataset.testid=o,a.style.zIndex="2",a.appendChild(n),this.unmountHandlers.push(()=>{ns(s),l()})}else document.body.appendChild(n);return s}createContainer(e,o=document.body){let n=window.getComputedStyle(o),s=document.createElement("div");return Ge(s),s.dataset.testid=e,s.style.color=n.color,s.style.fontSize=n.fontSize,s.style.fontFamily=n.fontFamily,s.style.fontVariant=n.fontVariant,s.setAttribute("translate","no"),o.appendChild(s),this.unmountHandlers.push(()=>{ns(s),s.remove()}),s}storeMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,o=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(e,o),T.info(`Stored analytics for ${this.conversationId()}`)}catch{}}restoreMetrics(){try{let e=`dd-metrics-${this.conversationId()}`,o=window.sessionStorage.getItem(e);if(!o)return;let n=JSON.parse(o);n.text.trim()===this.state.input.text.trim()?(T.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(Ni(n.metrics))):T.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(e)}catch{}}mount(e,o={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!Yr(e))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let{customStyles:n={},showStyleSuggestions:s,showTabCompletion:r,showTextSuggestions:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:c,showSuggestionsAfterPattern:p,isEmbedded:d,detectSubmit:u,insertLink:g,inputMediator:f,closestScrollSelector:m,appendOverlayTo:v,inlineSuggestions:w,floatingMenu:h}=o;this.configure({showStyleSuggestions:s,showTabCompletion:r,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:c,showSuggestionsAfterPattern:p,showTextSuggestions:i,insertLink:g,isEmbedded:d,inlineSuggestions:w,floatingMenu:!!h}),o.automaticHandlingTime&&this.setupHandlingTime(e),Ge(e),this.inputMediator=f||(Fe(e)?new Oe(e):new Bt(e)),this.inputMediator.on("change",({plainText:_})=>{this.notifyInputChanged(_)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(Mi({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",_=>{this.notifyKeyDown(_)}),this.inputMediator.on("paste",({pastedText:_,selectionText:R})=>{this.notifyPaste(_,R)}),this.inputMediator.on("cut",({selectionText:_})=>{this.notifyCut(_)});let x=m&&Yp(e,m)||void 0;if(w){let{customStyles:_,appendOverlayTo:R}=o;if(Fe(e))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let O=this.createInlineContainer(e,"deepdesk-caret");Ut(K(Ye,{store:this.store,customStyles:_,children:K(Je,{broadcastEvents:this.broadcastEvents,children:K(gc,{})})}),O),this.inputMediator.on("caret",I=>{this.store.dispatch(de([])),I?(O.style.display="block",O.style.top=`${I.top}px`,O.style.left=`${I.left}px`):O.style.display="none"});let X=this.overlayContainerFactory("floating-menu",x||e,{appendTo:typeof h=="object"&&"appendOverlayTo"in h?h.appendOverlayTo:R},_==null?void 0:_.floatingMenuRootNode);Ut(K(Ye,{store:this.store,customStyles:_,children:K(Je,{broadcastEvents:this.broadcastEvents,children:K(ld,{onLogIn:()=>this.loginViaPopup().catch(I=>T.warn(I.message))})})}),X)}else{let _=this.overlayContainerFactory("deepdesk-tab-completion",x||e,{appendTo:v,closestScrollElement:x,mirrorOverflow:!0,onRemove:()=>this.unmount()},n==null?void 0:n.rootNode),R=this.overlayContainerFactory("deepdesk-suggestions-overlay",x||e,{appendTo:v},n==null?void 0:n.suggestionsRootNode);Ut(K(Ye,{store:this.store,customStyles:n,children:K(Je,{broadcastEvents:this.broadcastEvents,children:K(jc,{inputElement:e})})}),_),Ut(K(Ye,{store:this.store,customStyles:n,children:K(Je,{broadcastEvents:this.broadcastEvents,children:K(bc,{onLogIn:()=>this.loginViaPopup().catch(O=>T.warn(O.message))})})}),R)}Ut(K(Ye,{store:this.store,customStyles:n,children:K(Je,{broadcastEvents:this.broadcastEvents,children:K(ac,{})})}),this.createContainer("deepdesk-overlays"));let b;this.inputMediator.on("selection",_=>{clearTimeout(b),_===null?b=setTimeout(()=>{_!==null&&this.store.dispatch(bs(_))},500):this.store.dispatch(bs(_))}),this.inputMediator.on("disabled",()=>{var _;(_=this.inputMediator)==null||_.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{u&&this.notifySubmit()}),this.inputMediator.on("blur",()=>this.store.dispatch(Et(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(Et(!0))),this.store.dispatch(wi({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.unmountHandlers.push(()=>{this.state.input.text!==""&&(this.store.dispatch(ve()),this.storeMetrics())}),this.whenConversationLoaded(()=>{var _;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((_=this.state.conversation.current)==null?void 0:_.sessionId)}),this.isMounted=!0}unmount(){var e;this.unmountHandlers.forEach(o=>o()),this.unmountHandlers=[],(e=this.inputMediator)==null||e.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(e,o={}){if(this.widgetRoot&&T.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:n,showImages:s,isEmbedded:r}=o;this.widgetRoot=e,this.configure({showImages:s,isEmbedded:r}),Ut(K(Ye,{store:this.store,customStyles:n,children:K(Je,{broadcastEvents:this.broadcastEvents,children:K(Np,{onLogIn:()=>this.loginViaPopup().catch(i=>T.warn(i.message))})})}),e),this.whenConversationLoaded(()=>{var i;this.broadcastEvents.setSessionId((i=this.state.conversation.current)==null?void 0:i.sessionId)})}unmountWidget(){this.widgetRoot&&ns(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(e){let o=ei(e,({isVisible:n})=>{n?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),o()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){ed(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(co());let e=Lt(this.state);e&&this.store.dispatch(qt({showSearch:e.search,showAutoflows:e.autoflows,showCustomMessages:e.customMessages,showImageSearch:e.imageSearch,showEntitiesCommand:e.entitiesCommand,showSummaryCommand:e.summarizer,showKnowledgeSearch:e.knowledgeAssistForAgents,recommendTextSuggestions:e.recommendTextSuggestions}))}),this.loadProfileConfigPromise)}async loginViaPopup(){let e=this.state.settings.adminUrl,o=new URL(e),n=await si(o.origin);return new Promise((s,r)=>{let i=new MessageChannel,a=i.port1,l=new URL(n.config.platform.hasSso?`${e}/platform/sso/`:`${e}/admin/`);l.searchParams.append("redirect","/sdk/popup/close.html");let c=!1,p=()=>{d&&!d.closed&&d.close(),window.removeEventListener("message",u),clearInterval(g)};a.onmessage=async f=>{var m,v;if((m=f.data)!=null&&m.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((v=f.data)==null?void 0:v.jwt),await this.isLoggedIn(),this.broadcastEvents.send(ro),p(),c=!0,i.port1.close(),s()}catch(w){r(w)}};let d=window.open(l.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");d===null&&r(new Error("Popup blocked by browser"));let u=async f=>{var m;if(f.origin===l.origin)switch((m=f.data)==null?void 0:m.type){case"deepdesk-popup-loaded":{d==null||d.postMessage({type:"deepdesk-popup-create-channel"},l.origin,[i.port2]);break}case"deepdesk-popup-error":{p(),f.data.message==="Timeout"&&T.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(f.data.message));break}}};window.addEventListener("message",u);let g=setInterval(()=>{d&&!d.closed||(p(),c||r(new Error("Popup closed by user")))},200);this.unmountHandlers.push(p)})}async checkForTrialMode(e){try{let{account:o}=await this.deepdeskApi.getPlatformConfig();if(!o.isTrial){this.shouldRender=!0;return}if(T.info("Trial is active"),!await this.deepdeskApi.checkUserExists(e))throw new Error("User is not in trial");this.shouldRender=!0}catch(o){let{message:n}=o;T.info(n),this.shouldRender=!1}}async refreshWidgetSuggestions(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:e}=this.state.profile.data;if(!e.widget)return;let o=kn(this.state);try{o.forEach(({type:n})=>{n==="entities"?this.store.dispatch(ce()):this.store.dispatch(xe(n))})}catch(n){this.handleError(n)}}};async function Rv(t,e,o={}){let{value:n}=t,{start:s,end:r}=o.replace??{start:0,end:n.length},i=`${n.slice(0,s)}${e}${n.slice(r)}`,a=o.selectionAfter??{start:s+e.length,end:s+e.length},l=()=>{if(o.setValue)return o.setValue(i);t.value=i};return Promise.resolve(l()).then(()=>{t.selectionStart=a.start,t.selectionEnd=a.end,t.blur(),t.focus()})}async function Iv(t,e,o={}){let n=o.replace?nt(t,o.replace.start,o.replace.end):So(t),s,r=()=>{if(o.setRange)return o.setRange(n.cloneRange());n.deleteContents(),s=document.createElement("span"),n.insertNode(s),o.insertBRs!==!1?e.split(`
|
|
10
10
|
`).reverse().forEach((i,a)=>{a>0&&n.insertNode(document.createElement("br")),n.insertNode(document.createTextNode(i))}):n.insertNode(document.createTextNode(e))};return Promise.resolve(r()).then(()=>{try{if(o.selectionAfter!==!1){t.focus();let i=o.selectionAfter?nt(t,o.selectionAfter.start,o.selectionAfter.end):(n.collapse(!1),n),a=window.getSelection();a==null||a.removeAllRanges(),a==null||a.addRange(i)}if(!s)return;s.scrollIntoView&&s.scrollIntoView({block:"nearest",inline:"nearest"})}finally{s&&s.remove()}})}function Pv(t){let e=document.createElement("template");return e.innerHTML=t,e.content}function Av(t){let e=document.createDocumentFragment();return t.split(`
|
|
11
11
|
`).reverse().forEach((o,n)=>{n>0&&e.appendChild(document.createElement("br")),e.appendChild(document.createTextNode(o))}),e}function pd(t,e){return!t.contains(e)||e===t?null:e.parentNode===t?e:pd(t,e.parentNode)}async function Lv(t,e,{isBlock:o,isHTML:n}={}){let s;t.dispatchEvent(new InputEvent("beforeinput",{inputType:"insertText",data:e,bubbles:!0,cancelable:!0}));let r=()=>{let i=t.ownerDocument.defaultView??window,a=i.getSelection();if((!a||a.rangeCount===0)&&(t.focus(),a=i.getSelection()),!a||a.rangeCount===0)return;let l=a.getRangeAt(0);if(!l)return;s=document.createElement("span"),l.insertNode(s);let c=n?Pv(e):Av(e);if(o){let p=pd(t,l.startContainer)??t.firstChild;t.insertBefore(c,(p==null?void 0:p.nextSibling)??null)}else l.insertNode(c),l.collapse(!1)};return Promise.resolve(r()).then(()=>{if(t.dispatchEvent(new InputEvent("input",{inputType:"insertText",data:e,bubbles:!0,cancelable:!0})),t.focus(),!!s)try{s.scrollIntoView&&s.scrollIntoView({block:"nearest",inline:"nearest"})}finally{s&&s.remove()}})}function Mv(t){return t.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}async function Nv(t,e,o){await new Ue(t).authenticateWithKey(e,o)}async function Ov(t){let o=await(t.fetch??window.fetch)(t.url),n=await o.blob();return new File([n],t.name,{type:t.mimeType??o.headers.get("Content-Type")??"image/jpeg"})}async function Dv(t,e){let o=await Ov(e),n=new Event("change",{bubbles:!0,cancelable:!0});try{Object.defineProperty(t,"files",{configurable:!0,get:()=>[o]}),t.dispatchEvent(n)}finally{Object.hasOwn(t,"files")&&delete t.files}}export{B as Card,Bt as ContentEditableInput,Ue as DeepdeskAPI,ss as DeepdeskSDK,he as HTTPClient,Ne as InputMediator,je as InputType,ps as KeyboardHint,ds as Label,Io as Locale,ze as Section,gs as SectionList,pe as Sources,D as Suggestion,re as SuggestionList,Oe as TextAreaInput,ut as ToggleButton,Dv as attachFile,Nv as authenticateWithKey,So as createFullRange,xt as createOverlayContainer,nt as createRangeFromOffsets,Qt as escapeHTML,si as fetchPlatformConfig,Mv as formatTextMarkup,Jn as getRangeOffsets,Yn as getRangeText,Lv as insertCKEditor,Yr as isSupportedInputElement,Iv as updateContentEditable,Rv as updateTextArea,y as useStyles,ei as waitForElementVisibilityChange};
|
package/dist/index.iife.js
CHANGED
|
@@ -22,7 +22,7 @@ Try polyfilling it using "@formatjs/intl-pluralrules"
|
|
|
22
22
|
c-17.9,17.9-27.3,40.1-27.3,65.7C163.4,163,163.4,233,163.4,233z M465.5,267.9V477c0,9.4-3.4,17.9-10.2,24.7
|
|
23
23
|
c-6.8,6.8-15.4,10.2-24.7,10.2h-349c-9.4,0-17.9-3.4-24.7-10.2c-6.8-6.8-10.2-15.4-10.2-24.7V267.9c0-9.4,3.4-17.9,10.2-24.7
|
|
24
24
|
c6.8-6.8,15.4-10.2,24.7-10.2h11.9v-70c0-44.4,16.2-82.8,47.8-115.2S212.1,0,256.4,0s82.8,16.2,115.2,47.8
|
|
25
|
-
c32.4,32.4,47.8,70,47.8,115.2v70h11.9c9.4,0,17.9,3.4,24.7,10.2C462.1,250,465.5,257.7,465.5,267.9z`})})});var Oh=S(w()),fA={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},vE=({className:e,color:t})=>(0,Oh.jsx)("svg",{className:e,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:(0,Oh.jsx)("path",{d:"M172.03 0.0199966H0V86.03C47.5 86.03 86 124.54 86 172.04C86 124.54 124.51 86.03 172.01 86.03C219.51 86.03 258.03 124.54 258.03 172.04C258.03 219.54 219.52 258.05 172.01 258.05C124.5 258.05 86 219.54 86 172.04C86 219.54 47.5 258.05 0 258.05V344.06H172.03C267.04 344.06 344.06 267.04 344.06 172.03C344.06 77.02 267.04 0 172.03 0V0.0199966Z",fill:fA[t||"pink"]})});var SE={root:"_root_bgd7a_1",text:"_text_bgd7a_18",icon:"_icon_bgd7a_33",logo:"_logo_bgd7a_38",lock:"_lock_bgd7a_43"};var Nh={};ke(Nh,{enUS:()=>mA,nlNL:()=>gA});var mA={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"}]},gA={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"}]};var So=S(w()),xE=({onLogIn:e})=>{let t=B(Nh),n=N("productName"),r=z(),o=I(pt),i=k("FloatingMenu",SE);if(o===null)return null;let s=()=>{o===!0?r($e(!0)):e()};return(0,So.jsxs)("button",{className:i.root,onClick:s,children:[(0,So.jsx)("div",{className:i.text,children:t(o?"search":"signin",{productName:n})}),(0,So.jsxs)("div",{className:i.icon,children:[(0,So.jsx)(vE,{className:i.logo,color:"pink"}),o===!1&&(0,So.jsx)(yE,{className:i.lock})]})]})};async function Md(e){let n=await new qt(e).get("/platform/config/",{version:null});return te(n)}var _e=S(w());var _E=gE("showTabHint",!0),Va=class e{static version="10.9.3-beta.1";static count=0;deepdeskApi;inputMediator=null;version;broadcastEvents;eventListeners={};unmountHandlers=[];widgetRoot=null;dynamicThunkObject={};isMounted=!1;instanceId;shouldRender=!0;store;constructor({deepdeskUrl:t,brokerUrl:n,version:r=e.version||"unknown",locale:o="en-US",token:i,fetch:s,productName:a,createCustomChannel:l}){let u=t.replace(/\/api$/,"");this.deepdeskApi=new Un(u,{token:i,fetch:s}),this.version=r,this.instanceId=e.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[dE({emit:(p,d,h)=>this.emit(p,d,h),handleAfterSendMessage:p=>this.handleAfterSendMessage(p),handleInputChanged:p=>this.handleInputChanged(p),handleKeyDown:p=>this.handleKeyDown(p),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:p=>this.logSendMessage(p),logSendEditSuggestionMessage:p=>this.logSendEditMessage(p),onUpdateShowTabHint:p=>_E.update(p),sendEvent:(p,d)=>this.deepdeskApi.sendEvent(p,d)})]};n&&Object.assign(c,{deepdeskBrokerAPI:new za(n)}),this.store=cE(c),this.broadcastEvents=new Zb({debug:!0,deepdeskUrl:u,eventMap:Kw(this.store),createCustomChannel:l}),this.store.dispatch(na),this.store.dispatch(ba(_E.value())),this.store.dispatch(na({locale:o,adminUrl:u,productName:a}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){return this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex]??null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(H.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(H.warn("Profile has not been loaded (yet)"),!0):(H.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(Ii(null)),this.store.dispatch(Ln()),new Promise(t=>{let n=this.store.subscribe(()=>{let r=this.store.getState();pt(r)&&Fw(r)!=="loading"&&(n(),t())});this.unmountHandlers.push(()=>{n()})})}async isLoggedIn(){return(await this.store.dispatch(Ln())).payload}async setPlatformAgentId(t){try{if((await this.deepdeskApi.client.get("/apis/admin/session/me/",{version:null})).external_id)return;await this.deepdeskApi.client.request("/apis/admin/session/me/",{method:"PATCH",body:JSON.stringify({external_id:t}),version:null})}catch(n){H.warn("Failed to attach user:",n)}}async isConversationSupported(t,n){return(await this.store.dispatch(Xm({sessionId:t,options:n}))).payload}async createConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(rc(t))).payload}async getConversationBySessionId(t,n){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(await this.store.dispatch(oc({sessionId:t,options:n}))).payload}async upsertConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(Qm(t))).payload}async postMessages(t){return(await this.store.dispatch(sc(t))).payload}async updateConversation(t){return(await this.store.dispatch(ic(t))).payload}resetConversation(){this.store.dispatch(J()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}async getSummary(){let t=await this.store.dispatch(On());if(t.error)throw new Error(t.error.message);return t.payload.summary}configure(t){this.store.dispatch(na(t))}setVisitorInfo(t){this.store.dispatch(nw(t))}async setAgentInfo(t){await this.store.dispatch(va(t))}async setAgentSettings(t){await this.store.dispatch(Mg(t))}async getAgentSettings(){return(await this.store.dispatch(Dg())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let t=[];return this.store.dispatch(ed()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})}notifyInputChanged(t){this.store.dispatch(pc(t))}notifyKeyDown(t){this.store.dispatch(cc(t))}notifyPaste(t,n){this.store.dispatch(o_({text:t,selectionText:n}))}notifyCut(t){this.store.dispatch(n_(t))}notifyExternalSuggestion(t){this.store.dispatch(Bt(t)),this.store.dispatch(_n())}notifyEditSuggestion(t){this.store.dispatch(bw(t.contentType,t.suggestions)),this.store.dispatch(In({contentType:t.contentType,suggestion:typeof t.index=="number"?t.suggestions[t.index]:null}))}handleInputChanged(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui;n&&r&&this.store.dispatch(Er({collapse:!1})),this.inputMediator&&this.store.dispatch(Qx({text:t,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(on([])))}handleKeyDown(t){let{overlayCollapsed:n}=this.state.ui,{textSuggestions:r,selectedSuggestionIndex:o,selection:i}=this.state.input,{inlineSuggestions:s}=this.state.settings,a=r.length>0,l=o!==-1;if(this.store.dispatch(r_(lc(t))),t.key!=="Tab"&&!this.settings.showTextSuggestions)return;let u=()=>{n||!a||i&&(t.shiftKey||(this.store.dispatch(Jx()),s||this.stageSelectedSuggestion({inputType:"arrow"}),t.preventDefault()))},c=()=>{if(n||!a||!i||t.shiftKey)return;this.store.dispatch(t_());let{selectedSuggestionIndex:p}=this.state.input;t.preventDefault(),!s&&(p===-1?this.store.dispatch(oa()):this.stageSelectedSuggestion({inputType:"arrow"}))};switch(t.key){case"Up":case"ArrowUp":s?c():u();return;case"Down":case"ArrowDown":{s?u():c();return}case"Esc":case"Escape":{s&&l&&this.store.dispatch(Sr(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(Sr(-1)),this.store.dispatch(oa()),t.preventDefault()):n||(this.store.dispatch(Er({collapse:!0})),this.store.dispatch(Aw(!0)),t.preventDefault());return}case"Tab":{let{userCommitted:p}=this.state.input,d=p.text.substring(0,p.selection.end),{tabCompletionSuggestion:h}=this.state.input;this.store.dispatch(ba(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!s&&this.settings.showTabCompletion&&h&&h.text.startsWith(d)&&(this.store.dispatch(Bt({text:h.text,suggestion:h,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch(_n())),t.preventDefault();break}default:}}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(i_()),this.store.dispatch(on([]))}handlingTimeStart(){this.state.handlingTime.startTime||(H.info("Start handling time"),this.store.dispatch(tE()))}handlingTimeStop(){this.state.handlingTime.startTime&&(H.info("Stop handling time"),this.store.dispatch(Id()))}logSendMessage(t){let n=Lh("input",this.state,{version:this.version});t&&(Object.assign(n,{text:t}),Object.assign(n,{lenTextTotal:t.length})),this.deepdeskApi.sendEventV1("Send Message",n),this.emit("send-message-event",n)}logSendEditMessage(t){let n=Lh("overlayInput",this.state,{version:this.version});t&&Object.assign(n,{text:t}),this.store.dispatch(Zx(this.state.overlayInput.metrics))}logHandlingTime(){let t=pE(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch(nE())}notifySubmit(t={}){this.shouldAbort()||(this.store.dispatch(_n()),this.store.dispatch(Jr(t.text??this.state.input.text)))}stageSelectedSuggestion(t){let n=this.state.input.selectedSuggestionIndex,{textSuggestions:r}=this.state.input;this.store.dispatch(Bt({text:r[n].text,suggestion:r[n],eventMetrics:t,replace:"until-selection-end"}))}emit(t,n,r={}){let o=()=>{this.eventListeners[t]&&this.eventListeners[t].forEach(i=>{try{i(n)}catch(s){H.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),H.error(s)}})};this.inputMediator&&r.mayApplyChanges?this.inputMediator.applyChanges(o):o()}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]=io(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),this.unmountHandlers.push(()=>{(0,Ot.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]=io(i,{appendTo:document.body});a.dataset.testid=n,a.style.zIndex="2",a.appendChild(r),this.unmountHandlers.push(()=>{(0,Ot.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 oo(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,Ot.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),H.info(`Stored analytics for ${this.conversationId()}`)}catch{}}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()?(H.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(a_(r.metrics))):H.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(t)}catch{}}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!Ad(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:h,inputMediator:v,closestScrollSelector:y,appendOverlayTo:m,inlineSuggestions:g,floatingMenu:f}=n;this.configure({showStyleSuggestions:o,showTabCompletion:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,showTextSuggestions:s,insertLink:h,isEmbedded:p,inlineSuggestions:g,floatingMenu:!!f}),n.automaticHandlingTime&&this.setupHandlingTime(t),oo(t),this.inputMediator=v||(kr(t)?new kn(t):new yo(t)),this.inputMediator.on("change",({plainText:b})=>{this.notifyInputChanged(b)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(s_({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",b=>{this.notifyKeyDown(b)}),this.inputMediator.on("paste",({pastedText:b,selectionText:E})=>{this.notifyPaste(b,E)}),this.inputMediator.on("cut",({selectionText:b})=>{this.notifyCut(b)});let x=y&&fE(t,y)||void 0;if(g){let{customStyles:b,appendOverlayTo:E}=n;if(kr(t))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let C=this.createInlineContainer(t,"deepdesk-caret");(0,Ot.render)((0,_e.jsx)(ho,{store:this.store,customStyles:b,children:(0,_e.jsx)(fo,{broadcastEvents:this.broadcastEvents,children:(0,_e.jsx)(N1,{})})}),C),this.inputMediator.on("caret",P=>{this.store.dispatch(on([])),P?(C.style.display="block",C.style.top=`${P.top}px`,C.style.left=`${P.left}px`):C.style.display="none"});let R=this.overlayContainerFactory("floating-menu",x||t,{appendTo:typeof f=="object"&&"appendOverlayTo"in f?f.appendOverlayTo:E},b==null?void 0:b.floatingMenuRootNode);(0,Ot.render)((0,_e.jsx)(ho,{store:this.store,customStyles:b,children:(0,_e.jsx)(fo,{broadcastEvents:this.broadcastEvents,children:(0,_e.jsx)(xE,{onLogIn:()=>this.loginViaPopup().catch(P=>H.warn(P.message))})})}),R)}else{let b=this.overlayContainerFactory("deepdesk-tab-completion",x||t,{appendTo:m,closestScrollElement:x,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),E=this.overlayContainerFactory("deepdesk-suggestions-overlay",x||t,{appendTo:m},r==null?void 0:r.suggestionsRootNode);(0,Ot.render)((0,_e.jsx)(ho,{store:this.store,customStyles:r,children:(0,_e.jsx)(fo,{broadcastEvents:this.broadcastEvents,children:(0,_e.jsx)(ob,{inputElement:t})})}),b),(0,Ot.render)((0,_e.jsx)(ho,{store:this.store,customStyles:r,children:(0,_e.jsx)(fo,{broadcastEvents:this.broadcastEvents,children:(0,_e.jsx)(z1,{onLogIn:()=>this.loginViaPopup().catch(C=>H.warn(C.message))})})}),E)}(0,Ot.render)((0,_e.jsx)(ho,{store:this.store,customStyles:r,children:(0,_e.jsx)(fo,{broadcastEvents:this.broadcastEvents,children:(0,_e.jsx)(P1,{})})}),this.createContainer("deepdesk-overlays"));let _;this.inputMediator.on("selection",b=>{clearTimeout(_),b===null?_=setTimeout(()=>{b!==null&&this.store.dispatch(Zm(b))},500):this.store.dispatch(Zm(b))}),this.inputMediator.on("disabled",()=>{var b;(b=this.inputMediator)==null||b.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(Ri(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(Ri(!0))),this.store.dispatch(Yx({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.unmountHandlers.push(()=>{this.state.input.text!==""&&(this.store.dispatch(_n()),this.storeMetrics())}),this.whenConversationLoaded(()=>{var b;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((b=this.state.conversation.current)==null?void 0:b.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&&H.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,Ot.render)((0,_e.jsx)(ho,{store:this.store,customStyles:r,children:(0,_e.jsx)(fo,{broadcastEvents:this.broadcastEvents,children:(0,_e.jsx)(Gb,{onLogIn:()=>this.loginViaPopup().catch(s=>H.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,Ot.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(t){let n=Od(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){mE(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(Aa());let t=Ni(this.state);t&&this.store.dispatch(na({showSearch:t.search,showAutoflows:t.autoflows,showCustomMessages:t.customMessages,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:t.summarizer,showKnowledgeSearch:t.knowledgeAssistForAgents,recommendTextSuggestions:t.recommendTextSuggestions}))}),this.loadProfileConfigPromise)}async loginViaPopup(){let t=this.state.settings.adminUrl,n=new URL(t),r=await Md(n.origin);return new Promise((o,i)=>{let s=new MessageChannel,a=s.port1,l=new URL(r.config.platform.hasSso?`${t}/platform/sso/`:`${t}/admin/`);l.searchParams.append("redirect","/sdk/popup/close.html");let u=!1,c=()=>{p&&!p.closed&&p.close(),window.removeEventListener("message",d),clearInterval(h)};a.onmessage=async v=>{var y,m;if((y=v.data)!=null&&y.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((m=v.data)==null?void 0:m.jwt),await this.isLoggedIn(),this.broadcastEvents.send(Ta),c(),u=!0,s.port1.close(),o()}catch(g){i(g)}};let p=window.open(l.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");p===null&&i(new Error("Popup blocked by browser"));let d=async v=>{var y;if(v.origin===l.origin)switch((y=v.data)==null?void 0:y.type){case"deepdesk-popup-loaded":{p==null||p.postMessage({type:"deepdesk-popup-create-channel"},l.origin,[s.port2]);break}case"deepdesk-popup-error":{c(),v.data.message==="Timeout"&&H.warn("Popup timed out. Check if the account's platform url is configured correctly."),i(new Error(v.data.message));break}}};window.addEventListener("message",d);let h=setInterval(()=>{p&&!p.closed||(c(),u||i(new Error("Popup closed by user")))},200);this.unmountHandlers.push(c)})}async checkForTrialMode(t){try{let{account:n}=await this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(H.info("Trial is active"),!await this.deepdeskApi.checkUserExists(t))throw new Error("User is not in trial");this.shouldRender=!0}catch(n){let{message:r}=n;H.info(r),this.shouldRender=!1}}async refreshWidgetSuggestions(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=od(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch(Wt()):this.store.dispatch(Rn(r))})}catch(r){this.handleError(r)}}};async function wE(e,t,n={}){let{value:r}=e,{start:o,end:i}=n.replace??{start:0,end:r.length},s=`${r.slice(0,o)}${t}${r.slice(i)}`,a=n.selectionAfter??{start:o+t.length,end:o+t.length},l=()=>{if(n.setValue)return n.setValue(s);e.value=s};return Promise.resolve(l()).then(()=>{e.selectionStart=a.start,e.selectionEnd=a.end,e.blur(),e.focus()})}async function bE(e,t,n={}){let r=n.replace?Ir(e,n.replace.start,n.replace.end):Bi(e),o,i=()=>{if(n.setRange)return n.setRange(r.cloneRange());r.deleteContents(),o=document.createElement("span"),r.insertNode(o),n.insertBRs!==!1?t.split(`
|
|
25
|
+
c32.4,32.4,47.8,70,47.8,115.2v70h11.9c9.4,0,17.9,3.4,24.7,10.2C462.1,250,465.5,257.7,465.5,267.9z`})})});var Oh=S(w()),fA={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},vE=({className:e,color:t})=>(0,Oh.jsx)("svg",{className:e,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:(0,Oh.jsx)("path",{d:"M172.03 0.0199966H0V86.03C47.5 86.03 86 124.54 86 172.04C86 124.54 124.51 86.03 172.01 86.03C219.51 86.03 258.03 124.54 258.03 172.04C258.03 219.54 219.52 258.05 172.01 258.05C124.5 258.05 86 219.54 86 172.04C86 219.54 47.5 258.05 0 258.05V344.06H172.03C267.04 344.06 344.06 267.04 344.06 172.03C344.06 77.02 267.04 0 172.03 0V0.0199966Z",fill:fA[t||"pink"]})});var SE={root:"_root_bgd7a_1",text:"_text_bgd7a_18",icon:"_icon_bgd7a_33",logo:"_logo_bgd7a_38",lock:"_lock_bgd7a_43"};var Nh={};ke(Nh,{enUS:()=>mA,nlNL:()=>gA});var mA={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"}]},gA={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"}]};var So=S(w()),xE=({onLogIn:e})=>{let t=B(Nh),n=N("productName"),r=z(),o=I(pt),i=k("FloatingMenu",SE);if(o===null)return null;let s=()=>{o===!0?r($e(!0)):e()};return(0,So.jsxs)("button",{className:i.root,onClick:s,children:[(0,So.jsx)("div",{className:i.text,children:t(o?"search":"signin",{productName:n})}),(0,So.jsxs)("div",{className:i.icon,children:[(0,So.jsx)(vE,{className:i.logo,color:"pink"}),o===!1&&(0,So.jsx)(yE,{className:i.lock})]})]})};async function Md(e){let n=await new qt(e).get("/platform/config/",{version:null});return te(n)}var _e=S(w());var _E=gE("showTabHint",!0),Va=class e{static version="10.9.3-beta.2";static count=0;deepdeskApi;inputMediator=null;version;broadcastEvents;eventListeners={};unmountHandlers=[];widgetRoot=null;dynamicThunkObject={};isMounted=!1;instanceId;shouldRender=!0;store;constructor({deepdeskUrl:t,brokerUrl:n,version:r=e.version||"unknown",locale:o="en-US",token:i,fetch:s,productName:a,createCustomChannel:l}){let u=t.replace(/\/api$/,"");this.deepdeskApi=new Un(u,{token:i,fetch:s}),this.version=r,this.instanceId=e.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[dE({emit:(p,d,h)=>this.emit(p,d,h),handleAfterSendMessage:p=>this.handleAfterSendMessage(p),handleInputChanged:p=>this.handleInputChanged(p),handleKeyDown:p=>this.handleKeyDown(p),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:p=>this.logSendMessage(p),logSendEditSuggestionMessage:p=>this.logSendEditMessage(p),onUpdateShowTabHint:p=>_E.update(p),sendEvent:(p,d)=>this.deepdeskApi.sendEvent(p,d)})]};n&&Object.assign(c,{deepdeskBrokerAPI:new za(n)}),this.store=cE(c),this.broadcastEvents=new Zb({debug:!0,deepdeskUrl:u,eventMap:Kw(this.store),createCustomChannel:l}),this.store.dispatch(na),this.store.dispatch(ba(_E.value())),this.store.dispatch(na({locale:o,adminUrl:u,productName:a}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){return this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex]??null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(H.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(H.warn("Profile has not been loaded (yet)"),!0):(H.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(Ii(null)),this.store.dispatch(Ln()),new Promise(t=>{let n=this.store.subscribe(()=>{let r=this.store.getState();pt(r)&&Fw(r)!=="loading"&&(n(),t())});this.unmountHandlers.push(()=>{n()})})}async isLoggedIn(){return(await this.store.dispatch(Ln())).payload}async setPlatformAgentId(t){try{if((await this.deepdeskApi.client.get("/apis/admin/session/me/",{version:null})).external_id)return;await this.deepdeskApi.client.request("/apis/admin/session/me/",{method:"PATCH",body:JSON.stringify({external_id:t}),version:null})}catch(n){H.warn("Failed to attach user:",n)}}async isConversationSupported(t,n){return(await this.store.dispatch(Xm({sessionId:t,options:n}))).payload}async createConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(rc(t))).payload}async getConversationBySessionId(t,n){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(await this.store.dispatch(oc({sessionId:t,options:n}))).payload}async upsertConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(Qm(t))).payload}async postMessages(t){return(await this.store.dispatch(sc(t))).payload}async updateConversation(t){return(await this.store.dispatch(ic(t))).payload}resetConversation(){this.store.dispatch(J()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}async getSummary(){let t=await this.store.dispatch(On());if(t.error)throw new Error(t.error.message);return t.payload.summary}configure(t){this.store.dispatch(na(t))}setVisitorInfo(t){this.store.dispatch(nw(t))}async setAgentInfo(t){await this.store.dispatch(va(t))}async setAgentSettings(t){await this.store.dispatch(Mg(t))}async getAgentSettings(){return(await this.store.dispatch(Dg())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let t=[];return this.store.dispatch(ed()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})}notifyInputChanged(t){this.store.dispatch(pc(t))}notifyKeyDown(t){this.store.dispatch(cc(t))}notifyPaste(t,n){this.store.dispatch(o_({text:t,selectionText:n}))}notifyCut(t){this.store.dispatch(n_(t))}notifyExternalSuggestion(t){this.store.dispatch(Bt(t)),this.store.dispatch(_n())}notifyEditSuggestion(t){this.store.dispatch(bw(t.contentType,t.suggestions)),this.store.dispatch(In({contentType:t.contentType,suggestion:typeof t.index=="number"?t.suggestions[t.index]:null}))}handleInputChanged(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui;n&&r&&this.store.dispatch(Er({collapse:!1})),this.inputMediator&&this.store.dispatch(Qx({text:t,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(on([])))}handleKeyDown(t){let{overlayCollapsed:n}=this.state.ui,{textSuggestions:r,selectedSuggestionIndex:o,selection:i}=this.state.input,{inlineSuggestions:s}=this.state.settings,a=r.length>0,l=o!==-1;if(this.store.dispatch(r_(lc(t))),t.key!=="Tab"&&!this.settings.showTextSuggestions)return;let u=()=>{n||!a||i&&(t.shiftKey||(this.store.dispatch(Jx()),s||this.stageSelectedSuggestion({inputType:"arrow"}),t.preventDefault()))},c=()=>{if(n||!a||!i||t.shiftKey)return;this.store.dispatch(t_());let{selectedSuggestionIndex:p}=this.state.input;t.preventDefault(),!s&&(p===-1?this.store.dispatch(oa()):this.stageSelectedSuggestion({inputType:"arrow"}))};switch(t.key){case"Up":case"ArrowUp":s?c():u();return;case"Down":case"ArrowDown":{s?u():c();return}case"Esc":case"Escape":{s&&l&&this.store.dispatch(Sr(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(Sr(-1)),this.store.dispatch(oa()),t.preventDefault()):n||(this.store.dispatch(Er({collapse:!0})),this.store.dispatch(Aw(!0)),t.preventDefault());return}case"Tab":{let{userCommitted:p}=this.state.input,d=p.text.substring(0,p.selection.end),{tabCompletionSuggestion:h}=this.state.input;this.store.dispatch(ba(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!s&&this.settings.showTabCompletion&&h&&h.text.startsWith(d)&&(this.store.dispatch(Bt({text:h.text,suggestion:h,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch(_n())),t.preventDefault();break}default:}}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(i_()),this.store.dispatch(on([]))}handlingTimeStart(){this.state.handlingTime.startTime||(H.info("Start handling time"),this.store.dispatch(tE()))}handlingTimeStop(){this.state.handlingTime.startTime&&(H.info("Stop handling time"),this.store.dispatch(Id()))}logSendMessage(t){let n=Lh("input",this.state,{version:this.version});t&&(Object.assign(n,{text:t}),Object.assign(n,{lenTextTotal:t.length})),this.deepdeskApi.sendEventV1("Send Message",n),this.emit("send-message-event",n)}logSendEditMessage(t){let n=Lh("overlayInput",this.state,{version:this.version});t&&Object.assign(n,{text:t}),this.store.dispatch(Zx(this.state.overlayInput.metrics))}logHandlingTime(){let t=pE(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch(nE())}notifySubmit(t={}){this.shouldAbort()||(this.store.dispatch(_n()),this.store.dispatch(Jr(t.text??this.state.input.text)))}stageSelectedSuggestion(t){let n=this.state.input.selectedSuggestionIndex,{textSuggestions:r}=this.state.input;this.store.dispatch(Bt({text:r[n].text,suggestion:r[n],eventMetrics:t,replace:"until-selection-end"}))}emit(t,n,r={}){let o=()=>{this.eventListeners[t]&&this.eventListeners[t].forEach(i=>{try{i(n)}catch(s){H.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),H.error(s)}})};this.inputMediator&&r.mayApplyChanges?this.inputMediator.applyChanges(o):o()}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]=io(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),this.unmountHandlers.push(()=>{(0,Ot.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]=io(i,{appendTo:document.body});a.dataset.testid=n,a.style.zIndex="2",a.appendChild(r),this.unmountHandlers.push(()=>{(0,Ot.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 oo(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,Ot.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),H.info(`Stored analytics for ${this.conversationId()}`)}catch{}}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()?(H.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(a_(r.metrics))):H.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(t)}catch{}}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!Ad(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:h,inputMediator:v,closestScrollSelector:y,appendOverlayTo:m,inlineSuggestions:g,floatingMenu:f}=n;this.configure({showStyleSuggestions:o,showTabCompletion:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,showTextSuggestions:s,insertLink:h,isEmbedded:p,inlineSuggestions:g,floatingMenu:!!f}),n.automaticHandlingTime&&this.setupHandlingTime(t),oo(t),this.inputMediator=v||(kr(t)?new kn(t):new yo(t)),this.inputMediator.on("change",({plainText:b})=>{this.notifyInputChanged(b)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(s_({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",b=>{this.notifyKeyDown(b)}),this.inputMediator.on("paste",({pastedText:b,selectionText:E})=>{this.notifyPaste(b,E)}),this.inputMediator.on("cut",({selectionText:b})=>{this.notifyCut(b)});let x=y&&fE(t,y)||void 0;if(g){let{customStyles:b,appendOverlayTo:E}=n;if(kr(t))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let C=this.createInlineContainer(t,"deepdesk-caret");(0,Ot.render)((0,_e.jsx)(ho,{store:this.store,customStyles:b,children:(0,_e.jsx)(fo,{broadcastEvents:this.broadcastEvents,children:(0,_e.jsx)(N1,{})})}),C),this.inputMediator.on("caret",P=>{this.store.dispatch(on([])),P?(C.style.display="block",C.style.top=`${P.top}px`,C.style.left=`${P.left}px`):C.style.display="none"});let R=this.overlayContainerFactory("floating-menu",x||t,{appendTo:typeof f=="object"&&"appendOverlayTo"in f?f.appendOverlayTo:E},b==null?void 0:b.floatingMenuRootNode);(0,Ot.render)((0,_e.jsx)(ho,{store:this.store,customStyles:b,children:(0,_e.jsx)(fo,{broadcastEvents:this.broadcastEvents,children:(0,_e.jsx)(xE,{onLogIn:()=>this.loginViaPopup().catch(P=>H.warn(P.message))})})}),R)}else{let b=this.overlayContainerFactory("deepdesk-tab-completion",x||t,{appendTo:m,closestScrollElement:x,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),E=this.overlayContainerFactory("deepdesk-suggestions-overlay",x||t,{appendTo:m},r==null?void 0:r.suggestionsRootNode);(0,Ot.render)((0,_e.jsx)(ho,{store:this.store,customStyles:r,children:(0,_e.jsx)(fo,{broadcastEvents:this.broadcastEvents,children:(0,_e.jsx)(ob,{inputElement:t})})}),b),(0,Ot.render)((0,_e.jsx)(ho,{store:this.store,customStyles:r,children:(0,_e.jsx)(fo,{broadcastEvents:this.broadcastEvents,children:(0,_e.jsx)(z1,{onLogIn:()=>this.loginViaPopup().catch(C=>H.warn(C.message))})})}),E)}(0,Ot.render)((0,_e.jsx)(ho,{store:this.store,customStyles:r,children:(0,_e.jsx)(fo,{broadcastEvents:this.broadcastEvents,children:(0,_e.jsx)(P1,{})})}),this.createContainer("deepdesk-overlays"));let _;this.inputMediator.on("selection",b=>{clearTimeout(_),b===null?_=setTimeout(()=>{b!==null&&this.store.dispatch(Zm(b))},500):this.store.dispatch(Zm(b))}),this.inputMediator.on("disabled",()=>{var b;(b=this.inputMediator)==null||b.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(Ri(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(Ri(!0))),this.store.dispatch(Yx({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.unmountHandlers.push(()=>{this.state.input.text!==""&&(this.store.dispatch(_n()),this.storeMetrics())}),this.whenConversationLoaded(()=>{var b;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((b=this.state.conversation.current)==null?void 0:b.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&&H.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,Ot.render)((0,_e.jsx)(ho,{store:this.store,customStyles:r,children:(0,_e.jsx)(fo,{broadcastEvents:this.broadcastEvents,children:(0,_e.jsx)(Gb,{onLogIn:()=>this.loginViaPopup().catch(s=>H.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,Ot.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(t){let n=Od(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){mE(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(Aa());let t=Ni(this.state);t&&this.store.dispatch(na({showSearch:t.search,showAutoflows:t.autoflows,showCustomMessages:t.customMessages,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:t.summarizer,showKnowledgeSearch:t.knowledgeAssistForAgents,recommendTextSuggestions:t.recommendTextSuggestions}))}),this.loadProfileConfigPromise)}async loginViaPopup(){let t=this.state.settings.adminUrl,n=new URL(t),r=await Md(n.origin);return new Promise((o,i)=>{let s=new MessageChannel,a=s.port1,l=new URL(r.config.platform.hasSso?`${t}/platform/sso/`:`${t}/admin/`);l.searchParams.append("redirect","/sdk/popup/close.html");let u=!1,c=()=>{p&&!p.closed&&p.close(),window.removeEventListener("message",d),clearInterval(h)};a.onmessage=async v=>{var y,m;if((y=v.data)!=null&&y.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((m=v.data)==null?void 0:m.jwt),await this.isLoggedIn(),this.broadcastEvents.send(Ta),c(),u=!0,s.port1.close(),o()}catch(g){i(g)}};let p=window.open(l.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");p===null&&i(new Error("Popup blocked by browser"));let d=async v=>{var y;if(v.origin===l.origin)switch((y=v.data)==null?void 0:y.type){case"deepdesk-popup-loaded":{p==null||p.postMessage({type:"deepdesk-popup-create-channel"},l.origin,[s.port2]);break}case"deepdesk-popup-error":{c(),v.data.message==="Timeout"&&H.warn("Popup timed out. Check if the account's platform url is configured correctly."),i(new Error(v.data.message));break}}};window.addEventListener("message",d);let h=setInterval(()=>{p&&!p.closed||(c(),u||i(new Error("Popup closed by user")))},200);this.unmountHandlers.push(c)})}async checkForTrialMode(t){try{let{account:n}=await this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(H.info("Trial is active"),!await this.deepdeskApi.checkUserExists(t))throw new Error("User is not in trial");this.shouldRender=!0}catch(n){let{message:r}=n;H.info(r),this.shouldRender=!1}}async refreshWidgetSuggestions(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=od(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch(Wt()):this.store.dispatch(Rn(r))})}catch(r){this.handleError(r)}}};async function wE(e,t,n={}){let{value:r}=e,{start:o,end:i}=n.replace??{start:0,end:r.length},s=`${r.slice(0,o)}${t}${r.slice(i)}`,a=n.selectionAfter??{start:o+t.length,end:o+t.length},l=()=>{if(n.setValue)return n.setValue(s);e.value=s};return Promise.resolve(l()).then(()=>{e.selectionStart=a.start,e.selectionEnd=a.end,e.blur(),e.focus()})}async function bE(e,t,n={}){let r=n.replace?Ir(e,n.replace.start,n.replace.end):Bi(e),o,i=()=>{if(n.setRange)return n.setRange(r.cloneRange());r.deleteContents(),o=document.createElement("span"),r.insertNode(o),n.insertBRs!==!1?t.split(`
|
|
26
26
|
`).reverse().forEach((s,a)=>{a>0&&r.insertNode(document.createElement("br")),r.insertNode(document.createTextNode(s))}):r.insertNode(document.createTextNode(t))};return Promise.resolve(i()).then(()=>{try{if(n.selectionAfter!==!1){e.focus();let s=n.selectionAfter?Ir(e,n.selectionAfter.start,n.selectionAfter.end):(r.collapse(!1),r),a=window.getSelection();a==null||a.removeAllRanges(),a==null||a.addRange(s)}if(!o)return;o.scrollIntoView&&o.scrollIntoView({block:"nearest",inline:"nearest"})}finally{o&&o.remove()}})}function hA(e){let t=document.createElement("template");return t.innerHTML=e,t.content}function yA(e){let t=document.createDocumentFragment();return e.split(`
|
|
27
27
|
`).reverse().forEach((n,r)=>{r>0&&t.appendChild(document.createElement("br")),t.appendChild(document.createTextNode(n))}),t}function EE(e,t){return!e.contains(t)||t===e?null:t.parentNode===e?t:EE(e,t.parentNode)}async function CE(e,t,{isBlock:n,isHTML:r}={}){let o;e.dispatchEvent(new InputEvent("beforeinput",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0}));let i=()=>{let s=e.ownerDocument.defaultView??window,a=s.getSelection();if((!a||a.rangeCount===0)&&(e.focus(),a=s.getSelection()),!a||a.rangeCount===0)return;let l=a.getRangeAt(0);if(!l)return;o=document.createElement("span"),l.insertNode(o);let u=r?hA(t):yA(t);if(n){let c=EE(e,l.startContainer)??e.firstChild;e.insertBefore(u,(c==null?void 0:c.nextSibling)??null)}else l.insertNode(u),l.collapse(!1)};return Promise.resolve(i()).then(()=>{if(e.dispatchEvent(new InputEvent("input",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0})),e.focus(),!!o)try{o.scrollIntoView&&o.scrollIntoView({block:"nearest",inline:"nearest"})}finally{o&&o.remove()}})}function TE(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}async function kE(e,t,n){await new Un(e).authenticateWithKey(t,n)}async function vA(e){let n=await(e.fetch??window.fetch)(e.url),r=await n.blob();return new File([r],e.name,{type:e.mimeType??n.headers.get("Content-Type")??"image/jpeg"})}async function PE(e,t){let n=await vA(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 ME(SA);})();
|
|
28
28
|
/*! Bundled license information:
|