@deepdesk/deepdesk-sdk 14.3.1-beta.8 → 14.3.1-beta.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs.js +1 -1
- package/dist/index.esm.js +1 -1
- package/dist/index.iife.js +1 -1
- package/package.json +1 -1
package/dist/index.iife.js
CHANGED
|
@@ -24,7 +24,7 @@ Try polyfilling it using "@formatjs/intl-pluralrules"
|
|
|
24
24
|
`+yt),xn&&Cf([B,V,fe],vt=>{yt=Il(yt,vt," ")}),S&&Kl?S.createHTML(yt):yt},t.setConfig=function(){let j=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Kf(j),jn=!0},t.clearConfig=function(){di=null,jn=!1},t.isValidAttribute=function(j,b,L){di||Kf({});let H=Fe(j),Q=Fe(b);return iv(H,Q,L)},t.addHook=function(j,b){typeof b=="function"&&(q[j]=q[j]||[],Al(q[j],b))},t.removeHook=function(j){if(q[j])return eC(q[j])},t.removeHooks=function(j){q[j]&&(q[j]=[])},t.removeAllHooks=function(){q={}},t}var pC=fC();var gr=x(F());var g_={"":["<em>","</em>"],_:["<strong>","</strong>"],"*":["<strong>","</strong>"],"~":["<s>","</s>"],"\n":["<br />"]," ":["<br />"],"-":["<hr />"]};function mC(e){return e.replace(RegExp("^"+(e.match(/^(\t| )+/)||"")[0],"gm"),"")}function Nl(e){return(e+"").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function _l(e,t){var n,r,o,i,s,a=/((?:^|\n+)(?:\n---+|\* \*(?: \*)+)\n)|(?:^``` *(\w*)\n([\s\S]*?)\n```$)|((?:(?:^|\n+)(?:\t| {2,}).+)+\n*)|((?:(?:^|\n)([>*+-]|\d+\.)\s+.*)+)|(?:!\[([^\]]*?)\]\(([^)]+?)\))|(\[)|(\](?:\(([^)]+?)\))?)|(?:(?:^|\n+)([^\s].*)\n(-{3,}|={3,})(?:\n+|$))|(?:(?:^|\n+)(#{1,6})\s*(.+)(?:\n+|$))|(?:`([^`].*?)`)|( \n\n*|\n{2,}|__|\*\*|[_*]|~~)/gm,l=[],u="",c=t||{},f=0;function d(y){var v=g_[y[1]||""],p=l[l.length-1]==y;return v?v[1]?(p?l.pop():l.push(y),v[0|p]):v[0]:y}function m(){for(var y="";l.length;)y+=d(l[l.length-1]);return y}for(e=e.replace(/^\[(.+?)\]:\s*(.+)$/gm,function(y,v,p){return c[v.toLowerCase()]=p,""}).replace(/^\n+|\n+$/g,"");o=a.exec(e);)r=e.substring(f,o.index),f=a.lastIndex,n=o[0],r.match(/[^\\](\\\\)*\\$/)||((s=o[3]||o[4])?n='<pre class="code '+(o[4]?"poetry":o[2].toLowerCase())+'"><code'+(o[2]?' class="language-'+o[2].toLowerCase()+'"':"")+">"+mC(Nl(s).replace(/^\n+|\n+$/g,""))+"</code></pre>":(s=o[6])?(s.match(/\./)&&(o[5]=o[5].replace(/^\d+/gm,"")),i=_l(mC(o[5].replace(/^\s*[>*+.-]/gm,""))),s==">"?s="blockquote":(s=s.match(/\./)?"ol":"ul",i=i.replace(/^(.*)(\n|$)/gm,"<li>$1</li>")),n="<"+s+">"+i+"</"+s+">"):o[8]?n='<img src="'+Nl(o[8])+'" alt="'+Nl(o[7])+'">':o[10]?(u=u.replace("<a>",'<a href="'+Nl(o[11]||c[r.toLowerCase()])+'">'),n=m()+"</a>"):o[9]?n="<a>":o[12]||o[14]?n="<"+(s="h"+(o[14]?o[14].length:o[13]>"="?1:2))+">"+_l(o[12]||o[15],c)+"</"+s+">":o[16]?n="<code>"+Nl(o[16])+"</code>":(o[17]||o[1])&&(n=d(o[17]||"--"))),u+=r,u+=n;return(u+e.substring(f)+m()).replace(/^\n+|\n+$/g,"")}var gC={root:"dd-L7b3z",popover:"dd-OQOTB",options:"dd-Y12RE",arrow:"dd-cv33T",copyIcon:"dd-6xOsH",option:"dd-9oFX4",divider:"dd-aiZf8",fadeup:"dd-Jq9pd"};var yn=x(T());function h_(e){return`<button type="button" data-copy-icon class=${e}><svg version="1.1" x="0px" y="0px" viewBox="0 0 115.77 122.88" width="10px" height="10px" fill="black"><g><path d="M89.62,13.96v7.73h12.19h0.01v0.02c3.85,0.01,7.34,1.57,9.86,4.1c2.5,2.51,4.06,5.98,4.07,9.82h0.02v0.02 v73.27v0.01h-0.02c-0.01,3.84-1.57,7.33-4.1,9.86c-2.51,2.5-5.98,4.06-9.82,4.07v0.02h-0.02h-61.7H40.1v-0.02 c-3.84-0.01-7.34-1.57-9.86-4.1c-2.5-2.51-4.06-5.98-4.07-9.82h-0.02v-0.02V92.51H13.96h-0.01v-0.02c-3.84-0.01-7.34-1.57-9.86-4.1 c-2.5-2.51-4.06-5.98-4.07-9.82H0v-0.02V13.96v-0.01h0.02c0.01-3.85,1.58-7.34,4.1-9.86c2.51-2.5,5.98-4.06,9.82-4.07V0h0.02h61.7 h0.01v0.02c3.85,0.01,7.34,1.57,9.86,4.1c2.5,2.51,4.06,5.98,4.07,9.82h0.02V13.96L89.62,13.96z M79.04,21.69v-7.73v-0.02h0.02 c0-0.91-0.39-1.75-1.01-2.37c-0.61-0.61-1.46-1-2.37-1v0.02h-0.01h-61.7h-0.02v-0.02c-0.91,0-1.75,0.39-2.37,1.01 c-0.61,0.61-1,1.46-1,2.37h0.02v0.01v64.59v0.02h-0.02c0,0.91,0.39,1.75,1.01,2.37c0.61,0.61,1.46,1,2.37,1v-0.02h0.01h12.19V35.65 v-0.01h0.02c0.01-3.85,1.58-7.34,4.1-9.86c2.51-2.5,5.98-4.06,9.82-4.07v-0.02h0.02H79.04L79.04,21.69z M105.18,108.92V35.65v-0.02 h0.02c0-0.91-0.39-1.75-1.01-2.37c-0.61-0.61-1.46-1-2.37-1v0.02h-0.01h-61.7h-0.02v-0.02c-0.91,0-1.75,0.39-2.37,1.01 c-0.61,0.61-1,1.46-1,2.37h0.02v0.01v73.27v0.02h-0.02c0,0.91,0.39,1.75,1.01,2.37c0.61,0.61,1.46,1,2.37,1v-0.02h0.01h61.7h0.02 v0.02c0.91,0,1.75-0.39,2.37-1.01c0.61-0.61,1-1.46,1-2.37h-0.02V108.92L105.18,108.92z"/></g></svg></button>`}function Cy(e){var n;let t=e.cloneNode(!0);return t.querySelectorAll("div,button").forEach(r=>r.remove()),(n=t.textContent)!=null?n:""}function y_(e){return e.replace(/\r\n/g,`
|
|
25
25
|
`)}var v_=({content:e,useLabel:t,copyLabel:n,onCopy:r,onUse:o})=>{let i=A("Markdown",gC),s=(0,gr.useRef)(null),[a,l]=(0,gr.useState)(null),u=(0,gr.useMemo)(()=>{let v=_l(y_(e));return pC.sanitize(v).replaceAll("</code>",`${h_(i.copyIcon)}</code>`).replaceAll('<a href="','<a target="_blank" rel="noreferrer noopener" href="')},[e]),c=v=>{var h;let p=v.target,g=!!((h=s.current)!=null&&h.querySelector("code"));if(["A","BUTTON"].includes(p.tagName)){l(null);return}a||g&&p.tagName!=="CODE"||!g&&p!==s.current||(p.addEventListener("mouseleave",()=>l(null),{once:!0}),l(p))},f=()=>{if(!a)return;l(null);let v=a.querySelector("button");v&&(hs(v,i.fadeup),r(Cy(a)))},d=v=>{let p=v.target;if(p.tagName==="A"){v.stopPropagation();return}"copyIcon"in p.dataset&&(hs(p,i.fadeup),r(Cy(p.parentElement)))},m=()=>{!a||!o||(l(null),o(Cy(a)))},y=v=>{if(v===null)return;let p=v.getBoundingClientRect();p.left<0?v.style.transform=`translateX(${-p.left+2}px)`:p.right>window.innerWidth&&(v.style.transform=`translateX(${window.innerWidth-p.right-2}px)`)};return(0,yn.jsxs)(gr.Fragment,{children:[a&&(0,yn.jsxs)(Ts,{triggerRef:{current:a},className:i.popover,parentNode:a,children:[(0,yn.jsxs)("div",{className:i.options,ref:y,children:[(0,yn.jsx)("button",{type:"button",className:i.option,onClick:f,children:n}),o&&(0,yn.jsxs)(gr.Fragment,{children:[(0,yn.jsx)("div",{className:i.divider}),(0,yn.jsx)("button",{type:"button",className:i.option,onClick:m,children:t})]})]}),(0,yn.jsx)("div",{className:i.arrow})]}),(0,yn.jsx)("div",{ref:s,"data-testid":"widget-markdown-content",className:i.root,dangerouslySetInnerHTML:{__html:u},onMouseOver:c,onClick:d})]})},Lf=v_;var ky={};at(ky,{enUS:()=>S_,nlNL:()=>x_});var S_={useCue:[{type:0,value:"Add to message"}],__summarizerAssistant__:[{type:0,value:"Summary"}],copyCue:[{type:0,value:"Copy"}],removeCue:[{type:0,value:"Close"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}]},x_={useCue:[{type:0,value:"Voeg toe aan bericht"}],__summarizerAssistant__:[{type:0,value:"Samenvatting"}],copyCue:[{type:0,value:"Kopi\xEBren"}],removeCue:[{type:0,value:"Sluiten"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}]};var hC={title:"dd-YBHrC",fadeup:"dd-cRM0K",fadedown:"dd-7D4Pq",selected:"dd-bueui",actions:"dd-9Iqn9",thumbsUp:"dd-6QwVx",thumbsDown:"dd-d3E8l",form:"dd-sPNU2",formInput:"dd-F3E4I",formSubmit:"dd-vw5S0",actionButton:"dd-cCWyJ",inputSpace:"dd-DGYB1"};var en=x(T()),w_=({cue:e,onCallToAction:t,onRemove:n,onCopy:r,onUse:o})=>{let i=A("WidgetCue",hC),s=Y(ky),a=Xr(),l=U("hasKeyboardInput"),u=()=>{t&&t(e),n(e)},c=m=>{r&&r(m,e)},f=m=>{o&&o(m,e)},d=m=>{m.preventDefault(),m.stopPropagation(),n(e)};return(0,yC.useEffect)(()=>{a("Assistant response displayed",{name:e.rule.name,description:e.rule.description,group:e.rule.label,cueText:e.text})},[]),(0,en.jsxs)(ue,{"data-testid":"cue",children:[(0,en.jsx)(ye,{children:(0,en.jsxs)(ye.Content,{children:[e.title&&(0,en.jsx)(ye.Title,{className:i.title,"data-testid":"widget-cue-title",children:e.rule.label.startsWith("__")?s(e.rule.label):e.title}),(0,en.jsx)(Lf,{content:e.text,useLabel:s("useCue"),copyLabel:s("copyCue"),onCopy:c,onUse:l?f:void 0})]})}),(0,en.jsxs)(ue.ButtonsContainer,{children:[(0,en.jsxs)("div",{className:i.actions,children:[e.callToAction&&(0,en.jsx)(ue.Button,{onClick:u,children:e.callToAction.label}),(0,en.jsx)(ue.Button,{onClick:d,children:s("removeCue")})]}),(0,en.jsx)(vs,{eventName:"Assistant response feedback",eventData:{name:e.rule.name,group:e.rule.label,description:e.rule.description,cueText:e.text},feedbackText:e.text,feedbackType:"assistant"})]})]})},vC=w_;var Cs=x(T()),b_=({cues:e})=>{let t=J(),n=kt(),r=Xr(),o=l=>{t(BT({id:l.rule.id})),t(zb({code:l.rule.label})),r("Assistant response closed",{name:l.rule.name,group:l.rule.label,description:l.rule.description,cueText:l.text})},i=(l,u)=>{Nn(l),r("Assistant response copied",{name:u.rule.name,group:u.rule.label,description:u.rule.description,copiedText:l})},s=l=>{l.callToAction&&(t(_d(l)),r("Assistant call to action",{name:l.rule.name,group:l.rule.label,description:l.rule.description,eventName:l.callToAction.event,value:l.callToAction.value}))},a=(l,u)=>{n.send(In,{text:l,suggestion:{source:"cue",sourceText:l}}),r("Assistant response used",{name:u.rule.name,group:u.rule.label,description:u.rule.description,usedText:l})};return(0,Cs.jsx)(Cs.Fragment,{children:e.map(l=>l.isLoading?(0,Cs.jsx)(Tf,{title:l.title},l.rule.id):(0,Cs.jsx)(vC,{cue:l,onCallToAction:s,onRemove:o,onCopy:i,onUse:a},l.rule.id))})},SC=b_;var Af=x(F());var xC={root:"dd-cvTAY",label:"dd-QWQxD",value:"dd-WSUHF",copyButton:"dd-67o9H",copyButtonText:"dd-oos-l",isTrue:"dd--1g2O",isFalse:"dd-sz2ir"};var vn=x(T());function E_(e,t){return t.split(".").reduce((n,r)=>!n||typeof n!="object"||!(r in n)?null:n[r],e)}var wC=({data:e,schema:t})=>{let n=A("WidgetCustomData",xC),r=o=>{Nn(o)};return(0,Af.useEffect)(()=>{z.info("Custom data",e,t)},[e]),(0,vn.jsx)("dl",{className:n.root,children:t.map(o=>{let i=E_(e,o.path);return(0,vn.jsxs)(Af.Fragment,{children:[(0,vn.jsx)("dt",{className:n.label,children:o.label}),(0,vn.jsx)("dd",{className:n.value,children:o.type==="boolean"&&i?(0,vn.jsx)("span",{className:n.isTrue,children:o.trueValue}):o.type==="boolean"&&!i?(0,vn.jsx)("span",{className:n.isFalse,children:o.falseValue}):i?(0,vn.jsxs)("button",{type:"button",onClick:()=>r(i),className:n.copyButton,children:[(0,vn.jsx)("span",{className:n.copyButtonText,children:i}),(0,vn.jsx)(Ll,{})]}):"-"})]},o.label)})})};var Pt=x(F());var Ry=x(T()),bC=()=>(0,Ry.jsx)("svg",{focusable:"false","aria-hidden":"true",viewBox:"0 0 24 24","data-testid":"ReplayIcon",children:(0,Ry.jsx)("path",{d:"M12 5V1L7 6l5 5V7c3.31 0 6 2.69 6 6s-2.69 6-6 6-6-2.69-6-6H4c0 4.42 3.58 8 8 8s8-3.58 8-8-3.58-8-8-8"})});var ks={};at(ks,{enUS:()=>T_,nlNL:()=>C_});var T_={titleKnowledgeAssistant:[{type:0,value:"Knowledge Assistant"}],inputPlaceholder:[{type:0,value:"What is your question?"}],useCue:[{type:0,value:"Add to message"}],copyCue:[{type:0,value:"Copy"}],removeCue:[{type:0,value:"Close"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}],submitLabel:[{type:0,value:"Submit"}],resetLabel:[{type:0,value:"Reset"}],showMore:[{type:0,value:"Show "},{type:1,value:"amount"},{type:0,value:" more"}]},C_={titleKnowledgeAssistant:[{type:0,value:"Knowledge Assistant"}],inputPlaceholder:[{type:0,value:"Wat is je vraag?"}],useCue:[{type:0,value:"Voeg toe aan bericht"}],copyCue:[{type:0,value:"Kopi\xEBren"}],removeCue:[{type:0,value:"Sluiten"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}],submitLabel:[{type:0,value:"Verzend"}],resetLabel:[{type:0,value:"Reset"}],showMore:[{type:0,value:"Toon "},{type:1,value:"amount"},{type:0,value:" meer"}]};var Py={form:"dd-pleCH",formInput:"dd-pGJMY",formSubmit:"dd--gkRg",actionButton:"dd-I2NEH",sources:"dd-xf9c6",source:"dd-a-vyX",link:"dd-PyUPS",linkContent:"dd-gARDA",showMoreSources:"dd-uDGi-"};var ge=x(T()),k_=3,R_=({sources:e,onClick:t})=>{let n=Y(ks),r=A("WidgetKnowledgeAssistant",Py),[o,i]=(0,Pt.useState)(!1),s=o?e:e.slice(0,k_);return s.length===0?null:(0,ge.jsxs)("ul",{className:r.sources,children:[s.map(a=>(0,ge.jsx)("li",{className:r.source,"data-testid":"knowledge-assist-source",children:(0,ge.jsx)("a",{className:r.link,rel:"noreferrer",target:"_blank",href:a.url,onClick:l=>{l.stopPropagation(),t(a)},"data-tooltip":a.url?decodeURIComponent(a.url):void 0,children:(0,ge.jsx)("span",{className:r.linkContent,children:a.name})})},a.name)),s<e&&(0,ge.jsx)("button",{type:"button",className:r.showMoreSources,onClick:()=>i(!0),children:n("showMore",{amount:e.length-s.length})})]})},P_=({innerRef:e,item:t,index:n,hasKeyboardInput:r,onCopy:o,onUse:i,onSourceClick:s})=>{var l;let a=Y(ks);return(0,ge.jsxs)(ue,{"data-testid":"knowledge-assist-answer",ref:e,children:[(0,ge.jsx)(ye,{children:(0,ge.jsxs)(ye.Content,{children:[(0,ge.jsx)(ye.Title,{children:t.question}),(0,ge.jsx)(Lf,{content:t.answer.answer,useLabel:a("useCue"),copyLabel:a("copyCue"),onCopy:o,onUse:r?i:void 0}),(0,ge.jsx)(R_,{sources:(l=t.answer.sources)!=null?l:[],onClick:u=>s(u,t.question)})]})}),(0,ge.jsxs)(ue.ButtonsContainer,{children:[(0,ge.jsx)("div",{}),(0,ge.jsx)(vs,{eventName:"knowledge assist feedback",eventData:{question:t.question,isFollowUpQuestion:n>0,isAgent:!0,answer:t.answer.answer},feedbackText:t.answer.answer,feedbackType:"assistant"})]})]})},Ly=(0,Pt.createContext)(null),EC=({children:e})=>{let[t,n]=(0,Pt.useState)(null),r=M(cl("knowledge-assist")),[o,i]=(0,Pt.useState)(!1),[s,a]=(0,Pt.useState)(null),l=J(),u=zo(d=>sl({input:d,threadId:t,onNewThreadId(m){n(m)}})),c={isEnabled:r,isSubmitting:o,threadId:t,pendingInput:s,onSubmit(d){return R(this,null,function*(){i(!0),a(d),yield u.call(d),i(!1),a(null)})},onReset(){t&&l(cs(t))}};return(0,ge.jsx)(Ly.Provider,{value:c,children:e})},TC=()=>{let e=Y(ks),t=A("WidgetKnowledgeAssistant",Py),n=(0,Pt.useContext)(Ly),r=(0,Pt.useRef)(null),[o,i]=(0,Pt.useState)(""),s=u=>{i(u.target.value)},a=u=>{u.preventDefault(),n.onSubmit(o).then(()=>{var c;r.current&&((c=r.current)==null||c.focus(),i(""))})},l=u=>{u.preventDefault(),n.onReset()};return n.isEnabled?(0,ge.jsxs)("form",{className:t.form,onSubmit:a,children:[(0,ge.jsx)("input",{ref:r,className:t.formInput,placeholder:e("inputPlaceholder"),type:"text",disabled:n.isSubmitting,value:o,onChange:s}),(0,ge.jsx)("button",{type:"submit",disabled:n.isSubmitting||o==="",className:t.formSubmit,children:e("submitLabel")}),(0,ge.jsx)("button",{type:"button",title:e("resetLabel"),disabled:n.threadId===null||n.isSubmitting,onClick:l,className:t.actionButton,children:(0,ge.jsx)(bC,{})})]}):null},CC=()=>{var c,f;let e=Y(ks),t=Xr(),n=(0,Pt.useRef)(null),r=(0,Pt.useContext)(Ly),o=(f=M(il((c=r.threadId)!=null?c:-1)))!=null?f:[],i=U("hasKeyboardInput"),s=kt(),a=d=>{Nn(d),t("Assistant response copied",{name:"Knowledge Assistant",group:"knowlegde-assist",description:"",copiedText:d})},l=(d,m)=>{t("knowledge assist source viewed",{question:m,sourceViewed:d.url||d.name})},u=d=>{s.send(In,{text:d,suggestion:{source:"cue",sourceText:d}}),t("Assistant response used",{name:"Knowledge Assistant",group:"knowlegde-assist",description:"",usedText:d})};return!r.isEnabled||(o==null?void 0:o.length)===0&&!r.isSubmitting?null:(0,ge.jsx)(wn,{type:"knowledge",title:e("titleKnowledgeAssistant"),"data-testid":"knowledge",children:(0,ge.jsxs)(wt,{withDivider:!0,children:[o.map((d,m)=>(0,ge.jsx)(P_,{innerRef:m===o.length-1?n:void 0,item:d,index:m,hasKeyboardInput:i,onCopy:a,onUse:u,onSourceClick:l},`${d.question}_${d.answer}_${m}`)),r.pendingInput&&(0,ge.jsx)(Tf,{title:r.pendingInput})]})})};var RC=x(F());var A_=/(https?:\/\/[^\s]+)/,kC=e=>e.split(" ").find(t=>A_.test(t));var tn=x(T()),I_=({suggestion:e,lines:t,onUse:n})=>{var f;let r=e.text||e.url||e.message,o=kC(r),i=Y(wl),s=U("showImages"),a=U("fallbackImage"),l=U("hasKeyboardInput"),u=d=>{d.preventDefault(),d.stopPropagation(),l&&n(r)},c=(0,RC.useCallback)(d=>{window.open(o,"_blank"),d.stopPropagation(),d.preventDefault()},[o]);return(0,tn.jsxs)(ue,{onClick:l?u:void 0,"data-testid":"edit-suggestion",children:[(0,tn.jsxs)(ye,{children:[s&&e.image&&(0,tn.jsx)(ye.Image,{src:vf(e,"small",a||void 0),title:e.title}),(0,tn.jsxs)(ye.Content,{children:[e.title&&(0,tn.jsx)(ye.Title,{"data-testid":"widget-suggestion-title",children:e.title}),e.searchKeywords&&((f=e.searchKeywords)==null?void 0:f.length)>0&&(0,tn.jsx)(ue.Labels,{labels:e.searchKeywords}),(0,tn.jsx)(ye.Content,{cropText:t==="single",lineClamp:t==="multiple",children:r})]})]}),(0,tn.jsxs)(ue.Actions,{children:[o&&(0,tn.jsx)(ue.ActionButton,{onClick:c,label:i("visitUrl")}),l&&(0,tn.jsx)(ue.ActionButton,{primary:!0,onClick:u,label:i("useSuggestion")})]})]})},PC=I_;var Ml=x(T()),O_=({lines:e,suggestions:t})=>{let n=kt(),r=(o,i)=>{n.send(In,{text:o,suggestion:I(k({},i),{source:i.source,sourceText:i.text})})};return(0,Ml.jsx)(Ml.Fragment,{children:t.map(o=>(0,Ml.jsx)(PC,{suggestion:o,lines:e,onUse:i=>r(i,o)},o.text||o.url||o.message))})},LC=O_;var Dl={};at(Dl,{enUS:()=>N_,nlNL:()=>__});var N_={waiting:[{type:0,value:"Loading\u2026"}],notSupported:[{type:0,value:"This conversation is not supported"}],noResults:[{type:0,value:"No results found\u2026"}],titleCues:[{type:0,value:"Assistant updates"}],actions:[{type:0,value:"Shortcuts"}],linkStudioLogin:[{type:0,value:"My "},{type:1,value:"productName"}],linkSummary:[{type:0,value:"Summarize"}],linkKnowledgeSearch:[{type:0,value:"Knowledge Assist"}],linkSearch:[{type:0,value:"Search"}]},__={waiting:[{type:0,value:"Laden\u2026"}],notSupported:[{type:0,value:"Dit gesprek wordt niet ondersteund"}],noResults:[{type:0,value:"Geen resultaten gevonden\u2026"}],titleCues:[{type:0,value:"Assistant updates"}],actions:[{type:0,value:"Shortcuts"}],linkStudioLogin:[{type:0,value:"Mijn "},{type:1,value:"productName"}],linkSummary:[{type:0,value:"Gesprek samenvatten"}],linkKnowledgeSearch:[{type:0,value:"Knowledge assist"}],linkSearch:[{type:0,value:"Zoeken"}]};var Zo={root:"dd-W9VCG",loginText:"dd--dS6t",stateText:"dd-348OC",sectionList:"dd-bF9pF",footer:"dd-tvofr",shortcutList:"dd-MuKK-",shortcut:"dd-5CnK9",footerShortcut:"dd-dH7XJ",link:"dd-DRo0x"};var K=x(T()),OC=(e,t)=>{let n=M(ct);(0,Rs.useEffect)(()=>n?t.every(r=>!!r)?e():()=>{}:()=>{},[...t,n])},M_=({onLogIn:e})=>{let t=A("Widget",Zo),n=U("isEmbedded"),r=U("adminUrl");return(0,K.jsx)("div",{className:t.loginText,children:(0,K.jsx)("div",{children:(0,K.jsx)(of,{isEmbedded:n,loginUrl:r,onLogIn:e})})},"login")},AC=({text:e})=>{let t=A("Widget",Zo);return(0,K.jsx)("div",{className:t.stateText,children:(0,K.jsx)("div",{children:(0,K.jsx)("p",{children:e})})},"notification")},D_=()=>{let e=Y(Dl),t=A("Widget",Zo),n=zo(()=>On({})),r=U("showSummaryCommand"),o=M(cl("knowledge-assist"));return(0,K.jsx)(K.Fragment,{children:r&&o&&(0,K.jsx)("button",{type:"button",disabled:n.state==="loading",className:t.footerShortcut,onClick:()=>n.call(),children:e("linkSummary")})})},F_=()=>{let e=Y(Dl),t=J(),n=A("Widget",Zo),r=U("showSearch"),o=U("showSummaryCommand"),i=U("showKnowledgeSearch"),s=M(cl("knowledge-assist")),a=U("isEmbedded"),l=M(ys("/admin/")),u=kt(),c=U("productName"),f=U("hasKeyboardInput"),d=zo(()=>On({})),m=r||o||i||l;return OC(()=>{if(a)return t(dy()),()=>{t(FT())}},[t,a]),!m||!f?null:(0,K.jsx)(wn,{title:e("actions"),type:"shortcuts",children:(0,K.jsxs)("div",{className:n.shortcutList,children:[r&&(0,K.jsxs)("button",{type:"button",className:n.shortcut,"data-testid":"shortcut-search","aria-label":e("linkSearch"),onClick:()=>u.send("ShowCommandPalette",{isOpen:!0}),children:[(0,K.jsx)(ps,{}),e("linkSearch")]}),o&&!s&&(0,K.jsxs)("button",{type:"button",className:n.shortcut,"data-testid":"shortcut-summary","aria-label":e("linkSummary"),disabled:d.state==="loading",onClick:()=>d.call(),children:[(0,K.jsx)(YT,{}),e("linkSummary")]}),i&&!s&&(0,K.jsxs)("button",{type:"button",className:n.shortcut,"data-testid":"shortcut-knowledge-assist","aria-label":e("linkKnowledgeSearch"),onClick:()=>u.send("ShowCommandPalette",{isOpen:!0,page:"knowledgeAssist"}),children:[(0,K.jsx)(GT,{}),e("linkKnowledgeSearch")]}),l&&(0,K.jsxs)("a",{className:n.shortcut,target:"_blank",href:l,"data-testid":"shortcut-studio-login","aria-label":e("linkStudioLogin",{productName:c}),rel:"noreferrer",children:[(0,K.jsx)(qT,{}),e("linkStudioLogin",{productName:c})]})]})})},H_=()=>{let e=J(),t=M(ul),n=M(Wb),r=M(WT),o=M(eb),i=M($d),s=M(Qd),a=M(No),l=M(An);return(0,Rs.useEffect)(()=>{!!o&&!n&&z.warn("Custom data provided, but no schema.")},[o,n]),OC(()=>{t.forEach(({type:u})=>{u==="entities"?e(mn()):lu.includes(u)||e(gn(u))})},[e,l,a]),(0,Rs.useEffect)(()=>{r.length>0&&!t.some(u=>u.type==="cues")&&z.warn("Received cues, but cues are not configured in widget.")},[t,r]),(0,K.jsx)(Rs.Fragment,{children:t.map(({type:u,title:c,amount:f,lines:d,schema:m})=>{var y,v;switch(u){case"entities":return i&&i.length>0&&(0,K.jsx)(wn,{type:u,title:c,"data-testid":`type-${u}`,children:(0,K.jsx)($T,{entities:i})},u);case"cues":return r&&r.length>0&&(0,K.jsx)(wn,{type:u,title:c,"data-testid":`type-${u}`,children:(0,K.jsx)(wt,{withDivider:!0,children:(0,K.jsx)(SC,{cues:r})})},u);case"custom-data":return o&&m&&(0,K.jsx)(wn,{type:u,title:c,"data-testid":`type-${u}`,children:(0,K.jsx)(wt,{withDivider:!0,children:(0,K.jsx)(wC,{data:o,schema:m})})},u);default:return((v=(y=s[u])==null?void 0:y.suggestions)==null?void 0:v.length)>0&&(0,K.jsx)(wn,{type:u,title:c,"data-testid":`type-${u}`,children:(0,K.jsx)(wt,{withDivider:!0,children:(0,K.jsx)(LC,{lines:d,contentType:u,suggestions:s[u].suggestions.slice(0,f)||[]})})},u)}})})},U_=({children:e})=>{let t=A("Widget",Zo);return(0,K.jsx)("div",{className:t.footer,children:e})},z_=({onLogIn:e})=>{let t=Y(Dl),n=A("Widget",Zo),r=M(is),o=M(ct),i=M(H1),s=M(No);return r===!1?(0,K.jsx)(AC,{text:t("notSupported")}):o===!1?(0,K.jsx)(M_,{onLogIn:e}):!s||!i||o===null?(0,K.jsx)(AC,{text:t("waiting")}):(0,K.jsx)("div",{className:(0,IC.default)(n.root),"data-testid":"widget",children:(0,K.jsxs)(EC,{children:[(0,K.jsxs)(iu,{className:n.sectionList,children:[(0,K.jsx)(F_,{}),(0,K.jsx)(H_,{}),(0,K.jsx)(CC,{})]}),(0,K.jsxs)(U_,{children:[(0,K.jsx)(TC,{}),(0,K.jsx)(D_,{})]})]})})},NC=z_;function Ps(e){let t=new Range;return t.selectNodeContents(e),t}function _C(e,t,n){try{return no(e,t,n),!0}catch(r){return!1}}function If(e){return"tagName"in e&&(e.tagName==="DIV"||e.tagName==="P")}function Of(e){return"tagName"in e&&e.tagName==="BR"}var Fl=/[\u200B-\u200D\uFEFF]/g;function no(e,t,n){let r=new Range;if(e.firstChild===null&&t===0&&n===0)return r.selectNodeContents(e),r;let o=0,i=!1;function s(l,u){let c=-1,f=/[\u200B-\u200D\uFEFF]/;if(!f.test(l))return u;for(let d=0;d<=l.length;d++)if(f.test(l[d])||c++,c===u)return d;throw new Error("Offset out of range")}function a(l){switch(l.nodeType){case Node.TEXT_NODE:{let u=l.textContent,c=u.replace(Fl,""),f=o+c.length,d=t>=o&&t<=f,m=n>=o&&n<=f;if(d){let y=s(u,t-o);y===0&&!m?r.setStartBefore(l):r.setStart(l,y)}m&&(r.setEnd(l,s(u,n-o)),i=!0),o=f;break}case Node.ELEMENT_NODE:{if(Of(l)&&(o===t&&r.setStartBefore(l),o++,o===n)){r.setEndAfter(l),i=!0;return}for(let c=0;c<l.childNodes.length&&(a(l.childNodes[c]),!i);c++);let u=l.lastChild;If(l)&&u&&!If(u)&&!Of(u)&&o++;break}default:break}}if(a(e),r.startContainer===document)throw new Error("Offsets out of bound");return r}function Hl(e,t){if(!e.contains(t.startContainer)||!e.contains(t.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:r,endContainer:o,endOffset:i,collapsed:s}=t,a,l,u=0;function c(f){let d=f===e,m=f===n,y=f===o;switch(f.nodeType){case Node.TEXT_NODE:{let v=f.textContent;m&&(a=u+v.substring(0,r).replace(Fl,"").length),y&&(l=u+v.substring(0,i).replace(Fl,"").length),u+=v.replace(Fl,"").length;break}case Node.ELEMENT_NODE:{if(Of(f)&&f.nextSibling){u++;break}!d&&If(f)&&f.previousSibling&&u++;for(let v=0;v<f.childNodes.length;v++){let p=m&&v===r,g=y&&v===i;if(p&&(a=u),g&&(l=u),l!==void 0||((!p||!s)&&c(f.childNodes[v]),y&&v===i-1&&(l=u),l!==void 0))break}y&&(l=u);break}default:break}}if(c(e),l===void 0)throw new Error("Could not determine start and end");return{start:a!=null?a:l,end:l}}function Ul(e,t){if(!e.contains(t.startContainer)||!e.contains(t.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:r,endContainer:o,endOffset:i,collapsed:s}=t,a=0,l="";function u(c){let f=c===e,d=c===n,m=c===o;switch(d&&(a=1),c.nodeType){case Node.TEXT_NODE:{if(a!==1)return;let y=d?r:0,v=m?i:void 0;l+=c.textContent.replace(Fl,"").substring(y,v);break}case Node.ELEMENT_NODE:{if(!s&&a===1&&Of(c)&&c.nextSibling){l+=`
|
|
26
26
|
`;break}!f&&!s&&a===1&&If(c)&&c.previousSibling&&(l+=`
|
|
27
|
-
`);let y=d?r:0,v=m?Math.min(i,c.childNodes.length):c.childNodes.length;for(let p=y;p<v&&(u(c.childNodes[p]),a!==2);p++);break}default:break}m&&(a=2)}return u(e),l}var MC=(s=>(s.CUT="Cut",s.BACKSPACE="Backspace",s.DELETE="Delete",s.ERASEEOF="EraseEof",s.UNDO="Undo",s.CLEAR="Clear",s))(MC||{}),hr=class{constructor(t){this.element=t;this.isFocused=!1;this.isActive=!0;this.isDisposed=!1;this.eventListeners={};this.disposeHandlers=[];this.cachedText="";this.cachedCaretPosition=null;this.cachedSelection={start:0,end:0};this.cachedHTML="";this.isSubmitting=!1;this.isPossibleClearInputAction=!1;this.cachedText=this.getText(),this.cachedHTML=this.getHTML(),this.cachedSelection=this.getSelection(),this.listen()}addEventListener(t,n){let r=o=>{n(o)};this.element.addEventListener(t,r),this.disposeHandlers.push(()=>{this.element.removeEventListener(t,r)})}removeEventListener(t,n){this.element.removeEventListener(t,n)}handleInteraction(){let t=this.getText(),n=this.getHTML(),r=this.getSelection(),o=this.cachedCaretPosition===null;if(!this.isActive||(t===""&&this.cachedText!==""&&!this.isPossibleClearInputAction&&this.emit("submit"),t!==this.cachedText?(this.cachedText=t,this.cachedHTML=n,o=!0,this.emit("change",{plainText:t,rawHTML:n})):n!==null&&n!==this.cachedHTML&&(this.cachedHTML=n,o=!0,this.emit("change",{plainText:t,rawHTML:n})),(r.start!==this.cachedSelection.start||r.end!==this.cachedSelection.end)&&(this.cachedSelection=r,o=!0,this.emit("selection",r)),!o))return;let i=this.getCaretPosition();$r(i,this.cachedCaretPosition)||(this.cachedCaretPosition=i,this.emit("caretposition",i))}handleClick(){this.handleInteraction()}handleFocus(){let t=!this.isFocused;this.isFocused=!0,t&&this.emit("focus"),this.handleInteraction()}handleBlur(){this.isPossibleClearInputAction=!1;let t=this.isFocused;this.isFocused=!1,t&&this.emit("blur")}handleKeyDown(t){let{key:n,ctrlKey:r,metaKey:o}=t;this.isPossibleClearInputAction=Object.values(MC).includes(n)||n.toLowerCase()==="z"&&(r||o),this.emit("keydown",t)}handleKeyUp(t){this.handleInteraction(),this.emit("keyup",t)}handleCut(){this.isPossibleClearInputAction=!0,this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(t){var r,o;let n=((r=t.clipboardData)==null?void 0:r.getData("text"))||((o=t.clipboardData)==null?void 0:o.getData("text/plain"))||"";this.emit("paste",{pastedText:n,selectionText:this.getSelectedText()})}listen(){this.addEventListener("keydown",n=>this.handleKeyDown(n)),this.addEventListener("keyup",n=>this.handleKeyUp(n)),this.addEventListener("input",()=>this.handleInteraction()),this.addEventListener("change",()=>this.handleInteraction()),this.addEventListener("focus",()=>this.handleFocus()),this.addEventListener("blur",()=>this.handleBlur()),this.addEventListener("cut",()=>this.handleCut()),this.addEventListener("paste",n=>this.handlePaste(n)),this.addEventListener("click",()=>this.handleInteraction()),document.activeElement===this.element&&(this.isFocused=!0);let t=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});t.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{t.disconnect()})}focus(){this.element.focus()}emit(t,...n){this.isDisposed||this.eventListeners[t]&&this.eventListeners[t].forEach(r=>{r(...n)})}on(t,n){this.isDisposed||(this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n))}activate(){let t=this.isActive===!1;this.isActive=!0,t&&this.handleInteraction()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(t=>t()),this.eventListeners={},this.isDisposed=!0}};function DC(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var Jo=class extends hr{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),Ul(this.element,n)}getHTML(){return this.element.innerHTML||""}getRange(){var s;let n=this.getRootNode();if(n.activeElement!==this.element)return null;let r="getSelection"in n?n.getSelection():window.getSelection();if(!r)return null;let o="getComposedRanges"in r&&n instanceof ShadowRoot?(s=r.getComposedRanges(n))==null?void 0:s[0]:r.rangeCount>0?r.getRangeAt(0):null;if(!o)return null;let i=this.element.ownerDocument.createRange();return i.setStart(o==null?void 0:o.startContainer,o==null?void 0:o.startOffset),i.setEnd(o==null?void 0:o.endContainer,o==null?void 0:o.endOffset),!i||!this.element.contains(i.startContainer)||!this.element.contains(i.endContainer)?null:i}getCaretPosition(){let n=this.getRange();if(!n||!n.collapsed||!("getBoundingClientRect"in n))return null;let r=n.getBoundingClientRect();return!DC(r)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),r=n.getBoundingClientRect(),n.deleteContents(),!DC(r))?null:{top:r.top+r.height,left:r.left}}getSelection(){let n=this.getRange();if(n)return Hl(this.element,n);let r=this.lastKnownSelection;if(r&&_C(this.element,r.start,r.end))return r;let o=Ps(this.element);return o.collapse(!1),Hl(this.element,o)}getSelectedText(){let{start:n,end:r}=this.getSelection();return Ul(this.element,no(this.element,n,r))}listen(){super.listen();let n=new MutationObserver(i=>{var s,a;i.length===2&&i[0].addedNodes.length===1&&((s=i[0].addedNodes[0])==null?void 0:s.textContent)==="\u2060"&&((a=i[1].removedNodes[0])==null?void 0:a.textContent)==="\u2060"||setTimeout(()=>{this.handleInteraction()},0)});n.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0}),this.disposeHandlers.push(()=>n.disconnect());let r=this.element.isContentEditable,o=new MutationObserver(()=>{this.element.isContentEditable!==r&&(r=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>o.disconnect())}};var j_=["direction","boxSizing","width","height","overflowX","overflowY","borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth","borderStyle","paddingTop","paddingRight","paddingBottom","paddingLeft","fontStyle","fontVariant","fontWeight","fontStretch","fontSize","fontSizeAdjust","lineHeight","fontFamily","textAlign","textTransform","textIndent","textDecoration","letterSpacing","wordSpacing","tabSize"];function FC(e,t){let n="mozInnerScreenX"in window,r=document.createElement("div");r.id="input-textarea-caret-position-mirror-div";let o=r.style,i=window.getComputedStyle(e),s=e.ownerDocument.body;o.whiteSpace="pre-wrap",o.wordWrap="break-word",o.position="absolute",o.visibility="hidden",j_.forEach(function(c){o[c]=i[c]}),n?e.scrollHeight>parseInt(i.height)&&(o.overflowY="scroll"):o.overflow="hidden",r.textContent=e.value.substring(0,t);let a=document.createElement("span");a.textContent=e.value.substring(t)||".",r.appendChild(a),s.appendChild(r);let l=e.getBoundingClientRect(),u={top:l.top-e.scrollTop+a.offsetTop+parseInt(i.borderTopWidth)+a.offsetHeight,left:l.left-e.scrollLeft+a.offsetLeft+parseInt(i.borderLeftWidth)};return s.removeChild(r),u}var ei=class extends hr{constructor(){super(...arguments);this.lastKnownSelection=null}getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:n,selectionEnd:r}=this.element;return{start:n,end:r}}getSelectedText(){let n=this.getSelection();return n?this.getText().slice(n.start,n.end):""}getCaretPosition(){return FC(this.element,this.element.selectionEnd)}listen(){super.listen();let n=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var i;return(i=n==null?void 0:n.get)==null?void 0:i.call(this.element)},set:i=>{var s;(s=n==null?void 0:n.set)==null||s.call(this.element,i),this.handleInteraction()}}),this.addEventListener("scroll",()=>{this.emit("caretposition",this.getCaretPosition())});let r=this.element.disabled,o=new MutationObserver(()=>{this.element.disabled!==r&&(r=this.element.disabled,this.emit(r?"disabled":"enabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>o.disconnect())}};function HC(e,t,n){let r=`deepdesk-iframe-${e}`,o=document.getElementById(r);if(o)return o;let i=document.createElement("iframe"),s=new URL(t);return Object.entries(n).forEach(([a,l])=>{s.searchParams.append(a,l)}),i.style.position="absolute",i.style.left="-999em",i.style.width="0px",i.style.height="0px",i.tabIndex=-1,i.id=r,i.title=`iframe-${e}`,i.src=s.toString(),window.document.body.appendChild(i),i}function B_(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(t){return e}}var Ay=class{constructor(t){this.name=t;this.disposeHandlers=[];this.broadcastChannel=new BroadcastChannel(t)}onMessage(t){this.broadcastChannel.addEventListener("message",t),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",t)})}postMessage(t){this.broadcastChannel.postMessage(JSON.stringify(t))}close(){this.disposeHandlers.forEach(t=>t()),this.broadcastChannel.close()}},Iy=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.disposeHandlers=[];this.iframe=HC(t,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}onMessage(t){window.addEventListener("message",t),this.disposeHandlers.push(()=>{window.removeEventListener("message",t)})}postMessage(t){var n;(n=this.iframe.contentWindow)==null||n.postMessage(JSON.stringify(t),this.targetOrigin)}close(){var t;this.disposeHandlers.forEach(n=>n()),(t=this.iframe)==null||t.remove()}},Oy=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.eventMap,this.sessionId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setSessionId(t){this.sessionId!==t&&(this.cleanup(),z.info("Set sessionId",t),this.sessionId=t,this.channel=this.createChannel(t))}createChannel(t){let n=this.params.createCustomChannel?this.params.createCustomChannel(t):this.isCrossOrigin?new Iy(t,this.deepdeskUrl,{debug:!0}):new Ay(t),r=o=>{var s,a;if(o.origin!==this.deepdeskUrl)return;let i=B_(o.data);typeof i!="object"||i.type!=="event"||i.channel!==t||(z.info("Received broadcast event",this.sessionId,o),(a=(s=this.eventMap)[i.name])==null||a.call(s,i.payload))};return n.onMessage(r),n}send(t,n,r){var s,a;z.info("Broadcast event",{sessionId:this.sessionId,name:t,payload:n});let o={type:"event",name:t,payload:n};r!==!1&&((a=(s=this.eventMap)[t])==null||a.call(s,n));let i=this.sessionId==="deepdesk-general"?this.defaultChannel:this.channel;i==null||i.postMessage(I(k({},o),{channel:this.sessionId}))}cleanup(t=!1){var n,r;(n=this.channel)==null||n.close(),delete this.channel,t&&((r=this.defaultChannel)==null||r.close(),delete this.defaultChannel)}},UC=Oy;function V_(e){return e.replace(/(_\w)/g,t=>t[1].toUpperCase())}function he(e){return Array.isArray(e)?e.map(he):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>I(k({},t),{[V_(n)]:he(e[n])}),{}):e}function W_(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function qe(e){return Array.isArray(e)?e.map(qe):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>I(k({},t),{[W_(n)]:qe(e[n])}),{}):e}var Ls=class extends Error{constructor(n,r){super(n);this.body=r;this.name="CustomError"}};var Ny=e=>new Promise(t=>{setTimeout(t,e)});var As=class extends Ls{constructor(){super(...arguments);this.name="ClientError"}},My=class extends Ls{constructor(){super(...arguments);this.name="ServerError"}},_y=new Map;function K_(e){return R(this,null,function*(){if(e.status===204)return e.text().catch(()=>{}),null;let t=e.headers.get("content-type");if(t&&t.includes("application/json"))return e.json();let n=yield e.text();return n===""?null:(z.warn("Unexpected response body:",n.slice(0,20)),JSON.parse(n))})}var ro=class ro{constructor(t="",n={}){this.baseUrl=t;this.options=n;this.latestRequestByUrl={};this.fetch=window.fetch.bind(window);n.fetch&&(this.fetch=n.fetch)}patchFetch(t){this.fetch=t(this.fetch)}setCsrfToken(t){this.csrfToken=t}request(t,n={}){return new Promise((r,o)=>{let i={isAborted:!1,reject:o},s=`${this.baseUrl}${t}`,a=this.fetch,l=n.method===void 0||n.method.toLowerCase()==="get",E=n,{useCache:u=!1,abortLatest:c=!1,attempts:f=1,retryDelay:d=500,refreshTokenOn401:m=!0,retryOnError:y=P=>P instanceof TypeError,retryOnResponse:v=P=>P.status>=500,version:p=null}=E,g=ee(E,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]);if(u)if(l){if(_y.has(s)){r(_y.get(s));return}}else throw new Error(`Can't use 'useCache' for ${n.method}`);let h=I(k({credentials:"include"},g),{headers:k({Accept:"application/json","Content-Type":"application/json"},g.headers)});!l&&this.csrfToken&&(h.headers=I(k({},h.headers),{"X-CSRFToken":this.csrfToken})),typeof p=="string"&&(h.headers=I(k({},h.headers),{"X-Deepdesk-API-Version":p}));let S=f,w=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[s]&&c&&(this.latestRequestByUrl[s].isAborted=!0,this.latestRequestByUrl[s].reject(new Error("Aborted"))),this.latestRequestByUrl[s]=i;let C=()=>R(this,null,function*(){return S--,a(s,h).then(P=>R(this,null,function*(){return v(P)&&!i.isAborted&&S>0?(yield Ny(d),C()):P.status===401&&m===!0&&w===!1?(w=!0,yield this.refreshToken(),C()):P})).catch(P=>R(this,null,function*(){if(y(P)&&!i.isAborted&&S>0)return yield Ny(d),C();throw P}))});C().then(P=>R(this,null,function*(){let N=yield K_(P);if(delete this.latestRequestByUrl[s],P.status>=500){o(new My("Server Error",N));return}else if(P.status===401){o(new As("Unauthorized",N));return}else if(P.status===403){o(new As("Forbidden",N));return}else if(P.status===404){o(new As("Not Found",N));return}else if(P.status>=400){o(new As("Bad Request",N));return}u&&_y.set(s,N),r(N)})).catch(P=>{o(P)})})}validateToken(){return R(this,null,function*(){let{has_valid_access_token:t}=yield this.get("/auth/validate");if(!t)try{yield this.refreshToken()}catch(r){return!1}let{is_logged_in:n}=yield this.get("/apis/admin/session/validate/");return!!n})}refreshToken(){return ro.refreshingToken||(ro.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{ro.refreshingToken=null},1e3*60)})),ro.refreshingToken}get(t,n){return this.request(t,n)}post(t,n,r){return this.request(t,k({method:"POST",body:JSON.stringify(n)},r))}patch(t,n,r){return this.request(t,k({method:"PATCH",body:JSON.stringify(n)},r))}put(t,n,r){return this.request(t,k({method:"PUT",body:JSON.stringify(n)},r))}delete(t,n){return this.request(t,k({method:"DELETE"},n))}};ro.refreshingToken=null;var ti=ro;var zC;(t=>{let e;(s=>(s.SEND_MESSAGE="Send Message",s.HANDLING_TIME="Handling Time",s.ADD_TO_PERSONAL_COLLECTION="Add to personal collection",s.DELETE_FROM_PERSONAL_COLLECTION="Delete from personal collection"))(e=t.EventType||(t.EventType={}))})(zC||(zC={}));function Nf(e){return I(k({},he(e)),{tags:e.tags})}var ni=class ni{constructor(t,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new ti(t,{fetch:n.fetch}),this.client.patchFetch(r=>(o,i)=>R(this,null,function*(){let s=yield r(o,i);return this.handleDeepdeskVersionHeaders(s),s}))}preflight(){return R(this,null,function*(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=yield this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(ni.exchangeTokenPromise||(ni.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),ni.exchangeTokenPromise):Promise.resolve()})}createConversation(t){return R(this,null,function*(){yield this.preflight(),z.info(`Creating conversation for session ${t.sessionId} and agent ${t.agentId}`);let n=yield this.client.post("/api/conversations",I(k({},qe(t)),{tags:t.tags}),{version:"v2"});return Nf(n)})}getMe(){return R(this,null,function*(){let t=yield this.client.get("/apis/admin/session/me/");return he(t)})}postIdentity(t){return R(this,null,function*(){yield this.client.post("/apis/admin/session/me/identities/",qe(t))})}patchMe(t){return R(this,null,function*(){let n=yield this.client.patch("/apis/admin/session/me/",qe(t));return he(n)})}getProfile(t){return R(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${t}/`,{useCache:!0});return he(n)})}getKnowledgeAssistant(t){return R(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{useCache:!0});return he(n)})}getContentTypes(){return R(this,null,function*(){let t=yield this.client.get("/apis/admin/content-types/",{useCache:!0});return he(t)})}getAccount(){return R(this,null,function*(){let t=yield this.client.get("/apis/admin/account/",{useCache:!0});return he(t)})}getPlatformConfig(t){return R(this,null,function*(){let n=t!==void 0?`/platform/config/${t}/`:"/platform/config/",{config:r}=yield this.client.get(n,{useCache:!0});return he(r)})}checkUserExists(t){return R(this,null,function*(){let{exists:n}=yield this.client.get(`/apis/admin/users/exists?external_id=${t}`,{version:"v1"});return n})}getConversationBySessionId(r){return R(this,arguments,function*(t,n={}){yield this.preflight(),z.info(`Getting conversation for session ${t}`);let{attempts:o=1,retryDelay:i=1e3}=n,s=yield this.client.get(`/api/conversations/by_session_id/${t}`,{attempts:o,retryDelay:i,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"});return z.info(`Successfully retrieved conversation ${s.id} for session ${t}`),Nf(s)})}isConversationSupported(r){return R(this,arguments,function*(t,n={}){z.info(`Check if conversation for session ${t} is supported`);let{attempts:o=1,retryDelay:i=1e3}=n;return(yield this.client.get(`/api/conversations/by_session_id/${t}/active_profile`,{attempts:o,retryDelay:i,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"})).has_active_profile})}updateConversation(t,n){return R(this,null,function*(){let r=qe(n);n.tags&&(r.tags=n.tags);let o=yield this.client.put(`/api/conversations/${t}`,r,{version:"v2"});return Nf(o)})}postMessages(t,n){return R(this,null,function*(){return(yield this.client.post(`/api/conversations/${t}/messages`,n.map(o=>I(k({},qe(o)),{tags:o.tags})),{version:"v2"})).map(o=>Nf(o))})}sendEvent(t,n){return R(this,null,function*(){let s=n,{data:r}=s,o=ee(s,["data"]),i=Object.entries(this.latestReceivedDeepdeskVersions).reduce((a,[l,u])=>I(k({},a),{[l]:u}),{});return this.client.post("/api/events",qe(I(k(k({},i),o),{data:r,name:t})),{version:"v2"})})}sendEventV1(t,n){return R(this,null,function*(){let r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((o,[i,s])=>I(k({},o),{[i]:s}),{});return this.client.post("/api/events",{event:t,data:qe(k(k({},n),r))},{version:"v1"})})}getEntities(t){return R(this,null,function*(){return(yield this.client.post("/api/entities",{messages:t.filter(r=>r.text)},{version:"v1"})).entities})}getTemporaryExchangeToken(){return R(this,null,function*(){return(yield this.client.get("/auth/exchange-token")).jwt})}exchangeTokenForAccessCookie(t){return R(this,null,function*(){return this.client.post("/apis/admin/session/jwt/",{jwt:t}).catch(n=>{throw z.warn(`Invalid token '${t}'`),n})})}authenticateWithKey(t,n){return R(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/api-key/",qe(n),{refreshTokenOn401:!1,headers:{apikey:t}})})}getTextSuggestions(o){return R(this,arguments,function*(t,n={},r){return r==="sticky-messages"?this.getPinnedMessages(t):(yield this.client.post(`/api/conversations/${t}/recommend/${r}`,qe(n),{abortLatest:!0,version:"v1"})).map(s=>I(k({},he(s)),{text:s.text||s.url||s.message,source:r,type:r})).filter((s,a,l)=>a===l.findIndex(u=>u.text===s.text))})}isLoggedIn(){return R(this,null,function*(){return yield this.preflight(),this.client.validateToken()})}getAutocompleteSuggestions(t,n){return R(this,null,function*(){return(yield this.client.post(`/api/conversations/${t}/autocomplete`,qe(n),{abortLatest:!0,version:"v1"})).map(o=>({score:1,source:o.source,sourceText:o.source_text,text:o.label,trainingJobs:o.training_jobs,searchKeywords:o.search_keywords,type:o.source})).filter((o,i,s)=>i===s.findIndex(a=>a.text===o.text))})}getPinnedMessages(t){return R(this,null,function*(){let n=yield this.client.get(`/api/conversations/${t}/sticky-messages`,{abortLatest:!0,version:"v1"});return he(n).map(r=>I(k({},r),{text:r.message,source:"sticky-messages",type:"pinned-message"}))})}getStyleSuggestions(t){return R(this,null,function*(){let n=yield this.client.post("/api/style-suggestions",qe(t),{abortLatest:!0,version:"v1"});return he(n)})}search(t){return R(this,null,function*(){let n=yield this.client.post(`/api/profiles/${t.profile}/search`,qe(t),{version:"v2"});return he(n)})}knowledgeAssist(i,s,a){return R(this,arguments,function*(t,n,r,o={}){let l=yield this.client.post(`/api/knowledge-assist/assistants/${r}/search`,qe({question:t.question,doNotKnowAnswer:t.doNotKnowAnswer,customerInstruction:t.customerInstruction,chatHistory:n.map(u=>({question:u.question,answer:u.answer.answer})),agentId:o.agentId,conversationId:o.conversationId}),{version:"v2"});return he(l)})}requestLoginByEmail(t){return R(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:t});return he(n)})}requestPasswordlessToken(){return R(this,null,function*(){let t=yield this.client.get("/apis/admin/session/passwordless/request/");return he(t.token)})}getCsrfToken(){return R(this,null,function*(){let{token:t}=yield this.client.get("/apis/admin/session/csrf/");return t})}verifyLoginToken(t){return R(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/login/",{token:t});return he(n)})}evaluateRule(i,s,a){return R(this,arguments,function*(t,n,r,o={}){let l=new URLSearchParams;o.raiseForFailingConditions&&l.set("raise_for_failing_conditions","true");let u=yield this.client.post(`/api/conversations/${n}/rules/${t}/evaluate?${l.toString()}`,r,{version:"v2"});return u?he(u.cues):[]})}getSummary(r){return R(this,arguments,function*(t,n={}){let o=yield this.client.post("/api/summary",{conversation:{messages:t.filter(i=>i.text&&i.source),agent_id:n.agentId,id:n.externalConversationId},prompt_instruction:n.promptInstruction,model:n.model},{version:"v1"});return he(o)})}evaluateAssistant(t,n){return R(this,null,function*(){var a;let r=new URLSearchParams,{expectFormat:o="text"}=n||{};if(o.startsWith("json-schema:")){let l=o.replace("json-schema:","");r.append("expect_response_format","json-schema"),r.append("expect_response_format_schema",l)}else r.append("expect_response_format",o);n!=null&&n.externalConversationId&&r.append("external_conversation_id",n.externalConversationId);let i=n!=null&&n.threadId?`/api/v2/assistants/${t}/threads/${n==null?void 0:n.threadId}/evaluate?${r.toString()}`:`/api/v2/assistants/${t}/evaluate?${r.toString()}`,s=yield this.client.post(i,{input:(a=n==null?void 0:n.input)!=null?a:{},conversation:n==null?void 0:n.transcript});return he(s.output)})}createAssistantThread(t){return R(this,null,function*(){let{assistantCode:n}=t,r=yield this.client.post(`/apis/admin/assistants/${n}/threads/`,{});return he(r)})}postMessageToAssistantThread(t){return R(this,null,function*(){let{assistantCode:n,threadId:r,message:o}=t,i=yield this.client.post(`/apis/admin/assistants/${n}/threads/${r}/messages/`,{content:o,role:"user"});return he(i)})}getRules(){return R(this,null,function*(){let t=new URLSearchParams,n=yield this.client.get(`/apis/admin/rule-engine/rules/?${t.toString()}`,{useCache:!0});return he(n)})}translateMessages(t){return R(this,null,function*(){let n=yield this.client.post("/api/translate",qe(t),{version:"v2"});return he(n)})}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),i=o.match(i0);if(!n||!i)return;let s=i[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[s];a&&n&&a!==n&&z.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[s]=n})}};ni.exchangeTokenPromise=null;var yr=ni;var jC={startTime:null,stopTime:null},BC=e=>e.handlingTime,VC=ne({name:"handlingTime",initialState:jC,reducers:{handlingTimeStart(e){if(e.startTime&&!e.stopTime)throw new Error("Timing already started");e.startTime=new Date,e.stopTime=null},handlingTimeStop(e){if(!e.startTime)throw new Error("Timing not started");e.stopTime=new Date},handlingTimeReset(e){e.startTime=null,e.stopTime=null}},extraReducers:e=>{e.addCase(Ae,()=>jC)}}),{handlingTimeStart:WC,handlingTimeStop:_f,handlingTimeReset:KC}=VC.actions,$C=VC.reducer;var qC=(e={})=>{let t=k({onAuthError:os(!1)},e);return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var Mf={list:{keywordMatches:[]},fetchState:"idle"};var ri=X("styleSuggestions/getAll",(n,r)=>R(void 0,[n,r],function*({text:e},t){var l;let{deepdeskAPI:o}=t.extra,i=t.getState(),{showStyleSuggestions:s}=i.settings,a=(l=i.conversation.current)==null?void 0:l.profileCode;if(!s)return Mf.list;if(!a)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:a,message:e})})),$_=ne({name:"styleSuggestions",initialState:Mf,reducers:{},extraReducers:e=>{e.addCase(ri.pending,t=>{t.fetchState="loading"}).addCase(ri.rejected,t=>{t.fetchState="error"}).addCase(ri.fulfilled,(t,n)=>{t.fetchState="done",$r(t.list,n.payload)||(t.list=n.payload)}).addCase(Lo,t=>{t.list=Mf.list}).addCase(Ae,()=>Mf)}}),GC=$_.reducer;var YC=(e={})=>{let t,n=!0,r=k({getStyleSuggestions:ri,debounce:500},e);return o=>i=>s=>{var m;let a=o.getState().input.text,l=i(s),u=o.getState();if(u.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:c}=u.settings;if(!((m=u.conversation.current)==null?void 0:m.id)||!c)return l;let{text:d}=u.input;return d===a&&!n||(clearTimeout(t),d==="")||(t=setTimeout(()=>{n=!1,o.dispatch(r.getStyleSuggestions({text:d}))},e.debounce)),l}};function q_(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var QC=(e={})=>{let t=k({getTextSuggestions:gn,getAutocompleteSuggestions:El,debounce:200,check:_n},e),n;return r=>o=>i=>{var v;let{input:s}=r.getState(),a=o(i),l=r.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:u,showTabCompletion:c}=l.settings,f=(v=l.conversation.current)==null?void 0:v.id,d=i.type===Xd.toString();if(!f||!u&&!c)return a;let{input:m}=l;return q_(m,s)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let p=ss(l);p===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(p))},d?0:t.debounce)),a}};var XC=ri.fulfilled.toString();function G_(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let i=e.keywordMatches.filter(l=>l.keyword===o),s=t.keywordMatches.filter(l=>l.keyword===o),a=s.length-i.length;a<=0||r.push(...s.slice(0,a))}),r}var ZC=e=>t=>n=>r=>{var u;if(r.type!==XC){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let i=t.getState(),s=i.styleSuggestions.list,a=(u=i.conversation)==null?void 0:u.current;if(o===s)return;let l=G_(o,s);r.type===XC&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var Y_=Pc({assistants:jb,auth:P1,conversation:U1,contentTypes:Vb,passwordlessToken:HT,entities:hE,knowledgeAssistant:Db,handlingTime:$C,info:ib,input:X1,settings:w1,profile:Kb,search:db,styleSuggestions:GC,ui:JE,rules:VT,textSuggestions:FE});function JC(e){return Rw({reducer:Y_,middleware:t=>[...t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI}},serializableCheck:!1}),qC(),QC({debounce:200}),YC({debounce:500}),ZC(e.deepdeskAPI),...e.middleware?e.middleware:[]],preloadedState:e.preloadedState})}var Q_=e=>{var t,n;return(n=(t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())!=null?n:"unknown"},X_=e=>t=>n=>r=>{var a,l,u,c,f,d,m;let o=t.getState(),i=th("inlineSuggestions")(o);switch(r.type){case os.toString():{!r.payload&&e.emit("logout",void 0);break}case mn.fulfilled.toString():r.payload.length>0&&e.sendEvent("entities found",{conversationId:(a=o.conversation.current)==null?void 0:a.id,data:{entities:r.payload}});break;case Gt.toString():e.sendEvent(r.payload.name,{conversationId:((l=r.payload.options)==null?void 0:l.includeConversationData)&&((u=o.conversation.current)==null?void 0:u.id),data:r.payload.data});break;case Lo.toString():e.logSendMessage(r.payload);break;case Yo.fulfilled.toString():r.isBroadcasted||e.broadcast(ch,r,!1),(c=r.payload.options)!=null&&c.shouldEmit&&e.emit("cues",r.payload.cues);break;case _d.toString():e.emit("call-to-action",{cue:r.payload});break;case rr.fulfilled.toString():r.isBroadcasted||e.broadcast(dh,r,!1);break;default:break}let s=n(r);switch(r.type){case Lo.toString():e.handleAfterSendMessage(r.payload);break;case Cl.toString():e.onUpdateShowTabHint(r.payload);break;case _f.toString():e.logHandlingTime();break;case"analytics/logEvent/fulfilled":{e.emit("event",r.meta.arg);break}case cd.toString():{let{start:y,end:v}=o.input.selection;e.emit("replace",I(k({},r.payload),{replace:r.payload.replace==="selection"?{start:y,end:v}:{start:0,end:v}}));break}case un.toString():{let{start:y,end:v}=o.input.selection;e.emit("select-suggestion",I(k({type:Q_(r.payload.suggestion)},r.payload),{replace:r.payload.replace==="selection"?{start:y,end:v}:{start:0,end:v}})),i&&t.dispatch(qr([]));break}case dd.toString():e.emit("select-image",r.payload),e.sendEvent("Image attached",{conversationId:(f=o.conversation.current)==null?void 0:f.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case qr.toString():{i&&r.payload.length>0&&t.dispatch(fd(0));break}case On.fulfilled.toString():{e.sendEvent("conversation summarized",{conversationId:(d=o.conversation.current)==null?void 0:d.id,data:{summary:r.payload,assistant:(m=t.getState().profile.data)==null?void 0:m.summarizerAssistantNew}});break}default:break}return s},ek=X_;function Dy(e){return e.toISOString().replace("T"," ").replace("Z","")}var Z_=(e,t)=>t.version,tk=ln([ls,An,BC,Z_],(e,t,n,r)=>{if(!t)return z.warn("No conversationId for handling time metrics"),null;let{startTime:o,stopTime:i}=n;return!o||!i?(z.warn("No startTime and stopTime for handling time metrics"),null):{conversationId:t,clientVersion:r,agentId:e==null?void 0:e.agentId,agentName:e==null?void 0:e.agentName,agentEmail:e==null?void 0:e.agentEmail,timeStart:Dy(o),timeStop:Dy(i)}});function nk(e,t,n){var N,_,q,B;let r=(N=t.conversation.current)==null?void 0:N.id;if(!r)return z.warn("No conversationId for send message metrics"),null;let{text:o,metrics:{numCharsTyped:i,numCharsPasted:s,numCharsCut:a,numCharsDeleted:l,numPaste:u,agentStartedTypingTimestamp:c,externalTimeTotalSeconds:f,pastes:d,cuts:m,deletions:y,textSuggestions:v,offeredTextSuggestions:p}}=t[e],g=o.length,S=v.reduce((V,{text:fe,searchTerm:Ge})=>V+fe.length-(Ge?Ge.length:0),0),w=c!=null?c:Date.now(),C=(Date.now()-w)/1e3+(f||0),E=i/C,P=v.reduce((V,{searchTerm:fe})=>V+(fe?fe.length:0),0);return{conversationId:r,source:"agent",text:o,clientVersion:n.version,pastes:d,cuts:m,deletions:y,lenTextTyped:i+P,lenTextTotal:g,lenTextAssisted:S,lenTextPasted:s,lenTextCut:a,lenTextDeleted:l,timeTotalSeconds:C,charsPerSecond:E,numPastes:u,textSuggestionsV2:v,suggestionsCounters:[{source:"gpt",countOffered:p.filter(V=>V.source==="gpt").length}],agentId:(_=t.info.agentInfo)==null?void 0:_.agentId,agentName:(q=t.info.agentInfo)==null?void 0:q.agentName,agentEmail:(B=t.info.agentInfo)==null?void 0:B.agentEmail}}function Fy(e,t){var i;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return Fy(r,t);let o=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;return o?Fy(o,t):null}function rk(e,t){return Fy(e,t)}function ok(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function J_(e){return typeof e=="object"&&e!==null&&"tagName"in e}function Df(e){return J_(e)&&(Go(e)||af(e))}var sk,Hn=new Map,eM=["bottom","height","left","right","top","width"],ik=(e,t)=>!e&&!t?!1:e&&!t||!e&&t?!0:eM.some(n=>e[n]!==t[n]);function ak(e){var n,r,o;if(e.ownerDocument===document)return[];let t=(o=(r=(n=e.ownerDocument)==null?void 0:n.defaultView)==null?void 0:r.frameElement)!=null?o:null;return t?[t,...ak(t)]:[]}function lk(e,t){return!e||!t?null:I(k({},e),{top:e.top+t.top,left:e.left+t.left})}var Ff=!1,uk=()=>{Ff=!0;let e=[];if(Hn.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),Hn.delete(n);return}let r=n.getBoundingClientRect();ik(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(lk,t.rect):t.rect;ik(n,t.totalRect)&&t.callbacks.forEach(r=>r(n)),t.totalRect=n}),Hn.size===0){Ff=!1;return}sk=window.requestAnimationFrame(uk)};function Hy(e,t){let n=ak(e),r=[],o=n.map((i,s)=>Hy(i,a=>{r[s]=a;let l=Hn.get(e);if(!l)return;let u=r.reduce(lk,l.rect);l.callbacks.forEach(c=>c(u))}));return{observe(i=!0){if(o.forEach(s=>s.observe(!1)),Hn.has(e)){let s=Hn.get(e);s.callbacks.push(t),s.rect&&t(s.rect)}else Hn.set(e,{rect:void 0,callbacks:[t],parentRects:r});i&&!Ff&&uk()},unobserve(){o.forEach(s=>s.unobserve());let i=Hn.get(e);if(i){let s=i.callbacks.indexOf(t);s>=0&&i.callbacks.splice(s,1),i.callbacks.length||Hn.delete(e),Hn.size||(cancelAnimationFrame(sk),Ff=!1)}}}}var ck,Un=new Map,dk=()=>{Un.forEach((e,t)=>{if(!t.isConnected){Un.delete(t);return}let{clientHeight:n,scrollHeight:r}=t,o=r>n;e.visible!==o&&(e.visible=o,e.callbacks.forEach(i=>i(e.visible)))}),Un.size!==0&&(ck=window.requestAnimationFrame(dk))};function fk(e,t){return{observe(){let n=Un.size===0;Un.has(e)?Un.get(e).callbacks.push(t):Un.set(e,{visible:void 0,callbacks:[t]}),n&&dk()},unobserve(){let n=Un.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||Un.delete(e),Un.size||cancelAnimationFrame(ck)}}}}var Uy=["borderLeftWidth","borderRightWidth","borderTopWidth","borderBottomWidth","borderStyle","boxSizing","color","overflowWrap","fontFamily","fontSize","fontSizeAdjust","fontStretch","fontWeight","fontKerning","lineHeight","letterSpacing","paddingLeft","paddingTop","paddingRight","paddingBottom","width","height","textIndent","whiteSpace","wordBreak","wordSpacing","wordWrap"];function zy(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function Is(e){return parseFloat(e)}function Hf(e){return Math.round(e*1e6)}function pk(e){return e/1e6}function jy(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=Is(e.width),i=Is(e.borderLeftWidth),s=Is(e.borderRightWidth),a=Is(e.paddingRight),l=pk(Hf(o)-Hf(i)-Hf(s)),u=pk(Hf(r));if(l-u>2){let c=l-u;n.style.paddingRight=`${a+c}px`}}function zl(e,t={}){var c,f;let n=t.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=(c=t.position)!=null?c:"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",Ko(n);let r=window.getComputedStyle(e),o=!0,i=()=>{n.scrollTop=e.scrollTop};zy(r,n,Uy),jy(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",i));let s=fk(e,()=>{zy(r,n,Uy),jy(r,e,n),i(),setTimeout(i,0)}),a,l=!0,u=Hy(e,d=>{if(d===null){t.onRemove&&t.onRemove(),n.remove();return}if(!l&&t.onMoveStart&&(Promise.resolve().then(()=>t.onMoveStart()),l=!0),clearTimeout(a),a=setTimeout(()=>{t.onMoveEnd&&t.onMoveEnd(),l=!1},200),d.height===0&&d.width===0){if(o===!0)return;t.onHide&&t.onHide(),n.style.display="none",o=!0;return}if(zy(r,n,Uy),jy(r,e,n),i(),n.style.top=`${d.top}px`,n.style.left=`${d.left}px`,t.closestScrollElement&&t.closestScrollElement!==e){let m=t.closestScrollElement.getBoundingClientRect(),y=window.getComputedStyle(t.closestScrollElement),v=Is(y.borderTopWidth),p=Is(y.borderBottomWidth),g=m.top+v-d.top,h=d.top+d.height+-(m.top+m.height-p);n.style.clipPath=`inset(${g}px 0px ${h}px 0px)`}o&&(n.style.display="block",t.onShow&&t.onShow(),o=!1)});return t.appendTo?t.appendTo.appendChild(n):(f=e.parentElement)==null||f.appendChild(n),u.observe(),s.observe(),[n,()=>{e.removeEventListener("scroll",i),u.unobserve(),s.unobserve()}]}var mk=(e,t)=>({value(){try{let n=sessionStorage.getItem(`dd-${e}`);if(!n)return t;try{return JSON.parse(n)}catch(r){return t}}catch(n){return t}},update(n){try{sessionStorage.setItem(`dd-${e}`,JSON.stringify(n))}catch(r){z.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function tM(e){return e.offsetParent!==null}function gk(e){if(!tM(e))return!1;let t=e.getBoundingClientRect();return t.top>=0&&t.left>=0&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&t.right<=(window.innerWidth||document.documentElement.clientWidth)}function Uf(e,t,n=100){let r=gk(e);t({isVisible:r});let o=setInterval(()=>{let i=gk(e);i!==r&&(r=i,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var Me=x(T());var hk=mk("showTabHint",!0),Os=class Os{constructor({deepdeskUrl:t,version:n=Os.version||"unknown",locale:r="en-US",token:o,fetch:i,productName:s,createCustomChannel:a}){this.inputMediator=null;this.eventListeners={};this.unmountHandlers=[];this.widgetRoot=null;this.dynamicThunkObject={};this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;let l=t.replace(/\/api$/,"");this.deepdeskApi=new yr(l,{token:o,fetch:i}),this.version=n,this.instanceId=Os.count++;let u={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[ek({broadcast:(c,f,d)=>{this.broadcastEvents.send(c,f,d)},emit:(c,f)=>this.emit(c,f),handleAfterSendMessage:c=>this.handleAfterSendMessage(c),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:c=>this.logSendMessage(c),onUpdateShowTabHint:c=>hk.update(c),sendEvent:(c,f)=>this.deepdeskApi.sendEvent(c,f)})]};this.store=JC(u),this.broadcastEvents=new UC({debug:!0,deepdeskUrl:l,eventMap:fb(this.store),createCustomChannel:a}),this.store.dispatch(Cl(hk.value())),this.store.dispatch(od({locale:r,adminUrl:l,productName:s}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){var t;return(t=this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex])!=null?t:null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(z.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(z.warn("Profile has not been loaded (yet)"),!0):(z.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(os(null)),this.store.dispatch(er()),new Promise(t=>{let n=this.store.subscribe(()=>{let r=this.store.getState();ct(r)&&b1(r)!=="loading"&&(n(),t())});this.unmountHandlers.push(()=>{n()})})}isLoggedIn(){return R(this,null,function*(){return(yield this.store.dispatch(er())).payload})}isConversationSupported(t,n){return R(this,null,function*(){return(yield this.store.dispatch(oh({sessionId:t,options:n}))).payload})}createConversation(t){return R(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(yield this.store.dispatch(sd(t))).payload})}getConversationBySessionId(t,n){return R(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(yield this.store.dispatch(ad({sessionId:t,options:n}))).payload})}upsertConversation(t){return R(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(yield this.store.dispatch(ih(t))).payload})}postMessages(t){return R(this,null,function*(){return(yield this.store.dispatch(ud(t))).payload})}updateConversation(t){return R(this,null,function*(){return(yield this.store.dispatch(ld(t))).payload})}resetConversation(){this.store.dispatch(Ae()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}configure(t){this.store.dispatch(od(t))}setVisitorInfo(t){this.store.dispatch(nb(t))}setCustomData(t){this.store.dispatch(rb(t))}setAgentInfo(t,n){return R(this,null,function*(){yield this.store.dispatch(Ga(k(k({},t),n)))})}setAgentSettings(t){return R(this,null,function*(){yield this.store.dispatch(ah(t))})}getAgentSettings(){return R(this,null,function*(){return(yield this.store.dispatch(lh())).payload})}refresh(){return R(this,null,function*(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.store.dispatch(pd({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()}));let t=[];return this.store.dispatch(Xd()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})})}notifyExternalSuggestion(t){this.store.dispatch(un(t))}evaluateRule(o){return R(this,arguments,function*(t,n={},r=UT){return(yield this.store.dispatch(Yo({label:t,params:n,options:r}))).payload.cues})}evaluateAssistant(t,n){return R(this,null,function*(){let c=n||{},{input:r={},transcript:o,showCuesInWidget:i=!0,includeTags:s,expectFormat:a}=c,l=ee(c,["input","transcript","showCuesInWidget","includeTags","expectFormat"]);Object.assign(r,l);let u=yield this.store.dispatch(rr({assistantCode:t,expectFormat:a||"json-schema:cues",transcript:o,includeTags:s,input:r,skipState:!i}));if(u.error)throw new Error(u.error.message);return u.payload})}evaluateConversationAssistant(t,n){return R(this,null,function*(){yield this.loadProfileConfig();let r={accepted:"conversationAcceptedAssistant","new-message":"conversationNewMessageAssistant",ended:"conversationEndedAssistant"},o=this.state.profile.data[r[t]];if(!o){z.warn(`No assistant set in profile for conversation event "${t}"`);return}yield this.evaluateAssistant(o,k({transcript:"stored-transcript",includeTags:!0},n))})}getSummary(){return R(this,null,function*(){var n;if(!this.hasConversation())return z.warn("No conversation to create summary for."),null;(n=this.state.profile.data)!=null&&n.summarizerAssistantNew||z.warn("No profile loaded yet, or no summarizer assistant set in profile");let t=yield this.store.dispatch(On({}));if(t.error)throw new Error(t.error.message);return t.payload})}handleKeyDown(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui,{textSuggestions:o,selectedSuggestionIndex:i,selection:s}=this.state.input,{inlineSuggestions:a,showTextSuggestions:l}=this.state.settings,u=a?"below":"above",c=o.length>0;if(!_n(this.state)||(this.store.dispatch(W1(sh(t))),t.key!=="Tab"&&!l))return;let f=()=>{n||!c||s&&(t.shiftKey||(this.store.dispatch(q1()),t.preventDefault()))},d=()=>{n||!c||a&&i<=0||s&&(t.shiftKey||(this.store.dispatch(G1()),t.preventDefault()))};switch(t.key){case"ArrowUp":u==="below"?d():f();break;case"ArrowDown":{u==="below"?f():d();break}case"Escape":{n||(this.store.dispatch(fd(-1)),this.store.dispatch(Jr({collapse:!0})),this.store.dispatch(XE(!0)),t.preventDefault());break}case"Tab":{t.preventDefault();let m=as(this.state);if(!m)return;this.store.dispatch(Cl(!1)),this.store.dispatch(un({text:m.text,suggestion:m,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(this.state.settings.inlineSuggestions||this.state.input.selectedSuggestionIndex===-1)return;let m=as(this.state);if(!m)return;this.store.dispatch(un({text:m.text,suggestion:m,eventMetrics:{inputType:"space"},replace:"until-selection-end"}));break}case"Enter":{if(this.state.settings.inlineSuggestions||t.shiftKey||this.state.input.selectedSuggestionIndex===-1)return;let m=as(this.state);if(!m)return;this.store.dispatch(un({text:m.text,suggestion:m,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),t.preventDefault();break}default:}n&&r&&this.store.dispatch(Jr({collapse:!1}))}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(qr([]))}handlingTimeStart(){this.state.handlingTime.startTime||(z.info("Start handling time"),this.store.dispatch(WC()))}handlingTimeStop(){this.state.handlingTime.startTime&&(z.info("Stop handling time"),this.store.dispatch(_f()))}logSendMessage(t){let n=nk("input",this.state,{version:this.version});n&&(t&&(Object.assign(n,{text:t}),Object.assign(n,{lenTextTotal:t.length})),this.deepdeskApi.sendEventV1("Send Message",n),this.emit("send-message-event",n))}logHandlingTime(){let t=tk(this.state,{version:this.version});t&&(this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch(KC()))}notifySubmit(t={}){var n;this.shouldAbort()||(this.store.dispatch(Lo((n=t.text)!=null?n:this.state.input.text)),this.store.dispatch(Q1()))}emit(t,n){let r=this.eventListeners[t];r&&r.forEach(o=>{try{o(n)}catch(i){z.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),z.error(i)}})}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),()=>{this.off(t,n)}}off(t,n){if(!t&&!n){this.eventListeners={};return}let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}setConversationQuery(t){this.dynamicThunkObject.conversationQuery=t}setPlatformVariables(t){this.store.dispatch(ob(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]=zl(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),this.unmountHandlers.push(()=>{(0,nn.unmountComponentAtNode)(i),s(),i.remove()}),i}createInlineContainer(t,n){var a;let r=document.createElement("div");r.style.position="absolute",r.style.top="0px",r.style.left="0px",r.style.height="0px",r.style.width="0px";let o=document.createElement("div");o.style.display="none",o.style.position="absolute",o.style.height="0px",o.style.width="0px",o.style.backgroundColor="red",r.appendChild(o);let i=(a=t.ownerDocument.defaultView)==null?void 0:a.frameElement,s=i?i.ownerDocument.defaultView:null;if(i&&(s===window||(s==null?void 0:s.parent)===window)){let[l,u]=zl(i,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});l.dataset.testid=n,l.style.zIndex="2",l.appendChild(r),this.unmountHandlers.push(()=>{(0,nn.unmountComponentAtNode)(o),u()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return Ko(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,nn.unmountComponentAtNode)(o),o.remove()}),o}storeMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(t,n),z.info(`Stored analytics for ${this.conversationId()}`)}catch(t){}}restoreMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=window.sessionStorage.getItem(t);if(!n)return;let r=JSON.parse(n);r.text.trim()===this.state.input.text.trim()?(z.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(Y1(r.metrics))):z.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(t)}catch(t){}}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!Df(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:f,detectSubmit:d,insertLink:m,inputMediator:y,closestScrollSelector:v,appendOverlayTo:p,inlineSuggestions:g,floatingMenu:h}=n;this.configure({showStyleSuggestions:o,showTabCompletion:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,showTextSuggestions:s,insertLink:m,isEmbedded:f,inlineSuggestions:g,floatingMenu:!!h}),n.automaticHandlingTime&&this.setupHandlingTime(t),Ko(t),this.inputMediator=y||(Go(t)?new ei(t):new Jo(t)),this.inputMediator.on("change",({plainText:C,rawHTML:E})=>{this.store.dispatch(pd({text:C,html:E}))}),this.inputMediator.on("keyup",C=>{this.store.dispatch(K1(sh(C)))}),this.inputMediator.on("keydown",C=>{this.handleKeyDown(C)}),this.inputMediator.on("paste",({pastedText:C,selectionText:E})=>{this.store.dispatch($1({text:C,selectionText:E}))}),this.inputMediator.on("cut",({selectionText:C})=>{this.store.dispatch(V1(C))});let S;this.inputMediator.on("selection",C=>{clearTimeout(S),C===null?S=setTimeout(()=>{C!==null&&this.store.dispatch(md(C))},500):this.store.dispatch(md(C))}),this.inputMediator.on("disabled",()=>{var C;(C=this.inputMediator)==null||C.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(ef(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(ef(!0))});let w=v&&rk(t,v)||void 0;if(g){let{customStyles:C,appendOverlayTo:E}=n,P=this.createInlineContainer(t,"deepdesk-caret");(0,nn.render)((0,Me.jsx)(qo,{store:this.store,customStyles:C,children:(0,Me.jsx)(Io,{broadcastEvents:this.broadcastEvents,children:(0,Me.jsx)(iT,{})})}),P),this.inputMediator.on("caretposition",_=>{_?(P.style.display="block",P.style.top=`${_.top}px`,P.style.left=`${_.left}px`):P.style.display="none"});let N=this.overlayContainerFactory("floating-menu",w||t,{appendTo:typeof h=="object"&&"appendOverlayTo"in h?h.appendOverlayTo:E},C==null?void 0:C.floatingMenuRootNode);(0,nn.render)((0,Me.jsx)(qo,{store:this.store,customStyles:C,children:(0,Me.jsx)(Io,{broadcastEvents:this.broadcastEvents,children:(0,Me.jsx)(GE,{onLogIn:()=>this.loginViaPopup().catch(_=>z.warn(_.message))})})}),N)}else{let C=this.overlayContainerFactory("deepdesk-tab-completion",w||t,{appendTo:p,closestScrollElement:w,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),E=this.overlayContainerFactory("deepdesk-suggestions-overlay",w||t,{appendTo:p},r==null?void 0:r.suggestionsRootNode);(0,nn.render)((0,Me.jsx)(qo,{store:this.store,customStyles:r,children:(0,Me.jsx)(Io,{broadcastEvents:this.broadcastEvents,children:(0,Me.jsx)(MT,{inputElement:t})})}),C),(0,nn.render)((0,Me.jsx)(qo,{store:this.store,customStyles:r,children:(0,Me.jsx)(Io,{broadcastEvents:this.broadcastEvents,children:(0,Me.jsx)(mT,{onLogIn:()=>this.loginViaPopup().catch(P=>z.warn(P.message))})})}),E)}(0,nn.render)((0,Me.jsx)(qo,{store:this.store,customStyles:r,children:(0,Me.jsx)(Io,{broadcastEvents:this.broadcastEvents,children:(0,Me.jsx)(VE,{})})}),this.createContainer("deepdesk-overlays")),this.store.dispatch(pd({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()})),this.store.dispatch(md(this.inputMediator.getSelection())),this.store.dispatch(ef(this.inputMediator.isFocused)),this.unmountHandlers.push(()=>{this.state.input.text!==""&&this.storeMetrics()}),this.whenConversationLoaded(()=>{var C;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((C=this.state.conversation.current)==null?void 0:C.sessionId)}),this.isMounted=!0}unmount(){var t;this.unmountHandlers.forEach(n=>n()),this.unmountHandlers=[],(t=this.inputMediator)==null||t.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(t,n={}){if(this.widgetRoot&&z.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:i}=n;this.widgetRoot=t,this.configure({showImages:o,isEmbedded:i}),(0,nn.render)((0,Me.jsx)(qo,{store:this.store,customStyles:r,children:(0,Me.jsx)(Io,{broadcastEvents:this.broadcastEvents,children:(0,Me.jsx)(NC,{onLogIn:()=>this.loginViaPopup().catch(s=>z.warn(s.message))})})}),t),this.whenConversationLoaded(()=>{var s;this.broadcastEvents.setSessionId((s=this.state.conversation.current)==null?void 0:s.sessionId)})}unmountWidget(){this.widgetRoot&&(0,nn.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(t){let n=Uf(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){ok(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(()=>R(this,null,function*(){yield this.store.dispatch(ll());let t=No(this.state);t&&(yield this.store.dispatch(rl()),this.store.dispatch(od({showSearch:t.search,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:!!t.summarizerAssistantNew||t.summarizer,showKnowledgeSearch:!!t.knowledgeAssistantNew||!!t.knowledgeAssistant,recommendTextSuggestions:t.recommendTextSuggestions})))})),this.loadProfileConfigPromise)}loginViaPopup(t){return R(this,null,function*(){return new Promise((n,r)=>{let o=new MessageChannel,i=o.port1,s=this.state.settings.adminUrl,a=new URL(t!=null&&t.url?t==null?void 0:t.url:`${s}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let l=!1,u=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",f),clearInterval(d)};i.onmessage=m=>R(this,null,function*(){var y,v;if((y=m.data)!=null&&y.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((v=m.data)==null?void 0:v.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(Qa),l=!0,o.port1.close(),n()}catch(p){console.error(p),r(p)}finally{l=!0,u()}});let c=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");c===null&&r(new Error("Popup blocked by browser"));let f=m=>R(this,null,function*(){var y;if(m.origin===a.origin)switch((y=m.data)==null?void 0:y.type){case"deepdesk-popup-loaded":{try{let v=JSON.stringify({type:"deepdesk-popup-create-channel"});c==null||c.postMessage(v,a.origin,[o.port2])}catch(v){z.error("Error posting message to popup",v),r(v)}break}case"deepdesk-popup-error":{u(),m.data.message==="Timeout"&&z.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(m.data.message));break}}});window.addEventListener("message",f);let d=setInterval(()=>{c&&!c.closed||(u(),l||r(new Error("Popup closed by user")))},200);this.unmountHandlers.push(u)})})}translateMessages(t){return this.deepdeskApi.translateMessages(t)}checkForTrialMode(t){return R(this,null,function*(){try{let{account:n}=yield this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(z.info("Trial is active"),!(yield this.deepdeskApi.checkUserExists(t)))throw new Error("User is not in trial");this.shouldRender=!0}catch(n){let{message:r}=n;z.info(r),this.shouldRender=!1}})}refreshWidgetSuggestions(){return R(this,null,function*(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=ul(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch(mn()):lu.includes(r)||this.store.dispatch(gn(r))})}catch(r){this.handleError(r)}})}};Os.version="14.3.1-beta.8",Os.count=0;var jl=Os;function nM(e){return R(this,null,function*(){var o,i,s;let n=yield((o=e.fetch)!=null?o:window.fetch)(e.url),r=yield n.blob();return new File([r],e.name,{type:(s=(i=e.mimeType)!=null?i:n.headers.get("Content-Type"))!=null?s:"image/jpeg"})})}function yk(e,t){return R(this,null,function*(){let n=yield nM(t),r=new Event("change",{bubbles:!0,cancelable:!0});try{Object.defineProperty(e,"files",{configurable:!0,get:()=>[n]}),e.dispatchEvent(r)}finally{Object.hasOwn(e,"files")&&delete e.files}})}function vk(e,t,n){return R(this,null,function*(){yield new yr(e).authenticateWithKey(t,n)})}function Sk(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function xk(r,o){return R(this,arguments,function*(e,t,n={}){var f,d;let{value:i}=e,{start:s,end:a}=(f=n.replace)!=null?f:{start:0,end:i.length},l=`${i.slice(0,s)}${t}${i.slice(a)}`,u=(d=n.selectionAfter)!=null?d:{start:s+t.length,end:s+t.length},c=()=>{if(n.setValue)return n.setValue(l);e.value=l};return Promise.resolve(c()).then(()=>{e.selectionStart=u.start,e.selectionEnd=u.end,e.blur(),e.focus()})})}function wk(r,o){return R(this,arguments,function*(e,t,n={}){let i=n.replace?no(e,n.replace.start,n.replace.end):Ps(e),s,a=()=>{if(n.setRange)return n.setRange(i.cloneRange());i.deleteContents(),s=document.createElement("span"),i.insertNode(s),n.insertBRs!==!1?t.split(`
|
|
27
|
+
`);let y=d?r:0,v=m?Math.min(i,c.childNodes.length):c.childNodes.length;for(let p=y;p<v&&(u(c.childNodes[p]),a!==2);p++);break}default:break}m&&(a=2)}return u(e),l}var MC=(s=>(s.CUT="Cut",s.BACKSPACE="Backspace",s.DELETE="Delete",s.ERASEEOF="EraseEof",s.UNDO="Undo",s.CLEAR="Clear",s))(MC||{}),hr=class{constructor(t){this.element=t;this.isFocused=!1;this.isActive=!0;this.isDisposed=!1;this.eventListeners={};this.disposeHandlers=[];this.cachedText="";this.cachedCaretPosition=null;this.cachedSelection={start:0,end:0};this.cachedHTML="";this.isSubmitting=!1;this.isPossibleClearInputAction=!1;this.cachedText=this.getText(),this.cachedHTML=this.getHTML(),this.cachedSelection=this.getSelection(),this.listen()}addEventListener(t,n){let r=o=>{n(o)};this.element.addEventListener(t,r),this.disposeHandlers.push(()=>{this.element.removeEventListener(t,r)})}removeEventListener(t,n){this.element.removeEventListener(t,n)}handleInteraction(){let t=this.getText(),n=this.getHTML(),r=this.getSelection(),o=this.cachedCaretPosition===null;if(!this.isActive||(t===""&&this.cachedText!==""&&!this.isPossibleClearInputAction&&this.emit("submit"),t!==this.cachedText?(this.cachedText=t,this.cachedHTML=n,o=!0,this.emit("change",{plainText:t,rawHTML:n})):n!==null&&n!==this.cachedHTML&&(this.cachedHTML=n,o=!0,this.emit("change",{plainText:t,rawHTML:n})),(r.start!==this.cachedSelection.start||r.end!==this.cachedSelection.end)&&(this.cachedSelection=r,o=!0,this.emit("selection",r)),!o))return;let i=this.getCaretPosition();$r(i,this.cachedCaretPosition)||(this.cachedCaretPosition=i,this.emit("caretposition",i))}handleClick(){this.handleInteraction()}handleFocus(){let t=!this.isFocused;this.isFocused=!0,t&&this.emit("focus"),this.handleInteraction()}handleBlur(){this.isPossibleClearInputAction=!1;let t=this.isFocused;this.isFocused=!1,t&&this.emit("blur")}handleKeyDown(t){let{key:n,ctrlKey:r,metaKey:o}=t;this.isPossibleClearInputAction=Object.values(MC).includes(n)||n.toLowerCase()==="z"&&(r||o),this.emit("keydown",t)}handleKeyUp(t){this.handleInteraction(),this.emit("keyup",t)}handleCut(){this.isPossibleClearInputAction=!0,this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(t){var r,o;let n=((r=t.clipboardData)==null?void 0:r.getData("text"))||((o=t.clipboardData)==null?void 0:o.getData("text/plain"))||"";this.emit("paste",{pastedText:n,selectionText:this.getSelectedText()})}listen(){this.addEventListener("keydown",n=>this.handleKeyDown(n)),this.addEventListener("keyup",n=>this.handleKeyUp(n)),this.addEventListener("input",()=>this.handleInteraction()),this.addEventListener("change",()=>this.handleInteraction()),this.addEventListener("focus",()=>this.handleFocus()),this.addEventListener("blur",()=>this.handleBlur()),this.addEventListener("cut",()=>this.handleCut()),this.addEventListener("paste",n=>this.handlePaste(n)),this.addEventListener("click",()=>this.handleInteraction()),document.activeElement===this.element&&(this.isFocused=!0);let t=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});t.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{t.disconnect()})}focus(){this.element.focus()}emit(t,...n){this.isDisposed||this.eventListeners[t]&&this.eventListeners[t].forEach(r=>{r(...n)})}on(t,n){this.isDisposed||(this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n))}activate(){let t=this.isActive===!1;this.isActive=!0,t&&this.handleInteraction()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(t=>t()),this.eventListeners={},this.isDisposed=!0}};function DC(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var Jo=class extends hr{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),Ul(this.element,n)}getHTML(){return this.element.innerHTML||""}getRange(){var s;let n=this.getRootNode();if(n.activeElement!==this.element)return null;let r="getSelection"in n?n.getSelection():window.getSelection();if(!r)return null;let o="getComposedRanges"in r&&n instanceof ShadowRoot?(s=r.getComposedRanges(n))==null?void 0:s[0]:r.rangeCount>0?r.getRangeAt(0):null;if(!o)return null;let i=this.element.ownerDocument.createRange();return i.setStart(o==null?void 0:o.startContainer,o==null?void 0:o.startOffset),i.setEnd(o==null?void 0:o.endContainer,o==null?void 0:o.endOffset),!i||!this.element.contains(i.startContainer)||!this.element.contains(i.endContainer)?null:i}getCaretPosition(){let n=this.getRange();if(!n||!n.collapsed||!("getBoundingClientRect"in n))return null;let r=n.getBoundingClientRect();return!DC(r)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),r=n.getBoundingClientRect(),n.deleteContents(),!DC(r))?null:{top:r.top+r.height,left:r.left}}getSelection(){let n=this.getRange();if(n)return Hl(this.element,n);let r=this.lastKnownSelection;if(r&&_C(this.element,r.start,r.end))return r;let o=Ps(this.element);return o.collapse(!1),Hl(this.element,o)}getSelectedText(){let{start:n,end:r}=this.getSelection();return Ul(this.element,no(this.element,n,r))}listen(){super.listen();let n=new MutationObserver(i=>{var s,a;i.length===2&&i[0].addedNodes.length===1&&((s=i[0].addedNodes[0])==null?void 0:s.textContent)==="\u2060"&&((a=i[1].removedNodes[0])==null?void 0:a.textContent)==="\u2060"||setTimeout(()=>{this.handleInteraction()},0)});n.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0}),this.disposeHandlers.push(()=>n.disconnect());let r=this.element.isContentEditable,o=new MutationObserver(()=>{this.element.isContentEditable!==r&&(r=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>o.disconnect())}};var j_=["direction","boxSizing","width","height","overflowX","overflowY","borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth","borderStyle","paddingTop","paddingRight","paddingBottom","paddingLeft","fontStyle","fontVariant","fontWeight","fontStretch","fontSize","fontSizeAdjust","lineHeight","fontFamily","textAlign","textTransform","textIndent","textDecoration","letterSpacing","wordSpacing","tabSize"];function FC(e,t){let n="mozInnerScreenX"in window,r=document.createElement("div");r.id="input-textarea-caret-position-mirror-div";let o=r.style,i=window.getComputedStyle(e),s=e.ownerDocument.body;o.whiteSpace="pre-wrap",o.wordWrap="break-word",o.position="absolute",o.visibility="hidden",j_.forEach(function(c){o[c]=i[c]}),n?e.scrollHeight>parseInt(i.height)&&(o.overflowY="scroll"):o.overflow="hidden",r.textContent=e.value.substring(0,t);let a=document.createElement("span");a.textContent=e.value.substring(t)||".",r.appendChild(a),s.appendChild(r);let l=e.getBoundingClientRect(),u={top:l.top-e.scrollTop+a.offsetTop+parseInt(i.borderTopWidth)+a.offsetHeight,left:l.left-e.scrollLeft+a.offsetLeft+parseInt(i.borderLeftWidth)};return s.removeChild(r),u}var ei=class extends hr{constructor(){super(...arguments);this.lastKnownSelection=null}getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:n,selectionEnd:r}=this.element;return{start:n,end:r}}getSelectedText(){let n=this.getSelection();return n?this.getText().slice(n.start,n.end):""}getCaretPosition(){return FC(this.element,this.element.selectionEnd)}listen(){super.listen();let n=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var i;return(i=n==null?void 0:n.get)==null?void 0:i.call(this.element)},set:i=>{var s;(s=n==null?void 0:n.set)==null||s.call(this.element,i),this.handleInteraction()}}),this.addEventListener("scroll",()=>{this.emit("caretposition",this.getCaretPosition())});let r=this.element.disabled,o=new MutationObserver(()=>{this.element.disabled!==r&&(r=this.element.disabled,this.emit(r?"disabled":"enabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>o.disconnect())}};function HC(e,t,n){let r=`deepdesk-iframe-${e}`,o=document.getElementById(r);if(o)return o;let i=document.createElement("iframe"),s=new URL(t);return Object.entries(n).forEach(([a,l])=>{s.searchParams.append(a,l)}),i.style.position="absolute",i.style.left="-999em",i.style.width="0px",i.style.height="0px",i.tabIndex=-1,i.id=r,i.title=`iframe-${e}`,i.src=s.toString(),window.document.body.appendChild(i),i}function B_(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(t){return e}}var Ay=class{constructor(t){this.name=t;this.disposeHandlers=[];this.broadcastChannel=new BroadcastChannel(t)}onMessage(t){this.broadcastChannel.addEventListener("message",t),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",t)})}postMessage(t){this.broadcastChannel.postMessage(JSON.stringify(t))}close(){this.disposeHandlers.forEach(t=>t()),this.broadcastChannel.close()}},Iy=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.disposeHandlers=[];this.iframe=HC(t,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}onMessage(t){window.addEventListener("message",t),this.disposeHandlers.push(()=>{window.removeEventListener("message",t)})}postMessage(t){var n;(n=this.iframe.contentWindow)==null||n.postMessage(JSON.stringify(t),this.targetOrigin)}close(){var t;this.disposeHandlers.forEach(n=>n()),(t=this.iframe)==null||t.remove()}},Oy=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.eventMap,this.sessionId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setSessionId(t){this.sessionId!==t&&(this.cleanup(),z.info("Set sessionId",t),this.sessionId=t,this.channel=this.createChannel(t))}createChannel(t){let n=this.params.createCustomChannel?this.params.createCustomChannel(t):this.isCrossOrigin?new Iy(t,this.deepdeskUrl,{debug:!0}):new Ay(t),r=o=>{var s,a;if(o.origin!==this.deepdeskUrl)return;let i=B_(o.data);typeof i!="object"||i.type!=="event"||i.channel!==t||(z.info("Received broadcast event",this.sessionId,o),(a=(s=this.eventMap)[i.name])==null||a.call(s,i.payload))};return n.onMessage(r),n}send(t,n,r){var s,a;z.info("Broadcast event",{sessionId:this.sessionId,name:t,payload:n});let o={type:"event",name:t,payload:n};r!==!1&&((a=(s=this.eventMap)[t])==null||a.call(s,n));let i=this.sessionId==="deepdesk-general"?this.defaultChannel:this.channel;i==null||i.postMessage(I(k({},o),{channel:this.sessionId}))}cleanup(t=!1){var n,r;(n=this.channel)==null||n.close(),delete this.channel,t&&((r=this.defaultChannel)==null||r.close(),delete this.defaultChannel)}},UC=Oy;function V_(e){return e.replace(/(_\w)/g,t=>t[1].toUpperCase())}function he(e){return Array.isArray(e)?e.map(he):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>I(k({},t),{[V_(n)]:he(e[n])}),{}):e}function W_(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function qe(e){return Array.isArray(e)?e.map(qe):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>I(k({},t),{[W_(n)]:qe(e[n])}),{}):e}var Ls=class extends Error{constructor(n,r){super(n);this.body=r;this.name="CustomError"}};var Ny=e=>new Promise(t=>{setTimeout(t,e)});var As=class extends Ls{constructor(){super(...arguments);this.name="ClientError"}},My=class extends Ls{constructor(){super(...arguments);this.name="ServerError"}},_y=new Map;function K_(e){return R(this,null,function*(){if(e.status===204)return e.text().catch(()=>{}),null;let t=e.headers.get("content-type");if(t&&t.includes("application/json"))return e.json();let n=yield e.text();return n===""?null:(z.warn("Unexpected response body:",n.slice(0,20)),JSON.parse(n))})}var ro=class ro{constructor(t="",n={}){this.baseUrl=t;this.options=n;this.latestRequestByUrl={};this.fetch=window.fetch.bind(window);n.fetch&&(this.fetch=n.fetch)}patchFetch(t){this.fetch=t(this.fetch)}setCsrfToken(t){this.csrfToken=t}request(t,n={}){return new Promise((r,o)=>{let i={isAborted:!1,reject:o},s=`${this.baseUrl}${t}`,a=this.fetch,l=n.method===void 0||n.method.toLowerCase()==="get",E=n,{useCache:u=!1,abortLatest:c=!1,attempts:f=1,retryDelay:d=500,refreshTokenOn401:m=!0,retryOnError:y=P=>P instanceof TypeError,retryOnResponse:v=P=>P.status>=500,version:p=null}=E,g=ee(E,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]);if(u)if(l){if(_y.has(s)){r(_y.get(s));return}}else throw new Error(`Can't use 'useCache' for ${n.method}`);let h=I(k({credentials:"include"},g),{headers:k({Accept:"application/json","Content-Type":"application/json"},g.headers)});!l&&this.csrfToken&&(h.headers=I(k({},h.headers),{"X-CSRFToken":this.csrfToken})),typeof p=="string"&&(h.headers=I(k({},h.headers),{"X-Deepdesk-API-Version":p}));let S=f,w=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[s]&&c&&(this.latestRequestByUrl[s].isAborted=!0,this.latestRequestByUrl[s].reject(new Error("Aborted"))),this.latestRequestByUrl[s]=i;let C=()=>R(this,null,function*(){return S--,a(s,h).then(P=>R(this,null,function*(){return v(P)&&!i.isAborted&&S>0?(yield Ny(d),C()):P.status===401&&m===!0&&w===!1?(w=!0,yield this.refreshToken(),C()):P})).catch(P=>R(this,null,function*(){if(y(P)&&!i.isAborted&&S>0)return yield Ny(d),C();throw P}))});C().then(P=>R(this,null,function*(){let N=yield K_(P);if(delete this.latestRequestByUrl[s],P.status>=500){o(new My("Server Error",N));return}else if(P.status===401){o(new As("Unauthorized",N));return}else if(P.status===403){o(new As("Forbidden",N));return}else if(P.status===404){o(new As("Not Found",N));return}else if(P.status>=400){o(new As("Bad Request",N));return}u&&_y.set(s,N),r(N)})).catch(P=>{o(P)})})}validateToken(){return R(this,null,function*(){let{has_valid_access_token:t}=yield this.get("/auth/validate");if(!t)try{yield this.refreshToken()}catch(r){return!1}let{is_logged_in:n}=yield this.get("/apis/admin/session/validate/");return!!n})}refreshToken(){return ro.refreshingToken||(ro.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{ro.refreshingToken=null},1e3*60)})),ro.refreshingToken}get(t,n){return this.request(t,n)}post(t,n,r){return this.request(t,k({method:"POST",body:JSON.stringify(n)},r))}patch(t,n,r){return this.request(t,k({method:"PATCH",body:JSON.stringify(n)},r))}put(t,n,r){return this.request(t,k({method:"PUT",body:JSON.stringify(n)},r))}delete(t,n){return this.request(t,k({method:"DELETE"},n))}};ro.refreshingToken=null;var ti=ro;var zC;(t=>{let e;(s=>(s.SEND_MESSAGE="Send Message",s.HANDLING_TIME="Handling Time",s.ADD_TO_PERSONAL_COLLECTION="Add to personal collection",s.DELETE_FROM_PERSONAL_COLLECTION="Delete from personal collection"))(e=t.EventType||(t.EventType={}))})(zC||(zC={}));function Nf(e){return I(k({},he(e)),{tags:e.tags})}var ni=class ni{constructor(t,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new ti(t,{fetch:n.fetch}),this.client.patchFetch(r=>(o,i)=>R(this,null,function*(){let s=yield r(o,i);return this.handleDeepdeskVersionHeaders(s),s}))}preflight(){return R(this,null,function*(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=yield this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(ni.exchangeTokenPromise||(ni.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),ni.exchangeTokenPromise):Promise.resolve()})}createConversation(t){return R(this,null,function*(){yield this.preflight(),z.info(`Creating conversation for session ${t.sessionId} and agent ${t.agentId}`);let n=yield this.client.post("/api/conversations",I(k({},qe(t)),{tags:t.tags}),{version:"v2"});return Nf(n)})}getMe(){return R(this,null,function*(){let t=yield this.client.get("/apis/admin/session/me/");return he(t)})}postIdentity(t){return R(this,null,function*(){yield this.client.post("/apis/admin/session/me/identities/",qe(t))})}patchMe(t){return R(this,null,function*(){let n=yield this.client.patch("/apis/admin/session/me/",qe(t));return he(n)})}getProfile(t){return R(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${t}/`,{useCache:!0});return he(n)})}getKnowledgeAssistant(t){return R(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{useCache:!0});return he(n)})}getContentTypes(){return R(this,null,function*(){let t=yield this.client.get("/apis/admin/content-types/",{useCache:!0});return he(t)})}getAccount(){return R(this,null,function*(){let t=yield this.client.get("/apis/admin/account/",{useCache:!0});return he(t)})}getPlatformConfig(t){return R(this,null,function*(){let n=t!==void 0?`/platform/config/${t}/`:"/platform/config/",{config:r}=yield this.client.get(n,{useCache:!0});return he(r)})}checkUserExists(t){return R(this,null,function*(){let{exists:n}=yield this.client.get(`/apis/admin/users/exists?external_id=${t}`,{version:"v1"});return n})}getConversationBySessionId(r){return R(this,arguments,function*(t,n={}){yield this.preflight(),z.info(`Getting conversation for session ${t}`);let{attempts:o=1,retryDelay:i=1e3}=n,s=yield this.client.get(`/api/conversations/by_session_id/${t}`,{attempts:o,retryDelay:i,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"});return z.info(`Successfully retrieved conversation ${s.id} for session ${t}`),Nf(s)})}isConversationSupported(r){return R(this,arguments,function*(t,n={}){z.info(`Check if conversation for session ${t} is supported`);let{attempts:o=1,retryDelay:i=1e3}=n;return(yield this.client.get(`/api/conversations/by_session_id/${t}/active_profile`,{attempts:o,retryDelay:i,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"})).has_active_profile})}updateConversation(t,n){return R(this,null,function*(){let r=qe(n);n.tags&&(r.tags=n.tags);let o=yield this.client.put(`/api/conversations/${t}`,r,{version:"v2"});return Nf(o)})}postMessages(t,n){return R(this,null,function*(){return(yield this.client.post(`/api/conversations/${t}/messages`,n.map(o=>I(k({},qe(o)),{tags:o.tags})),{version:"v2"})).map(o=>Nf(o))})}sendEvent(t,n){return R(this,null,function*(){let s=n,{data:r}=s,o=ee(s,["data"]),i=Object.entries(this.latestReceivedDeepdeskVersions).reduce((a,[l,u])=>I(k({},a),{[l]:u}),{});return this.client.post("/api/events",qe(I(k(k({},i),o),{data:r,name:t})),{version:"v2"})})}sendEventV1(t,n){return R(this,null,function*(){let r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((o,[i,s])=>I(k({},o),{[i]:s}),{});return this.client.post("/api/events",{event:t,data:qe(k(k({},n),r))},{version:"v1"})})}getEntities(t){return R(this,null,function*(){return(yield this.client.post("/api/entities",{messages:t.filter(r=>r.text)},{version:"v1"})).entities})}getTemporaryExchangeToken(){return R(this,null,function*(){return(yield this.client.get("/auth/exchange-token")).jwt})}exchangeTokenForAccessCookie(t){return R(this,null,function*(){return this.client.post("/apis/admin/session/jwt/",{jwt:t}).catch(n=>{throw z.warn(`Invalid token '${t}'`),n})})}authenticateWithKey(t,n){return R(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/api-key/",qe(n),{refreshTokenOn401:!1,headers:{apikey:t}})})}getTextSuggestions(o){return R(this,arguments,function*(t,n={},r){return r==="sticky-messages"?this.getPinnedMessages(t):(yield this.client.post(`/api/conversations/${t}/recommend/${r}`,qe(n),{abortLatest:!0,version:"v1"})).map(s=>I(k({},he(s)),{text:s.text||s.url||s.message,source:r,type:r})).filter((s,a,l)=>a===l.findIndex(u=>u.text===s.text))})}isLoggedIn(){return R(this,null,function*(){return yield this.preflight(),this.client.validateToken()})}getAutocompleteSuggestions(t,n){return R(this,null,function*(){return(yield this.client.post(`/api/conversations/${t}/autocomplete`,qe(n),{abortLatest:!0,version:"v1"})).map(o=>({score:1,source:o.source,sourceText:o.source_text,text:o.label,trainingJobs:o.training_jobs,searchKeywords:o.search_keywords,type:o.source})).filter((o,i,s)=>i===s.findIndex(a=>a.text===o.text))})}getPinnedMessages(t){return R(this,null,function*(){let n=yield this.client.get(`/api/conversations/${t}/sticky-messages`,{abortLatest:!0,version:"v1"});return he(n).map(r=>I(k({},r),{text:r.message,source:"sticky-messages",type:"pinned-message"}))})}getStyleSuggestions(t){return R(this,null,function*(){let n=yield this.client.post("/api/style-suggestions",qe(t),{abortLatest:!0,version:"v1"});return he(n)})}search(t){return R(this,null,function*(){let n=yield this.client.post(`/api/profiles/${t.profile}/search`,qe(t),{version:"v2"});return he(n)})}knowledgeAssist(i,s,a){return R(this,arguments,function*(t,n,r,o={}){let l=yield this.client.post(`/api/knowledge-assist/assistants/${r}/search`,qe({question:t.question,doNotKnowAnswer:t.doNotKnowAnswer,customerInstruction:t.customerInstruction,chatHistory:n.map(u=>({question:u.question,answer:u.answer.answer})),agentId:o.agentId,conversationId:o.conversationId}),{version:"v2"});return he(l)})}requestLoginByEmail(t){return R(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:t});return he(n)})}requestPasswordlessToken(){return R(this,null,function*(){let t=yield this.client.get("/apis/admin/session/passwordless/request/");return he(t.token)})}getCsrfToken(){return R(this,null,function*(){let{token:t}=yield this.client.get("/apis/admin/session/csrf/");return t})}verifyLoginToken(t){return R(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/login/",{token:t});return he(n)})}evaluateRule(i,s,a){return R(this,arguments,function*(t,n,r,o={}){let l=new URLSearchParams;o.raiseForFailingConditions&&l.set("raise_for_failing_conditions","true");let u=yield this.client.post(`/api/conversations/${n}/rules/${t}/evaluate?${l.toString()}`,r,{version:"v2"});return u?he(u.cues):[]})}getSummary(r){return R(this,arguments,function*(t,n={}){let o=yield this.client.post("/api/summary",{conversation:{messages:t.filter(i=>i.text&&i.source),agent_id:n.agentId,id:n.externalConversationId},prompt_instruction:n.promptInstruction,model:n.model},{version:"v1"});return he(o)})}evaluateAssistant(t,n){return R(this,null,function*(){var a;let r=new URLSearchParams,{expectFormat:o="text"}=n||{};if(o.startsWith("json-schema:")){let l=o.replace("json-schema:","");r.append("expect_response_format","json-schema"),r.append("expect_response_format_schema",l)}else r.append("expect_response_format",o);n!=null&&n.externalConversationId&&r.append("external_conversation_id",n.externalConversationId);let i=n!=null&&n.threadId?`/api/v2/assistants/${t}/threads/${n==null?void 0:n.threadId}/evaluate?${r.toString()}`:`/api/v2/assistants/${t}/evaluate?${r.toString()}`,s=yield this.client.post(i,{input:(a=n==null?void 0:n.input)!=null?a:{},conversation:n==null?void 0:n.transcript});return he(s.output)})}createAssistantThread(t){return R(this,null,function*(){let{assistantCode:n}=t,r=yield this.client.post(`/apis/admin/assistants/${n}/threads/`,{});return he(r)})}postMessageToAssistantThread(t){return R(this,null,function*(){let{assistantCode:n,threadId:r,message:o}=t,i=yield this.client.post(`/apis/admin/assistants/${n}/threads/${r}/messages/`,{content:o,role:"user"});return he(i)})}getRules(){return R(this,null,function*(){let t=new URLSearchParams,n=yield this.client.get(`/apis/admin/rule-engine/rules/?${t.toString()}`,{useCache:!0});return he(n)})}translateMessages(t){return R(this,null,function*(){let n=yield this.client.post("/api/translate",qe(t),{version:"v2"});return he(n)})}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),i=o.match(i0);if(!n||!i)return;let s=i[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[s];a&&n&&a!==n&&z.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[s]=n})}};ni.exchangeTokenPromise=null;var yr=ni;var jC={startTime:null,stopTime:null},BC=e=>e.handlingTime,VC=ne({name:"handlingTime",initialState:jC,reducers:{handlingTimeStart(e){if(e.startTime&&!e.stopTime)throw new Error("Timing already started");e.startTime=new Date,e.stopTime=null},handlingTimeStop(e){if(!e.startTime)throw new Error("Timing not started");e.stopTime=new Date},handlingTimeReset(e){e.startTime=null,e.stopTime=null}},extraReducers:e=>{e.addCase(Ae,()=>jC)}}),{handlingTimeStart:WC,handlingTimeStop:_f,handlingTimeReset:KC}=VC.actions,$C=VC.reducer;var qC=(e={})=>{let t=k({onAuthError:os(!1)},e);return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var Mf={list:{keywordMatches:[]},fetchState:"idle"};var ri=X("styleSuggestions/getAll",(n,r)=>R(void 0,[n,r],function*({text:e},t){var l;let{deepdeskAPI:o}=t.extra,i=t.getState(),{showStyleSuggestions:s}=i.settings,a=(l=i.conversation.current)==null?void 0:l.profileCode;if(!s)return Mf.list;if(!a)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:a,message:e})})),$_=ne({name:"styleSuggestions",initialState:Mf,reducers:{},extraReducers:e=>{e.addCase(ri.pending,t=>{t.fetchState="loading"}).addCase(ri.rejected,t=>{t.fetchState="error"}).addCase(ri.fulfilled,(t,n)=>{t.fetchState="done",$r(t.list,n.payload)||(t.list=n.payload)}).addCase(Lo,t=>{t.list=Mf.list}).addCase(Ae,()=>Mf)}}),GC=$_.reducer;var YC=(e={})=>{let t,n=!0,r=k({getStyleSuggestions:ri,debounce:500},e);return o=>i=>s=>{var m;let a=o.getState().input.text,l=i(s),u=o.getState();if(u.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:c}=u.settings;if(!((m=u.conversation.current)==null?void 0:m.id)||!c)return l;let{text:d}=u.input;return d===a&&!n||(clearTimeout(t),d==="")||(t=setTimeout(()=>{n=!1,o.dispatch(r.getStyleSuggestions({text:d}))},e.debounce)),l}};function q_(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var QC=(e={})=>{let t=k({getTextSuggestions:gn,getAutocompleteSuggestions:El,debounce:200,check:_n},e),n;return r=>o=>i=>{var v;let{input:s}=r.getState(),a=o(i),l=r.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:u,showTabCompletion:c}=l.settings,f=(v=l.conversation.current)==null?void 0:v.id,d=i.type===Xd.toString();if(!f||!u&&!c)return a;let{input:m}=l;return q_(m,s)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let p=ss(l);p===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(p))},d?0:t.debounce)),a}};var XC=ri.fulfilled.toString();function G_(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let i=e.keywordMatches.filter(l=>l.keyword===o),s=t.keywordMatches.filter(l=>l.keyword===o),a=s.length-i.length;a<=0||r.push(...s.slice(0,a))}),r}var ZC=e=>t=>n=>r=>{var u;if(r.type!==XC){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let i=t.getState(),s=i.styleSuggestions.list,a=(u=i.conversation)==null?void 0:u.current;if(o===s)return;let l=G_(o,s);r.type===XC&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var Y_=Pc({assistants:jb,auth:P1,conversation:U1,contentTypes:Vb,passwordlessToken:HT,entities:hE,knowledgeAssistant:Db,handlingTime:$C,info:ib,input:X1,settings:w1,profile:Kb,search:db,styleSuggestions:GC,ui:JE,rules:VT,textSuggestions:FE});function JC(e){return Rw({reducer:Y_,middleware:t=>[...t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI}},serializableCheck:!1}),qC(),QC({debounce:200}),YC({debounce:500}),ZC(e.deepdeskAPI),...e.middleware?e.middleware:[]],preloadedState:e.preloadedState})}var Q_=e=>{var t,n;return(n=(t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())!=null?n:"unknown"},X_=e=>t=>n=>r=>{var a,l,u,c,f,d,m;let o=t.getState(),i=th("inlineSuggestions")(o);switch(r.type){case os.toString():{!r.payload&&e.emit("logout",void 0);break}case mn.fulfilled.toString():r.payload.length>0&&e.sendEvent("entities found",{conversationId:(a=o.conversation.current)==null?void 0:a.id,data:{entities:r.payload}});break;case Gt.toString():e.sendEvent(r.payload.name,{conversationId:((l=r.payload.options)==null?void 0:l.includeConversationData)&&((u=o.conversation.current)==null?void 0:u.id),data:r.payload.data});break;case Lo.toString():e.logSendMessage(r.payload);break;case Yo.fulfilled.toString():r.isBroadcasted||e.broadcast(ch,r,!1),(c=r.payload.options)!=null&&c.shouldEmit&&e.emit("cues",r.payload.cues);break;case _d.toString():e.emit("call-to-action",{cue:r.payload});break;case rr.fulfilled.toString():r.isBroadcasted||e.broadcast(dh,r,!1);break;default:break}let s=n(r);switch(r.type){case Lo.toString():e.handleAfterSendMessage(r.payload);break;case Cl.toString():e.onUpdateShowTabHint(r.payload);break;case _f.toString():e.logHandlingTime();break;case"analytics/logEvent/fulfilled":{e.emit("event",r.meta.arg);break}case cd.toString():{let{start:y,end:v}=o.input.selection;e.emit("replace",I(k({},r.payload),{replace:r.payload.replace==="selection"?{start:y,end:v}:{start:0,end:v}}));break}case un.toString():{let{start:y,end:v}=o.input.selection;e.emit("select-suggestion",I(k({type:Q_(r.payload.suggestion)},r.payload),{replace:r.payload.replace==="selection"?{start:y,end:v}:{start:0,end:v}})),i&&t.dispatch(qr([]));break}case dd.toString():e.emit("select-image",r.payload),e.sendEvent("Image attached",{conversationId:(f=o.conversation.current)==null?void 0:f.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case qr.toString():{i&&r.payload.length>0&&t.dispatch(fd(0));break}case On.fulfilled.toString():{e.sendEvent("conversation summarized",{conversationId:(d=o.conversation.current)==null?void 0:d.id,data:{summary:r.payload,assistant:(m=t.getState().profile.data)==null?void 0:m.summarizerAssistantNew}});break}default:break}return s},ek=X_;function Dy(e){return e.toISOString().replace("T"," ").replace("Z","")}var Z_=(e,t)=>t.version,tk=ln([ls,An,BC,Z_],(e,t,n,r)=>{if(!t)return z.warn("No conversationId for handling time metrics"),null;let{startTime:o,stopTime:i}=n;return!o||!i?(z.warn("No startTime and stopTime for handling time metrics"),null):{conversationId:t,clientVersion:r,agentId:e==null?void 0:e.agentId,agentName:e==null?void 0:e.agentName,agentEmail:e==null?void 0:e.agentEmail,timeStart:Dy(o),timeStop:Dy(i)}});function nk(e,t,n){var N,_,q,B;let r=(N=t.conversation.current)==null?void 0:N.id;if(!r)return z.warn("No conversationId for send message metrics"),null;let{text:o,metrics:{numCharsTyped:i,numCharsPasted:s,numCharsCut:a,numCharsDeleted:l,numPaste:u,agentStartedTypingTimestamp:c,externalTimeTotalSeconds:f,pastes:d,cuts:m,deletions:y,textSuggestions:v,offeredTextSuggestions:p}}=t[e],g=o.length,S=v.reduce((V,{text:fe,searchTerm:Ge})=>V+fe.length-(Ge?Ge.length:0),0),w=c!=null?c:Date.now(),C=(Date.now()-w)/1e3+(f||0),E=i/C,P=v.reduce((V,{searchTerm:fe})=>V+(fe?fe.length:0),0);return{conversationId:r,source:"agent",text:o,clientVersion:n.version,pastes:d,cuts:m,deletions:y,lenTextTyped:i+P,lenTextTotal:g,lenTextAssisted:S,lenTextPasted:s,lenTextCut:a,lenTextDeleted:l,timeTotalSeconds:C,charsPerSecond:E,numPastes:u,textSuggestionsV2:v,suggestionsCounters:[{source:"gpt",countOffered:p.filter(V=>V.source==="gpt").length}],agentId:(_=t.info.agentInfo)==null?void 0:_.agentId,agentName:(q=t.info.agentInfo)==null?void 0:q.agentName,agentEmail:(B=t.info.agentInfo)==null?void 0:B.agentEmail}}function Fy(e,t){var i;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return Fy(r,t);let o=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;return o?Fy(o,t):null}function rk(e,t){return Fy(e,t)}function ok(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function J_(e){return typeof e=="object"&&e!==null&&"tagName"in e}function Df(e){return J_(e)&&(Go(e)||af(e))}var sk,Hn=new Map,eM=["bottom","height","left","right","top","width"],ik=(e,t)=>!e&&!t?!1:e&&!t||!e&&t?!0:eM.some(n=>e[n]!==t[n]);function ak(e){var n,r,o;if(e.ownerDocument===document)return[];let t=(o=(r=(n=e.ownerDocument)==null?void 0:n.defaultView)==null?void 0:r.frameElement)!=null?o:null;return t?[t,...ak(t)]:[]}function lk(e,t){return!e||!t?null:I(k({},e),{top:e.top+t.top,left:e.left+t.left})}var Ff=!1,uk=()=>{Ff=!0;let e=[];if(Hn.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),Hn.delete(n);return}let r=n.getBoundingClientRect();ik(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(lk,t.rect):t.rect;ik(n,t.totalRect)&&t.callbacks.forEach(r=>r(n)),t.totalRect=n}),Hn.size===0){Ff=!1;return}sk=window.requestAnimationFrame(uk)};function Hy(e,t){let n=ak(e),r=[],o=n.map((i,s)=>Hy(i,a=>{r[s]=a;let l=Hn.get(e);if(!l)return;let u=r.reduce(lk,l.rect);l.callbacks.forEach(c=>c(u))}));return{observe(i=!0){if(o.forEach(s=>s.observe(!1)),Hn.has(e)){let s=Hn.get(e);s.callbacks.push(t),s.rect&&t(s.rect)}else Hn.set(e,{rect:void 0,callbacks:[t],parentRects:r});i&&!Ff&&uk()},unobserve(){o.forEach(s=>s.unobserve());let i=Hn.get(e);if(i){let s=i.callbacks.indexOf(t);s>=0&&i.callbacks.splice(s,1),i.callbacks.length||Hn.delete(e),Hn.size||(cancelAnimationFrame(sk),Ff=!1)}}}}var ck,Un=new Map,dk=()=>{Un.forEach((e,t)=>{if(!t.isConnected){Un.delete(t);return}let{clientHeight:n,scrollHeight:r}=t,o=r>n;e.visible!==o&&(e.visible=o,e.callbacks.forEach(i=>i(e.visible)))}),Un.size!==0&&(ck=window.requestAnimationFrame(dk))};function fk(e,t){return{observe(){let n=Un.size===0;Un.has(e)?Un.get(e).callbacks.push(t):Un.set(e,{visible:void 0,callbacks:[t]}),n&&dk()},unobserve(){let n=Un.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||Un.delete(e),Un.size||cancelAnimationFrame(ck)}}}}var Uy=["borderLeftWidth","borderRightWidth","borderTopWidth","borderBottomWidth","borderStyle","boxSizing","color","overflowWrap","fontFamily","fontSize","fontSizeAdjust","fontStretch","fontWeight","fontKerning","lineHeight","letterSpacing","paddingLeft","paddingTop","paddingRight","paddingBottom","width","height","textIndent","whiteSpace","wordBreak","wordSpacing","wordWrap"];function zy(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function Is(e){return parseFloat(e)}function Hf(e){return Math.round(e*1e6)}function pk(e){return e/1e6}function jy(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=Is(e.width),i=Is(e.borderLeftWidth),s=Is(e.borderRightWidth),a=Is(e.paddingRight),l=pk(Hf(o)-Hf(i)-Hf(s)),u=pk(Hf(r));if(l-u>2){let c=l-u;n.style.paddingRight=`${a+c}px`}}function zl(e,t={}){var c,f;let n=t.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=(c=t.position)!=null?c:"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",Ko(n);let r=window.getComputedStyle(e),o=!0,i=()=>{n.scrollTop=e.scrollTop};zy(r,n,Uy),jy(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",i));let s=fk(e,()=>{zy(r,n,Uy),jy(r,e,n),i(),setTimeout(i,0)}),a,l=!0,u=Hy(e,d=>{if(d===null){t.onRemove&&t.onRemove(),n.remove();return}if(!l&&t.onMoveStart&&(Promise.resolve().then(()=>t.onMoveStart()),l=!0),clearTimeout(a),a=setTimeout(()=>{t.onMoveEnd&&t.onMoveEnd(),l=!1},200),d.height===0&&d.width===0){if(o===!0)return;t.onHide&&t.onHide(),n.style.display="none",o=!0;return}if(zy(r,n,Uy),jy(r,e,n),i(),n.style.top=`${d.top}px`,n.style.left=`${d.left}px`,t.closestScrollElement&&t.closestScrollElement!==e){let m=t.closestScrollElement.getBoundingClientRect(),y=window.getComputedStyle(t.closestScrollElement),v=Is(y.borderTopWidth),p=Is(y.borderBottomWidth),g=m.top+v-d.top,h=d.top+d.height+-(m.top+m.height-p);n.style.clipPath=`inset(${g}px 0px ${h}px 0px)`}o&&(n.style.display="block",t.onShow&&t.onShow(),o=!1)});return t.appendTo?t.appendTo.appendChild(n):(f=e.parentElement)==null||f.appendChild(n),u.observe(),s.observe(),[n,()=>{e.removeEventListener("scroll",i),u.unobserve(),s.unobserve()}]}var mk=(e,t)=>({value(){try{let n=sessionStorage.getItem(`dd-${e}`);if(!n)return t;try{return JSON.parse(n)}catch(r){return t}}catch(n){return t}},update(n){try{sessionStorage.setItem(`dd-${e}`,JSON.stringify(n))}catch(r){z.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function tM(e){return e.offsetParent!==null}function gk(e){if(!tM(e))return!1;let t=e.getBoundingClientRect();return t.top>=0&&t.left>=0&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&t.right<=(window.innerWidth||document.documentElement.clientWidth)}function Uf(e,t,n=100){let r=gk(e);t({isVisible:r});let o=setInterval(()=>{let i=gk(e);i!==r&&(r=i,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var Me=x(T());var hk=mk("showTabHint",!0),Os=class Os{constructor({deepdeskUrl:t,version:n=Os.version||"unknown",locale:r="en-US",token:o,fetch:i,productName:s,createCustomChannel:a}){this.inputMediator=null;this.eventListeners={};this.unmountHandlers=[];this.widgetRoot=null;this.dynamicThunkObject={};this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;let l=t.replace(/\/api$/,"");this.deepdeskApi=new yr(l,{token:o,fetch:i}),this.version=n,this.instanceId=Os.count++;let u={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[ek({broadcast:(c,f,d)=>{this.broadcastEvents.send(c,f,d)},emit:(c,f)=>this.emit(c,f),handleAfterSendMessage:c=>this.handleAfterSendMessage(c),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:c=>this.logSendMessage(c),onUpdateShowTabHint:c=>hk.update(c),sendEvent:(c,f)=>this.deepdeskApi.sendEvent(c,f)})]};this.store=JC(u),this.broadcastEvents=new UC({debug:!0,deepdeskUrl:l,eventMap:fb(this.store),createCustomChannel:a}),this.store.dispatch(Cl(hk.value())),this.store.dispatch(od({locale:r,adminUrl:l,productName:s}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){var t;return(t=this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex])!=null?t:null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(z.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(z.warn("Profile has not been loaded (yet)"),!0):(z.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(os(null)),this.store.dispatch(er()),new Promise(t=>{let n=this.store.subscribe(()=>{let r=this.store.getState();ct(r)&&b1(r)!=="loading"&&(n(),t())});this.unmountHandlers.push(()=>{n()})})}isLoggedIn(){return R(this,null,function*(){return(yield this.store.dispatch(er())).payload})}isConversationSupported(t,n){return R(this,null,function*(){return(yield this.store.dispatch(oh({sessionId:t,options:n}))).payload})}createConversation(t){return R(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(yield this.store.dispatch(sd(t))).payload})}getConversationBySessionId(t,n){return R(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(yield this.store.dispatch(ad({sessionId:t,options:n}))).payload})}upsertConversation(t){return R(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(yield this.store.dispatch(ih(t))).payload})}postMessages(t){return R(this,null,function*(){return(yield this.store.dispatch(ud(t))).payload})}updateConversation(t){return R(this,null,function*(){return(yield this.store.dispatch(ld(t))).payload})}resetConversation(){this.store.dispatch(Ae()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}configure(t){this.store.dispatch(od(t))}setVisitorInfo(t){this.store.dispatch(nb(t))}setCustomData(t){this.store.dispatch(rb(t))}setAgentInfo(t,n){return R(this,null,function*(){yield this.store.dispatch(Ga(k(k({},t),n)))})}setAgentSettings(t){return R(this,null,function*(){yield this.store.dispatch(ah(t))})}getAgentSettings(){return R(this,null,function*(){return(yield this.store.dispatch(lh())).payload})}refresh(){return R(this,null,function*(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.store.dispatch(pd({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()}));let t=[];return this.store.dispatch(Xd()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})})}notifyExternalSuggestion(t){this.store.dispatch(un(t))}evaluateRule(o){return R(this,arguments,function*(t,n={},r=UT){return(yield this.store.dispatch(Yo({label:t,params:n,options:r}))).payload.cues})}evaluateAssistant(t,n){return R(this,null,function*(){let c=n||{},{input:r={},transcript:o,showCuesInWidget:i=!0,includeTags:s,expectFormat:a}=c,l=ee(c,["input","transcript","showCuesInWidget","includeTags","expectFormat"]);Object.assign(r,l);let u=yield this.store.dispatch(rr({assistantCode:t,expectFormat:a||"json-schema:cues",transcript:o,includeTags:s,input:r,skipState:!i}));if(u.error)throw new Error(u.error.message);return u.payload})}evaluateConversationAssistant(t,n){return R(this,null,function*(){yield this.loadProfileConfig();let r={accepted:"conversationAcceptedAssistant","new-message":"conversationNewMessageAssistant",ended:"conversationEndedAssistant"},o=this.state.profile.data[r[t]];if(!o){z.warn(`No assistant set in profile for conversation event "${t}"`);return}yield this.evaluateAssistant(o,k({transcript:"stored-transcript",includeTags:!0},n))})}getSummary(){return R(this,null,function*(){var n;if(!this.hasConversation())return z.warn("No conversation to create summary for."),null;(n=this.state.profile.data)!=null&&n.summarizerAssistantNew||z.warn("No profile loaded yet, or no summarizer assistant set in profile");let t=yield this.store.dispatch(On({}));if(t.error)throw new Error(t.error.message);return t.payload})}handleKeyDown(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui,{textSuggestions:o,selectedSuggestionIndex:i,selection:s}=this.state.input,{inlineSuggestions:a,showTextSuggestions:l}=this.state.settings,u=a?"below":"above",c=o.length>0;if(!_n(this.state)||(this.store.dispatch(W1(sh(t))),t.key!=="Tab"&&!l))return;let f=()=>{n||!c||s&&(t.shiftKey||(this.store.dispatch(q1()),t.preventDefault()))},d=()=>{n||!c||a&&i<=0||s&&(t.shiftKey||(this.store.dispatch(G1()),t.preventDefault()))};switch(t.key){case"ArrowUp":u==="below"?d():f();break;case"ArrowDown":{u==="below"?f():d();break}case"Escape":{n||(this.store.dispatch(fd(-1)),this.store.dispatch(Jr({collapse:!0})),this.store.dispatch(XE(!0)),t.preventDefault());break}case"Tab":{t.preventDefault();let m=as(this.state);if(!m)return;this.store.dispatch(Cl(!1)),this.store.dispatch(un({text:m.text,suggestion:m,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(this.state.settings.inlineSuggestions||this.state.input.selectedSuggestionIndex===-1)return;let m=as(this.state);if(!m)return;this.store.dispatch(un({text:m.text,suggestion:m,eventMetrics:{inputType:"space"},replace:"until-selection-end"}));break}case"Enter":{if(this.state.settings.inlineSuggestions||t.shiftKey||this.state.input.selectedSuggestionIndex===-1)return;let m=as(this.state);if(!m)return;this.store.dispatch(un({text:m.text,suggestion:m,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),t.preventDefault();break}default:}n&&r&&this.store.dispatch(Jr({collapse:!1}))}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(qr([]))}handlingTimeStart(){this.state.handlingTime.startTime||(z.info("Start handling time"),this.store.dispatch(WC()))}handlingTimeStop(){this.state.handlingTime.startTime&&(z.info("Stop handling time"),this.store.dispatch(_f()))}logSendMessage(t){let n=nk("input",this.state,{version:this.version});n&&(t&&(Object.assign(n,{text:t}),Object.assign(n,{lenTextTotal:t.length})),this.deepdeskApi.sendEventV1("Send Message",n),this.emit("send-message-event",n))}logHandlingTime(){let t=tk(this.state,{version:this.version});t&&(this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch(KC()))}notifySubmit(t={}){var n;this.shouldAbort()||(this.store.dispatch(Lo((n=t.text)!=null?n:this.state.input.text)),this.store.dispatch(Q1()))}emit(t,n){let r=this.eventListeners[t];r&&r.forEach(o=>{try{o(n)}catch(i){z.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),z.error(i)}})}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),()=>{this.off(t,n)}}off(t,n){if(!t&&!n){this.eventListeners={};return}let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}setConversationQuery(t){this.dynamicThunkObject.conversationQuery=t}setPlatformVariables(t){this.store.dispatch(ob(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]=zl(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),this.unmountHandlers.push(()=>{(0,nn.unmountComponentAtNode)(i),s(),i.remove()}),i}createInlineContainer(t,n){var a;let r=document.createElement("div");r.style.position="absolute",r.style.top="0px",r.style.left="0px",r.style.height="0px",r.style.width="0px";let o=document.createElement("div");o.style.display="none",o.style.position="absolute",o.style.height="0px",o.style.width="0px",o.style.backgroundColor="red",r.appendChild(o);let i=(a=t.ownerDocument.defaultView)==null?void 0:a.frameElement,s=i?i.ownerDocument.defaultView:null;if(i&&(s===window||(s==null?void 0:s.parent)===window)){let[l,u]=zl(i,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});l.dataset.testid=n,l.style.zIndex="2",l.appendChild(r),this.unmountHandlers.push(()=>{(0,nn.unmountComponentAtNode)(o),u()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return Ko(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,nn.unmountComponentAtNode)(o),o.remove()}),o}storeMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(t,n),z.info(`Stored analytics for ${this.conversationId()}`)}catch(t){}}restoreMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=window.sessionStorage.getItem(t);if(!n)return;let r=JSON.parse(n);r.text.trim()===this.state.input.text.trim()?(z.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(Y1(r.metrics))):z.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(t)}catch(t){}}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!Df(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:f,detectSubmit:d,insertLink:m,inputMediator:y,closestScrollSelector:v,appendOverlayTo:p,inlineSuggestions:g,floatingMenu:h}=n;this.configure({showStyleSuggestions:o,showTabCompletion:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,showTextSuggestions:s,insertLink:m,isEmbedded:f,inlineSuggestions:g,floatingMenu:!!h}),n.automaticHandlingTime&&this.setupHandlingTime(t),Ko(t),this.inputMediator=y||(Go(t)?new ei(t):new Jo(t)),this.inputMediator.on("change",({plainText:C,rawHTML:E})=>{this.store.dispatch(pd({text:C,html:E}))}),this.inputMediator.on("keyup",C=>{this.store.dispatch(K1(sh(C)))}),this.inputMediator.on("keydown",C=>{this.handleKeyDown(C)}),this.inputMediator.on("paste",({pastedText:C,selectionText:E})=>{this.store.dispatch($1({text:C,selectionText:E}))}),this.inputMediator.on("cut",({selectionText:C})=>{this.store.dispatch(V1(C))});let S;this.inputMediator.on("selection",C=>{clearTimeout(S),C===null?S=setTimeout(()=>{C!==null&&this.store.dispatch(md(C))},500):this.store.dispatch(md(C))}),this.inputMediator.on("disabled",()=>{var C;(C=this.inputMediator)==null||C.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(ef(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(ef(!0))});let w=v&&rk(t,v)||void 0;if(g){let{customStyles:C,appendOverlayTo:E}=n,P=this.createInlineContainer(t,"deepdesk-caret");(0,nn.render)((0,Me.jsx)(qo,{store:this.store,customStyles:C,children:(0,Me.jsx)(Io,{broadcastEvents:this.broadcastEvents,children:(0,Me.jsx)(iT,{})})}),P),this.inputMediator.on("caretposition",_=>{_?(P.style.display="block",P.style.top=`${_.top}px`,P.style.left=`${_.left}px`):P.style.display="none"});let N=this.overlayContainerFactory("floating-menu",w||t,{appendTo:typeof h=="object"&&"appendOverlayTo"in h?h.appendOverlayTo:E},C==null?void 0:C.floatingMenuRootNode);(0,nn.render)((0,Me.jsx)(qo,{store:this.store,customStyles:C,children:(0,Me.jsx)(Io,{broadcastEvents:this.broadcastEvents,children:(0,Me.jsx)(GE,{onLogIn:()=>this.loginViaPopup().catch(_=>z.warn(_.message))})})}),N)}else{let C=this.overlayContainerFactory("deepdesk-tab-completion",w||t,{appendTo:p,closestScrollElement:w,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),E=this.overlayContainerFactory("deepdesk-suggestions-overlay",w||t,{appendTo:p},r==null?void 0:r.suggestionsRootNode);(0,nn.render)((0,Me.jsx)(qo,{store:this.store,customStyles:r,children:(0,Me.jsx)(Io,{broadcastEvents:this.broadcastEvents,children:(0,Me.jsx)(MT,{inputElement:t})})}),C),(0,nn.render)((0,Me.jsx)(qo,{store:this.store,customStyles:r,children:(0,Me.jsx)(Io,{broadcastEvents:this.broadcastEvents,children:(0,Me.jsx)(mT,{onLogIn:()=>this.loginViaPopup().catch(P=>z.warn(P.message))})})}),E)}(0,nn.render)((0,Me.jsx)(qo,{store:this.store,customStyles:r,children:(0,Me.jsx)(Io,{broadcastEvents:this.broadcastEvents,children:(0,Me.jsx)(VE,{})})}),this.createContainer("deepdesk-overlays")),this.store.dispatch(pd({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()})),this.store.dispatch(md(this.inputMediator.getSelection())),this.store.dispatch(ef(this.inputMediator.isFocused)),this.unmountHandlers.push(()=>{this.state.input.text!==""&&this.storeMetrics()}),this.whenConversationLoaded(()=>{var C;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((C=this.state.conversation.current)==null?void 0:C.sessionId)}),this.isMounted=!0}unmount(){var t;this.unmountHandlers.forEach(n=>n()),this.unmountHandlers=[],(t=this.inputMediator)==null||t.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(t,n={}){if(this.widgetRoot&&z.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:i}=n;this.widgetRoot=t,this.configure({showImages:o,isEmbedded:i}),(0,nn.render)((0,Me.jsx)(qo,{store:this.store,customStyles:r,children:(0,Me.jsx)(Io,{broadcastEvents:this.broadcastEvents,children:(0,Me.jsx)(NC,{onLogIn:()=>this.loginViaPopup().catch(s=>z.warn(s.message))})})}),t),this.whenConversationLoaded(()=>{var s;this.broadcastEvents.setSessionId((s=this.state.conversation.current)==null?void 0:s.sessionId)})}unmountWidget(){this.widgetRoot&&(0,nn.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(t){let n=Uf(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){ok(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(()=>R(this,null,function*(){yield this.store.dispatch(ll());let t=No(this.state);t&&(yield this.store.dispatch(rl()),this.store.dispatch(od({showSearch:t.search,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:!!t.summarizerAssistantNew||t.summarizer,showKnowledgeSearch:!!t.knowledgeAssistantNew||!!t.knowledgeAssistant,recommendTextSuggestions:t.recommendTextSuggestions})))})),this.loadProfileConfigPromise)}loginViaPopup(t){return R(this,null,function*(){return new Promise((n,r)=>{let o=new MessageChannel,i=o.port1,s=this.state.settings.adminUrl,a=new URL(t!=null&&t.url?t==null?void 0:t.url:`${s}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let l=!1,u=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",f),clearInterval(d)};i.onmessage=m=>R(this,null,function*(){var y,v;if((y=m.data)!=null&&y.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((v=m.data)==null?void 0:v.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(Qa),l=!0,o.port1.close(),n()}catch(p){console.error(p),r(p)}finally{l=!0,u()}});let c=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");c===null&&r(new Error("Popup blocked by browser"));let f=m=>R(this,null,function*(){var y;if(m.origin===a.origin)switch((y=m.data)==null?void 0:y.type){case"deepdesk-popup-loaded":{try{let v=JSON.stringify({type:"deepdesk-popup-create-channel"});c==null||c.postMessage(v,a.origin,[o.port2])}catch(v){z.error("Error posting message to popup",v),r(v)}break}case"deepdesk-popup-error":{u(),m.data.message==="Timeout"&&z.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(m.data.message));break}}});window.addEventListener("message",f);let d=setInterval(()=>{c&&!c.closed||(u(),l||r(new Error("Popup closed by user")))},200);this.unmountHandlers.push(u)})})}translateMessages(t){return this.deepdeskApi.translateMessages(t)}checkForTrialMode(t){return R(this,null,function*(){try{let{account:n}=yield this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(z.info("Trial is active"),!(yield this.deepdeskApi.checkUserExists(t)))throw new Error("User is not in trial");this.shouldRender=!0}catch(n){let{message:r}=n;z.info(r),this.shouldRender=!1}})}refreshWidgetSuggestions(){return R(this,null,function*(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=ul(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch(mn()):lu.includes(r)||this.store.dispatch(gn(r))})}catch(r){this.handleError(r)}})}};Os.version="14.3.1-beta.9",Os.count=0;var jl=Os;function nM(e){return R(this,null,function*(){var o,i,s;let n=yield((o=e.fetch)!=null?o:window.fetch)(e.url),r=yield n.blob();return new File([r],e.name,{type:(s=(i=e.mimeType)!=null?i:n.headers.get("Content-Type"))!=null?s:"image/jpeg"})})}function yk(e,t){return R(this,null,function*(){let n=yield nM(t),r=new Event("change",{bubbles:!0,cancelable:!0});try{Object.defineProperty(e,"files",{configurable:!0,get:()=>[n]}),e.dispatchEvent(r)}finally{Object.hasOwn(e,"files")&&delete e.files}})}function vk(e,t,n){return R(this,null,function*(){yield new yr(e).authenticateWithKey(t,n)})}function Sk(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function xk(r,o){return R(this,arguments,function*(e,t,n={}){var f,d;let{value:i}=e,{start:s,end:a}=(f=n.replace)!=null?f:{start:0,end:i.length},l=`${i.slice(0,s)}${t}${i.slice(a)}`,u=(d=n.selectionAfter)!=null?d:{start:s+t.length,end:s+t.length},c=()=>{if(n.setValue)return n.setValue(l);e.value=l};return Promise.resolve(c()).then(()=>{e.selectionStart=u.start,e.selectionEnd=u.end,e.blur(),e.focus()})})}function wk(r,o){return R(this,arguments,function*(e,t,n={}){let i=n.replace?no(e,n.replace.start,n.replace.end):Ps(e),s,a=()=>{if(n.setRange)return n.setRange(i.cloneRange());i.deleteContents(),s=document.createElement("span"),i.insertNode(s),n.insertBRs!==!1?t.split(`
|
|
28
28
|
`).reverse().forEach((l,u)=>{u>0&&i.insertNode(document.createElement("br")),i.insertNode(document.createTextNode(l))}):i.insertNode(document.createTextNode(t))};return Promise.resolve(a()).then(()=>{try{if(n.selectionAfter!==!1){e.focus();let l=n.selectionAfter?no(e,n.selectionAfter.start,n.selectionAfter.end):(i.collapse(!1),i),u=window.getSelection();u==null||u.removeAllRanges(),u==null||u.addRange(l)}if(!s)return;s.scrollIntoView&&s.scrollIntoView({block:"nearest",inline:"nearest"})}finally{s&&s.remove()}})})}function rM(e){let t=document.createElement("template");return t.innerHTML=e.replace(/(\[([^\]]+)])\(([^)]+)\)/g,'<a href="$3" target="_blank" rel="noopener noreferrer">$2</a>'),t.content}function oM(e){let t=document.createDocumentFragment();return e.split(`
|
|
29
29
|
`).forEach((n,r)=>{r>0&&t.appendChild(document.createElement("br"));let o={index:0},i=0;for(;o=n.slice(i).match(/(\[([^\]]+)])\(([^)]+)\)/);){let s=document.createElement("a");s.href=o[3],s.setAttribute("target","_blank"),s.setAttribute("rel","noopener noreferrer"),s.appendChild(document.createTextNode(o[2])),t.appendChild(document.createTextNode(n.slice(i,i+o.index))),t.appendChild(s),i=i+o.index+o[0].length}t.appendChild(document.createTextNode(n.slice(i)))}),t}function bk(e,t){let n=e.parentElement;if(!n){console.warn("No insert point found");return}let{display:r}=window.getComputedStyle(n);r.includes("block")||r==="table-cell"?n==null||n.insertBefore(t,e.nextSibling):bk(n,t)}function Ek(o,i){return R(this,arguments,function*(e,t,{isBlock:n,isHTML:r}={}){let s;e.dispatchEvent(new InputEvent("beforeinput",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0}));let a=()=>{var d;let l=(d=e.ownerDocument.defaultView)!=null?d:window,u=l.getSelection();if((!u||u.rangeCount===0)&&(e.focus(),u=l.getSelection()),!u||u.rangeCount===0)return;let c=u.getRangeAt(0);if(!c)return;s=document.createElement("span"),c.insertNode(s);let f=r?rM(t):oM(t);n?bk(c.startContainer,f):(c.insertNode(f),c.collapse(!1))};return Promise.resolve(a()).then(()=>{if(e.dispatchEvent(new InputEvent("input",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0})),e.focus(),!!s)try{s.scrollIntoView&&s.scrollIntoView({block:"nearest",inline:"nearest"})}finally{s&&s.remove()}})})}return Hk(iM);})();
|
|
30
30
|
/*! Bundled license information:
|