@deepdesk/deepdesk-sdk 10.3.1-beta.1 → 10.3.1-beta.3
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/dialogs.css +1 -1
- package/dist/index.cjs.js +6 -5
- package/dist/index.d.mts +69 -42
- package/dist/index.d.ts +69 -42
- package/dist/index.esm.js +6 -5
- package/dist/index.iife.js +13 -12
- package/input.css +1 -1
- package/package.json +5 -5
- package/styles/index.js +1 -1
- package/styles.css +1 -1
- package/widget.css +1 -1
package/dist/index.esm.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
var Vp=Object.defineProperty;var z=(t,e)=>{for(var o in e)Vp(t,o,{get:e[o],enumerable:!0})};import Yn from"classnames";import Qp,{createContext as Zp,useContext as es,useEffect as Jp,useState as Yp}from"react";import Wp,{useContext as Gp}from"react";import $p from"classnames";var Ot=Wp.createContext({});function y(t,e){let{debug:o,...n}=Gp(Ot),s=n[t];return s?Object.entries(e).reduce((r,[i,a])=>{let l=s[i];return{...r,[i]:$p(a,l,o?`${t}__${i}`:!1)}},{}):e}var Wr={root:"_root_vr71j_1"};import{jsx as vo,jsxs as Xp}from"react/jsx-runtime";var _o=()=>Xp("svg",{className:Wr.root,width:"185",height:"170",viewBox:"0 0 185 170",xmlns:"http://www.w3.org/2000/svg",children:[vo("defs",{children:vo("style",{children:".cls-1 { fill: #b3b3b3; }"})}),vo("title",{children:"Failed loading image"}),vo("path",{className:"cls-1",d:"M15 130.896V16.994c0-1.097.898-1.994 2.007-1.994h150.986A2 2 0 0 1 170 16.994v69.147L133.015 51 87.26 120.377l-35.863-17.758L15 130.896zM2 0C.895 0 0 .887 0 2v166c0 1.105.887 2 2 2h181c1.105 0 2-.887 2-2V2c0-1.105-.887-2-2-2H2zm49 72c11.046 0 20-9.178 20-20.5S62.046 31 51 31s-20 9.178-20 20.5S39.954 72 51 72z",fillRule:"evenodd"})]});var Jn={root:"_root_4e7lf_1",imageWrapper:"_imageWrapper_4e7lf_7",image:"_image_4e7lf_7",content:"_content_4e7lf_24",title:"_title_4e7lf_35",contentIsCropped:"_contentIsCropped_4e7lf_45",lineClamp:"_lineClamp_4e7lf_51"};import{jsx as tt}from"react/jsx-runtime";var xo=Zp(Jn),eu=({title:t,src:e})=>{let o=es(xo),[n,s]=Yp(!1);return Jp(()=>{s(!1)},[e]),tt("div",{className:o.imageWrapper,children:e&&!n?tt("img",{className:o.image,alt:t,src:e,onError:()=>s(!0)}):tt(_o,{})})},tu=({className:t,lineClamp:e=!1,cropText:o=!1,children:n})=>{let s=es(xo);return tt("div",{className:Yn(s.content,t,{[s.contentIsCropped]:o,[s.lineClamp]:e}),children:n})},ou=({as:t="h1",cropText:e=!1,className:o,children:n,...s})=>{let r=es(xo);return Qp.createElement(t,{className:Yn(r.title,o,{[r.contentIsCropped]:e}),...s},n)},bo=({children:t})=>{let e=y("Card",Jn);return tt("div",{className:Yn(e.root),children:tt(xo.Provider,{value:e,children:t})})};bo.Image=eu;bo.Content=tu;bo.Title=ou;var H=bo;var Gr={root:"_root_nkim0_1"};import{createContext as mu,useContext as fu}from"react";var ts=function(t,e){return ts=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(o,n){o.__proto__=n}||function(o,n){for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(o[s]=n[s])},ts(t,e)};function Dt(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");ts(t,e);function o(){this.constructor=t}t.prototype=e===null?Object.create(e):(o.prototype=e.prototype,new o)}var Z=function(){return Z=Object.assign||function(e){for(var o,n=1,s=arguments.length;n<s;n++){o=arguments[n];for(var r in o)Object.prototype.hasOwnProperty.call(o,r)&&(e[r]=o[r])}return e},Z.apply(this,arguments)};function $r(t,e){var o={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(o[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(o[n[s]]=t[n[s]]);return o}function Co(t,e,o){if(o||arguments.length===2)for(var n=0,s=e.length,r;n<s;n++)(r||!(n in e))&&(r||(r=Array.prototype.slice.call(e,0,n)),r[n]=e[n]);return t.concat(r||Array.prototype.slice.call(e))}var wo;(function(t){t[t.EXPECT_ARGUMENT_CLOSING_BRACE=1]="EXPECT_ARGUMENT_CLOSING_BRACE",t[t.EMPTY_ARGUMENT=2]="EMPTY_ARGUMENT",t[t.MALFORMED_ARGUMENT=3]="MALFORMED_ARGUMENT",t[t.EXPECT_ARGUMENT_TYPE=4]="EXPECT_ARGUMENT_TYPE",t[t.INVALID_ARGUMENT_TYPE=5]="INVALID_ARGUMENT_TYPE",t[t.EXPECT_ARGUMENT_STYLE=6]="EXPECT_ARGUMENT_STYLE",t[t.INVALID_NUMBER_SKELETON=7]="INVALID_NUMBER_SKELETON",t[t.INVALID_DATE_TIME_SKELETON=8]="INVALID_DATE_TIME_SKELETON",t[t.EXPECT_NUMBER_SKELETON=9]="EXPECT_NUMBER_SKELETON",t[t.EXPECT_DATE_TIME_SKELETON=10]="EXPECT_DATE_TIME_SKELETON",t[t.UNCLOSED_QUOTE_IN_ARGUMENT_STYLE=11]="UNCLOSED_QUOTE_IN_ARGUMENT_STYLE",t[t.EXPECT_SELECT_ARGUMENT_OPTIONS=12]="EXPECT_SELECT_ARGUMENT_OPTIONS",t[t.EXPECT_PLURAL_ARGUMENT_OFFSET_VALUE=13]="EXPECT_PLURAL_ARGUMENT_OFFSET_VALUE",t[t.INVALID_PLURAL_ARGUMENT_OFFSET_VALUE=14]="INVALID_PLURAL_ARGUMENT_OFFSET_VALUE",t[t.EXPECT_SELECT_ARGUMENT_SELECTOR=15]="EXPECT_SELECT_ARGUMENT_SELECTOR",t[t.EXPECT_PLURAL_ARGUMENT_SELECTOR=16]="EXPECT_PLURAL_ARGUMENT_SELECTOR",t[t.EXPECT_SELECT_ARGUMENT_SELECTOR_FRAGMENT=17]="EXPECT_SELECT_ARGUMENT_SELECTOR_FRAGMENT",t[t.EXPECT_PLURAL_ARGUMENT_SELECTOR_FRAGMENT=18]="EXPECT_PLURAL_ARGUMENT_SELECTOR_FRAGMENT",t[t.INVALID_PLURAL_ARGUMENT_SELECTOR=19]="INVALID_PLURAL_ARGUMENT_SELECTOR",t[t.DUPLICATE_PLURAL_ARGUMENT_SELECTOR=20]="DUPLICATE_PLURAL_ARGUMENT_SELECTOR",t[t.DUPLICATE_SELECT_ARGUMENT_SELECTOR=21]="DUPLICATE_SELECT_ARGUMENT_SELECTOR",t[t.MISSING_OTHER_CLAUSE=22]="MISSING_OTHER_CLAUSE",t[t.INVALID_TAG=23]="INVALID_TAG",t[t.INVALID_TAG_NAME=25]="INVALID_TAG_NAME",t[t.UNMATCHED_CLOSING_TAG=26]="UNMATCHED_CLOSING_TAG",t[t.UNCLOSED_TAG=27]="UNCLOSED_TAG"})(wo||(wo={}));var To=class{constructor(e){console.warn(`[vite-messages-plugin]: Message "${e}" was not precompiled. Did you use the correct extenstion *.messages.ts?`)}};var re;(function(t){t[t.literal=0]="literal",t[t.argument=1]="argument",t[t.number=2]="number",t[t.date=3]="date",t[t.time=4]="time",t[t.select=5]="select",t[t.plural=6]="plural",t[t.pound=7]="pound",t[t.tag=8]="tag"})(re||(re={}));var Eo;(function(t){t[t.number=0]="number",t[t.dateTime=1]="dateTime"})(Eo||(Eo={}));function os(t){return t.type===re.literal}function Xr(t){return t.type===re.argument}function ko(t){return t.type===re.number}function Ro(t){return t.type===re.date}function Po(t){return t.type===re.time}function Io(t){return t.type===re.select}function Ao(t){return t.type===re.plural}function Qr(t){return t.type===re.pound}function Lo(t){return t.type===re.tag}function Mo(t){return!!(t&&typeof t=="object"&&t.type===Eo.number)}function Ht(t){return!!(t&&typeof t=="object"&&t.type===Eo.dateTime)}function ns(t){t.forEach(function(e){if(delete e.location,Io(e)||Ao(e))for(var o in e.options)delete e.options[o].location,ns(e.options[o].value);else ko(e)&&Mo(e.style)||(Ro(e)||Po(e))&&Ht(e.style)?delete e.style.location:Lo(e)&&ns(e.children)})}function Zr(t,e){e===void 0&&(e={}),e=Z({shouldParseSkeletons:!0,requiresOtherClause:!0},e);var o=new To(t,e).parse();if(o.err){var n=SyntaxError(wo[o.err.kind]);throw n.location=o.err.location,n.originalMessage=o.err.message,n}return e!=null&&e.captureLocation||ns(o.val),o.val}function No(t,e){var o=e&&e.cache?e.cache:lu,n=e&&e.serializer?e.serializer:au,s=e&&e.strategy?e.strategy:su;return s(t,{cache:o,serializer:n})}function nu(t){return t==null||typeof t=="number"||typeof t=="boolean"}function Jr(t,e,o,n){var s=nu(n)?n:o(n),r=e.get(s);return typeof r>"u"&&(r=t.call(this,n),e.set(s,r)),r}function Yr(t,e,o){var n=Array.prototype.slice.call(arguments,3),s=o(n),r=e.get(s);return typeof r>"u"&&(r=t.apply(this,n),e.set(s,r)),r}function ss(t,e,o,n,s){return o.bind(e,t,n,s)}function su(t,e){var o=t.length===1?Jr:Yr;return ss(t,this,o,e.cache.create(),e.serializer)}function ru(t,e){return ss(t,this,Yr,e.cache.create(),e.serializer)}function iu(t,e){return ss(t,this,Jr,e.cache.create(),e.serializer)}var au=function(){return JSON.stringify(arguments)};function rs(){this.cache=Object.create(null)}rs.prototype.get=function(t){return this.cache[t]};rs.prototype.set=function(t,e){this.cache[t]=e};var lu={create:function(){return new rs}},Oo={variadic:ru,monadic:iu};var Fe;(function(t){t.MISSING_VALUE="MISSING_VALUE",t.INVALID_VALUE="INVALID_VALUE",t.MISSING_INTL_API="MISSING_INTL_API"})(Fe||(Fe={}));var Bt=function(t){Dt(e,t);function e(o,n,s){var r=t.call(this,o)||this;return r.code=n,r.originalMessage=s,r}return e.prototype.toString=function(){return"[formatjs Error: ".concat(this.code,"] ").concat(this.message)},e}(Error);var is=function(t){Dt(e,t);function e(o,n,s,r){return t.call(this,'Invalid values for "'.concat(o,'": "').concat(n,'". Options are "').concat(Object.keys(s).join('", "'),'"'),Fe.INVALID_VALUE,r)||this}return e}(Bt);var ei=function(t){Dt(e,t);function e(o,n,s){return t.call(this,'Value for "'.concat(o,'" must be of type ').concat(n),Fe.INVALID_VALUE,s)||this}return e}(Bt);var ti=function(t){Dt(e,t);function e(o,n){return t.call(this,'The intl string context variable "'.concat(o,'" was not provided to the string "').concat(n,'"'),Fe.MISSING_VALUE,n)||this}return e}(Bt);var j;(function(t){t[t.literal=0]="literal",t[t.object=1]="object"})(j||(j={}));function cu(t){return t.length<2?t:t.reduce(function(e,o){var n=e[e.length-1];return!n||n.type!==j.literal||o.type!==j.literal?e.push(o):n.value+=o.value,e},[])}function pu(t){return typeof t=="function"}function Ft(t,e,o,n,s,r,i){if(t.length===1&&os(t[0]))return[{type:j.literal,value:t[0].value}];for(var a=[],l=0,c=t;l<c.length;l++){var p=c[l];if(os(p)){a.push({type:j.literal,value:p.value});continue}if(Qr(p)){typeof r=="number"&&a.push({type:j.literal,value:o.getNumberFormat(e).format(r)});continue}var u=p.value;if(!(s&&u in s))throw new ti(u,i);var d=s[u];if(Xr(p)){(!d||typeof d=="string"||typeof d=="number")&&(d=typeof d=="string"||typeof d=="number"?String(d):""),a.push({type:typeof d=="string"?j.literal:j.object,value:d});continue}if(Ro(p)){var m=typeof p.style=="string"?n.date[p.style]:Ht(p.style)?p.style.parsedOptions:void 0;a.push({type:j.literal,value:o.getDateTimeFormat(e,m).format(d)});continue}if(Po(p)){var m=typeof p.style=="string"?n.time[p.style]:Ht(p.style)?p.style.parsedOptions:n.time.medium;a.push({type:j.literal,value:o.getDateTimeFormat(e,m).format(d)});continue}if(ko(p)){var m=typeof p.style=="string"?n.number[p.style]:Mo(p.style)?p.style.parsedOptions:void 0;m&&m.scale&&(d=d*(m.scale||1)),a.push({type:j.literal,value:o.getNumberFormat(e,m).format(d)});continue}if(Lo(p)){var h=p.children,g=p.value,v=s[g];if(!pu(v))throw new ei(g,"function",i);var E=Ft(h,e,o,n,s,r),f=v(E.map(function(C){return C.value}));Array.isArray(f)||(f=[f]),a.push.apply(a,f.map(function(C){return{type:typeof C=="string"?j.literal:j.object,value:C}}))}if(Io(p)){var _=p.options[d]||p.options.other;if(!_)throw new is(p.value,d,Object.keys(p.options),i);a.push.apply(a,Ft(_.value,e,o,n,s));continue}if(Ao(p)){var _=p.options["=".concat(d)];if(!_){if(!Intl.PluralRules)throw new Bt(`Intl.PluralRules is not available in this environment.
|
|
1
|
+
var eu=Object.defineProperty;var U=(t,e)=>{for(var o in e)eu(t,o,{get:e[o],enumerable:!0})};import rs from"classnames";import ru,{createContext as iu,useContext as is,useEffect as au,useState as lu}from"react";import tu,{useContext as ou}from"react";import nu from"classnames";var Kt=tu.createContext({});function S(t,e){let{debug:o,...n}=ou(Kt),s=n[t];return s?Object.entries(e).reduce((r,[i,a])=>{let l=s[i];return{...r,[i]:nu(a,l,o?`${t}__${i}`:!1)}},{}):e}var Yr={root:"_root_vr71j_1"};import{jsx as Co,jsxs as su}from"react/jsx-runtime";var wo=()=>su("svg",{className:Yr.root,width:"185",height:"170",viewBox:"0 0 185 170",xmlns:"http://www.w3.org/2000/svg",children:[Co("defs",{children:Co("style",{children:".cls-1 { fill: #b3b3b3; }"})}),Co("title",{children:"Failed loading image"}),Co("path",{className:"cls-1",d:"M15 130.896V16.994c0-1.097.898-1.994 2.007-1.994h150.986A2 2 0 0 1 170 16.994v69.147L133.015 51 87.26 120.377l-35.863-17.758L15 130.896zM2 0C.895 0 0 .887 0 2v166c0 1.105.887 2 2 2h181c1.105 0 2-.887 2-2V2c0-1.105-.887-2-2-2H2zm49 72c11.046 0 20-9.178 20-20.5S62.046 31 51 31s-20 9.178-20 20.5S39.954 72 51 72z",fillRule:"evenodd"})]});var ss={root:"_root_4e7lf_1",imageWrapper:"_imageWrapper_4e7lf_7",image:"_image_4e7lf_7",content:"_content_4e7lf_24",title:"_title_4e7lf_35",contentIsCropped:"_contentIsCropped_4e7lf_45",lineClamp:"_lineClamp_4e7lf_51"};import{jsx as st}from"react/jsx-runtime";var To=iu(ss),cu=({title:t,src:e})=>{let o=is(To),[n,s]=lu(!1);return au(()=>{s(!1)},[e]),st("div",{className:o.imageWrapper,children:e&&!n?st("img",{className:o.image,alt:t,src:e,onError:()=>s(!0)}):st(wo,{})})},pu=({className:t,lineClamp:e=!1,cropText:o=!1,children:n})=>{let s=is(To);return st("div",{className:rs(s.content,t,{[s.contentIsCropped]:o,[s.lineClamp]:e}),children:n})},uu=({as:t="h1",cropText:e=!1,className:o,children:n,...s})=>{let r=is(To);return ru.createElement(t,{className:rs(r.title,o,{[r.contentIsCropped]:e}),...s},n)},Eo=({children:t})=>{let e=S("Card",ss);return st("div",{className:rs(e.root),children:st(To.Provider,{value:e,children:t})})};Eo.Image=cu;Eo.Content=pu;Eo.Title=uu;var D=Eo;var ei={root:"_root_nkim0_1"};import{createContext as Cu,useContext as wu}from"react";var as=function(t,e){return as=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(o,n){o.__proto__=n}||function(o,n){for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(o[s]=n[s])},as(t,e)};function Ut(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");as(t,e);function o(){this.constructor=t}t.prototype=e===null?Object.create(e):(o.prototype=e.prototype,new o)}var Z=function(){return Z=Object.assign||function(e){for(var o,n=1,s=arguments.length;n<s;n++){o=arguments[n];for(var r in o)Object.prototype.hasOwnProperty.call(o,r)&&(e[r]=o[r])}return e},Z.apply(this,arguments)};function ti(t,e){var o={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(o[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(o[n[s]]=t[n[s]]);return o}function ko(t,e,o){if(o||arguments.length===2)for(var n=0,s=e.length,r;n<s;n++)(r||!(n in e))&&(r||(r=Array.prototype.slice.call(e,0,n)),r[n]=e[n]);return t.concat(r||Array.prototype.slice.call(e))}var Ro;(function(t){t[t.EXPECT_ARGUMENT_CLOSING_BRACE=1]="EXPECT_ARGUMENT_CLOSING_BRACE",t[t.EMPTY_ARGUMENT=2]="EMPTY_ARGUMENT",t[t.MALFORMED_ARGUMENT=3]="MALFORMED_ARGUMENT",t[t.EXPECT_ARGUMENT_TYPE=4]="EXPECT_ARGUMENT_TYPE",t[t.INVALID_ARGUMENT_TYPE=5]="INVALID_ARGUMENT_TYPE",t[t.EXPECT_ARGUMENT_STYLE=6]="EXPECT_ARGUMENT_STYLE",t[t.INVALID_NUMBER_SKELETON=7]="INVALID_NUMBER_SKELETON",t[t.INVALID_DATE_TIME_SKELETON=8]="INVALID_DATE_TIME_SKELETON",t[t.EXPECT_NUMBER_SKELETON=9]="EXPECT_NUMBER_SKELETON",t[t.EXPECT_DATE_TIME_SKELETON=10]="EXPECT_DATE_TIME_SKELETON",t[t.UNCLOSED_QUOTE_IN_ARGUMENT_STYLE=11]="UNCLOSED_QUOTE_IN_ARGUMENT_STYLE",t[t.EXPECT_SELECT_ARGUMENT_OPTIONS=12]="EXPECT_SELECT_ARGUMENT_OPTIONS",t[t.EXPECT_PLURAL_ARGUMENT_OFFSET_VALUE=13]="EXPECT_PLURAL_ARGUMENT_OFFSET_VALUE",t[t.INVALID_PLURAL_ARGUMENT_OFFSET_VALUE=14]="INVALID_PLURAL_ARGUMENT_OFFSET_VALUE",t[t.EXPECT_SELECT_ARGUMENT_SELECTOR=15]="EXPECT_SELECT_ARGUMENT_SELECTOR",t[t.EXPECT_PLURAL_ARGUMENT_SELECTOR=16]="EXPECT_PLURAL_ARGUMENT_SELECTOR",t[t.EXPECT_SELECT_ARGUMENT_SELECTOR_FRAGMENT=17]="EXPECT_SELECT_ARGUMENT_SELECTOR_FRAGMENT",t[t.EXPECT_PLURAL_ARGUMENT_SELECTOR_FRAGMENT=18]="EXPECT_PLURAL_ARGUMENT_SELECTOR_FRAGMENT",t[t.INVALID_PLURAL_ARGUMENT_SELECTOR=19]="INVALID_PLURAL_ARGUMENT_SELECTOR",t[t.DUPLICATE_PLURAL_ARGUMENT_SELECTOR=20]="DUPLICATE_PLURAL_ARGUMENT_SELECTOR",t[t.DUPLICATE_SELECT_ARGUMENT_SELECTOR=21]="DUPLICATE_SELECT_ARGUMENT_SELECTOR",t[t.MISSING_OTHER_CLAUSE=22]="MISSING_OTHER_CLAUSE",t[t.INVALID_TAG=23]="INVALID_TAG",t[t.INVALID_TAG_NAME=25]="INVALID_TAG_NAME",t[t.UNMATCHED_CLOSING_TAG=26]="UNMATCHED_CLOSING_TAG",t[t.UNCLOSED_TAG=27]="UNCLOSED_TAG"})(Ro||(Ro={}));var Po=class{constructor(e){console.warn(`[vite-messages-plugin]: Message "${e}" was not precompiled. Did you use the correct extenstion *.messages.ts?`)}};var se;(function(t){t[t.literal=0]="literal",t[t.argument=1]="argument",t[t.number=2]="number",t[t.date=3]="date",t[t.time=4]="time",t[t.select=5]="select",t[t.plural=6]="plural",t[t.pound=7]="pound",t[t.tag=8]="tag"})(se||(se={}));var Io;(function(t){t[t.number=0]="number",t[t.dateTime=1]="dateTime"})(Io||(Io={}));function ls(t){return t.type===se.literal}function oi(t){return t.type===se.argument}function Ao(t){return t.type===se.number}function Lo(t){return t.type===se.date}function Mo(t){return t.type===se.time}function Oo(t){return t.type===se.select}function No(t){return t.type===se.plural}function ni(t){return t.type===se.pound}function Do(t){return t.type===se.tag}function Ho(t){return!!(t&&typeof t=="object"&&t.type===Io.number)}function zt(t){return!!(t&&typeof t=="object"&&t.type===Io.dateTime)}function cs(t){t.forEach(function(e){if(delete e.location,Oo(e)||No(e))for(var o in e.options)delete e.options[o].location,cs(e.options[o].value);else Ao(e)&&Ho(e.style)||(Lo(e)||Mo(e))&&zt(e.style)?delete e.style.location:Do(e)&&cs(e.children)})}function si(t,e){e===void 0&&(e={}),e=Z({shouldParseSkeletons:!0,requiresOtherClause:!0},e);var o=new Po(t,e).parse();if(o.err){var n=SyntaxError(Ro[o.err.kind]);throw n.location=o.err.location,n.originalMessage=o.err.message,n}return e!=null&&e.captureLocation||cs(o.val),o.val}function Bo(t,e){var o=e&&e.cache?e.cache:yu,n=e&&e.serializer?e.serializer:hu,s=e&&e.strategy?e.strategy:gu;return s(t,{cache:o,serializer:n})}function du(t){return t==null||typeof t=="number"||typeof t=="boolean"}function ri(t,e,o,n){var s=du(n)?n:o(n),r=e.get(s);return typeof r>"u"&&(r=t.call(this,n),e.set(s,r)),r}function ii(t,e,o){var n=Array.prototype.slice.call(arguments,3),s=o(n),r=e.get(s);return typeof r>"u"&&(r=t.apply(this,n),e.set(s,r)),r}function ps(t,e,o,n,s){return o.bind(e,t,n,s)}function gu(t,e){var o=t.length===1?ri:ii;return ps(t,this,o,e.cache.create(),e.serializer)}function mu(t,e){return ps(t,this,ii,e.cache.create(),e.serializer)}function fu(t,e){return ps(t,this,ri,e.cache.create(),e.serializer)}var hu=function(){return JSON.stringify(arguments)};function us(){this.cache=Object.create(null)}us.prototype.get=function(t){return this.cache[t]};us.prototype.set=function(t,e){this.cache[t]=e};var yu={create:function(){return new us}},Fo={variadic:mu,monadic:fu};var ze;(function(t){t.MISSING_VALUE="MISSING_VALUE",t.INVALID_VALUE="INVALID_VALUE",t.MISSING_INTL_API="MISSING_INTL_API"})(ze||(ze={}));var jt=function(t){Ut(e,t);function e(o,n,s){var r=t.call(this,o)||this;return r.code=n,r.originalMessage=s,r}return e.prototype.toString=function(){return"[formatjs Error: ".concat(this.code,"] ").concat(this.message)},e}(Error);var ds=function(t){Ut(e,t);function e(o,n,s,r){return t.call(this,'Invalid values for "'.concat(o,'": "').concat(n,'". Options are "').concat(Object.keys(s).join('", "'),'"'),ze.INVALID_VALUE,r)||this}return e}(jt);var ai=function(t){Ut(e,t);function e(o,n,s){return t.call(this,'Value for "'.concat(o,'" must be of type ').concat(n),ze.INVALID_VALUE,s)||this}return e}(jt);var li=function(t){Ut(e,t);function e(o,n){return t.call(this,'The intl string context variable "'.concat(o,'" was not provided to the string "').concat(n,'"'),ze.MISSING_VALUE,n)||this}return e}(jt);var z;(function(t){t[t.literal=0]="literal",t[t.object=1]="object"})(z||(z={}));function Su(t){return t.length<2?t:t.reduce(function(e,o){var n=e[e.length-1];return!n||n.type!==z.literal||o.type!==z.literal?e.push(o):n.value+=o.value,e},[])}function vu(t){return typeof t=="function"}function qt(t,e,o,n,s,r,i){if(t.length===1&&ls(t[0]))return[{type:z.literal,value:t[0].value}];for(var a=[],l=0,c=t;l<c.length;l++){var p=c[l];if(ls(p)){a.push({type:z.literal,value:p.value});continue}if(ni(p)){typeof r=="number"&&a.push({type:z.literal,value:o.getNumberFormat(e).format(r)});continue}var u=p.value;if(!(s&&u in s))throw new li(u,i);var d=s[u];if(oi(p)){(!d||typeof d=="string"||typeof d=="number")&&(d=typeof d=="string"||typeof d=="number"?String(d):""),a.push({type:typeof d=="string"?z.literal:z.object,value:d});continue}if(Lo(p)){var m=typeof p.style=="string"?n.date[p.style]:zt(p.style)?p.style.parsedOptions:void 0;a.push({type:z.literal,value:o.getDateTimeFormat(e,m).format(d)});continue}if(Mo(p)){var m=typeof p.style=="string"?n.time[p.style]:zt(p.style)?p.style.parsedOptions:n.time.medium;a.push({type:z.literal,value:o.getDateTimeFormat(e,m).format(d)});continue}if(Ao(p)){var m=typeof p.style=="string"?n.number[p.style]:Ho(p.style)?p.style.parsedOptions:void 0;m&&m.scale&&(d=d*(m.scale||1)),a.push({type:z.literal,value:o.getNumberFormat(e,m).format(d)});continue}if(Do(p)){var f=p.children,g=p.value,x=s[g];if(!vu(x))throw new ai(g,"function",i);var w=qt(f,e,o,n,s,r),h=x(w.map(function(C){return C.value}));Array.isArray(h)||(h=[h]),a.push.apply(a,h.map(function(C){return{type:typeof C=="string"?z.literal:z.object,value:C}}))}if(Oo(p)){var y=p.options[d]||p.options.other;if(!y)throw new ds(p.value,d,Object.keys(p.options),i);a.push.apply(a,qt(y.value,e,o,n,s));continue}if(No(p)){var y=p.options["=".concat(d)];if(!y){if(!Intl.PluralRules)throw new jt(`Intl.PluralRules is not available in this environment.
|
|
2
2
|
Try polyfilling it using "@formatjs/intl-pluralrules"
|
|
3
|
-
`,Fe.MISSING_INTL_API,i);var x=o.getPluralRules(e,{type:p.pluralType}).select(d-(p.offset||0));_=p.options[x]||p.options.other}if(!_)throw new is(p.value,d,Object.keys(p.options),i);a.push.apply(a,Ft(_.value,e,o,n,s,d-(p.offset||0)));continue}}return cu(a)}function uu(t,e){return e?Z(Z(Z({},t||{}),e||{}),Object.keys(t).reduce(function(o,n){return o[n]=Z(Z({},t[n]),e[n]||{}),o},{})):t}function du(t,e){return e?Object.keys(t).reduce(function(o,n){return o[n]=uu(t[n],e[n]),o},Z({},t)):t}function as(t){return{create:function(){return{get:function(e){return t[e]},set:function(e,o){t[e]=o}}}}}function gu(t){return t===void 0&&(t={number:{},dateTime:{},pluralRules:{}}),{getNumberFormat:No(function(){for(var e,o=[],n=0;n<arguments.length;n++)o[n]=arguments[n];return new((e=Intl.NumberFormat).bind.apply(e,Co([void 0],o,!1)))},{cache:as(t.number),strategy:Oo.variadic}),getDateTimeFormat:No(function(){for(var e,o=[],n=0;n<arguments.length;n++)o[n]=arguments[n];return new((e=Intl.DateTimeFormat).bind.apply(e,Co([void 0],o,!1)))},{cache:as(t.dateTime),strategy:Oo.variadic}),getPluralRules:No(function(){for(var e,o=[],n=0;n<arguments.length;n++)o[n]=arguments[n];return new((e=Intl.PluralRules).bind.apply(e,Co([void 0],o,!1)))},{cache:as(t.pluralRules),strategy:Oo.variadic})}}var oi=function(){function t(e,o,n,s){o===void 0&&(o=t.defaultLocale);var r=this;if(this.formatterCache={number:{},dateTime:{},pluralRules:{}},this.format=function(c){var p=r.formatToParts(c);if(p.length===1)return p[0].value;var u=p.reduce(function(d,m){return!d.length||m.type!==j.literal||typeof d[d.length-1]!="string"?d.push(m.value):d[d.length-1]+=m.value,d},[]);return u.length<=1?u[0]||"":u},this.formatToParts=function(c){return Ft(r.ast,r.locales,r.formatters,r.formats,c,void 0,r.message)},this.resolvedOptions=function(){var c;return{locale:((c=r.resolvedLocale)===null||c===void 0?void 0:c.toString())||Intl.NumberFormat.supportedLocalesOf(r.locales)[0]}},this.getAst=function(){return r.ast},this.locales=o,this.resolvedLocale=t.resolveLocale(o),typeof e=="string"){if(this.message=e,!t.__parse)throw new TypeError("IntlMessageFormat.__parse must be set to process `message` of type `string`");var i=s||{},a=i.formatters,l=$r(i,["formatters"]);this.ast=t.__parse(e,Z(Z({},l),{locale:this.resolvedLocale}))}else this.ast=e;if(!Array.isArray(this.ast))throw new TypeError("A message must be provided as a String or AST.");this.formats=du(t.formats,n),this.formatters=s&&s.formatters||gu(this.formatterCache)}return Object.defineProperty(t,"defaultLocale",{get:function(){return t.memoizedDefaultLocale||(t.memoizedDefaultLocale=new Intl.NumberFormat().resolvedOptions().locale),t.memoizedDefaultLocale},enumerable:!1,configurable:!0}),t.memoizedDefaultLocale=null,t.resolveLocale=function(e){if(!(typeof Intl.Locale>"u")){var o=Intl.NumberFormat.supportedLocalesOf(e);return o.length>0?new Intl.Locale(o[0]):new Intl.Locale(typeof e=="string"?e:e[0])}},t.__parse=Zr,t.formats={number:{integer:{maximumFractionDigits:0},currency:{style:"currency"},percent:{style:"percent"}},date:{short:{month:"numeric",day:"numeric",year:"2-digit"},medium:{month:"short",day:"numeric",year:"numeric"},long:{month:"long",day:"numeric",year:"numeric"},full:{weekday:"long",month:"long",day:"numeric",year:"numeric"}},time:{short:{hour:"numeric",minute:"numeric"},medium:{hour:"numeric",minute:"numeric",second:"numeric"},long:{hour:"numeric",minute:"numeric",second:"numeric",timeZoneName:"short"},full:{hour:"numeric",minute:"numeric",second:"numeric",timeZoneName:"short"}}},t}();function hu(t,e){return e.split(".").reduce((o,n)=>o?o[n]:void 0,t)}var yu="dummy",ls=mu(null);function w(t){let e=fu(ls);if(!e)throw new Error("useTranslator() may be used only in the context of a <LocaleContext> component.");let o=t[e]??{};return(n,s)=>{let r=hu(o,n);return r?new oi(r).format(s):(e!==yu&&console.warn(`${n} does not exist in messages of ${e}`),`[${n}]`)}}var cs={};z(cs,{enUS:()=>Su,nlNL:()=>vu});var Su={experimental:[{type:0,value:"Experimental"}]},vu={experimental:[{type:0,value:"Experimenteel"}]};import{jsx as si}from"react/jsx-runtime";var ni=({children:t})=>{let e=y("Chip",Gr);return si("span",{className:e.root,children:t})},Do=()=>{let t=w(cs);return si(ni,{children:t("experimental")})},_u=ni;import xu from"classnames";var ri={root:"_root_cq1yq_1"};import{jsx as wu}from"react/jsx-runtime";var bu={"arrow-up":"\u25B2","arrow-down":"\u25BC",tab:"tab",esc:"Esc",enter:"\u21B5"},Cu=({className:t,keyCode:e,...o})=>{let n=y("KeyboardHint",ri);return wu("span",{"data-key":bu[e],className:xu(t,n.root),...o})},ps=Cu;import Tu from"classnames";var ii={root:"_root_4a08n_1"};import{jsx as ku}from"react/jsx-runtime";var Eu=({className:t,children:e,...o})=>{let n=y("Label",ii);return ku("span",{...o,className:Tu(t,n.root),children:e})},us=Eu;var ai={root:"_root_jlggj_1",subTitleContainer:"_subTitleContainer_jlggj_5",subtitle:"_subtitle_jlggj_9",suggestions:"_suggestions_jlggj_17"};import{jsx as ds,jsxs as Pu}from"react/jsx-runtime";var Ru=({title:t,children:e,type:o,...n})=>{let s=y("Section",ai);return Pu("section",{...n,className:s.root,"data-section-type":o,children:[t&&ds("div",{className:s.subTitleContainer,children:ds("span",{className:s.subtitle,children:t})}),ds("div",{className:s.suggestions,children:e})]})},Ke=Ru;import Iu from"classnames";import Au from"react";var li={root:"_root_19wxp_1"};import{jsx as Mu}from"react/jsx-runtime";var Lu=Au.forwardRef(({className:t,children:e},o)=>{let n=y("SectionList",li);return Mu("div",{ref:o,className:Iu(n.root,t),children:e})}),gs=Lu;import Ho from"classnames";import Nu,{createContext as Ou,useCallback as Du,useContext as Kt}from"react";var ms={root:"_root_9kn3u_10",fadein:"_fadein_9kn3u_1",isClickable:"_isClickable_9kn3u_47",isSelected:"_isSelected_9kn3u_52",actions:"_actions_9kn3u_76",actionsIsFixed:"_actionsIsFixed_9kn3u_98",actionButton:"_actionButton_9kn3u_106",dropdownList:"_dropdownList_9kn3u_127",dropdownButton:"_dropdownButton_9kn3u_142",dropdownItem:"_dropdownItem_9kn3u_152",dropdownItemButton:"_dropdownItemButton_9kn3u_161",actionButtonIsPrimary:"_actionButtonIsPrimary_9kn3u_175",actionButtonIsDisabled:"_actionButtonIsDisabled_9kn3u_179",labels:"_labels_9kn3u_187",label:"_label_9kn3u_187"};import{jsx as me,jsxs as Uu}from"react/jsx-runtime";var ot=Ou(ms),Hu=({fixed:t,children:e,...o})=>{let n=Kt(ot);return me("div",{...o,className:Ho(n.actions,{[n.actionsIsFixed]:t}),children:e})},Bu=({className:t,primary:e,disabled:o,label:n,children:s})=>{let r=Kt(ot);return Uu("div",{className:Ho(t,r.actionButton,r.dropdownButton,{[r.actionButtonIsPrimary]:e,[r.actionButtonIsDisabled]:o}),onMouseDown:i=>i.stopPropagation(),onClick:i=>i.stopPropagation(),children:[n,me("ul",{className:r.dropdownList,children:s})]})},Fu=({index:t,label:e,onClick:o})=>{let n=Kt(ot);return me("li",{className:n.dropdownItem,children:me("button",{className:n.dropdownItemButton,type:"button","data-index":t,onClick:o,children:e})})},Ku=({className:t,primary:e,disabled:o,onClick:n,label:s})=>{let r=Kt(ot);return me("button",{type:"button",className:Ho(t,r.actionButton,{[r.actionButtonIsPrimary]:e,[r.actionButtonIsDisabled]:o}),onClick:n??(i=>i.stopPropagation()),disabled:o,"aria-hidden":o,children:s})},fs=({labels:t})=>{let e=Kt(ot);return me("div",{className:e.labels,children:t.map(o=>me("span",{className:e.label,children:o},o))})},nt=Nu.forwardRef(({className:t,selected:e,onClick:o,children:n,as:s="div",...r},i)=>{let a=y("Suggestion",ms),l=Du(c=>{c.preventDefault(),o&&o(c)},[o]);return me(s,{...r,ref:i,className:Ho(t,a.root,{[a.isSelected]:e,[a.isClickable]:!!o}),onClick:l,children:me(ot.Provider,{value:a,children:n})})});nt.Labels=fs;nt.Actions=Hu;nt.ActionButton=Ku;nt.DropdownButton=Bu;nt.DropdownItem=Fu;var O=nt;import zu from"classnames";var ci={root:"_root_fp74r_1",isWithDivider:"_isWithDivider_fp74r_9"};import{jsx as qu}from"react/jsx-runtime";var ju=({withDivider:t,children:e})=>{let o=y("SuggestionList",ci);return qu("div",{"data-testid":"suggestions-overlay-list",className:zu(o.root,{[o.isWithDivider]:t}),children:e})},fe=ju;import Vu from"classnames";var pi={root:"_root_1wpmq_1",isCollapsed:"_isCollapsed_1wpmq_17"};import{jsx as hs}from"react/jsx-runtime";var Wu=({className:t,isCollapsed:e,title:o,onClick:n})=>{let s=y("ToggleButton",pi);return hs("button",{type:"button",className:Vu(s.root,t,{[s.isCollapsed]:e}),onClick:n,title:o,children:hs("svg",{width:"14",height:"8",viewBox:"-2.5 -5 75 60",preserveAspectRatio:"none",children:hs("path",{d:"M0,0 l35,50 l35,-50",fill:"none",stroke:"grey",strokeLinecap:"round",strokeWidth:"6"})})})},st=Wu;var ui=/(?:[.,;:!?\\n]|:\\)|:\\(|:-\\)|:-\\()/g,rt=/(((\$!\{)|(\{))[a-zA-Z0-9_.]+\})/g;var di=/x-deepdesk-(([a-z0-9\-_])+-version)/,le=(g=>(g.SEARCH="search",g.TEMPLATE="template",g.ELASTIC_SEARCH="search-autocomplete",g.GPT="gpt",g.TRIE="trie",g.TRIE_WITH_TYPOS="trie-with-typos",g.SEMANTIC="semantic",g.TEXT_RECOMMENDATION="text_recommendation",g.URL_RECOMMENDATION="url_recommendation",g.LINK_RECOMMENDATION="link_recommendation",g.PERSONAL_COLLECTION="personal-collection",g.PERSONAL_COLLECTION_SEARCH="personal-collection-search",g.SEARCH_OVERLAY="search-overlay",g.SEARCH_PREVIEW="search-preview",g.SEARCH_URL="search-url",g))(le||{}),Ue=(s=>(s.TAB="tab",s.ARROW="arrow",s.HOTKEY="hotkey",s.MOUSE="mouse",s))(Ue||{});import{render as Gn,unmountComponentAtNode as qr}from"react-dom";import{Fragment as jm}from"react";import{createSlice as Gu}from"@reduxjs/toolkit";import{useSelector as $u}from"react-redux";var Bo=(o=>(o.NL_NL="nl-NL",o.EN_US="en-US",o))(Bo||{});var Xu={locale:"en-US",deanonymize:!1,fallbackImage:!1,isEmbedded:!1,showAutoflows:!1,showCustomMessages:!1,showImages:!1,showPersonalCollectionLink:!1,showSearch:!1,showImageSearch:!1,showStyleSuggestions:!1,showMidSentenceSuggestions:!1,showSuggestionsBeforePattern:!1,showSuggestionsAfterPattern:!1,showTabCompletion:!0,showTextSuggestions:!0,showEntitiesCommand:!1,showSummaryCommand:!1,showKnowledgeSearch:!1,textSuggestionsCount:3,recommendTextSuggestions:!0,searchTriggerKey:"k",visible:!0,insertLink:!1,inlineSuggestions:!1,adminUrl:void 0,productName:"Deepdesk"},gi=Gu({name:"settings",initialState:Xu,reducers:{set(t,e){Object.entries(e.payload).forEach(o=>{let[n,s]=o;typeof s>"u"||(t[n]=s)})}}}),{set:Ut}=gi.actions,ys=t=>e=>e.settings[t],b=t=>$u(ys(t)),mi=gi.reducer;import{useState as Ig}from"react";import{useDispatch as Ag,useSelector as Qs}from"react-redux";import{createAction as ze,createSlice as nd}from"@reduxjs/toolkit";import{diffChars as sd}from"diff";import{useSelector as rd}from"react-redux";function fi(t){return typeof t=="object"&&!Array.isArray(t)&&t!==null}function it(t,e,o=10){let n=typeof t,s=typeof e;if(o===0)throw new Error("Max depth deepEqual, possible circular references?");return n!==s?!1:t==null||n==="string"||n==="number"||n==="boolean"?t===e:Array.isArray(t)&&Array.isArray(e)?t.length!==e.length?!1:t.every((r,i)=>it(r,e[i],o-1)):fi(t)&&fi(e)?Object.keys(t).length!==Object.keys(e).length?!1:Object.keys(t).every(i=>it(t[i],e[i],o-1)):!1}function Qu(t){return Math.max(...t.map(e=>e.length))}function Zu(t,e){let o=t.reduce((n,s)=>{if(s){let r=n[s]?n[s]+1:1;return{...n,[s]:r}}return n},{});return Object.keys(o).reduce((n,s)=>(o[s]<e&&n.push(s),n),[])}function hi(t,e){let n=[...t.map(({text:s})=>s.split(/\b(\w+)\b/))];for(let s=0;s<Qu(n);s++){let r=Zu(n.map(a=>a[s]),e),i=n.filter(a=>!r.includes(a[s]));if(i.length>=e)n=i;else return{text:n[0].slice(0,s).join("").replace(/ (\?| |!|\.|,|\n)/g,"$1").trimEnd(),source:"mixed"}}}var Ju=2;function Ss(t,e=""){if(t.length===0)return;if(t.length===1)return t[0];let o=hi(t,Ju);return o&&o.text!==e?o:t[0]}import{createAction as Yu,createAsyncThunk as at,createSlice as ed}from"@reduxjs/toolkit";var yi={current:null,isSupported:null},P=Yu("resetConversation"),Fo=t=>{let{current:e}=t.conversation;return(e==null?void 0:e.sessionId)||null},Ko=t=>{let{current:e}=t.conversation;return(e==null?void 0:e.id)||null},Uo=t=>t.conversation.isSupported,vs=at("conversation/isSupported",(t,e)=>{let{deepdeskAPI:o}=e.extra;return o.isConversationSupported(t.sessionId,t.options)}),zo=at("conversation/create",(t,e)=>{let{deepdeskAPI:o}=e.extra;return o.createConversation(t)}),jo=at("conversation/bySessionId",(t,e)=>{let{deepdeskAPI:o}=e.extra;return o.getConversationBySessionId(t.sessionId,t.options)}),qo=at("conversation/update",(t,e)=>{let{deepdeskAPI:o}=e.extra,n=Ko(e.getState());if(!n)throw new Error("No current conversation to update");return o.updateConversation(n,t)}),_s=at("conversation/upsert",(t,e)=>{let{deepdeskAPI:o}=e.extra;return o.getConversationBySessionId(t.sessionId).catch(()=>null).then(n=>{if(!n)return o.createConversation(t);let{agentId:s,agentName:r,agentEmail:i,agentNickname:a,tags:l}=t;return o.updateConversation(n.id,{agentId:s,agentEmail:i,agentName:r,agentNickname:a,tags:l})})}),Vo=at("conversation/postMessages",(t,e)=>{let{deepdeskAPI:o}=e.extra,n=Ko(e.getState());if(!n)throw new Error("No current conversation to update messages");return o.postMessages(n,t.map(s=>({...s})))}),td=[zo.rejected,jo.rejected,qo.rejected,Vo.rejected].map(t=>t==null?void 0:t.toString()),od=ed({name:"conversation",initialState:yi,reducers:{},extraReducers:t=>{t.addCase(vs.fulfilled,(e,o)=>{e.isSupported=o.payload}).addCase(zo.fulfilled,(e,o)=>{var n;e.current=o.payload,e.isSupported=((n=o.payload)==null?void 0:n.hasActiveProfile)??null}).addCase(jo.fulfilled,(e,o)=>{var n;e.current=o.payload,e.isSupported=((n=o.payload)==null?void 0:n.hasActiveProfile)??null}).addCase(_s.fulfilled,(e,o)=>{var n;e.current=o.payload,e.isSupported=((n=o.payload)==null?void 0:n.hasActiveProfile)??null}).addCase(qo.fulfilled,(e,o)=>{var n;e.current=o.payload,e.isSupported=((n=o.payload)==null?void 0:n.hasActiveProfile)??null}).addCase(Vo.fulfilled,(e,o)=>{e.current&&(e.current.messages=o.payload)}).addCase(P,()=>yi).addMatcher(e=>td.includes(e.type),(e,o)=>{throw new Error(o.error.message)})}}),Si=od.reducer;var Pe={text:"",html:null,selection:{start:0,end:0},stagedSuggestion:null,userCommitted:{text:"",selection:{start:0,end:0}},tabCompletionSuggestion:void 0,previousKeyDownEvent:null,textSuggestions:[],selectedSuggestionIndex:-1,metrics:{numCharsTyped:0,numCharsPasted:0,numCharsCut:0,numCharsDeleted:0,numPaste:0,agentStartedTypingTimestamp:null,externalTimeTotalSeconds:null,pastes:[],deletions:[],offeredTextSuggestions:[],textSuggestions:[],cuts:[]}};function Go(t){let{key:e,shiftKey:o,ctrlKey:n,metaKey:s,altKey:r}=t;return{key:e,shiftKey:o,ctrlKey:n,metaKey:s,altKey:r}}var $o=ze("input/replaceText"),Xo=ze("input/keyDown"),je=ze("input/sendMessage"),Qo=ze("input/sendEditSuggestionMessage"),Zo=ze("input/uiInputChange"),Jo=ze("input/applyImageSuggestion"),J=ze("input/sendEvent");function Wo(t){if(!t.stagedSuggestion)return;let{text:e,suggestion:{source:o,abVariant:n,abTestName:s,trainingJobs:r,sourceText:i,searchTerm:a,text:l},eventMetrics:{inputType:c},replace:p}=t.stagedSuggestion,u=o==="search"||o==="personal-collection-search",d=e.slice(t.userCommitted.text.substring(0,t.userCommitted.selection.start).length);(u||p==="selection")&&(d=e),t.stagedSuggestion.suggestion.source==="search-overlay"&&(d=l),t.userCommitted.text=t.text,t.userCommitted.selection=t.selection,t.metrics.textSuggestions.push({text:d,source:o,abVariant:n,abTestName:s,inputType:c,sourceText:i,trainingJobs:r||[],searchTerm:u?t.userCommitted.text:a}),t.stagedSuggestion=null,t.textSuggestions=[],t.selectedSuggestionIndex=-1}var vi=t=>nd({name:t,initialState:Pe,reducers:{initialInput(e,o){let{text:n,selection:s,html:r}=o.payload;e.text=n,e.selection.start=(s==null?void 0:s.start)??n.length,e.selection.end=(s==null?void 0:s.end)??n.length,e.userCommitted.text=n,e.userCommitted.selection.start=(s==null?void 0:s.start)??n.length,e.userCommitted.selection.end=(s==null?void 0:s.end)??n.length,e.html=r||null},reset(e){Object.assign(e,{...Pe,selection:e.selection})},resetToCommitted(e){e.text=e.userCommitted.text,e.selection=e.userCommitted.selection,e.stagedSuggestion=null,e.tabCompletionSuggestion=Ss(e.textSuggestions,e.userCommitted.text)},changeSelection(e,o){o.payload&&(it(e.selection,o.payload)||(e.selection=o.payload,e.userCommitted.selection=e.selection,e.stagedSuggestion&&Wo(e)))},platformInput(e,o){let{text:n,html:s,selection:r}=o.payload;r&&(e.selection.start=r.start,e.selection.end=r.end),e.text=n,e.html=s||null},userInput(e,o){var i,a,l,c;if(e.previousKeyDownEvent){let{key:p,shiftKey:u,ctrlKey:d,metaKey:m,altKey:h}=e.previousKeyDownEvent;switch(p){case"Enter":u&&(e.metrics.numCharsTyped+=1);break;case"Backspace":case"Delete":{let{text:g}=e,{text:v}=o.payload,E=sd(g,v);g.length-v.length>1&&e.metrics.deletions.push(...E.filter(f=>f.removed).map(f=>f.value)),e.metrics.numCharsDeleted+=g.length-v.length;break}case"C":case"V":case"X":if(!d&&!m){e.metrics.numCharsTyped+=1;let g=((i=e.selection)==null?void 0:i.start)!==void 0&&((a=e.selection)==null?void 0:a.end)!==void 0?e.text.substring(e.selection.start,e.selection.end):null;g&&g.length>0&&(e.metrics.numCharsDeleted+=g.length,e.metrics.deletions.push(g))}break;case"Shift":break;default:if(!d&&!m&&!h){e.metrics.numCharsTyped+=1;let g=((l=e.selection)==null?void 0:l.start)!==void 0&&((c=e.selection)==null?void 0:c.end)!==void 0?e.text.substring(e.selection.start,e.selection.end):null;g&&g.length>0&&(e.metrics.numCharsDeleted+=g.length,e.metrics.deletions.push(g))}}}!e.metrics.agentStartedTypingTimestamp&&o.payload.text!==e.text&&(e.metrics.agentStartedTypingTimestamp=Date.now()),o.payload.text===""&&(e.metrics=Pe.metrics,e.textSuggestions=[],e.stagedSuggestion=null),e.text!==o.payload.text&&Wo(e);let{text:n,html:s,selection:r}=o.payload;r&&(e.selection.start=r.start,e.selection.end=r.end,e.userCommitted.selection.start=r.start,e.userCommitted.selection.end=r.end),e.text=n,e.html=s||null,e.userCommitted.text=n,e.previousKeyDownEvent=null},stageSuggestion(e,o){let{text:n}=o.payload;switch(e.stagedSuggestion=o.payload,e.tabCompletionSuggestion=void 0,o.payload.replace){case"selection":e.text=`${e.text.slice(0,e.selection.start)}${n}${e.text.slice(e.selection.end)}`,e.selection.end=e.selection.start+n.length,e.selection.start+=n.length;break;case"until-selection-end":e.text=`${n}${e.text.slice(e.selection.end)}`,e.selection.start=n.length,e.selection.end=n.length;break;default:throw new Error(`Unknown replace ${o.payload.replace}`)}o.payload.eventMetrics.inputType==="tab"&&Wo(e)},commitSuggestion(e){Wo(e)},offeredTextSuggestion(e,o){let{text:n,suggestion:{source:s}}=o.payload;e.metrics.offeredTextSuggestions.find(i=>i.text===n)||e.metrics.offeredTextSuggestions.push({text:n,source:s})},registerCut(e,o){let{metrics:n}=e,s=o.payload;e.metrics={...e.metrics,numCharsCut:n.numCharsCut+s.length,cuts:[...n.cuts,s]}},registerPaste(e,o){let{metrics:n}=e,{text:s,selectionText:r}=o.payload,i=n.numCharsDeleted+(r&&r.length?r.length:0),a=r&&r.length?[...n.deletions,r]:n.deletions;e.metrics={...e.metrics,numCharsDeleted:i,deletions:a,numCharsPasted:n.numCharsPasted+s.length,numPaste:n.numPaste+1,pastes:[...n.pastes,s]}},registerKeyDown(e,o){e.previousKeyDownEvent=o.payload},nextTextSuggestionIndex(e){let o=e.textSuggestions.length;e.selectedSuggestionIndex=e.selectedSuggestionIndex<o-1?e.selectedSuggestionIndex+1:e.selectedSuggestionIndex},previousTextSuggestionIndex(e){e.selectedSuggestionIndex=e.selectedSuggestionIndex>=0?e.selectedSuggestionIndex-1:e.selectedSuggestionIndex},setTextSuggestions(e,o){if(e.selectedSuggestionIndex=-1,e.textSuggestions=o.payload,o.payload.length===0)return;let n=e.userCommitted.text.substring(0,e.userCommitted.selection.end),s=Ss(o.payload,n);e.tabCompletionSuggestion=s!=null&&s.text.includes(n)?s:void 0},setSelectedTextSuggestionIndex(e,o){e.selectedSuggestionIndex=o.payload},mergeMetrics(e,{payload:o}){let n=o.agentStartedTypingTimestamp!=null?o.agentStartedTypingTimestamp:Date.now(),s=(Date.now()-n)/1e3;e.metrics.externalTimeTotalSeconds=s,e.metrics.numCharsTyped+=o.numCharsTyped,e.metrics.numCharsPasted+=o.numCharsPasted,e.metrics.numCharsCut+=o.numCharsCut,e.metrics.numCharsDeleted+=o.numCharsDeleted,e.metrics.numPaste+=o.numPaste,e.metrics.pastes.push(...o.pastes),e.metrics.deletions.push(...o.deletions)}},extraReducers:e=>{e.addCase(P,o=>{o.tabCompletionSuggestion=Pe.tabCompletionSuggestion,o.previousKeyDownEvent=Pe.previousKeyDownEvent,o.textSuggestions=Pe.textSuggestions,o.selectedSuggestionIndex=Pe.selectedSuggestionIndex,o.metrics=Pe.metrics})}}),xs=vi("input"),lt=t=>t.input.userCommitted.text.substring(0,t.input.userCommitted.selection.end),id=t=>t.input.selection,_i=()=>rd(id),{userInput:xi,changeSelection:bs,initialInput:bi,mergeMetrics:Ci,nextTextSuggestionIndex:wi,offeredTextSuggestion:Ti,previousTextSuggestionIndex:Ei,registerCut:ki,registerKeyDown:Ri,registerPaste:Pi,reset:Ii,resetToCommitted:zt,platformInput:Ai,setSelectedTextSuggestionIndex:Yo,setTextSuggestions:Ie,stageSuggestion:ie,commitSuggestion:Ae}=xs.actions,W=vi("overlay");import{useEffect as Mi,useRef as Ni}from"react";var Li={root:"_root_1qp5s_1",content:"_content_1qp5s_23"};import{jsx as Oi}from"react/jsx-runtime";var ad=({isOpen:t,autoFocus:e,children:o,onClose:n,onBack:s,overlayAriaLabel:r,contentAriaLabel:i})=>{let a=Ni(null),l=Ni(null),c=y("Dialog",Li);return Mi(()=>{var d,m;let p=h=>{h.key==="Escape"&&(h.preventDefault(),h.stopPropagation(),s())},u=h=>{let g=window.getSelection();g!=null&&g.toString()||h.target===a.current&&t&&n()};return(d=a.current)==null||d.addEventListener("click",u),(m=a.current)==null||m.addEventListener("keyup",p),()=>{var h,g;(h=a.current)==null||h.removeEventListener("click",u),(g=a.current)==null||g.removeEventListener("keyup",p)}},[a,l,s,n]),Mi(()=>{var p,u;!a.current||!t||!e||(u=(p=a.current)==null?void 0:p.querySelector("input, textarea"))==null||u.focus()},[t,e,a]),t?Oi("div",{role:"dialog","data-testid":"dialog",className:c.root,"aria-label":r,ref:a,children:Oi("div",{ref:l,"data-testid":"dialog-content",className:c.content,"aria-label":i,children:o})}):null},ct=ad;import{useEffect as Ca}from"react";import{useDispatch as ug,useSelector as dg}from"react-redux";var Cs={};z(Cs,{enUS:()=>ld,nlNL:()=>cd});var ld={dismiss:[{type:0,value:"Close"}],add:[{type:0,value:"Add to message"}],next:[{type:0,value:"Next"}],previous:[{type:0,value:"Previous"}],warning:[{type:0,value:"Are you sure you want to discard the message?"}]},cd={dismiss:[{type:0,value:"Sluiten"}],add:[{type:0,value:"Toevoegen"}],next:[{type:0,value:"Volgende"}],previous:[{type:0,value:"Vorige"}],warning:[{type:0,value:"Weet je zeker dat je de wijzigingen wilt weggooien?"}]};var Di={root:"_root_l80t9_1",content:"_content_l80t9_3",title:"_title_l80t9_7",actions:"_actions_l80t9_15",pagination:"_pagination_l80t9_20",primaryButton:"_primaryButton_l80t9_51",primaryButtons:"_primaryButtons_l80t9_55"};import{jsx as Hi,jsxs as pd}from"react/jsx-runtime";var en=()=>pd("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 256 512","aria-labelledby":"angleLeftTitle",children:[Hi("title",{id:"angleLeftTitle",children:"AngleLeft"}),Hi("path",{d:"M192 448c-8.188 0-16.38-3.125-22.62-9.375l-160-160c-12.5-12.5-12.5-32.75 0-45.25l160-160c12.5-12.5 32.75-12.5 45.25 0s12.5 32.75 0 45.25L77.25 256l137.4 137.4c12.5 12.5 12.5 32.75 0 45.25C208.4 444.9 200.2 448 192 448z"})]});import{jsx as Bi,jsxs as ud}from"react/jsx-runtime";var Fi=()=>ud("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 256 512","aria-labelledby":"angleRightTitle",children:[Bi("title",{id:"angleRightTitle",children:"AngleRight"}),Bi("path",{d:"M64 448c-8.188 0-16.38-3.125-22.62-9.375c-12.5-12.5-12.5-32.75 0-45.25L178.8 256L41.38 118.6c-12.5-12.5-12.5-32.75 0-45.25s32.75-12.5 45.25 0l160 160c12.5 12.5 12.5 32.75 0 45.25l-160 160C80.38 444.9 72.19 448 64 448z"})]});import{useEffect as qt,useRef as Is,useState as Rd}from"react";import{useDispatch as Pd}from"react-redux";import{Interweave as Id}from"interweave";import ta from"classnames";var ws={root:"_root_kxnai_1",agentText:"_agentText_kxnai_3",textInput:"_textInput_kxnai_8",textInputWrapper:"_textInputWrapper_kxnai_27",alert:"_alert_kxnai_31",alertText:"_alertText_kxnai_50",warning:"_warning_kxnai_60",success:"_success_kxnai_69"};import{Matcher as fd}from"interweave";import hd from"classnames";import{useEffect as dd,useRef as gd,useState as md}from"react";function Ki(t,e){let o;return[(...n)=>{window.cancelAnimationFrame(o);let s=e?e(...n):n;o=window.requestAnimationFrame(()=>{t(...s)})},()=>window.cancelAnimationFrame(o)]}function tn(t){let e=gd(null),[o,n]=md(!1);return dd(()=>{let s=!1,r=parseFloat(window.getComputedStyle(document.body).zoom??"1"),[i,a]=Ki((p,u)=>{let d=e.current;if(!d)return;let m=p/r,h=u/r,g=d.getBoundingClientRect(),v=m>g.x&&m<g.x+g.width&&h>g.y&&h<g.y+g.height;v&&!s?(s=!0,n(!0)):!v&&s&&(s=!1,n(!1))},({clientX:p,clientY:u})=>[p,u]),[l,c]=Ki(()=>{s=!1,n(!1)});return t.addEventListener("mousemove",i),t.addEventListener("mouseleave",l),()=>{a(),c(),t.removeEventListener("mousemove",i),t.removeEventListener("mouseleave",l)}},[e]),[e,o]}var te={root:"_root_81non_1",container:"_container_81non_3",agentText:"_agentText_81non_5",tabText:"_tabText_81non_6",hint:"_hint_81non_6",matchSelection:"_matchSelection_81non_10",focus:"_focus_81non_16",resetIndent:"_resetIndent_81non_20",matchKeyword:"_matchKeyword_81non_24",matchPlaceholder:"_matchPlaceholder_81non_25",hover:"_hover_81non_31",hintText:"_hintText_81non_64",popover:"_popover_81non_72",popoverRoot:"_popoverRoot_81non_77",popoverContentContainer:"_popoverContentContainer_81non_81",popoverContent:"_popoverContent_81non_81",selectionOptions:"_selectionOptions_81non_107",selectionOptionsIsHidden:"_selectionOptionsIsHidden_81non_112",selectionOptionsButton:"_selectionOptionsButton_81non_116",caret:"_caret_81non_132",popoverSuggestionsRoot:"_popoverSuggestionsRoot_81non_136",suggestionsOverlayInputStyles:"_suggestionsOverlayInputStyles_81non_141"};import{jsx as Ui}from"react/jsx-runtime";var yd=({inputElement:t,children:e})=>{let o=y("TabCompletion",te),[n,s]=tn(t);return Ui("mark",{ref:n,className:hd(o.matchPlaceholder,{[o.hover]:s}),children:e})},pt=class extends fd{match(e){let o=e.match(/(((\$!\{)|(\{))[a-zA-Z0-9_.]+\}(?!\}))/);return o?{index:o.index,length:o[0].length,match:o[0],matchString:o[0],valid:!0}:null}replaceWith(e,o){return Ui(yd,{inputElement:o.inputElement,children:e},`placeholder_${o.matchString}_${o.key}`)}asTag(){return"mark"}};import{useEffect as Sd,useRef as vd,useState as _d}from"react";function on(t){return t.contentEditable==="true"}function xd(t){let e=0,o=0,n=window.getSelection();if(n.rangeCount!==0){let s=n.getRangeAt(0),r=s.cloneRange();r.selectNodeContents(t),r.setEnd(s.endContainer,s.endOffset),o=r.toString().length,r.selectNodeContents(t),r.setEnd(s.startContainer,s.startOffset),e=r.toString().length}return{selectionStart:e,selectionEnd:o}}function zi(t){let{selectionStart:e,selectionEnd:o}=on(t)?xd(t):t;return[e,o]}function nn(t){let[,e]=_d(),o=vd(null);return o.current=zi(t),Sd(()=>{let n=()=>{let[s,r]=o.current??[],i=zi(t);(!i||s!==i[0]||r!==i[1])&&(o.current=i,e({}))};return t.addEventListener("keyup",n),t.addEventListener("click",n),t.addEventListener("focus",n),document.addEventListener("selectionchange",n),()=>{t.removeEventListener("keyup",n),t.removeEventListener("click",n),t.removeEventListener("focus",n),document.removeEventListener("selectionchange",n)}},[t]),o.current}function sn(t,e){if(!e)return;let o=t,{value:n}=o,[s,r]=e,i=n.match(rt);if(!i||i.length===0)return;let a=0;i.find(l=>{let c=n.indexOf(l,a);return s>c&&r<c+l.length?(o.selectionStart=c,o.selectionEnd=c+l.length,!0):(a=c+l.length,!1)})}import{useEffect as bd}from"react";function ut(t){bd(()=>{let e=o=>{o.isWithinRoot||t(o)};return document.body.addEventListener("mouseup",e),()=>{document.body.removeEventListener("mouseup",e)}},[t])}function qe(t){t.addEventListener("mouseup",e=>{e.isWithinRoot=!0},!0)}var ji,ce=new Map,Cd=["bottom","height","left","right","top","width"],wd=(t={},e={})=>Cd.some(o=>t[o]!==e[o]),qi=()=>{let t=[];ce.forEach((e,o)=>{if(!o.isConnected){e.rect=null,t.push(e),ce.delete(o);return}let n=o.getBoundingClientRect();wd(n,e.rect)&&(e.rect=n,t.push(e))}),t.forEach(e=>{e.callbacks.forEach(o=>o(e.rect))}),ce.size!==0&&(ji=window.requestAnimationFrame(qi))};function Vi(t,e){return{observe(){let o=ce.size===0;if(ce.has(t)){let n=ce.get(t);n.callbacks.push(e),n.rect&&e(n.rect)}else ce.set(t,{rect:void 0,callbacks:[e]});o&&qi()},unobserve(){let o=ce.get(t);if(o){let n=o.callbacks.indexOf(e);n>=0&&o.callbacks.splice(n,1),o.callbacks.length||ce.delete(t),ce.size||cancelAnimationFrame(ji)}}}}var Wi,pe=new Map,Gi=()=>{pe.forEach((t,e)=>{if(!e.isConnected){pe.delete(e);return}let{clientHeight:o,scrollHeight:n}=e,s=n>o;t.visible!==s&&(t.visible=s,t.callbacks.forEach(r=>r(t.visible)))}),pe.size!==0&&(Wi=window.requestAnimationFrame(Gi))};function $i(t,e){return{observe(){let o=pe.size===0;pe.has(t)?pe.get(t).callbacks.push(e):pe.set(t,{visible:void 0,callbacks:[e]}),o&&Gi()},unobserve(){let o=pe.get(t);if(o){let n=o.callbacks.indexOf(e);n>=0&&o.callbacks.splice(n,1),o.callbacks.length||pe.delete(t),pe.size||cancelAnimationFrame(Wi)}}}}var Ts=["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 Es(t,e,o){return o.forEach(n=>{e.style[n]=t[n]})}function dt(t){return parseFloat(t)}function rn(t){return Math.round(t*1e6)}function Xi(t){return t/1e6}function ks(t,e,o){if(t.boxSizing==="content-box")return;let{clientWidth:n}=e,s=dt(t.width),r=dt(t.borderLeftWidth),i=dt(t.borderRightWidth),a=dt(t.paddingRight),l=Xi(rn(s)-rn(r)-rn(i)),c=Xi(rn(n));if(l-c>2){let p=l-c;o.style.paddingRight=`${a+p}px`}}function jt(t,e={}){var l;let o=e.overlayContainer||document.createElement("div");o.style.display="none",o.style.position="fixed",o.style.pointerEvents="none",o.style.borderColor="transparent",qe(o);let n=window.getComputedStyle(t),s=!0,r=()=>{o.scrollTop=t.scrollTop};Es(n,o,Ts),ks(n,t,o),e.mirrorOverflow&&(o.style.overflow="hidden",t.addEventListener("scroll",r));let i=$i(t,()=>{Es(n,o,Ts),ks(n,t,o),r(),setTimeout(r,0)}),a=Vi(t,c=>{if(c===null){e.onRemove&&e.onRemove(),o.remove();return}if(c.height===0&&c.width===0){if(s===!0)return;e.onHide&&e.onHide(),o.style.display="none",s=!0;return}if(Es(n,o,Ts),ks(n,t,o),r(),o.style.top=`${c.top}px`,o.style.left=`${c.left}px`,e.closestScrollElement&&e.closestScrollElement!==t){let p=e.closestScrollElement.getBoundingClientRect(),u=window.getComputedStyle(e.closestScrollElement),d=dt(u.borderTopWidth),m=dt(u.borderBottomWidth),h=p.top+d-c.top,g=c.top+c.height+-(p.top+p.height-m);o.style.clipPath=`inset(${h}px 0px ${g}px 0px)`}s&&(o.style.display="block",e.onShow&&e.onShow(),s=!1)});return e.appendTo?e.appendTo.appendChild(o):(l=t.parentElement)==null||l.appendChild(o),a.observe(),i.observe(),[o,()=>{t.removeEventListener("scroll",r),a.unobserve(),i.unobserve()}]}var Rs={};z(Rs,{enUS:()=>Td,nlNL:()=>Ed});var Td={placeholders:[{type:6,value:"placeholderSize",options:{"=0":{value:[{type:0,value:"No placeholders found"}]},one:{value:[{type:0,value:"There is one placeholder in your message"}]},other:{value:[{type:0,value:"There are "},{type:7},{type:0,value:" placeholders in your message"}]}},offset:0,pluralType:"cardinal"}]},Ed={placeholders:[{type:6,value:"placeholderSize",options:{"=0":{value:[{type:0,value:"Alle placeholders zijn uit je bericht"}]},one:{value:[{type:0,value:"Er is 1 placeholder in jouw bericht"}]},other:{value:[{type:0,value:"Er zijn "},{type:7},{type:0,value:" placeholders in jouw bericht"}]}},offset:0,pluralType:"cardinal"}]};import{jsx as Qi,jsxs as kd}from"react/jsx-runtime";var Zi=()=>kd("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 512 512","aria-labelledby":"circleCheckTitle",children:[Qi("title",{id:"circleCheckTitle",children:"Check"}),Qi("path",{d:"M243.8 339.8C232.9 350.7 215.1 350.7 204.2 339.8L140.2 275.8C129.3 264.9 129.3 247.1 140.2 236.2C151.1 225.3 168.9 225.3 179.8 236.2L224 280.4L332.2 172.2C343.1 161.3 360.9 161.3 371.8 172.2C382.7 183.1 382.7 200.9 371.8 211.8L243.8 339.8zM512 256C512 397.4 397.4 512 256 512C114.6 512 0 397.4 0 256C0 114.6 114.6 0 256 0C397.4 0 512 114.6 512 256zM256 48C141.1 48 48 141.1 48 256C48 370.9 141.1 464 256 464C370.9 464 464 370.9 464 256C464 141.1 370.9 48 256 48z"})]});import{jsx as Ji}from"react/jsx-runtime";var Yi=()=>Ji("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",fill:"currentColor",children:Ji("path",{d:"M256 32c14.2 0 27.3 7.5 34.5 19.8l216 368c7.3 12.4 7.3 27.7 .2 40.1S486.3 480 472 480H40c-14.3 0-27.6-7.7-34.7-20.1s-7-27.8 .2-40.1l216-368C228.7 39.5 241.8 32 256 32zm0 128c-13.3 0-24 10.7-24 24V296c0 13.3 10.7 24 24 24s24-10.7 24-24V184c0-13.3-10.7-24-24-24zm32 224c0-17.7-14.3-32-32-32s-32 14.3-32 32s14.3 32 32 32s32-14.3 32-32z"})});var ea=(i=>(i.CUT="Cut",i.BACKSPACE="Backspace",i.DELETE="Delete",i.ERASEEOF="EraseEof",i.UNDO="Undo",i.CLEAR="Clear",i))(ea||{}),Le=class{constructor(e){this.element=e;this.currentText=this.getText(),this.currentHTML=this.getHTML(),this.listen()}eventListeners={};disposeHandlers=[];currentText="";currentSelection={start:0,end:0};currentHTML="";isFocused=!1;isActive=!0;isSettingValue=!1;isSubmitting=!1;isPossibleClearInputAction=!1;isDisposed=!1;addEventListener(e,o){let n=s=>{o(s)};this.element.addEventListener(e,n),this.disposeHandlers.push(()=>{this.element.removeEventListener(e,n)})}removeEventListener(e,o){this.element.removeEventListener(e,o)}triggerChange(){let e=this.getText(),o=this.getHTML(),n=e!==this.currentText;this.isActive&&(e===""&&this.currentText!==""&&!this.isSettingValue&&!this.isPossibleClearInputAction&&(this.isSubmitting=!0,this.emit("submit")),!this.isSettingValue&&n&&!this.isSubmitting&&this.emit("change",{plainText:e}),n&&(this.currentSelection=this.getSelection()),this.currentText=e,this.isSubmitting=!1,(this.currentHTML!==o||o===null&&n)&&(this.emit("updated",{plainText:e}),this.currentHTML=o))}triggerSelection(){let e=this.getSelection();(e.start!==this.currentSelection.start||e.end!==this.currentSelection.end)&&(this.currentSelection=e,this.emit("selection",e))}handleKeyUp(e){let{key:o,shiftKey:n}=e;(o==="Enter"&&n===!0||o==="Backspace")&&this.triggerChange(),this.triggerSelection()}handleClick(){this.triggerSelection()}handleFocus(){this.isFocused||this.emit("focus"),this.triggerSelection(),this.isFocused=!0}handleBlur(){this.isPossibleClearInputAction=!1,this.isFocused&&this.emit("blur"),this.isFocused=!1}handleKeyDown(e){let{key:o,ctrlKey:n,metaKey:s}=e;this.isPossibleClearInputAction=Object.values(ea).includes(o)||o.toLowerCase()==="z"&&(n||s),this.emit("keydown",e)}handleCut(){this.isPossibleClearInputAction=!0,this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(e){var n,s;let o=((n=e.clipboardData)==null?void 0:n.getData("text"))||((s=e.clipboardData)==null?void 0:s.getData("text/plain"))||"";this.emit("paste",{pastedText:o,selectionText:this.getSelectedText()})}listen(){this.addEventListener("keydown",o=>this.handleKeyDown(o)),this.addEventListener("keyup",o=>this.handleKeyUp(o)),this.addEventListener("input",()=>this.triggerChange()),this.addEventListener("change",()=>this.triggerChange()),this.addEventListener("focus",()=>this.handleFocus()),this.addEventListener("blur",()=>this.handleBlur()),this.addEventListener("cut",()=>this.handleCut()),this.addEventListener("paste",o=>this.handlePaste(o)),this.addEventListener("click",()=>this.triggerSelection()),document.activeElement===this.element&&setTimeout(()=>{this.handleFocus()},0);let e=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});e.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{e.disconnect()})}focus(){this.element.focus()}emit(e,...o){this.isDisposed||this.eventListeners[e]&&this.eventListeners[e].forEach(n=>{n(...o)})}on(e,o){this.isDisposed||(this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(o))}activate(){let e=this.isActive===!1;this.isActive=!0,e&&this.triggerChange()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(e=>e()),this.eventListeners={},this.isDisposed=!0}};var Me=class extends Le{lastKnownSelection=null;getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:e,selectionEnd:o}=this.element;return{start:e,end:o}}getSelectedText(){let e=this.getSelection();return e?this.getText().slice(e.start,e.end):""}applyChanges(e){if(!this.isActive)return;this.isSettingValue=!0;let o=this.getText(),n=e(this.element);return Promise.resolve(n).then(()=>{this.currentText=this.getText(),o!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(){super.listen();let e=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var s;return(s=e==null?void 0:e.get)==null?void 0:s.call(this.element)},set:s=>{var r;(r=e==null?void 0:e.set)==null||r.call(this.element,s),this.triggerChange()}});let o=this.element.disabled,n=new MutationObserver(()=>{this.element.disabled!==o&&(o=this.element.disabled,this.emit(o?"disabled":"enabled"))});n.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>n.disconnect())}};import{jsx as he,jsxs as Ps}from"react/jsx-runtime";var Ad=({value:t,onUse:e,...o})=>{var p;let n=w(Rs),s=Pd(),r=y("EditSuggestionTextInput",ws),[i,a]=Rd(null),l=Is(null),c=((p=t.match(rt))==null?void 0:p.length)||0;return qt(()=>{let u;return l.current&&(a(l.current),u=new Me(l.current),u.on("change",({plainText:d})=>{s(W.actions.userInput({text:d,selection:u.getSelection()}))}),u.on("keydown",d=>{s(W.actions.registerKeyDown(Go(d))),d.code==="Enter"&&d.shiftKey&&e(u.getText())}),u.on("paste",({pastedText:d,selectionText:m})=>{s(W.actions.registerPaste({text:d,selectionText:m}))}),u.on("cut",({selectionText:d})=>{s(W.actions.registerCut(d))})),()=>{s(W.actions.reset()),u.dispose(),u.deactivate()}},[l]),qt(()=>{t&&l.current&&(l.current.value=t)},[t,l]),qt(()=>{l.current&&setTimeout(()=>{if(!l.current)return;let u=l.current.value.length;l.current.setSelectionRange(u,u),l.current.focus()},0)},[l]),Ps("div",{className:r.textInputWrapper,children:[he("textarea",{...o,ref:l,"data-testid":"edit-suggestion-dialog-textarea",className:r.textInput,defaultValue:t,onChange:()=>{}}),i&&he(Ld,{inputElement:l.current,value:t}),Ps("div",{className:ta(r.alert,c===0?r.success:r.warning),children:[he("div",{className:r.alertText,children:n("placeholders",{placeholderSize:c})}),c===0?he(Zi,{}):he(Yi,{})]})]})},Ld=({inputElement:t,value:e})=>{let o=y("EditSuggestionTextInput",ws),n=Is(null),s=nn(t);return qt(()=>{sn(t,s)},[s,t]),he(Md,{inputElement:t,children:Ps("div",{ref:n,className:ta(o.root,o.agentText),children:[he(Id,{tagName:"span",disableLineBreaks:!0,content:e,matchers:[new pt("placeholders")],inputElement:t,boundaryRef:n}),he("br",{})]})})},Md=({inputElement:t,children:e})=>{let o=Is(null);return qt(()=>{if(!o.current)return()=>{};let[n,s]=jt(t,{overlayContainer:o.current,mirrorOverflow:!0});return n.setAttribute("translate","no"),()=>{s()}},[o.current]),he("div",{ref:o,children:e})},oa=Ad;import{useEffect as ag,useState as lg,useRef as cg}from"react";import{useState as Dd}from"react";import As from"classnames";var G={root:"_root_185k9_1",list:"_list_185k9_2",listWrapper:"_listWrapper_185k9_6",listHorizontal:"_listHorizontal_185k9_10",page:"_page_185k9_19",search:"_search_185k9_25",pageNav:"_pageNav_185k9_33",pageTitle:"_pageTitle_185k9_41",pageBackButton:"_pageBackButton_185k9_48",listHeading:"_listHeading_185k9_62",listItem:"_listItem_185k9_70",listItemContent:"_listItemContent_185k9_79",listItemText:"_listItemText_185k9_97",listItemDescription:"_listItemDescription_185k9_105",truncate:"_truncate_185k9_112",lineClamp:"_lineClamp_185k9_118",listItemTitle:"_listItemTitle_185k9_125",listItemAction:"_listItemAction_185k9_132",listItemPrimaryAction:"_listItemPrimaryAction_185k9_146",listItemSelected:"_listItemSelected_185k9_151",sources:"_sources_185k9_155",sourcesTitle:"_sourcesTitle_185k9_162",source:"_source_185k9_155",icon:"_icon_185k9_177",searchIcon:"_searchIcon_185k9_194",searchInputWrapper:"_searchInputWrapper_185k9_199",searchInput:"_searchInput_185k9_199",select:"_select_185k9_220",selectType:"_selectType_185k9_237",selectWrapper:"_selectWrapper_185k9_241",image:"_image_185k9_271",imageSrc:"_imageSrc_185k9_278",imageSrcHidden:"_imageSrcHidden_185k9_289",imageSrcStatus:"_imageSrcStatus_185k9_293",imageTitle:"_imageTitle_185k9_303",actions:"_actions_185k9_308",actionsWrapper:"_actionsWrapper_185k9_312",actionsBar:"_actionsBar_185k9_318",actionButton:"_actionButton_185k9_327",actionShortcut:"_actionShortcut_185k9_345",actionShortcutFixKerning:"_actionShortcutFixKerning_185k9_352"};var Ve={};z(Ve,{enUS:()=>Nd,nlNL:()=>Od});var Nd={visitUrl:[{type:0,value:"Visit"}],back:[{type:0,value:"Back"}],loading:[{type:0,value:"Loading..."}],imageError:[{type:0,value:"Could not load image"}]},Od={visitUrl:[{type:0,value:"Bekijk"}],back:[{type:0,value:"Terug"}],loading:[{type:0,value:"Laden..."}],imageError:[{type:0,value:"Kan afbeelding niet laden"}]};import{jsx as Vt,jsxs as Bd}from"react/jsx-runtime";var Hd=({src:t,title:e})=>{let o=y("CommandPalette",G),[n,s]=Dd("loading"),r=w(Ve);return Bd("div",{className:o.image,children:[Vt("img",{src:t,alt:e,onLoad:()=>s("done"),onError:()=>s("error"),className:As(o.imageSrc,{[o.imageSrcHidden]:["loading","error"].includes(n)})}),n==="loading"&&Vt("span",{className:As(o.imageSrc,o.imageSrcStatus),children:r("loading")}),n==="error"&&Vt("span",{className:As(o.imageSrc,o.imageSrcStatus),children:Vt(_o,{})}),e&&Vt("span",{className:o.imageTitle,children:e})]})},na=Hd;import Fd from"react";import Kd from"classnames";import{jsx as sa,jsxs as Ud}from"react/jsx-runtime";function Ls({children:t,heading:e,orientation:o}){let n=y("CommandPalette",G);return Fd.Children.count(t)===0?null:Ud("div",{"data-testid":"commandpalette-list",className:n.list,children:[e&&sa("h4",{className:n.listHeading,children:e}),sa("div",{className:Kd(n.listWrapper,o==="horizontal"&&n.listHorizontal),children:t})]})}import an from"classnames";import Ms from"react";import{jsx as zd}from"react/jsx-runtime";var ra=Ms.createContext(void 0);function Ne(){let t=Ms.useContext(ra);if(t===void 0)throw new Error("useCommandPalette must be used within the CommandPalette component");return t}var ia=({children:t,page:e,isOpen:o,onChangeOpen:n,selected:s,setSelected:r})=>{let i=Ms.useMemo(()=>({page:e,isOpen:o,onChangeOpen:n,selected:s,setSelected:r}),[o,e,s]);return zd(ra.Provider,{value:i,children:t})};import{jsx as gt,jsxs as ln}from"react/jsx-runtime";function Ns({closeOnSelect:t=!0,lineClamp:e,children:o,onClick:n,onSourceClick:s,index:r,isExperimental:i,description:a,sources:l,styles:c,...p}){let{selected:u,onChangeOpen:d}=Ne(),m=y("CommandPalette",G);function h(g){n(g),t&&d(!1)}return ln("div",{className:an(m.listItem,u===r&&m.listItemSelected),children:[ln("button",{type:"button",className:an("command-palette-list-item",m.listItemAction,m.listItemPrimaryAction),"aria-disabled":p.disabled??!1,onClick:h,...p,children:[ln("div",{className:m.listItemContent,children:[typeof o=="string"?gt("p",{className:an(m.listItemText,m.truncate,c==null?void 0:c.title),children:o}):o,a&>("p",{className:an(m.listItemDescription,c==null?void 0:c.description,e?m.lineClamp:m.truncate),children:a})]}),i&>(Do,{})]}),l&&ln("div",{className:m.sources,children:[gt("span",{className:m.sourcesTitle,children:"Sources"}),l.map(g=>g.url?gt("a",{className:m.source,href:g.url,target:"_blank",title:g.url,rel:"noopener noreferrer",onClick:()=>s&&s(g),children:g.name},g.url):gt("span",{className:m.source,children:g.name},g.name))]})]})}import{jsx as Os,jsxs as Ds}from"react/jsx-runtime";function Hs({children:t,title:e,id:o,onDismiss:n,isExperimental:s}){let r=w(Ve),i=y("CommandPalette",G),{page:a}=Ne();return a!==o?null:Ds("div",{className:i.page,id:`page_${o}`,tabIndex:-1,children:[n&&Ds("div",{className:i.pageNav,children:[Ds("button",{className:i.pageBackButton,type:"button",onClick:n,children:[Os(en,{}),r("back")]}),e&&Os("h3",{className:i.pageTitle,children:e}),s&&Os(Do,{})]}),t]})}import{Fragment as Yd,useCallback as eg,useEffect as tg,useRef as og}from"react";var cn=()=>/Mac/i.test(navigator.platform);import{createAsyncThunk as Gd,createSlice as $d}from"@reduxjs/toolkit";var jd={info(...t){console.info("[Deepdesk]",...t)},warn(...t){console.warn("[Deepdesk]",...t)},error(...t){console.error("[Deepdesk]",...t)}},k=jd;import{createAsyncThunk as Fs,createSlice as Vd}from"@reduxjs/toolkit";function qd(t){return t.replace(/(_\w)/g,e=>e[1].toUpperCase())}function L(t){return Array.isArray(t)?t.map(L):typeof t=="object"&&t!==null?Object.keys(t).reduce((e,o)=>({...e,[qd(o)]:L(t[o])}),{}):t}function Bs(t){return t.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}function F(t){return Array.isArray(t)?t.map(F):typeof t=="object"&&t!==null?Object.keys(t).reduce((e,o)=>({...e,[Bs(o)]:F(t[o])}),{}):t}var Wd={agentInfo:void 0,agentSettings:{},visitorInfo:void 0,fetchState:"idle"},Gt=t=>{var e,o,n;return{timezone:((e=t.info.visitorInfo)==null?void 0:e.visitorTimeZone)||Intl.DateTimeFormat().resolvedOptions().timeZone,agentName:((o=t.info.agentInfo)==null?void 0:o.agentNickname)||"",visitorName:((n=t.info.visitorInfo)==null?void 0:n.visitorName)||""}},Wt=Fs("info/setAgentInfo",async(t,e)=>{let{deepdeskAPI:o}=e.extra;if(!t.agentId&&!t.agentNickname)throw new Error("At least provide agentId or agentNickname");let n=await o.client.get("/apis/admin/session/me/",{version:null}),s={};return n.external_id||(s.external_id=t.agentId),n.nickname||(s.nickname=t.agentNickname),!s.external_id&&!s.nickname?L(n):(await o.client.patch("/apis/admin/session/me/",s,{version:null}),L(n))}),Ks=Fs("info/setAgentSettings",async(t,e)=>{let{deepdeskAPI:o}=e.extra,n=await o.client.get("/apis/admin/session/me/",{version:null}),s={...typeof n.ui_config=="object"?n.ui_config:{},...t};return await o.client.patch("/apis/admin/session/me/",{ui_config:s}),s}),Us=Fs("info/getAgentSettings",async(t,e)=>{let{deepdeskAPI:o}=e.extra;return(await o.client.get("/apis/admin/session/me/",{version:null})).ui_config}),aa=t=>t.info.agentInfo,la=Vd({name:"info",initialState:Wd,reducers:{setVisitorInfo(t,e){t.visitorInfo={...t.visitorInfo,...e.payload}}},extraReducers:t=>{t.addCase(Wt.pending,(e,o)=>{e.fetchState="loading",e.agentInfo={...e.agentInfo,...o.meta.arg}}).addCase(Wt.rejected,e=>{e.fetchState="error"}).addCase(Wt.fulfilled,(e,o)=>{e.fetchState="done",e.agentInfo={...e.agentInfo,...o.meta.arg,agentId:o.payload.externalId||o.meta.arg.agentId||"",agentNickname:o.payload.nickname||o.meta.arg.agentNickname||""}}).addCase(Ks.fulfilled,(e,o)=>{e.agentSettings=o.payload}).addCase(Us.fulfilled,(e,o)=>{e.agentSettings=o.payload}).addCase(P,e=>{e.visitorInfo=void 0})}}),{setVisitorInfo:ca}=la.actions,pa=la.reducer;var pn={list:[],fetchState:"idle",isOpen:!1,page:"search"},ua=t=>t.search.isOpen,da=t=>t.search.page,ga=t=>t.search.list;function ma(t,e=o=>o){return o=>o.search.list.filter(n=>n.type===t).map(e)}var We=Gd("search/getAll",async(t,e)=>{var i;let{deepdeskAPI:o}=e.extra,n=e.getState(),s=(i=n.conversation.current)==null?void 0:i.profileCode;if(!s)throw new Error("Profile should be provided in order to be able to search");let{results:r}=await o.search({profile:s,query:t.query,filters:{type:t.type},params:Gt(n),tags:t.tags});return r.map(a=>({...a,source:`search-${a.type.toLowerCase()}`,searchTerm:t.query}))}),fa=$d({name:"search",initialState:pn,reducers:{setIsOpen(t,e){t.isOpen=e.payload},setPage(t,e){t.page=e.payload},resetSearch(t){t.fetchState=pn.fetchState,t.list=pn.list}},extraReducers:t=>{t.addCase(We.pending,e=>{e.fetchState="loading"}).addCase(We.rejected,(e,o)=>{e.fetchState="error",k.error(o.error)}).addCase(We.fulfilled,(e,o)=>{e.fetchState="done",e.list=o.payload}).addCase(P,()=>pn)}}),{resetSearch:un,setIsOpen:Y,setPage:q}=fa.actions,ha=fa.reducer;var Xd=/(https?:\/\/[^\s]+)/,dn=t=>t.split(" ").find(e=>Xd.test(e));import ya from"classnames";import{jsx as Zd,jsxs as Jd}from"react/jsx-runtime";var Qd=({onClick:t,shortKeys:e,children:o,...n})=>{let s=y("CommandPalette",G);return Jd("button",{type:"button",...n,onClick:t,className:ya(s.actionButton,n.className),children:[o,e&&e.map(r=>Zd("span",{className:ya(s.actionShortcut,r===8629&&s.actionShortcutFixKerning),children:typeof r=="number"?String.fromCharCode(r):r},r))]})},mt=Qd;import{jsx as gn,jsxs as zs}from"react/jsx-runtime";var ng=({children:t,primaryLabel:e,secondaryLabel:o,onPrimary:n,onSecondary:s,list:r})=>{let i=y("CommandPalette",G),a=w(Ve),{selected:l,setSelected:c}=Ne(),p=r[l],u=p&&typeof p.text=="string"&&dn(p.text),d=og(null);function m(_){if(!d.current)return;let x=d.current.querySelectorAll(".command-palette-list-item"),C=0,T=0;_==="down"?(x.forEach((ee,D)=>{D===l&&(C=D)}),T=C===x.length-1?0:C+1):_==="up"?(x.forEach((ee,D)=>{D===l&&(C=D)}),T=C?C-1:x.length-1):c(0);let N=x[T];N&&typeof T=="number"&&(c(T),N.scrollIntoView&&N.scrollIntoView({behavior:"smooth",block:T?"center":"end"}))}function h(){if(!d.current)return;let _=d.current.querySelectorAll(".command-palette-list-item"),x=0;_.forEach((T,N)=>{N===l&&(x=N)});let C=_[x];C&&C.click()}let g=()=>{u&&window.open(u,"_blank")},v=()=>{p&&n(p,l)},E=()=>{!p.type||["IMAGE","command"].includes(p.type)||s&&s(p,l)},f=eg(_=>{if(_.key==="Enter"&&_.altKey&&u){g();return}if(_.key==="Enter"&&_.shiftKey){E();return}if(_.key==="ArrowDown"){_.preventDefault(),_.stopPropagation(),m("down");return}if(_.key==="ArrowUp"){_.preventDefault(),_.stopPropagation(),m("up");return}_.key==="Enter"&&l!==-1&&(_.preventDefault(),_.stopPropagation(),h())},[l]);return tg(()=>(window.addEventListener("keyup",f),()=>{window.removeEventListener("keyup",f)}),[f]),zs("div",{className:i.actions,children:[gn("div",{className:i.actionsWrapper,ref:d,children:t}),zs("div",{className:i.actionsBar,children:[u&&gn(mt,{onClick:g,shortKeys:[cn()?8997:"ALT",8629],children:a("visitUrl")}),p&&zs(Yd,{children:[s&&p.type&&!["command","image"].includes(p.type.toLowerCase())&&gn(mt,{onClick:E,shortKeys:[8679,8629],children:o}),gn(mt,{onClick:v,shortKeys:[8629],children:e})]})]})]})},va=ng;import{forwardRef as rg}from"react";import{jsx as _a,jsxs as sg}from"react/jsx-runtime";var ft=()=>sg("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 0 24 24",width:"1em",fill:"currentColor",children:[_a("path",{d:"M0 0h24v24H0z",fill:"none"}),_a("path",{d:"M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"})]});import{jsx as ht,jsxs as js}from"react/jsx-runtime";function ig({onChange:t,onChangeType:e,placeholder:o,typePlaceholder:n,types:s,value:r,selectedType:i},a){let l=y("CommandPalette",G);return js("div",{className:l.search,children:[ht("div",{className:l.searchIcon,children:ht(ft,{})}),js("div",{className:l.searchInputWrapper,children:[ht("input",{ref:a,spellCheck:!1,autoComplete:"off",onChange:c=>{t(c.currentTarget.value)},onFocus:c=>{c.currentTarget.select()},className:l.searchInput,placeholder:o,value:r,type:"text",id:"command-palette-search-input",autoFocus:!0}),s&&s.length>0&&ht("div",{className:l.selectWrapper,children:js("select",{"data-testid":"command-palette-type-select",className:l.select,onChange:c=>e(c.target.value===n?void 0:c.target.value),value:i||n,children:[n&&ht("option",{children:n}),s.map(c=>ht("option",{value:c.value,children:c.label},c.value))]})})]})]})}var xa=rg(ig);import{jsx as ba,jsxs as pg}from"react/jsx-runtime";function Ge({placeholder:t="Start typing to search...",typePlaceholder:e="All types",defaultPage:o="search",page:n,onChangePage:s,onChangeSearch:r,onChangeType:i,onChangeOpen:a,selectedType:l,types:c,children:p,isOpen:u,search:d}){let[m,h]=lg(0),g=cg(null),v=()=>{s&&s(o),i(void 0),r(""),a(!1)},E=()=>{var f;if(n!==o&&s){s(o);return}if(l&&i){i(void 0),(f=g.current)==null||f.focus();return}if(d.length>0){r("");return}a(!1)};return ag(()=>{h(0)},[d,n]),ba(ct,{autoFocus:!0,contentAriaLabel:"Search Results",overlayAriaLabel:"Command Palette",isOpen:u,onBack:E,onClose:v,children:pg(ia,{selected:m,setSelected:h,isOpen:u,onChangeOpen:a,page:n,children:[n===o&&ba(xa,{ref:g,onChange:r,onChangeType:i,placeholder:t,value:d,selectedType:l,types:c,typePlaceholder:e}),p]})})}Ge.Page=Hs;Ge.List=Ls;Ge.Image=na;Ge.ListItem=Ns;Ge.ActionsBar=va;Ge.Button=mt;var I=Ge;import{jsx as ye,jsxs as $t}from"react/jsx-runtime";var gg=({suggestion:t,onUse:e,onDismiss:o,onTouched:n,onNext:s,onPrevious:r})=>{let i=t.text||t.url||t.message,a=y("EditSuggestionForm",Di),l=ug(),c=w(Cs),p=dg(h=>h.overlayInput.text);Ca(()=>{t&&(l(W.actions.reset()),l(W.actions.stageSuggestion({text:i,suggestion:t,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"})),l(W.actions.commitSuggestion()))},[t]);let u=h=>{h.preventDefault(),d(p)},d=h=>{l(Qo(h)),e(h)},m=h=>g=>{p!==i?window.confirm(c("warning"))&&h(g):h(g)};return Ca(()=>{n&&n(p!==i)},[n,t,p]),$t("div",{className:a.root,children:[$t("div",{className:a.content,children:[t.title&&ye("h3",{className:a.title,children:t.title}),t.searchKeywords&&t.searchKeywords.length>0&&ye(fs,{labels:t.searchKeywords}),ye(oa,{onUse:d,value:p})]}),$t("form",{className:a.actions,onSubmit:u,children:[$t("div",{children:[ye("button",{disabled:!r,className:a.pagination,type:"button",onClick:r&&m(r),children:ye(en,{})}),ye("button",{disabled:!s,className:a.pagination,type:"button",onClick:s&&m(s),children:ye(Fi,{})})]}),$t("div",{className:a.primaryButtons,children:[ye(I.Button,{onClick:m(o),shortKeys:["esc"],children:c("dismiss")}),ye(I.Button,{shortKeys:[8679,8629],type:"submit",children:c("add")})]})]})]})},mn=gg;import{createAction as hg,createAsyncThunk as ka,createSlice as yg}from"@reduxjs/toolkit";var mg=["{amount}"," {amount}","{date}","{email}","{iban}","{name}","{postal_code}","{street}","{tarif}","{usage}","{3_digits}","{4_digits}","{5_digits}","{6_digits}","{7_digits}","{8_digits}","{9_digits}","{10_digits}"],fg=new RegExp(mg.map(t=>`(?:${t.replace("{","\\{").replace("}","\\}")})`).join("|"));function wa(t,e){let o=t.split(fg),n=0,s=[];for(let r=0;r<o.length;r++){let i=o[r];if(s.push(i),r===o.length-1)break;if(e.indexOf(i)===-1)return t;let a=o[r+1],l=r===o.length-2;n+=i.length;let c=n;if(l){let u=a.charAt(0),d=0;do c=u?e.indexOf(u,c+1):-1,d+=1;while(c!==-1&&a.indexOf(e.slice(c))!==0);if(c===-1&&d>2)return t}else c=a&&a!==""?e.indexOf(a,n):-1;let p=c===-1?e.slice(n):e.slice(n,c);s.push(p),n=c}return s.join("")}function Ta(t,e){return typeof e=="boolean"?t:t.slice(0,e)}var Ra={suggestions:[],fetchState:"idle",isInitialRequest:null},Ea={default:Ra},Pa=t=>e=>{var o;return((o=e.textSuggestions[t])==null?void 0:o.suggestions)||[]},Ia=t=>e=>{var o;return((o=e.textSuggestions[t])==null?void 0:o.suggestions)??[]},Aa=t=>{let e=Object.keys(t.textSuggestions).map(o=>{var n;return(n=t.textSuggestions[o])==null?void 0:n.fetchState});return e.length===0?!0:e.every(o=>o!=="done")},yt=t=>t.textSuggestions,La=t=>e=>e.text.startsWith(t),fn=hg("textSuggestions/refresh"),Se=ka("textSuggestions/recommendations",async(t,e)=>{var c;let{deepdeskAPI:o}=e.extra,n=e.getState(),s=(c=n.conversation.current)==null?void 0:c.id,{textSuggestionsCount:r,inlineSuggestions:i}=n.settings,a=lt(n);if(!s)throw new Error("No current conversation to fetch text suggestions");let l=await o.getTextSuggestions(s,Gt(n),t);if(t==="default"){let p=i?l.filter(La(a)):l;e.dispatch(Ie(p.slice(0,r)))}return l}),Xt=ka("textSuggestions/autocompletions",async(t,e)=>{var c;let{deepdeskAPI:o}=e.extra,n=e.getState(),s=(c=n.conversation.current)==null?void 0:c.id,{textSuggestionsCount:r,deanonymize:i,inlineSuggestions:a}=n.settings;if(!s)throw new Error("No current conversation to fetch text suggestions");let l=await o.getAutocompleteSuggestions(s,{...Gt(n),input:t});if(!e.getState().input.text)throw new Error("Abort");return a&&(l=l.filter(La(t))),i&&(l=l.map(p=>({...p,text:p.source!=="trie-with-typos"?wa(p.text,t):p.text}))),l=Ta(l,r),e.dispatch(Ie(l)),l}),Ma=yg({name:"textSuggestions",initialState:Ea,reducers:{setTextSuggestions:{reducer(t,e){let{contentType:o}=e.payload;t[o].fetchState="done",t[o].suggestions=e.payload.suggestions},prepare(t,e){return{payload:{contentType:t,suggestions:e}}}},setSuggestionState(t,e){return e.payload}},extraReducers:t=>{t.addCase(Se.pending,(e,o)=>{let n=o.meta.arg,s=e[n]||Ra;return{...e,[n]:{...s,fetchState:"loading",isInitialRequest:s.isInitialRequest===null}}}).addCase(Se.rejected,(e,o)=>{let n=o.meta.arg;e[n]&&(e[n].fetchState="error")}).addCase(Se.fulfilled,(e,o)=>{let n=o.meta.arg;e[n]&&(e[n].fetchState="done",e[n].suggestions=o.payload)}).addCase(Xt.pending,e=>{e.default.fetchState="loading"}).addCase(Xt.rejected,e=>{e.default.fetchState="error"}).addCase(Xt.fulfilled,(e,o)=>{e.default.fetchState="done",e.default.suggestions=o.payload}).addCase(P,()=>Ea)}}),{setTextSuggestions:Na,setSuggestionState:Oa}=Ma.actions,Da=Ma.reducer;import{createSlice as Sg}from"@reduxjs/toolkit";var Ha={contentType:null,suggestion:null},Ba=t=>t.activeSuggestion.suggestion,Fa=t=>t.activeSuggestion.contentType,Ka=Sg({name:"activeSuggestion",initialState:Ha,reducers:{setActiveSuggestion(t,e){let{contentType:o,suggestion:n}=e.payload;t.contentType=o,t.suggestion=n},resetActiveSuggestion(t){t.contentType=null,t.suggestion=null}},extraReducers:t=>{t.addCase(P,()=>Ha)}}),{setActiveSuggestion:ve,resetActiveSuggestion:qs}=Ka.actions,Ua=Ka.reducer;var Vs={};z(Vs,{enUS:()=>vg,nlNL:()=>_g});var vg={warning:[{type:0,value:"Are you sure you want to discard the message?"}],editContentLabel:[{type:0,value:"Edit and view suggestion"}],overlayLabel:[{type:0,value:"Close dialog"}]},_g={warning:[{type:0,value:"Weet je zeker dat je de wijzigingen wilt weggooien?"}],editContentLabel:[{type:0,value:"Bewerk en bekijk suggestie"}],overlayLabel:[{type:0,value:"Sluit"}]};import{createSlice as xg}from"@reduxjs/toolkit";var bg={showTabHint:!1,inputHasFocus:!1,overlayCollapsed:!1,openOverlayWhenTyping:!1,overlayCollapsedUserOverwrite:!1};var za=({ui:t})=>t.overlayCollapsed;var ja=xg({name:"ui",initialState:bg,reducers:{setShowTabHint(t,e){t.showTabHint=e.payload},setInputHasFocus(t,e){t.overlayCollapsedUserOverwrite!==!0&&(e.payload===!0&&(t.overlayCollapsed=!1),t.inputHasFocus=e.payload)},setOverlayCollapsed(t,e){e.payload.collapse===!1&&(t.openOverlayWhenTyping=!1),!(e.payload.skipWhenInputFocus&&t.inputHasFocus)&&(t.overlayCollapsed=e.payload.collapse)},setOpenOverlayWhenTyping(t,e){t.openOverlayWhenTyping=e.payload},setOverlayCollapsedUserOverwrite(t,e){t.overlayCollapsedUserOverwrite=e.payload,t.overlayCollapsed=e.payload}}}),{setShowTabHint:Qt,setInputHasFocus:St,setOverlayCollapsed:vt,setOpenOverlayWhenTyping:qa,setOverlayCollapsedUserOverwrite:Va}=ja.actions,Wa=ja.reducer;import Ga,{useContext as Cg}from"react";import{jsx as wg}from"react/jsx-runtime";var $a=Ga.createContext(null),Zt=({broadcastEvents:t,children:e})=>{let o=Ga.useMemo(()=>t,[]);return wg($a.Provider,{value:o,children:e})},oe=()=>{let t=Cg($a);if(!t)throw new Error("You should use the useBroadcastEvents within a BroadcastEventsProvider");return t};import{createAsyncThunk as Ws,createSlice as Tg}from"@reduxjs/toolkit";var Eg={isLoggedIn:!0,loginFetchState:"idle",verifyFetchState:"idle",showLoginOverlay:!1},_e=t=>t.auth.isLoggedIn,Xa=t=>t.auth.loginFetchState,Qa=t=>t.auth.verifyFetchState,Za=t=>t.auth.showLoginOverlay,Oe=Ws("auth/validate",async(t,e)=>e.extra.deepdeskAPI.isLoggedIn()),Ja=Ws("auth/requestLogin",async({email:t},e)=>{let{deepdeskAPI:o}=e.extra;return o.requestLoginByEmail(t)}),Jt=Ws("auth/verifyLoginToken",async({token:t},e)=>{let{deepdeskAPI:o}=e.extra;return o.verifyLoginToken(t)}),Ya=Tg({name:"auth",initialState:Eg,reducers:{setIsLoggedIn(t,e){t.isLoggedIn=e.payload},setShowLoginOverlay(t,e){t.showLoginOverlay=e.payload}},extraReducers:t=>{t.addCase(Oe.pending,e=>{e.loginFetchState="loading"}),t.addCase(Oe.fulfilled,(e,{payload:o})=>{e.isLoggedIn=o,e.loginFetchState="done"}),t.addCase(Oe.rejected,e=>{e.loginFetchState="error",e.isLoggedIn=!1}),t.addCase(Jt.pending,e=>{e.verifyFetchState="loading"}),t.addCase(Jt.rejected,e=>{e.verifyFetchState="error"}),t.addCase(Jt.fulfilled,(e,o)=>{o.payload.isLoggedIn?e.verifyFetchState="done":e.verifyFetchState="error"})}}),{setIsLoggedIn:_t,setShowLoginOverlay:el}=Ya.actions,tl=Ya.reducer;var Gs="SetActiveSuggestion",xt="ShowLoginOverlay",$s="UserLoggedIn",kg="UserLoggedOut",xe="ApplySuggestion",Xs="ApplyImageSuggestion",Rg="ShowCommandPalette",Pg=t=>({[Gs]:e=>{t.dispatch(Oa(e.state)),t.dispatch(ve({contentType:e.contentType,suggestion:e.suggestion}))},[Rg]:e=>{t.dispatch(Y(e.isOpen)),e.page&&t.dispatch(q(e.page))},[xt]:e=>{t.dispatch(el(e))},[$s]:()=>{t.dispatch(Oe())},[kg]:()=>{t.dispatch(Oe())},[Xs]:e=>{t.dispatch(Jo({suggestion:e.suggestion}))},[xe]:e=>{t.dispatch(ie({...e,eventMetrics:{inputType:"mouse"},replace:"selection"})),t.dispatch(Ae())}}),ol=Pg;import{jsx as nl}from"react/jsx-runtime";var Lg=()=>{var h;let[t,e]=Ig(!1),o=Qs(Ba),n=Qs(Fa),s=Qs(yt),r=Ag(),i=oe(),a=w(Vs),l=()=>{o!==null&&t?window.confirm(a("warning"))&&c():c()},c=()=>{r(qs()),r(St(!0)),r(W.actions.reset())},p=(g,v)=>{r(qs()),r(St(!0)),i.send(xe,{text:g,suggestion:{...v,source:`${v.source||"text_recommendation"}-preview`}})};if(o===null||n===null)return null;let u=(h=s[n])==null?void 0:h.suggestions.indexOf(o),d=u===0||u===null?void 0:()=>r(ve({contentType:n,suggestion:s[n].suggestions[u-1]})),m=u===s[n].suggestions.length-1||u===null?void 0:()=>r(ve({contentType:n,suggestion:s[n].suggestions[u+1]}));return nl(ct,{autoFocus:!0,isOpen:u!==null,onClose:l,onBack:l,contentAriaLabel:a("editContentLabel"),overlayAriaLabel:a("overlayLabel"),children:nl(mn,{onTouched:e,onDismiss:c,onUse:g=>p(g,o),suggestion:o,onNext:m,onPrevious:d})})},sl=Lg;import{useSelector as cl}from"react-redux";import Js from"classnames";import{useCallback as al,useEffect as Bg,useMemo as Fg,useState as Ys}from"react";import{useDispatch as Kg,useSelector as Ug}from"react-redux";import Mg from"classnames";var rl={root:"_root_1ukx5_1"};import{jsx as Og}from"react/jsx-runtime";var Ng=({className:t,value:e,...o})=>{let n=y("TextInput",rl);return Og("input",{className:Mg(t,n.root),type:"text",value:e,...o})},Yt=Ng;var Zs={};z(Zs,{enUS:()=>Dg,nlNL:()=>Hg});var Dg={back:[{type:0,value:"Back"}],promptTitle:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],verifyCodeTitle:[{type:0,value:"Paste the code from your email"}],verifyCodeBody:[{type:0,value:"Copy the code from the email you just received and paste it here."}],verifyCodeInputPlaceholder:[{type:0,value:"Paste link or code here"}],verifyCodeSubmitLabel:[{type:0,value:"Sign in"}],verifyCodeError:[{type:0,value:"Sign in failed. The code is probably no longer valid. Please "},{type:8,value:"login",children:[{type:0,value:"request new code"}]},{type:0,value:"."}],requestCodeTitle:[{type:0,value:"Have a code sent to your email"}],requestCodeBody:[{type:0,value:"Enter your email and request a code. If you are an existing "},{type:1,value:"productName"},{type:0,value:" user you will receive an email with a code. If you are a new user you will receive an email asking to request access to "},{type:1,value:"productName"},{type:0,value:" first."}],requestCodeInputPlaceholder:[{type:0,value:"Enter your email"}],requestCodeSubmitLabel:[{type:0,value:"Request code"}]},Hg={back:[{type:0,value:"Terug"}],promptTitle:[{type:0,value:"Login bij "},{type:1,value:"productName"}],verifyCodeTitle:[{type:0,value:"Plak de code uit je email"}],verifyCodeBody:[{type:0,value:"Kopieer de code uit de email en plak deze hier."}],verifyCodeInputPlaceholder:[{type:0,value:"Plak hier de code"}],verifyCodeSubmitLabel:[{type:0,value:"Inloggen"}],verifyCodeError:[{type:0,value:"Inloggen is niet gelukt. De code is waarschijnlijk niet meer geldig. "},{type:8,value:"login",children:[{type:0,value:"Vraag een nieuwe code aan"}]},{type:0,value:"."}],requestCodeTitle:[{type:0,value:"Verstuur een login code naar je email"}],requestCodeBody:[{type:0,value:"Voer je e-mailadres in en krijg een login code. Als je een bestaande "},{type:1,value:"productName"},{type:0,value:" gebruiker bent krijg je een email met een code. Als je een nieuwe gebruiker bent wordt er een email verstuurd met een toegangsverzoek voor "},{type:1,value:"productName"},{type:0,value:"."}],requestCodeInputPlaceholder:[{type:0,value:"Typ hier je e-mailadres"}],requestCodeSubmitLabel:[{type:0,value:"Code aanvragen"}]};var il={root:"_root_1edpl_1",anchorButton:"_anchorButton_1edpl_5",errorMessage:"_errorMessage_1edpl_19",title:"_title_1edpl_25",subtitle:"_subtitle_1edpl_31",text:"_text_1edpl_38",input:"_input_1edpl_43",actions:"_actions_1edpl_48",button:"_button_1edpl_55",primaryButton:"_primaryButton_1edpl_70"};import{jsx as $,jsxs as hn}from"react/jsx-runtime";var zg=t=>{try{let e=new URL(t);return new URLSearchParams(e.search).get("token")||void 0}catch{return t}},jg=({agentEmail:t,isOpen:e,origin:o="",onSuccess:n,onDismiss:s})=>{let r=w(Zs),i=y("LoginTokenDialog",il),a=Ug(Qa),l=Kg(),c=b("productName"),[p,u]=Ys(t||""),[d,m]=Ys(0),[h,g]=Ys(""),v=al(async x=>{x.preventDefault(),l(Ja({email:p})),m(1)},[o,p]),E=()=>{g(""),m(0)},f=al(async x=>{x.preventDefault();let C=zg(x.target.elements.token.value);if(!C){g(r("verifyCodeError",{login:_}));return}l(Jt({token:C}))},[o]),_=Fg(()=>x=>$("button",{type:"button","data-testid":"login-token-dialog-back-button",className:i.anchorButton,onClick:E,children:x},"back-button"),[]);return Bg(()=>{a==="error"&&g(r("verifyCodeError",{login:_})),a==="done"&&n()},[a]),$(ct,{autoFocus:!0,isOpen:e,contentAriaLabel:r("promptTitle",{productName:c}),overlayAriaLabel:r("promptTitle",{productName:c}),onClose:s,onBack:s,children:hn("div",{className:i.root,children:[$("h1",{className:i.title,children:r("promptTitle",{productName:c})}),d===0&&hn("form",{onSubmit:v,children:[$("h2",{className:i.subtitle,children:r("requestCodeTitle")}),$("p",{className:i.text,children:r("requestCodeBody",{productName:c})}),$(Yt,{className:i.input,name:"email",placeholder:r("requestCodeInputPlaceholder"),value:p,onChange:x=>u(x.target.value)}),$("div",{className:i.actions,children:$("button",{type:"submit",className:Js(i.button,i.primaryButton),children:r("requestCodeSubmitLabel")})})]}),d===1&&hn("form",{onSubmit:f,children:[$("h2",{className:i.subtitle,children:r("verifyCodeTitle")}),$("p",{className:i.text,children:r("verifyCodeBody")}),$(Yt,{className:i.input,name:"token",placeholder:r("verifyCodeInputPlaceholder"),disabled:["loading","done"].includes(a)}),h&&$("div",{className:i.errorMessage,children:h}),hn("div",{className:i.actions,children:[$("button",{type:"button",className:Js(i.button),onClick:E,children:r("back")}),$("button",{type:"submit",className:Js(i.button,i.primaryButton),disabled:["loading","done"].includes(a),children:r("verifyCodeSubmitLabel")})]})]})]})})},ll=jg;import{jsx as Vg}from"react/jsx-runtime";var qg=()=>{let t=cl(Za),e=cl(aa),o=b("adminUrl"),n=oe(),s=()=>n.send(xt,!1),r=()=>{n.send(xt,!1),n.send($s)};return Vg(ll,{isOpen:t,agentEmail:e==null?void 0:e.agentEmail,origin:o,onDismiss:s,onSuccess:r})},pl=qg;import Dm from"lodash.debounce";import{useCallback as ar,useEffect as lr,useState as no}from"react";import{useDispatch as Hm,useSelector as Et}from"react-redux";import{createAsyncThunk as Wg,createSlice as Gg}from"@reduxjs/toolkit";var $g={data:null,fetchState:"idle"},ul=t=>t.contentTypes.data,eo=Wg("contentTypes/getContentTypes",async(t,e)=>e.extra.deepdeskAPI.getContentTypes()),Xg=Gg({name:"contentTypes",initialState:$g,reducers:{},extraReducers:t=>{t.addCase(eo.pending,e=>{e.fetchState="loading"}).addCase(eo.rejected,e=>{e.fetchState="error"}).addCase(eo.fulfilled,(e,o)=>{e.fetchState="done",e.data=o.payload})}}),dl=Xg.reducer;function to(t){let e=document.createElement("textarea");e.value=t,e.style.position="fixed",e.style.left="-999999px",e.style.top="-999999px",document.body.appendChild(e),e.focus(),e.select(),document.execCommand("copy"),e.remove()}import{useEffect as Qg}from"react";function gl(t,e){Qg(()=>{let o=n=>{var s;((s=navigator==null?void 0:navigator.platform)!=null&&s.toLowerCase().includes("mac")?n.metaKey:n.ctrlKey)&&n.key===t&&(n.preventDefault(),n.stopPropagation(),e())};return document.addEventListener("keydown",o),()=>{document.removeEventListener("keydown",o)}},[])}import{useEffect as yl,useRef as nm}from"react";import{useSelector as sm,useDispatch as rm}from"react-redux";import{createAsyncThunk as Zg,createSlice as Jg}from"@reduxjs/toolkit";var ml={data:null,fetchState:"idle"},yn=t=>{var r;let e=[],{visitorName:o}=t.info.visitorInfo??{},{agentName:n,agentNickname:s}=t.info.agentInfo??{};return n&&n!==o&&e.push(n),s&&s!==o&&e.push(s),((r=t.entities.data)==null?void 0:r.filter(i=>!e.includes(i.text)))??null},ae=Zg("entities/getEntities",async(t,e)=>{let{deepdeskAPI:o,dynamicThunkObject:n}=e.extra;if(!n.conversationQuery)return Promise.resolve([]);let s=n.conversationQuery,r=await s();return r.length===0?Promise.resolve([]):o.getEntities(r)}),Yg=t=>t.filter((e,o)=>o===t.findIndex(n=>n.text===e.text)),em=Jg({name:"entities",initialState:ml,reducers:{},extraReducers:t=>{t.addCase(ae.pending,e=>{e.fetchState="loading"}).addCase(ae.rejected,e=>{e.fetchState="error"}).addCase(ae.fulfilled,(e,o)=>{e.fetchState="done",e.data=Yg(e.data?[...e.data,...o.payload]:o.payload)}).addCase(P,()=>ml)}}),fl=em.reducer;var er={};z(er,{enUS:()=>tm,nlNL:()=>om});var tm={noResults:[{type:0,value:"No entities have been found"}],copy:[{type:0,value:"Copy"}],use:[{type:0,value:"Use"}]},om={noResults:[{type:0,value:"Er zijn geen entiteiten gevonden"}],copy:[{type:0,value:"Kopieer"}],use:[{type:0,value:"Gebruik"}]};var hl={root:"_root_17kae_1",empty:"_empty_17kae_5"};import{jsx as Sn,jsxs as am}from"react/jsx-runtime";var im=({onCopy:t,onUse:e})=>{let o=nm(null),n=y("EntitiesList",hl),s=w(er),r=sm(yn),i=rm();return yl(()=>{i(ae())},[]),yl(()=>{o.current&&o.current.focus()},[o]),am("div",{className:n.root,ref:o,tabIndex:-1,children:[r&&r.length>0&&Sn(I.ActionsBar,{primaryLabel:s("copy"),secondaryLabel:s("use"),onPrimary:(a,l)=>t(r[l]),onSecondary:(a,l)=>e(r[l]),list:r.map(a=>({text:a.text,type:a.label,primaryAction:"copy",secondaryAction:"use"})),children:Sn(I.List,{children:r.map((a,l)=>Sn(I.ListItem,{index:l,closeOnSelect:!0,onClick:()=>t(a),children:a.text},a.text))},"entities")}),r&&r.length===0&&Sn("p",{className:n.empty,children:s("noResults")})]})},Sl=im;import{Fragment as gm,useEffect as vn,useRef as mm,useState as fm}from"react";import{useSelector as wl,useDispatch as hm}from"react-redux";import{createAsyncThunk as lm,createSlice as cm}from"@reduxjs/toolkit";var vl={data:null,fetchState:"idle"},_l=t=>t.summary.data,xl=t=>t.summary.fetchState==="error",be=lm("summary/getSummary",async(t,e)=>{let o=e.getState().profile.data;if(!o)throw new Error("Profile is not defined");let{deepdeskAPI:n,dynamicThunkObject:s}=e.extra;if(!s.conversationQuery)return Promise.reject(new Error("setConversationQuery method is not defined"));let r=s.conversationQuery,i=await r();return i.length===0?Promise.reject(new Error("No messages are included")):{summary:await n.getSummary(i,{promptInstruction:o.summarizerPromptInstruction,model:o.summarizerModel})}}),pm=cm({name:"summary",initialState:vl,reducers:{},extraReducers:t=>{t.addCase(be.pending,e=>{e.data=null,e.fetchState="loading"}).addCase(be.rejected,e=>{e.data=null,e.fetchState="error"}).addCase(be.fulfilled,(e,o)=>{e.fetchState="done",o.payload&&(e.data=o.payload.summary)}).addCase(P,()=>vl)}}),bl=pm.reducer;var tr={};z(tr,{enUS:()=>um,nlNL:()=>dm});var um={copy:[{type:0,value:"Copy"}],error:[{type:0,value:"Could not generate a summary"}],loading:[{type:0,value:"Generating summary, this may take a few moments."}]},dm={copy:[{type:0,value:"Kopieer"}],error:[{type:0,value:"Kon helaas geen samenvatting genereren."}],loading:[{type:0,value:"Samenvatting wordt gemaakt, dit kan even duren."}]};var Cl={root:"_root_6ahh3_1",actions:"_actions_6ahh3_5",main:"_main_6ahh3_11",textInput:"_textInput_6ahh3_15",loading:"_loading_6ahh3_34",error:"_error_6ahh3_38"};import{jsx as bt,jsxs as Sm}from"react/jsx-runtime";var ym=({onCopy:t})=>{let e=mm(null),o=y("SummaryForm",Cl),[n,s]=fm(""),r=w(tr),i=wl(_l),a=wl(xl),l=hm(),c=()=>{l(J({name:"summary copied to clipboard",data:{originalText:i,finalText:n},options:{includeConversationData:!0}})),t(n)},p=()=>{let u=document.getSelection();u&&l(J({name:"summary copied to clipboard",data:{originalText:i,finalText:u==null?void 0:u.toString()},options:{includeConversationData:!0}}))};return vn(()=>{l(be())},[]),vn(()=>{s(i||"")},[i]),vn(()=>{e.current&&i&&e.current.focus()},[e,i]),vn(()=>{let u=d=>{d.key==="Enter"&&d.shiftKey&&c()};return document.addEventListener("keydown",u),()=>{document.removeEventListener("keydown",u)}},[n]),bt("div",{className:o.root,tabIndex:-1,children:a?bt("p",{className:o.error,children:r("error")}):Sm(gm,{children:[bt("div",{className:o.main,children:bt("textarea",{placeholder:i?void 0:r("loading"),disabled:!i,className:o.textInput,ref:e,value:n,onCopy:p,onChange:u=>s(u.target.value)})}),bt("div",{className:o.actions,children:bt(I.Button,{shortKeys:[8679,8629],onClick:c,children:r("copy")})})]})})},Tl=ym;var or={};z(or,{enUS:()=>vm,nlNL:()=>_m});var vm={personalCollectionLink:[{type:0,value:"Go to Personal Collection"}],searchPlaceholder:[{type:0,value:"Start typing to search..."}],urlSuggestions:[{type:0,value:"Link suggestions"}],personalSuggestions:[{type:0,value:"Personal suggestions"}],pinnedMessages:[{type:0,value:"Pinned messages"}],imageSuggestions:[{type:0,value:"Images"}],typePlaceholder:[{type:0,value:"All types"}],navigation:[{type:0,value:"Navigation"}],entitiesClipboard:[{type:0,value:"Conversation clipper"}],entitiesTitle:[{type:0,value:"Copy to your clipboard"}],summaryClipboard:[{type:0,value:"Summarize conversation"}],summaryTitle:[{type:0,value:"Conversation summary"}],knowledgeAssist:[{type:0,value:"Knowledge assist"}],commands:[{type:0,value:"Commands"}],use:[{type:0,value:"Use"}],preview:[{type:0,value:"Preview"}],warning:[{type:0,value:"Are you sure you want to discard the message?"}]},_m={personalCollectionLink:[{type:0,value:"Ga naar persoonlijke collectie"}],searchPlaceholder:[{type:0,value:"Begin met typen om te zoeken..."}],personalSuggestions:[{type:0,value:"Persoonlijke suggesties"}],urlSuggestions:[{type:0,value:"Link suggesties"}],imageSuggestions:[{type:0,value:"Afbeeldingen"}],navigation:[{type:0,value:"Navigatie"}],typePlaceholder:[{type:0,value:"Alle types"}],pinnedMessages:[{type:0,value:"Actueel"}],entitiesClipboard:[{type:0,value:"Klembord"}],entitiesTitle:[{type:0,value:"Kopieer naar klembord"}],summaryClipboard:[{type:0,value:"Gesprek samenvatten"}],summaryTitle:[{type:0,value:"Gesprek samenvatting"}],knowledgeAssist:[{type:0,value:"Knowledge assist"}],commands:[{type:0,value:"Acties"}],use:[{type:0,value:"Gebruik"}],preview:[{type:0,value:"Bewerk"}],warning:[{type:0,value:"Weet je zeker dat je de wijzigingen wilt weggooien?"}]};import Rm,{useEffect as rr,useRef as Pm}from"react";import{useDispatch as Im,useSelector as Ll}from"react-redux";var nr={};z(nr,{enUS:()=>xm,nlNL:()=>bm});var xm={use:[{type:0,value:"Use"}],loading:[{type:0,value:"Loading..."}],error:[{type:0,value:"Something went wrong, please try again later."}],anotherQuestion:[{type:0,value:"Send a message..."}],reset:[{type:0,value:"Reset conversation"}]},bm={use:[{type:0,value:"Gebruik"}],loading:[{type:0,value:"Laden..."}],error:[{type:0,value:"Er ging iets mis, probeer het later opnieuw."}],anotherQuestion:[{type:0,value:"Stuur een bericht..."}],reset:[{type:0,value:"Reset gesprek"}]};var El={root:"_root_1g4pq_1",title:"_title_1g4pq_9",empty:"_empty_1g4pq_20",status:"_status_1g4pq_24",form:"_form_1g4pq_30",input:"_input_1g4pq_43",submit:"_submit_1g4pq_55",question:"_question_1g4pq_63",answer:"_answer_1g4pq_67",alignRight:"_alignRight_1g4pq_73"};import{createAction as Cm,createAsyncThunk as wm,createSlice as Tm}from"@reduxjs/toolkit";var sr={data:[],fetchState:"idle"},kl=t=>{var e;return(e=t.answer)==null?void 0:e.data},Rl=t=>t.answer.fetchState,wt=Cm("answer/resetKnowledgeSearch"),Ct=wm("answer/getAnswer",async(t,e)=>{var i;let{deepdeskAPI:o}=e.extra,n=e.getState().answer.data,s=(i=e.getState().conversation.current)==null?void 0:i.profileCode;if(!s)throw new Error("Profile is not defined");let r=await o.knowledgeAssist({promptInstruction:t.promptInstruction,question:t.question},n,s);return{question:t.question,answer:r}}),Em=Tm({name:"answer",initialState:sr,reducers:{},extraReducers:t=>{t.addCase(Ct.pending,e=>{e.fetchState="loading"}).addCase(Ct.rejected,e=>{e.fetchState="error"}).addCase(Ct.fulfilled,(e,o)=>{e.fetchState="done",e.data=[...e.data,o.payload]}).addCase(P,()=>sr).addCase(wt,()=>sr)}}),Pl=Em.reducer;import{jsx as Il,jsxs as km}from"react/jsx-runtime";var Al=()=>km("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 512 512","aria-labelledby":"paperPlaneTitle",children:[Il("title",{id:"paperPlaneTitle",children:"PaperPlane"}),Il("path",{d:"M498.1 5.6c10.1 7 15.4 19.1 13.5 31.2l-64 416c-1.5 9.7-7.4 18.2-16 23s-18.9 5.4-28 1.6L284 427.7l-68.5 74.1c-8.9 9.7-22.9 12.9-35.2 8.1S160 493.2 160 480V396.4c0-4 1.5-7.8 4.2-10.7L331.8 202.8c5.8-6.3 5.6-16-.4-22s-15.7-6.4-22-.7L106 360.8 17.7 316.6C7.1 311.3 .3 300.7 0 288.9s5.9-22.8 16.1-28.7l448-256c10.7-6.1 23.9-5.5 34 1.4z"})]});import{jsx as Ce,jsxs as ir}from"react/jsx-runtime";var Am=({onUse:t,onResetQuestion:e,question:o,promptInstruction:n})=>{let[s,r]=Rm.useState(""),{setSelected:i}=Ne(),a=Pm(null),l=y("EntitiesList",El),c=w(nr),p=Im(),u=Ll(kl),d=Ll(Rl),m=async g=>{g.preventDefault(),g.stopPropagation(),s!==""&&p(Ct({question:s,promptInstruction:n}))},h=(g,v)=>{p(J({name:"knowledge assist source viewed",data:{question:v,sourceViewed:g.url||g.name},options:{includeConversationData:!0}}))};return rr(()=>{var g;o&&d==="idle"?p(Ct({question:o,promptInstruction:n})):(g=a.current)==null||g.focus()},[a,d]),rr(()=>{d==="done"&&(p(J({name:"knowledge assist question answered",data:{question:s||o,sources:u[u.length-1].answer.sources,answer:u[u.length-1].answer.answer,isFollowUpQuestion:u.length>1},options:{includeConversationData:!0}})),i(u.length-1),r(""))},[d,u]),rr(()=>{a.current&&a.current.scrollIntoView({behavior:"smooth"})},[a,u]),ir("div",{className:l.root,children:[u.length>0&&Ce("div",{className:l.alignRight,children:Ce(I.Button,{onClick:e,children:c("reset")})}),ir(I.ActionsBar,{list:u.map(({answer:g})=>({text:g.answer,type:"answer"})),primaryLabel:c("use"),onPrimary:g=>t(g.text),children:[u.map(({question:g,answer:v},E)=>Ce(I.List,{children:Ce(I.ListItem,{"data-testid":"knowledge-search-answer",index:E,description:v.answer,closeOnSelect:!0,onClick:()=>t(v.answer),onSourceClick:f=>h(f,g),sources:v.sources,styles:{title:l.question,description:l.answer},children:g})},`${v.answer}_${E}`)),d==="loading"&&Ce("p",{className:l.status,children:c("loading")}),d==="error"&&Ce("p",{className:l.status,children:c("error")}),ir("form",{className:l.form,onSubmit:m,children:[Ce("input",{ref:a,placeholder:c("anotherQuestion"),className:l.input,type:"text",value:s,onFocus:()=>{i(-1)},onChange:g=>{i(-1),r(g.target.value)}}),Ce("button",{type:"submit",className:l.submit,children:Ce(Al,{})})]})]})]})},Ml=Am;import{createAsyncThunk as Lm,createSlice as Mm}from"@reduxjs/toolkit";var Nm={data:null,fetchState:"idle"},Tt=t=>t.profile.data,_n=t=>t.profile.data?t.profile.data.uiConfig.widget.types.filter(e=>e.isActive):[],oo=Lm("profile/getProfile",async(t,e)=>{var r;let{deepdeskAPI:o}=e.extra,n=e.getState(),s=n.conversation.current;if(!s||!s.profileCode)throw new Error("No conversation of conversation profileCode found");return((r=n.profile.data)==null?void 0:r.code)===s.profileCode?n.profile.data:o.getProfile(s.profileCode)}),Om=Mm({name:"profile",initialState:Nm,reducers:{},extraReducers:t=>{t.addCase(oo.pending,e=>{e.fetchState="loading"}).addCase(oo.rejected,e=>{e.fetchState="error"}).addCase(oo.fulfilled,(e,o)=>{e.fetchState="done",e.data=o.payload})}}),Nl=Om.reducer;import{jsx as X,jsxs as Dl}from"react/jsx-runtime";var Bm=200,Fm=5,Km=4,Um=t=>t.reduce((e,o)=>[...e,...o.list.map(n=>({...n,type:o.value}))],[]),Ol=(t,e)=>!e||t.toLowerCase().includes(e.toLowerCase()),zm=()=>{let t=Hm(),e=oe(),o=w(or),[n,s]=no(!1),[r,i]=no(""),a=Et(da),l=Et(Tt),[c,p]=no(null),[u,d]=no([]),[m,h]=no(),g=Et(_e),v=b("showSearch"),E=b("showEntitiesCommand"),f=b("showSummaryCommand"),_=b("showKnowledgeSearch"),x=b("showImageSearch"),C=b("searchTriggerKey"),T=Et(ul),N=Et(ga),ee=Et(ua),D=S=>Zn(N.filter(A=>A.type===S.toUpperCase()),S),R=[{value:"PERSONAL",label:o("personalSuggestions"),list:D("PERSONAL"),lineClamp:!1,listOrientation:"vertical",shouldShow:!0},{value:"URL",label:o("urlSuggestions"),list:D("URL"),lineClamp:!1,listOrientation:"vertical",shouldShow:!0},{value:"STICKYMESSAGE",label:o("pinnedMessages"),list:D("STICKYMESSAGE"),lineClamp:!1,listOrientation:"vertical",shouldShow:!0},{value:"IMAGE",label:o("imageSuggestions"),lineClamp:!1,list:D("IMAGE"),listOrientation:"horizontal",shouldShow:x}].filter(S=>S.shouldShow),B=[{label:o("entitiesClipboard"),onClick:()=>t(q("entities")),shouldShow:E&&Ol(o("entitiesClipboard"),r),experimental:!0},{label:o("summaryClipboard"),onClick:()=>t(q("summary")),shouldShow:f&&Ol(o("summaryClipboard"),r),experimental:!0},{label:r?`${o("knowledgeAssist")}: ${r}`:o("knowledgeAssist"),onClick:()=>t(q("knowledgeAssist")),shouldShow:_,experimental:!0}].filter(S=>S.shouldShow),V=(T==null?void 0:T.map(S=>({value:S.code.toUpperCase(),label:`${S.name}s`,list:D(S.code.toUpperCase()),listOrientation:"vertical",lineClamp:!0})))||[],Xn=ar(Dm((S,A)=>{t(We({query:S,type:A,tags:["search-overlay"]}))},Bm),[]),Be=Um([...V,...R]),Op=ar((S,A)=>{if(!A)return;let Re=[...R,...V].find(({value:et})=>et===A);Re&&(t(q("edit")),p({...S,searchTerm:void 0}),d(Re.list))},[t,c,V]),Qn=ar((S,A)=>{switch(A.type){case"IMAGE":e.send(Xs,{suggestion:A});break;default:e.send(xe,{text:S,suggestion:A})}t(Y(!1))},[t]),Dp=S=>{to(S.text),t(J({name:"entity copied",data:{entity:S,type:"copy"}})),t(Y(!1))},Hp=S=>{e.send(xe,{text:S,suggestion:{source:"knowledge-assist",text:S}}),t(J({name:"answer used",data:{originalText:S},options:{includeConversationData:!0}})),i(""),t(q("search")),t(wt()),t(Y(!1))},Bp=S=>{to(S),t(Y(!1))},Fp=S=>{e.send(xe,{text:S.text,suggestion:{source:"entity",text:S.text}}),t(Y(!1))},Kp=c===null||u.indexOf(c)-1<0?void 0:()=>p(u[u.indexOf(c)-1]),Up=c===null||u.indexOf(c)===u.length-1?void 0:()=>p(u[u.indexOf(c)+1]);function Zn(S,A){return S.slice(0,m?10:A.toLowerCase()==="image"?Km:Fm)}function Vr(S,A,Re){return A.reduce((et,So)=>Re&&m===Re?So.length+et:Zn(So,Re).length+et,S)}function Ye(S){return A=>{n?window.confirm(o("warning"))&&(S(A),s(!1)):S(A)}}return lr(()=>{r?Xn(r,m):t(un())},[r,m]),lr(()=>{a==="search"&&t(wt())},[a]),lr(()=>{g&&t(eo())},[g]),gl(C,()=>t(Y(!0))),!v||!l?null:Dl(I,{placeholder:o("searchPlaceholder"),typePlaceholder:o("typePlaceholder"),onChangeSearch:i,onChangeOpen:Ye(S=>t(Y(S))),onChangeType:S=>h(S),onChangePage:Ye(S=>t(q(S))),selectedType:m,search:r,page:a,isOpen:ee,types:[...V,...R],children:[X(I.Page,{id:"search",children:Dl(I.ActionsBar,{list:[...B.map(S=>({text:S.label,type:"command"})),...Be.map(S=>({text:S.text||S.url||S.message,type:S.type}))],primaryLabel:o("use"),secondaryLabel:o("preview"),onPrimary:({text:S},A)=>Qn(S,Be[A]),onSecondary:(S,A)=>{Op(Be[A-B.length],Be[A-B.length].type)},children:[B.length>0&&X(I.List,{heading:o("commands"),children:B.map((S,A)=>X(I.ListItem,{index:Vr(A,[],"commands"),closeOnSelect:!1,onClick:S.onClick,isExperimental:S.experimental,children:S.label},S.label))}),[...V,...R].map(({value:S,label:A,list:Re,lineClamp:et,listOrientation:So},zp)=>X(I.List,{heading:A,orientation:So==="horizontal"?"horizontal":"vertical",children:Zn(Re,S).map((se,jp)=>X(I.ListItem,{index:Vr(B.length+jp,[...V,...R].slice(0,zp).map(({list:qp})=>qp),S),closeOnSelect:!1,lineClamp:et,onClick:()=>Qn(se.text,se),description:S!=="IMAGE"?se.title&&se.text:void 0,children:S==="IMAGE"?X(I.Image,{title:se.title||se.text,src:se.image}):se.title||se.text},`${se.id}-${se.text}`))},S))]})}),X(I.Page,{id:"edit",onDismiss:Ye(()=>{t(q("search")),p(null)}),children:c&&X(mn,{suggestion:c,onTouched:s,onDismiss:()=>{s(!1),t(q("search")),p(null),d([])},onNext:Up,onPrevious:Kp,onUse:S=>{t(q("search")),Qn(S,{...c,source:`${c.source||"text_recommendation"}-preview`}),t(Y(!1)),d([]),p(null)}})}),X(I.Page,{id:"entities",title:o("entitiesTitle"),isExperimental:!0,onDismiss:Ye(()=>{t(q("search"))}),children:X(Sl,{onUse:Fp,onCopy:Dp})}),X(I.Page,{id:"summary",title:o("summaryTitle"),isExperimental:!0,onDismiss:Ye(()=>{t(q("search"))}),children:X(Tl,{onCopy:Bp})}),X(I.Page,{id:"knowledgeAssist",title:o("knowledgeAssist"),isExperimental:!0,onDismiss:Ye(()=>{t(wt()),t(q("search"))}),children:X(Ml,{promptInstruction:l.knowledgeAssistPromptInstruction,question:r,onUse:Hp,onResetQuestion:()=>{t(wt()),i("")}})})]})},Hl=zm;import{jsx as cr,jsxs as Vm}from"react/jsx-runtime";var qm=()=>{let t=b("showSearch"),e=b("isEmbedded");return Vm(jm,{children:[t&&cr(Hl,{}),cr(sl,{}),e&&cr(pl,{})]})},Bl=qm;import{Provider as Wm}from"react-redux";import{jsx as xn}from"react/jsx-runtime";var Gm=({children:t})=>{let o=b("locale").replace("-","");return xn(ls.Provider,{value:o,children:t})},$m=({store:t,customStyles:e={},children:o})=>xn(Wm,{store:t,children:xn(Gm,{children:xn(Ot.Provider,{value:e,children:o})})}),so=$m;import hr from"classnames";import{useEffect as Ef,useRef as kf,useState as Rf}from"react";import{connect as Pf,useDispatch as If,useSelector as Tn}from"react-redux";import{useState as Xm}from"react";function Fl(t,e){let[o,n]=Xm(()=>{if(typeof window>"u")return e;try{let r=window.localStorage.getItem(t);return r?JSON.parse(r):e}catch(r){return k.error(r),e}});return[o,r=>{try{let i=r instanceof Function?r(o):r;n(i),typeof window<"u"&&window.localStorage.setItem(t,JSON.stringify(i))}catch(i){k.error(i)}}]}function bn(t){let{showMidSentenceSuggestions:e,showSuggestionsBeforePattern:o,showSuggestionsAfterPattern:n}=t.settings,{text:s,selection:r}=t.input.userCommitted;return r.start!==r.end?!1:r.end>=s.length?!0:e?o&&new RegExp(o).test(s.substring(r.end))||n&&new RegExp(n).test(s.substring(0,r.end))?!0:o===!1&&n===!1:!1}import Jm from"classnames";import{Fragment as Ym,useCallback as ur,useMemo as Ul}from"react";var pr={};z(pr,{enUS:()=>Qm,nlNL:()=>Zm});var Qm={loginPlease:[{type:8,value:"login",children:[{type:0,value:"Sign in"}]},{type:0,value:" to enable "},{type:1,value:"productName"},{type:0,value:"."}],snooze:[{type:0,value:"Snooze for "},{type:8,value:"min",children:[{type:0,value:"10 minutes"}]},{type:0,value:", "},{type:8,value:"hour",children:[{type:0,value:"1 hour"}]},{type:0,value:" or "},{type:8,value:"day",children:[{type:0,value:"1 day"}]}]},Zm={loginPlease:[{type:8,value:"login",children:[{type:0,value:"Log in"}]},{type:0,value:" bij "},{type:1,value:"productName"},{type:0,value:"."}],snooze:[{type:0,value:"Snooze voor "},{type:8,value:"min",children:[{type:0,value:"10 minuten"}]},{type:0,value:", "},{type:8,value:"hour",children:[{type:0,value:"1 uur"}]},{type:0,value:" of "},{type:8,value:"day",children:[{type:0,value:"1 dag"}]}]};var Kl={root:"_root_1vfca_1",anchor:"_anchor_1vfca_6",anchorButton:"_anchorButton_1vfca_11"};import{jsx as Cn,jsxs as zl}from"react/jsx-runtime";var dr=(t,e,o)=>n=>Cn("button",{className:t.anchorButton,type:"button",value:e,onClick:o,children:n},e),ef=({className:t,loginUrl:e,isEmbedded:o,onSnooze:n})=>{let s=w(pr),r=oe(),i=y("Login",Kl),a=b("productName"),l=ur(g=>{g.preventDefault(),n&&n(parseInt(g.target.value,10))},[]),c=ur(g=>{g.preventDefault(),r.send(xt,!0)},[e]),p=Ul(()=>g=>Cn("a",{href:e,className:i.anchor,target:"_blank",rel:"noreferrer",children:g},"login"),[e]),u=ur(g=>Cn("button",{type:"button",className:i.anchorButton,onClick:c,children:g},"prompt"),[c]),{min:d,hour:m,day:h}=Ul(()=>({min:dr(i,60*10,l),hour:dr(i,60*60,l),day:dr(i,60*60*12,l)}),[]);return zl("div",{className:Jm(t,i.root),children:[s("loginPlease",{login:o?u:p,productName:a}),n&&zl(Ym,{children:[Cn("br",{}),s("snooze",{min:d,hour:m,day:h})]})]})},wn=ef;import{useDispatch as tf}from"react-redux";var jl={root:"_root_1g8fi_1",text:"_text_1g8fi_19"};import{jsx as ql,jsxs as nf}from"react/jsx-runtime";var of=({title:t})=>{let e=y("SearchTrigger",jl),o=tf();return nf("button",{type:"button",className:e.root,onClick:()=>o(Y(!0)),children:[ql(ft,{}),ql("span",{className:e.text,children:t})]})},Vl=of;import{Fragment as bf}from"react";import{Interweave as df}from"interweave";import{useEffect as gf,useMemo as mf,useRef as ff}from"react";import{useDispatch as hf,useSelector as yf}from"react-redux";import{useEffect as sf}from"react";function Wl(t,e,o){sf(()=>{let n=t.current;return n?(n.addEventListener(e,o),()=>{n.removeEventListener(e,o)}):()=>{}},[t,e,o])}var rf=/[.*+?^${}()|[\]\\]/g,af=/[^0-9A-Za-zÀ-ÖØ-öø-ÿ](?=[0-9A-Za-zÀ-ÖØ-öø-ÿ]*$)/;function lf(t){return t.replace(rf,"\\$&")}function cf(t,e){let o=t.split("").findIndex((n,s)=>n!==e[s]);return o>-1?o:Math.min(t.length,e.length)}function gr(t){return t.search(af)}function Gl(t,e=[]){let o=t;return e.forEach(n=>{if(!n)return;let s=new RegExp(`\\b(${lf(n)})\\b`,"gi");o=o.replace(s,"<strong>$1</strong>")}),o}function $l(t){return t.replace(rt,'<mark data-type="placeholder">$1</mark>')}function ro(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function pf(t,e){return t.split("").map((i,a)=>({char:i,index:a})).filter(({char:i,index:a})=>/\s/.test(i)&&a<=e).map(({index:i})=>i).reverse()[0]}function mr(t,e,o={}){if(e){let n=cf(e.toLowerCase(),t.toLowerCase()),s=ro(t.substring(n,t.length));if(o.stripAgentPart){let l=t.substring(0,n),c=gr(l);return`<span style="opacity: 0.5">${l.substring(c+1)}</span>${s}`}let i=e.split(ui).length>3||e.length>30?pf(e.trim(),n):0;return`${`${i>0?"\u2026":""}${ro(t.substring(i,n))}`}<strong>${s}</strong>`}return t}var Xl={badge:"_badge_8rv7b_1",formattedText:"_formattedText_8rv7b_5"};import{jsx as Ql}from"react/jsx-runtime";var Sf=["search","personal-collection-search","search-autocomplete"];function vf(t,e,o,n={}){let s="";return Sf.includes(e)?s=Gl(mr(t,o,{stripAgentPart:!0}),n.searchKeywords??[o]):s=mr(t,o,n),n.placeholders===!0&&(s=$l(s)),s}var _f=()=>{},xf=({index:t,selected:e,suggestion:o})=>{let n=b("inlineSuggestions"),s=yf(lt),r=hf(),i=y("TextSuggestion",Xl),a=ff(null);gf(()=>{let c=setTimeout(()=>{r(Ti({text:o.text,suggestion:o}))},500);return()=>{clearTimeout(c)}},[o]),Wl(a,"click",()=>{r(Yo(t)),r(ie({suggestion:o,text:o.text,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"}))});let l=mf(()=>vf(o.text,o.source,s,{stripAgentPart:n,placeholders:!0,searchKeywords:o.searchKeywords}),[n,o.text,o.source,s,o.searchKeywords]);return o.source==="gpt"?null:Ql(O,{ref:a,as:"button","data-testid":"suggestions-overlay-item",selected:e,onClick:_f,children:Ql(df,{containerTagName:"div",noWrap:!1,tagName:"span",className:i.formattedText,content:l})})},Zl=xf;import{jsx as Jl}from"react/jsx-runtime";var Cf=({suggestions:t,selectedIndex:e})=>Jl(bf,{children:t.slice().map((o,n)=>Jl(Zl,{index:n,selected:n===e,suggestion:o},`${o.text}-${o.source}`)).reverse()}),Yl=Cf;var fr={};z(fr,{enUS:()=>wf,nlNL:()=>Tf});var wf={arrowHint:[{type:0,value:"Tip: use arrow keys to navigate suggestions"}],searchHintWindows:[{type:0,value:"Press CTRL+"},{type:1,value:"searchTriggerKey"},{type:0,value:" to search"}],searchHintMac:[{type:0,value:"Press CMD+"},{type:1,value:"searchTriggerKey"},{type:0,value:" to search"}],open:[{type:0,value:"Open "},{type:1,value:"productName"}],collapse:[{type:0,value:"Close"}],search:[{type:0,value:"Search"}]},Tf={arrowHint:[{type:0,value:"Tip: Selecteer suggesties met pijltoetsen"}],searchHintWindows:[{type:0,value:"Druk CTRL+"},{type:1,value:"searchTriggerKey"},{type:0,value:" om te zoeken"}],searchHintMac:[{type:0,value:"Druk CMD+"},{type:1,value:"searchTriggerKey"},{type:0,value:" om te zoeken"}],open:[{type:0,value:"Open "},{type:1,value:"productName"}],collapse:[{type:0,value:"Sluiten"}],search:[{type:0,value:"Zoeken"}]};var ec={root:"_root_4kcme_1",isInline:"_isInline_4kcme_14",toggleButton:"_toggleButton_4kcme_18",toggleButtonWrapper:"_toggleButtonWrapper_4kcme_22",toggleButtonWrapperHidden:"_toggleButtonWrapperHidden_4kcme_29",isCollapsed:"_isCollapsed_4kcme_33",collapsible:"_collapsible_4kcme_33",hints:"_hints_4kcme_41",hintsHidden:"_hintsHidden_4kcme_48",triggers:"_triggers_4kcme_53",triggersRight:"_triggersRight_4kcme_68"};import{jsx as U,jsxs as io}from"react/jsx-runtime";var Af=({inline:t=!1,textSuggestions:e,selectedIndex:o})=>{let n=y("SuggestionsOverlay",ec),s=w(fr),r=b("inlineSuggestions"),i=Tn(bn),a=_i(),l=If(),c=kf(null),p=b("searchTriggerKey"),u=b("productName"),d=Tn(za),m=Tn(_e),h=Tn(Uo),[g,v]=Rf(null),E=b("showSearch"),f=b("showTextSuggestions"),_=b("adminUrl"),x=b("isEmbedded"),[C,T]=Fl("dd-snooze-until-ms",0),N=d||C>Date.now(),ee=e.filter(B=>B.source!=="gpt").length,D=()=>{N&&T(0),l(Va(!N))},R=B=>{let V=Date.now()+B*1e3;T(V),k.info(`Snooze until: ${new Date(V)}`),l(vt({collapse:!0}))};return Ef(()=>{ee===0&&v(null)},[e,ee]),ut(()=>{l(vt({collapse:!0,skipWhenInputFocus:!0}))}),r!==t||m===null||h===!1?null:m===!1?io("div",{ref:c,className:hr(n.root,{[n.isCollapsed]:N,[n.isInline]:t}),"data-inline":t,children:[!N&&io("div",{className:n.triggers,children:[U("div",{style:{flex:1}}),U("div",{className:n.triggersRight,children:U(st,{className:n.toggleButton,title:s("collapse"),onClick:D,isCollapsed:!1})})]}),U("div",{className:n.toggleButtonWrapper,children:U(st,{className:n.toggleButton,title:s("open",{productName:u}),onClick:D,isCollapsed:!0})}),U("div",{className:n.collapsible,children:U(wn,{loginUrl:_,isEmbedded:x,onSnooze:R})})]}):!a||!i?null:io("div",{ref:c,className:hr(n.root,{[n.isCollapsed]:N,[n.isInline]:t}),"data-inline":t,children:[!N&&io("div",{className:n.triggers,children:[U("div",{style:{flex:1},children:E&&U("div",{style:{display:"inline-block"},onFocus:()=>{},onMouseOver:()=>v(s(cn()?"searchHintMac":"searchHintWindows",{searchTriggerKey:p.toUpperCase()})),onMouseLeave:()=>v(null),children:U(Vl,{title:s("search")})})}),io("div",{className:n.triggersRight,onFocus:()=>{},children:[U("div",{className:hr(!g&&n.hintsHidden,n.hints),children:g}),U(st,{className:n.toggleButton,title:s("collapse"),onClick:D,isCollapsed:!1})]})]}),U("div",{className:n.toggleButtonWrapper,children:U(st,{className:n.toggleButton,title:s("open",{productName:u}),onClick:D,isCollapsed:!0})}),ee>0&&f&&U("div",{className:n.collapsible,onFocus:()=>{},children:U(fe,{children:U(Yl,{suggestions:e,selectedIndex:o})})})]})},Lf=({input:t})=>({selectedIndex:t.selectedSuggestionIndex,textSuggestions:t.textSuggestions}),En=Pf(Lf)(Af);import kr from"classnames";import{Interweave as wh}from"interweave";import{useCallback as Th,useEffect as Eh,useMemo as _c,useRef as kh}from"react";import{connect as Rh}from"react-redux";import{cloneElement as Mf}from"react";var Nf=["div","span","mark","strong","b","i","u","em"];function yr(t,e,o=0){var r;let n=t[t.length-1],s=typeof n=="object"&&n!==null?(r=n.props)==null?void 0:r.tagName:void 0;if(s==="br")return t.pop(),[...t,...e,n];if(Nf.includes(s)){let i=Array.isArray(n.props.children)?n.props.children:[n.props.children];return[...t.slice(0,t.length-1),Mf(n,{children:yr(i,e,o+1)})]}return[...t,...e]}function we(t){return t.tagName.toLowerCase()==="textarea"}var tc={root:"_root_81non_1",container:"_container_81non_3",agentText:"_agentText_81non_5",tabText:"_tabText_81non_6",hint:"_hint_81non_6",matchSelection:"_matchSelection_81non_10",focus:"_focus_81non_16",resetIndent:"_resetIndent_81non_20",matchKeyword:"_matchKeyword_81non_24",matchPlaceholder:"_matchPlaceholder_81non_25",hover:"_hover_81non_31",hintText:"_hintText_81non_64",popover:"_popover_81non_72",popoverRoot:"_popoverRoot_81non_77",popoverContentContainer:"_popoverContentContainer_81non_81",popoverContent:"_popoverContent_81non_81",selectionOptions:"_selectionOptions_81non_107",selectionOptionsIsHidden:"_selectionOptionsIsHidden_81non_112",selectionOptionsButton:"_selectionOptionsButton_81non_116",caret:"_caret_81non_132",popoverSuggestionsRoot:"_popoverSuggestionsRoot_81non_136",suggestionsOverlayInputStyles:"_suggestionsOverlayInputStyles_81non_141"};import{Matcher as $f}from"interweave";import{Fragment as Xf,useEffect as Qf}from"react";import ic from"classnames";import{createRef as qf,useCallback as vr,useMemo as Vf,useRef as Wf,useState as Gf}from"react";import{useState as Of,useLayoutEffect as Df}from"react";var Hf=["bottom","height","left","right","top","width"],Bf=(t={},e={})=>Hf.some(o=>t[o]!==e[o]),Te=new Map,oc,nc=()=>{let t=[],e=[];Te.forEach((o,n)=>{if(n instanceof Element&&!n.isConnected){e.push(n);return}let s=n.getBoundingClientRect();Bf(s,o.rect)&&(o.rect=s,t.push(o))}),e.forEach(o=>{Te.delete(o)}),t.forEach(o=>{o.callbacks.forEach(n=>n(o.rect))}),oc=window.requestAnimationFrame(nc)};function Ff(t,e){return{observe(){let o=Te.size===0;if(Te.has(t)){let n=Te.get(t);n.callbacks.push(e),n.rect&&e(n.rect)}else Te.set(t,{rect:void 0,hasRectChanged:!1,callbacks:[e]});o&&nc()},unobserve(){let o=Te.get(t);if(o){let n=o.callbacks.indexOf(e);n>=0&&o.callbacks.splice(n,1),o.callbacks.length||Te.delete(t),Te.size||cancelAnimationFrame(oc)}}}}function Sr(t){let[e,o]=Of(null);return Df(()=>{if(!t.current)return;let n=Ff(t.current,s=>{o(s)});return n.observe(),()=>{n.unobserve()}},[t]),e}import{useContext as Kf,useLayoutEffect as Uf,useState as zf}from"react";import{createPortal as jf}from"react-dom";var sc={root:"_root_1jq08_1"};var rc=({children:t})=>{let[e,o]=zf(null),n=Kf(Ot);return Uf(()=>{let s=document.createElement("div");return qe(s),s.classList.add(sc.root),n!=null&&n.portalRootNode&&s.classList.add(n==null?void 0:n.portalRootNode),document.body.appendChild(s),o(s),()=>{s.isConnected&&document.body.removeChild(s)}},[]),e?jf(t,e):null};var ue={ref:"_ref_1rcyi_1",root:"_root_1rcyi_7",positionAbove:"_positionAbove_1rcyi_13",positionBelow:"_positionBelow_1rcyi_17",positionLeft:"_positionLeft_1rcyi_21",positionRight:"_positionRight_1rcyi_25",alignStart:"_alignStart_1rcyi_29",alignCenter:"_alignCenter_1rcyi_34",alignEnd:"_alignEnd_1rcyi_40"};import{jsx as _r}from"react/jsx-runtime";var kt=(t=!1)=>{let[e,o]=Gf(t),n=vr(()=>o(!0),[]),s=vr(()=>o(!1),[]),r=vr(()=>o(a=>!a),[]),i=Wf(null);return{opened:e,open:n,close:s,toggle:r,triggerRef:i}};function xr(t,e=null,o=0){if(!t)return{display:"none"};let n=e?t.top-e.top<0||t.top<e.top-o?e.top-o:t.top+t.height>e.top+e.height+o?e.top+e.height+o-t.height:t.top:t.top,s=e?t.left<e.left-o?e.left-o:t.left+t.width>e.left+e.width+o?e.left+e.width+o-t.width:t.left:t.left;return{top:n,left:s,height:t.height,width:t.width}}var Rt=({className:t,triggerRef:e,boundaryRef:o=qf(),position:n="above",align:s="center",children:r,toStyle:i=xr,...a})=>{let l=Sr(e),c=Sr(o),p=Vf(()=>i(l,c,0),[l,c]);return _r(rc,{children:_r("div",{className:ic(ue.ref,{[ue.positionAbove]:n==="above",[ue.positionBelow]:n==="below",[ue.positionLeft]:n==="left",[ue.positionRight]:n==="right",[ue.alignStart]:s==="start",[ue.alignCenter]:s==="center",[ue.alignEnd]:s==="end"}),style:p,...a,role:"dialog",children:_r("div",{className:ic(t,ue.root),children:r})})})};import{jsx as ao,jsxs as Jf}from"react/jsx-runtime";var Zf=({inputStyle:t,inputElement:e})=>{let o=y("TabCompletion",te),n=kt(document.activeElement===e);return ut(()=>n.close()),Qf(()=>{let s=()=>n.open();return e.addEventListener("focus",s),()=>{e.removeEventListener("focus",s)}},[]),Jf(Xf,{children:[ao("mark",{className:te.caret,ref:n.triggerRef}),n.opened&&ao(Rt,{className:o.popoverSuggestionsRoot,triggerRef:n.triggerRef,position:"above",align:"start",children:ao("div",{style:t,className:o.suggestionsOverlayInputStyles,children:ao(En,{inline:!0})})})]})},kn=class extends $f{charCounter=0;charLength=0;found=!1;onlyAtEnd=!1;props;onBeforeParse(e,o){var n;return this.props=o,this.charCounter=0,this.onlyAtEnd=o.inlineSuggestionsOnlyAtEnd??!1,this.charLength=(we(o.inputElement)?o.inputElement.value.length:(n=o.inputElement.textContent)==null?void 0:n.length)??0,this.found=!1,e}match(e){if(this.found||!this.props||this.props.selection===null)return null;let[o,n]=this.props.selection;if(o!==n||this.onlyAtEnd&&o!==this.charLength)return null;let s=o,i=s>=this.charCounter&&s<=this.charCounter+e.length?{index:gr(e.slice(0,s))+1-this.charCounter,length:0,match:"",valid:!0}:null;return i&&(this.found=!0),this.charCounter+=e.length,i??null}replaceWith(e,o){return ao(Zf,{inputStyle:o.inputStyle,inputElement:o.inputElement},"caret")}asTag(){return"mark"}};import oh from"classnames";import{Matcher as nh}from"interweave";import{useEffect as sh,useMemo as rh}from"react";function ac(t){return t.replace(/[.*+^${}()|[\]\\]/g,"\\$&")}function Rn(t){return e=>{t.forEach(o=>{typeof o=="function"?o(e):o!=null&&(o.current=e)})}}function lc(t){return t!=null}import Yf from"classnames";import{forwardRef as eh,useRef as th}from"react";import{jsx as cc}from"react/jsx-runtime";var Pn=eh(({className:t,children:e,...o},n)=>{let s=th(null),r=y("TabCompletion",te);return cc("div",{ref:Rn([s,n]),className:Yf(t,r.popoverContentContainer),...o,children:cc("div",{className:r.popoverContent,children:e})})});import{jsx as lo,jsxs as lh}from"react/jsx-runtime";var ih=t=>e=>{let o=xr(e);return"top"in o&&(o.width=t.width-(e.left-t.left)-10),o},ah=({inputElement:t,boundaryRef:e,inputStyle:o,children:n,suggestion:s})=>{let r=y("TabCompletion",te),i=kt(),a=rh(()=>ih(t.getBoundingClientRect()),[t]),[l,c]=tn(t);return sh(()=>{c?i.open():i.close()},[c]),lh("span",{children:[lo("mark",{ref:Rn([l,i.triggerRef]),className:oh(r.matchKeyword,{[r.hover]:c}),"aria-haspopup":"dialog","aria-expanded":i.opened?"true":"false",children:n}),i.opened&&lo(Rt,{className:r.popover,triggerRef:i.triggerRef,boundaryRef:e,position:"below",align:"start",toStyle:a,children:lo(Pn,{style:o,children:lo("div",{className:r.hintText,children:s})})})]})},In=class extends nh{keywordMatches=[];preparedKeywordMatches=[];usedKeywordMatches=new Set;onBeforeParse(e,o){return o.keywordMatches&&o.keywordMatches!==this.keywordMatches&&(this.preparedKeywordMatches=o.keywordMatches.map(n=>({...n,keywordRegex:new RegExp(`\\b${ac(n.keyword)}\\b`,"i")})),this.keywordMatches=o.keywordMatches),this.usedKeywordMatches.clear(),e}match(e){let o=this.preparedKeywordMatches.map(s=>{if(this.usedKeywordMatches.has(s))return null;let r=e.match(s.keywordRegex);if(!r)return null;let i=e.charAt(r.index-1),a=e.charAt(r.index+s.keyword.length);return i==="{"&&a==="}"?null:{index:r.index,length:r[0].length,match:r[0],matchString:r[0],suggestion:s.suggestion,preparedKeywordMatch:s,valid:!0}}).filter(lc);if(o.length===0)return null;let n=o.reduce((s,r)=>r.index<s.index?r:s);return this.usedKeywordMatches.add(n.preparedKeywordMatch),n}replaceWith(e,o){return lo(ah,{inputElement:o.inputElement,suggestion:o.suggestion,inputStyle:o.inputStyle,boundaryRef:o.boundaryRef,children:e},`keyword_${o.matchString}_${o.key}`)}asTag(){return"mark"}};import Er from"classnames";import{Matcher as yh}from"interweave";import{createRef as Sh,forwardRef as vh,useCallback as _h,useEffect as yc,useRef as Sc,useState as vc}from"react";import{useDispatch as xh}from"react-redux";import{jsx as pc}from"react/jsx-runtime";var uc=()=>pc("svg",{width:"1.3em",height:"1.3em",focusable:"false","aria-hidden":"true",viewBox:"0 0 24 24","data-testid":"InsertLinkIcon",tabIndex:-1,children:pc("path",{fill:"currentColor",d:"M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76 0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71 0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71 0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76 0 5-2.24 5-5s-2.24-5-5-5z"})});import{useCallback as ch,useEffect as gc,useState as mc}from"react";import{useDispatch as ph,useSelector as fc}from"react-redux";import uh from"lodash.debounce";var dc={root:"_root_1muu8_1",content:"_content_1muu8_7"};function An(t,e,o){var s;let n=((s=t.imageSizes)==null?void 0:s[e])||t.image||o;if(!n)return null;try{return new URL(n).toString()}catch{return null}}function br(t){return t.replace("https://www.","").replace("https://","")}import{jsx as $e,jsxs as Cr}from"react/jsx-runtime";var dh=3,gh=t=>({image:t.image||"",text:t.text,id:t.id,title:t.title}),mh=({onSelectLink:t,onDismiss:e,placeholder:o,visitUrlText:n,linkCount:s=dh})=>{let r=y("LinkSearch",dc),[i,a]=mc(""),l=ph(),c=fc(Pa("url")),p=fc(ma("URL",gh)),[u,d]=mc(p.length-1),m=b("fallbackImage"),h=f=>{let _=f.target;a(_.value)},g=(f,_)=>{f.stopPropagation(),f.preventDefault(),window.open(_,"_blank")},v=f=>{var C;let _=u-1<0?p.length-1:u-1,x=u+1===p.length?0:u+1;f.code==="Escape"&&(a(""),e()),f.code==="ArrowUp"&&d(_),f.code==="ArrowDown"&&d(x),f.code==="Enter"&&t(((C=p[u])==null?void 0:C.text)||i)},E=ch(uh(f=>{l(We({query:f,type:"URL",tags:["link-search"]}))},300),[]);return gc(()=>{i&&E(i)},[i]),gc(()=>()=>{l(un())},[]),Cr("div",{className:r.root,children:[$e(fe,{withDivider:!0,children:(i?p:c).slice(0,s).map((f,_)=>$e(O,{selected:u===_,onClick:()=>t(f.text),"data-testid":"linksearch-suggestion",children:Cr(H,{children:[$e(H.Image,{src:An(f,"small",m||void 0),title:f.title||f.text}),Cr(H.Content,{className:r.content,cropText:!0,children:[$e(H.Title,{children:f.title||br(f.text)}),f.title&&br(f.text)]}),$e(O.Actions,{children:$e(O.ActionButton,{label:n,onClick:x=>g(x,f.text)})})]})},f.text))}),$e(Yt,{value:i,onChange:h,autoFocus:!0,placeholder:o,onKeyUp:v})]})},hc=mh;var wr={};z(wr,{enUS:()=>fh,nlNL:()=>hh});var fh={insertLink:[{type:0,value:"Insert link"}],linkInputPlaceholder:[{type:0,value:"Search, type or paste link"}],visitUrl:[{type:0,value:"Visit"}]},hh={insertLink:[{type:0,value:"Voeg link toe"}],linkInputPlaceholder:[{type:0,value:"Zoek, typ of plak link"}],visitUrl:[{type:0,value:"Bekijk"}]};import{jsx as de,jsxs as Tr}from"react/jsx-runtime";var bh=vh((t,e)=>{let o=y("TabCompletion",te);return de("mark",{ref:e,className:Er(o.matchSelection)},"selection-start")}),Ch=({startRef:t,boundaryRef:e,inputStyle:o,inputElement:n,children:s})=>{let r=w(wr),i=y("TabCompletion",te),a=Sc(null),l=Sc(null),[c,p]=vc(null),u=xh(),d=kt(document.activeElement===n),[m]=vc(()=>document.createRange());d.triggerRef.current=m,yc(()=>()=>m.detach(),[]),yc(()=>{let g=t.current,v=a.current;!g||!v||(m.setStart(g,0),m.setEnd(v,0))},[t.current,a.current]),ut(()=>{d.close()});let h=_h(g=>{let v=m.toString(),E=/^http(s?):\/\//.test(g)?g:`https://${g}`;u($o({text:`[${v}](${E})`,replace:"selection"}))},[]);return Tr("span",{children:[de("mark",{ref:a,className:Er(i.matchSelection),"aria-haspopup":"dialog","aria-expanded":d.opened?"true":"false",children:s}),d.opened&&de(Rt,{className:i.popoverRoot,triggerRef:d.triggerRef,boundaryRef:e,position:"above",align:"start",children:Tr(Pn,{style:o,ref:l,children:[de("div",{className:Er(i.selectionOptions,{[i.selectionOptionsIsHidden]:c!==null}),children:Tr("button",{type:"button",tabIndex:c===null?-1:void 0,className:i.selectionOptionsButton,onClick:()=>p("insertLink"),children:[de(uc,{}),de("span",{children:"\xA0"}),de("span",{children:r("insertLink")})]})}),c==="insertLink"&&de(hc,{placeholder:r("linkInputPlaceholder"),visitUrlText:r("visitUrl"),onSelectLink:h,onDismiss:()=>{p(null),d.close()}})]})})]},"selection-end")},Ln=class extends yh{charCount=0;foundIndex=0;startRef=null;props;onBeforeParse(e,o){return this.props=o,this.charCount=0,this.startRef=Sh(),this.foundIndex=0,e}match(e){if(!this.props||this.props.selection===null||this.foundIndex===2)return null;let[o,n]=this.props.selection;if(o===n)return null;let s=this.foundIndex===0?o:n,r=s>=this.charCount&&s<=this.charCount+e.length?{index:s-this.charCount,length:0,match:"",valid:!0}:null;r&&this.foundIndex++;let i=this.foundIndex===1;return r&&i?this.charCount+=s-this.charCount:this.charCount+=e.length,r?{isStart:i,...r}:null}replaceWith(e,o){return o.isStart?de(bh,{ref:this.startRef}):de(Ch,{inputElement:o.inputElement,startRef:this.startRef,boundaryRef:o.boundaryRef,inputStyle:o.inputStyle})}asTag(){return"mark"}};import{jsx as Pt,jsxs as Ah}from"react/jsx-runtime";var Ph=({enabled:t,content:e,tabText:o,showTabHint:n,showTabCompletion:s,showStyleSuggestions:r,keywordMatches:i,inputElement:a,source:l})=>{let c=y("TabCompletion",tc),p=b("insertLink"),u=b("showMidSentenceSuggestions"),d=b("inlineSuggestions"),m=nn(a),h=kh(null);Eh(()=>{we(a)&&m&&sn(a,m)},[m]);let g=Th(f=>{if(!s||!o)return f;let _=[Pt("span",{className:c.resetIndent,children:"\u200B"},"u200B"),Pt("span",{"data-testid":"tab-completion",className:kr(c.tabText,c.resetIndent),"data-source":l,children:o},"tabText")];return n&&_.push(Pt("span",{className:kr(c.hint,c.resetIndent),children:Pt(ps,{keyCode:"tab"},"tabHint")})),yr(f,_)},[s,o,n]),v=_c(()=>{let f=[];return d&&f.push(new kn("inline")),p&&f.push(new Ln("selection")),f.push(new pt("placeholders")),r&&f.push(new In("keywords")),f},[d,p,r]),E=_c(()=>{let f=window.getComputedStyle(a);return{"--dd-color":f.color,"--dd-font-size":f.fontSize,"--dd-font-family":f.fontFamily,"--dd-font-variant":f.fontVariant}},[]);return t?Ah("div",{ref:f=>{f!=null&&f.parentElement&&(h.current=f==null?void 0:f.parentElement)},className:c.root,style:E,children:[Pt(wh,{tagName:"span",containerTagName:"div",className:kr(c.container,c.agentText),disableLineBreaks:we(a),content:e||"\u200B",onAfterParse:g,matchers:v,selection:m,keywordMatches:i,inputElement:a,inputStyle:E,boundaryRef:h,inlineSuggestionsOnlyAtEnd:!u}),Pt("br",{})]}):null},Ih=({input:t,ui:e,settings:o,styleSuggestions:n,conversation:s})=>{var g;let{tabCompletionSuggestion:r}=t,i=(r==null?void 0:r.text)||"",a=(r==null?void 0:r.source)||"",l=t.html??ro(t.text),c=i.indexOf(t.text)===0?i.slice(t.text.length):"",{showTabHint:p}=e,{isSupported:u}=s,{showTabCompletion:d,visible:m,showStyleSuggestions:h}=o;return{showTabHint:p,showStyleSuggestions:h,showTabCompletion:d,content:l,tabText:c,source:a,keywordMatches:((g=n.list)==null?void 0:g.keywordMatches)??[],enabled:m&&u!==!1}},xc=Rh(Ih)(Ph);import my from"classnames";import{useEffect as fy}from"react";import{useDispatch as hy,useSelector as Q}from"react-redux";import{createAsyncThunk as co,createSlice as Lh}from"@reduxjs/toolkit";var bc={list:[],fetchState:"idle",isInitialRequest:null},wc=t=>t.autoflows.list||[],Cc=t=>e=>{var o;return(o=e.list)==null?void 0:o.find(n=>n.triggerPayload===t)},Ee=co("autoflows/getAll",async(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");return o.getAutoflows(t)}),Rr=co("autoflows/start",async(t,e)=>{let{dispatch:o}=e,{deepdeskBrokerAPI:n}=e.extra;if(!n)throw new Error("Deepdesk Broker not initialized");await n.startAutoflowSession(t),await o(Ee(t.platformSessionId))}),Pr=co("autoflows/stop",async(t,e)=>{let{dispatch:o}=e,{deepdeskBrokerAPI:n}=e.extra;if(!n)throw new Error("Deepdesk Broker not initialized");await n.stopAutoflowSession(t.platformSessionId),await o(Ee(t.platformSessionId))}),Mh=Lh({name:"autoflows",initialState:bc,reducers:{},extraReducers:t=>{t.addCase(Rr.pending,(e,o)=>{let n=Cc(o.meta.arg.triggerPayload)(e);n.state="Started",n.isBusy=!0}),t.addCase(Pr.pending,(e,o)=>{let n=Cc(o.meta.arg.triggerPayload)(e);n.state="Aborted",n.isBusy=!0}),t.addCase(Ee.pending,e=>{e.isInitialRequest=e.isInitialRequest===null,e.fetchState="loading"}),t.addCase(Ee.rejected,e=>{e.fetchState="error"}),t.addCase(Ee.fulfilled,(e,o)=>{e.list=o.payload,e.fetchState="done"}),t.addCase(P,()=>bc)}}),Tc=co("autoflows/openStream",(t,e)=>{let{dispatch:o}=e,{deepdeskBrokerAPI:n}=e.extra;if(!n)throw new Error("Deepdesk Broker not initialized");let s=n.openStream(t);s.on("sessionAborted",()=>{o(Ee(t))}),s.on("sessionCompleted",()=>{o(Ee(t))})}),Ec=co("autoflows/closeStream",(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");o.closeStream(t)}),kc=Mh.reducer;import{createAsyncThunk as uo,createSlice as Nh}from"@reduxjs/toolkit";var Rc={list:[],fetchState:"idle",isInitialRequest:null,sentSuggestions:[],errorSuggestions:[],answeredSuggestions:[]},Pc=t=>t.customMessages.list,Ic=t=>e=>!!e.customMessages.sentSuggestions.find(o=>o===t),Ac=t=>e=>!!e.customMessages.answeredSuggestions.find(o=>o===t),Lc=t=>e=>!!e.customMessages.errorSuggestions.find(o=>o===t),po=uo("customMessages/getAll",async(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");return o.getCustomMessages(t)}),Mn=uo("customMessages/send",async(t,e)=>{let{platformSessionId:o,suggestion:n}=t,{deepdeskBrokerAPI:s}=e.extra;if(!s)throw new Error("Deepdesk Broker not initialized");await s.sendCustomMessage(o,n)}),Nn=uo("customMessages/answer",async(t,e)=>{let{platformSessionId:o,reply:n}=t,{deepdeskBrokerAPI:s}=e.extra;if(!s)throw new Error("Deepdesk Broker not initialized");await s.answerCustomMessage(o,n)}),Mc=Nh({name:"customMessages",initialState:Rc,reducers:{onCustomMessage(t,e){Array.isArray(e.payload)?t.list=e.payload:t.list=[e.payload]}},extraReducers:t=>{t.addCase(po.pending,e=>{e.isInitialRequest=e.isInitialRequest===null,e.fetchState="loading"}).addCase(po.rejected,e=>{e.fetchState="error"}).addCase(po.fulfilled,(e,o)=>{e.fetchState="done",e.list=o.payload||[]}).addCase(Mn.pending,(e,o)=>{e.sentSuggestions.push(o.meta.arg.suggestion.text),e.errorSuggestions=e.errorSuggestions.filter(n=>o.meta.arg.suggestion.text!==n)}).addCase(Mn.rejected,(e,o)=>{let n=e.sentSuggestions.indexOf(o.meta.arg.suggestion.text);e.errorSuggestions.push(...e.sentSuggestions.splice(n,1))}).addCase(Nn.pending,(e,o)=>{e.sentSuggestions.push(o.meta.arg.suggestion.text),e.answeredSuggestions.push(o.meta.arg.suggestion.text)}).addCase(Nn.rejected,(e,o)=>{let n=e.answeredSuggestions.indexOf(o.meta.arg.suggestion.text);e.errorSuggestions.push(...e.sentSuggestions.splice(n,1)),e.answeredSuggestions.splice(n,1)}).addCase(P,()=>Rc)}}),Nc=uo("customMessages/openStream",(t,e)=>{let{dispatch:o}=e,{deepdeskBrokerAPI:n}=e.extra;if(!n)throw new Error("Deepdesk Broker not initialized");n.openStream(t).on("customMessageSuggestion",r=>{o(Mc.actions.onCustomMessage(r))})}),Oc=uo("customMessages/closeStream",(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");o.closeStream(t)}),Dc=Mc.reducer;import{createAsyncThunk as Hc,createSlice as Oh}from"@reduxjs/toolkit";var Dh={jwt:null,accountUrl:null,interval:null},Bc=t=>e=>{let{exchangeToken:{jwt:o,accountUrl:n}}=e;return o&&n?`${n}/apis/admin/session/jwt/?jwt=${o}&redirect=${t}`:null},Ir=Hc("exchangeToken/getTemporaryExchangeToken",async(t,e)=>{let{deepdeskAPI:o}=e.extra,n=await o.getTemporaryExchangeToken();return{accountUrl:o.client.baseUrl,jwt:n}}),Ar=Hc("exchangeToken/pollExchangeToken",(t={},e)=>{let{interval:o=1e3*60*30}=t,{dispatch:n}=e;return n(Ir()),setInterval(()=>n(Ir()),o)}),Fc=Oh({name:"exchangeToken",initialState:Dh,reducers:{stopPollExchangeToken(t){t.interval&&clearInterval(t.interval),t.interval=null}},extraReducers:t=>{t.addCase(Ir.fulfilled,(e,o)=>{e.jwt=o.payload.jwt,e.accountUrl=o.payload.accountUrl}),t.addCase(Ar.fulfilled,(e,o)=>{e.interval=o.payload})}}),{stopPollExchangeToken:Kc}=Fc.actions,Uc=Fc.reducer;function zc(t){let{customMessages:e,autoflows:o}=t;return o.fetchState==="loading"&&o.isInitialRequest===!0||e.fetchState==="loading"&&e.isInitialRequest===!0}import{Fragment as Wh}from"react";import{connect as Gh}from"react-redux";import jh from"classnames";import{Fragment as qh}from"react";import Hh from"classnames";var jc={root:"_root_838fd_1"};import{jsx as Fh}from"react/jsx-runtime";var Bh=({className:t,children:e})=>{let o=y("Unicode",jc);return Fh("span",{className:Hh(t,o.root),children:e})},qc=Bh;var Vc={isDisabled:"_isDisabled_1rmfm_1",buttonStart:"_buttonStart_1rmfm_5",root:"_root_1rmfm_8",buttonStop:"_buttonStop_1rmfm_8",stateBadge:"_stateBadge_1rmfm_19",isCompleted:"_isCompleted_1rmfm_26",isStarted:"_isStarted_1rmfm_30",isAborted:"_isAborted_1rmfm_34"};var Lr={};z(Lr,{enUS:()=>Kh,nlNL:()=>Uh});var Kh={start:[{type:0,value:"Start"}],stop:[{type:0,value:"Stop"}],aborted:[{type:0,value:"Stopped"}],completed:[{type:0,value:"Completed"}],Aborted:[{type:0,value:"Stopped"}],Started:[{type:0,value:"Running"}],Completed:[{type:0,value:"Completed"}]},Uh={start:[{type:0,value:"Start"}],stop:[{type:0,value:"Stop"}],aborted:[{type:0,value:"Stopped"}],completed:[{type:0,value:"Completed"}],Aborted:[{type:0,value:"Stopped"}],Started:[{type:0,value:"Running"}],Completed:[{type:0,value:"Completed"}]};import{jsx as Xe,jsxs as On}from"react/jsx-runtime";var Vh=({disabled:t,state:e,displayName:o,description:n,onStartAutoflow:s,onStopAutoflow:r})=>{let i=y("Autoflow",Vc),a=w(Lr),l=e==="Started"?"stop":"start",c=l==="start"?"\u25B6":l==="stop"?"\u25FC":"";return On(O,{className:jh(i.root,{[i.isDisabled]:t,[i.isCompleted]:e==="Completed",[i.isAborted]:e==="Aborted",[i.isStarted]:e==="Started"}),children:[Xe(H,{children:On(H.Content,{children:[On(H.Title,{children:[e&&Xe("span",{className:i.stateBadge,children:a(e)}),o]}),Xe("span",{children:n})]})}),Xe(O.Actions,{fixed:e==="Started",children:Xe(O.ActionButton,{primary:!0,className:l==="start"?i.buttonStart:i.buttonStop,onClick:e==="Started"?r:s,disabled:t,label:On(qh,{children:[Xe(qc,{children:c})," ",Xe("span",{children:a(l)})]})})})]})},Wc=Vh;import{jsx as Gc}from"react/jsx-runtime";var $h=(t,e)=>{let o=e.filter(n=>n.state==="Started");return o.length>0?o.indexOf(t)===-1:!1},Xh=({autoflows:t,onStartAutoflow:e,onStopAutoflow:o,platformSessionId:n})=>Gc(Wh,{children:t.map(s=>Gc(Wc,{displayName:s.displayName,description:s.description,disabled:s.isBusy||$h(s,t),state:s.state,onStartAutoflow:()=>e({platformSessionId:n,triggerPayload:s.triggerPayload}),onStopAutoflow:()=>o({platformSessionId:n,triggerPayload:s.triggerPayload})},s.displayName))}),Qh=({autoflows:t,conversation:e})=>{var o;return{autoflows:t.list,platformSessionId:(o=e.current)==null?void 0:o.sessionId}},Zh={onStartAutoflow:Rr,onStopAutoflow:Pr},$c=Gh(Qh,Zh)(Xh);import{useEffect as Jh,useState as Yh}from"react";import{useDispatch as ey}from"react-redux";import Zc from"classnames";import{jsx as Xc}from"react/jsx-runtime";var Mr=()=>Xc("svg",{width:"1em",height:"1em",viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",children:Xc("path",{d:"M502.6 70.63l-61.25-61.25C435.4 3.371 427.2 0 418.7 0H255.1c-35.35 0-64 28.66-64 64l.0195 256C192 355.4 220.7 384 256 384h192c35.2 0 64-28.8 64-64V93.25C512 84.77 508.6 76.63 502.6 70.63zM464 320c0 8.836-7.164 16-16 16H255.1c-8.838 0-16-7.164-16-16L239.1 64.13c0-8.836 7.164-16 16-16h128L384 96c0 17.67 14.33 32 32 32h47.1V320zM272 448c0 8.836-7.164 16-16 16H63.1c-8.838 0-16-7.164-16-16L47.98 192.1c0-8.836 7.164-16 16-16H160V128H63.99c-35.35 0-64 28.65-64 64l.0098 256C.002 483.3 28.66 512 64 512h192c35.2 0 64-28.8 64-64v-32h-47.1L272 448z"})});var Qc={root:"_root_rjdyr_1",entity:"_entity_rjdyr_10",entityText:"_entityText_rjdyr_46",iconWrapper:"_iconWrapper_rjdyr_53",icon:"_icon_rjdyr_53",iconClicked:"_iconClicked_rjdyr_67"};import{jsx as It,jsxs as Jc}from"react/jsx-runtime";var ty=({entities:t})=>{let e=y("EntitiesWidgetList",Qc),[o,n]=Yh(void 0),s=ey(),r=()=>{n(void 0)},i=a=>{t&&(n(t.indexOf(a)),to(a.text),s(J({name:"entity copied",data:{entity:a,type:"copy"}})))};return Jh(()=>{let a=setTimeout(r,500);return()=>{clearTimeout(a)}},[o]),!t||t.length===0?null:It("div",{className:e.root,"data-testid":"widget-entities-list",children:t.map((a,l)=>Jc("button",{title:a.text,className:e.entity,type:"button",onClick:()=>i(a),children:[It("span",{className:e.entityText,children:a.text}),Jc("span",{className:e.iconWrapper,children:[It("span",{className:Zc(e.icon),children:It(Mr,{})}),It("span",{className:Zc(e.icon,o===l&&e.iconClicked),children:It(Mr,{})})]})]},a.text))})},Yc=ty;import sy from"classnames";import{useCallback as ep}from"react";import{useDispatch as ry,useSelector as Dn}from"react-redux";var go={};z(go,{enUS:()=>oy,nlNL:()=>ny});var oy={preview:[{type:0,value:"Preview"}],useSuggestion:[{type:0,value:"Add"}],sendSuggestion:[{type:0,value:"Send"}],suggestionSent:[{type:0,value:"Sent"}],sendingError:[{type:0,value:"Sending failed"}],tryAgain:[{type:0,value:"Try again"}],editSuggestion:[{type:0,value:"Edit"}],visitUrl:[{type:0,value:"Visit"}],answer:[{type:0,value:"Answer"}]},ny={preview:[{type:0,value:"Preview"}],useSuggestion:[{type:0,value:"Gebruik"}],sendSuggestion:[{type:0,value:"Verzenden"}],suggestionSent:[{type:0,value:"Verzonden"}],sendingError:[{type:0,value:"Verzenden mislukt"}],tryAgain:[{type:0,value:"Probeer opnieuw"}],editSuggestion:[{type:0,value:"Bewerken"}],visitUrl:[{type:0,value:"Bekijk"}],answer:[{type:0,value:"Antwoord"}]};var ke={root:"_root_1e6ej_1",title:"_title_1e6ej_8",isUsed:"_isUsed_1e6ej_13",quickReplies:"_quickReplies_1e6ej_22",quickReply:"_quickReply_1e6ej_29",hasError:"_hasError_1e6ej_39",label:"_label_1e6ej_43",errorIcon:"_errorIcon_1e6ej_48"};import{jsx as De,jsxs as Hn}from"react/jsx-runtime";var iy=({suggestion:t})=>{let e=w(go),o=ry(),n=Dn(Ic(t.text)),s=Dn(Ac(t.text)),r=Dn(Lc(t.text)),i=Dn(Fo),{replyOptions:a}=t,l=ep(p=>{p.preventDefault(),p.stopPropagation(),!(n||!i)&&o(Mn({platformSessionId:i,suggestion:t}))},[t,n,o,i]),c=ep(p=>{if(p.preventDefault(),p.stopPropagation(),!i||!a)return;let u=parseInt(p.target.dataset.index,10),d=a[u];o(Nn({platformSessionId:i,reply:d,suggestion:t}))},[t,n,o,i]);return Hn(O,{onClick:l,className:sy(ke.root,{[ke.isUsed]:n,[ke.hasError]:r}),children:[De(H,{children:Hn(H.Content,{children:[Hn(H.Title,{className:ke.title,children:[t.text," ",De(us,{className:ke.label,children:"analyse tool"})," ",r&&De("span",{className:ke.errorIcon,role:"img","aria-label":e("sendingError"),title:e("sendingError"),children:"!"})]}),a&&a.length>0&&De("ul",{className:ke.quickReplies,children:a.map(p=>De("li",{className:ke.quickReply,children:p.title},p.title))})]})}),Hn(O.Actions,{fixed:r||n,children:[a&&a.length>0&&De(O.DropdownButton,{label:e("answer"),disabled:s,children:a.map((p,u)=>De(O.DropdownItem,{index:u,label:p.title,onClick:c},p.title))}),De(O.ActionButton,{primary:!0,disabled:n,onClick:l,label:e(n?"suggestionSent":r?"tryAgain":"sendSuggestion")})]})]})},tp=iy;import{jsx as op}from"react/jsx-runtime";var np=()=>op("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:op("path",{d:"M17 13.5v6H5v-12h6m3-3h6v6m0-6-9 9",stroke:"currentColor",strokeWidth:"1.5",fill:"none",fillRule:"evenodd",strokeLinecap:"round",strokeLinejoin:"round"})});import{useSelector as cy}from"react-redux";import{useCallback as ay}from"react";import{jsx as Qe,jsxs as Bn}from"react/jsx-runtime";var ly=({suggestion:t,lines:e,onEdit:o,onUse:n})=>{var d;let s=t.text||t.url||t.message,r=dn(s),i=w(go),a=b("showImages"),l=b("fallbackImage"),c=m=>{m.preventDefault(),m.stopPropagation(),n(s)},p=m=>{m.preventDefault(),m.stopPropagation(),o(t)},u=ay(m=>{window.open(r,"_blank"),m.stopPropagation(),m.preventDefault()},[r]);return Bn(O,{onClick:c,"data-testid":"edit-suggestion",children:[Bn(H,{children:[a&&t.image&&Qe(H.Image,{src:An(t,"small",l||void 0),title:t.title}),Bn(H.Content,{children:[t.title&&Qe(H.Title,{"data-testid":"widget-suggestion-title",children:t.title}),t.searchKeywords&&((d=t.searchKeywords)==null?void 0:d.length)>0&&Qe(O.Labels,{labels:t.searchKeywords}),Qe(H.Content,{cropText:e==="single",lineClamp:e==="multiple",children:s})]})]}),Bn(O.Actions,{children:[r&&Qe(O.ActionButton,{onClick:u,label:i("visitUrl")}),Qe(O.ActionButton,{primary:!0,onClick:p,label:i("preview")}),Qe(O.ActionButton,{primary:!0,onClick:c,label:i("useSuggestion")})]})]})},sp=ly;import{Fragment as uy,jsx as rp}from"react/jsx-runtime";var py=({contentType:t,lines:e,suggestions:o})=>{let n=oe(),s=cy(yt),r=a=>{n.send(Gs,{state:s,suggestion:a,contentType:t})},i=(a,l)=>{n.send(xe,{text:a,suggestion:{...l,source:l.source,sourceText:l.text}})};return rp(uy,{children:o.map(a=>rp(sp,{suggestion:a,lines:e,onEdit:l=>r(l),onUse:l=>i(l,a)},a.text||a.url||a.message))})},ip=py;var Nr={};z(Nr,{enUS:()=>dy,nlNL:()=>gy});var dy={waiting:[{type:0,value:"Loading\u2026"}],notSupported:[{type:0,value:"This conversation is not supported"}],noResults:[{type:0,value:"No results found\u2026"}],titleAutoflows:[{type:0,value:"Autoflows"}],titleCustomMessages:[{type:0,value:"Quick replies"}],actions:[{type:0,value:"Shortcuts"}],linkPersonalcollection:[{type:0,value:"Personal Collection"}],linkSummary:[{type:0,value:"Summarize"}],linkKnowledgeSearch:[{type:0,value:"Knowledge Assist"}],linkSearch:[{type:0,value:"Search"}]},gy={waiting:[{type:0,value:"Laden\u2026"}],notSupported:[{type:0,value:"Dit gesprek wordt niet ondersteund"}],noResults:[{type:0,value:"Geen resultaten gevonden\u2026"}],titleAutoflows:[{type:0,value:"Autoflows"}],titleCustomMessages:[{type:0,value:"Quick replies"}],actions:[{type:0,value:"Shortcuts"}],linkPersonalcollection:[{type:0,value:"Personal Collection"}],linkSummary:[{type:0,value:"Gesprek samenvatten"}],linkKnowledgeSearch:[{type:0,value:"Knowledge assist"}],linkSearch:[{type:0,value:"Zoeken"}]};var ap={root:"_root_x0pwe_1",loginText:"_loginText_x0pwe_7",stateText:"_stateText_x0pwe_8",sectionList:"_sectionList_x0pwe_20",shortcutList:"_shortcutList_x0pwe_24",shortcut:"_shortcut_x0pwe_24",link:"_link_x0pwe_52"};import{jsx as lp}from"react/jsx-runtime";var cp=()=>lp("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:lp("path",{d:"M543-340q16.595 0 28.798-12.202Q584-364.405 584-381t-12.202-28.798Q559.595-422 543-422t-28.798 12.202Q502-397.595 502-381t12.202 28.798Q526.405-340 543-340Zm-25-126h47q2-29 8.5-43t32.5-39q27-26 37.5-45.395Q654-612.79 654-639q0-45.882-31.5-74.941Q591-743 540-743q-38 0-68 20.5T428-665l45 19q11-25 27.5-38t39.5-13q29.778 0 48.389 17Q607-663 607-637q0 20-9 35t-32 32q-32 29-40 46.5t-8 57.5ZM260-200q-24 0-42-18t-18-42v-560q0-24 18-42t42-18h560q24 0 42 18t18 42v560q0 24-18 42t-42 18H260Zm0-60h560v-560H260v560ZM140-80q-24 0-42-18t-18-42v-620h60v620h620v60H140Zm120-740v560-560Z"})});import{jsx as pp}from"react/jsx-runtime";var up=()=>pp("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:pp("path",{d:"M319-250h322v-60H319v60Zm0-170h322v-60H319v60ZM220-80q-24 0-42-18t-18-42v-680q0-24 18-42t42-18h361l219 219v521q0 24-18 42t-42 18H220Zm331-554v-186H220v680h520v-494H551ZM220-820v186-186 680-680Z"})});import{jsx as M,jsxs as At}from"react/jsx-runtime";var Fn=(t,e)=>{let o=Q(_e);fy(()=>o?e.every(n=>!!n)?t():()=>{}:()=>{},[...e,o])},yy=()=>{let t=w(Nr),e=hy(),o=b("isEmbedded"),n=y("Widget",ap),s=b("showAutoflows"),r=b("showCustomMessages"),i=b("showPersonalCollectionLink"),a=b("showSummaryCommand"),l=b("showKnowledgeSearch"),c=b("showSearch"),p=Q(Tt),u=Q(_n),d=Q(wc),m=Q(yn),h=Q(Pc),g=Q(Ko),v=Q(Uo),E=Q(_e),f=Q(Fo),_=Q(zc),x=Q(yt),C=oe(),T=Q(Aa),N=Q(Bc("/admin/personal-collection")),ee=b("adminUrl");if(Fn(()=>(e(po(f)),e(Nc(f)),()=>{e(Oc(f))}),[e,v,r,f]),Fn(()=>(e(Ee(f)),e(Tc(f)),()=>{e(Ec(f))}),[e,v,s,f]),Fn(()=>{u.forEach(({type:R})=>{e(R==="entities"?ae():Se(R))})},[e,v,g,p]),Fn(()=>(e(Ar()),()=>{e(Kc())}),[e,v,i,g]),v===!1)return M("div",{className:n.stateText,children:M("div",{children:M("p",{children:t("notSupported")})})},"supported");if(E===!1)return M("div",{className:n.loginText,children:M("div",{children:M(wn,{isEmbedded:o,loginUrl:ee})})},"login");if(!p||!f||E===null||T||_)return M("div",{className:n.stateText,children:M("div",{children:M("p",{children:t("waiting")})})},"waiting");let D=c||a||l||N;return M("div",{className:my(n.root),"data-testid":"widget",children:At(gs,{className:n.sectionList,children:[D&&M(Ke,{title:t("actions"),type:"shortcuts",children:At("div",{className:n.shortcutList,children:[c&&At("button",{className:n.shortcut,"data-testid":"shortcut-search",onClick:()=>C.send("ShowCommandPalette",{isOpen:!0}),children:[M(ft,{}),t("linkSearch")]}),a&&At("button",{className:n.shortcut,"data-testid":"shortcut-summary",onClick:()=>C.send("ShowCommandPalette",{isOpen:!0,page:"summary"}),children:[M(up,{}),t("linkSummary")]}),l&&At("button",{className:n.shortcut,"data-testid":"shortcut-knowledge-assist",onClick:()=>C.send("ShowCommandPalette",{isOpen:!0,page:"knowledgeAssist"}),children:[M(cp,{}),t("linkKnowledgeSearch")]}),N&&At("a",{className:n.shortcut,target:"_blank",href:N,"data-testid":"shortcut-personal-collection",rel:"noreferrer",children:[M(np,{}),t("linkPersonalcollection")]})]})}),r&&h.length>0&&M(Ke,{type:"custom-messages","data-testid":"custom-messages",children:M(fe,{withDivider:!0,children:h.map(R=>M(tp,{suggestion:R},R.text))})}),s&&d.length>0&&M(Ke,{type:"autoflows",title:t("titleAutoflows"),"data-testid":"autoflows",children:M(fe,{withDivider:!0,children:M($c,{})})}),u.map(({type:R,title:B,amount:V,lines:Xn})=>{var Be;switch(R){case"entities":return m&&m.length>0&&M(Ke,{type:R,title:B,"data-testid":`type-${R}`,children:M(Yc,{entities:m})},R);default:return((Be=x[R])==null?void 0:Be.fetchState)==="done"&&x[R].suggestions.length>0&&M(Ke,{type:R,title:B,"data-testid":`type-${R}`,children:M(fe,{withDivider:!0,children:M(ip,{lines:Xn,contentType:R,suggestions:x[R].suggestions.slice(0,V)||[]})})},R)}})]})})},dp=yy;function fo(t){let e=new Range;return e.selectNodeContents(t),e}function gp(t,e,o){try{return Ze(t,e,o),!0}catch{return!1}}function Kn(t){return"tagName"in t&&(t.tagName==="DIV"||t.tagName==="P")}function Un(t){return"tagName"in t&&t.tagName==="BR"}var mo=/[\u200B-\u200D\uFEFF]/g;function Ze(t,e,o){let n=new Range;if(t.firstChild===null&&e===0&&o===0)return n.selectNodeContents(t),n;let s=0,r=!1;function i(l,c){let p=-1,u=/[\u200B-\u200D\uFEFF]/;if(!u.test(l))return c;for(let d=0;d<=l.length;d++)if(u.test(l[d])||p++,p===c)return d;throw new Error("Offset out of range")}function a(l){switch(l.nodeType){case Node.TEXT_NODE:{let c=l.textContent,p=c.replace(mo,""),u=s+p.length,d=e>=s&&e<=u,m=o>=s&&o<=u;if(d){let h=i(c,e-s);h===0&&!m?n.setStartBefore(l):n.setStart(l,h)}m&&(n.setEnd(l,i(c,o-s)),r=!0),s=u;break}case Node.ELEMENT_NODE:{if(Un(l)&&(s===e&&n.setStartBefore(l),s++,s===o)){n.setEndAfter(l),r=!0;return}for(let p=0;p<l.childNodes.length&&(a(l.childNodes[p]),!r);p++);let c=l.lastChild;Kn(l)&&c&&!Kn(c)&&!Un(c)&&s++;break}default:break}}if(a(t),n.startContainer===document)throw new Error("Offsets out of bound");return n}function zn(t,e){if(!t.contains(e.startContainer)||!t.contains(e.endContainer))throw new Error("Range not within root element");let{startContainer:o,startOffset:n,endContainer:s,endOffset:r,collapsed:i}=e,a,l,c=0;function p(u){let d=u===o,m=u===s;switch(u.nodeType){case Node.TEXT_NODE:{let h=u.textContent;d&&(a=c+h.substring(0,n).replace(mo,"").length),m&&(l=c+h.substring(0,r).replace(mo,"").length),c+=h.replace(mo,"").length;break}case Node.ELEMENT_NODE:{let h=u.nextSibling===null;Un(u)&&!h&&c++;for(let g=0;g<u.childNodes.length;g++){let v=d&&g===n;if(v&&(a=c),(!v||!i)&&p(u.childNodes[g]),m&&g===r-1&&(l=c),l!==void 0)break}!m&&Kn(u)&&!h&&c++,m&&(l=c);break}default:break}}if(p(t),l===void 0)throw new Error("Could not determine start and end");return{start:a??l,end:l}}function jn(t,e){if(!t.contains(e.startContainer)||!t.contains(e.endContainer))throw new Error("Range not within root element");let{startContainer:o,startOffset:n,endContainer:s,endOffset:r}=e,i=-1,a="";function l(c){let p=c===o,u=c===s;switch(p&&i++,c.nodeType){case Node.TEXT_NODE:{if(i!==0)return;let d=p?n:0,m=u?r:void 0,h=c.textContent.replace(mo,"");d===0&&m===void 0?a+=h:a+=h.substring(d,m);break}case Node.ELEMENT_NODE:{let d=c.nextSibling===null;i===0&&Un(c)&&!d&&(a+=`
|
|
4
|
-
`);for(let m=p?n:0;m<(u?Math.min(r,c.childNodes.length):c.childNodes.length)&&(l(c.childNodes[m]),i!==1);m++);!u&&i===0&&
|
|
5
|
-
`);break}default:break}u&&i++}return l(t),a}var Lt=class extends Le{observer;lastKnownSelection=null;getRootNode(){return this.element.getRootNode()}getText(){let e=new Range;return e.selectNodeContents(this.element),jn(this.element,e)}getHTML(){return this.element.innerHTML||""}getRange(){var s;let e=this.getRootNode();if(e.activeElement!==this.element)return null;let o="getSelection"in e?e.getSelection():window.getSelection();if(!o)return null;let n="getComposedRanges"in o&&e instanceof ShadowRoot?(s=o.getComposedRanges(e))==null?void 0:s[0]:o.rangeCount>0?o.getRangeAt(0):null;return!n||!this.element.contains(n.startContainer)||!this.element.contains(n.endContainer)?null:n}getSelection(){let e=this.getRange();if(e)return zn(this.element,e);let o=this.lastKnownSelection;if(o&&gp(this.element,o.start,o.end))return o;let n=fo(this.element);return n.collapse(!1),zn(this.element,n)}getSelectedText(){let{start:e,end:o}=this.getSelection();return jn(this.element,Ze(this.element,e,o))}applyChanges(e){var s;if(!this.isActive)return;this.isSettingValue=!0;let o=this.getText(),n=e(this.element);return(s=this.observer)==null||s.takeRecords(),Promise.resolve(n).then(()=>{this.currentText=this.getText(),o!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(){super.listen(),this.observer=new MutationObserver(()=>{setTimeout(()=>{this.triggerChange()},0)}),this.observer.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0});let e=this.element.isContentEditable,o=new MutationObserver(()=>{this.element.isContentEditable!==e&&(e=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>o.disconnect())}dispose(){super.dispose(),this.observer&&this.observer.disconnect()}};var Or=class{constructor(e){this.name=e;this.broadcastChannel=new BroadcastChannel(e)}broadcastChannel;disposeHandlers=[];onMessage(e){this.broadcastChannel.addEventListener("message",e),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",e)})}postMessage(e){this.broadcastChannel.postMessage(e)}close(){this.disposeHandlers.forEach(e=>e()),this.broadcastChannel.close()}},Dr=class{constructor(e,o,n){this.name=e;this.targetOrigin=o;this.options=n;this.iframe=this.createIframe(),document.body.appendChild(this.iframe)}iframe;disposeHandlers=[];createIframe(){let e=`deepdesk-iframe-${this.name}`,o=document.getElementById(e);if(o)return o;let n=document.createElement("iframe"),s=`${this.targetOrigin}/v2/widget/liveengage/channel.html`,r=new URLSearchParams({channel:this.name,host:window.location.origin});return this.options.debug&&r.set("debug","1"),n.style.position="absolute",n.style.left="-999em",n.style.width="0px",n.style.height="0px",n.tabIndex=-1,n.id=e,n.title=`iframe-${this.name}`,n.src=`${s}?${r.toString()}`,n}onMessage(e){window.addEventListener("message",e),this.disposeHandlers.push(()=>{window.removeEventListener("message",e)})}postMessage(e){var o;(o=this.iframe.contentWindow)==null||o.postMessage(e,this.targetOrigin)}close(){var e;this.disposeHandlers.forEach(o=>o()),(e=this.iframe)==null||e.remove()}},Hr=class{constructor(e){this.params=e;this.deepdeskUrl=e.deepdeskUrl,this.eventMap=e.eventMap,this.defaultChannel=this.createChannel("deepdesk-general")}sessionId;deepdeskUrl;channel;defaultChannel;eventMap;get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setSessionId(e){this.sessionId!==e&&(this.cleanup(),k.info("Set sessionId",e),this.sessionId=e,this.channel=this.createChannel(e))}createChannel(e){let o=this.params.createCustomChannel?this.params.createCustomChannel(e):this.isCrossOrigin?new Dr(e,this.deepdeskUrl,{debug:!0}):new Or(e),n=s=>{var r,i;s.origin===this.deepdeskUrl&&s.data.type==="event"&&s.data.channel===e&&(k.info("Received broadcast event",this.sessionId,s),(i=(r=this.eventMap)[s.data.name])==null||i.call(r,s.data.payload))};return o.onMessage(n),o}send(e,o){var s,r,i;if(!this.sessionId)return;k.info("broadcast event",{sessionId:this.sessionId,name:e,payload:o});let n={type:"event",name:e,payload:o};(r=(s=this.eventMap)[e])==null||r.call(s,o),(i=this.channel)==null||i.postMessage({...n,channel:this.sessionId})}cleanup(e=!1){var o,n;(o=this.channel)==null||o.close(),delete this.channel,e&&((n=this.defaultChannel)==null||n.close(),delete this.defaultChannel)}},mp=Hr;var Mt=class extends Error{constructor(o,n){super(o);this.body=n}name="CustomError"};var Br=t=>new Promise(e=>{setTimeout(e,t)});var Nt=class extends Mt{name="ClientError"},Fr=class extends Mt{name="ServerError"},ge=class t{constructor(e="",o={}){this.baseUrl=e;this.options=o;o.fetch&&(this.fetch=o.fetch)}latestRequestByUrl={};csrfToken;fetch=window.fetch.bind(window);static refreshingToken=null;patchFetch(e){this.fetch=e(this.fetch)}setCsrfToken(e){this.csrfToken=e}request(e,o={}){return new Promise((n,s)=>{let r={isAborted:!1,reject:s},i=`${this.baseUrl}${e}`,a=this.fetch,{abortLatest:l=!1,attempts:c=1,retryDelay:p=500,refreshTokenOn401:u=!0,retryOnError:d=x=>x instanceof TypeError,retryOnResponse:m=x=>x.status>=500,version:h="v1",...g}=o,v={credentials:"include",...g,headers:{"Content-Type":"application/json",...g.headers}};o.method!==void 0&&o.method!=="GET"&&this.csrfToken&&(v.headers={...v.headers,"X-CSRFToken":this.csrfToken}),typeof h=="string"&&(v.headers={...v.headers,"X-Deepdesk-API-Version":h});let E=c,f=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[i]&&l&&(this.latestRequestByUrl[i].isAborted=!0,this.latestRequestByUrl[i].reject(new Error("Aborted"))),this.latestRequestByUrl[i]=r;let _=async()=>(E--,a(i,v).then(async x=>m(x)&&!r.isAborted&&E>0?(await Br(p),_()):x.status===401&&u===!0&&f===!1?(f=!0,await this.refreshToken(),_()):x).catch(async x=>{if(d(x)&&!r.isAborted&&E>0)return await Br(p),_();throw x}));_().then(x=>x.json().catch(()=>null).then(C=>{x.status>=500?s(new Fr("Server Error",C)):x.status===401?s(new Nt("Unauthorized",C)):x.status===403?s(new Nt("Forbidden",C)):x.status===404?s(new Nt("Not Found",C)):x.status>=400&&s(new Nt("Bad Request",C)),delete this.latestRequestByUrl[i],n(C)})).catch(x=>{s(x)})})}async validateToken(){let{has_valid_access_token:e}=await this.get("/auth/validate");if(!e)return!1;let{is_logged_in:o}=await this.get("/apis/admin/session/validate/",{version:null});return!!o}refreshToken(){return t.refreshingToken||(t.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{t.refreshingToken=null},1e3*60)})),t.refreshingToken}get(e,o){return this.request(e,o)}post(e,o,n){return this.request(e,{method:"POST",body:JSON.stringify(o),...n})}patch(e,o,n){return this.request(e,{method:"PATCH",body:JSON.stringify(o),...n})}put(e,o,n){return this.request(e,{method:"PUT",body:JSON.stringify(o),...n})}delete(e,o){return this.request(e,{method:"DELETE",...o})}};var Sy;(e=>{let t;(l=>(l.SEND_MESSAGE="Send Message",l.HANDLING_TIME="Handling Time",l.START_AUTOFLOW="Start Autoflow",l.ABORT_AUTOFLOW="Abort Autoflow",l.ADD_TO_PERSONAL_COLLECTION="Add to personal collection",l.DELETE_FROM_PERSONAL_COLLECTION="Delete from personal collection"))(t=e.EventType||={})})(Sy||={});function qn(t){return{...L(t),tags:t.tags}}var He=class t{constructor(e,o={}){this.options=o;this.client=new ge(e,{fetch:o.fetch}),this.client.patchFetch(n=>async(s,r)=>{let i=await n(s,r);return this.handleDeepdeskVersionHeaders(i),i})}latestReceivedDeepdeskVersions={};client;shouldFetchCsrfToken=!0;static exchangeTokenPromise=null;async preflight(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let e=await this.getCsrfToken();this.client.setCsrfToken(e)}return this.options.token?(t.exchangeTokenPromise||(t.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),t.exchangeTokenPromise):Promise.resolve()}async createConversation(e){await this.preflight(),k.info(`Creating conversation for session ${e.sessionId} and agent ${e.agentId}`);let o=await this.client.post("/api/conversations",{...F(e),tags:e.tags},{version:"v2"});return qn(o)}async getProfile(e){let o=await this.client.get(`/apis/admin/profiles/${e}/`,{version:null});return L(o)}async getContentTypes(){let e=await this.client.get("/apis/admin/content-types/",{version:null});return L(e)}async getPlatformConfig(){let{config:e}=await this.client.get("/platform/config/",{version:null});return L(e)}async checkUserExists(e){let{exists:o}=await this.client.get(`/apis/admin/users/exists?external_id=${e}`);return o}async getConversationBySessionId(e,o={}){await this.preflight(),k.info(`Getting conversation for session ${e}`);let{attempts:n=1,retryDelay:s=1e3}=o,r=await this.client.get(`/api/conversations/by_session_id/${e}`,{attempts:n,retryDelay:s,retryOnResponse:i=>i.status===404||i.status>=500,version:"v2"});return qn(r)}async isConversationSupported(e,o={}){k.info(`Check if conversation for session ${e} is supported`);let{attempts:n=1,retryDelay:s=1e3}=o;return(await this.client.get(`/api/conversations/by_session_id/${e}/active_profile`,{attempts:n,retryDelay:s,retryOnResponse:i=>i.status===404||i.status>=500,version:"v2"})).has_active_profile}async updateConversation(e,o){let n=F(o);o.tags&&(n.tags=o.tags);let s=await this.client.put(`/api/conversations/${e}`,n,{version:"v2"});return qn(s)}async postMessages(e,o){return(await this.client.post(`/api/conversations/${e}/messages`,o.map(s=>({...F(s),tags:s.tags})),{version:"v2"})).map(s=>qn(s))}async sendEvent(e,o){let{data:n,...s}=o,r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((i,[a,l])=>({...i,[a]:l}),{});return this.client.post("/api/events",F({...r,...s,data:n,name:e}),{version:"v2"})}async sendEventV1(e,o){let n=Object.entries(this.latestReceivedDeepdeskVersions).reduce((s,[r,i])=>({...s,[r]:i}),{});return this.client.post("/api/events",{event:e,data:F({...o,...n})})}async getEntities(e){return(await this.client.post("/api/entities",{messages:e.filter(n=>n.text)})).entities}async getSummary(e,o={}){return(await this.client.post("/api/summary",{conversation:{messages:e.filter(s=>s.text&&s.source)},prompt_instruction:o.promptInstruction,model:o.model})).summary}async getTemporaryExchangeToken(){return(await this.client.get("/auth/exchange-token",{version:null})).jwt}async exchangeTokenForAccessCookie(e){return this.client.post("/apis/admin/session/jwt/",{jwt:e},{version:null}).catch(o=>{throw k.warn(`Invalid token '${e}'`),o})}async authenticateWithKey(e,o){await this.client.post("/apis/admin/session/api-key/",F(o),{version:null,refreshTokenOn401:!1,headers:{apikey:e}})}async getTextSuggestions(e,o={},n){return n==="sticky-messages"?this.getPinnedMessages(e):(await this.client.post(`/api/conversations/${e}/recommend/${n}`,F(o),{abortLatest:!0})).map(r=>({...L(r),text:r.text||r.url||r.message,source:n,type:n})).filter((r,i,a)=>i===a.findIndex(l=>l.text===r.text))}async isLoggedIn(){return await this.preflight(),this.client.validateToken()}async getAutocompleteSuggestions(e,o){return(await this.client.post(`/api/conversations/${e}/autocomplete`,F(o),{abortLatest:!0})).map(s=>({score:1,source:s.source,sourceText:s.source_text,text:s.label,trainingJobs:s.training_jobs,searchKeywords:s.search_keywords,type:s.source})).filter((s,r,i)=>r===i.findIndex(a=>a.text===s.text))}async getPinnedMessages(e){let o=await this.client.get(`/api/conversations/${e}/sticky-messages`,{abortLatest:!0});return L(o).map(n=>({...n,text:n.message,source:"sticky-messages",type:"pinned-message"}))}async getStyleSuggestions(e){let o=await this.client.post("/api/style-suggestions",F(e),{abortLatest:!0});return L(o)}async search(e){let o=await this.client.post(`/api/profiles/${e.profile}/search`,F(e),{version:"v2"});return L(o)}async knowledgeAssist(e,o,n){let s=await this.client.post("/api/knowledge-search/search",F({question:e.question,promptInstruction:e.promptInstruction,profile:n,chatHistory:o.map(r=>({question:r.question,answer:r.answer.answer}))}),{version:"v2"});return L(s)}async requestLoginByEmail(e){let o=await this.client.post("/apis/admin/session/passwordless/request/",{email:e},{version:null});return L(o)}async getCsrfToken(){let{token:e}=await this.client.get("/apis/admin/session/csrf/",{version:null});return e}async verifyLoginToken(e){let o=await this.client.post("/apis/admin/session/passwordless/login/",{token:e},{version:null});return L(o)}handleDeepdeskVersionHeaders(e){e.headers.forEach((o,n)=>{let s=n.toLowerCase(),r=s.match(di);if(!o||!r)return;let i=r[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&o&&a!==o&&k.warn(`Overwritten Version header ${s}: ${JSON.stringify(a)} -> ${JSON.stringify(o)}`),this.latestReceivedDeepdeskVersions[i]=o})}};var ho=class{constructor(e,o){this.url=e;this.options={timeout:25e3,...o}}eventListeners={};options;timeoutTimer;eventSource;proxyEvent(e){this.eventSource.addEventListener(Bs(e),o=>{let{data:n}=o;try{let s=JSON.parse(n);this.emit(e,L(s))}catch{k.warn(`Invalid JSON for ${e}: ${n}`)}})}connect(){clearTimeout(this.timeoutTimer);let e=new EventSource(this.url,{withCredentials:!0});this.eventSource=e;let o=!1;e.onopen=()=>{o=!0},e.onerror=()=>{o&&e.readyState===2&&this.connect()},this.timeoutTimer=setTimeout(()=>{e.close(),this.connect()},this.options.timeout),Object.keys(this.eventListeners).forEach(n=>{this.proxyEvent(n)})}disconnect(){var e;clearTimeout(this.timeoutTimer),this.eventListeners={},(e=this.eventSource)==null||e.close()}emit(e,o){this.eventListeners[e]&&this.eventListeners[e].forEach(n=>n(o))}on(e,o){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(o),this.proxyEvent(e),()=>{this.off(e,o)}}off(e,o){let n;this.eventListeners[e]&&(n=this.eventListeners[e].indexOf(o),n>-1&&this.eventListeners[e].splice(n,1))}};var vy;(e=>{let t;(r=>(r.Started="Started",r.Aborted="Aborted",r.Completed="Completed"))(t=e.AutoflowSessionState||={})})(vy||={});var yo=class{constructor(e,o={}){this.apiUrl=e;this.client=new ge(e,o)}client;streams={};logger=k;async getCustomMessages(e){let o=await this.client.get(`/sessions/${e}/suggestions`);return L(o.suggestions)}async sendCustomMessage(e,o){let n=await this.client.post(`/sessions/${e}/messages`,F(o));return L(n)}async answerCustomMessage(e,o){await this.client.post(`/sessions/${e}/answers`,F(o))}async getAutoflows(e){let o=await this.client.get(`/sessions/${e}/autoflows`);return L(o.autoflows)}async startAutoflowSession(e){let o=await this.client.post("/autoflow-sessions",F(e));return L(o)}async stopAutoflowSession(e){await this.client.delete(`/autoflow-sessions/${e}`)}openStream(e){return this.streams[e]||(this.streams[e]=new ho(`${this.apiUrl}/sessions/${e}/events`),this.streams[e].connect()),this.streams[e]}closeStream(e){this.streams[e]||(this.streams[e].disconnect(),delete this.streams[e])}};import{combineReducers as Ey,configureStore as ky}from"@reduxjs/toolkit";import{createSlice as _y}from"@reduxjs/toolkit";var fp={startTime:null,stopTime:null},hp=_y({name:"handlingTime",initialState:fp,reducers:{handlingTimeStart(t){if(t.startTime&&!t.stopTime)throw new Error("Timing already started");t.startTime=new Date,t.stopTime=null},handlingTimeStop(t){if(!t.startTime)throw new Error("Timing not started");t.stopTime=new Date},handlingTimeReset(t){t.startTime=null,t.stopTime=null}},extraReducers:t=>{t.addCase(P,()=>fp)}}),{handlingTimeStart:yp,handlingTimeStop:Vn,handlingTimeReset:Sp}=hp.actions,vp=hp.reducer;var _p=(t={})=>{let e={onAuthError:_t(!1),...t};return o=>n=>s=>("error"in s&&s.error.message==="Unauthorized"&&o.dispatch(e.onAuthError),n(s))};import{createAsyncThunk as xy,createSlice as by}from"@reduxjs/toolkit";var Wn={list:{keywordMatches:[]},fetchState:"idle",isInitialRequest:null};var Je=xy("styleSuggestions/getAll",async({text:t},e)=>{var i;let{deepdeskAPI:o}=e.extra,n=e.getState(),{showStyleSuggestions:s}=n.settings,r=(i=n.conversation.current)==null?void 0:i.profileCode;if(!s)return Wn.list;if(!r)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:r,message:t})}),Cy=by({name:"styleSuggestions",initialState:Wn,reducers:{},extraReducers:t=>{t.addCase(Je.pending,e=>{e.isInitialRequest=e.isInitialRequest===null,e.fetchState="loading"}).addCase(Je.rejected,e=>{e.fetchState="error"}).addCase(Je.fulfilled,(e,o)=>{e.fetchState="done",it(e.list,o.payload)||(e.list=o.payload)}).addCase(je,e=>{e.list=Wn.list}).addCase(P,()=>Wn)}}),xp=Cy.reducer;var bp=(t={})=>{let e,o=!0,n={getStyleSuggestions:Je,debounce:500,...t};return s=>r=>i=>{var m;let a=s.getState().input.text,l=r(i),c=s.getState();if(c.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:p}=c.settings;if(!((m=c.conversation.current)==null?void 0:m.id)||!p)return l;let{text:d}=c.input;return d===a&&!o||(clearTimeout(e),d==="")||(e=setTimeout(()=>{o=!1,s.dispatch(n.getStyleSuggestions({text:d}))},t.debounce)),l}};function wy(t,e){return t.text===e.text&&t.selection.start===e.selection.start&&t.selection.end===e.selection.end}var Cp=(t={})=>{let e={getTextSuggestions:Se,getAutocompleteSuggestions:Xt,debounce:200,check:bn,...t},o;return n=>s=>r=>{var g;let{input:{userCommitted:i}}=n.getState(),a=s(r),l=n.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:c,showTabCompletion:p}=l.settings,u=(g=l.conversation.current)==null?void 0:g.id,d=r.type===fn.toString();if(!u||!c&&!p)return a;let{input:{userCommitted:m}}=l;return wy(m,i)&&!d||(clearTimeout(o),!e.check(l))||(o=setTimeout(()=>{let v=lt(l);v===""?n.dispatch(e.getTextSuggestions("default")):n.dispatch(e.getAutocompleteSuggestions(v))},d?0:e.debounce)),a}};var wp=Je.fulfilled.toString();function Ty(t,e){let o=new Set([...e.keywordMatches.map(s=>s.keyword)]),n=[];return o.forEach(s=>{let r=t.keywordMatches.filter(l=>l.keyword===s),i=e.keywordMatches.filter(l=>l.keyword===s),a=i.length-r.length;a<=0||n.push(...i.slice(0,a))}),n}var Tp=t=>e=>o=>n=>{var c;if(n.type!==wp){o(n);return}let s=e.getState().styleSuggestions.list;o(n);let r=e.getState(),i=r.styleSuggestions.list,a=(c=r.conversation)==null?void 0:c.current;if(s===i)return;let l=Ty(s,i);n.type===wp&&l.length>0&&t.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var Ry=Ey({activeSuggestion:Ua,answer:Pl,auth:tl,autoflows:kc,conversation:Si,contentTypes:dl,customMessages:Dc,exchangeToken:Uc,entities:fl,handlingTime:vp,info:pa,input:xs.reducer,overlayInput:W.reducer,settings:mi,profile:Nl,search:ha,summary:bl,styleSuggestions:xp,ui:Wa,textSuggestions:Da});function Ep(t){return ky({reducer:Ry,middleware:e=>[...e({thunk:{extraArgument:{dynamicThunkObject:t.dynamicThunkObject,deepdeskAPI:t.deepdeskAPI,deepdeskBrokerAPI:t.deepdeskBrokerAPI}},serializableCheck:!1}),_p(),Cp({debounce:200}),bp({debounce:500}),Tp(t.deepdeskAPI),...t.middleware?t.middleware:[]],preloadedState:t.preloadedState})}var Py=t=>{var e;return((e=t==null?void 0:t.type)==null?void 0:e.toLowerCase())??"unknown"},Iy=t=>e=>o=>n=>{var a;let s=e.getState(),r=ys("inlineSuggestions")(s);switch(n.type){case ve.toString():{let l=Ia(n.payload.contentType)(e.getState()),c=l.indexOf(n.payload.suggestion);t.emit("edit-suggestion",{contentType:n.payload.contentType,index:c,suggestions:l});break}case _t.toString():{!n.payload&&t.emit("logout",void 0);break}case ie.toString():{let{start:l,end:c}=s.input.selection;t.emit("select-suggestion",{type:Py(n.payload.suggestion),...n.payload,replace:n.payload.replace==="selection"?{start:l,end:c}:{start:0,end:c}},{mayApplyChanges:!0});break}case $o.toString():{let{start:l,end:c}=s.input.selection;t.emit("replace",{...n.payload,replace:n.payload.replace==="selection"?{start:l,end:c}:{start:0,end:c}},{mayApplyChanges:!0});break}case zt.toString():{let l=e.getState(),{text:c,selection:p}=l.input.userCommitted;t.emit("reset",{text:c,selectionAfter:p},{mayApplyChanges:!0});break}case Jo.toString():t.emit("select-image",n.payload,{mayApplyChanges:!0}),t.sendEvent("Image attached",{conversationId:s.conversation.current.id,data:{path:n.payload.suggestion.image,title:n.payload.suggestion.title}});break;case ae.fulfilled.toString():n.payload.length>0&&t.sendEvent("entities found",{conversationId:s.conversation.current.id,data:{entities:n.payload}});break;case be.fulfilled.toString():t.sendEvent("conversation summarized",{conversationId:s.conversation.current.id,data:{summary:n.payload.summary}});break;case J.toString():t.sendEvent(n.payload.name,{conversationId:((a=n.payload.options)==null?void 0:a.includeConversationData)&&s.conversation.current.id,data:n.payload.data});break;case Xo.toString():t.handleKeyDown(n.payload);break;case je.toString():t.logSendMessage(n.payload);break;case Qo.toString():t.logSendEditSuggestionMessage(n.payload);break;case Zo.toString():t.handleInputChanged(n.payload);break;default:break}let i=o(n);switch(n.type){case je.toString():t.handleAfterSendMessage(n.payload);break;case Qt.toString():t.onUpdateShowTabHint(n.payload);break;case Vn.toString():t.logHandlingTime();break;case ie.toString():{r&&(e.dispatch(Ie([])),e.dispatch(Ae()));break}default:break}return i},kp=Iy;function Kr(t){return t.toISOString().replace("T"," ").replace("Z","")}function Rp(t,e){var s,r,i;let{startTime:o,stopTime:n}=t.handlingTime;if(!o||!n)throw new Error("No startTime and stopTime for handling time metrics");return{conversationId:t.conversation.current.id,clientVersion:e.version,agentId:(s=t.info.agentInfo)==null?void 0:s.agentId,agentName:(r=t.info.agentInfo)==null?void 0:r.agentName,agentEmail:(i=t.info.agentInfo)==null?void 0:i.agentEmail,timeStart:Kr(o),timeStop:Kr(n)}}function Ur(t,e,o){var N,ee,D;let{text:n,metrics:{numCharsTyped:s,numCharsPasted:r,numCharsCut:i,numCharsDeleted:a,numPaste:l,agentStartedTypingTimestamp:c,externalTimeTotalSeconds:p,pastes:u,cuts:d,deletions:m,textSuggestions:h,offeredTextSuggestions:g}}=e[t],v=n.length,f=h.reduce((R,{text:B,searchTerm:V})=>R+B.length-(V?V.length:0),0),_=c??Date.now(),x=(Date.now()-_)/1e3+(p||0),C=s/x,T=h.reduce((R,{searchTerm:B})=>R+(B?B.length:0),0);return{conversationId:e.conversation.current.id,source:"agent",text:n,clientVersion:o.version,pastes:u,cuts:d,deletions:m,lenTextTyped:s+T,lenTextTotal:v,lenTextAssisted:f,lenTextPasted:r,lenTextCut:i,lenTextDeleted:a,timeTotalSeconds:x,charsPerSecond:C,numPastes:l,textSuggestionsV2:h,suggestionsCounters:[{source:"gpt",countOffered:g.filter(R=>R.source==="gpt").length}],agentId:(N=e.info.agentInfo)==null?void 0:N.agentId,agentName:(ee=e.info.agentInfo)==null?void 0:ee.agentName,agentEmail:(D=e.info.agentInfo)==null?void 0:D.agentEmail}}function Pp(t,e){let o=t.closest(e);if(o)return o;let n=t.getRootNode().host;return n instanceof HTMLElement?Pp(n,e):null}function Ip(t,e){return Pp(t,e)}function Ap(t){return typeof t=="object"&&t!==null&&"name"in t&&"message"in t}function zr(t){return t instanceof HTMLElement&&(we(t)||on(t))}var Lp=(t,e)=>({value(){try{let o=sessionStorage.getItem(`dd-${t}`);if(!o)return e;try{return JSON.parse(o)}catch{return e}}catch{return e}},update(o){try{sessionStorage.setItem(`dd-${t}`,JSON.stringify(o))}catch{k.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function Ay(t){return t.offsetParent!==null}function Mp(t){if(!Ay(t))return!1;let e=t.getBoundingClientRect();return e.top>=0&&e.left>=0&&e.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&e.right<=(window.innerWidth||document.documentElement.clientWidth)}function jr(t,e,o=100){let n=Mp(t);e({isVisible:n});let s=setInterval(()=>{let r=Mp(t);r!==n&&(n=r,e({isVisible:n}))},o);return()=>{clearTimeout(s)}}import{jsx as ne}from"react/jsx-runtime";var Np=Lp("showTabHint",!0),$n=class t{static version="10.3.1-beta.1";static count=0;deepdeskApi;inputMediator=null;version;broadcastEvents;eventListeners={};unmountHandlers=[];widgetRoot=null;dynamicThunkObject={};isMounted=!1;instanceId;shouldRender=!0;store;constructor({deepdeskUrl:e,brokerUrl:o,version:n=t.version||"unknown",locale:s="en-US",token:r,fetch:i,productName:a,createCustomChannel:l}){let c=e.replace(/\/api$/,"");this.deepdeskApi=new He(c,{token:r,fetch:i}),this.version=n,this.instanceId=t.count++;let p={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[kp({emit:(u,d,m)=>this.emit(u,d,m),handleAfterSendMessage:u=>this.handleAfterSendMessage(u),handleInputChanged:u=>this.handleInputChanged(u),handleKeyDown:u=>this.handleKeyDown(u),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:u=>this.logSendMessage(u),logSendEditSuggestionMessage:u=>this.logSendEditMessage(u),onUpdateShowTabHint:u=>Np.update(u),sendEvent:(u,d)=>this.deepdeskApi.sendEvent(u,d)})]};o&&Object.assign(p,{deepdeskBrokerAPI:new yo(o)}),this.store=Ep(p),this.broadcastEvents=new mp({debug:!0,deepdeskUrl:c,eventMap:ol(this.store),createCustomChannel:l}),this.store.dispatch(Ut),this.store.dispatch(Qt(Np.value())),this.store.dispatch(Ut({locale:s,adminUrl:c,productName:a}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){return this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex]??null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(k.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(k.warn("Profile has not been loaded (yet)"),!0):(k.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(_t(null)),this.store.dispatch(Oe()),new Promise(e=>{let o=this.store.subscribe(()=>{let n=this.store.getState();_e(n)&&Xa(n)!=="loading"&&e()});this.unmountHandlers.push(()=>{o()})})}isLoggedIn(){return this.deepdeskApi.isLoggedIn()}async setPlatformAgentId(e){try{if((await this.deepdeskApi.client.get("/apis/admin/session/me/",{version:null})).external_id)return;await this.deepdeskApi.client.request("/apis/admin/session/me/",{method:"PATCH",body:JSON.stringify({external_id:e}),version:null})}catch(o){k.warn("Failed to attach user:",o)}}async isConversationSupported(e,o){return(await this.store.dispatch(vs({sessionId:e,options:o}))).payload}async createConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(zo(e))).payload}async getConversationBySessionId(e,o){return this.hasConversation()&&this.sessionId()!==e&&this.resetConversation(),(await this.store.dispatch(jo({sessionId:e,options:o}))).payload}async upsertConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(_s(e))).payload}async postMessages(e){return(await this.store.dispatch(Vo(e))).payload}async updateConversation(e){return(await this.store.dispatch(qo(e))).payload}resetConversation(){this.store.dispatch(P()),this.dynamicThunkObject.conversationQuery=null}async getSummary(){let e=await this.store.dispatch(be());if(e.error)throw new Error(e.error.message);return e.payload.summary}configure(e){this.store.dispatch(Ut(e))}setVisitorInfo(e){this.store.dispatch(ca(e))}async setAgentInfo(e){await this.store.dispatch(Wt(e))}async setAgentSettings(e){await this.store.dispatch(Ks(e))}async getAgentSettings(){return(await this.store.dispatch(Us())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let e=[];return this.store.dispatch(fn()),e.push(this.refreshWidgetSuggestions()),Promise.all(e).then(()=>{})}notifyInputChanged(e){this.store.dispatch(Zo(e))}notifyKeyDown(e){this.store.dispatch(Xo(e))}notifyPaste(e,o){this.store.dispatch(Pi({text:e,selectionText:o}))}notifyCut(e){this.store.dispatch(ki(e))}notifyExternalSuggestion(e){this.store.dispatch(ie(e)),this.store.dispatch(Ae())}notifyEditSuggestion(e){this.store.dispatch(Na(e.contentType,e.suggestions)),this.store.dispatch(ve({contentType:e.contentType,suggestion:typeof e.index=="number"?e.suggestions[e.index]:null}))}handleInputChanged(e){let{overlayCollapsed:o,openOverlayWhenTyping:n}=this.state.ui;o&&n&&this.store.dispatch(vt({collapse:!1})),this.inputMediator&&this.store.dispatch(xi({text:e,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(Ie([])))}handleKeyDown(e){let{overlayCollapsed:o}=this.state.ui,{textSuggestions:n,selectedSuggestionIndex:s,selection:r}=this.state.input,{inlineSuggestions:i}=this.state.settings,a=n.length>0,l=s!==-1;if(this.store.dispatch(Ri(Go(e))),!(e.key!=="Tab"&&!this.settings.showTextSuggestions))switch(e.key){case"Up":case"ArrowUp":if(o||!a||!r||e.shiftKey)return;this.store.dispatch(wi()),i||this.stageSelectedSuggestion({inputType:"arrow"}),e.preventDefault();return;case"Down":case"ArrowDown":{if(o||!a||!r||e.shiftKey)return;this.store.dispatch(Ei());let{selectedSuggestionIndex:c}=this.state.input;c===-1?this.store.dispatch(zt()):i||this.stageSelectedSuggestion({inputType:"arrow"}),e.preventDefault();return}case"Esc":case"Escape":{l?(this.store.dispatch(Yo(-1)),this.store.dispatch(zt()),e.preventDefault()):o||(this.store.dispatch(vt({collapse:!0})),this.store.dispatch(qa(!0)),e.preventDefault());return}case"Tab":{let{userCommitted:c}=this.state.input,p=c.text.substring(0,c.selection.end),{tabCompletionSuggestion:u}=this.state.input;this.store.dispatch(Qt(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):this.settings.showTabCompletion&&u&&u.text.startsWith(p)&&(this.store.dispatch(ie({text:u.text,suggestion:u,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch(Ae())),e.preventDefault();break}default:}}handleAfterSendMessage(e){this.emit("send-message",e),this.store.dispatch(Ii()),this.store.dispatch(Ie([]))}handlingTimeStart(){this.state.handlingTime.startTime||(k.info("Start handling time"),this.store.dispatch(yp()))}handlingTimeStop(){this.state.handlingTime.startTime&&(k.info("Stop handling time"),this.store.dispatch(Vn()))}logSendMessage(e){let o=Ur("input",this.state,{version:this.version});e&&Object.assign(o,{text:e}),this.deepdeskApi.sendEventV1("Send Message",o),this.emit("send-message-event",o)}logSendEditMessage(e){let o=Ur("overlayInput",this.state,{version:this.version});e&&Object.assign(o,{text:e}),this.store.dispatch(Ci(this.state.overlayInput.metrics))}logHandlingTime(){let e=Rp(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",e),this.store.dispatch(Sp())}notifySubmit(e={}){this.shouldAbort()||(this.store.dispatch(Ae()),this.store.dispatch(je(e.text??this.state.input.text)))}stageSelectedSuggestion(e){let o=this.state.input.selectedSuggestionIndex,{textSuggestions:n}=this.state.input;this.store.dispatch(ie({text:n[o].text,suggestion:n[o],eventMetrics:e,replace:"until-selection-end"}))}emit(e,o,n={}){let s=()=>{this.eventListeners[e]&&this.eventListeners[e].forEach(r=>{try{r(o)}catch(i){k.warn(`The following error occurred in deepdeskSDK.on('${e}', handler)`),k.error(i)}})};this.inputMediator&&n.mayApplyChanges?this.inputMediator.applyChanges(s):s()}on(e,o){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(o),()=>{this.off(e,o)}}off(e,o){if(!e&&!o){this.eventListeners={};return}let n;this.eventListeners[e]&&(n=this.eventListeners[e].indexOf(o),n>-1&&this.eventListeners[e].splice(n,1))}setConversationQuery(e){this.dynamicThunkObject.conversationQuery=e}whenConversationLoaded(e){let o=()=>this.loadProfileConfig().then(()=>e());this.hasConversation()&&o();let n=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==n&&(n=this.hasConversation(),n&&o())})}overlayContainerFactory(e,o,n,s){let[r,i]=jt(o,n);return r.setAttribute("translate","no"),r.dataset.testid=e,s&&r.classList.add(s),this.unmountHandlers.push(()=>{qr(r),i(),r.remove()}),r}createContainer(e,o=document.body){let n=window.getComputedStyle(o),s=document.createElement("div");return qe(s),s.dataset.testid=e,s.style.color=n.color,s.style.fontSize=n.fontSize,s.style.fontFamily=n.fontFamily,s.style.fontVariant=n.fontVariant,s.setAttribute("translate","no"),o.appendChild(s),this.unmountHandlers.push(()=>{qr(s),s.remove()}),s}mount(e,o={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!zr(e))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let{customStyles:n={},showStyleSuggestions:s,showTabCompletion:r,showTextSuggestions:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:c,showSuggestionsAfterPattern:p,isEmbedded:u,detectSubmit:d,insertLink:m,inputMediator:h,closestScrollSelector:g,appendOverlayTo:v,inlineSuggestions:E}=o;this.configure({showStyleSuggestions:s,showTabCompletion:r,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:c,showSuggestionsAfterPattern:p,showTextSuggestions:i,insertLink:m,isEmbedded:u,inlineSuggestions:E});let f=g&&Ip(e,g)||void 0,_=this.overlayContainerFactory("deepdesk-tab-completion",f||e,{appendTo:v,closestScrollElement:f,mirrorOverflow:!0,onRemove:()=>this.unmount()},n==null?void 0:n.rootNode),x=this.overlayContainerFactory("deepdesk-suggestions-overlay",f||e,{appendTo:v},n==null?void 0:n.suggestionsRootNode);o.automaticHandlingTime&&this.setupHandlingTime(e),Gn(ne(so,{store:this.store,customStyles:n,children:ne(Zt,{broadcastEvents:this.broadcastEvents,children:ne(xc,{inputElement:e})})}),_),Gn(ne(so,{store:this.store,customStyles:n,children:ne(Zt,{broadcastEvents:this.broadcastEvents,children:ne(En,{})})}),x),Gn(ne(so,{store:this.store,customStyles:n,children:ne(Zt,{broadcastEvents:this.broadcastEvents,children:ne(Bl,{})})}),this.createContainer("deepdesk-overlays")),qe(e),this.inputMediator=h||(we(e)?new Me(e):new Lt(e)),this.inputMediator.on("change",({plainText:T})=>{this.notifyInputChanged(T)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(Ai({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",T=>{this.notifyKeyDown(T)}),this.inputMediator.on("paste",({pastedText:T,selectionText:N})=>{this.notifyPaste(T,N)}),this.inputMediator.on("cut",({selectionText:T})=>{this.notifyCut(T)});let C;this.inputMediator.on("selection",T=>{clearTimeout(C),T===null?C=setTimeout(()=>{T!==null&&this.store.dispatch(bs(T))},500):this.store.dispatch(bs(T))}),this.inputMediator.on("disabled",()=>{var T;(T=this.inputMediator)==null||T.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{d&&this.notifySubmit()}),this.inputMediator.on("blur",()=>this.store.dispatch(St(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(St(!0))),this.store.dispatch(bi({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.whenConversationLoaded(()=>{var T;this.refresh(),this.broadcastEvents.setSessionId((T=this.state.conversation.current)==null?void 0:T.sessionId)}),this.isMounted=!0}unmount(){var e;this.unmountHandlers.forEach(o=>o()),this.unmountHandlers=[],(e=this.inputMediator)==null||e.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(e,o={}){if(this.widgetRoot&&k.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:n,showImages:s,showPersonalCollectionLink:r,isEmbedded:i}=o;this.widgetRoot=e,this.configure({showImages:s,showPersonalCollectionLink:r,isEmbedded:i}),Gn(ne(so,{store:this.store,customStyles:n,children:ne(Zt,{broadcastEvents:this.broadcastEvents,children:ne(dp,{})})}),e),this.whenConversationLoaded(()=>{var a;this.broadcastEvents.setSessionId((a=this.state.conversation.current)==null?void 0:a.sessionId)})}unmountWidget(){this.widgetRoot&&qr(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(e){let o=jr(e,({isVisible:n})=>{n?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),o()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){Ap(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(oo());let e=Tt(this.state);e&&this.store.dispatch(Ut({showSearch:e.search,showAutoflows:e.autoflows,showCustomMessages:e.customMessages,showImageSearch:e.imageSearch,showEntitiesCommand:e.entitiesCommand,showSummaryCommand:e.summarizer,showKnowledgeSearch:e.knowledgeAssistForAgents,recommendTextSuggestions:e.recommendTextSuggestions}))}),this.loadProfileConfigPromise)}async checkForTrialMode(e){try{let{account:o}=await this.deepdeskApi.getPlatformConfig();if(!o.isTrial){this.shouldRender=!0;return}if(k.info("Trial is active"),!await this.deepdeskApi.checkUserExists(e))throw new Error("User is not in trial");this.shouldRender=!0}catch(o){let{message:n}=o;k.info(n),this.shouldRender=!1}}async refreshWidgetSuggestions(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:e}=this.state.profile.data;if(!e.widget)return;let o=_n(this.state);try{o.forEach(({type:n})=>{n==="entities"?this.store.dispatch(ae()):this.store.dispatch(Se(n))})}catch(n){this.handleError(n)}}};async function Ly(t,e,o={}){let{value:n}=t,{start:s,end:r}=o.replace??{start:0,end:n.length},i=`${n.slice(0,s)}${e}${n.slice(r)}`,a=o.selectionAfter??{start:s+e.length,end:s+e.length},l=()=>{if(o.setValue)return o.setValue(i);t.value=i};return Promise.resolve(l()).then(()=>{t.selectionStart=a.start,t.selectionEnd=a.end,t.blur(),t.focus()})}async function My(t,e,o={}){let n=o.replace?Ze(t,o.replace.start,o.replace.end):fo(t),s,r=()=>{if(o.setRange)return o.setRange(n.cloneRange());n.deleteContents(),s=document.createElement("span"),n.insertNode(s),o.insertBRs!==!1?e.split(`
|
|
6
|
-
`).reverse().forEach((i,a)=>{a>0&&n.insertNode(document.createElement("br")),n.insertNode(document.createTextNode(i))}):n.insertNode(document.createTextNode(e))};return Promise.resolve(r()).then(()=>{try{if(o.selectionAfter!==!1){t.focus();let i=o.selectionAfter?
|
|
3
|
+
`,ze.MISSING_INTL_API,i);var _=o.getPluralRules(e,{type:p.pluralType}).select(d-(p.offset||0));y=p.options[_]||p.options.other}if(!y)throw new ds(p.value,d,Object.keys(p.options),i);a.push.apply(a,qt(y.value,e,o,n,s,d-(p.offset||0)));continue}}return Su(a)}function _u(t,e){return e?Z(Z(Z({},t||{}),e||{}),Object.keys(t).reduce(function(o,n){return o[n]=Z(Z({},t[n]),e[n]||{}),o},{})):t}function xu(t,e){return e?Object.keys(t).reduce(function(o,n){return o[n]=_u(t[n],e[n]),o},Z({},t)):t}function gs(t){return{create:function(){return{get:function(e){return t[e]},set:function(e,o){t[e]=o}}}}}function bu(t){return t===void 0&&(t={number:{},dateTime:{},pluralRules:{}}),{getNumberFormat:Bo(function(){for(var e,o=[],n=0;n<arguments.length;n++)o[n]=arguments[n];return new((e=Intl.NumberFormat).bind.apply(e,ko([void 0],o,!1)))},{cache:gs(t.number),strategy:Fo.variadic}),getDateTimeFormat:Bo(function(){for(var e,o=[],n=0;n<arguments.length;n++)o[n]=arguments[n];return new((e=Intl.DateTimeFormat).bind.apply(e,ko([void 0],o,!1)))},{cache:gs(t.dateTime),strategy:Fo.variadic}),getPluralRules:Bo(function(){for(var e,o=[],n=0;n<arguments.length;n++)o[n]=arguments[n];return new((e=Intl.PluralRules).bind.apply(e,ko([void 0],o,!1)))},{cache:gs(t.pluralRules),strategy:Fo.variadic})}}var ci=function(){function t(e,o,n,s){o===void 0&&(o=t.defaultLocale);var r=this;if(this.formatterCache={number:{},dateTime:{},pluralRules:{}},this.format=function(c){var p=r.formatToParts(c);if(p.length===1)return p[0].value;var u=p.reduce(function(d,m){return!d.length||m.type!==z.literal||typeof d[d.length-1]!="string"?d.push(m.value):d[d.length-1]+=m.value,d},[]);return u.length<=1?u[0]||"":u},this.formatToParts=function(c){return qt(r.ast,r.locales,r.formatters,r.formats,c,void 0,r.message)},this.resolvedOptions=function(){var c;return{locale:((c=r.resolvedLocale)===null||c===void 0?void 0:c.toString())||Intl.NumberFormat.supportedLocalesOf(r.locales)[0]}},this.getAst=function(){return r.ast},this.locales=o,this.resolvedLocale=t.resolveLocale(o),typeof e=="string"){if(this.message=e,!t.__parse)throw new TypeError("IntlMessageFormat.__parse must be set to process `message` of type `string`");var i=s||{},a=i.formatters,l=ti(i,["formatters"]);this.ast=t.__parse(e,Z(Z({},l),{locale:this.resolvedLocale}))}else this.ast=e;if(!Array.isArray(this.ast))throw new TypeError("A message must be provided as a String or AST.");this.formats=xu(t.formats,n),this.formatters=s&&s.formatters||bu(this.formatterCache)}return Object.defineProperty(t,"defaultLocale",{get:function(){return t.memoizedDefaultLocale||(t.memoizedDefaultLocale=new Intl.NumberFormat().resolvedOptions().locale),t.memoizedDefaultLocale},enumerable:!1,configurable:!0}),t.memoizedDefaultLocale=null,t.resolveLocale=function(e){if(!(typeof Intl.Locale>"u")){var o=Intl.NumberFormat.supportedLocalesOf(e);return o.length>0?new Intl.Locale(o[0]):new Intl.Locale(typeof e=="string"?e:e[0])}},t.__parse=si,t.formats={number:{integer:{maximumFractionDigits:0},currency:{style:"currency"},percent:{style:"percent"}},date:{short:{month:"numeric",day:"numeric",year:"2-digit"},medium:{month:"short",day:"numeric",year:"numeric"},long:{month:"long",day:"numeric",year:"numeric"},full:{weekday:"long",month:"long",day:"numeric",year:"numeric"}},time:{short:{hour:"numeric",minute:"numeric"},medium:{hour:"numeric",minute:"numeric",second:"numeric"},long:{hour:"numeric",minute:"numeric",second:"numeric",timeZoneName:"short"},full:{hour:"numeric",minute:"numeric",second:"numeric",timeZoneName:"short"}}},t}();function Tu(t,e){return e.split(".").reduce((o,n)=>o?o[n]:void 0,t)}var Eu="dummy",ms=Cu(null);function T(t){let e=wu(ms);if(!e)throw new Error("useTranslator() may be used only in the context of a <LocaleContext> component.");let o=t[e]??{};return(n,s)=>{let r=Tu(o,n);return r?new ci(r).format(s):(e!==Eu&&console.warn(`${n} does not exist in messages of ${e}`),`[${n}]`)}}var fs={};U(fs,{enUS:()=>ku,nlNL:()=>Ru});var ku={experimental:[{type:0,value:"Experimental"}]},Ru={experimental:[{type:0,value:"Experimenteel"}]};import{jsx as ui}from"react/jsx-runtime";var pi=({children:t})=>{let e=S("Chip",ei);return ui("span",{className:e.root,children:t})},Ko=()=>{let t=T(fs);return ui(pi,{children:t("experimental")})},Pu=pi;import Iu from"classnames";var di={root:"_root_cq1yq_1"};import{jsx as Mu}from"react/jsx-runtime";var Au={"arrow-up":"\u25B2","arrow-down":"\u25BC",tab:"tab",esc:"Esc",enter:"\u21B5"},Lu=({className:t,keyCode:e,...o})=>{let n=S("KeyboardHint",di);return Mu("span",{"data-key":Au[e],className:Iu(t,n.root),...o})},hs=Lu;import Ou from"classnames";var gi={root:"_root_4a08n_1"};import{jsx as Du}from"react/jsx-runtime";var Nu=({className:t,children:e,...o})=>{let n=S("Label",gi);return Du("span",{...o,className:Ou(t,n.root),children:e})},ys=Nu;var mi={root:"_root_jlggj_1",subTitleContainer:"_subTitleContainer_jlggj_5",subtitle:"_subtitle_jlggj_9",suggestions:"_suggestions_jlggj_17"};import{jsx as Ss,jsxs as Bu}from"react/jsx-runtime";var Hu=({title:t,children:e,type:o,...n})=>{let s=S("Section",mi);return Bu("section",{...n,className:s.root,"data-section-type":o,children:[t&&Ss("div",{className:s.subTitleContainer,children:Ss("span",{className:s.subtitle,children:t})}),Ss("div",{className:s.suggestions,children:e})]})},je=Hu;import Fu from"classnames";import Ku from"react";var fi={root:"_root_19wxp_1"};import{jsx as zu}from"react/jsx-runtime";var Uu=Ku.forwardRef(({className:t,children:e},o)=>{let n=S("SectionList",fi);return zu("div",{ref:o,className:Fu(n.root,t),children:e})}),vs=Uu;import Uo from"classnames";import ju,{createContext as qu,useCallback as Vu,useContext as Vt}from"react";var _s={root:"_root_fsa1k_10",fadein:"_fadein_fsa1k_1",isClickable:"_isClickable_fsa1k_45",isSelected:"_isSelected_fsa1k_50",actions:"_actions_fsa1k_74",actionsIsFixed:"_actionsIsFixed_fsa1k_96",actionButton:"_actionButton_fsa1k_104",dropdownList:"_dropdownList_fsa1k_125",dropdownButton:"_dropdownButton_fsa1k_140",dropdownItem:"_dropdownItem_fsa1k_150",dropdownItemButton:"_dropdownItemButton_fsa1k_159",actionButtonIsPrimary:"_actionButtonIsPrimary_fsa1k_173",actionButtonIsDisabled:"_actionButtonIsDisabled_fsa1k_177",labels:"_labels_fsa1k_185",label:"_label_fsa1k_185"};import{jsx as ye,jsxs as Qu}from"react/jsx-runtime";var rt=qu(_s),Wu=({fixed:t,children:e,...o})=>{let n=Vt(rt);return ye("div",{...o,className:Uo(n.actions,{[n.actionsIsFixed]:t}),children:e})},Gu=({className:t,primary:e,disabled:o,label:n,children:s})=>{let r=Vt(rt);return Qu("div",{className:Uo(t,r.actionButton,r.dropdownButton,{[r.actionButtonIsPrimary]:e,[r.actionButtonIsDisabled]:o}),onMouseDown:i=>i.stopPropagation(),onClick:i=>i.stopPropagation(),children:[n,ye("ul",{className:r.dropdownList,children:s})]})},$u=({index:t,label:e,onClick:o})=>{let n=Vt(rt);return ye("li",{className:n.dropdownItem,children:ye("button",{className:n.dropdownItemButton,type:"button","data-index":t,onClick:o,children:e})})},Xu=({className:t,primary:e,disabled:o,onClick:n,label:s})=>{let r=Vt(rt);return ye("button",{type:"button",className:Uo(t,r.actionButton,{[r.actionButtonIsPrimary]:e,[r.actionButtonIsDisabled]:o}),onClick:n??(i=>i.stopPropagation()),disabled:o,"aria-hidden":o,children:s})},xs=({labels:t})=>{let e=Vt(rt);return ye("div",{className:e.labels,children:t.map(o=>ye("span",{className:e.label,children:o},o))})},it=ju.forwardRef(({className:t,selected:e,onClick:o,children:n,as:s="div",...r},i)=>{let a=S("Suggestion",_s),l=Vu(c=>{c.preventDefault(),o&&o(c)},[o]);return ye(s,{...r,ref:i,className:Uo(t,a.root,{[a.isSelected]:e,[a.isClickable]:!!o}),onClick:l,children:ye(rt.Provider,{value:a,children:n})})});it.Labels=xs;it.Actions=Wu;it.ActionButton=Xu;it.DropdownButton=Gu;it.DropdownItem=$u;var M=it;import Zu from"classnames";var hi={root:"_root_fp74r_1",isWithDivider:"_isWithDivider_fp74r_9"};import{jsx as Yu}from"react/jsx-runtime";var Ju=({withDivider:t,children:e})=>{let o=S("SuggestionList",hi);return Yu("div",{"data-testid":"suggestions-overlay-list",className:Zu(o.root,{[o.isWithDivider]:t}),children:e})},re=Ju;import ed from"classnames";var yi={root:"_root_1wpmq_1",isCollapsed:"_isCollapsed_1wpmq_17"};import{jsx as bs}from"react/jsx-runtime";var td=({className:t,isCollapsed:e,title:o,onClick:n})=>{let s=S("ToggleButton",yi);return bs("button",{type:"button",className:ed(s.root,t,{[s.isCollapsed]:e}),onClick:n,title:o,children:bs("svg",{width:"14",height:"8",viewBox:"-2.5 -5 75 60",preserveAspectRatio:"none",children:bs("path",{d:"M0,0 l35,50 l35,-50",fill:"none",stroke:"grey",strokeLinecap:"round",strokeWidth:"6"})})})},at=td;var Si=/(?:[.,;:!?\\n]|:\\)|:\\(|:-\\)|:-\\()/g,lt=/(((\$!\{)|(\{))[a-zA-Z0-9_.]+\})/g;var vi=/x-deepdesk-(([a-z0-9\-_])+-version)/,pe=(g=>(g.SEARCH="search",g.TEMPLATE="template",g.ELASTIC_SEARCH="search-autocomplete",g.GPT="gpt",g.TRIE="trie",g.TRIE_WITH_TYPOS="trie-with-typos",g.SEMANTIC="semantic",g.TEXT_RECOMMENDATION="text_recommendation",g.URL_RECOMMENDATION="url_recommendation",g.LINK_RECOMMENDATION="link_recommendation",g.PERSONAL_COLLECTION="personal-collection",g.PERSONAL_COLLECTION_SEARCH="personal-collection-search",g.SEARCH_OVERLAY="search-overlay",g.SEARCH_PREVIEW="search-preview",g.SEARCH_URL="search-url",g))(pe||{}),qe=(s=>(s.TAB="tab",s.ARROW="arrow",s.HOTKEY="hotkey",s.MOUSE="mouse",s))(qe||{});import{render as xo,unmountComponentAtNode as Yn}from"react-dom";import{Fragment as Ym}from"react";import{createSlice as od}from"@reduxjs/toolkit";import{useSelector as nd}from"react-redux";var zo=(o=>(o.NL_NL="nl-NL",o.EN_US="en-US",o))(zo||{});var sd={locale:"en-US",deanonymize:!1,fallbackImage:!1,isEmbedded:!1,showAutoflows:!1,showCustomMessages:!1,showImages:!1,showPersonalCollectionLink:!1,showSearch:!1,showImageSearch:!1,showStyleSuggestions:!1,showMidSentenceSuggestions:!1,showSuggestionsBeforePattern:!1,showSuggestionsAfterPattern:!1,showTabCompletion:!0,showTextSuggestions:!0,showEntitiesCommand:!1,showSummaryCommand:!1,showKnowledgeSearch:!1,textSuggestionsCount:3,recommendTextSuggestions:!0,searchTriggerKey:"k",visible:!0,insertLink:!1,inlineSuggestions:!1,adminUrl:void 0,productName:"Deepdesk"},_i=od({name:"settings",initialState:sd,reducers:{set(t,e){Object.entries(e.payload).forEach(o=>{let[n,s]=o;typeof s>"u"||(t[n]=s)})}}}),{set:Wt}=_i.actions,Cs=t=>e=>e.settings[t],b=t=>nd(Cs(t)),xi=_i.reducer;import{useState as Kg}from"react";import{useDispatch as Ug,useSelector as sr}from"react-redux";import{createAction as Ve,createSlice as dd}from"@reduxjs/toolkit";import{diffChars as gd}from"diff";import{useSelector as md}from"react-redux";function bi(t){return typeof t=="object"&&!Array.isArray(t)&&t!==null}function Ie(t,e,o=10){let n=typeof t,s=typeof e;if(o===0)throw new Error("Max depth deepEqual, possible circular references?");return n!==s?!1:t==null||n==="string"||n==="number"||n==="boolean"?t===e:Array.isArray(t)&&Array.isArray(e)?t.length!==e.length?!1:t.every((r,i)=>Ie(r,e[i],o-1)):bi(t)&&bi(e)?Object.keys(t).length!==Object.keys(e).length?!1:Object.keys(t).every(i=>Ie(t[i],e[i],o-1)):!1}function rd(t){return Math.max(...t.map(e=>e.length))}function id(t,e){let o=t.reduce((n,s)=>{if(s){let r=n[s]?n[s]+1:1;return{...n,[s]:r}}return n},{});return Object.keys(o).reduce((n,s)=>(o[s]<e&&n.push(s),n),[])}function Ci(t,e){let n=[...t.map(({text:s})=>s.split(/\b(\w+)\b/))];for(let s=0;s<rd(n);s++){let r=id(n.map(a=>a[s]),e),i=n.filter(a=>!r.includes(a[s]));if(i.length>=e)n=i;else return{text:n[0].slice(0,s).join("").replace(/ (\?| |!|\.|,|\n)/g,"$1").trimEnd(),source:"mixed"}}}var ad=2;function ws(t,e=""){if(t.length===0)return;if(t.length===1)return t[0];let o=Ci(t,ad);return o&&o.text!==e?o:t[0]}import{createAction as ld,createAsyncThunk as ct,createSlice as cd}from"@reduxjs/toolkit";var wi={current:null,isSupported:null},R=ld("resetConversation"),jo=t=>{let{current:e}=t.conversation;return(e==null?void 0:e.sessionId)||null},qo=t=>{let{current:e}=t.conversation;return(e==null?void 0:e.id)||null},pt=t=>t.conversation.isSupported,Ts=ct("conversation/isSupported",(t,e)=>{let{deepdeskAPI:o}=e.extra;return o.isConversationSupported(t.sessionId,t.options)}),Vo=ct("conversation/create",(t,e)=>{let{deepdeskAPI:o}=e.extra;return o.createConversation(t)}),Wo=ct("conversation/bySessionId",(t,e)=>{let{deepdeskAPI:o}=e.extra;return o.getConversationBySessionId(t.sessionId,t.options)}),Go=ct("conversation/update",(t,e)=>{let{deepdeskAPI:o}=e.extra,n=qo(e.getState());if(!n)throw new Error("No current conversation to update");return o.updateConversation(n,t)}),Es=ct("conversation/upsert",(t,e)=>{let{deepdeskAPI:o}=e.extra;return o.getConversationBySessionId(t.sessionId).catch(()=>null).then(n=>{if(!n)return o.createConversation(t);let{agentId:s,agentName:r,agentEmail:i,agentNickname:a,tags:l}=t;return o.updateConversation(n.id,{agentId:s,agentEmail:i,agentName:r,agentNickname:a,tags:l})})}),$o=ct("conversation/postMessages",(t,e)=>{let{deepdeskAPI:o}=e.extra,n=qo(e.getState());if(!n)throw new Error("No current conversation to update messages");return o.postMessages(n,t.map(s=>({...s})))}),pd=[Vo.rejected,Wo.rejected,Go.rejected,$o.rejected].map(t=>t==null?void 0:t.toString()),ud=cd({name:"conversation",initialState:wi,reducers:{},extraReducers:t=>{t.addCase(Ts.fulfilled,(e,o)=>{e.isSupported=o.payload}).addCase(Vo.fulfilled,(e,o)=>{var n;e.current=o.payload,e.isSupported=((n=o.payload)==null?void 0:n.hasActiveProfile)??null}).addCase(Wo.fulfilled,(e,o)=>{var n;e.current=o.payload,e.isSupported=((n=o.payload)==null?void 0:n.hasActiveProfile)??null}).addCase(Es.fulfilled,(e,o)=>{var n;e.current=o.payload,e.isSupported=((n=o.payload)==null?void 0:n.hasActiveProfile)??null}).addCase(Go.fulfilled,(e,o)=>{var n;e.current=o.payload,e.isSupported=((n=o.payload)==null?void 0:n.hasActiveProfile)??null}).addCase($o.fulfilled,(e,o)=>{e.current&&(e.current.messages=o.payload)}).addCase(R,()=>wi).addMatcher(e=>pd.includes(e.type),(e,o)=>{throw new Error(o.error.message)})}}),Ti=ud.reducer;var Ae={text:"",html:null,selection:{start:0,end:0},stagedSuggestion:null,userCommitted:{text:"",selection:{start:0,end:0}},tabCompletionSuggestion:void 0,previousKeyDownEvent:null,textSuggestions:[],selectedSuggestionIndex:-1,metrics:{numCharsTyped:0,numCharsPasted:0,numCharsCut:0,numCharsDeleted:0,numPaste:0,agentStartedTypingTimestamp:null,externalTimeTotalSeconds:null,pastes:[],deletions:[],offeredTextSuggestions:[],textSuggestions:[],cuts:[]}};function Qo(t){let{key:e,shiftKey:o,ctrlKey:n,metaKey:s,altKey:r}=t;return{key:e,shiftKey:o,ctrlKey:n,metaKey:s,altKey:r}}var Zo=Ve("input/replaceText"),Jo=Ve("input/keyDown"),We=Ve("input/sendMessage"),Yo=Ve("input/sendEditSuggestionMessage"),en=Ve("input/uiInputChange"),tn=Ve("input/applyImageSuggestion"),J=Ve("input/sendEvent");function Xo(t){if(!t.stagedSuggestion)return;let{text:e,suggestion:{source:o,abVariant:n,abTestName:s,trainingJobs:r,sourceText:i,searchTerm:a,text:l},eventMetrics:{inputType:c},replace:p}=t.stagedSuggestion,u=o==="search"||o==="personal-collection-search",d=e.slice(t.userCommitted.text.substring(0,t.userCommitted.selection.start).length);(u||p==="selection")&&(d=e),t.stagedSuggestion.suggestion.source==="search-overlay"&&(d=l),t.userCommitted.text=t.text,t.userCommitted.selection=t.selection,t.metrics.textSuggestions.push({text:d,source:o,abVariant:n,abTestName:s,inputType:c,sourceText:i,trainingJobs:r||[],searchTerm:u?t.userCommitted.text:a}),t.stagedSuggestion=null,t.textSuggestions=[],t.selectedSuggestionIndex=-1}var Ei=t=>dd({name:t,initialState:Ae,reducers:{initialInput(e,o){let{text:n,selection:s,html:r}=o.payload;e.text=n,e.selection.start=(s==null?void 0:s.start)??n.length,e.selection.end=(s==null?void 0:s.end)??n.length,e.userCommitted.text=n,e.userCommitted.selection.start=(s==null?void 0:s.start)??n.length,e.userCommitted.selection.end=(s==null?void 0:s.end)??n.length,e.html=r||null},reset(e){Object.assign(e,{...Ae,selection:e.selection})},resetToCommitted(e){e.text=e.userCommitted.text,e.selection=e.userCommitted.selection,e.stagedSuggestion=null,e.tabCompletionSuggestion=ws(e.textSuggestions,e.userCommitted.text)},changeSelection(e,o){o.payload&&(Ie(e.selection,o.payload)||(e.selection=o.payload,e.userCommitted.selection=e.selection,e.stagedSuggestion&&Xo(e)))},platformInput(e,o){let{text:n,html:s,selection:r}=o.payload;r&&(e.selection.start=r.start,e.selection.end=r.end),e.text=n,e.html=s||null},userInput(e,o){var i,a,l,c;if(e.previousKeyDownEvent){let{key:p,shiftKey:u,ctrlKey:d,metaKey:m,altKey:f}=e.previousKeyDownEvent;switch(p){case"Enter":u&&(e.metrics.numCharsTyped+=1);break;case"Backspace":case"Delete":{let{text:g}=e,{text:x}=o.payload,w=gd(g,x);g.length-x.length>1&&e.metrics.deletions.push(...w.filter(h=>h.removed).map(h=>h.value)),e.metrics.numCharsDeleted+=g.length-x.length;break}case"C":case"V":case"X":if(!d&&!m){e.metrics.numCharsTyped+=1;let g=((i=e.selection)==null?void 0:i.start)!==void 0&&((a=e.selection)==null?void 0:a.end)!==void 0?e.text.substring(e.selection.start,e.selection.end):null;g&&g.length>0&&(e.metrics.numCharsDeleted+=g.length,e.metrics.deletions.push(g))}break;case"Shift":break;default:if(!d&&!m&&!f){e.metrics.numCharsTyped+=1;let g=((l=e.selection)==null?void 0:l.start)!==void 0&&((c=e.selection)==null?void 0:c.end)!==void 0?e.text.substring(e.selection.start,e.selection.end):null;g&&g.length>0&&(e.metrics.numCharsDeleted+=g.length,e.metrics.deletions.push(g))}}}!e.metrics.agentStartedTypingTimestamp&&o.payload.text!==e.text&&(e.metrics.agentStartedTypingTimestamp=Date.now()),o.payload.text===""&&(e.metrics=Ae.metrics,e.textSuggestions=[],e.stagedSuggestion=null),e.text!==o.payload.text&&Xo(e);let{text:n,html:s,selection:r}=o.payload;r&&(e.selection.start=r.start,e.selection.end=r.end,e.userCommitted.selection.start=r.start,e.userCommitted.selection.end=r.end),e.text=n,e.html=s||null,e.userCommitted.text=n,e.previousKeyDownEvent=null},stageSuggestion(e,o){let{text:n}=o.payload;switch(e.stagedSuggestion=o.payload,e.tabCompletionSuggestion=void 0,o.payload.replace){case"selection":e.text=`${e.text.slice(0,e.selection.start)}${n}${e.text.slice(e.selection.end)}`,e.selection.end=e.selection.start+n.length,e.selection.start+=n.length;break;case"until-selection-end":e.text=`${n}${e.text.slice(e.selection.end)}`,e.selection.start=n.length,e.selection.end=n.length;break;default:throw new Error(`Unknown replace ${o.payload.replace}`)}o.payload.eventMetrics.inputType==="tab"&&Xo(e)},commitSuggestion(e){Xo(e)},offeredTextSuggestion(e,o){let{text:n,suggestion:{source:s}}=o.payload;e.metrics.offeredTextSuggestions.find(i=>i.text===n)||e.metrics.offeredTextSuggestions.push({text:n,source:s})},registerCut(e,o){let{metrics:n}=e,s=o.payload;e.metrics={...e.metrics,numCharsCut:n.numCharsCut+s.length,cuts:[...n.cuts,s]}},registerPaste(e,o){let{metrics:n}=e,{text:s,selectionText:r}=o.payload,i=n.numCharsDeleted+(r&&r.length?r.length:0),a=r&&r.length?[...n.deletions,r]:n.deletions;e.metrics={...e.metrics,numCharsDeleted:i,deletions:a,numCharsPasted:n.numCharsPasted+s.length,numPaste:n.numPaste+1,pastes:[...n.pastes,s]}},registerKeyDown(e,o){e.previousKeyDownEvent=o.payload},nextTextSuggestionIndex(e){let o=e.textSuggestions.length;e.selectedSuggestionIndex=e.selectedSuggestionIndex<o-1?e.selectedSuggestionIndex+1:e.selectedSuggestionIndex},previousTextSuggestionIndex(e){e.selectedSuggestionIndex=e.selectedSuggestionIndex>=0?e.selectedSuggestionIndex-1:e.selectedSuggestionIndex},setTextSuggestions(e,o){if(e.selectedSuggestionIndex=-1,e.textSuggestions=o.payload,o.payload.length===0)return;let n=e.userCommitted.text.substring(0,e.userCommitted.selection.end),s=ws(o.payload,n);e.tabCompletionSuggestion=s!=null&&s.text.includes(n)?s:void 0},setSelectedTextSuggestionIndex(e,o){e.selectedSuggestionIndex=o.payload},mergeMetrics(e,{payload:o}){let n=o.agentStartedTypingTimestamp!=null?o.agentStartedTypingTimestamp:Date.now(),s=(Date.now()-n)/1e3;e.metrics.externalTimeTotalSeconds=s,e.metrics.numCharsTyped+=o.numCharsTyped,e.metrics.numCharsPasted+=o.numCharsPasted,e.metrics.numCharsCut+=o.numCharsCut,e.metrics.numCharsDeleted+=o.numCharsDeleted,e.metrics.numPaste+=o.numPaste,e.metrics.pastes.push(...o.pastes),e.metrics.deletions.push(...o.deletions)}},extraReducers:e=>{e.addCase(R,o=>{o.tabCompletionSuggestion=Ae.tabCompletionSuggestion,o.previousKeyDownEvent=Ae.previousKeyDownEvent,o.textSuggestions=Ae.textSuggestions,o.selectedSuggestionIndex=Ae.selectedSuggestionIndex,o.metrics=Ae.metrics})}}),ks=Ei("input"),ut=t=>t.input.userCommitted.text.substring(0,t.input.userCommitted.selection.end),fd=t=>t.input.selection,ki=()=>md(fd),{userInput:Ri,changeSelection:Rs,initialInput:Pi,mergeMetrics:Ii,nextTextSuggestionIndex:Ai,offeredTextSuggestion:Li,previousTextSuggestionIndex:Mi,registerCut:Oi,registerKeyDown:Ni,registerPaste:Di,reset:Hi,resetToCommitted:Gt,platformInput:Bi,setSelectedTextSuggestionIndex:$t,setTextSuggestions:Se,stageSuggestion:ie,commitSuggestion:Le}=ks.actions,W=Ei("overlay");import{useEffect as Ki,useRef as Ui}from"react";var Fi={root:"_root_1qp5s_1",content:"_content_1qp5s_23"};import{jsx as zi}from"react/jsx-runtime";var hd=({isOpen:t,autoFocus:e,children:o,onClose:n,onBack:s,overlayAriaLabel:r,contentAriaLabel:i})=>{let a=Ui(null),l=Ui(null),c=S("Dialog",Fi);return Ki(()=>{var d,m;let p=f=>{f.key==="Escape"&&(f.preventDefault(),f.stopPropagation(),s())},u=f=>{let g=window.getSelection();g!=null&&g.toString()||f.target===a.current&&t&&n()};return(d=a.current)==null||d.addEventListener("click",u),(m=a.current)==null||m.addEventListener("keyup",p),()=>{var f,g;(f=a.current)==null||f.removeEventListener("click",u),(g=a.current)==null||g.removeEventListener("keyup",p)}},[a,l,s,n]),Ki(()=>{var p,u;!a.current||!t||!e||(u=(p=a.current)==null?void 0:p.querySelector("input, textarea"))==null||u.focus()},[t,e,a]),t?zi("div",{role:"dialog","data-testid":"dialog",className:c.root,"aria-label":r,ref:a,children:zi("div",{ref:l,"data-testid":"dialog-content",className:c.content,"aria-label":i,children:o})}):null},dt=hd;import{useEffect as Aa}from"react";import{useDispatch as xg,useSelector as bg}from"react-redux";var Ps={};U(Ps,{enUS:()=>yd,nlNL:()=>Sd});var yd={dismiss:[{type:0,value:"Close"}],add:[{type:0,value:"Add to message"}],next:[{type:0,value:"Next"}],previous:[{type:0,value:"Previous"}],warning:[{type:0,value:"Are you sure you want to discard the message?"}]},Sd={dismiss:[{type:0,value:"Sluiten"}],add:[{type:0,value:"Toevoegen"}],next:[{type:0,value:"Volgende"}],previous:[{type:0,value:"Vorige"}],warning:[{type:0,value:"Weet je zeker dat je de wijzigingen wilt weggooien?"}]};var ji={root:"_root_l80t9_1",content:"_content_l80t9_3",title:"_title_l80t9_7",actions:"_actions_l80t9_15",pagination:"_pagination_l80t9_20",primaryButton:"_primaryButton_l80t9_51",primaryButtons:"_primaryButtons_l80t9_55"};import{jsx as qi,jsxs as vd}from"react/jsx-runtime";var on=()=>vd("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 256 512","aria-labelledby":"angleLeftTitle",children:[qi("title",{id:"angleLeftTitle",children:"AngleLeft"}),qi("path",{d:"M192 448c-8.188 0-16.38-3.125-22.62-9.375l-160-160c-12.5-12.5-12.5-32.75 0-45.25l160-160c12.5-12.5 32.75-12.5 45.25 0s12.5 32.75 0 45.25L77.25 256l137.4 137.4c12.5 12.5 12.5 32.75 0 45.25C208.4 444.9 200.2 448 192 448z"})]});import{jsx as Vi,jsxs as _d}from"react/jsx-runtime";var Wi=()=>_d("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 256 512","aria-labelledby":"angleRightTitle",children:[Vi("title",{id:"angleRightTitle",children:"AngleRight"}),Vi("path",{d:"M64 448c-8.188 0-16.38-3.125-22.62-9.375c-12.5-12.5-12.5-32.75 0-45.25L178.8 256L41.38 118.6c-12.5-12.5-12.5-32.75 0-45.25s32.75-12.5 45.25 0l160 160c12.5 12.5 12.5 32.75 0 45.25l-160 160C80.38 444.9 72.19 448 64 448z"})]});import{useEffect as Xt,useRef as Bs,useState as Bd}from"react";import{useDispatch as Fd}from"react-redux";import{Interweave as Kd}from"interweave";import ca from"classnames";var Is={root:"_root_kxnai_1",agentText:"_agentText_kxnai_3",textInput:"_textInput_kxnai_8",textInputWrapper:"_textInputWrapper_kxnai_27",alert:"_alert_kxnai_31",alertText:"_alertText_kxnai_50",warning:"_warning_kxnai_60",success:"_success_kxnai_69"};import{Matcher as wd}from"interweave";import Td from"classnames";import{useEffect as xd,useRef as bd,useState as Cd}from"react";function Gi(t,e){let o;return[(...n)=>{window.cancelAnimationFrame(o);let s=e?e(...n):n;o=window.requestAnimationFrame(()=>{t(...s)})},()=>window.cancelAnimationFrame(o)]}function nn(t){let e=bd(null),[o,n]=Cd(!1);return xd(()=>{let s=!1,r=parseFloat(window.getComputedStyle(document.body).zoom??"1"),[i,a]=Gi((p,u)=>{let d=e.current;if(!d)return;let m=p/r,f=u/r,g=d.getBoundingClientRect(),x=m>g.x&&m<g.x+g.width&&f>g.y&&f<g.y+g.height;x&&!s?(s=!0,n(!0)):!x&&s&&(s=!1,n(!1))},({clientX:p,clientY:u})=>[p,u]),[l,c]=Gi(()=>{s=!1,n(!1)});return t.addEventListener("mousemove",i),t.addEventListener("mouseleave",l),()=>{a(),c(),t.removeEventListener("mousemove",i),t.removeEventListener("mouseleave",l)}},[e]),[e,o]}var ee={root:"_root_81non_1",container:"_container_81non_3",agentText:"_agentText_81non_5",tabText:"_tabText_81non_6",hint:"_hint_81non_6",matchSelection:"_matchSelection_81non_10",focus:"_focus_81non_16",resetIndent:"_resetIndent_81non_20",matchKeyword:"_matchKeyword_81non_24",matchPlaceholder:"_matchPlaceholder_81non_25",hover:"_hover_81non_31",hintText:"_hintText_81non_64",popover:"_popover_81non_72",popoverRoot:"_popoverRoot_81non_77",popoverContentContainer:"_popoverContentContainer_81non_81",popoverContent:"_popoverContent_81non_81",selectionOptions:"_selectionOptions_81non_107",selectionOptionsIsHidden:"_selectionOptionsIsHidden_81non_112",selectionOptionsButton:"_selectionOptionsButton_81non_116",caret:"_caret_81non_132",popoverSuggestionsRoot:"_popoverSuggestionsRoot_81non_136",suggestionsOverlayInputStyles:"_suggestionsOverlayInputStyles_81non_141"};import{jsx as $i}from"react/jsx-runtime";var Ed=({inputElement:t,children:e})=>{let o=S("TabCompletion",ee),[n,s]=nn(t);return $i("mark",{ref:n,className:Td(o.matchPlaceholder,{[o.hover]:s}),children:e})},gt=class extends wd{match(e){let o=e.match(/(((\$!\{)|(\{))[a-zA-Z0-9_.]+\}(?!\}))/);return o?{index:o.index,length:o[0].length,match:o[0],matchString:o[0],valid:!0}:null}replaceWith(e,o){return $i(Ed,{inputElement:o.inputElement,children:e},`placeholder_${o.matchString}_${o.key}`)}asTag(){return"mark"}};import{useEffect as kd,useRef as Rd,useState as Pd}from"react";function sn(t){return t.contentEditable==="true"}function Id(t){let e=0,o=0,n=window.getSelection();if(n.rangeCount!==0){let s=n.getRangeAt(0),r=s.cloneRange();r.selectNodeContents(t),r.setEnd(s.endContainer,s.endOffset),o=r.toString().length,r.selectNodeContents(t),r.setEnd(s.startContainer,s.startOffset),e=r.toString().length}return{selectionStart:e,selectionEnd:o}}function Xi(t){let{selectionStart:e,selectionEnd:o}=sn(t)?Id(t):t;return[e,o]}function rn(t){let[,e]=Pd(),o=Rd(null);return o.current=Xi(t),kd(()=>{let n=()=>{let[s,r]=o.current??[],i=Xi(t);(!i||s!==i[0]||r!==i[1])&&(o.current=i,e({}))};return t.addEventListener("keyup",n),t.addEventListener("click",n),t.addEventListener("focus",n),document.addEventListener("selectionchange",n),()=>{t.removeEventListener("keyup",n),t.removeEventListener("click",n),t.removeEventListener("focus",n),document.removeEventListener("selectionchange",n)}},[t]),o.current}function an(t,e){if(!e)return;let o=t,{value:n}=o,[s,r]=e,i=n.match(lt);if(!i||i.length===0)return;let a=0;i.find(l=>{let c=n.indexOf(l,a);return s>c&&r<c+l.length?(o.selectionStart=c,o.selectionEnd=c+l.length,!0):(a=c+l.length,!1)})}import{useEffect as Ad}from"react";function Me(t){Ad(()=>{let e=o=>{o.isWithinRoot||t(o)};return document.body.addEventListener("mouseup",e),()=>{document.body.removeEventListener("mouseup",e)}},[t])}function Ge(t){t.addEventListener("mouseup",e=>{e.isWithinRoot=!0},!0)}var Qi,ue=new Map,Ld=["bottom","height","left","right","top","width"],Md=(t={},e={})=>Ld.some(o=>t[o]!==e[o]);function Zi(t){var o,n;let e=((n=(o=t.ownerDocument)==null?void 0:o.defaultView)==null?void 0:n.frameElement)??null;return e?[e,...Zi(e)]:[]}function Ji(t,e){return!t||!e?null:{...t,top:t.top+e.top,left:t.left+e.left}}var As=!1,Yi=()=>{As=!0;let t=[];ue.forEach((e,o)=>{if(!o.isConnected){e.rect=null,t.push(e),ue.delete(o);return}let n=o.getBoundingClientRect();Md(n,e.rect)&&(e.rect=n,t.push(e))}),t.forEach(e=>{let o=e.parentRects?e.parentRects.reduce(Ji,e.rect):e.rect;e.callbacks.forEach(n=>n(o))}),ue.size!==0&&(Qi=window.requestAnimationFrame(Yi))};function Ls(t,e){let o=Zi(t),n=[],s=o.map((r,i)=>Ls(r,a=>{n[i]=a;let l=ue.get(t);if(!l)return;let c=n.reduce(Ji,l.rect);l.callbacks.forEach(p=>p(c))}));return{observe(r=!0){if(s.forEach(i=>i.observe(!1)),ue.has(t)){let i=ue.get(t);i.callbacks.push(e),i.rect&&e(i.rect)}else ue.set(t,{rect:void 0,callbacks:[e],parentRects:n});r&&!As&&Yi()},unobserve(){s.forEach(i=>i.unobserve());let r=ue.get(t);if(r){let i=r.callbacks.indexOf(e);i>=0&&r.callbacks.splice(i,1),r.callbacks.length||ue.delete(t),ue.size||(cancelAnimationFrame(Qi),As=!1)}}}}var ea,de=new Map,ta=()=>{de.forEach((t,e)=>{if(!e.isConnected){de.delete(e);return}let{clientHeight:o,scrollHeight:n}=e,s=n>o;t.visible!==s&&(t.visible=s,t.callbacks.forEach(r=>r(t.visible)))}),de.size!==0&&(ea=window.requestAnimationFrame(ta))};function oa(t,e){return{observe(){let o=de.size===0;de.has(t)?de.get(t).callbacks.push(e):de.set(t,{visible:void 0,callbacks:[e]}),o&&ta()},unobserve(){let o=de.get(t);if(o){let n=o.callbacks.indexOf(e);n>=0&&o.callbacks.splice(n,1),o.callbacks.length||de.delete(t),de.size||cancelAnimationFrame(ea)}}}}var Ms=["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 Os(t,e,o){return o.forEach(n=>{e.style[n]=t[n]})}function mt(t){return parseFloat(t)}function ln(t){return Math.round(t*1e6)}function na(t){return t/1e6}function Ns(t,e,o){if(t.boxSizing==="content-box")return;let{clientWidth:n}=e,s=mt(t.width),r=mt(t.borderLeftWidth),i=mt(t.borderRightWidth),a=mt(t.paddingRight),l=na(ln(s)-ln(r)-ln(i)),c=na(ln(n));if(l-c>2){let p=l-c;o.style.paddingRight=`${a+p}px`}}function ft(t,e={}){var l;let o=e.overlayContainer||document.createElement("div");o.style.display="none",o.style.position=e.position??"fixed",o.style.pointerEvents="none",o.style.borderColor="transparent",Ge(o);let n=window.getComputedStyle(t),s=!0,r=()=>{o.scrollTop=t.scrollTop};Os(n,o,Ms),Ns(n,t,o),e.mirrorOverflow&&(o.style.overflow="hidden",t.addEventListener("scroll",r));let i=oa(t,()=>{Os(n,o,Ms),Ns(n,t,o),r(),setTimeout(r,0)}),a=Ls(t,c=>{if(c===null){e.onRemove&&e.onRemove(),o.remove();return}if(c.height===0&&c.width===0){if(s===!0)return;e.onHide&&e.onHide(),o.style.display="none",s=!0;return}if(Os(n,o,Ms),Ns(n,t,o),r(),o.style.top=`${c.top}px`,o.style.left=`${c.left}px`,e.closestScrollElement&&e.closestScrollElement!==t){let p=e.closestScrollElement.getBoundingClientRect(),u=window.getComputedStyle(e.closestScrollElement),d=mt(u.borderTopWidth),m=mt(u.borderBottomWidth),f=p.top+d-c.top,g=c.top+c.height+-(p.top+p.height-m);o.style.clipPath=`inset(${f}px 0px ${g}px 0px)`}s&&(o.style.display="block",e.onShow&&e.onShow(),s=!1)});return e.appendTo?e.appendTo.appendChild(o):(l=t.parentElement)==null||l.appendChild(o),a.observe(),i.observe(),[o,()=>{t.removeEventListener("scroll",r),a.unobserve(),i.unobserve()}]}var Ds={};U(Ds,{enUS:()=>Od,nlNL:()=>Nd});var Od={placeholders:[{type:6,value:"placeholderSize",options:{"=0":{value:[{type:0,value:"No placeholders found"}]},one:{value:[{type:0,value:"There is one placeholder in your message"}]},other:{value:[{type:0,value:"There are "},{type:7},{type:0,value:" placeholders in your message"}]}},offset:0,pluralType:"cardinal"}]},Nd={placeholders:[{type:6,value:"placeholderSize",options:{"=0":{value:[{type:0,value:"Alle placeholders zijn uit je bericht"}]},one:{value:[{type:0,value:"Er is 1 placeholder in jouw bericht"}]},other:{value:[{type:0,value:"Er zijn "},{type:7},{type:0,value:" placeholders in jouw bericht"}]}},offset:0,pluralType:"cardinal"}]};import{jsx as sa,jsxs as Dd}from"react/jsx-runtime";var ra=()=>Dd("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 512 512","aria-labelledby":"circleCheckTitle",children:[sa("title",{id:"circleCheckTitle",children:"Check"}),sa("path",{d:"M243.8 339.8C232.9 350.7 215.1 350.7 204.2 339.8L140.2 275.8C129.3 264.9 129.3 247.1 140.2 236.2C151.1 225.3 168.9 225.3 179.8 236.2L224 280.4L332.2 172.2C343.1 161.3 360.9 161.3 371.8 172.2C382.7 183.1 382.7 200.9 371.8 211.8L243.8 339.8zM512 256C512 397.4 397.4 512 256 512C114.6 512 0 397.4 0 256C0 114.6 114.6 0 256 0C397.4 0 512 114.6 512 256zM256 48C141.1 48 48 141.1 48 256C48 370.9 141.1 464 256 464C370.9 464 464 370.9 464 256C464 141.1 370.9 48 256 48z"})]});import{jsx as ia}from"react/jsx-runtime";var aa=()=>ia("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",fill:"currentColor",children:ia("path",{d:"M256 32c14.2 0 27.3 7.5 34.5 19.8l216 368c7.3 12.4 7.3 27.7 .2 40.1S486.3 480 472 480H40c-14.3 0-27.6-7.7-34.7-20.1s-7-27.8 .2-40.1l216-368C228.7 39.5 241.8 32 256 32zm0 128c-13.3 0-24 10.7-24 24V296c0 13.3 10.7 24 24 24s24-10.7 24-24V184c0-13.3-10.7-24-24-24zm32 224c0-17.7-14.3-32-32-32s-32 14.3-32 32s14.3 32 32 32s32-14.3 32-32z"})});function Hd(t){let e=t.scrollHeight>t.clientHeight,n=window.getComputedStyle(t).overflowY.indexOf("hidden")!==-1;return e&&!n}function cn(t){return t?t instanceof ShadowRoot?cn(t.host):t===t.ownerDocument.body?t.ownerDocument:Hd(t)?t:cn(t.parentNode):document.body}var la=(i=>(i.CUT="Cut",i.BACKSPACE="Backspace",i.DELETE="Delete",i.ERASEEOF="EraseEof",i.UNDO="Undo",i.CLEAR="Clear",i))(la||{}),Oe=class{constructor(e){this.element=e;this.currentText=this.getText(),this.currentHTML=this.getHTML(),this.listen()}eventListeners={};disposeHandlers=[];currentText="";currentCaret=null;currentSelection={start:0,end:0};currentHTML="";isFocused=!1;isActive=!0;isSettingValue=!1;isSubmitting=!1;isPossibleClearInputAction=!1;isDisposed=!1;addEventListener(e,o){let n=s=>{o(s)};this.element.addEventListener(e,n),this.disposeHandlers.push(()=>{this.element.removeEventListener(e,n)})}removeEventListener(e,o){this.element.removeEventListener(e,o)}triggerChange(){let e=this.getText(),o=this.getHTML(),n=e!==this.currentText;this.isActive&&(e===""&&this.currentText!==""&&!this.isSettingValue&&!this.isPossibleClearInputAction&&(this.isSubmitting=!0,this.emit("submit")),!this.isSettingValue&&n&&!this.isSubmitting&&this.emit("change",{plainText:e}),n&&(this.currentSelection=this.getSelection()),this.currentText=e,this.isSubmitting=!1,(this.currentHTML!==o||o===null&&n)&&(this.emit("updated",{plainText:e}),this.triggerCaretPosition(),this.currentHTML=o))}triggerSelection(){let e=this.getSelection();(e.start!==this.currentSelection.start||e.end!==this.currentSelection.end)&&(this.currentSelection=e,this.emit("selection",e),this.triggerCaretPosition())}triggerCaretPosition(){let e=this.getCaretPosition();Ie(e,this.currentCaret)||(this.currentCaret=e,this.emit("caret",e))}handleKeyUp(e){let{key:o,shiftKey:n}=e;(o==="Enter"&&n===!0||o==="Backspace")&&this.triggerChange(),this.triggerSelection()}handleClick(){this.triggerSelection()}handleFocus(){this.isFocused||this.emit("focus"),this.triggerSelection(),this.isFocused=!0}handleBlur(){this.isPossibleClearInputAction=!1,this.isFocused&&this.emit("blur"),this.isFocused=!1}handleKeyDown(e){let{key:o,ctrlKey:n,metaKey:s}=e;this.isPossibleClearInputAction=Object.values(la).includes(o)||o.toLowerCase()==="z"&&(n||s),this.emit("keydown",e)}handleCut(){this.isPossibleClearInputAction=!0,this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(e){var n,s;let o=((n=e.clipboardData)==null?void 0:n.getData("text"))||((s=e.clipboardData)==null?void 0:s.getData("text/plain"))||"";this.emit("paste",{pastedText:o,selectionText:this.getSelectedText()})}listen(){this.addEventListener("keydown",n=>this.handleKeyDown(n)),this.addEventListener("keyup",n=>this.handleKeyUp(n)),this.addEventListener("input",()=>this.triggerChange()),this.addEventListener("change",()=>this.triggerChange()),this.addEventListener("focus",()=>this.handleFocus()),this.addEventListener("blur",()=>this.handleBlur()),this.addEventListener("cut",()=>this.handleCut()),this.addEventListener("paste",n=>this.handlePaste(n)),this.addEventListener("click",()=>this.triggerSelection()),document.activeElement===this.element&&setTimeout(()=>{this.handleFocus()},0);let e=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});e.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{e.disconnect()});let o=cn(this.element);if(o){let n=()=>{this.currentCaret!==null&&(this.currentCaret=null,this.emit("caret",null))};o.addEventListener("scroll",n),this.disposeHandlers.push(()=>{o.removeEventListener("scroll",n)})}}focus(){this.element.focus()}emit(e,...o){this.isDisposed||this.eventListeners[e]&&this.eventListeners[e].forEach(n=>{n(...o)})}on(e,o){this.isDisposed||(this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(o))}activate(){let e=this.isActive===!1;this.isActive=!0,e&&this.triggerChange()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(e=>e()),this.eventListeners={},this.isDisposed=!0}};var Ne=class extends Oe{lastKnownSelection=null;getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:e,selectionEnd:o}=this.element;return{start:e,end:o}}getSelectedText(){let e=this.getSelection();return e?this.getText().slice(e.start,e.end):""}getCaretPosition(){return null}applyChanges(e){if(!this.isActive)return;this.isSettingValue=!0;let o=this.getText(),n=e(this.element);return Promise.resolve(n).then(()=>{this.currentText=this.getText(),o!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(){super.listen();let e=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var s;return(s=e==null?void 0:e.get)==null?void 0:s.call(this.element)},set:s=>{var r;(r=e==null?void 0:e.set)==null||r.call(this.element,s),this.triggerChange()}});let o=this.element.disabled,n=new MutationObserver(()=>{this.element.disabled!==o&&(o=this.element.disabled,this.emit(o?"disabled":"enabled"))});n.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>n.disconnect())}};import{jsx as ve,jsxs as Hs}from"react/jsx-runtime";var Ud=({value:t,onUse:e,...o})=>{var p;let n=T(Ds),s=Fd(),r=S("EditSuggestionTextInput",Is),[i,a]=Bd(null),l=Bs(null),c=((p=t.match(lt))==null?void 0:p.length)||0;return Xt(()=>{let u;return l.current&&(a(l.current),u=new Ne(l.current),u.on("change",({plainText:d})=>{s(W.actions.userInput({text:d,selection:u.getSelection()}))}),u.on("keydown",d=>{s(W.actions.registerKeyDown(Qo(d))),d.code==="Enter"&&d.shiftKey&&e(u.getText())}),u.on("paste",({pastedText:d,selectionText:m})=>{s(W.actions.registerPaste({text:d,selectionText:m}))}),u.on("cut",({selectionText:d})=>{s(W.actions.registerCut(d))})),()=>{s(W.actions.reset()),u.dispose(),u.deactivate()}},[l]),Xt(()=>{t&&l.current&&(l.current.value=t)},[t,l]),Xt(()=>{l.current&&setTimeout(()=>{if(!l.current)return;let u=l.current.value.length;l.current.setSelectionRange(u,u),l.current.focus()},0)},[l]),Hs("div",{className:r.textInputWrapper,children:[ve("textarea",{...o,ref:l,"data-testid":"edit-suggestion-dialog-textarea",className:r.textInput,defaultValue:t,onChange:()=>{}}),i&&ve(zd,{inputElement:l.current,value:t}),Hs("div",{className:ca(r.alert,c===0?r.success:r.warning),children:[ve("div",{className:r.alertText,children:n("placeholders",{placeholderSize:c})}),c===0?ve(ra,{}):ve(aa,{})]})]})},zd=({inputElement:t,value:e})=>{let o=S("EditSuggestionTextInput",Is),n=Bs(null),s=rn(t);return Xt(()=>{an(t,s)},[s,t]),ve(jd,{inputElement:t,children:Hs("div",{ref:n,className:ca(o.root,o.agentText),children:[ve(Kd,{tagName:"span",disableLineBreaks:!0,content:e,matchers:[new gt("placeholders")],inputElement:t,boundaryRef:n}),ve("br",{})]})})},jd=({inputElement:t,children:e})=>{let o=Bs(null);return Xt(()=>{if(!o.current)return()=>{};let[n,s]=ft(t,{overlayContainer:o.current,mirrorOverflow:!0});return n.setAttribute("translate","no"),()=>{s()}},[o.current]),ve("div",{ref:o,children:e})},pa=Ud;import{useEffect as yg,useState as Sg,useRef as vg}from"react";import{useState as Wd}from"react";import Fs from"classnames";var G={root:"_root_185k9_1",list:"_list_185k9_2",listWrapper:"_listWrapper_185k9_6",listHorizontal:"_listHorizontal_185k9_10",page:"_page_185k9_19",search:"_search_185k9_25",pageNav:"_pageNav_185k9_33",pageTitle:"_pageTitle_185k9_41",pageBackButton:"_pageBackButton_185k9_48",listHeading:"_listHeading_185k9_62",listItem:"_listItem_185k9_70",listItemContent:"_listItemContent_185k9_79",listItemText:"_listItemText_185k9_97",listItemDescription:"_listItemDescription_185k9_105",truncate:"_truncate_185k9_112",lineClamp:"_lineClamp_185k9_118",listItemTitle:"_listItemTitle_185k9_125",listItemAction:"_listItemAction_185k9_132",listItemPrimaryAction:"_listItemPrimaryAction_185k9_146",listItemSelected:"_listItemSelected_185k9_151",sources:"_sources_185k9_155",sourcesTitle:"_sourcesTitle_185k9_162",source:"_source_185k9_155",icon:"_icon_185k9_177",searchIcon:"_searchIcon_185k9_194",searchInputWrapper:"_searchInputWrapper_185k9_199",searchInput:"_searchInput_185k9_199",select:"_select_185k9_220",selectType:"_selectType_185k9_237",selectWrapper:"_selectWrapper_185k9_241",image:"_image_185k9_271",imageSrc:"_imageSrc_185k9_278",imageSrcHidden:"_imageSrcHidden_185k9_289",imageSrcStatus:"_imageSrcStatus_185k9_293",imageTitle:"_imageTitle_185k9_303",actions:"_actions_185k9_308",actionsWrapper:"_actionsWrapper_185k9_312",actionsBar:"_actionsBar_185k9_318",actionButton:"_actionButton_185k9_327",actionShortcut:"_actionShortcut_185k9_345",actionShortcutFixKerning:"_actionShortcutFixKerning_185k9_352"};var $e={};U($e,{enUS:()=>qd,nlNL:()=>Vd});var qd={visitUrl:[{type:0,value:"Visit"}],back:[{type:0,value:"Back"}],loading:[{type:0,value:"Loading..."}],imageError:[{type:0,value:"Could not load image"}]},Vd={visitUrl:[{type:0,value:"Bekijk"}],back:[{type:0,value:"Terug"}],loading:[{type:0,value:"Laden..."}],imageError:[{type:0,value:"Kan afbeelding niet laden"}]};import{jsx as Qt,jsxs as $d}from"react/jsx-runtime";var Gd=({src:t,title:e})=>{let o=S("CommandPalette",G),[n,s]=Wd("loading"),r=T($e);return $d("div",{className:o.image,children:[Qt("img",{src:t,alt:e,onLoad:()=>s("done"),onError:()=>s("error"),className:Fs(o.imageSrc,{[o.imageSrcHidden]:["loading","error"].includes(n)})}),n==="loading"&&Qt("span",{className:Fs(o.imageSrc,o.imageSrcStatus),children:r("loading")}),n==="error"&&Qt("span",{className:Fs(o.imageSrc,o.imageSrcStatus),children:Qt(wo,{})}),e&&Qt("span",{className:o.imageTitle,children:e})]})},ua=Gd;import Xd from"react";import Qd from"classnames";import{jsx as da,jsxs as Zd}from"react/jsx-runtime";function Ks({children:t,heading:e,orientation:o}){let n=S("CommandPalette",G);return Xd.Children.count(t)===0?null:Zd("div",{"data-testid":"commandpalette-list",className:n.list,children:[e&&da("h4",{className:n.listHeading,children:e}),da("div",{className:Qd(n.listWrapper,o==="horizontal"&&n.listHorizontal),children:t})]})}import pn from"classnames";import Us from"react";import{jsx as Jd}from"react/jsx-runtime";var ga=Us.createContext(void 0);function De(){let t=Us.useContext(ga);if(t===void 0)throw new Error("useCommandPalette must be used within the CommandPalette component");return t}var ma=({children:t,page:e,isOpen:o,onChangeOpen:n,selected:s,setSelected:r})=>{let i=Us.useMemo(()=>({page:e,isOpen:o,onChangeOpen:n,selected:s,setSelected:r}),[o,e,s]);return Jd(ga.Provider,{value:i,children:t})};import{jsx as ht,jsxs as un}from"react/jsx-runtime";function zs({closeOnSelect:t=!0,lineClamp:e,children:o,onClick:n,onSourceClick:s,index:r,isExperimental:i,description:a,sources:l,styles:c,...p}){let{selected:u,onChangeOpen:d}=De(),m=S("CommandPalette",G);function f(g){n(g),t&&d(!1)}return un("div",{className:pn(m.listItem,u===r&&m.listItemSelected),children:[un("button",{type:"button",className:pn("command-palette-list-item",m.listItemAction,m.listItemPrimaryAction),"aria-disabled":p.disabled??!1,onClick:f,...p,children:[un("div",{className:m.listItemContent,children:[typeof o=="string"?ht("p",{className:pn(m.listItemText,m.truncate,c==null?void 0:c.title),children:o}):o,a&&ht("p",{className:pn(m.listItemDescription,c==null?void 0:c.description,e?m.lineClamp:m.truncate),children:a})]}),i&&ht(Ko,{})]}),l&&un("div",{className:m.sources,children:[ht("span",{className:m.sourcesTitle,children:"Sources"}),l.map(g=>g.url?ht("a",{className:m.source,href:g.url,target:"_blank",title:g.url,rel:"noopener noreferrer",onClick:()=>s&&s(g),children:g.name},g.url):ht("span",{className:m.source,children:g.name},g.name))]})]})}import{jsx as js,jsxs as qs}from"react/jsx-runtime";function Vs({children:t,title:e,id:o,onDismiss:n,isExperimental:s}){let r=T($e),i=S("CommandPalette",G),{page:a}=De();return a!==o?null:qs("div",{className:i.page,id:`page_${o}`,tabIndex:-1,children:[n&&qs("div",{className:i.pageNav,children:[qs("button",{className:i.pageBackButton,type:"button",onClick:n,children:[js(on,{}),r("back")]}),e&&js("h3",{className:i.pageTitle,children:e}),s&&js(Ko,{})]}),t]})}import{Fragment as cg,useCallback as pg,useEffect as ug,useRef as dg}from"react";var dn=()=>/Mac/i.test(navigator.platform);import{createAsyncThunk as ng,createSlice as sg}from"@reduxjs/toolkit";var Yd={info(...t){console.info("[Deepdesk]",...t)},warn(...t){console.warn("[Deepdesk]",...t)},error(...t){console.error("[Deepdesk]",...t)}},E=Yd;import{createAsyncThunk as Gs,createSlice as tg}from"@reduxjs/toolkit";function eg(t){return t.replace(/(_\w)/g,e=>e[1].toUpperCase())}function A(t){return Array.isArray(t)?t.map(A):typeof t=="object"&&t!==null?Object.keys(t).reduce((e,o)=>({...e,[eg(o)]:A(t[o])}),{}):t}function Ws(t){return t.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}function B(t){return Array.isArray(t)?t.map(B):typeof t=="object"&&t!==null?Object.keys(t).reduce((e,o)=>({...e,[Ws(o)]:B(t[o])}),{}):t}var og={agentInfo:void 0,agentSettings:{},visitorInfo:void 0,fetchState:"idle"},Jt=t=>{var e,o,n;return{timezone:((e=t.info.visitorInfo)==null?void 0:e.visitorTimeZone)||Intl.DateTimeFormat().resolvedOptions().timeZone,agentName:((o=t.info.agentInfo)==null?void 0:o.agentNickname)||"",visitorName:((n=t.info.visitorInfo)==null?void 0:n.visitorName)||""}},Zt=Gs("info/setAgentInfo",async(t,e)=>{let{deepdeskAPI:o}=e.extra;if(!t.agentId&&!t.agentNickname)throw new Error("At least provide agentId or agentNickname");let n=await o.client.get("/apis/admin/session/me/",{version:null}),s={};return n.external_id||(s.external_id=t.agentId),n.nickname||(s.nickname=t.agentNickname),!s.external_id&&!s.nickname?A(n):(await o.client.patch("/apis/admin/session/me/",s,{version:null}),A(n))}),$s=Gs("info/setAgentSettings",async(t,e)=>{let{deepdeskAPI:o}=e.extra,n=await o.client.get("/apis/admin/session/me/",{version:null}),s={...typeof n.ui_config=="object"?n.ui_config:{},...t};return await o.client.patch("/apis/admin/session/me/",{ui_config:s}),s}),Xs=Gs("info/getAgentSettings",async(t,e)=>{let{deepdeskAPI:o}=e.extra;return(await o.client.get("/apis/admin/session/me/",{version:null})).ui_config}),fa=t=>t.info.agentInfo,ha=tg({name:"info",initialState:og,reducers:{setVisitorInfo(t,e){t.visitorInfo={...t.visitorInfo,...e.payload}}},extraReducers:t=>{t.addCase(Zt.pending,(e,o)=>{e.fetchState="loading",e.agentInfo={...e.agentInfo,...o.meta.arg}}).addCase(Zt.rejected,e=>{e.fetchState="error"}).addCase(Zt.fulfilled,(e,o)=>{e.fetchState="done",e.agentInfo={...e.agentInfo,...o.meta.arg,agentId:o.payload.externalId||o.meta.arg.agentId||"",agentNickname:o.payload.nickname||o.meta.arg.agentNickname||""}}).addCase($s.fulfilled,(e,o)=>{e.agentSettings=o.payload}).addCase(Xs.fulfilled,(e,o)=>{e.agentSettings=o.payload}).addCase(R,e=>{e.visitorInfo=void 0})}}),{setVisitorInfo:ya}=ha.actions,Sa=ha.reducer;var gn={list:[],fetchState:"idle",isOpen:!1,page:"search"},va=t=>t.search.isOpen,_a=t=>t.search.page,xa=t=>t.search.list;function ba(t,e=o=>o){return o=>o.search.list.filter(n=>n.type===t).map(e)}var Xe=ng("search/getAll",async(t,e)=>{var i;let{deepdeskAPI:o}=e.extra,n=e.getState(),s=(i=n.conversation.current)==null?void 0:i.profileCode;if(!s)throw new Error("Profile should be provided in order to be able to search");let{results:r}=await o.search({profile:s,query:t.query,filters:{type:t.type},params:Jt(n),tags:t.tags});return r.map(a=>({...a,source:`search-${a.type.toLowerCase()}`,searchTerm:t.query}))}),Ca=sg({name:"search",initialState:gn,reducers:{setIsOpen(t,e){t.isOpen=e.payload},setPage(t,e){t.page=e.payload},resetSearch(t){t.fetchState=gn.fetchState,t.list=gn.list}},extraReducers:t=>{t.addCase(Xe.pending,e=>{e.fetchState="loading"}).addCase(Xe.rejected,(e,o)=>{e.fetchState="error",E.error(o.error)}).addCase(Xe.fulfilled,(e,o)=>{e.fetchState="done",e.list=o.payload}).addCase(R,()=>gn)}}),{resetSearch:mn,setIsOpen:Y,setPage:j}=Ca.actions,wa=Ca.reducer;var rg=/(https?:\/\/[^\s]+)/,fn=t=>t.split(" ").find(e=>rg.test(e));import Ta from"classnames";import{jsx as ag,jsxs as lg}from"react/jsx-runtime";var ig=({onClick:t,shortKeys:e,children:o,...n})=>{let s=S("CommandPalette",G);return lg("button",{type:"button",...n,onClick:t,className:Ta(s.actionButton,n.className),children:[o,e&&e.map(r=>ag("span",{className:Ta(s.actionShortcut,r===8629&&s.actionShortcutFixKerning),children:typeof r=="number"?String.fromCharCode(r):r},r))]})},yt=ig;import{jsx as hn,jsxs as Qs}from"react/jsx-runtime";var gg=({children:t,primaryLabel:e,secondaryLabel:o,onPrimary:n,onSecondary:s,list:r})=>{let i=S("CommandPalette",G),a=T($e),{selected:l,setSelected:c}=De(),p=r[l],u=p&&typeof p.text=="string"&&fn(p.text),d=dg(null);function m(y){if(!d.current)return;let _=d.current.querySelectorAll(".command-palette-list-item"),C=0,H=0;y==="down"?(_.forEach((ce,N)=>{N===l&&(C=N)}),H=C===_.length-1?0:C+1):y==="up"?(_.forEach((ce,N)=>{N===l&&(C=N)}),H=C?C-1:_.length-1):c(0);let O=_[H];O&&typeof H=="number"&&(c(H),O.scrollIntoView&&O.scrollIntoView({behavior:"smooth",block:H?"center":"end"}))}function f(){if(!d.current)return;let y=d.current.querySelectorAll(".command-palette-list-item"),_=0;y.forEach((H,O)=>{O===l&&(_=O)});let C=y[_];C&&C.click()}let g=()=>{u&&window.open(u,"_blank")},x=()=>{p&&n(p,l)},w=()=>{!p.type||["IMAGE","command"].includes(p.type)||s&&s(p,l)},h=pg(y=>{if(y.key==="Enter"&&y.altKey&&u){g();return}if(y.key==="Enter"&&y.shiftKey){w();return}if(y.key==="ArrowDown"){y.preventDefault(),y.stopPropagation(),m("down");return}if(y.key==="ArrowUp"){y.preventDefault(),y.stopPropagation(),m("up");return}y.key==="Enter"&&l!==-1&&(y.preventDefault(),y.stopPropagation(),f())},[l]);return ug(()=>(window.addEventListener("keyup",h),()=>{window.removeEventListener("keyup",h)}),[h]),Qs("div",{className:i.actions,children:[hn("div",{className:i.actionsWrapper,ref:d,children:t}),Qs("div",{className:i.actionsBar,children:[u&&hn(yt,{onClick:g,shortKeys:[dn()?8997:"ALT",8629],children:a("visitUrl")}),p&&Qs(cg,{children:[s&&p.type&&!["command","image"].includes(p.type.toLowerCase())&&hn(yt,{onClick:w,shortKeys:[8679,8629],children:o}),hn(yt,{onClick:x,shortKeys:[8629],children:e})]})]})]})},ka=gg;import{forwardRef as fg}from"react";import{jsx as Ra,jsxs as mg}from"react/jsx-runtime";var St=()=>mg("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 0 24 24",width:"1em",fill:"currentColor",children:[Ra("path",{d:"M0 0h24v24H0z",fill:"none"}),Ra("path",{d:"M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"})]});import{jsx as vt,jsxs as Zs}from"react/jsx-runtime";function hg({onChange:t,onChangeType:e,placeholder:o,typePlaceholder:n,types:s,value:r,selectedType:i},a){let l=S("CommandPalette",G);return Zs("div",{className:l.search,children:[vt("div",{className:l.searchIcon,children:vt(St,{})}),Zs("div",{className:l.searchInputWrapper,children:[vt("input",{ref:a,spellCheck:!1,autoComplete:"off",onChange:c=>{t(c.currentTarget.value)},onFocus:c=>{c.currentTarget.select()},className:l.searchInput,placeholder:o,value:r,type:"text",id:"command-palette-search-input",autoFocus:!0}),s&&s.length>0&&vt("div",{className:l.selectWrapper,children:Zs("select",{"data-testid":"command-palette-type-select",className:l.select,onChange:c=>e(c.target.value===n?void 0:c.target.value),value:i||n,children:[n&&vt("option",{children:n}),s.map(c=>vt("option",{value:c.value,children:c.label},c.value))]})})]})]})}var Pa=fg(hg);import{jsx as Ia,jsxs as _g}from"react/jsx-runtime";function Qe({placeholder:t="Start typing to search...",typePlaceholder:e="All types",defaultPage:o="search",page:n,onChangePage:s,onChangeSearch:r,onChangeType:i,onChangeOpen:a,selectedType:l,types:c,children:p,isOpen:u,search:d}){let[m,f]=Sg(0),g=vg(null),x=()=>{s&&s(o),i(void 0),r(""),a(!1)},w=()=>{var h;if(n!==o&&s){s(o);return}if(l&&i){i(void 0),(h=g.current)==null||h.focus();return}if(d.length>0){r("");return}a(!1)};return yg(()=>{f(0)},[d,n]),Ia(dt,{autoFocus:!0,contentAriaLabel:"Search Results",overlayAriaLabel:"Command Palette",isOpen:u,onBack:w,onClose:x,children:_g(ma,{selected:m,setSelected:f,isOpen:u,onChangeOpen:a,page:n,children:[n===o&&Ia(Pa,{ref:g,onChange:r,onChangeType:i,placeholder:t,value:d,selectedType:l,types:c,typePlaceholder:e}),p]})})}Qe.Page=Vs;Qe.List=Ks;Qe.Image=ua;Qe.ListItem=zs;Qe.ActionsBar=ka;Qe.Button=yt;var P=Qe;import{jsx as _e,jsxs as Yt}from"react/jsx-runtime";var Cg=({suggestion:t,onUse:e,onDismiss:o,onTouched:n,onNext:s,onPrevious:r})=>{let i=t.text||t.url||t.message,a=S("EditSuggestionForm",ji),l=xg(),c=T(Ps),p=bg(f=>f.overlayInput.text);Aa(()=>{t&&(l(W.actions.reset()),l(W.actions.stageSuggestion({text:i,suggestion:t,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"})),l(W.actions.commitSuggestion()))},[t]);let u=f=>{f.preventDefault(),d(p)},d=f=>{l(Yo(f)),e(f)},m=f=>g=>{p!==i?window.confirm(c("warning"))&&f(g):f(g)};return Aa(()=>{n&&n(p!==i)},[n,t,p]),Yt("div",{className:a.root,children:[Yt("div",{className:a.content,children:[t.title&&_e("h3",{className:a.title,children:t.title}),t.searchKeywords&&t.searchKeywords.length>0&&_e(xs,{labels:t.searchKeywords}),_e(pa,{onUse:d,value:p})]}),Yt("form",{className:a.actions,onSubmit:u,children:[Yt("div",{children:[_e("button",{disabled:!r,className:a.pagination,type:"button",onClick:r&&m(r),children:_e(on,{})}),_e("button",{disabled:!s,className:a.pagination,type:"button",onClick:s&&m(s),children:_e(Wi,{})})]}),Yt("div",{className:a.primaryButtons,children:[_e(P.Button,{onClick:m(o),shortKeys:["esc"],children:c("dismiss")}),_e(P.Button,{shortKeys:[8679,8629],type:"submit",children:c("add")})]})]})]})},yn=Cg;import{createAction as Eg,createAsyncThunk as Na,createSlice as kg}from"@reduxjs/toolkit";var wg=["{amount}"," {amount}","{date}","{email}","{iban}","{name}","{postal_code}","{street}","{tarif}","{usage}","{3_digits}","{4_digits}","{5_digits}","{6_digits}","{7_digits}","{8_digits}","{9_digits}","{10_digits}"],Tg=new RegExp(wg.map(t=>`(?:${t.replace("{","\\{").replace("}","\\}")})`).join("|"));function La(t,e){let o=t.split(Tg),n=0,s=[];for(let r=0;r<o.length;r++){let i=o[r];if(s.push(i),r===o.length-1)break;if(e.indexOf(i)===-1)return t;let a=o[r+1],l=r===o.length-2;n+=i.length;let c=n;if(l){let u=a.charAt(0),d=0;do c=u?e.indexOf(u,c+1):-1,d+=1;while(c!==-1&&a.indexOf(e.slice(c))!==0);if(c===-1&&d>2)return t}else c=a&&a!==""?e.indexOf(a,n):-1;let p=c===-1?e.slice(n):e.slice(n,c);s.push(p),n=c}return s.join("")}function Ma(t,e){return typeof e=="boolean"?t:t.slice(0,e)}var Da={suggestions:[],fetchState:"idle",isInitialRequest:null},Oa={default:Da},Ha=t=>e=>{var o;return((o=e.textSuggestions[t])==null?void 0:o.suggestions)||[]},Ba=t=>e=>{var o;return((o=e.textSuggestions[t])==null?void 0:o.suggestions)??[]},Fa=t=>{let e=Object.keys(t.textSuggestions).map(o=>{var n;return(n=t.textSuggestions[o])==null?void 0:n.fetchState});return e.length===0?!0:e.every(o=>o!=="done")},_t=t=>t.textSuggestions,Ka=t=>e=>e.text.startsWith(t),Sn=Eg("textSuggestions/refresh"),xe=Na("textSuggestions/recommendations",async(t,e)=>{var c;let{deepdeskAPI:o}=e.extra,n=e.getState(),s=(c=n.conversation.current)==null?void 0:c.id,{textSuggestionsCount:r,inlineSuggestions:i}=n.settings,a=ut(n);if(!s)throw new Error("No current conversation to fetch text suggestions");let l=await o.getTextSuggestions(s,Jt(n),t);if(t==="default"){let p=i?l.filter(Ka(a)):l;e.dispatch(Se(p.slice(0,r)))}return l}),eo=Na("textSuggestions/autocompletions",async(t,e)=>{var c;let{deepdeskAPI:o}=e.extra,n=e.getState(),s=(c=n.conversation.current)==null?void 0:c.id,{textSuggestionsCount:r,deanonymize:i,inlineSuggestions:a}=n.settings;if(!s)throw new Error("No current conversation to fetch text suggestions");let l=await o.getAutocompleteSuggestions(s,{...Jt(n),input:t});if(!e.getState().input.text)throw new Error("Abort");return a&&(l=l.filter(Ka(t))),i&&(l=l.map(p=>({...p,text:p.source!=="trie-with-typos"?La(p.text,t):p.text}))),l=Ma(l,r),e.dispatch(Se(l)),l}),Ua=kg({name:"textSuggestions",initialState:Oa,reducers:{setTextSuggestions:{reducer(t,e){let{contentType:o}=e.payload;t[o].fetchState="done",t[o].suggestions=e.payload.suggestions},prepare(t,e){return{payload:{contentType:t,suggestions:e}}}},setSuggestionState(t,e){return e.payload}},extraReducers:t=>{t.addCase(xe.pending,(e,o)=>{let n=o.meta.arg,s=e[n]||Da;return{...e,[n]:{...s,fetchState:"loading",isInitialRequest:s.isInitialRequest===null}}}).addCase(xe.rejected,(e,o)=>{let n=o.meta.arg;e[n]&&(e[n].fetchState="error")}).addCase(xe.fulfilled,(e,o)=>{let n=o.meta.arg;e[n]&&(e[n].fetchState="done",e[n].suggestions=o.payload)}).addCase(eo.pending,e=>{e.default.fetchState="loading"}).addCase(eo.rejected,e=>{e.default.fetchState="error"}).addCase(eo.fulfilled,(e,o)=>{e.default.fetchState="done",e.default.suggestions=o.payload}).addCase(R,()=>Oa)}}),{setTextSuggestions:za,setSuggestionState:ja}=Ua.actions,qa=Ua.reducer;import{createSlice as Rg}from"@reduxjs/toolkit";var Va={contentType:null,suggestion:null},Wa=t=>t.activeSuggestion.suggestion,Ga=t=>t.activeSuggestion.contentType,$a=Rg({name:"activeSuggestion",initialState:Va,reducers:{setActiveSuggestion(t,e){let{contentType:o,suggestion:n}=e.payload;t.contentType=o,t.suggestion=n},resetActiveSuggestion(t){t.contentType=null,t.suggestion=null}},extraReducers:t=>{t.addCase(R,()=>Va)}}),{setActiveSuggestion:be,resetActiveSuggestion:Js}=$a.actions,Xa=$a.reducer;var Ys={};U(Ys,{enUS:()=>Pg,nlNL:()=>Ig});var Pg={warning:[{type:0,value:"Are you sure you want to discard the message?"}],editContentLabel:[{type:0,value:"Edit and view suggestion"}],overlayLabel:[{type:0,value:"Close dialog"}]},Ig={warning:[{type:0,value:"Weet je zeker dat je de wijzigingen wilt weggooien?"}],editContentLabel:[{type:0,value:"Bewerk en bekijk suggestie"}],overlayLabel:[{type:0,value:"Sluit"}]};import{createSlice as Ag}from"@reduxjs/toolkit";var Lg={showTabHint:!1,inputHasFocus:!1,overlayCollapsed:!1,openOverlayWhenTyping:!1,overlayCollapsedUserOverwrite:!1};var vn=({ui:t})=>t.overlayCollapsed;var Qa=Ag({name:"ui",initialState:Lg,reducers:{setShowTabHint(t,e){t.showTabHint=e.payload},setInputHasFocus(t,e){t.overlayCollapsedUserOverwrite!==!0&&(e.payload===!0&&(t.overlayCollapsed=!1),t.inputHasFocus=e.payload)},setOverlayCollapsed(t,e){e.payload.collapse===!1&&(t.openOverlayWhenTyping=!1),!(e.payload.skipWhenInputFocus&&t.inputHasFocus)&&(t.overlayCollapsed=e.payload.collapse)},setOpenOverlayWhenTyping(t,e){t.openOverlayWhenTyping=e.payload},setOverlayCollapsedUserOverwrite(t,e){t.overlayCollapsedUserOverwrite=e.payload,t.overlayCollapsed=e.payload}}}),{setShowTabHint:to,setInputHasFocus:xt,setOverlayCollapsed:He,setOpenOverlayWhenTyping:Za,setOverlayCollapsedUserOverwrite:Ja}=Qa.actions,Ya=Qa.reducer;import el,{useContext as Mg}from"react";import{jsx as Og}from"react/jsx-runtime";var tl=el.createContext(null),bt=({broadcastEvents:t,children:e})=>{let o=el.useMemo(()=>t,[]);return Og(tl.Provider,{value:o,children:e})},te=()=>{let t=Mg(tl);if(!t)throw new Error("You should use the useBroadcastEvents within a BroadcastEventsProvider");return t};import{createAsyncThunk as er,createSlice as Ng}from"@reduxjs/toolkit";var Dg={isLoggedIn:!0,loginFetchState:"idle",verifyFetchState:"idle",showLoginOverlay:!1},ae=t=>t.auth.isLoggedIn,ol=t=>t.auth.loginFetchState,nl=t=>t.auth.verifyFetchState,sl=t=>t.auth.showLoginOverlay,Be=er("auth/validate",async(t,e)=>e.extra.deepdeskAPI.isLoggedIn()),rl=er("auth/requestLogin",async({email:t},e)=>{let{deepdeskAPI:o}=e.extra;return o.requestLoginByEmail(t)}),oo=er("auth/verifyLoginToken",async({token:t},e)=>{let{deepdeskAPI:o}=e.extra;return o.verifyLoginToken(t)}),il=Ng({name:"auth",initialState:Dg,reducers:{setIsLoggedIn(t,e){t.isLoggedIn=e.payload},setShowLoginOverlay(t,e){t.showLoginOverlay=e.payload}},extraReducers:t=>{t.addCase(Be.pending,e=>{e.loginFetchState="loading"}),t.addCase(Be.fulfilled,(e,{payload:o})=>{e.isLoggedIn=o,e.loginFetchState="done"}),t.addCase(Be.rejected,e=>{e.loginFetchState="error",e.isLoggedIn=!1}),t.addCase(oo.pending,e=>{e.verifyFetchState="loading"}),t.addCase(oo.rejected,e=>{e.verifyFetchState="error"}),t.addCase(oo.fulfilled,(e,o)=>{o.payload.isLoggedIn?e.verifyFetchState="done":e.verifyFetchState="error"})}}),{setIsLoggedIn:Ct,setShowLoginOverlay:al}=il.actions,ll=il.reducer;var tr="SetActiveSuggestion",wt="ShowLoginOverlay",or="UserLoggedIn",Hg="UserLoggedOut",Ce="ApplySuggestion",nr="ApplyImageSuggestion",Bg="ShowCommandPalette",Fg=t=>({[tr]:e=>{t.dispatch(ja(e.state)),t.dispatch(be({contentType:e.contentType,suggestion:e.suggestion}))},[Bg]:e=>{t.dispatch(Y(e.isOpen)),e.page&&t.dispatch(j(e.page))},[wt]:e=>{t.dispatch(al(e))},[or]:()=>{t.dispatch(Be())},[Hg]:()=>{t.dispatch(Be())},[nr]:e=>{t.dispatch(tn({suggestion:e.suggestion}))},[Ce]:e=>{t.dispatch(ie({...e,eventMetrics:{inputType:"mouse"},replace:"selection"})),t.dispatch(Le())}}),cl=Fg;import{jsx as pl}from"react/jsx-runtime";var zg=()=>{var f;let[t,e]=Kg(!1),o=sr(Wa),n=sr(Ga),s=sr(_t),r=Ug(),i=te(),a=T(Ys),l=()=>{o!==null&&t?window.confirm(a("warning"))&&c():c()},c=()=>{r(Js()),r(xt(!0)),r(W.actions.reset())},p=(g,x)=>{r(Js()),r(xt(!0)),i.send(Ce,{text:g,suggestion:{...x,source:`${x.source||"text_recommendation"}-preview`}})};if(o===null||n===null)return null;let u=(f=s[n])==null?void 0:f.suggestions.indexOf(o),d=u===0||u===null?void 0:()=>r(be({contentType:n,suggestion:s[n].suggestions[u-1]})),m=u===s[n].suggestions.length-1||u===null?void 0:()=>r(be({contentType:n,suggestion:s[n].suggestions[u+1]}));return pl(dt,{autoFocus:!0,isOpen:u!==null,onClose:l,onBack:l,contentAriaLabel:a("editContentLabel"),overlayAriaLabel:a("overlayLabel"),children:pl(yn,{onTouched:e,onDismiss:c,onUse:g=>p(g,o),suggestion:o,onNext:m,onPrevious:d})})},ul=zg;import{useSelector as hl}from"react-redux";import ir from"classnames";import{useCallback as ml,useEffect as $g,useMemo as Xg,useState as ar}from"react";import{useDispatch as Qg,useSelector as Zg}from"react-redux";import jg from"classnames";var dl={root:"_root_1ukx5_1"};import{jsx as Vg}from"react/jsx-runtime";var qg=({className:t,value:e,...o})=>{let n=S("TextInput",dl);return Vg("input",{className:jg(t,n.root),type:"text",value:e,...o})},no=qg;var rr={};U(rr,{enUS:()=>Wg,nlNL:()=>Gg});var Wg={back:[{type:0,value:"Back"}],promptTitle:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],verifyCodeTitle:[{type:0,value:"Paste the code from your email"}],verifyCodeBody:[{type:0,value:"Copy the code from the email you just received and paste it here."}],verifyCodeInputPlaceholder:[{type:0,value:"Paste link or code here"}],verifyCodeSubmitLabel:[{type:0,value:"Sign in"}],verifyCodeError:[{type:0,value:"Sign in failed. The code is probably no longer valid. Please "},{type:8,value:"login",children:[{type:0,value:"request new code"}]},{type:0,value:"."}],requestCodeTitle:[{type:0,value:"Have a code sent to your email"}],requestCodeBody:[{type:0,value:"Enter your email and request a code. If you are an existing "},{type:1,value:"productName"},{type:0,value:" user you will receive an email with a code. If you are a new user you will receive an email asking to request access to "},{type:1,value:"productName"},{type:0,value:" first."}],requestCodeInputPlaceholder:[{type:0,value:"Enter your email"}],requestCodeSubmitLabel:[{type:0,value:"Request code"}]},Gg={back:[{type:0,value:"Terug"}],promptTitle:[{type:0,value:"Login bij "},{type:1,value:"productName"}],verifyCodeTitle:[{type:0,value:"Plak de code uit je email"}],verifyCodeBody:[{type:0,value:"Kopieer de code uit de email en plak deze hier."}],verifyCodeInputPlaceholder:[{type:0,value:"Plak hier de code"}],verifyCodeSubmitLabel:[{type:0,value:"Inloggen"}],verifyCodeError:[{type:0,value:"Inloggen is niet gelukt. De code is waarschijnlijk niet meer geldig. "},{type:8,value:"login",children:[{type:0,value:"Vraag een nieuwe code aan"}]},{type:0,value:"."}],requestCodeTitle:[{type:0,value:"Verstuur een login code naar je email"}],requestCodeBody:[{type:0,value:"Voer je e-mailadres in en krijg een login code. Als je een bestaande "},{type:1,value:"productName"},{type:0,value:" gebruiker bent krijg je een email met een code. Als je een nieuwe gebruiker bent wordt er een email verstuurd met een toegangsverzoek voor "},{type:1,value:"productName"},{type:0,value:"."}],requestCodeInputPlaceholder:[{type:0,value:"Typ hier je e-mailadres"}],requestCodeSubmitLabel:[{type:0,value:"Code aanvragen"}]};var gl={root:"_root_1edpl_1",anchorButton:"_anchorButton_1edpl_5",errorMessage:"_errorMessage_1edpl_19",title:"_title_1edpl_25",subtitle:"_subtitle_1edpl_31",text:"_text_1edpl_38",input:"_input_1edpl_43",actions:"_actions_1edpl_48",button:"_button_1edpl_55",primaryButton:"_primaryButton_1edpl_70"};import{jsx as $,jsxs as _n}from"react/jsx-runtime";var Jg=t=>{try{let e=new URL(t);return new URLSearchParams(e.search).get("token")||void 0}catch{return t}},Yg=({agentEmail:t,isOpen:e,origin:o="",onSuccess:n,onDismiss:s})=>{let r=T(rr),i=S("LoginTokenDialog",gl),a=Zg(nl),l=Qg(),c=b("productName"),[p,u]=ar(t||""),[d,m]=ar(0),[f,g]=ar(""),x=ml(async _=>{_.preventDefault(),l(rl({email:p})),m(1)},[o,p]),w=()=>{g(""),m(0)},h=ml(async _=>{_.preventDefault();let C=Jg(_.target.elements.token.value);if(!C){g(r("verifyCodeError",{login:y}));return}l(oo({token:C}))},[o]),y=Xg(()=>_=>$("button",{type:"button","data-testid":"login-token-dialog-back-button",className:i.anchorButton,onClick:w,children:_},"back-button"),[]);return $g(()=>{a==="error"&&g(r("verifyCodeError",{login:y})),a==="done"&&n()},[a]),$(dt,{autoFocus:!0,isOpen:e,contentAriaLabel:r("promptTitle",{productName:c}),overlayAriaLabel:r("promptTitle",{productName:c}),onClose:s,onBack:s,children:_n("div",{className:i.root,children:[$("h1",{className:i.title,children:r("promptTitle",{productName:c})}),d===0&&_n("form",{onSubmit:x,children:[$("h2",{className:i.subtitle,children:r("requestCodeTitle")}),$("p",{className:i.text,children:r("requestCodeBody",{productName:c})}),$(no,{className:i.input,name:"email",placeholder:r("requestCodeInputPlaceholder"),value:p,onChange:_=>u(_.target.value)}),$("div",{className:i.actions,children:$("button",{type:"submit",className:ir(i.button,i.primaryButton),children:r("requestCodeSubmitLabel")})})]}),d===1&&_n("form",{onSubmit:h,children:[$("h2",{className:i.subtitle,children:r("verifyCodeTitle")}),$("p",{className:i.text,children:r("verifyCodeBody")}),$(no,{className:i.input,name:"token",placeholder:r("verifyCodeInputPlaceholder"),disabled:["loading","done"].includes(a)}),f&&$("div",{className:i.errorMessage,children:f}),_n("div",{className:i.actions,children:[$("button",{type:"button",className:ir(i.button),onClick:w,children:r("back")}),$("button",{type:"submit",className:ir(i.button,i.primaryButton),disabled:["loading","done"].includes(a),children:r("verifyCodeSubmitLabel")})]})]})]})})},fl=Yg;import{jsx as tm}from"react/jsx-runtime";var em=()=>{let t=hl(sl),e=hl(fa),o=b("adminUrl"),n=te(),s=()=>n.send(wt,!1),r=()=>{n.send(wt,!1),n.send(or)};return tm(fl,{isOpen:t,agentEmail:e==null?void 0:e.agentEmail,origin:o,onDismiss:s,onSuccess:r})},yl=em;import Wm from"lodash.debounce";import{useCallback as fr,useEffect as hr,useState as ao}from"react";import{useDispatch as Gm,useSelector as Pt}from"react-redux";import{createAsyncThunk as om,createSlice as nm}from"@reduxjs/toolkit";var sm={data:null,fetchState:"idle"},Sl=t=>t.contentTypes.data,so=om("contentTypes/getContentTypes",async(t,e)=>e.extra.deepdeskAPI.getContentTypes()),rm=nm({name:"contentTypes",initialState:sm,reducers:{},extraReducers:t=>{t.addCase(so.pending,e=>{e.fetchState="loading"}).addCase(so.rejected,e=>{e.fetchState="error"}).addCase(so.fulfilled,(e,o)=>{e.fetchState="done",e.data=o.payload})}}),vl=rm.reducer;function ro(t){let e=document.createElement("textarea");e.value=t,e.style.position="fixed",e.style.left="-999999px",e.style.top="-999999px",document.body.appendChild(e),e.focus(),e.select(),document.execCommand("copy"),e.remove()}import{useEffect as im}from"react";function _l(t,e){im(()=>{let o=n=>{var s;((s=navigator==null?void 0:navigator.platform)!=null&&s.toLowerCase().includes("mac")?n.metaKey:n.ctrlKey)&&n.key===t&&(n.preventDefault(),n.stopPropagation(),e())};return document.addEventListener("keydown",o),()=>{document.removeEventListener("keydown",o)}},[])}import{useEffect as wl,useRef as gm}from"react";import{useSelector as mm,useDispatch as fm}from"react-redux";import{createAsyncThunk as am,createSlice as lm}from"@reduxjs/toolkit";var xl={data:null,fetchState:"idle"},xn=t=>{var r;let e=[],{visitorName:o}=t.info.visitorInfo??{},{agentName:n,agentNickname:s}=t.info.agentInfo??{};return n&&n!==o&&e.push(n),s&&s!==o&&e.push(s),((r=t.entities.data)==null?void 0:r.filter(i=>!e.includes(i.text)))??null},le=am("entities/getEntities",async(t,e)=>{let{deepdeskAPI:o,dynamicThunkObject:n}=e.extra;if(!n.conversationQuery)return Promise.resolve([]);let s=n.conversationQuery,r=await s();return r.length===0?Promise.resolve([]):o.getEntities(r)}),cm=t=>t.filter((e,o)=>o===t.findIndex(n=>n.text===e.text)),pm=lm({name:"entities",initialState:xl,reducers:{},extraReducers:t=>{t.addCase(le.pending,e=>{e.fetchState="loading"}).addCase(le.rejected,e=>{e.fetchState="error"}).addCase(le.fulfilled,(e,o)=>{e.fetchState="done",e.data=cm(e.data?[...e.data,...o.payload]:o.payload)}).addCase(R,()=>xl)}}),bl=pm.reducer;var lr={};U(lr,{enUS:()=>um,nlNL:()=>dm});var um={noResults:[{type:0,value:"No entities have been found"}],copy:[{type:0,value:"Copy"}],use:[{type:0,value:"Use"}]},dm={noResults:[{type:0,value:"Er zijn geen entiteiten gevonden"}],copy:[{type:0,value:"Kopieer"}],use:[{type:0,value:"Gebruik"}]};var Cl={root:"_root_17kae_1",empty:"_empty_17kae_5"};import{jsx as bn,jsxs as ym}from"react/jsx-runtime";var hm=({onCopy:t,onUse:e})=>{let o=gm(null),n=S("EntitiesList",Cl),s=T(lr),r=mm(xn),i=fm();return wl(()=>{i(le())},[]),wl(()=>{o.current&&o.current.focus()},[o]),ym("div",{className:n.root,ref:o,tabIndex:-1,children:[r&&r.length>0&&bn(P.ActionsBar,{primaryLabel:s("copy"),secondaryLabel:s("use"),onPrimary:(a,l)=>t(r[l]),onSecondary:(a,l)=>e(r[l]),list:r.map(a=>({text:a.text,type:a.label,primaryAction:"copy",secondaryAction:"use"})),children:bn(P.List,{children:r.map((a,l)=>bn(P.ListItem,{index:l,closeOnSelect:!0,onClick:()=>t(a),children:a.text},a.text))},"entities")}),r&&r.length===0&&bn("p",{className:n.empty,children:s("noResults")})]})},Tl=hm;import{Fragment as Cm,useEffect as Cn,useRef as wm,useState as Tm}from"react";import{useSelector as Al,useDispatch as Em}from"react-redux";import{createAsyncThunk as Sm,createSlice as vm}from"@reduxjs/toolkit";var El={data:null,fetchState:"idle"},kl=t=>t.summary.data,Rl=t=>t.summary.fetchState==="error",we=Sm("summary/getSummary",async(t,e)=>{let o=e.getState().profile.data;if(!o)throw new Error("Profile is not defined");let{deepdeskAPI:n,dynamicThunkObject:s}=e.extra;if(!s.conversationQuery)return Promise.reject(new Error("setConversationQuery method is not defined"));let r=s.conversationQuery,i=await r();return i.length===0?Promise.reject(new Error("No messages are included")):{summary:await n.getSummary(i,{promptInstruction:o.summarizerPromptInstruction,model:o.summarizerModel})}}),_m=vm({name:"summary",initialState:El,reducers:{},extraReducers:t=>{t.addCase(we.pending,e=>{e.data=null,e.fetchState="loading"}).addCase(we.rejected,e=>{e.data=null,e.fetchState="error"}).addCase(we.fulfilled,(e,o)=>{e.fetchState="done",o.payload&&(e.data=o.payload.summary)}).addCase(R,()=>El)}}),Pl=_m.reducer;var cr={};U(cr,{enUS:()=>xm,nlNL:()=>bm});var xm={copy:[{type:0,value:"Copy"}],error:[{type:0,value:"Could not generate a summary"}],loading:[{type:0,value:"Generating summary, this may take a few moments."}]},bm={copy:[{type:0,value:"Kopieer"}],error:[{type:0,value:"Kon helaas geen samenvatting genereren."}],loading:[{type:0,value:"Samenvatting wordt gemaakt, dit kan even duren."}]};var Il={root:"_root_6ahh3_1",actions:"_actions_6ahh3_5",main:"_main_6ahh3_11",textInput:"_textInput_6ahh3_15",loading:"_loading_6ahh3_34",error:"_error_6ahh3_38"};import{jsx as Tt,jsxs as Rm}from"react/jsx-runtime";var km=({onCopy:t})=>{let e=wm(null),o=S("SummaryForm",Il),[n,s]=Tm(""),r=T(cr),i=Al(kl),a=Al(Rl),l=Em(),c=()=>{l(J({name:"summary copied to clipboard",data:{originalText:i,finalText:n},options:{includeConversationData:!0}})),t(n)},p=()=>{let u=document.getSelection();u&&l(J({name:"summary copied to clipboard",data:{originalText:i,finalText:u==null?void 0:u.toString()},options:{includeConversationData:!0}}))};return Cn(()=>{l(we())},[]),Cn(()=>{s(i||"")},[i]),Cn(()=>{e.current&&i&&e.current.focus()},[e,i]),Cn(()=>{let u=d=>{d.key==="Enter"&&d.shiftKey&&c()};return document.addEventListener("keydown",u),()=>{document.removeEventListener("keydown",u)}},[n]),Tt("div",{className:o.root,tabIndex:-1,children:a?Tt("p",{className:o.error,children:r("error")}):Rm(Cm,{children:[Tt("div",{className:o.main,children:Tt("textarea",{placeholder:i?void 0:r("loading"),disabled:!i,className:o.textInput,ref:e,value:n,onCopy:p,onChange:u=>s(u.target.value)})}),Tt("div",{className:o.actions,children:Tt(P.Button,{shortKeys:[8679,8629],onClick:c,children:r("copy")})})]})})},Ll=km;var pr={};U(pr,{enUS:()=>Pm,nlNL:()=>Im});var Pm={personalCollectionLink:[{type:0,value:"Go to Personal Collection"}],searchPlaceholder:[{type:0,value:"Start typing to search..."}],urlSuggestions:[{type:0,value:"Link suggestions"}],personalSuggestions:[{type:0,value:"Personal suggestions"}],pinnedMessages:[{type:0,value:"Pinned messages"}],imageSuggestions:[{type:0,value:"Images"}],typePlaceholder:[{type:0,value:"All types"}],navigation:[{type:0,value:"Navigation"}],entitiesClipboard:[{type:0,value:"Conversation clipper"}],entitiesTitle:[{type:0,value:"Copy to your clipboard"}],summaryClipboard:[{type:0,value:"Summarize conversation"}],summaryTitle:[{type:0,value:"Conversation summary"}],knowledgeAssist:[{type:0,value:"Knowledge assist"}],commands:[{type:0,value:"Commands"}],use:[{type:0,value:"Use"}],preview:[{type:0,value:"Preview"}],warning:[{type:0,value:"Are you sure you want to discard the message?"}]},Im={personalCollectionLink:[{type:0,value:"Ga naar persoonlijke collectie"}],searchPlaceholder:[{type:0,value:"Begin met typen om te zoeken..."}],personalSuggestions:[{type:0,value:"Persoonlijke suggesties"}],urlSuggestions:[{type:0,value:"Link suggesties"}],imageSuggestions:[{type:0,value:"Afbeeldingen"}],navigation:[{type:0,value:"Navigatie"}],typePlaceholder:[{type:0,value:"Alle types"}],pinnedMessages:[{type:0,value:"Actueel"}],entitiesClipboard:[{type:0,value:"Klembord"}],entitiesTitle:[{type:0,value:"Kopieer naar klembord"}],summaryClipboard:[{type:0,value:"Gesprek samenvatten"}],summaryTitle:[{type:0,value:"Gesprek samenvatting"}],knowledgeAssist:[{type:0,value:"Knowledge assist"}],commands:[{type:0,value:"Acties"}],use:[{type:0,value:"Gebruik"}],preview:[{type:0,value:"Bewerk"}],warning:[{type:0,value:"Weet je zeker dat je de wijzigingen wilt weggooien?"}]};import Bm,{useEffect as gr,useRef as Fm}from"react";import{useDispatch as Km,useSelector as Fl}from"react-redux";var ur={};U(ur,{enUS:()=>Am,nlNL:()=>Lm});var Am={use:[{type:0,value:"Use"}],loading:[{type:0,value:"Loading..."}],error:[{type:0,value:"Something went wrong, please try again later."}],anotherQuestion:[{type:0,value:"Send a message..."}],reset:[{type:0,value:"Reset conversation"}]},Lm={use:[{type:0,value:"Gebruik"}],loading:[{type:0,value:"Laden..."}],error:[{type:0,value:"Er ging iets mis, probeer het later opnieuw."}],anotherQuestion:[{type:0,value:"Stuur een bericht..."}],reset:[{type:0,value:"Reset gesprek"}]};var Ml={root:"_root_1g4pq_1",title:"_title_1g4pq_9",empty:"_empty_1g4pq_20",status:"_status_1g4pq_24",form:"_form_1g4pq_30",input:"_input_1g4pq_43",submit:"_submit_1g4pq_55",question:"_question_1g4pq_63",answer:"_answer_1g4pq_67",alignRight:"_alignRight_1g4pq_73"};import{createAction as Mm,createAsyncThunk as Om,createSlice as Nm}from"@reduxjs/toolkit";var dr={data:[],fetchState:"idle"},Ol=t=>{var e;return(e=t.answer)==null?void 0:e.data},Nl=t=>t.answer.fetchState,kt=Mm("answer/resetKnowledgeSearch"),Et=Om("answer/getAnswer",async(t,e)=>{var i;let{deepdeskAPI:o}=e.extra,n=e.getState().answer.data,s=(i=e.getState().conversation.current)==null?void 0:i.profileCode;if(!s)throw new Error("Profile is not defined");let r=await o.knowledgeAssist({promptInstruction:t.promptInstruction,question:t.question},n,s);return{question:t.question,answer:r}}),Dm=Nm({name:"answer",initialState:dr,reducers:{},extraReducers:t=>{t.addCase(Et.pending,e=>{e.fetchState="loading"}).addCase(Et.rejected,e=>{e.fetchState="error"}).addCase(Et.fulfilled,(e,o)=>{e.fetchState="done",e.data=[...e.data,o.payload]}).addCase(R,()=>dr).addCase(kt,()=>dr)}}),Dl=Dm.reducer;import{jsx as Hl,jsxs as Hm}from"react/jsx-runtime";var Bl=()=>Hm("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 512 512","aria-labelledby":"paperPlaneTitle",children:[Hl("title",{id:"paperPlaneTitle",children:"PaperPlane"}),Hl("path",{d:"M498.1 5.6c10.1 7 15.4 19.1 13.5 31.2l-64 416c-1.5 9.7-7.4 18.2-16 23s-18.9 5.4-28 1.6L284 427.7l-68.5 74.1c-8.9 9.7-22.9 12.9-35.2 8.1S160 493.2 160 480V396.4c0-4 1.5-7.8 4.2-10.7L331.8 202.8c5.8-6.3 5.6-16-.4-22s-15.7-6.4-22-.7L106 360.8 17.7 316.6C7.1 311.3 .3 300.7 0 288.9s5.9-22.8 16.1-28.7l448-256c10.7-6.1 23.9-5.5 34 1.4z"})]});import{jsx as Te,jsxs as mr}from"react/jsx-runtime";var Um=({onUse:t,onResetQuestion:e,question:o,promptInstruction:n})=>{let[s,r]=Bm.useState(""),{setSelected:i}=De(),a=Fm(null),l=S("EntitiesList",Ml),c=T(ur),p=Km(),u=Fl(Ol),d=Fl(Nl),m=async g=>{g.preventDefault(),g.stopPropagation(),s!==""&&p(Et({question:s,promptInstruction:n}))},f=(g,x)=>{p(J({name:"knowledge assist source viewed",data:{question:x,sourceViewed:g.url||g.name},options:{includeConversationData:!0}}))};return gr(()=>{var g;o&&d==="idle"?p(Et({question:o,promptInstruction:n})):(g=a.current)==null||g.focus()},[a,d]),gr(()=>{d==="done"&&(p(J({name:"knowledge assist question answered",data:{question:s||o,sources:u[u.length-1].answer.sources,answer:u[u.length-1].answer.answer,isFollowUpQuestion:u.length>1},options:{includeConversationData:!0}})),i(u.length-1),r(""))},[d,u]),gr(()=>{a.current&&a.current.scrollIntoView({behavior:"smooth"})},[a,u]),mr("div",{className:l.root,children:[u.length>0&&Te("div",{className:l.alignRight,children:Te(P.Button,{onClick:e,children:c("reset")})}),mr(P.ActionsBar,{list:u.map(({answer:g})=>({text:g.answer,type:"answer"})),primaryLabel:c("use"),onPrimary:g=>t(g.text),children:[u.map(({question:g,answer:x},w)=>Te(P.List,{children:Te(P.ListItem,{"data-testid":"knowledge-search-answer",index:w,description:x.answer,closeOnSelect:!0,onClick:()=>t(x.answer),onSourceClick:h=>f(h,g),sources:x.sources,styles:{title:l.question,description:l.answer},children:g})},`${x.answer}_${w}`)),d==="loading"&&Te("p",{className:l.status,children:c("loading")}),d==="error"&&Te("p",{className:l.status,children:c("error")}),mr("form",{className:l.form,onSubmit:m,children:[Te("input",{ref:a,placeholder:c("anotherQuestion"),className:l.input,type:"text",value:s,onFocus:()=>{i(-1)},onChange:g=>{i(-1),r(g.target.value)}}),Te("button",{type:"submit",className:l.submit,children:Te(Bl,{})})]})]})]})},Kl=Um;import{createAsyncThunk as zm,createSlice as jm}from"@reduxjs/toolkit";var qm={data:null,fetchState:"idle"},Rt=t=>t.profile.data,wn=t=>t.profile.data?t.profile.data.uiConfig.widget.types.filter(e=>e.isActive):[],io=zm("profile/getProfile",async(t,e)=>{var r;let{deepdeskAPI:o}=e.extra,n=e.getState(),s=n.conversation.current;if(!s||!s.profileCode)throw new Error("No conversation of conversation profileCode found");return((r=n.profile.data)==null?void 0:r.code)===s.profileCode?n.profile.data:o.getProfile(s.profileCode)}),Vm=jm({name:"profile",initialState:qm,reducers:{},extraReducers:t=>{t.addCase(io.pending,e=>{e.fetchState="loading"}).addCase(io.rejected,e=>{e.fetchState="error"}).addCase(io.fulfilled,(e,o)=>{e.fetchState="done",e.data=o.payload})}}),Ul=Vm.reducer;import{jsx as X,jsxs as jl}from"react/jsx-runtime";var $m=200,Xm=5,Qm=4,Zm=t=>t.reduce((e,o)=>[...e,...o.list.map(n=>({...n,type:o.value}))],[]),zl=(t,e)=>!e||t.toLowerCase().includes(e.toLowerCase()),Jm=()=>{let t=Gm(),e=te(),o=T(pr),[n,s]=ao(!1),[r,i]=ao(""),a=Pt(_a),l=Pt(Rt),[c,p]=ao(null),[u,d]=ao([]),[m,f]=ao(),g=Pt(ae),x=b("showSearch"),w=b("showEntitiesCommand"),h=b("showSummaryCommand"),y=b("showKnowledgeSearch"),_=b("showImageSearch"),C=b("searchTriggerKey"),H=Pt(Sl),O=Pt(xa),ce=Pt(va),N=v=>ns(O.filter(I=>I.type===v.toUpperCase()),v),k=[{value:"PERSONAL",label:o("personalSuggestions"),list:N("PERSONAL"),lineClamp:!1,listOrientation:"vertical",shouldShow:!0},{value:"URL",label:o("urlSuggestions"),list:N("URL"),lineClamp:!1,listOrientation:"vertical",shouldShow:!0},{value:"STICKYMESSAGE",label:o("pinnedMessages"),list:N("STICKYMESSAGE"),lineClamp:!1,listOrientation:"vertical",shouldShow:!0},{value:"IMAGE",label:o("imageSuggestions"),lineClamp:!1,list:N("IMAGE"),listOrientation:"horizontal",shouldShow:_}].filter(v=>v.shouldShow),V=[{label:o("entitiesClipboard"),onClick:()=>t(j("entities")),shouldShow:w&&zl(o("entitiesClipboard"),r),experimental:!0},{label:o("summaryClipboard"),onClick:()=>t(j("summary")),shouldShow:h&&zl(o("summaryClipboard"),r),experimental:!0},{label:r?`${o("knowledgeAssist")}: ${r}`:o("knowledgeAssist"),onClick:()=>t(j("knowledgeAssist")),shouldShow:y,experimental:!0}].filter(v=>v.shouldShow),oe=(H==null?void 0:H.map(v=>({value:v.code.toUpperCase(),label:`${v.name}s`,list:N(v.code.toUpperCase()),listOrientation:"vertical",lineClamp:!0})))||[],ts=fr(Wm((v,I)=>{t(Xe({query:v,type:I,tags:["search-overlay"]}))},$m),[]),Ue=Zm([...oe,...k]),qp=fr((v,I)=>{if(!I)return;let Pe=[...k,...oe].find(({value:nt})=>nt===I);Pe&&(t(j("edit")),p({...v,searchTerm:void 0}),d(Pe.list))},[t,c,oe]),os=fr((v,I)=>{switch(I.type){case"IMAGE":e.send(nr,{suggestion:I});break;default:e.send(Ce,{text:v,suggestion:I})}t(Y(!1))},[t]),Vp=v=>{ro(v.text),t(J({name:"entity copied",data:{entity:v,type:"copy"}})),t(Y(!1))},Wp=v=>{e.send(Ce,{text:v,suggestion:{source:"knowledge-assist",text:v}}),t(J({name:"answer used",data:{originalText:v},options:{includeConversationData:!0}})),i(""),t(j("search")),t(kt()),t(Y(!1))},Gp=v=>{ro(v),t(Y(!1))},$p=v=>{e.send(Ce,{text:v.text,suggestion:{source:"entity",text:v.text}}),t(Y(!1))},Xp=c===null||u.indexOf(c)-1<0?void 0:()=>p(u[u.indexOf(c)-1]),Qp=c===null||u.indexOf(c)===u.length-1?void 0:()=>p(u[u.indexOf(c)+1]);function ns(v,I){return v.slice(0,m?10:I.toLowerCase()==="image"?Qm:Xm)}function Jr(v,I,Pe){return I.reduce((nt,bo)=>Pe&&m===Pe?bo.length+nt:ns(bo,Pe).length+nt,v)}function ot(v){return I=>{n?window.confirm(o("warning"))&&(v(I),s(!1)):v(I)}}return hr(()=>{r?ts(r,m):t(mn())},[r,m]),hr(()=>{a==="search"&&t(kt())},[a]),hr(()=>{g&&t(so())},[g]),_l(C,()=>t(Y(!0))),!x||!l?null:jl(P,{placeholder:o("searchPlaceholder"),typePlaceholder:o("typePlaceholder"),onChangeSearch:i,onChangeOpen:ot(v=>t(Y(v))),onChangeType:v=>f(v),onChangePage:ot(v=>t(j(v))),selectedType:m,search:r,page:a,isOpen:ce,types:[...oe,...k],children:[X(P.Page,{id:"search",children:jl(P.ActionsBar,{list:[...V.map(v=>({text:v.label,type:"command"})),...Ue.map(v=>({text:v.text||v.url||v.message,type:v.type}))],primaryLabel:o("use"),secondaryLabel:o("preview"),onPrimary:({text:v},I)=>os(v,Ue[I]),onSecondary:(v,I)=>{qp(Ue[I-V.length],Ue[I-V.length].type)},children:[V.length>0&&X(P.List,{heading:o("commands"),children:V.map((v,I)=>X(P.ListItem,{index:Jr(I,[],"commands"),closeOnSelect:!1,onClick:v.onClick,isExperimental:v.experimental,children:v.label},v.label))}),[...oe,...k].map(({value:v,label:I,list:Pe,lineClamp:nt,listOrientation:bo},Zp)=>X(P.List,{heading:I,orientation:bo==="horizontal"?"horizontal":"vertical",children:ns(Pe,v).map((ne,Jp)=>X(P.ListItem,{index:Jr(V.length+Jp,[...oe,...k].slice(0,Zp).map(({list:Yp})=>Yp),v),closeOnSelect:!1,lineClamp:nt,onClick:()=>os(ne.text,ne),description:v!=="IMAGE"?ne.title&&ne.text:void 0,children:v==="IMAGE"?X(P.Image,{title:ne.title||ne.text,src:ne.image}):ne.title||ne.text},`${ne.id}-${ne.text}`))},v))]})}),X(P.Page,{id:"edit",onDismiss:ot(()=>{t(j("search")),p(null)}),children:c&&X(yn,{suggestion:c,onTouched:s,onDismiss:()=>{s(!1),t(j("search")),p(null),d([])},onNext:Qp,onPrevious:Xp,onUse:v=>{t(j("search")),os(v,{...c,source:`${c.source||"text_recommendation"}-preview`}),t(Y(!1)),d([]),p(null)}})}),X(P.Page,{id:"entities",title:o("entitiesTitle"),isExperimental:!0,onDismiss:ot(()=>{t(j("search"))}),children:X(Tl,{onUse:$p,onCopy:Vp})}),X(P.Page,{id:"summary",title:o("summaryTitle"),isExperimental:!0,onDismiss:ot(()=>{t(j("search"))}),children:X(Ll,{onCopy:Gp})}),X(P.Page,{id:"knowledgeAssist",title:o("knowledgeAssist"),isExperimental:!0,onDismiss:ot(()=>{t(kt()),t(j("search"))}),children:X(Kl,{promptInstruction:l.knowledgeAssistPromptInstruction,question:r,onUse:Wp,onResetQuestion:()=>{t(kt()),i("")}})})]})},ql=Jm;import{jsx as yr,jsxs as tf}from"react/jsx-runtime";var ef=()=>{let t=b("showSearch"),e=b("isEmbedded");return tf(Ym,{children:[t&&yr(ql,{}),yr(ul,{}),e&&yr(yl,{})]})},Vl=ef;import{connect as Cf,useDispatch as wf,useSelector as En}from"react-redux";function It(t){let{showMidSentenceSuggestions:e,showSuggestionsBeforePattern:o,showSuggestionsAfterPattern:n}=t.settings,{text:s,selection:r}=t.input.userCommitted;return r.start!==r.end?!1:r.end>=s.length?!0:e?o&&new RegExp(o).test(s.substring(r.end))||n&&new RegExp(n).test(s.substring(0,r.end))?!0:o===!1&&n===!1:!1}import{Fragment as _f,useMemo as xf}from"react";import{Interweave as pf}from"interweave";import{useEffect as uf,useMemo as df,useRef as gf}from"react";import{useDispatch as mf,useSelector as ff}from"react-redux";import{useEffect as of}from"react";function Wl(t,e,o){of(()=>{let n=t.current;return n?(n.addEventListener(e,o),()=>{n.removeEventListener(e,o)}):()=>{}},[t,e,o])}var nf=/[.*+?^${}()|[\]\\]/g,sf=/[^0-9A-Za-zÀ-ÖØ-öø-ÿ](?=[0-9A-Za-zÀ-ÖØ-öø-ÿ]*$)/;function rf(t){return t.replace(nf,"\\$&")}function af(t,e){let o=t.split("").findIndex((n,s)=>n!==e[s]);return o>-1?o:Math.min(t.length,e.length)}function Sr(t){return t.search(sf)}function Gl(t,e=[]){let o=t;return e.forEach(n=>{if(!n)return;let s=new RegExp(`\\b(${rf(n)})\\b`,"gi");o=o.replace(s,"<strong>$1</strong>")}),o}function $l(t){return t.replace(lt,'<mark data-type="placeholder">$1</mark>')}function lo(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function lf(t,e){return t.split("").map((i,a)=>({char:i,index:a})).filter(({char:i,index:a})=>/\s/.test(i)&&a<=e).map(({index:i})=>i).reverse()[0]}function vr(t,e,o={}){if(e){let n=af(e.toLowerCase(),t.toLowerCase()),s=lo(t.substring(n,t.length));if(o.stripAgentPart){let l=t.substring(0,n),c=Sr(l);return`<span style="opacity: 0.5">${l.substring(c+1)}</span>${s}`}let i=e.split(Si).length>3||e.length>30?lf(e.trim(),n):0;return`${`${i>0?"\u2026":""}${lo(t.substring(i,n))}`}<strong>${s}</strong>`}return t}var Xl={badge:"_badge_1syy2_1",formattedText:"_formattedText_1syy2_5"};import{jsx as Ql}from"react/jsx-runtime";var hf=["search","personal-collection-search","search-autocomplete"];function yf(t,e,o,n={}){let s="";return hf.includes(e)?s=Gl(vr(t,o,{stripAgentPart:!0}),n.searchKeywords??[o]):s=vr(t,o,n),n.placeholders===!0&&(s=$l(s)),s}var Sf=()=>{},vf=({index:t,selected:e,suggestion:o})=>{let n=b("inlineSuggestions"),s=ff(ut),r=mf(),i=S("TextSuggestion",Xl),a=gf(null);uf(()=>{let c=setTimeout(()=>{r(Li({text:o.text,suggestion:o}))},500);return()=>{clearTimeout(c)}},[o]),Wl(a,"click",()=>{r($t(t)),r(ie({suggestion:o,text:o.text,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"}))});let l=df(()=>yf(o.text,o.source,s,{stripAgentPart:n,placeholders:!0,searchKeywords:o.searchKeywords}),[n,o.text,o.source,s,o.searchKeywords]);return o.source==="gpt"&&!n?null:Ql(M,{ref:a,as:"button","data-testid":"suggestions-overlay-item",selected:e,onClick:Sf,children:Ql(pf,{containerTagName:"div",noWrap:!1,tagName:"span",className:i.formattedText,content:l})})},Zl=vf;import{jsx as Jl}from"react/jsx-runtime";var bf=({suggestions:t,selectedIndex:e,reverse:o})=>{let n=xf(()=>{let s=t.map((r,i)=>Jl(Zl,{index:i,selected:i===e,suggestion:r},`${r.text}-${r.source}`));return o?s.reverse():s},[t,e,o]);return Jl(_f,{children:n})},Tn=bf;var Yl={root:"_root_otdbu_1",paper:"_paper_otdbu_11"};import{jsx as kn}from"react/jsx-runtime";var Tf=({textSuggestions:t,selectedIndex:e})=>{let o=S("InlineSuggestionsOverlay",Yl),n=En(It),s=wf(),r=En(ae),i=En(pt),a=En(vn),l=b("showTextSuggestions");return Me(()=>{s(He({collapse:!0,skipWhenInputFocus:!0}))}),a||!n||!l||t.length===0||r!==!0||i===!1?null:kn("div",{className:o.root,"data-variant":"inline",children:kn("div",{className:o.paper,children:kn(re,{children:kn(Tn,{suggestions:t,selectedIndex:e})})})})},Ef=({input:t})=>({selectedIndex:t.selectedSuggestionIndex,textSuggestions:t.textSuggestions}),ec=Cf(Ef)(Tf);import wr from"classnames";import{useEffect as Bf,useRef as Ff,useState as Kf}from"react";import{connect as Uf,useDispatch as zf,useSelector as In}from"react-redux";import{useState as kf}from"react";function tc(t,e){let[o,n]=kf(()=>{if(typeof window>"u")return e;try{let r=window.localStorage.getItem(t);return r?JSON.parse(r):e}catch(r){return E.error(r),e}});return[o,r=>{try{let i=r instanceof Function?r(o):r;n(i),typeof window<"u"&&window.localStorage.setItem(t,JSON.stringify(i))}catch(i){E.error(i)}}]}import If from"classnames";import{Fragment as Af,useCallback as xr,useMemo as nc}from"react";var _r={};U(_r,{enUS:()=>Rf,nlNL:()=>Pf});var Rf={loginPlease:[{type:8,value:"login",children:[{type:0,value:"Sign in"}]},{type:0,value:" to enable "},{type:1,value:"productName"},{type:0,value:"."}],snooze:[{type:0,value:"Snooze for "},{type:8,value:"min",children:[{type:0,value:"10 minutes"}]},{type:0,value:", "},{type:8,value:"hour",children:[{type:0,value:"1 hour"}]},{type:0,value:" or "},{type:8,value:"day",children:[{type:0,value:"1 day"}]}]},Pf={loginPlease:[{type:8,value:"login",children:[{type:0,value:"Log in"}]},{type:0,value:" bij "},{type:1,value:"productName"},{type:0,value:"."}],snooze:[{type:0,value:"Snooze voor "},{type:8,value:"min",children:[{type:0,value:"10 minuten"}]},{type:0,value:", "},{type:8,value:"hour",children:[{type:0,value:"1 uur"}]},{type:0,value:" of "},{type:8,value:"day",children:[{type:0,value:"1 dag"}]}]};var oc={root:"_root_1vfca_1",anchor:"_anchor_1vfca_6",anchorButton:"_anchorButton_1vfca_11"};import{jsx as Rn,jsxs as sc}from"react/jsx-runtime";var br=(t,e,o)=>n=>Rn("button",{className:t.anchorButton,type:"button",value:e,onClick:o,children:n},e),Lf=({className:t,loginUrl:e,isEmbedded:o,onSnooze:n})=>{let s=T(_r),r=te(),i=S("Login",oc),a=b("productName"),l=xr(g=>{g.preventDefault(),n&&n(parseInt(g.target.value,10))},[]),c=xr(g=>{g.preventDefault(),r.send(wt,!0)},[e]),p=nc(()=>g=>Rn("a",{href:e,className:i.anchor,target:"_blank",rel:"noreferrer",children:g},"login"),[e]),u=xr(g=>Rn("button",{type:"button",className:i.anchorButton,onClick:c,children:g},"prompt"),[c]),{min:d,hour:m,day:f}=nc(()=>({min:br(i,60*10,l),hour:br(i,60*60,l),day:br(i,60*60*12,l)}),[]);return sc("div",{className:If(t,i.root),children:[s("loginPlease",{login:o?u:p,productName:a}),n&&sc(Af,{children:[Rn("br",{}),s("snooze",{min:d,hour:m,day:f})]})]})},Pn=Lf;import{useDispatch as Mf}from"react-redux";var rc={root:"_root_1g8fi_1",text:"_text_1g8fi_19"};import{jsx as ic,jsxs as Nf}from"react/jsx-runtime";var Of=({title:t})=>{let e=S("SearchTrigger",rc),o=Mf();return Nf("button",{type:"button",className:e.root,onClick:()=>o(Y(!0)),children:[ic(St,{}),ic("span",{className:e.text,children:t})]})},ac=Of;var Cr={};U(Cr,{enUS:()=>Df,nlNL:()=>Hf});var Df={arrowHint:[{type:0,value:"Tip: use arrow keys to navigate suggestions"}],searchHintWindows:[{type:0,value:"Press CTRL+"},{type:1,value:"searchTriggerKey"},{type:0,value:" to search"}],searchHintMac:[{type:0,value:"Press CMD+"},{type:1,value:"searchTriggerKey"},{type:0,value:" to search"}],open:[{type:0,value:"Open "},{type:1,value:"productName"}],collapse:[{type:0,value:"Close"}],search:[{type:0,value:"Search"}]},Hf={arrowHint:[{type:0,value:"Tip: Selecteer suggesties met pijltoetsen"}],searchHintWindows:[{type:0,value:"Druk CTRL+"},{type:1,value:"searchTriggerKey"},{type:0,value:" om te zoeken"}],searchHintMac:[{type:0,value:"Druk CMD+"},{type:1,value:"searchTriggerKey"},{type:0,value:" om te zoeken"}],open:[{type:0,value:"Open "},{type:1,value:"productName"}],collapse:[{type:0,value:"Sluiten"}],search:[{type:0,value:"Zoeken"}]};var lc={root:"_root_onpov_1",isInline:"_isInline_onpov_14",toggleButton:"_toggleButton_onpov_21",toggleButtonWrapper:"_toggleButtonWrapper_onpov_25",toggleButtonWrapperHidden:"_toggleButtonWrapperHidden_onpov_32",isCollapsed:"_isCollapsed_onpov_36",collapsible:"_collapsible_onpov_36",hints:"_hints_onpov_44",hintsHidden:"_hintsHidden_onpov_51",triggers:"_triggers_onpov_56",triggersRight:"_triggersRight_onpov_71"};import{jsx as K,jsxs as co}from"react/jsx-runtime";var jf=({textSuggestions:t,selectedIndex:e})=>{let o=S("SuggestionsOverlay",lc),n=T(Cr),s=In(It),r=ki(),i=zf(),a=Ff(null),l=b("searchTriggerKey"),c=b("productName"),p=In(vn),u=In(ae),d=In(pt),[m,f]=Kf(null),g=b("showSearch"),x=b("showTextSuggestions"),w=b("adminUrl"),h=b("isEmbedded"),[y,_]=tc("dd-snooze-until-ms",0),C=p||y>Date.now(),H=t.filter(N=>N.source!=="gpt").length,O=()=>{C&&_(0),i(Ja(!C))},ce=N=>{let k=Date.now()+N*1e3;_(k),E.info(`Snooze until: ${new Date(k)}`),i(He({collapse:!0}))};return Bf(()=>{H===0&&f(null)},[t,H]),Me(()=>{i(He({collapse:!0,skipWhenInputFocus:!0}))}),u===null||d===!1?null:u===!1?co("div",{ref:a,className:wr(o.root,{[o.isCollapsed]:C}),children:[!C&&co("div",{className:o.triggers,children:[K("div",{style:{flex:1}}),K("div",{className:o.triggersRight,children:K(at,{className:o.toggleButton,title:n("collapse"),onClick:O,isCollapsed:!1})})]}),K("div",{className:o.toggleButtonWrapper,children:K(at,{className:o.toggleButton,title:n("open",{productName:c}),onClick:O,isCollapsed:!0})}),K("div",{className:o.collapsible,children:K(Pn,{loginUrl:w,isEmbedded:h,onSnooze:ce})})]}):!r||!s?null:co("div",{ref:a,className:wr(o.root,{[o.isCollapsed]:C}),children:[!C&&co("div",{className:o.triggers,children:[K("div",{style:{flex:1},children:g&&K("div",{style:{display:"inline-block"},onFocus:()=>{},onMouseOver:()=>f(n(dn()?"searchHintMac":"searchHintWindows",{searchTriggerKey:l.toUpperCase()})),onMouseLeave:()=>f(null),children:K(ac,{title:n("search")})})}),co("div",{className:o.triggersRight,onFocus:()=>{},children:[K("div",{className:wr(!m&&o.hintsHidden,o.hints),children:m}),K(at,{className:o.toggleButton,title:n("collapse"),onClick:O,isCollapsed:!1})]})]}),K("div",{className:o.toggleButtonWrapper,children:K(at,{className:o.toggleButton,title:n("open",{productName:c}),onClick:O,isCollapsed:!0})}),H>0&&x&&K("div",{className:o.collapsible,onFocus:()=>{},children:K(re,{children:K(Tn,{suggestions:t,selectedIndex:e,reverse:!0})})})]})},qf=({input:t})=>({selectedIndex:t.selectedSuggestionIndex,textSuggestions:t.textSuggestions}),An=Uf(qf)(jf);import{Provider as Vf}from"react-redux";import{jsx as Ln}from"react/jsx-runtime";var Wf=({children:t})=>{let o=b("locale").replace("-","");return Ln(ms.Provider,{value:o,children:t})},Gf=({store:t,customStyles:e={},children:o})=>Ln(Vf,{store:t,children:Ln(Wf,{children:Ln(Kt.Provider,{value:e,children:o})})}),At=Gf;import Nr from"classnames";import{Interweave as Fh}from"interweave";import{useCallback as Kh,useEffect as Uh,useMemo as Rc,useRef as zh}from"react";import{connect as jh}from"react-redux";import{cloneElement as $f}from"react";var Xf=["div","span","mark","strong","b","i","u","em"];function Tr(t,e,o=0){var r;let n=t[t.length-1],s=typeof n=="object"&&n!==null?(r=n.props)==null?void 0:r.tagName:void 0;if(s==="br")return t.pop(),[...t,...e,n];if(Xf.includes(s)){let i=Array.isArray(n.props.children)?n.props.children:[n.props.children];return[...t.slice(0,t.length-1),$f(n,{children:Tr(i,e,o+1)})]}return[...t,...e]}function ge(t){return t.tagName.toLowerCase()==="textarea"}var cc={root:"_root_81non_1",container:"_container_81non_3",agentText:"_agentText_81non_5",tabText:"_tabText_81non_6",hint:"_hint_81non_6",matchSelection:"_matchSelection_81non_10",focus:"_focus_81non_16",resetIndent:"_resetIndent_81non_20",matchKeyword:"_matchKeyword_81non_24",matchPlaceholder:"_matchPlaceholder_81non_25",hover:"_hover_81non_31",hintText:"_hintText_81non_64",popover:"_popover_81non_72",popoverRoot:"_popoverRoot_81non_77",popoverContentContainer:"_popoverContentContainer_81non_81",popoverContent:"_popoverContent_81non_81",selectionOptions:"_selectionOptions_81non_107",selectionOptionsIsHidden:"_selectionOptionsIsHidden_81non_112",selectionOptionsButton:"_selectionOptionsButton_81non_116",caret:"_caret_81non_132",popoverSuggestionsRoot:"_popoverSuggestionsRoot_81non_136",suggestionsOverlayInputStyles:"_suggestionsOverlayInputStyles_81non_141"};import{Matcher as ch}from"interweave";import{Fragment as ph,useEffect as uh}from"react";import mc from"classnames";import{createRef as rh,useCallback as kr,useMemo as ih,useRef as ah,useState as lh}from"react";import{useState as Qf,useLayoutEffect as Zf}from"react";var Jf=["bottom","height","left","right","top","width"],Yf=(t={},e={})=>Jf.some(o=>t[o]!==e[o]),Ee=new Map,pc,uc=()=>{let t=[],e=[];Ee.forEach((o,n)=>{if(n instanceof Element&&!n.isConnected){e.push(n);return}let s=n.getBoundingClientRect();Yf(s,o.rect)&&(o.rect=s,t.push(o))}),e.forEach(o=>{Ee.delete(o)}),t.forEach(o=>{o.callbacks.forEach(n=>n(o.rect))}),pc=window.requestAnimationFrame(uc)};function eh(t,e){return{observe(){let o=Ee.size===0;if(Ee.has(t)){let n=Ee.get(t);n.callbacks.push(e),n.rect&&e(n.rect)}else Ee.set(t,{rect:void 0,hasRectChanged:!1,callbacks:[e]});o&&uc()},unobserve(){let o=Ee.get(t);if(o){let n=o.callbacks.indexOf(e);n>=0&&o.callbacks.splice(n,1),o.callbacks.length||Ee.delete(t),Ee.size||cancelAnimationFrame(pc)}}}}function Er(t){let[e,o]=Qf(null);return Zf(()=>{if(!t.current)return;let n=eh(t.current,s=>{o(s)});return n.observe(),()=>{n.unobserve()}},[t]),e}import{useContext as th,useLayoutEffect as oh,useState as nh}from"react";import{createPortal as sh}from"react-dom";var dc={root:"_root_1jq08_1"};var gc=({children:t})=>{let[e,o]=nh(null),n=th(Kt);return oh(()=>{let s=document.createElement("div");return Ge(s),s.classList.add(dc.root),n!=null&&n.portalRootNode&&s.classList.add(n==null?void 0:n.portalRootNode),document.body.appendChild(s),o(s),()=>{s.isConnected&&document.body.removeChild(s)}},[]),e?sh(t,e):null};var me={ref:"_ref_1rcyi_1",root:"_root_1rcyi_7",positionAbove:"_positionAbove_1rcyi_13",positionBelow:"_positionBelow_1rcyi_17",positionLeft:"_positionLeft_1rcyi_21",positionRight:"_positionRight_1rcyi_25",alignStart:"_alignStart_1rcyi_29",alignCenter:"_alignCenter_1rcyi_34",alignEnd:"_alignEnd_1rcyi_40"};import{jsx as Rr}from"react/jsx-runtime";var Lt=(t=!1)=>{let[e,o]=lh(t),n=kr(()=>o(!0),[]),s=kr(()=>o(!1),[]),r=kr(()=>o(a=>!a),[]),i=ah(null);return{opened:e,open:n,close:s,toggle:r,triggerRef:i}};function Pr(t,e=null,o=0){if(!t)return{display:"none"};let n=e?t.top-e.top<0||t.top<e.top-o?e.top-o:t.top+t.height>e.top+e.height+o?e.top+e.height+o-t.height:t.top:t.top,s=e?t.left<e.left-o?e.left-o:t.left+t.width>e.left+e.width+o?e.left+e.width+o-t.width:t.left:t.left;return{top:n,left:s,height:t.height,width:t.width}}var Mt=({className:t,triggerRef:e,boundaryRef:o=rh(),position:n="above",align:s="center",children:r,toStyle:i=Pr,...a})=>{let l=Er(e),c=Er(o),p=ih(()=>i(l,c,0),[l,c]);return Rr(gc,{children:Rr("div",{className:mc(me.ref,{[me.positionAbove]:n==="above",[me.positionBelow]:n==="below",[me.positionLeft]:n==="left",[me.positionRight]:n==="right",[me.alignStart]:s==="start",[me.alignCenter]:s==="center",[me.alignEnd]:s==="end"}),style:p,...a,role:"dialog",children:Rr("div",{className:mc(t,me.root),children:r})})})};import{jsx as po,jsxs as gh}from"react/jsx-runtime";var dh=({inputStyle:t,inputElement:e})=>{let o=S("TabCompletion",ee),n=Lt(document.activeElement===e);return Me(()=>n.close()),uh(()=>{let s=()=>n.open();return e.addEventListener("focus",s),()=>{e.removeEventListener("focus",s)}},[]),gh(ph,{children:[po("mark",{className:ee.caret,ref:n.triggerRef}),n.opened&&po(Mt,{className:o.popoverSuggestionsRoot,triggerRef:n.triggerRef,position:"above",align:"start",children:po("div",{style:t,className:o.suggestionsOverlayInputStyles,children:po(An,{inline:!0})})})]})},Mn=class extends ch{charCounter=0;charLength=0;found=!1;onlyAtEnd=!1;props;onBeforeParse(e,o){var n;return this.props=o,this.charCounter=0,this.onlyAtEnd=o.inlineSuggestionsOnlyAtEnd??!1,this.charLength=(ge(o.inputElement)?o.inputElement.value.length:(n=o.inputElement.textContent)==null?void 0:n.length)??0,this.found=!1,e}match(e){if(this.found||!this.props||this.props.selection===null)return null;let[o,n]=this.props.selection;if(o!==n||this.onlyAtEnd&&o!==this.charLength)return null;let s=o,i=s>=this.charCounter&&s<=this.charCounter+e.length?{index:Sr(e.slice(0,s))+1-this.charCounter,length:0,match:"",valid:!0}:null;return i&&(this.found=!0),this.charCounter+=e.length,i??null}replaceWith(e,o){return po(dh,{inputStyle:o.inputStyle,inputElement:o.inputElement},"caret")}asTag(){return"mark"}};import yh from"classnames";import{Matcher as Sh}from"interweave";import{useEffect as vh,useMemo as _h}from"react";function fc(t){return t.replace(/[.*+^${}()|[\]\\]/g,"\\$&")}function On(t){return e=>{t.forEach(o=>{typeof o=="function"?o(e):o!=null&&(o.current=e)})}}function hc(t){return t!=null}import mh from"classnames";import{forwardRef as fh,useRef as hh}from"react";import{jsx as yc}from"react/jsx-runtime";var Nn=fh(({className:t,children:e,...o},n)=>{let s=hh(null),r=S("TabCompletion",ee);return yc("div",{ref:On([s,n]),className:mh(t,r.popoverContentContainer),...o,children:yc("div",{className:r.popoverContent,children:e})})});import{jsx as uo,jsxs as Ch}from"react/jsx-runtime";var xh=t=>e=>{let o=Pr(e);return"top"in o&&(o.width=t.width-(e.left-t.left)-10),o},bh=({inputElement:t,boundaryRef:e,inputStyle:o,children:n,suggestion:s})=>{let r=S("TabCompletion",ee),i=Lt(),a=_h(()=>xh(t.getBoundingClientRect()),[t]),[l,c]=nn(t);return vh(()=>{c?i.open():i.close()},[c]),Ch("span",{children:[uo("mark",{ref:On([l,i.triggerRef]),className:yh(r.matchKeyword,{[r.hover]:c}),"aria-haspopup":"dialog","aria-expanded":i.opened?"true":"false",children:n}),i.opened&&uo(Mt,{className:r.popover,triggerRef:i.triggerRef,boundaryRef:e,position:"below",align:"start",toStyle:a,children:uo(Nn,{style:o,children:uo("div",{className:r.hintText,children:s})})})]})},Dn=class extends Sh{keywordMatches=[];preparedKeywordMatches=[];usedKeywordMatches=new Set;onBeforeParse(e,o){return o.keywordMatches&&o.keywordMatches!==this.keywordMatches&&(this.preparedKeywordMatches=o.keywordMatches.map(n=>({...n,keywordRegex:new RegExp(`\\b${fc(n.keyword)}\\b`,"i")})),this.keywordMatches=o.keywordMatches),this.usedKeywordMatches.clear(),e}match(e){let o=this.preparedKeywordMatches.map(s=>{if(this.usedKeywordMatches.has(s))return null;let r=e.match(s.keywordRegex);if(!r)return null;let i=e.charAt(r.index-1),a=e.charAt(r.index+s.keyword.length);return i==="{"&&a==="}"?null:{index:r.index,length:r[0].length,match:r[0],matchString:r[0],suggestion:s.suggestion,preparedKeywordMatch:s,valid:!0}}).filter(hc);if(o.length===0)return null;let n=o.reduce((s,r)=>r.index<s.index?r:s);return this.usedKeywordMatches.add(n.preparedKeywordMatch),n}replaceWith(e,o){return uo(bh,{inputElement:o.inputElement,suggestion:o.suggestion,inputStyle:o.inputStyle,boundaryRef:o.boundaryRef,children:e},`keyword_${o.matchString}_${o.key}`)}asTag(){return"mark"}};import Or from"classnames";import{Matcher as Lh}from"interweave";import{createRef as Mh,forwardRef as Oh,useCallback as Nh,useEffect as Tc,useRef as Ec,useState as kc}from"react";import{useDispatch as Dh}from"react-redux";import{jsx as Sc}from"react/jsx-runtime";var vc=()=>Sc("svg",{width:"1.3em",height:"1.3em",focusable:"false","aria-hidden":"true",viewBox:"0 0 24 24","data-testid":"InsertLinkIcon",tabIndex:-1,children:Sc("path",{fill:"currentColor",d:"M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76 0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71 0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71 0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76 0 5-2.24 5-5s-2.24-5-5-5z"})});import{useCallback as wh,useEffect as xc,useState as bc}from"react";import{useDispatch as Th,useSelector as Cc}from"react-redux";import Eh from"lodash.debounce";var _c={root:"_root_1muu8_1",content:"_content_1muu8_7"};function Hn(t,e,o){var s;let n=((s=t.imageSizes)==null?void 0:s[e])||t.image||o;if(!n)return null;try{return new URL(n).toString()}catch{return null}}function Ir(t){return t.replace("https://www.","").replace("https://","")}import{jsx as Ze,jsxs as Ar}from"react/jsx-runtime";var kh=3,Rh=t=>({image:t.image||"",text:t.text,id:t.id,title:t.title}),Ph=({onSelectLink:t,onDismiss:e,placeholder:o,visitUrlText:n,linkCount:s=kh})=>{let r=S("LinkSearch",_c),[i,a]=bc(""),l=Th(),c=Cc(Ha("url")),p=Cc(ba("URL",Rh)),[u,d]=bc(p.length-1),m=b("fallbackImage"),f=h=>{let y=h.target;a(y.value)},g=(h,y)=>{h.stopPropagation(),h.preventDefault(),window.open(y,"_blank")},x=h=>{var C;let y=u-1<0?p.length-1:u-1,_=u+1===p.length?0:u+1;h.code==="Escape"&&(a(""),e()),h.code==="ArrowUp"&&d(y),h.code==="ArrowDown"&&d(_),h.code==="Enter"&&t(((C=p[u])==null?void 0:C.text)||i)},w=wh(Eh(h=>{l(Xe({query:h,type:"URL",tags:["link-search"]}))},300),[]);return xc(()=>{i&&w(i)},[i]),xc(()=>()=>{l(mn())},[]),Ar("div",{className:r.root,children:[Ze(re,{withDivider:!0,children:(i?p:c).slice(0,s).map((h,y)=>Ze(M,{selected:u===y,onClick:()=>t(h.text),"data-testid":"linksearch-suggestion",children:Ar(D,{children:[Ze(D.Image,{src:Hn(h,"small",m||void 0),title:h.title||h.text}),Ar(D.Content,{className:r.content,cropText:!0,children:[Ze(D.Title,{children:h.title||Ir(h.text)}),h.title&&Ir(h.text)]}),Ze(M.Actions,{children:Ze(M.ActionButton,{label:n,onClick:_=>g(_,h.text)})})]})},h.text))}),Ze(no,{value:i,onChange:f,autoFocus:!0,placeholder:o,onKeyUp:x})]})},wc=Ph;var Lr={};U(Lr,{enUS:()=>Ih,nlNL:()=>Ah});var Ih={insertLink:[{type:0,value:"Insert link"}],linkInputPlaceholder:[{type:0,value:"Search, type or paste link"}],visitUrl:[{type:0,value:"Visit"}]},Ah={insertLink:[{type:0,value:"Voeg link toe"}],linkInputPlaceholder:[{type:0,value:"Zoek, typ of plak link"}],visitUrl:[{type:0,value:"Bekijk"}]};import{jsx as fe,jsxs as Mr}from"react/jsx-runtime";var Hh=Oh((t,e)=>{let o=S("TabCompletion",ee);return fe("mark",{ref:e,className:Or(o.matchSelection)},"selection-start")}),Bh=({startRef:t,boundaryRef:e,inputStyle:o,inputElement:n,children:s})=>{let r=T(Lr),i=S("TabCompletion",ee),a=Ec(null),l=Ec(null),[c,p]=kc(null),u=Dh(),d=Lt(document.activeElement===n),[m]=kc(()=>document.createRange());d.triggerRef.current=m,Tc(()=>()=>m.detach(),[]),Tc(()=>{let g=t.current,x=a.current;!g||!x||(m.setStart(g,0),m.setEnd(x,0))},[t.current,a.current]),Me(()=>{d.close()});let f=Nh(g=>{let x=m.toString(),w=/^http(s?):\/\//.test(g)?g:`https://${g}`;u(Zo({text:`[${x}](${w})`,replace:"selection"}))},[]);return Mr("span",{children:[fe("mark",{ref:a,className:Or(i.matchSelection),"aria-haspopup":"dialog","aria-expanded":d.opened?"true":"false",children:s}),d.opened&&fe(Mt,{className:i.popoverRoot,triggerRef:d.triggerRef,boundaryRef:e,position:"above",align:"start",children:Mr(Nn,{style:o,ref:l,children:[fe("div",{className:Or(i.selectionOptions,{[i.selectionOptionsIsHidden]:c!==null}),children:Mr("button",{type:"button",tabIndex:c===null?-1:void 0,className:i.selectionOptionsButton,onClick:()=>p("insertLink"),children:[fe(vc,{}),fe("span",{children:"\xA0"}),fe("span",{children:r("insertLink")})]})}),c==="insertLink"&&fe(wc,{placeholder:r("linkInputPlaceholder"),visitUrlText:r("visitUrl"),onSelectLink:f,onDismiss:()=>{p(null),d.close()}})]})})]},"selection-end")},Bn=class extends Lh{charCount=0;foundIndex=0;startRef=null;props;onBeforeParse(e,o){return this.props=o,this.charCount=0,this.startRef=Mh(),this.foundIndex=0,e}match(e){if(!this.props||this.props.selection===null||this.foundIndex===2)return null;let[o,n]=this.props.selection;if(o===n)return null;let s=this.foundIndex===0?o:n,r=s>=this.charCount&&s<=this.charCount+e.length?{index:s-this.charCount,length:0,match:"",valid:!0}:null;r&&this.foundIndex++;let i=this.foundIndex===1;return r&&i?this.charCount+=s-this.charCount:this.charCount+=e.length,r?{isStart:i,...r}:null}replaceWith(e,o){return o.isStart?fe(Hh,{ref:this.startRef}):fe(Bh,{inputElement:o.inputElement,startRef:this.startRef,boundaryRef:o.boundaryRef,inputStyle:o.inputStyle})}asTag(){return"mark"}};import{jsx as Ot,jsxs as Wh}from"react/jsx-runtime";var qh=({enabled:t,content:e,tabText:o,showTabHint:n,showTabCompletion:s,showStyleSuggestions:r,keywordMatches:i,inputElement:a,source:l})=>{let c=S("TabCompletion",cc),p=b("insertLink"),u=b("showMidSentenceSuggestions"),d=b("inlineSuggestions"),m=rn(a),f=zh(null);Uh(()=>{ge(a)&&m&&an(a,m)},[m]);let g=Kh(h=>{if(!s||!o)return h;let y=[Ot("span",{className:c.resetIndent,children:"\u200B"},"u200B"),Ot("span",{"data-testid":"tab-completion",className:Nr(c.tabText,c.resetIndent),"data-source":l,children:o},"tabText")];return n&&y.push(Ot("span",{className:Nr(c.hint,c.resetIndent),children:Ot(hs,{keyCode:"tab"},"tabHint")})),Tr(h,y)},[s,o,n]),x=Rc(()=>{let h=[];return d&&h.push(new Mn("inline")),p&&h.push(new Bn("selection")),h.push(new gt("placeholders")),r&&h.push(new Dn("keywords")),h},[d,p,r]),w=Rc(()=>{let h=window.getComputedStyle(a);return{"--dd-color":h.color,"--dd-font-size":h.fontSize,"--dd-font-family":h.fontFamily,"--dd-font-variant":h.fontVariant}},[]);return t?Wh("div",{ref:h=>{h!=null&&h.parentElement&&(f.current=h==null?void 0:h.parentElement)},className:c.root,style:w,children:[Ot(Fh,{tagName:"span",containerTagName:"div",className:Nr(c.container,c.agentText),disableLineBreaks:ge(a),content:e||"\u200B",onAfterParse:g,matchers:x,selection:m,keywordMatches:i,inputElement:a,inputStyle:w,boundaryRef:f,inlineSuggestionsOnlyAtEnd:!u}),Ot("br",{})]}):null},Vh=({input:t,ui:e,settings:o,styleSuggestions:n,conversation:s})=>{var g;let{tabCompletionSuggestion:r}=t,i=(r==null?void 0:r.text)||"",a=(r==null?void 0:r.source)||"",l=t.html??lo(t.text),c=i.indexOf(t.text)===0?i.slice(t.text.length):"",{showTabHint:p}=e,{isSupported:u}=s,{showTabCompletion:d,visible:m,showStyleSuggestions:f}=o;return{showTabHint:p,showStyleSuggestions:f,showTabCompletion:d,content:l,tabText:c,source:a,keywordMatches:((g=n.list)==null?void 0:g.keywordMatches)??[],enabled:m&&u!==!1}},Pc=jh(Vh)(qh);import Py from"classnames";import{useEffect as Iy}from"react";import{useDispatch as Ay,useSelector as Q}from"react-redux";import{createAsyncThunk as go,createSlice as Gh}from"@reduxjs/toolkit";var Ic={list:[],fetchState:"idle",isInitialRequest:null},Lc=t=>t.autoflows.list||[],Ac=t=>e=>{var o;return(o=e.list)==null?void 0:o.find(n=>n.triggerPayload===t)},ke=go("autoflows/getAll",async(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");return o.getAutoflows(t)}),Dr=go("autoflows/start",async(t,e)=>{let{dispatch:o}=e,{deepdeskBrokerAPI:n}=e.extra;if(!n)throw new Error("Deepdesk Broker not initialized");await n.startAutoflowSession(t),await o(ke(t.platformSessionId))}),Hr=go("autoflows/stop",async(t,e)=>{let{dispatch:o}=e,{deepdeskBrokerAPI:n}=e.extra;if(!n)throw new Error("Deepdesk Broker not initialized");await n.stopAutoflowSession(t.platformSessionId),await o(ke(t.platformSessionId))}),$h=Gh({name:"autoflows",initialState:Ic,reducers:{},extraReducers:t=>{t.addCase(Dr.pending,(e,o)=>{let n=Ac(o.meta.arg.triggerPayload)(e);n.state="Started",n.isBusy=!0}),t.addCase(Hr.pending,(e,o)=>{let n=Ac(o.meta.arg.triggerPayload)(e);n.state="Aborted",n.isBusy=!0}),t.addCase(ke.pending,e=>{e.isInitialRequest=e.isInitialRequest===null,e.fetchState="loading"}),t.addCase(ke.rejected,e=>{e.fetchState="error"}),t.addCase(ke.fulfilled,(e,o)=>{e.list=o.payload,e.fetchState="done"}),t.addCase(R,()=>Ic)}}),Mc=go("autoflows/openStream",(t,e)=>{let{dispatch:o}=e,{deepdeskBrokerAPI:n}=e.extra;if(!n)throw new Error("Deepdesk Broker not initialized");let s=n.openStream(t);s.on("sessionAborted",()=>{o(ke(t))}),s.on("sessionCompleted",()=>{o(ke(t))})}),Oc=go("autoflows/closeStream",(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");o.closeStream(t)}),Nc=$h.reducer;import{createAsyncThunk as fo,createSlice as Xh}from"@reduxjs/toolkit";var Dc={list:[],fetchState:"idle",isInitialRequest:null,sentSuggestions:[],errorSuggestions:[],answeredSuggestions:[]},Hc=t=>t.customMessages.list,Bc=t=>e=>!!e.customMessages.sentSuggestions.find(o=>o===t),Fc=t=>e=>!!e.customMessages.answeredSuggestions.find(o=>o===t),Kc=t=>e=>!!e.customMessages.errorSuggestions.find(o=>o===t),mo=fo("customMessages/getAll",async(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");return o.getCustomMessages(t)}),Fn=fo("customMessages/send",async(t,e)=>{let{platformSessionId:o,suggestion:n}=t,{deepdeskBrokerAPI:s}=e.extra;if(!s)throw new Error("Deepdesk Broker not initialized");await s.sendCustomMessage(o,n)}),Kn=fo("customMessages/answer",async(t,e)=>{let{platformSessionId:o,reply:n}=t,{deepdeskBrokerAPI:s}=e.extra;if(!s)throw new Error("Deepdesk Broker not initialized");await s.answerCustomMessage(o,n)}),Uc=Xh({name:"customMessages",initialState:Dc,reducers:{onCustomMessage(t,e){Array.isArray(e.payload)?t.list=e.payload:t.list=[e.payload]}},extraReducers:t=>{t.addCase(mo.pending,e=>{e.isInitialRequest=e.isInitialRequest===null,e.fetchState="loading"}).addCase(mo.rejected,e=>{e.fetchState="error"}).addCase(mo.fulfilled,(e,o)=>{e.fetchState="done",e.list=o.payload||[]}).addCase(Fn.pending,(e,o)=>{e.sentSuggestions.push(o.meta.arg.suggestion.text),e.errorSuggestions=e.errorSuggestions.filter(n=>o.meta.arg.suggestion.text!==n)}).addCase(Fn.rejected,(e,o)=>{let n=e.sentSuggestions.indexOf(o.meta.arg.suggestion.text);e.errorSuggestions.push(...e.sentSuggestions.splice(n,1))}).addCase(Kn.pending,(e,o)=>{e.sentSuggestions.push(o.meta.arg.suggestion.text),e.answeredSuggestions.push(o.meta.arg.suggestion.text)}).addCase(Kn.rejected,(e,o)=>{let n=e.answeredSuggestions.indexOf(o.meta.arg.suggestion.text);e.errorSuggestions.push(...e.sentSuggestions.splice(n,1)),e.answeredSuggestions.splice(n,1)}).addCase(R,()=>Dc)}}),zc=fo("customMessages/openStream",(t,e)=>{let{dispatch:o}=e,{deepdeskBrokerAPI:n}=e.extra;if(!n)throw new Error("Deepdesk Broker not initialized");n.openStream(t).on("customMessageSuggestion",r=>{o(Uc.actions.onCustomMessage(r))})}),jc=fo("customMessages/closeStream",(t,e)=>{let{deepdeskBrokerAPI:o}=e.extra;if(!o)throw new Error("Deepdesk Broker not initialized");o.closeStream(t)}),qc=Uc.reducer;import{createAsyncThunk as Vc,createSlice as Qh}from"@reduxjs/toolkit";var Zh={jwt:null,accountUrl:null,interval:null},Wc=t=>e=>{let{exchangeToken:{jwt:o,accountUrl:n}}=e;return o&&n?`${n}/apis/admin/session/jwt/?jwt=${o}&redirect=${t}`:null},Br=Vc("exchangeToken/getTemporaryExchangeToken",async(t,e)=>{let{deepdeskAPI:o}=e.extra,n=await o.getTemporaryExchangeToken();return{accountUrl:o.client.baseUrl,jwt:n}}),Fr=Vc("exchangeToken/pollExchangeToken",(t={},e)=>{let{interval:o=1e3*60*30}=t,{dispatch:n}=e;return n(Br()),setInterval(()=>n(Br()),o)}),Gc=Qh({name:"exchangeToken",initialState:Zh,reducers:{stopPollExchangeToken(t){t.interval&&clearInterval(t.interval),t.interval=null}},extraReducers:t=>{t.addCase(Br.fulfilled,(e,o)=>{e.jwt=o.payload.jwt,e.accountUrl=o.payload.accountUrl}),t.addCase(Fr.fulfilled,(e,o)=>{e.interval=o.payload})}}),{stopPollExchangeToken:$c}=Gc.actions,Xc=Gc.reducer;function Qc(t){let{customMessages:e,autoflows:o}=t;return o.fetchState==="loading"&&o.isInitialRequest===!0||e.fetchState==="loading"&&e.isInitialRequest===!0}import{Fragment as ay}from"react";import{connect as ly}from"react-redux";import sy from"classnames";import{Fragment as ry}from"react";import Jh from"classnames";var Zc={root:"_root_838fd_1"};import{jsx as ey}from"react/jsx-runtime";var Yh=({className:t,children:e})=>{let o=S("Unicode",Zc);return ey("span",{className:Jh(t,o.root),children:e})},Jc=Yh;var Yc={isDisabled:"_isDisabled_1rmfm_1",buttonStart:"_buttonStart_1rmfm_5",root:"_root_1rmfm_8",buttonStop:"_buttonStop_1rmfm_8",stateBadge:"_stateBadge_1rmfm_19",isCompleted:"_isCompleted_1rmfm_26",isStarted:"_isStarted_1rmfm_30",isAborted:"_isAborted_1rmfm_34"};var Kr={};U(Kr,{enUS:()=>ty,nlNL:()=>oy});var ty={start:[{type:0,value:"Start"}],stop:[{type:0,value:"Stop"}],aborted:[{type:0,value:"Stopped"}],completed:[{type:0,value:"Completed"}],Aborted:[{type:0,value:"Stopped"}],Started:[{type:0,value:"Running"}],Completed:[{type:0,value:"Completed"}]},oy={start:[{type:0,value:"Start"}],stop:[{type:0,value:"Stop"}],aborted:[{type:0,value:"Stopped"}],completed:[{type:0,value:"Completed"}],Aborted:[{type:0,value:"Stopped"}],Started:[{type:0,value:"Running"}],Completed:[{type:0,value:"Completed"}]};import{jsx as Je,jsxs as Un}from"react/jsx-runtime";var iy=({disabled:t,state:e,displayName:o,description:n,onStartAutoflow:s,onStopAutoflow:r})=>{let i=S("Autoflow",Yc),a=T(Kr),l=e==="Started"?"stop":"start",c=l==="start"?"\u25B6":l==="stop"?"\u25FC":"";return Un(M,{className:sy(i.root,{[i.isDisabled]:t,[i.isCompleted]:e==="Completed",[i.isAborted]:e==="Aborted",[i.isStarted]:e==="Started"}),children:[Je(D,{children:Un(D.Content,{children:[Un(D.Title,{children:[e&&Je("span",{className:i.stateBadge,children:a(e)}),o]}),Je("span",{children:n})]})}),Je(M.Actions,{fixed:e==="Started",children:Je(M.ActionButton,{primary:!0,className:l==="start"?i.buttonStart:i.buttonStop,onClick:e==="Started"?r:s,disabled:t,label:Un(ry,{children:[Je(Jc,{children:c})," ",Je("span",{children:a(l)})]})})})]})},ep=iy;import{jsx as tp}from"react/jsx-runtime";var cy=(t,e)=>{let o=e.filter(n=>n.state==="Started");return o.length>0?o.indexOf(t)===-1:!1},py=({autoflows:t,onStartAutoflow:e,onStopAutoflow:o,platformSessionId:n})=>tp(ay,{children:t.map(s=>tp(ep,{displayName:s.displayName,description:s.description,disabled:s.isBusy||cy(s,t),state:s.state,onStartAutoflow:()=>e({platformSessionId:n,triggerPayload:s.triggerPayload}),onStopAutoflow:()=>o({platformSessionId:n,triggerPayload:s.triggerPayload})},s.displayName))}),uy=({autoflows:t,conversation:e})=>{var o;return{autoflows:t.list,platformSessionId:(o=e.current)==null?void 0:o.sessionId}},dy={onStartAutoflow:Dr,onStopAutoflow:Hr},op=ly(uy,dy)(py);import{useEffect as gy,useState as my}from"react";import{useDispatch as fy}from"react-redux";import rp from"classnames";import{jsx as np}from"react/jsx-runtime";var Ur=()=>np("svg",{width:"1em",height:"1em",viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",children:np("path",{d:"M502.6 70.63l-61.25-61.25C435.4 3.371 427.2 0 418.7 0H255.1c-35.35 0-64 28.66-64 64l.0195 256C192 355.4 220.7 384 256 384h192c35.2 0 64-28.8 64-64V93.25C512 84.77 508.6 76.63 502.6 70.63zM464 320c0 8.836-7.164 16-16 16H255.1c-8.838 0-16-7.164-16-16L239.1 64.13c0-8.836 7.164-16 16-16h128L384 96c0 17.67 14.33 32 32 32h47.1V320zM272 448c0 8.836-7.164 16-16 16H63.1c-8.838 0-16-7.164-16-16L47.98 192.1c0-8.836 7.164-16 16-16H160V128H63.99c-35.35 0-64 28.65-64 64l.0098 256C.002 483.3 28.66 512 64 512h192c35.2 0 64-28.8 64-64v-32h-47.1L272 448z"})});var sp={root:"_root_rjdyr_1",entity:"_entity_rjdyr_10",entityText:"_entityText_rjdyr_46",iconWrapper:"_iconWrapper_rjdyr_53",icon:"_icon_rjdyr_53",iconClicked:"_iconClicked_rjdyr_67"};import{jsx as Nt,jsxs as ip}from"react/jsx-runtime";var hy=({entities:t})=>{let e=S("EntitiesWidgetList",sp),[o,n]=my(void 0),s=fy(),r=()=>{n(void 0)},i=a=>{t&&(n(t.indexOf(a)),ro(a.text),s(J({name:"entity copied",data:{entity:a,type:"copy"}})))};return gy(()=>{let a=setTimeout(r,500);return()=>{clearTimeout(a)}},[o]),!t||t.length===0?null:Nt("div",{className:e.root,"data-testid":"widget-entities-list",children:t.map((a,l)=>ip("button",{title:a.text,className:e.entity,type:"button",onClick:()=>i(a),children:[Nt("span",{className:e.entityText,children:a.text}),ip("span",{className:e.iconWrapper,children:[Nt("span",{className:rp(e.icon),children:Nt(Ur,{})}),Nt("span",{className:rp(e.icon,o===l&&e.iconClicked),children:Nt(Ur,{})})]})]},a.text))})},ap=hy;import vy from"classnames";import{useCallback as lp}from"react";import{useDispatch as _y,useSelector as zn}from"react-redux";var ho={};U(ho,{enUS:()=>yy,nlNL:()=>Sy});var yy={preview:[{type:0,value:"Preview"}],useSuggestion:[{type:0,value:"Add"}],sendSuggestion:[{type:0,value:"Send"}],suggestionSent:[{type:0,value:"Sent"}],sendingError:[{type:0,value:"Sending failed"}],tryAgain:[{type:0,value:"Try again"}],editSuggestion:[{type:0,value:"Edit"}],visitUrl:[{type:0,value:"Visit"}],answer:[{type:0,value:"Answer"}]},Sy={preview:[{type:0,value:"Preview"}],useSuggestion:[{type:0,value:"Gebruik"}],sendSuggestion:[{type:0,value:"Verzenden"}],suggestionSent:[{type:0,value:"Verzonden"}],sendingError:[{type:0,value:"Verzenden mislukt"}],tryAgain:[{type:0,value:"Probeer opnieuw"}],editSuggestion:[{type:0,value:"Bewerken"}],visitUrl:[{type:0,value:"Bekijk"}],answer:[{type:0,value:"Antwoord"}]};var Re={root:"_root_1e6ej_1",title:"_title_1e6ej_8",isUsed:"_isUsed_1e6ej_13",quickReplies:"_quickReplies_1e6ej_22",quickReply:"_quickReply_1e6ej_29",hasError:"_hasError_1e6ej_39",label:"_label_1e6ej_43",errorIcon:"_errorIcon_1e6ej_48"};import{jsx as Fe,jsxs as jn}from"react/jsx-runtime";var xy=({suggestion:t})=>{let e=T(ho),o=_y(),n=zn(Bc(t.text)),s=zn(Fc(t.text)),r=zn(Kc(t.text)),i=zn(jo),{replyOptions:a}=t,l=lp(p=>{p.preventDefault(),p.stopPropagation(),!(n||!i)&&o(Fn({platformSessionId:i,suggestion:t}))},[t,n,o,i]),c=lp(p=>{if(p.preventDefault(),p.stopPropagation(),!i||!a)return;let u=parseInt(p.target.dataset.index,10),d=a[u];o(Kn({platformSessionId:i,reply:d,suggestion:t}))},[t,n,o,i]);return jn(M,{onClick:l,className:vy(Re.root,{[Re.isUsed]:n,[Re.hasError]:r}),children:[Fe(D,{children:jn(D.Content,{children:[jn(D.Title,{className:Re.title,children:[t.text," ",Fe(ys,{className:Re.label,children:"analyse tool"})," ",r&&Fe("span",{className:Re.errorIcon,role:"img","aria-label":e("sendingError"),title:e("sendingError"),children:"!"})]}),a&&a.length>0&&Fe("ul",{className:Re.quickReplies,children:a.map(p=>Fe("li",{className:Re.quickReply,children:p.title},p.title))})]})}),jn(M.Actions,{fixed:r||n,children:[a&&a.length>0&&Fe(M.DropdownButton,{label:e("answer"),disabled:s,children:a.map((p,u)=>Fe(M.DropdownItem,{index:u,label:p.title,onClick:c},p.title))}),Fe(M.ActionButton,{primary:!0,disabled:n,onClick:l,label:e(n?"suggestionSent":r?"tryAgain":"sendSuggestion")})]})]})},cp=xy;import{jsx as pp}from"react/jsx-runtime";var up=()=>pp("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:pp("path",{d:"M17 13.5v6H5v-12h6m3-3h6v6m0-6-9 9",stroke:"currentColor",strokeWidth:"1.5",fill:"none",fillRule:"evenodd",strokeLinecap:"round",strokeLinejoin:"round"})});import{useSelector as wy}from"react-redux";import{useCallback as by}from"react";import{jsx as Ye,jsxs as qn}from"react/jsx-runtime";var Cy=({suggestion:t,lines:e,onEdit:o,onUse:n})=>{var d;let s=t.text||t.url||t.message,r=fn(s),i=T(ho),a=b("showImages"),l=b("fallbackImage"),c=m=>{m.preventDefault(),m.stopPropagation(),n(s)},p=m=>{m.preventDefault(),m.stopPropagation(),o(t)},u=by(m=>{window.open(r,"_blank"),m.stopPropagation(),m.preventDefault()},[r]);return qn(M,{onClick:c,"data-testid":"edit-suggestion",children:[qn(D,{children:[a&&t.image&&Ye(D.Image,{src:Hn(t,"small",l||void 0),title:t.title}),qn(D.Content,{children:[t.title&&Ye(D.Title,{"data-testid":"widget-suggestion-title",children:t.title}),t.searchKeywords&&((d=t.searchKeywords)==null?void 0:d.length)>0&&Ye(M.Labels,{labels:t.searchKeywords}),Ye(D.Content,{cropText:e==="single",lineClamp:e==="multiple",children:s})]})]}),qn(M.Actions,{children:[r&&Ye(M.ActionButton,{onClick:u,label:i("visitUrl")}),Ye(M.ActionButton,{primary:!0,onClick:p,label:i("preview")}),Ye(M.ActionButton,{primary:!0,onClick:c,label:i("useSuggestion")})]})]})},dp=Cy;import{Fragment as Ey,jsx as gp}from"react/jsx-runtime";var Ty=({contentType:t,lines:e,suggestions:o})=>{let n=te(),s=wy(_t),r=a=>{n.send(tr,{state:s,suggestion:a,contentType:t})},i=(a,l)=>{n.send(Ce,{text:a,suggestion:{...l,source:l.source,sourceText:l.text}})};return gp(Ey,{children:o.map(a=>gp(dp,{suggestion:a,lines:e,onEdit:l=>r(l),onUse:l=>i(l,a)},a.text||a.url||a.message))})},mp=Ty;var zr={};U(zr,{enUS:()=>ky,nlNL:()=>Ry});var ky={waiting:[{type:0,value:"Loading\u2026"}],notSupported:[{type:0,value:"This conversation is not supported"}],noResults:[{type:0,value:"No results found\u2026"}],titleAutoflows:[{type:0,value:"Autoflows"}],titleCustomMessages:[{type:0,value:"Quick replies"}],actions:[{type:0,value:"Shortcuts"}],linkPersonalcollection:[{type:0,value:"Personal Collection"}],linkSummary:[{type:0,value:"Summarize"}],linkKnowledgeSearch:[{type:0,value:"Knowledge Assist"}],linkSearch:[{type:0,value:"Search"}]},Ry={waiting:[{type:0,value:"Laden\u2026"}],notSupported:[{type:0,value:"Dit gesprek wordt niet ondersteund"}],noResults:[{type:0,value:"Geen resultaten gevonden\u2026"}],titleAutoflows:[{type:0,value:"Autoflows"}],titleCustomMessages:[{type:0,value:"Quick replies"}],actions:[{type:0,value:"Shortcuts"}],linkPersonalcollection:[{type:0,value:"Personal Collection"}],linkSummary:[{type:0,value:"Gesprek samenvatten"}],linkKnowledgeSearch:[{type:0,value:"Knowledge assist"}],linkSearch:[{type:0,value:"Zoeken"}]};var fp={root:"_root_x0pwe_1",loginText:"_loginText_x0pwe_7",stateText:"_stateText_x0pwe_8",sectionList:"_sectionList_x0pwe_20",shortcutList:"_shortcutList_x0pwe_24",shortcut:"_shortcut_x0pwe_24",link:"_link_x0pwe_52"};import{jsx as hp}from"react/jsx-runtime";var yp=()=>hp("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:hp("path",{d:"M543-340q16.595 0 28.798-12.202Q584-364.405 584-381t-12.202-28.798Q559.595-422 543-422t-28.798 12.202Q502-397.595 502-381t12.202 28.798Q526.405-340 543-340Zm-25-126h47q2-29 8.5-43t32.5-39q27-26 37.5-45.395Q654-612.79 654-639q0-45.882-31.5-74.941Q591-743 540-743q-38 0-68 20.5T428-665l45 19q11-25 27.5-38t39.5-13q29.778 0 48.389 17Q607-663 607-637q0 20-9 35t-32 32q-32 29-40 46.5t-8 57.5ZM260-200q-24 0-42-18t-18-42v-560q0-24 18-42t42-18h560q24 0 42 18t18 42v560q0 24-18 42t-42 18H260Zm0-60h560v-560H260v560ZM140-80q-24 0-42-18t-18-42v-620h60v620h620v60H140Zm120-740v560-560Z"})});import{jsx as Sp}from"react/jsx-runtime";var vp=()=>Sp("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:Sp("path",{d:"M319-250h322v-60H319v60Zm0-170h322v-60H319v60ZM220-80q-24 0-42-18t-18-42v-680q0-24 18-42t42-18h361l219 219v521q0 24-18 42t-42 18H220Zm331-554v-186H220v680h520v-494H551ZM220-820v186-186 680-680Z"})});import{jsx as L,jsxs as Dt}from"react/jsx-runtime";var Vn=(t,e)=>{let o=Q(ae);Iy(()=>o?e.every(n=>!!n)?t():()=>{}:()=>{},[...e,o])},Ly=()=>{let t=T(zr),e=Ay(),o=b("isEmbedded"),n=S("Widget",fp),s=b("showAutoflows"),r=b("showCustomMessages"),i=b("showPersonalCollectionLink"),a=b("showSummaryCommand"),l=b("showKnowledgeSearch"),c=b("showSearch"),p=Q(Rt),u=Q(wn),d=Q(Lc),m=Q(xn),f=Q(Hc),g=Q(qo),x=Q(pt),w=Q(ae),h=Q(jo),y=Q(Qc),_=Q(_t),C=te(),H=Q(Fa),O=Q(Wc("/admin/personal-collection")),ce=b("adminUrl");if(Vn(()=>(e(mo(h)),e(zc(h)),()=>{e(jc(h))}),[e,x,r,h]),Vn(()=>(e(ke(h)),e(Mc(h)),()=>{e(Oc(h))}),[e,x,s,h]),Vn(()=>{u.forEach(({type:k})=>{e(k==="entities"?le():xe(k))})},[e,x,g,p]),Vn(()=>(e(Fr()),()=>{e($c())}),[e,x,i,g]),x===!1)return L("div",{className:n.stateText,children:L("div",{children:L("p",{children:t("notSupported")})})},"supported");if(w===!1)return L("div",{className:n.loginText,children:L("div",{children:L(Pn,{isEmbedded:o,loginUrl:ce})})},"login");if(!p||!h||w===null||H||y)return L("div",{className:n.stateText,children:L("div",{children:L("p",{children:t("waiting")})})},"waiting");let N=c||a||l||O;return L("div",{className:Py(n.root),"data-testid":"widget",children:Dt(vs,{className:n.sectionList,children:[N&&L(je,{title:t("actions"),type:"shortcuts",children:Dt("div",{className:n.shortcutList,children:[c&&Dt("button",{className:n.shortcut,"data-testid":"shortcut-search",onClick:()=>C.send("ShowCommandPalette",{isOpen:!0}),children:[L(St,{}),t("linkSearch")]}),a&&Dt("button",{className:n.shortcut,"data-testid":"shortcut-summary",onClick:()=>C.send("ShowCommandPalette",{isOpen:!0,page:"summary"}),children:[L(vp,{}),t("linkSummary")]}),l&&Dt("button",{className:n.shortcut,"data-testid":"shortcut-knowledge-assist",onClick:()=>C.send("ShowCommandPalette",{isOpen:!0,page:"knowledgeAssist"}),children:[L(yp,{}),t("linkKnowledgeSearch")]}),O&&Dt("a",{className:n.shortcut,target:"_blank",href:O,"data-testid":"shortcut-personal-collection",rel:"noreferrer",children:[L(up,{}),t("linkPersonalcollection")]})]})}),r&&f.length>0&&L(je,{type:"custom-messages","data-testid":"custom-messages",children:L(re,{withDivider:!0,children:f.map(k=>L(cp,{suggestion:k},k.text))})}),s&&d.length>0&&L(je,{type:"autoflows",title:t("titleAutoflows"),"data-testid":"autoflows",children:L(re,{withDivider:!0,children:L(op,{})})}),u.map(({type:k,title:V,amount:oe,lines:ts})=>{var Ue;switch(k){case"entities":return m&&m.length>0&&L(je,{type:k,title:V,"data-testid":`type-${k}`,children:L(ap,{entities:m})},k);default:return((Ue=_[k])==null?void 0:Ue.fetchState)==="done"&&_[k].suggestions.length>0&&L(je,{type:k,title:V,"data-testid":`type-${k}`,children:L(re,{withDivider:!0,children:L(mp,{lines:ts,contentType:k,suggestions:_[k].suggestions.slice(0,oe)||[]})})},k)}})]})})},_p=Ly;function So(t){let e=new Range;return e.selectNodeContents(t),e}function xp(t,e,o){try{return et(t,e,o),!0}catch{return!1}}function Wn(t){return"tagName"in t&&(t.tagName==="DIV"||t.tagName==="P")}function Gn(t){return"tagName"in t&&t.tagName==="BR"}var yo=/[\u200B-\u200D\uFEFF]/g;function et(t,e,o){let n=new Range;if(t.firstChild===null&&e===0&&o===0)return n.selectNodeContents(t),n;let s=0,r=!1;function i(l,c){let p=-1,u=/[\u200B-\u200D\uFEFF]/;if(!u.test(l))return c;for(let d=0;d<=l.length;d++)if(u.test(l[d])||p++,p===c)return d;throw new Error("Offset out of range")}function a(l){switch(l.nodeType){case Node.TEXT_NODE:{let c=l.textContent,p=c.replace(yo,""),u=s+p.length,d=e>=s&&e<=u,m=o>=s&&o<=u;if(d){let f=i(c,e-s);f===0&&!m?n.setStartBefore(l):n.setStart(l,f)}m&&(n.setEnd(l,i(c,o-s)),r=!0),s=u;break}case Node.ELEMENT_NODE:{if(Gn(l)&&(s===e&&n.setStartBefore(l),s++,s===o)){n.setEndAfter(l),r=!0;return}for(let p=0;p<l.childNodes.length&&(a(l.childNodes[p]),!r);p++);let c=l.lastChild;Wn(l)&&c&&!Wn(c)&&!Gn(c)&&s++;break}default:break}}if(a(t),n.startContainer===document)throw new Error("Offsets out of bound");return n}function $n(t,e){if(!t.contains(e.startContainer)||!t.contains(e.endContainer))throw new Error("Range not within root element");let{startContainer:o,startOffset:n,endContainer:s,endOffset:r,collapsed:i}=e,a,l,c=0;function p(u){let d=u===o,m=u===s;switch(u.nodeType){case Node.TEXT_NODE:{let f=u.textContent;d&&(a=c+f.substring(0,n).replace(yo,"").length),m&&(l=c+f.substring(0,r).replace(yo,"").length),c+=f.replace(yo,"").length;break}case Node.ELEMENT_NODE:{let f=u.nextSibling===null;Gn(u)&&!f&&c++;for(let g=0;g<u.childNodes.length;g++){let x=d&&g===n,w=m&&g===r;if(x&&(a=c),w&&(l=c),l!==void 0||((!x||!i)&&p(u.childNodes[g]),m&&g===r-1&&(l=c),l!==void 0))break}!m&&Wn(u)&&!f&&c++,m&&(l=c);break}default:break}}if(p(t),l===void 0)throw new Error("Could not determine start and end");return{start:a??l,end:l}}function Xn(t,e){if(!t.contains(e.startContainer)||!t.contains(e.endContainer))throw new Error("Range not within root element");let{startContainer:o,startOffset:n,endContainer:s,endOffset:r}=e,i=-1,a="";function l(c){let p=c===o,u=c===s;switch(p&&i++,c.nodeType){case Node.TEXT_NODE:{if(i!==0)return;let d=p?n:0,m=u?r:void 0,f=c.textContent.replace(yo,"");d===0&&m===void 0?a+=f:a+=f.substring(d,m);break}case Node.ELEMENT_NODE:{let d=c.nextSibling===null;i===0&&Gn(c)&&!d&&(a+=`
|
|
4
|
+
`);for(let m=p?n:0;m<(u?Math.min(r,c.childNodes.length):c.childNodes.length)&&(l(c.childNodes[m]),i!==1);m++);!u&&i===0&&Wn(c)&&!d&&(a+=`
|
|
5
|
+
`);break}default:break}u&&i++}return l(t),a}function bp(t){return t.top!==0||t.left!==0||t.height!==0||t.width!==0}var Ht=class extends Oe{observer;lastKnownSelection=null;getRootNode(){return this.element.getRootNode()}getText(){let e=new Range;return e.selectNodeContents(this.element),Xn(this.element,e)}getHTML(){return this.element.innerHTML||""}getRange(){var r;let e=this.getRootNode();if(e.activeElement!==this.element)return null;let o="getSelection"in e?e.getSelection():window.getSelection();if(!o)return null;let n="getComposedRanges"in o&&e instanceof ShadowRoot?(r=o.getComposedRanges(e))==null?void 0:r[0]:o.rangeCount>0?o.getRangeAt(0):null;if(!n)return null;let s=this.element.ownerDocument.createRange();return s.setStart(n==null?void 0:n.startContainer,n==null?void 0:n.startOffset),s.setEnd(n==null?void 0:n.endContainer,n==null?void 0:n.endOffset),!s||!this.element.contains(s.startContainer)||!this.element.contains(s.endContainer)?null:s}getCaretPosition(){let e=this.getRange();if(!e||!e.collapsed||!("getBoundingClientRect"in e))return null;let o=e.getBoundingClientRect();return!bp(o)&&(e.insertNode(this.element.ownerDocument.createTextNode("\u2060")),o=e.getBoundingClientRect(),e.deleteContents(),!bp(o))?null:{top:o.top+o.height,left:o.left}}getSelection(){let e=this.getRange();if(e)return $n(this.element,e);let o=this.lastKnownSelection;if(o&&xp(this.element,o.start,o.end))return o;let n=So(this.element);return n.collapse(!1),$n(this.element,n)}getSelectedText(){let{start:e,end:o}=this.getSelection();return Xn(this.element,et(this.element,e,o))}applyChanges(e){var s;if(!this.isActive)return;this.isSettingValue=!0;let o=this.getText(),n=e(this.element);return(s=this.observer)==null||s.takeRecords(),Promise.resolve(n).then(()=>{this.currentText=this.getText(),o!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(){super.listen(),this.observer=new MutationObserver(()=>{setTimeout(()=>{this.triggerChange()},0)}),this.observer.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0});let e=this.element.isContentEditable,o=new MutationObserver(()=>{this.element.isContentEditable!==e&&(e=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>o.disconnect())}dispose(){super.dispose(),this.observer&&this.observer.disconnect()}};var jr=class{constructor(e){this.name=e;this.broadcastChannel=new BroadcastChannel(e)}broadcastChannel;disposeHandlers=[];onMessage(e){this.broadcastChannel.addEventListener("message",e),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",e)})}postMessage(e){this.broadcastChannel.postMessage(e)}close(){this.disposeHandlers.forEach(e=>e()),this.broadcastChannel.close()}},qr=class{constructor(e,o,n){this.name=e;this.targetOrigin=o;this.options=n;this.iframe=this.createIframe(),document.body.appendChild(this.iframe)}iframe;disposeHandlers=[];createIframe(){let e=`deepdesk-iframe-${this.name}`,o=document.getElementById(e);if(o)return o;let n=document.createElement("iframe"),s=`${this.targetOrigin}/v2/widget/liveengage/channel.html`,r=new URLSearchParams({channel:this.name,host:window.location.origin});return this.options.debug&&r.set("debug","1"),n.style.position="absolute",n.style.left="-999em",n.style.width="0px",n.style.height="0px",n.tabIndex=-1,n.id=e,n.title=`iframe-${this.name}`,n.src=`${s}?${r.toString()}`,n}onMessage(e){window.addEventListener("message",e),this.disposeHandlers.push(()=>{window.removeEventListener("message",e)})}postMessage(e){var o;(o=this.iframe.contentWindow)==null||o.postMessage(e,this.targetOrigin)}close(){var e;this.disposeHandlers.forEach(o=>o()),(e=this.iframe)==null||e.remove()}},Vr=class{constructor(e){this.params=e;this.deepdeskUrl=e.deepdeskUrl,this.eventMap=e.eventMap,this.defaultChannel=this.createChannel("deepdesk-general")}sessionId;deepdeskUrl;channel;defaultChannel;eventMap;get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setSessionId(e){this.sessionId!==e&&(this.cleanup(),E.info("Set sessionId",e),this.sessionId=e,this.channel=this.createChannel(e))}createChannel(e){let o=this.params.createCustomChannel?this.params.createCustomChannel(e):this.isCrossOrigin?new qr(e,this.deepdeskUrl,{debug:!0}):new jr(e),n=s=>{var r,i;s.origin===this.deepdeskUrl&&s.data.type==="event"&&s.data.channel===e&&(E.info("Received broadcast event",this.sessionId,s),(i=(r=this.eventMap)[s.data.name])==null||i.call(r,s.data.payload))};return o.onMessage(n),o}send(e,o){var s,r,i;if(!this.sessionId)return;E.info("broadcast event",{sessionId:this.sessionId,name:e,payload:o});let n={type:"event",name:e,payload:o};(r=(s=this.eventMap)[e])==null||r.call(s,o),(i=this.channel)==null||i.postMessage({...n,channel:this.sessionId})}cleanup(e=!1){var o,n;(o=this.channel)==null||o.close(),delete this.channel,e&&((n=this.defaultChannel)==null||n.close(),delete this.defaultChannel)}},Cp=Vr;var Bt=class extends Error{constructor(o,n){super(o);this.body=n}name="CustomError"};var Wr=t=>new Promise(e=>{setTimeout(e,t)});var Ft=class extends Bt{name="ClientError"},Gr=class extends Bt{name="ServerError"},he=class t{constructor(e="",o={}){this.baseUrl=e;this.options=o;o.fetch&&(this.fetch=o.fetch)}latestRequestByUrl={};csrfToken;fetch=window.fetch.bind(window);static refreshingToken=null;patchFetch(e){this.fetch=e(this.fetch)}setCsrfToken(e){this.csrfToken=e}request(e,o={}){return new Promise((n,s)=>{let r={isAborted:!1,reject:s},i=`${this.baseUrl}${e}`,a=this.fetch,{abortLatest:l=!1,attempts:c=1,retryDelay:p=500,refreshTokenOn401:u=!0,retryOnError:d=_=>_ instanceof TypeError,retryOnResponse:m=_=>_.status>=500,version:f="v1",...g}=o,x={credentials:"include",...g,headers:{"Content-Type":"application/json",...g.headers}};o.method!==void 0&&o.method!=="GET"&&this.csrfToken&&(x.headers={...x.headers,"X-CSRFToken":this.csrfToken}),typeof f=="string"&&(x.headers={...x.headers,"X-Deepdesk-API-Version":f});let w=c,h=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[i]&&l&&(this.latestRequestByUrl[i].isAborted=!0,this.latestRequestByUrl[i].reject(new Error("Aborted"))),this.latestRequestByUrl[i]=r;let y=async()=>(w--,a(i,x).then(async _=>m(_)&&!r.isAborted&&w>0?(await Wr(p),y()):_.status===401&&u===!0&&h===!1?(h=!0,await this.refreshToken(),y()):_).catch(async _=>{if(d(_)&&!r.isAborted&&w>0)return await Wr(p),y();throw _}));y().then(_=>_.json().catch(()=>null).then(C=>{_.status>=500?s(new Gr("Server Error",C)):_.status===401?s(new Ft("Unauthorized",C)):_.status===403?s(new Ft("Forbidden",C)):_.status===404?s(new Ft("Not Found",C)):_.status>=400&&s(new Ft("Bad Request",C)),delete this.latestRequestByUrl[i],n(C)})).catch(_=>{s(_)})})}async validateToken(){let{has_valid_access_token:e}=await this.get("/auth/validate");if(!e)return!1;let{is_logged_in:o}=await this.get("/apis/admin/session/validate/",{version:null});return!!o}refreshToken(){return t.refreshingToken||(t.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{t.refreshingToken=null},1e3*60)})),t.refreshingToken}get(e,o){return this.request(e,o)}post(e,o,n){return this.request(e,{method:"POST",body:JSON.stringify(o),...n})}patch(e,o,n){return this.request(e,{method:"PATCH",body:JSON.stringify(o),...n})}put(e,o,n){return this.request(e,{method:"PUT",body:JSON.stringify(o),...n})}delete(e,o){return this.request(e,{method:"DELETE",...o})}};var My;(e=>{let t;(l=>(l.SEND_MESSAGE="Send Message",l.HANDLING_TIME="Handling Time",l.START_AUTOFLOW="Start Autoflow",l.ABORT_AUTOFLOW="Abort Autoflow",l.ADD_TO_PERSONAL_COLLECTION="Add to personal collection",l.DELETE_FROM_PERSONAL_COLLECTION="Delete from personal collection"))(t=e.EventType||={})})(My||={});function Qn(t){return{...A(t),tags:t.tags}}var Ke=class t{constructor(e,o={}){this.options=o;this.client=new he(e,{fetch:o.fetch}),this.client.patchFetch(n=>async(s,r)=>{let i=await n(s,r);return this.handleDeepdeskVersionHeaders(i),i})}latestReceivedDeepdeskVersions={};client;shouldFetchCsrfToken=!0;static exchangeTokenPromise=null;async preflight(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let e=await this.getCsrfToken();this.client.setCsrfToken(e)}return this.options.token?(t.exchangeTokenPromise||(t.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),t.exchangeTokenPromise):Promise.resolve()}async createConversation(e){await this.preflight(),E.info(`Creating conversation for session ${e.sessionId} and agent ${e.agentId}`);let o=await this.client.post("/api/conversations",{...B(e),tags:e.tags},{version:"v2"});return Qn(o)}async getProfile(e){let o=await this.client.get(`/apis/admin/profiles/${e}/`,{version:null});return A(o)}async getContentTypes(){let e=await this.client.get("/apis/admin/content-types/",{version:null});return A(e)}async getPlatformConfig(){let{config:e}=await this.client.get("/platform/config/",{version:null});return A(e)}async checkUserExists(e){let{exists:o}=await this.client.get(`/apis/admin/users/exists?external_id=${e}`);return o}async getConversationBySessionId(e,o={}){await this.preflight(),E.info(`Getting conversation for session ${e}`);let{attempts:n=1,retryDelay:s=1e3}=o,r=await this.client.get(`/api/conversations/by_session_id/${e}`,{attempts:n,retryDelay:s,retryOnResponse:i=>i.status===404||i.status>=500,version:"v2"});return Qn(r)}async isConversationSupported(e,o={}){E.info(`Check if conversation for session ${e} is supported`);let{attempts:n=1,retryDelay:s=1e3}=o;return(await this.client.get(`/api/conversations/by_session_id/${e}/active_profile`,{attempts:n,retryDelay:s,retryOnResponse:i=>i.status===404||i.status>=500,version:"v2"})).has_active_profile}async updateConversation(e,o){let n=B(o);o.tags&&(n.tags=o.tags);let s=await this.client.put(`/api/conversations/${e}`,n,{version:"v2"});return Qn(s)}async postMessages(e,o){return(await this.client.post(`/api/conversations/${e}/messages`,o.map(s=>({...B(s),tags:s.tags})),{version:"v2"})).map(s=>Qn(s))}async sendEvent(e,o){let{data:n,...s}=o,r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((i,[a,l])=>({...i,[a]:l}),{});return this.client.post("/api/events",B({...r,...s,data:n,name:e}),{version:"v2"})}async sendEventV1(e,o){let n=Object.entries(this.latestReceivedDeepdeskVersions).reduce((s,[r,i])=>({...s,[r]:i}),{});return this.client.post("/api/events",{event:e,data:B({...o,...n})})}async getEntities(e){return(await this.client.post("/api/entities",{messages:e.filter(n=>n.text)})).entities}async getSummary(e,o={}){return(await this.client.post("/api/summary",{conversation:{messages:e.filter(s=>s.text&&s.source)},prompt_instruction:o.promptInstruction,model:o.model})).summary}async getTemporaryExchangeToken(){return(await this.client.get("/auth/exchange-token",{version:null})).jwt}async exchangeTokenForAccessCookie(e){return this.client.post("/apis/admin/session/jwt/",{jwt:e},{version:null}).catch(o=>{throw E.warn(`Invalid token '${e}'`),o})}async authenticateWithKey(e,o){await this.client.post("/apis/admin/session/api-key/",B(o),{version:null,refreshTokenOn401:!1,headers:{apikey:e}})}async getTextSuggestions(e,o={},n){return n==="sticky-messages"?this.getPinnedMessages(e):(await this.client.post(`/api/conversations/${e}/recommend/${n}`,B(o),{abortLatest:!0})).map(r=>({...A(r),text:r.text||r.url||r.message,source:n,type:n})).filter((r,i,a)=>i===a.findIndex(l=>l.text===r.text))}async isLoggedIn(){return await this.preflight(),this.client.validateToken()}async getAutocompleteSuggestions(e,o){return(await this.client.post(`/api/conversations/${e}/autocomplete`,B(o),{abortLatest:!0})).map(s=>({score:1,source:s.source,sourceText:s.source_text,text:s.label,trainingJobs:s.training_jobs,searchKeywords:s.search_keywords,type:s.source})).filter((s,r,i)=>r===i.findIndex(a=>a.text===s.text))}async getPinnedMessages(e){let o=await this.client.get(`/api/conversations/${e}/sticky-messages`,{abortLatest:!0});return A(o).map(n=>({...n,text:n.message,source:"sticky-messages",type:"pinned-message"}))}async getStyleSuggestions(e){let o=await this.client.post("/api/style-suggestions",B(e),{abortLatest:!0});return A(o)}async search(e){let o=await this.client.post(`/api/profiles/${e.profile}/search`,B(e),{version:"v2"});return A(o)}async knowledgeAssist(e,o,n){let s=await this.client.post("/api/knowledge-search/search",B({question:e.question,promptInstruction:e.promptInstruction,profile:n,chatHistory:o.map(r=>({question:r.question,answer:r.answer.answer}))}),{version:"v2"});return A(s)}async requestLoginByEmail(e){let o=await this.client.post("/apis/admin/session/passwordless/request/",{email:e},{version:null});return A(o)}async getCsrfToken(){let{token:e}=await this.client.get("/apis/admin/session/csrf/",{version:null});return e}async verifyLoginToken(e){let o=await this.client.post("/apis/admin/session/passwordless/login/",{token:e},{version:null});return A(o)}handleDeepdeskVersionHeaders(e){e.headers.forEach((o,n)=>{let s=n.toLowerCase(),r=s.match(vi);if(!o||!r)return;let i=r[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&o&&a!==o&&E.warn(`Overwritten Version header ${s}: ${JSON.stringify(a)} -> ${JSON.stringify(o)}`),this.latestReceivedDeepdeskVersions[i]=o})}};var vo=class{constructor(e,o){this.url=e;this.options={timeout:25e3,...o}}eventListeners={};options;timeoutTimer;eventSource;proxyEvent(e){this.eventSource.addEventListener(Ws(e),o=>{let{data:n}=o;try{let s=JSON.parse(n);this.emit(e,A(s))}catch{E.warn(`Invalid JSON for ${e}: ${n}`)}})}connect(){clearTimeout(this.timeoutTimer);let e=new EventSource(this.url,{withCredentials:!0});this.eventSource=e;let o=!1;e.onopen=()=>{o=!0},e.onerror=()=>{o&&e.readyState===2&&this.connect()},this.timeoutTimer=setTimeout(()=>{e.close(),this.connect()},this.options.timeout),Object.keys(this.eventListeners).forEach(n=>{this.proxyEvent(n)})}disconnect(){var e;clearTimeout(this.timeoutTimer),this.eventListeners={},(e=this.eventSource)==null||e.close()}emit(e,o){this.eventListeners[e]&&this.eventListeners[e].forEach(n=>n(o))}on(e,o){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(o),this.proxyEvent(e),()=>{this.off(e,o)}}off(e,o){let n;this.eventListeners[e]&&(n=this.eventListeners[e].indexOf(o),n>-1&&this.eventListeners[e].splice(n,1))}};var Oy;(e=>{let t;(r=>(r.Started="Started",r.Aborted="Aborted",r.Completed="Completed"))(t=e.AutoflowSessionState||={})})(Oy||={});var _o=class{constructor(e,o={}){this.apiUrl=e;this.client=new he(e,o)}client;streams={};logger=E;async getCustomMessages(e){let o=await this.client.get(`/sessions/${e}/suggestions`);return A(o.suggestions)}async sendCustomMessage(e,o){let n=await this.client.post(`/sessions/${e}/messages`,B(o));return A(n)}async answerCustomMessage(e,o){await this.client.post(`/sessions/${e}/answers`,B(o))}async getAutoflows(e){let o=await this.client.get(`/sessions/${e}/autoflows`);return A(o.autoflows)}async startAutoflowSession(e){let o=await this.client.post("/autoflow-sessions",B(e));return A(o)}async stopAutoflowSession(e){await this.client.delete(`/autoflow-sessions/${e}`)}openStream(e){return this.streams[e]||(this.streams[e]=new vo(`${this.apiUrl}/sessions/${e}/events`),this.streams[e].connect()),this.streams[e]}closeStream(e){this.streams[e]||(this.streams[e].disconnect(),delete this.streams[e])}};import{combineReducers as Uy,configureStore as zy}from"@reduxjs/toolkit";import{createSlice as Ny}from"@reduxjs/toolkit";var wp={startTime:null,stopTime:null},Tp=Ny({name:"handlingTime",initialState:wp,reducers:{handlingTimeStart(t){if(t.startTime&&!t.stopTime)throw new Error("Timing already started");t.startTime=new Date,t.stopTime=null},handlingTimeStop(t){if(!t.startTime)throw new Error("Timing not started");t.stopTime=new Date},handlingTimeReset(t){t.startTime=null,t.stopTime=null}},extraReducers:t=>{t.addCase(R,()=>wp)}}),{handlingTimeStart:Ep,handlingTimeStop:Zn,handlingTimeReset:kp}=Tp.actions,Rp=Tp.reducer;var Pp=(t={})=>{let e={onAuthError:Ct(!1),...t};return o=>n=>s=>("error"in s&&s.error.message==="Unauthorized"&&o.dispatch(e.onAuthError),n(s))};import{createAsyncThunk as Dy,createSlice as Hy}from"@reduxjs/toolkit";var Jn={list:{keywordMatches:[]},fetchState:"idle",isInitialRequest:null};var tt=Dy("styleSuggestions/getAll",async({text:t},e)=>{var i;let{deepdeskAPI:o}=e.extra,n=e.getState(),{showStyleSuggestions:s}=n.settings,r=(i=n.conversation.current)==null?void 0:i.profileCode;if(!s)return Jn.list;if(!r)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:r,message:t})}),By=Hy({name:"styleSuggestions",initialState:Jn,reducers:{},extraReducers:t=>{t.addCase(tt.pending,e=>{e.isInitialRequest=e.isInitialRequest===null,e.fetchState="loading"}).addCase(tt.rejected,e=>{e.fetchState="error"}).addCase(tt.fulfilled,(e,o)=>{e.fetchState="done",Ie(e.list,o.payload)||(e.list=o.payload)}).addCase(We,e=>{e.list=Jn.list}).addCase(R,()=>Jn)}}),Ip=By.reducer;var Ap=(t={})=>{let e,o=!0,n={getStyleSuggestions:tt,debounce:500,...t};return s=>r=>i=>{var m;let a=s.getState().input.text,l=r(i),c=s.getState();if(c.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:p}=c.settings;if(!((m=c.conversation.current)==null?void 0:m.id)||!p)return l;let{text:d}=c.input;return d===a&&!o||(clearTimeout(e),d==="")||(e=setTimeout(()=>{o=!1,s.dispatch(n.getStyleSuggestions({text:d}))},t.debounce)),l}};function Fy(t,e){return t.text===e.text&&t.selection.start===e.selection.start&&t.selection.end===e.selection.end}var Lp=(t={})=>{let e={getTextSuggestions:xe,getAutocompleteSuggestions:eo,debounce:200,check:It,...t},o;return n=>s=>r=>{var g;let{input:{userCommitted:i}}=n.getState(),a=s(r),l=n.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:c,showTabCompletion:p}=l.settings,u=(g=l.conversation.current)==null?void 0:g.id,d=r.type===Sn.toString();if(!u||!c&&!p)return a;let{input:{userCommitted:m}}=l;return Fy(m,i)&&!d||(clearTimeout(o),!e.check(l))||(o=setTimeout(()=>{let x=ut(l);x===""?n.dispatch(e.getTextSuggestions("default")):n.dispatch(e.getAutocompleteSuggestions(x))},d?0:e.debounce)),a}};var Mp=tt.fulfilled.toString();function Ky(t,e){let o=new Set([...e.keywordMatches.map(s=>s.keyword)]),n=[];return o.forEach(s=>{let r=t.keywordMatches.filter(l=>l.keyword===s),i=e.keywordMatches.filter(l=>l.keyword===s),a=i.length-r.length;a<=0||n.push(...i.slice(0,a))}),n}var Op=t=>e=>o=>n=>{var c;if(n.type!==Mp){o(n);return}let s=e.getState().styleSuggestions.list;o(n);let r=e.getState(),i=r.styleSuggestions.list,a=(c=r.conversation)==null?void 0:c.current;if(s===i)return;let l=Ky(s,i);n.type===Mp&&l.length>0&&t.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var jy=Uy({activeSuggestion:Xa,answer:Dl,auth:ll,autoflows:Nc,conversation:Ti,contentTypes:vl,customMessages:qc,exchangeToken:Xc,entities:bl,handlingTime:Rp,info:Sa,input:ks.reducer,overlayInput:W.reducer,settings:xi,profile:Ul,search:wa,summary:Pl,styleSuggestions:Ip,ui:Ya,textSuggestions:qa});function Np(t){return zy({reducer:jy,middleware:e=>[...e({thunk:{extraArgument:{dynamicThunkObject:t.dynamicThunkObject,deepdeskAPI:t.deepdeskAPI,deepdeskBrokerAPI:t.deepdeskBrokerAPI}},serializableCheck:!1}),Pp(),Lp({debounce:200}),Ap({debounce:500}),Op(t.deepdeskAPI),...t.middleware?t.middleware:[]],preloadedState:t.preloadedState})}var qy=t=>{var e;return((e=t==null?void 0:t.type)==null?void 0:e.toLowerCase())??"unknown"},Vy=t=>e=>o=>n=>{var a;let s=e.getState(),r=Cs("inlineSuggestions")(s);switch(n.type){case be.toString():{let l=Ba(n.payload.contentType)(e.getState()),c=l.indexOf(n.payload.suggestion);t.emit("edit-suggestion",{contentType:n.payload.contentType,index:c,suggestions:l});break}case Ct.toString():{!n.payload&&t.emit("logout",void 0);break}case ie.toString():{let{start:l,end:c}=s.input.selection;t.emit("select-suggestion",{type:qy(n.payload.suggestion),...n.payload,replace:n.payload.replace==="selection"?{start:l,end:c}:{start:0,end:c}},{mayApplyChanges:!0});break}case Zo.toString():{let{start:l,end:c}=s.input.selection;t.emit("replace",{...n.payload,replace:n.payload.replace==="selection"?{start:l,end:c}:{start:0,end:c}},{mayApplyChanges:!0});break}case Gt.toString():{let l=e.getState(),{text:c,selection:p}=l.input.userCommitted;t.emit("reset",{text:c,selectionAfter:p},{mayApplyChanges:!0});break}case tn.toString():t.emit("select-image",n.payload,{mayApplyChanges:!0}),t.sendEvent("Image attached",{conversationId:s.conversation.current.id,data:{path:n.payload.suggestion.image,title:n.payload.suggestion.title}});break;case le.fulfilled.toString():n.payload.length>0&&t.sendEvent("entities found",{conversationId:s.conversation.current.id,data:{entities:n.payload}});break;case we.fulfilled.toString():t.sendEvent("conversation summarized",{conversationId:s.conversation.current.id,data:{summary:n.payload.summary}});break;case J.toString():t.sendEvent(n.payload.name,{conversationId:((a=n.payload.options)==null?void 0:a.includeConversationData)&&s.conversation.current.id,data:n.payload.data});break;case Jo.toString():t.handleKeyDown(n.payload);break;case We.toString():t.logSendMessage(n.payload);break;case Yo.toString():t.logSendEditSuggestionMessage(n.payload);break;case en.toString():t.handleInputChanged(n.payload);break;default:break}let i=o(n);switch(n.type){case We.toString():t.handleAfterSendMessage(n.payload);break;case to.toString():t.onUpdateShowTabHint(n.payload);break;case Zn.toString():t.logHandlingTime();break;case ie.toString():{r&&(e.dispatch(Se([])),e.dispatch(Le()));break}default:break}return i},Dp=Vy;function $r(t){return t.toISOString().replace("T"," ").replace("Z","")}function Hp(t,e){var s,r,i;let{startTime:o,stopTime:n}=t.handlingTime;if(!o||!n)throw new Error("No startTime and stopTime for handling time metrics");return{conversationId:t.conversation.current.id,clientVersion:e.version,agentId:(s=t.info.agentInfo)==null?void 0:s.agentId,agentName:(r=t.info.agentInfo)==null?void 0:r.agentName,agentEmail:(i=t.info.agentInfo)==null?void 0:i.agentEmail,timeStart:$r(o),timeStop:$r(n)}}function Xr(t,e,o){var O,ce,N;let{text:n,metrics:{numCharsTyped:s,numCharsPasted:r,numCharsCut:i,numCharsDeleted:a,numPaste:l,agentStartedTypingTimestamp:c,externalTimeTotalSeconds:p,pastes:u,cuts:d,deletions:m,textSuggestions:f,offeredTextSuggestions:g}}=e[t],x=n.length,h=f.reduce((k,{text:V,searchTerm:oe})=>k+V.length-(oe?oe.length:0),0),y=c??Date.now(),_=(Date.now()-y)/1e3+(p||0),C=s/_,H=f.reduce((k,{searchTerm:V})=>k+(V?V.length:0),0);return{conversationId:e.conversation.current.id,source:"agent",text:n,clientVersion:o.version,pastes:u,cuts:d,deletions:m,lenTextTyped:s+H,lenTextTotal:x,lenTextAssisted:h,lenTextPasted:r,lenTextCut:i,lenTextDeleted:a,timeTotalSeconds:_,charsPerSecond:C,numPastes:l,textSuggestionsV2:f,suggestionsCounters:[{source:"gpt",countOffered:g.filter(k=>k.source==="gpt").length}],agentId:(O=e.info.agentInfo)==null?void 0:O.agentId,agentName:(ce=e.info.agentInfo)==null?void 0:ce.agentName,agentEmail:(N=e.info.agentInfo)==null?void 0:N.agentEmail}}function Bp(t,e){let o=t.closest(e);if(o)return o;let n=t.getRootNode().host;return n instanceof HTMLElement?Bp(n,e):null}function Fp(t,e){return Bp(t,e)}function Kp(t){return typeof t=="object"&&t!==null&&"name"in t&&"message"in t}function Wy(t){return typeof t=="object"&&t!==null&&"tagName"in t}function Qr(t){return Wy(t)&&(ge(t)||sn(t))}var Up=(t,e)=>({value(){try{let o=sessionStorage.getItem(`dd-${t}`);if(!o)return e;try{return JSON.parse(o)}catch{return e}}catch{return e}},update(o){try{sessionStorage.setItem(`dd-${t}`,JSON.stringify(o))}catch{E.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function Gy(t){return t.offsetParent!==null}function zp(t){if(!Gy(t))return!1;let e=t.getBoundingClientRect();return e.top>=0&&e.left>=0&&e.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&e.right<=(window.innerWidth||document.documentElement.clientWidth)}function Zr(t,e,o=100){let n=zp(t);e({isVisible:n});let s=setInterval(()=>{let r=zp(t);r!==n&&(n=r,e({isVisible:n}))},o);return()=>{clearTimeout(s)}}import{jsx as q}from"react/jsx-runtime";var jp=Up("showTabHint",!0),es=class t{static version="10.3.1-beta.3";static count=0;deepdeskApi;inputMediator=null;version;broadcastEvents;eventListeners={};unmountHandlers=[];widgetRoot=null;dynamicThunkObject={};isMounted=!1;instanceId;shouldRender=!0;store;constructor({deepdeskUrl:e,brokerUrl:o,version:n=t.version||"unknown",locale:s="en-US",token:r,fetch:i,productName:a,createCustomChannel:l}){let c=e.replace(/\/api$/,"");this.deepdeskApi=new Ke(c,{token:r,fetch:i}),this.version=n,this.instanceId=t.count++;let p={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[Dp({emit:(u,d,m)=>this.emit(u,d,m),handleAfterSendMessage:u=>this.handleAfterSendMessage(u),handleInputChanged:u=>this.handleInputChanged(u),handleKeyDown:u=>this.handleKeyDown(u),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:u=>this.logSendMessage(u),logSendEditSuggestionMessage:u=>this.logSendEditMessage(u),onUpdateShowTabHint:u=>jp.update(u),sendEvent:(u,d)=>this.deepdeskApi.sendEvent(u,d)})]};o&&Object.assign(p,{deepdeskBrokerAPI:new _o(o)}),this.store=Np(p),this.broadcastEvents=new Cp({debug:!0,deepdeskUrl:c,eventMap:cl(this.store),createCustomChannel:l}),this.store.dispatch(Wt),this.store.dispatch(to(jp.value())),this.store.dispatch(Wt({locale:s,adminUrl:c,productName:a}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){return this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex]??null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(E.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(E.warn("Profile has not been loaded (yet)"),!0):(E.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(Ct(null)),this.store.dispatch(Be()),new Promise(e=>{let o=this.store.subscribe(()=>{let n=this.store.getState();ae(n)&&ol(n)!=="loading"&&e()});this.unmountHandlers.push(()=>{o()})})}isLoggedIn(){return this.deepdeskApi.isLoggedIn()}async setPlatformAgentId(e){try{if((await this.deepdeskApi.client.get("/apis/admin/session/me/",{version:null})).external_id)return;await this.deepdeskApi.client.request("/apis/admin/session/me/",{method:"PATCH",body:JSON.stringify({external_id:e}),version:null})}catch(o){E.warn("Failed to attach user:",o)}}async isConversationSupported(e,o){return(await this.store.dispatch(Ts({sessionId:e,options:o}))).payload}async createConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(Vo(e))).payload}async getConversationBySessionId(e,o){return this.hasConversation()&&this.sessionId()!==e&&this.resetConversation(),(await this.store.dispatch(Wo({sessionId:e,options:o}))).payload}async upsertConversation(e){return this.hasConversation()&&this.sessionId()!==e.sessionId&&this.resetConversation(),(await this.store.dispatch(Es(e))).payload}async postMessages(e){return(await this.store.dispatch($o(e))).payload}async updateConversation(e){return(await this.store.dispatch(Go(e))).payload}resetConversation(){this.store.dispatch(R()),this.dynamicThunkObject.conversationQuery=null}async getSummary(){let e=await this.store.dispatch(we());if(e.error)throw new Error(e.error.message);return e.payload.summary}configure(e){this.store.dispatch(Wt(e))}setVisitorInfo(e){this.store.dispatch(ya(e))}async setAgentInfo(e){await this.store.dispatch(Zt(e))}async setAgentSettings(e){await this.store.dispatch($s(e))}async getAgentSettings(){return(await this.store.dispatch(Xs())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let e=[];return this.store.dispatch(Sn()),e.push(this.refreshWidgetSuggestions()),Promise.all(e).then(()=>{})}notifyInputChanged(e){this.store.dispatch(en(e))}notifyKeyDown(e){this.store.dispatch(Jo(e))}notifyPaste(e,o){this.store.dispatch(Di({text:e,selectionText:o}))}notifyCut(e){this.store.dispatch(Oi(e))}notifyExternalSuggestion(e){this.store.dispatch(ie(e)),this.store.dispatch(Le())}notifyEditSuggestion(e){this.store.dispatch(za(e.contentType,e.suggestions)),this.store.dispatch(be({contentType:e.contentType,suggestion:typeof e.index=="number"?e.suggestions[e.index]:null}))}handleInputChanged(e){let{overlayCollapsed:o,openOverlayWhenTyping:n}=this.state.ui;o&&n&&this.store.dispatch(He({collapse:!1})),this.inputMediator&&this.store.dispatch(Ri({text:e,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(Se([])))}handleKeyDown(e){let{overlayCollapsed:o}=this.state.ui,{textSuggestions:n,selectedSuggestionIndex:s,selection:r}=this.state.input,{inlineSuggestions:i}=this.state.settings,a=n.length>0,l=s!==-1;if(this.store.dispatch(Ni(Qo(e))),e.key!=="Tab"&&!this.settings.showTextSuggestions)return;let c=()=>{o||!a||r&&(e.shiftKey||(this.store.dispatch(Ai()),i||this.stageSelectedSuggestion({inputType:"arrow"}),e.preventDefault()))},p=()=>{if(o||!a||!r||e.shiftKey)return;this.store.dispatch(Mi());let{selectedSuggestionIndex:u}=this.state.input;u===-1?this.store.dispatch(Gt()):i||this.stageSelectedSuggestion({inputType:"arrow"}),e.preventDefault()};switch(e.key){case"Up":case"ArrowUp":i?p():c();return;case"Down":case"ArrowDown":{i?c():p();return}case"Esc":case"Escape":{i&&l&&this.store.dispatch($t(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch($t(-1)),this.store.dispatch(Gt()),e.preventDefault()):o||(this.store.dispatch(He({collapse:!0})),this.store.dispatch(Za(!0)),e.preventDefault());return}case"Tab":{let{userCommitted:u}=this.state.input,d=u.text.substring(0,u.selection.end),{tabCompletionSuggestion:m}=this.state.input;this.store.dispatch(to(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):this.settings.showTabCompletion&&m&&m.text.startsWith(d)&&(this.store.dispatch(ie({text:m.text,suggestion:m,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch(Le())),e.preventDefault();break}default:}}handleAfterSendMessage(e){this.emit("send-message",e),this.store.dispatch(Hi()),this.store.dispatch(Se([]))}handlingTimeStart(){this.state.handlingTime.startTime||(E.info("Start handling time"),this.store.dispatch(Ep()))}handlingTimeStop(){this.state.handlingTime.startTime&&(E.info("Stop handling time"),this.store.dispatch(Zn()))}logSendMessage(e){let o=Xr("input",this.state,{version:this.version});e&&Object.assign(o,{text:e}),this.deepdeskApi.sendEventV1("Send Message",o),this.emit("send-message-event",o)}logSendEditMessage(e){let o=Xr("overlayInput",this.state,{version:this.version});e&&Object.assign(o,{text:e}),this.store.dispatch(Ii(this.state.overlayInput.metrics))}logHandlingTime(){let e=Hp(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",e),this.store.dispatch(kp())}notifySubmit(e={}){this.shouldAbort()||(this.store.dispatch(Le()),this.store.dispatch(We(e.text??this.state.input.text)))}stageSelectedSuggestion(e){let o=this.state.input.selectedSuggestionIndex,{textSuggestions:n}=this.state.input;this.store.dispatch(ie({text:n[o].text,suggestion:n[o],eventMetrics:e,replace:"until-selection-end"}))}emit(e,o,n={}){let s=()=>{this.eventListeners[e]&&this.eventListeners[e].forEach(r=>{try{r(o)}catch(i){E.warn(`The following error occurred in deepdeskSDK.on('${e}', handler)`),E.error(i)}})};this.inputMediator&&n.mayApplyChanges?this.inputMediator.applyChanges(s):s()}on(e,o){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(o),()=>{this.off(e,o)}}off(e,o){if(!e&&!o){this.eventListeners={};return}let n;this.eventListeners[e]&&(n=this.eventListeners[e].indexOf(o),n>-1&&this.eventListeners[e].splice(n,1))}setConversationQuery(e){this.dynamicThunkObject.conversationQuery=e}whenConversationLoaded(e){let o=()=>this.loadProfileConfig().then(()=>e());this.hasConversation()&&o();let n=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==n&&(n=this.hasConversation(),n&&o())})}overlayContainerFactory(e,o,n,s){let[r,i]=ft(o,n);return r.setAttribute("translate","no"),r.dataset.testid=e,s&&r.classList.add(s),this.unmountHandlers.push(()=>{Yn(r),i(),r.remove()}),r}createInlineContainer(e,o){var i;let n=document.createElement("div");n.style.position="absolute",n.style.top="0px",n.style.left="0px",n.style.height="0px",n.style.width="0px";let s=document.createElement("div");s.style.display="none",s.style.position="absolute",s.style.height="0px",s.style.width="0px",s.style.backgroundColor="red",n.appendChild(s);let r=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;if(r){let[a,l]=ft(r,{appendTo:document.body});a.dataset.testid=o,a.style.zIndex="2",a.appendChild(n),this.unmountHandlers.push(()=>{Yn(s),l()})}else document.body.appendChild(n);return s}createContainer(e,o=document.body){let n=window.getComputedStyle(o),s=document.createElement("div");return Ge(s),s.dataset.testid=e,s.style.color=n.color,s.style.fontSize=n.fontSize,s.style.fontFamily=n.fontFamily,s.style.fontVariant=n.fontVariant,s.setAttribute("translate","no"),o.appendChild(s),this.unmountHandlers.push(()=>{Yn(s),s.remove()}),s}mount(e,o={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!Qr(e))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let{customStyles:n={},showStyleSuggestions:s,showTabCompletion:r,showTextSuggestions:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:c,showSuggestionsAfterPattern:p,isEmbedded:u,detectSubmit:d,insertLink:m,inputMediator:f,closestScrollSelector:g,appendOverlayTo:x,inlineSuggestions:w}=o;if(this.configure({showStyleSuggestions:s,showTabCompletion:r,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:c,showSuggestionsAfterPattern:p,showTextSuggestions:i,insertLink:m,isEmbedded:u,inlineSuggestions:w}),o.automaticHandlingTime&&this.setupHandlingTime(e),Ge(e),this.inputMediator=f||(ge(e)?new Ne(e):new Ht(e)),this.inputMediator.on("change",({plainText:y})=>{this.notifyInputChanged(y)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(Bi({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",y=>{this.notifyKeyDown(y)}),this.inputMediator.on("paste",({pastedText:y,selectionText:_})=>{this.notifyPaste(y,_)}),this.inputMediator.on("cut",({selectionText:y})=>{this.notifyCut(y)}),w){if(ge(e))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let y=this.createInlineContainer(e,"deepdesk-caret");xo(q(At,{store:this.store,customStyles:n,children:q(bt,{broadcastEvents:this.broadcastEvents,children:q(ec,{})})}),y),this.inputMediator.on("caret",_=>{this.store.dispatch(Se([])),_?(y.style.display="block",y.style.top=`${_.top}px`,y.style.left=`${_.left}px`):y.style.display="none"})}else{let y=g&&Fp(e,g)||void 0,_=this.overlayContainerFactory("deepdesk-tab-completion",y||e,{appendTo:x,closestScrollElement:y,mirrorOverflow:!0,onRemove:()=>this.unmount()},n==null?void 0:n.rootNode),C=this.overlayContainerFactory("deepdesk-suggestions-overlay",y||e,{appendTo:x},n==null?void 0:n.suggestionsRootNode);xo(q(At,{store:this.store,customStyles:n,children:q(bt,{broadcastEvents:this.broadcastEvents,children:q(Pc,{inputElement:e})})}),_),xo(q(At,{store:this.store,customStyles:n,children:q(bt,{broadcastEvents:this.broadcastEvents,children:q(An,{})})}),C)}xo(q(At,{store:this.store,customStyles:n,children:q(bt,{broadcastEvents:this.broadcastEvents,children:q(Vl,{})})}),this.createContainer("deepdesk-overlays"));let h;this.inputMediator.on("selection",y=>{clearTimeout(h),y===null?h=setTimeout(()=>{y!==null&&this.store.dispatch(Rs(y))},500):this.store.dispatch(Rs(y))}),this.inputMediator.on("disabled",()=>{var y;(y=this.inputMediator)==null||y.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(xt(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(xt(!0))),this.store.dispatch(Pi({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.whenConversationLoaded(()=>{var y;this.refresh(),this.broadcastEvents.setSessionId((y=this.state.conversation.current)==null?void 0:y.sessionId)}),this.isMounted=!0}unmount(){var e;this.unmountHandlers.forEach(o=>o()),this.unmountHandlers=[],(e=this.inputMediator)==null||e.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(e,o={}){if(this.widgetRoot&&E.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:n,showImages:s,showPersonalCollectionLink:r,isEmbedded:i}=o;this.widgetRoot=e,this.configure({showImages:s,showPersonalCollectionLink:r,isEmbedded:i}),xo(q(At,{store:this.store,customStyles:n,children:q(bt,{broadcastEvents:this.broadcastEvents,children:q(_p,{})})}),e),this.whenConversationLoaded(()=>{var a;this.broadcastEvents.setSessionId((a=this.state.conversation.current)==null?void 0:a.sessionId)})}unmountWidget(){this.widgetRoot&&Yn(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(e){let o=Zr(e,({isVisible:n})=>{n?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),o()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(e){Kp(e)&&e.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(io());let e=Rt(this.state);e&&this.store.dispatch(Wt({showSearch:e.search,showAutoflows:e.autoflows,showCustomMessages:e.customMessages,showImageSearch:e.imageSearch,showEntitiesCommand:e.entitiesCommand,showSummaryCommand:e.summarizer,showKnowledgeSearch:e.knowledgeAssistForAgents,recommendTextSuggestions:e.recommendTextSuggestions}))}),this.loadProfileConfigPromise)}async checkForTrialMode(e){try{let{account:o}=await this.deepdeskApi.getPlatformConfig();if(!o.isTrial){this.shouldRender=!0;return}if(E.info("Trial is active"),!await this.deepdeskApi.checkUserExists(e))throw new Error("User is not in trial");this.shouldRender=!0}catch(o){let{message:n}=o;E.info(n),this.shouldRender=!1}}async refreshWidgetSuggestions(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:e}=this.state.profile.data;if(!e.widget)return;let o=wn(this.state);try{o.forEach(({type:n})=>{n==="entities"?this.store.dispatch(le()):this.store.dispatch(xe(n))})}catch(n){this.handleError(n)}}};async function $y(t,e,o={}){let{value:n}=t,{start:s,end:r}=o.replace??{start:0,end:n.length},i=`${n.slice(0,s)}${e}${n.slice(r)}`,a=o.selectionAfter??{start:s+e.length,end:s+e.length},l=()=>{if(o.setValue)return o.setValue(i);t.value=i};return Promise.resolve(l()).then(()=>{t.selectionStart=a.start,t.selectionEnd=a.end,t.blur(),t.focus()})}async function Xy(t,e,o={}){let n=o.replace?et(t,o.replace.start,o.replace.end):So(t),s,r=()=>{if(o.setRange)return o.setRange(n.cloneRange());n.deleteContents(),s=document.createElement("span"),n.insertNode(s),o.insertBRs!==!1?e.split(`
|
|
6
|
+
`).reverse().forEach((i,a)=>{a>0&&n.insertNode(document.createElement("br")),n.insertNode(document.createTextNode(i))}):n.insertNode(document.createTextNode(e))};return Promise.resolve(r()).then(()=>{try{if(o.selectionAfter!==!1){t.focus();let i=o.selectionAfter?et(t,o.selectionAfter.start,o.selectionAfter.end):(n.collapse(!1),n),a=window.getSelection();a==null||a.removeAllRanges(),a==null||a.addRange(i)}if(!s)return;s.scrollIntoView&&s.scrollIntoView({block:"nearest",inline:"nearest"})}finally{s&&s.remove()}})}async function Qy(t,e){let o;t.dispatchEvent(new InputEvent("beforeinput",{inputType:"insertText",data:e,bubbles:!0,cancelable:!0}));let n=()=>{let r=(t.ownerDocument.defaultView??window).getSelection();if(!r)return;let i=r.getRangeAt(0);i&&(i.deleteContents(),o=document.createElement("span"),i.insertNode(o),e.split(`
|
|
7
|
+
`).reverse().forEach((a,l)=>{l>0&&i.insertNode(document.createElement("br")),i.insertNode(document.createTextNode(a))}),i.collapse(!1))};return Promise.resolve(n()).then(()=>{if(t.dispatchEvent(new InputEvent("input",{inputType:"insertText",data:e,bubbles:!0,cancelable:!0})),t.focus(),!!o)try{o.scrollIntoView&&o.scrollIntoView({block:"nearest",inline:"nearest"})}finally{o&&o.remove()}})}function Zy(t){return t.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}async function Jy(t,e,o){await new Ke(t).authenticateWithKey(e,o)}async function Yy(t){let o=await new he(t).get("/platform/config/",{version:null});return A(o)}async function eS(t){let o=await(t.fetch??window.fetch)(t.url),n=await o.blob();return new File([n],t.name,{type:t.mimeType??o.headers.get("Content-Type")??"image/jpeg"})}async function tS(t,e){let o=await eS(e),n=new Event("change",{bubbles:!0,cancelable:!0});try{Object.defineProperty(t,"files",{configurable:!0,get:()=>[o]}),t.dispatchEvent(n)}finally{Object.hasOwn(t,"files")&&delete t.files}}export{D as Card,Pu as Chip,Ht as ContentEditableInput,Ke as DeepdeskAPI,es as DeepdeskSDK,he as HTTPClient,Oe as InputMediator,qe as InputType,hs as KeyboardHint,ys as Label,zo as Locale,je as Section,vs as SectionList,pe as Sources,M as Suggestion,re as SuggestionList,Ne as TextAreaInput,at as ToggleButton,tS as attachFile,Jy as authenticateWithKey,So as createFullRange,ft as createOverlayContainer,et as createRangeFromOffsets,lo as escapeHTML,Yy as fetchPlatformConfig,Zy as formatTextMarkup,$n as getRangeOffsets,Xn as getRangeText,Qy as insertCKEditor,Qr as isSupportedInputElement,Xy as updateContentEditable,$y as updateTextArea,S as useStyles,Zr as waitForElementVisibilityChange};
|