2020 Una Oportunidad
ation please see chatbot.js.LICENSE.txt */
( () => {
«use strict»;
var webpack_modules = {
469: (unused_webpack_module, _webpack_exports, webpack_require) => {
webpack_require.d(webpack_exports, {
G: () => ChatbotContextProvider,
o: () => useChatbotContext
});
var _app_chatbot_helpers__WEBPACK_IMPORTED_MODULE_0_ = webpack_require(728)
, app_chatbot_MwaiAPI__WEBPACK_IMPORTED_MODULE_3_ = webpack_require(137)
, app_helpers__WEBPACK_IMPORTED_MODULE_2_ = webpack_require(678)
, app_helpers_tokenManager__WEBPACK_IMPORTED_MODULE_1_ = webpack_require(213);
const {useContext, createContext, useState, useMemo, useEffect, useCallback, useRef} = wp.element
, rawAiName = «AI: «
, rawUserName = «User: «
, ChatbotContext = createContext()
, useChatbotContext = () => {
const e = useContext(ChatbotContext);
if (!e)
throw new Error(«useChatbotContext must be used within a ChatbotContextProvider»);
return e
}
, ChatbotContextProvider = ({children, …rest}) => {
var params$startSentence; const {params, system, theme, atts} = rest , {timeElapsed, startChrono, stopChrono} = (0, _app_chatbot_helpers__WEBPACK_IMPORTED_MODULE_0_.dh)()
, shortcodeStyles = useMemo(( () => (null == theme ? void 0 : theme.settings) || {}), [theme])
, [restNonce,setRestNonce] = useState(system.restNonce || app_helpers_tokenManager__WEBPACK_IMPORTED_MODULE_1_.A.getToken())
, restNonceRef = useRef(system.restNonce || app_helpers_tokenManager__WEBPACK_IMPORTED_MODULE_1_.A.getToken());
useEffect(( () => app_helpers_tokenManager__WEBPACK_IMPORTED_MODULE_1_.A.subscribe((e => {
setRestNonce(e),
restNonceRef.current = e
}
))), []);
const [messages,setMessages] = useState([])
, [shortcuts,setShortcuts] = useState([])
, [blocks,setBlocks] = useState([])
, [locked,setLocked] = useState(!1)
, [chatId,setChatId] = useState((0,
app_helpers__WEBPACK_IMPORTED_MODULE_2_.vx)())
, [inputText,setInputText] = useState(«»)
, [chatbotTriggered,setChatbotTriggered] = useState(!1)
, [showIconMessage,setShowIconMessage] = useState(!1)
, [uploadedFile,setUploadedFile] = useState({
localFile: null,
uploadedId: null,
uploadedUrl: null,
uploadProgress: null
})
, [windowed,setWindowed] = useState(!0)
, [open,setOpen] = useState(!1)
, [error,setError] = useState(null)
, [busy,setBusy] = useState(!1)
, [busyNonce,setBusyNonce] = useState(!1)
, [lastFailedQuery,setLastFailedQuery] = useState(null)
, [serverReply,setServerReply] = useState()
, [previousResponseId,setPreviousResponseId] = useState(null)
, chatbotInputRef = useRef()
, conversationRef = useRef()
, hasFocusRef = useRef(!1)
, {isListening, setIsListening, speechRecognitionAvailable} = (0,
app_chatbot_helpers__WEBPACK_IMPORTED_MODULE_0_.Vw)((e => {
setInputText(e)
}
))
, stream = system.stream || !1
, internalId = useMemo(( () => (0,
app_helpers__WEBPACK_IMPORTED_MODULE_2_.vx)()), [])
, botId = system.botId
, customId = system.customId
, userData = system.userData
, [sessionId,setSessionId] = useState(system.sessionId)
, contextId = system.contextId
, pluginUrl = system.pluginUrl
, restUrl = system.restUrl
, debugMode = system.debugMode
, eventLogs = system.eventLogs
, virtualKeyboardFix = system.virtual_keyboard_fix
, typewriter = (null == system ? void 0 : system.typewriter) ?? !1
, speechRecognition = (null == system ? void 0 : system.speech_recognition) ?? !1
, speechSynthesis = (null == system ? void 0 : system.speech_synthesis) ?? !1
, startSentence = (0,
app_chatbot_helpers__WEBPACK_IMPORTED_MODULE_0_.Mc)((null === (params$startSentence = params.startSentence) || void 0 === _params$startSentence ? void 0 : _params$startSentence.trim()) ?? «», userData) , initialActions = system.actions || [] , initialShortcuts = system.shortcuts || [] , initialBlocks = system.blocks || [] , isMobile = document.innerWidth <= 768 , processedParams = (0, _app_chatbot_helpers__WEBPACK_IMPORTED_MODULE_0_.$)(params, userData) , {aiName, userName, guestName, aiAvatar, userAvatar, guestAvatar} = processedParams , {textSend, textClear, textInputMaxLength, textInputPlaceholder, textCompliance, window: isWindow, copyButton, headerSubtitle, fullscreen, localMemory: localMemoryParam, icon, iconText, iconTextDelay, iconAlt, iconPosition, iconBubble, imageUpload, fileUpload, fileSearch} = processedParams , isRealtime = «realtime» === processedParams.mode , localMemory = localMemoryParam && (!!customId || !!botId) , localStorageKey = localMemory ? mwai-chat-${customId || botId} : null , {cssVariables, iconUrl, aiAvatarUrl, userAvatarUrl, guestAvatarUrl} = useMemo(( () => { const e = e => e ? (0, _app_helpers__WEBPACK_IMPORTED_MODULE_2_.Ve)(e) || (0,
app_chatbot_helpers__WEBPACK_IMPORTED_MODULE_0_.mv)(e) ? e : ${pluginUrl}/images/${e} : null
, t = icon ? e(icon) : ${pluginUrl}/images/chat-traditional-1.svg
, a = e(processedParams.aiAvatarUrl)
, n = e(processedParams.userAvatarUrl)
, s = e(processedParams.guestAvatarUrl);
return {
cssVariables: Object.keys(shortcodeStyles).reduce(( (e, t) => (e[--mwai-${t}] = shortcodeStyles[t],
e)), {}),
iconUrl: t,
aiAvatarUrl: a,
userAvatarUrl: n,
guestAvatarUrl: s
}
}
), [icon, pluginUrl, shortcodeStyles, processedParams])
, [draggingType,setDraggingType] = useState(!1)
, [isBlocked,setIsBlocked] = useState(!1)
, uploadIconPosition = useMemo(( () => «timeless» === (null == theme ? void 0 : theme.themeId) ? «mwai-tools» : «mwai-input»), [null == theme ? void 0 : theme.themeId])
, submitButtonConf = useMemo(( () => ({
text: textSend,
textSend,
textClear,
imageSend: «timeless» === (null == theme ? void 0 : theme.themeId) ? pluginUrl + «/images/action-submit-blue.svg» : null,
imageClear: «timeless» === (null == theme ? void 0 : theme.themeId) ? pluginUrl + «/images/action-clear-blue.svg» : null
})), [pluginUrl, textClear, textSend, null == theme ? void 0 : theme.themeId])
, resetMessages = () => {
if (resetUploadedFile(),
setPreviousResponseId(null),
startSentence) {
const e = { id: (0, app_helpers__WEBPACK_IMPORTED_MODULE_2_.vx)(), role: «assistant», content: startSentence, who: rawAiName, timestamp: (new Date).getTime() };
setMessages(e)
} else
setMessages([])
}
, refreshRestNonce = useCallback((async (e=!1) => {
try {
if (!e && restNonce)
return restNonce;
setBusyNonce(!0);
const t = await (0,
app_helpers__WEBPACK_IMPORTED_MODULE_2_.ti)(${restUrl}/mwai/v1/start_session)
, a = await t.json();
if (setRestNonce(a.restNonce),
restNonceRef.current = a.restNonce,
app_helpers_tokenManager__WEBPACK_IMPORTED_MODULE_1_.A.setToken(a.restNonce),
a.sessionId && «N/A» !== a.sessionId && setSessionId(a.sessionId),
a.new_token) {
if (a.token_expires_at) {
const e = new Date(1e3 * a.token_expires_at);
console.log([MWAI] 🔐 New token received - expires at ${e.toLocaleTimeString()} (in ${a.token_expires_in}s))
}
return setRestNonce(a.new_token),
restNonceRef.current = a.new_token,
app_helpers_tokenManager__WEBPACK_IMPORTED_MODULE_1_.A.setToken(a.new_token),
a.new_token
}
return a.restNonce
} catch (e) {
console.error(«Error while fetching the restNonce.», e)
} finally {
setBusyNonce(!1)
}
}
), [restNonce, setRestNonce, restUrl, setSessionId])
, [isResumingConversation,setIsResumingConversation] = useState(!1)
, [isConversationLoaded,setIsConversationLoaded] = useState(!1);
useEffect(( () => {
isConversationLoaded && (isResumingConversation || messages.length > 1 || 1 === messages.length && messages[0].content !== startSentence || (initialActions.length > 0 && handleActions(initialActions),
initialShortcuts.length > 0 && handleShortcuts(initialShortcuts),
initialBlocks.length > 0 && handleBlocks(initialBlocks)))
}
), [isConversationLoaded, isResumingConversation, messages, startSentence]),
useEffect(( () => {
chatbotTriggered && !restNonce && refreshRestNonce()
}
), [chatbotTriggered]),
useEffect(( () => {
inputText.length > 0 && !chatbotTriggered && setChatbotTriggered(!0)
}
), [chatbotTriggered, inputText]),
useEffect(( () => {
resetMessages()
}
), [startSentence]),
useEffect(( () => {
if (customId || botId) {
const e = app_chatbot_MwaiAPI__WEBPACK_IMPORTED_MODULE_3_.HX.chatbots.findIndex((e => e.internalId === internalId))
, t = {
internalId,
botId,
chatId,
customId,
localStorageKey,
open: () => {
setTasks((e => […e, {
action: «open»
}]))
}
,
close: () => {
setTasks((e => […e, {
action: «close»
}]))
}
,
clear: e => {
const {chatId: t=null} = e || {};
setTasks((e => […e, {
action: «clear»,
data: {
chatId: t
}
}]))
}
,
toggle: () => {
setTasks((e => […e, {
action: «toggle»
}]))
}
,
ask: (e, t=!1) => {
setTasks((a => […a, {
action: «ask»,
data: {
text: e,
submit: t
}
}]))
}
,
lock: () => {
setLocked(!0)
}
,
unlock: () => {
setLocked(!1)
}
,
setShortcuts: e => {
setTasks((t => […t, {
action: «setShortcuts»,
data: e
}]))
}
,
setBlocks: e => {
setTasks((t => […t, {
action: «setBlocks»,
data: e
}]))
}
,
addBlock: e => {
setTasks((t => […t, {
action: «addBlock»,
data: e
}]))
}
,
removeBlockById: e => {
setTasks((t => […t, {
action: «removeBlockById»,
data: e
}]))
}
,
getBlocks: () => blocks,
setContext: ({chatId: e, messages: t, previousResponseId: a}) => {
console.warn(«MwaiAPI: setContext is deprecated. Please use setConversation instead.»),
setTasks((n => […n, {
action: «setContext»,
data: {
chatId: e,
messages: t,
previousResponseId: a
}
}]))
}
,
setConversation: ({chatId: e, messages: t, previousResponseId: a}) => {
setTasks((n => […n, {
action: «setContext»,
data: {
chatId: e,
messages: t,
previousResponseId: a
}
}]))
}
};
-1 !== e ? app_chatbot_MwaiAPI__WEBPACK_IMPORTED_MODULE_3_.HX.chatbots[e] = t : app_chatbot_MwaiAPI__WEBPACK_IMPORTED_MODULE_3_.HX.chatbots.push(t)
}
}
), [botId, chatId, customId, internalId, localStorageKey, blocks]),
useEffect(( () => {
var e;
busy ? startChrono() : (!isMobile && hasFocusRef.current && null !== (e = chatbotInputRef.current) && void 0 !== e && e.focusInput && chatbotInputRef.current.focusInput(),
stopChrono())
}
), [busy, startChrono, stopChrono, isMobile]);
const saveMessages = useCallback((e => {
localStorageKey && localStorage.setItem(localStorageKey, (0,
app_helpers__WEBPACK_IMPORTED_MODULE_2_.F1)({
chatId,
messages: e
}))
}
), [localStorageKey, chatId])
, resetError = () => {
setError(null)
}
, addErrorMessage = useCallback(( (e, t=null) => {
const a = {
id: (0,
app_helpers__WEBPACK_IMPORTED_MODULE_2_.vx)(),
role: «error»,
content: e,
who: «Error»,
timestamp: (new Date).getTime(),
isError: !0,
failedQuery: t
};
setMessages((e => […e, a])),
setLastFailedQuery(t)
}
), []);
useEffect(( () => {
let e = [];
if (localStorageKey && (e = localStorage.getItem(localStorageKey),
e))
return e = JSON.parse(e),
setMessages(e.messages),
setChatId(e.chatId),
setIsResumingConversation(!0),
void setIsConversationLoaded(!0);
setIsResumingConversation(!1),
setIsConversationLoaded(!0),
resetMessages()
}
), [botId]);
const executedActionsRef = useRef(new Set)
, handleActions = useCallback(( (actions, lastMessage) => {
actions = actions || [];
let callsCount = 0;
for (const action of actions)
if («function» === action.type) {
const data = action.data || {}
, {name=null, args=[]} = data
, actionKey = ${name}_${JSON.stringify(args)};
if (executedActionsRef.current.has(actionKey)) {
debugMode && console.log([CHATBOT] Skipping duplicate execution of ${name});
continue
}
const finalArgs = args ? Object.values(args).map((e => JSON.stringify(e))) : [];
try {
debugMode && console.log([CHATBOT] CALL ${name}(${finalArgs.join(", ")})),
executedActionsRef.current.add(actionKey),
eval(${name}(${finalArgs.join(", ")})),
callsCount++,
setTimeout(( () => {
executedActionsRef.current.delete(actionKey)
}
), 5e3)
} catch (e) {
console.error(«Error while executing an action.», e),
executedActionsRef.current.delete(actionKey)
}
}
!lastMessage.content && callsCount > 0 && (lastMessage.content = «Done!«)
}
), [debugMode])
, handleShortcuts = useCallback((e => {
setShortcuts(e || [])
}
), [])
, handleBlocks = useCallback((e => {
setBlocks(e || [])
}
), []);
useEffect(( () => {
if (!serverReply)
return;
setBusy(!1);
const e = […messages]
, t = e.length > 0 ? e[e.length – 1] : null;
if (!serverReply.success) {
«assistant» === t.role && t.isQuerying && e.pop();
const a = e.length – 1;
let n = null
, s = null;
if (a >= 0 && «user» === e[a].role) {
const t = e[a].content
, r = t.match(/^(?:|[.?](.?))\n(.*)$/s);
n = r ? r[1] : t,
r && uploadedFile && (s = uploadedFile)
}
return setMessages(e),
saveMessages(e),
void addErrorMessage(serverReply.message, n ? {
text: n,
file: s
} : null)
}
if («assistant» === t.role && t.isQuerying)
t.content = (0,
app_chatbot_MwaiAPI__WEBPACK_IMPORTED_MODULE_3_.W5)(«ai.reply», serverReply.reply, {
chatId,
botId
}),
serverReply.images && (t.images = serverReply.images),
t.timestamp = (new Date).getTime(),
delete t.isQuerying,
handleActions(null == serverReply ? void 0 : serverReply.actions, t),
handleBlocks(null == serverReply ? void 0 : serverReply.blocks),
handleShortcuts(null == serverReply ? void 0 : serverReply.shortcuts);
else if («assistant» === t.role && t.isStreaming) {
if (t.content = (0,
app_chatbot_MwaiAPI__WEBPACK_IMPORTED_MODULE_3_.W5)(«ai.reply», serverReply.reply, {
chatId,
botId
}),
serverReply.images && (t.images = serverReply.images),
t.timestamp = (new Date).getTime(),
delete t.isStreaming,
debugMode && t.streamEvents) {
var a;
const e = (new Date).getTime()
, n = e – ((null === (a = t.streamEvents[0]) || void 0 === a ? void 0 : a.timestamp) || e);
let s;
s = n < 1e3 ? ${n}ms : n < 6e4 ? ${(n / 1e3).toFixed(1)}s : ${Math.floor(n / 6e4)}m ${(n % 6e4 / 1e3).toFixed(0)}s, t.streamEvents.push({ type: «event», subtype: «status», data: Request completed in ${s}., timestamp: e }) } handleActions(null == serverReply ? void 0 : serverReply.actions, t), handleBlocks(null == serverReply ? void 0 : serverReply.blocks), handleShortcuts(null == serverReply ? void 0 : serverReply.shortcuts) } else { const t = { id: (0, app_helpers__WEBPACK_IMPORTED_MODULE_2_.vx)(), role: «assistant», content: (0, app_chatbot_MwaiAPI__WEBPACK_IMPORTED_MODULE_3_.W5)(«ai.reply», serverReply.reply, { botId, chatId, customId }), who: rawAiName, timestamp: (new Date).getTime() }; serverReply.images && (t.images = serverReply.images), handleActions(null == serverReply ? void 0 : serverReply.actions, t), handleBlocks(null == serverReply ? void 0 : serverReply.blocks), handleShortcuts(null == serverReply ? void 0 : serverReply.shortcuts), e.push(t) } serverReply.responseId && setPreviousResponseId(serverReply.responseId), setMessages(e), saveMessages(e) } ), [serverReply]); const onClear = useCallback((async ({chatId: e=null}={}) => {
e || (e = (0,
app_helpers__WEBPACK_IMPORTED_MODULE_2_.vx)()),
await setChatId(e),
localStorageKey && localStorage.removeItem(localStorageKey),
resetMessages(),
setInputText(«»),
setIsResumingConversation(!1),
setIsConversationLoaded(!0),
initialShortcuts.length > 0 ? handleShortcuts(initialShortcuts) : setShortcuts([]),
setBlocks([]),
setPreviousResponseId(null)
}
), [botId, initialShortcuts, handleShortcuts])
, onStartRealtimeSession = useCallback((async () => {
const e = {
botId,
customId,
contextId,
chatId
}
, t = restNonceRef.current ?? await refreshRestNonce()
, a = await (0,
app_helpers__WEBPACK_IMPORTED_MODULE_2_.ti)(${restUrl}/mwai-ui/v1/openai/realtime/start, e, t);
return await (0,
app_helpers__WEBPACK_IMPORTED_MODULE_2_.Pn)(a, null, null, null, debugMode)
}
), [botId, customId, contextId, chatId, restNonce, refreshRestNonce, restUrl])
, onCommitStats = useCallback((async (e, t=null) => {
try {
const a = restNonceRef.current ?? await refreshRestNonce()
, n = await (0,
app_helpers__WEBPACK_IMPORTED_MODULE_2_.ti)(${restUrl}/mwai-ui/v1/openai/realtime/stats, {
botId,
session: sessionId,
refId: t || chatId,
stats: e
}, a)
, s = await (0,
app_helpers__WEBPACK_IMPORTED_MODULE_2_.Pn)(n, null, null, null, debugMode);
return {
success: s.success,
message: s.message,
overLimit: s.overLimit || !1,
limitMessage: s.limitMessage || null
}
} catch (e) {
return console.error(«Error while committing stats.», e),
{
success: !1,
message: «An error occurred while committing the stats.»
}
}
}
), [botId, restNonce, refreshRestNonce, restUrl, sessionId, chatId])
, onCommitDiscussions = useCallback((async (e=[]) => {
try {
const t = restNonceRef.current ?? await refreshRestNonce()
, a = {
botId,
session: sessionId,
chatId,
messages: (e ?? []).filter((e => «error» !== e.role && !e.isError))
}
, n = await (0,
app_helpers__WEBPACK_IMPORTED_MODULE_2_.ti)(${restUrl}/mwai-ui/v1/openai/realtime/discussions, a, t)
, s = await (0,
app_helpers__WEBPACK_IMPORTED_MODULE_2_.Pn)(n, null, null, null, debugMode);
return {
success: s.success,
message: s.message
}
} catch (e) {
return console.error(«Error while committing discussion.», e),
{
success: !1,
message: «An error occurred while committing the discussion.»
}
}
}
), [botId, chatId, restNonce, refreshRestNonce, restUrl, sessionId])
, onRealtimeFunctionCallback = useCallback((async (functionId, functionType, functionName, functionTarget, args) => {
const body = {
functionId,
functionType,
functionName,
functionTarget,
arguments: args
};
if («js» !== functionTarget) {
const e = restNonceRef.current ?? await refreshRestNonce()
, t = await (0,
app_helpers__WEBPACK_IMPORTED_MODULE_2_.ti)(${restUrl}/mwai-ui/v1/openai/realtime/call, body, e)
, a = await (0,
app_helpers__WEBPACK_IMPORTED_MODULE_2_.Pn)(t, null, null, null, debugMode);
return a
}
{
const finalArgs = args ? Object.values(args).map((e => JSON.stringify(e))) : [];
try {
return debugMode && console.log([CHATBOT] CALL ${functionName}(${finalArgs.join(", ")})),
eval(${functionName}(${finalArgs.join(", ")})),
{
success: !0,
message: «The function was executed»,
data: null
}
} catch (e) {
return console.error(«Error while executing an action.», e),
{
success: !1,
message: «An error occurred while executing the function.»,
data: null
}
}
}
return null
}
), [restNonce, refreshRestNonce, restUrl, debugMode])
, onSubmit = useCallback((async e => {
var t;
if (busy)
return void console.error(«AI Engine: There is already a query in progress.»);
«string» != typeof e && (e = inputText);
const a = uploadedFile
, n = null == uploadedFile ? void 0 : uploadedFile.uploadedUrl
, s = null == uploadedFile || null === (t = uploadedFile.localFile) || void 0 === t ? void 0 : t.type
, r = !!s && s.startsWith(«image»);
let o = e;
n && (o = r ? \n${e} : [Uploaded File](${n})\n${e}),
setBusy(!0),
setInputText(«»),
setShortcuts([]),
setBlocks([]),
resetUploadedFile();
const i = …messages, { id: (0, app_helpers__WEBPACK_IMPORTED_MODULE_2_.vx)(), role: «user», content: o, who: rawUserName, timestamp: (new Date).getTime() };
saveMessages(i);
const l = (0,
app_helpers__WEBPACK_IMPORTED_MODULE_2_.vx)()
, c = […i, {
id: l,
role: «assistant»,
content: stream ? «» : null,
who: rawAiName,
timestamp: null,
isQuerying: !stream,
isStreaming: !!stream,
streamEvents: stream && debugMode ? [] : void 0
}];
if (setMessages(c),
«[ERROR]» === e) {
setBusy(!1);
const t = messages.slice(0, -1);
setMessages(t);
const n = [«Connection timeout: The server took too long to respond.», «Invalid API key: Please check your OpenAI API key in settings.», «Rate limit exceeded: Too many requests. Please try again later.», «Model overloaded: The AI model is currently experiencing high demand.», «Network error: Failed to establish connection to the AI service.», «Authentication failed: Your session has expired. Please refresh the page.», «Service unavailable: The AI service is temporarily down for maintenance.», «Invalid request: The message format was not recognized by the server.», «Quota exceeded: You have reached your usage limit for this period.», «Internal server error: An unexpected error occurred. Please try again.»]
, s = n[Math.floor(Math.random() * n.length)]
, r = {
id: (0,
app_helpers__WEBPACK_IMPORTED_MODULE_2_.vx)(),
role: «error»,
content: [TEST ERROR] ${s},
who: «Error»,
timestamp: (new Date).getTime(),
isError: !0,
failedQuery: {
text: e,
file: a
}
}
, o = […i, r];
return setMessages(o),
saveMessages(o),
void setLastFailedQuery({
text: e,
file: a
})
}
const u = {
botId,
customId,
session: sessionId,
chatId,
contextId,
messages: messages.filter((e => «error» !== e.role && !e.isError)),
newMessage: e,
newFileId: null == a ? void 0 : a.uploadedId,
stream,
…atts
};
previousResponseId && (u.previousResponseId = previousResponseId);
try {
debugMode && console.log(«[CHATBOT] OUT: «, u);
const e = stream ? (e, t) => {
debugMode && t && t.subtype && console.log(«[CHATBOT] STREAM EVENT:», t),
setMessages((a => {
const n = […a]
, s = n.length > 0 ? n[n.length – 1] : null;
return s && s.id === l && (s.content = e,
s.timestamp = (new Date).getTime(),
t && t.subtype && (s.streamEvents || (s.streamEvents = []),
s.streamEvents.push({
…t,
timestamp: (new Date).getTime()
}))),
n
}
))
}
: null
, t = restNonceRef.current ?? await refreshRestNonce();
stream && debugMode && e && e(«», {
type: «event»,
subtype: «status»,
data: «Request sent…»,
timestamp: (new Date).getTime()
});
const n = e => {
setRestNonce(e),
restNonceRef.current = e,
app_helpers_tokenManager__WEBPACK_IMPORTED_MODULE_1_.A.setToken(e)
}
, s = await (0,
app_helpers__WEBPACK_IMPORTED_MODULE_2_.ti)(${restUrl}/mwai-ui/v1/chats/submit, u, t, stream, void 0, n)
, r = await (0,
app_helpers__WEBPACK_IMPORTED_MODULE_2_.Pn)(s, e, debugMode ? «CHATBOT» : null, n, debugMode);
if (!r.success && r.message) {
const e = […c];
e.pop();
const t = e.length – 1;
let n = null
, s = null;
if (t >= 0 && «user» === e[t].role) {
const r = e[t].content
, o = r.match(/^(?:|[.?](.?))\n(.)$/s); n = o ? o[1] : r, o && (s = a) } return setMessages(e), saveMessages(e), addErrorMessage(r.message, n ? { text: n, file: s } : null), void setBusy(!1) } setServerReply(r) } catch (e) { console.error(«An error happened in the handling of the chatbot response.», { err: e }), setBusy(!1), setMessages((e => { const t = e[e.length – 1]; return !t || «assistant» !== t.role || «» !== t.content && null !== t.content ? e : e.slice(0, -1) } )); const t = messages.length; let n = null , s = null; if (t >= 0 && «user» === c[t].role) { const e = c[t].content , r = e.match(/^(?:|[.?](.?))\n(.)$/s);
n = r ? r[1] : e,
r && (s = a)
}
addErrorMessage(e.message || «An error occurred while processing your request. Please try again.», n ? {
text: n,
file: s
} : null)
}
}
), [busy, uploadedFile, messages, saveMessages, stream, botId, customId, sessionId, chatId, contextId, atts, inputText, debugMode, restNonce, refreshRestNonce, restUrl])
, onSubmitAction = useCallback(( (e=null) => {
var t;
const a = !(null == uploadedFile || !uploadedFile.uploadedId);
hasFocusRef.current = (null === (t = chatbotInputRef.current) || void 0 === t ? void 0 : t.currentElement) && document.activeElement === chatbotInputRef.current.currentElement(),
e ? onSubmit(e) : (a || inputText.length > 0) && onSubmit(inputText)
}
), [inputText, onSubmit, null == uploadedFile ? void 0 : uploadedFile.uploadedId])
, retryLastQuery = useCallback(( () => {
var e;
lastFailedQuery && (setInputText(lastFailedQuery.text),
lastFailedQuery.file && setUploadedFile(lastFailedQuery.file),
setLastFailedQuery(null),
null !== (e = chatbotInputRef.current) && void 0 !== e && e.focusInput && setTimeout(( () => {
chatbotInputRef.current.focusInput()
}
), 100))
}
), [lastFailedQuery, setInputText, chatbotInputRef])
, onFileUpload = async (e, t=»N/A», a=»N/A») => {
try {
if (null === e)
return void resetUploadedFile();
const n = {
type: t,
purpose: a
}
, s = ${restUrl}/mwai-ui/v1/files/upload
, r = restNonceRef.current ?? await refreshRestNonce()
, o = await (0,
app_helpers__WEBPACK_IMPORTED_MODULE_2_.uE)(s, e, r, (t => {
setUploadedFile({
localFile: e,
uploadedId: null,
uploadedUrl: null,
uploadProgress: t
})
}
), n);
setUploadedFile({
localFile: e,
uploadedId: o.data.id,
uploadedUrl: o.data.url,
uploadProgress: null
})
} catch (e) {
console.error(«onFileUpload Error», e),
addErrorMessage(e.message || «An unknown error occurred»),
resetUploadedFile()
}
}
, onUploadFile = async e => (setMessages((e => e.filter((e => !e.isError)))),
onFileUpload(e))
, resetUploadedFile = () => {
setUploadedFile({
localFile: null,
uploadedId: null,
uploadedUrl: null,
uploadProgress: null
})
}
, runTimer = useCallback(( () => {
const e = setTimeout(( () => {
setOpen((e => (e || setShowIconMessage(!0),
e)))
}
), 1e3 * iconTextDelay);
return () => clearTimeout(e)
}
), [iconText, iconTextDelay]);
useEffect(( () => {
if (iconText && !iconTextDelay)
setShowIconMessage(!0);
else if (iconText && iconTextDelay)
return runTimer()
}
), [iconText]);
const [tasks,setTasks] = useState([])
, runTasks = useCallback((async () => {
if (tasks.length > 0) {
const e = tasks[0];
if («ask» === e.action) {
const {text: t, submit: a} = e.data;
a ? onSubmit(t) : setInputText(t)
} else if («toggle» === e.action)
setOpen((e => !e));
else if («open» === e.action)
setOpen(!0);
else if («close» === e.action)
setOpen(!1);
else if («clear» === e.action) {
const {chatId: t} = e.data;
onClear({
chatId: t
})
} else if («setContext» === e.action) {
const {chatId: t, messages: a, previousResponseId: n} = e.data;
setChatId(t),
setMessages(a),
n && setPreviousResponseId(n),
setIsResumingConversation(!0),
setIsConversationLoaded(!0),
setShortcuts([]),
saveMessages(a)
} else if («setShortcuts» === e.action) {
const t = e.data;
handleShortcuts(t)
} else if («setBlocks» === e.action) {
const t = e.data;
handleBlocks(t)
} else if («addBlock» === e.action) {
const t = e.data;
setBlocks((e => […e, t]))
} else if («removeBlockById» === e.action) {
const t = e.data;
setBlocks((e => e.filter((e => e.id !== t))))
}
setTasks((e => e.slice(1)))
}
}
), [tasks, onClear, onSubmit, setChatId, setInputText, setMessages, setOpen, handleShortcuts, handleBlocks]);
useEffect(( () => {
runTasks()
}
), [runTasks]);
const actions = {
setInputText,
saveMessages,
setMessages,
resetMessages,
setError,
resetError,
addErrorMessage,
retryLastQuery,
onClear,
onSubmit,
onSubmitAction,
onFileUpload,
onUploadFile,
resetUploadedFile,
setUploadedFile,
setOpen,
setWindowed,
setShowIconMessage,
setIsListening,
setDraggingType,
setIsBlocked,
onStartRealtimeSession,
onRealtimeFunctionCallback,
onCommitStats,
onCommitDiscussions
}
, state = {
theme,
botId,
customId,
userData,
pluginUrl,
inputText,
messages,
shortcuts,
blocks,
busy,
error,
setBusy,
typewriter,
speechRecognition,
speechSynthesis,
virtualKeyboardFix,
localMemory,
isRealtime,
imageUpload,
fileUpload,
uploadedFile,
fileSearch,
textSend,
textClear,
textInputMaxLength,
textInputPlaceholder,
textCompliance,
aiName,
userName,
guestName,
aiAvatar,
userAvatar,
guestAvatar,
aiAvatarUrl,
userAvatarUrl,
guestAvatarUrl,
isWindow,
copyButton,
headerSubtitle,
fullscreen,
icon,
iconText,
iconAlt,
iconPosition,
iconBubble,
cssVariables,
iconUrl,
chatbotInputRef,
conversationRef,
isMobile,
open,
locked,
windowed,
showIconMessage,
timeElapsed,
isListening,
speechRecognitionAvailable,
uploadIconPosition,
submitButtonConf,
draggingType,
isBlocked,
busyNonce,
debugMode,
eventLogs,
system
};
return React.createElement(ChatbotContext.Provider, {
value: {
state,
actions
}
}, children)
}
}
,
137: (e, t, a) => {
a.d(t, {
HX: () => s,
W5: () => r
});
class n {
constructor() {
if («undefined» != typeof window && window.MwaiAPI)
return window.MwaiAPI;
this.chatbots = [],
this.forms = [],
this.filters = {},
this.actions = {},
«undefined» != typeof window && (window.MwaiAPI = this)
}
getChatbot(e=null) {
return e ? this.chatbots.find((t => t.botId === e || t.customId === e)) : this.chatbots[0]
}
getForm(e=null) {
return e ? this.forms.find((t => t.formId === e)) : this.forms[0]
}
addFilter(e, t, a=10) {
this.filters[e] || (this.filters[e] = []),
this.filters[e].push({
callback: t,
priority: a
}),
this.filters[e].sort(( (e, t) => e.priority – t.priority))
}
applyFilters(e, t, …a) {
return this.filters[e] ? this.filters[e].reduce(( (e, t) => t.callback(e, …a)), t) : t
}
addAction(e, t, a=10) {
this.actions[e] || (this.actions[e] = []),
this.actions[e].push({
callback: t,
priority: a
}),
this.actions[e].sort(( (e, t) => e.priority – t.priority))
}
doAction(e, …t) {
this.actions[e] && this.actions[e].forEach((e => {
e.callback(…t)
}
))
}
}
const s = ( () => {
if («undefined» != typeof window && window.MwaiAPI)
return window.MwaiAPI;
const e = new n;
return «undefined» != typeof window && (window.MwaiAPI = e),
e
}
)()
, r = (e, t, …a) => s.applyFilters(e, t, …a)
}
,
728: (e, t, a) => {
a.d(t, {
tm: () => u,
bE: () => f,
Mc: () => h,
mv: () => m,
$: () => g, dh: () => p, gR: () => d, Vw: () => ,
kW: () => y
});
const n = (0,
a(407).A)(«Mic», [[«path», {
d: «M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z»,
key: «131961»
}], [«path», {
d: «M19 10v2a7 7 0 0 1-14 0v-2»,
key: «1vc78b»
}], [«line», {
x1: «12»,
x2: «12»,
y1: «19»,
y2: «22»,
key: «x3vr5v»
}]]);
function s() {
return s = Object.assign ? Object.assign.bind() : function(e) {
for (var t = 1; t < arguments.length; t++) { var a = arguments[t]; for (var n in a) Object.prototype.hasOwnProperty.call(a, n) && (e[n] = a[n]) } return e } , s.apply(this, arguments) } const {useState: r, useMemo: o, useEffect: i, useRef: l, useCallback: c} = wp.element , u = ({active: e, disabled: t, …a}) => React.createElement(«div», s({
active: e ? «true» : «false»,
disabled: t
}, a), React.createElement(n, {
size: «24»
}))
, d = () => o(( () => (e, t) => (Array.isArray(e) || (e = [e]),
t && Object.entries(t).forEach(( ([t,a]) => {
a && e.push(t)
}
)),
e.join(» «))), []);
function m(e) {
return !(!e || «string» != typeof e) && 0 === e.indexOf(«http»)
}
function p() {
const [e,t] = r(null)
, a = l(null);
return i(( () => () => {
clearInterval(a.current)
}
), []),
{
timeElapsed: e,
startChrono: function() {
if (null !== a.current)
return;
const e = Date.now();
a.current = setInterval(( () => {
const a = Math.floor((Date.now() – e) / 1e3);
var n;
t((n = a,${Math.floor(n / 60)}:${(n % 60).toString().padStart(2, "0")}))
}
), 500)
},
stopChrono: function() {
clearInterval(a.current),
a.current = null,
t(null)
}
}
}
const h = (e, t) => «string» == typeof e && t ? (Object.entries(t).forEach(( ([t,a]) => {
e = e.replace(new RegExp({${t}},»g»), a)
}
)),
e) : e
, g = (e, t=[]) => {
var a, n, s, r, o, i, l, c, u, d, m, p, g, , f; const y = (null === (a = e.guestName) || void 0 === a ? void 0 : a.trim()) ?? «» , b = (null === (n = e.textSend) || void 0 === n ? void 0 : n.trim()) ?? «» , v = (null === (s = e.textClear) || void 0 === s ? void 0 : s.trim()) ?? «» , E = parseInt(e.textInputMaxLength) , R = (null === (r = e.textInputPlaceholder) || void 0 === r ? void 0 : r.trim()) ?? «»; let w = (null === (o = e.textCompliance) || void 0 === o ? void 0 : o.trim()) ?? «» , C = «»; const k = Boolean(e.window) , x = Boolean(e.copyButton) , S = Boolean(e.fullscreen) , I = (null === (i = e.icon) || void 0 === i ? void 0 : i.trim()) ?? «»; let M = (null === (l = e.iconText) || void 0 === l ? void 0 : l.trim()) ?? «»; const T = parseInt(e.iconTextDelay || 1) , A = (null === (c = e.iconAlt) || void 0 === c ? void 0 : c.trim()) ?? «» , N = (null === (u = e.iconPosition) || void 0 === u ? void 0 : u.trim()) ?? «» , L = Boolean(e.iconBubble) , D = (null === (d = e.aiName) || void 0 === d ? void 0 : d.trim()) ?? «» , U = (null === (m = e.userName) || void 0 === m ? void 0 : m.trim()) ?? «» , P = Boolean(null == e ? void 0 : e.aiAvatar) , O = Boolean(null == e ? void 0 : e.userAvatar) , B = Boolean(null == e ? void 0 : e.guestAvatar) , F = P ? (null == e || null === (p = e.aiAvatarUrl) || void 0 === p ? void 0 : p.trim()) ?? «» : null , z = O ? (null == e || null === (g = e.userAvatarUrl) || void 0 === g ? void 0 : g.trim()) ?? «» : null , $ = B ? (null == e || null === ( = e.guestAvatarUrl) || void 0 === _ ? void 0 : .trim()) ?? «» : null , j = Boolean(e.localMemory) , W = Boolean(e.imageUpload) , H = Boolean(e.fileUpload) , V = Boolean(e.fileSearch) , K = (null === (f = e.mode) || void 0 === f ? void 0 : f.trim()) ?? «chat»; var q; return C = null === e.headerSubtitle || void 0 === e.headerSubtitle ? «Discuss with» : (null === (q = e.headerSubtitle) || void 0 === q ? void 0 : q.trim()) ?? «», t && (w = h(w, t), M = h(M, t)), { textSend: b, textClear: v, textInputMaxLength: E, textInputPlaceholder: R, textCompliance: w, mode: K, window: k, copyButton: x, fullscreen: S, localMemory: j, imageUpload: W, fileUpload: H, fileSearch: V, icon: I, iconText: M, iconTextDelay: T, iconAlt: A, iconPosition: N, iconBubble: L, headerSubtitle: C, aiName: D, userName: U, guestName: y, aiAvatar: P, userAvatar: O, guestAvatar: B, aiAvatarUrl: F, userAvatarUrl: z, guestAvatarUrl: $ } } , = e => {
const [t,a] = r(!1)
, [n,s] = r(!1);
return i(( () => {
«undefined» != typeof window && («SpeechRecognition»in window || «webkitSpeechRecognition»in window) && s(!0)
}
), []),
i(( () => {
if (!n)
return;
const s = new (window.SpeechRecognition || window.webkitSpeechRecognition);
let r = null;
return navigator.userAgent.toLowerCase().indexOf(«android») > -1 ? (s.interimResults = !1,
s.continuous = !1,
r = t => {
const n = Array.from(t.results).filter((e => e.isFinal)).map((e => e[0].transcript)).join(«»);
e(n),
a(!1)
}
) : (s.interimResults = !0,
s.continuous = !0,
r = t => {
const a = Array.from(t.results).map((e => e[0])).map((e => e.transcript)).join(«»);
e(a)
}
),
t ? (s.addEventListener(«result», r),
s.start()) : (s.removeEventListener(«result», r),
s.abort()),
() => {
s.abort()
}
}
), [t, n]),
{
isListening: t,
setIsListening: a,
speechRecognitionAvailable: n
}
}
, f = ({if: e, className: t, disableTransition: a=!1, children: n, …o}) => {
const [l,c] = r(!1)
, [u,d] = r(«mwai-transition»);
return i(( () => {
a ? c(e) : e ? (c(!0),
setTimeout(( () => {
d(«mwai-transition mwai-transition-visible»)
}
), 150)) : d(«mwai-transition»)
}
), [e, a]),
l ? React.createElement(«div», s({
className: ${t} ${a ? "" : u},
onTransitionEnd: () => {
«mwai-transition» !== u || a || c(!1)
}
}, o), n) : null
}
, y = () => {
const [e,t] = r(window.visualViewport.height)
, a = o(( () => /Android/.test(navigator.userAgent)), [])
, n = o(( () => /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream), [])
, s = l(window.visualViewport)
, u = c(( () => {
t(s.current.height)
}
), []);
return i(( () => {
const e = s.current;
return e.addEventListener(«resize», u),
n ? (window.addEventListener(«resize», u),
document.addEventListener(«focusin», u)) : e.addEventListener(«scroll», u),
() => {
e.removeEventListener(«resize», u),
n ? (window.removeEventListener(«resize», u),
document.removeEventListener(«focusin», u)) : e.removeEventListener(«scroll», u)
}
}
), [u, n]),
{
viewportHeight: e,
isIOS: n,
isAndroid: a
}
}
}
,
678: (e, t, a) => {
a.d(t, {
F1: () => o,
Pn: () => i,
Ve: () => p,
rn: () => d,
ti: () => l,
uE: () => c,
vx: () => u
});
const {useMemo: n, useEffect: s, useState: r} = wp.element;
function o(e, t=null, a=!0) {
const n = [];
return JSON.stringify(e, ( (e, t) => {
if («object» == typeof t && null !== t) {
if (n.includes(t)) {
if (!a)
throw console.warn(«Circular reference found.», {
key: e,
value: t,
cache: n,
cacheIndex: n.indexOf(t)
}),
new Error(«Circular reference found. Cancelled.»);
return
}
n.push(t)
}
return t
}
), t)
}
async function i(e, t, a=null, n=null, s=!1) {
if (!t)
try {
const t = await e.json();
return a && console.log([${a}] IN:, t),
t.new_token && (s && console.log(«[MWAI] Token refreshed!»),
n && n(t.new_token)),
t
} catch (e) {
return console.error(«Could not parse the regular response.», {
err: e,
data
}),
{
success: !1,
message: «Could not parse the regular response.»
}
}
const r = e.body.getReader()
, o = new TextDecoder(«utf-8»);
let i = «»
, l = «»;
for (; ; ) {
const {value: e, done: c} = await r.read();
if (i += o.decode(e, {
stream: !0
}),
c)
break;
const u = i.split(«\n»);
for (let e = 0; e < u.length – 1; e++) { if (0 !== u[e].indexOf(«data: «)) continue; const r = JSON.parse(u[e].replace(«data: «, «»)); if («live» === r.type) a && console.log([${a} STREAM] LIVE:, r), r.subtype ? (t && t(l, r), «content» === r.subtype && (l += r.data)) : (l += r.data, t && t(l, r.data)); else if («error» === r.type) try { return a && console.error([${a} STREAM] ERROR:, r.data), { success: !1, message: r.data } } catch (e) { return console.error(«Could not parse the ‘error’ stream.», { err: e, data: r }), { success: !1, message: «Could not parse the ‘error’ stream.» } } else if («end» === r.type) try { const e = JSON.parse(r.data); return a && console.log([${a} STREAM] END:, e), e.new_token && (s && console.log(«[MWAI] Token refreshed!»), n && n(e.new_token)), e } catch (e) { return console.error(«Could not parse the ‘end’ stream.», { err: e, data: r }), { success: !1, message: «Could not parse the ‘end’ stream.» } } } i = u[u.length – 1] } try { const e = JSON.parse(i); return a && console.log([${a} STREAM] IN:, e), e } catch (e) { return console.error(«Could not parse the buffer.», { err: e, buffer: i }), { success: !1, message: «Could not parse the buffer.» } } } async function l(e, t, a, n, s=void 0, r=null) { const i = { «Content-Type»: «application/json» }; a && (i[«X-WP-Nonce»] = a), n && (i.Accept = «text/event-stream»); const l = await fetch(${e}, { method: «POST», headers: i, body: o(t), credentials: «same-origin», signal: s }); if (403 === l.status || 401 === l.status) try { const e = await l.clone().json(); if («rest_cookie_invalid_nonce» === e.code || «rest_forbidden» === e.code) throw console.error(«[MWAI] Authentication token has expired. Please refresh the page to continue.»), new Error(«Your session has expired. Please refresh the page to continue using AI Engine.») } catch (e) { if (e.message && e.message.includes(«session has expired»)) throw e } if (!n && l.ok) try { const e = l.clone() , t = await e.json(); t.new_token && r && r(t.new_token) } catch (e) {} return l } async function c(e, t, a, n, s={}) { return new Promise(( (r, o) => {
const i = new FormData;
i.append(«file», t);
for (const [e,t] of Object.entries(s))
i.append(e, t);
const l = new XMLHttpRequest;
l.open(«POST», e, !0),
a && l.setRequestHeader(«X-WP-Nonce», a),
l.upload.onprogress = function(e) {
if (e.lengthComputable && n) {
const t = e.loaded / e.total * 100;
n(t)
}
}
,
l.onload = function() {
if (l.status >= 200 && l.status < 300) try { const e = JSON.parse(l.responseText); r(e) } catch (e) { o({ status: l.status, statusText: l.statusText, error: «The server response is not valid JSON» }) } else { try { const e = JSON.parse(l.responseText); return void o({ status: l.status, message: e.message }) } catch (e) {} o({ status: l.status, statusText: l.statusText }) } } , l.onerror = function() { o({ status: l.status, statusText: l.statusText }) } , l.send(i) } )) } function u() { return Math.random().toString(36).substring(2) } const d = () => {
const [e,t] = r(!0);
s(( () => {
const e = setTimeout(( () => {
const e = setInterval(( () => {
t((e => !e))
}
), 500);
return () => clearInterval(e)
}
), 200);
return () => clearTimeout(e)
}
), []);
const a = {
opacity: e ? 1 : 0,
width: «1px»,
height: «1em»,
borderLeft: «8px solid»,
marginLeft: «2px»
};
return React.createElement(«span», {
style: a
})
}
, m = /([\u2700-\u27BF]|[\uE000-\uF8FF]|[\uD800-\uDFFF]|[\uFE00-\uFE0F]|[\u1F100-\u1F1FF]|[\u1F200-\u1F2FF]|[\u1F300-\u1F5FF]|[\u1F600-\u1F64F]|[\u1F680-\u1F6FF]|[\u1F700-\u1F77F]|[\u1F780-\u1F7FF]|[\u1F800-\u1F8FF]|[\u1F900-\u1F9FF]|[\u1FA00-\u1FA6F])/;
function p(e) {
return e && 2 === e.length && m.test(e)
}
}
,
213: (e, t, a) => {
a.d(t, {
A: () => s
});
const n = new class {
constructor() {
this.token = null,
this.listeners = new Set
}
setToken(e) {
this.token !== e && (this.token = e,
this.notifyListeners())
}
getToken() {
return this.token
}
subscribe(e) {
return this.listeners.add(e),
() => this.listeners.delete(e)
}
notifyListeners() {
this.listeners.forEach((e => e(this.token)))
}
}
;
«undefined» != typeof window && window.mwai && window.mwai.rest_nonce && n.setToken(window.mwai.rest_nonce);
const s = n
}
,
407: (e, t, a) => {
a.d(t, {
A: () => i
});
var n = a(594);
const s = (…e) => e.filter(( (e, t, a) => Boolean(e) && «» !== e.trim() && a.indexOf(e) === t)).join(» «).trim();
var r = {
xmlns: «http://www.w3.org/2000/svg»,
width: 24,
height: 24,
viewBox: «0 0 24 24»,
fill: «none»,
stroke: «currentColor»,
strokeWidth: 2,
strokeLinecap: «round»,
strokeLinejoin: «round»
};
const o = (0,
n.forwardRef)(( ({color: e=»currentColor», size: t=24, strokeWidth: a=2, absoluteStrokeWidth: o, className: i=»», children: l, iconNode: c, …u}, d) => (0,
n.createElement)(«svg», {
ref: d,
…r,
width: t,
height: t,
stroke: e,
strokeWidth: o ? 24 * Number(a) / Number(t) : a,
className: s(«lucide», i),
…u
}, […c.map(( ([e,t]) => (0,
n.createElement)(e, t))), …Array.isArray(l) ? l : [l]])))
, i = (e, t) => {
const a = (0,
n.forwardRef)(( ({className: a, …r}, i) => {
return (0,
n.createElement)(o, {
ref: i,
iconNode: t,
className: s(lucide-${l = e, l.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase()}, a),
…r
});
var l
}
));
return a.displayName = ${e},
a
}
}
,
594: e => {
e.exports = React
}
}
, webpack_module_cache = {};
function webpack_require(e) {
var t = webpack_module_cache[e];
if (void 0 !== t)
return t.exports;
var a = webpack_module_cache[e] = {
exports: {}
};
return webpack_modules[e](a, a.exports, webpack_require),
a.exports
}
webpack_require.d = (e, t) => {
for (var a in t)
webpack_require.o(t, a) && !webpack_require.o(e, a) && Object.defineProperty(e, a, {
enumerable: !0,
get: t[a]
})
}
,
webpack_require.o = (e, t) => Object.prototype.hasOwnProperty.call(e, t);
var webpack_exports = {}
, ChatbotContext = webpack_require(469)
, helpers = webpack_require(728);
const BouncingDots = () => {
const e = {
width: 9,
height: 9,
margin: «5px 0px 0px 5px»,
borderRadius: «50%»,
backgroundColor: «#a3a1a1»,
opacity: 1,
animation: «bouncing-loader 0.4s infinite alternate»
};
return React.createElement(React.Fragment, null, React.createElement(«style», null, «\n @keyframes bouncing-loader {\n to {\n opacity: 0.6;\n transform: translateY(-10px);\n }\n }\n «), React.createElement(«div», {
style: {
display: «flex»,
justifyContent: «center»,
alignItems: «center»,
width: «100%»,
height: 26
}
}, [«0.1s», «0.2s», «0.3s»].map(( (t, a) => React.createElement(«div», {
key: a,
style: {
…e,
animationDelay: t
}
})))))
}
;
function extends() { return _extends = Object.assign ? Object.assign.bind() : function(e) { for (var t = 1; t < arguments.length; t++) { var a = arguments[t]; for (var n in a) Object.prototype.hasOwnProperty.call(a, n) && (e[n] = a[n]) } return e } , _extends.apply(this, arguments) } const {useState, useEffect, useRef, useCallback} = wp.element , svgPathDefault = » , svgPathSuccess = » , svgPathError = » , ReplyActions = ({enabled: e, content: t, children: a, className: n, …s}) => { const r = (0, helpers.gR)() , [o,i] = useState(«idle») , [l,c] = useState(!0) , u = useRef(null) , d = useRef(!1) , m = useCallback(( () => { d.current || (d.current = !0, u.current = setTimeout(( () => { c(!1) } ), 500)) } ), []) , p = useCallback(( () => { u.current && clearTimeout(u.current), c(!0), d.current = !1 } ), []); useEffect(( () => () => { u.current && clearTimeout(u.current) } ), []); const h = «success» === o ? svgPathSuccess : «error» === o ? svgPathError : svgPathDefault; return React.createElement(«div», _extends({}, s, { onMouseLeave: p, onMouseEnter: m, onMouseOver: m }), React.createElement(«span», { className: n }, a), React.createElement(«div», { className: r(«mwai-reply-actions», { «mwai-hidden»: l }) }, e && React.createElement(«div», { className: «mwai-copy-button», onClick: () => { try { navigator.clipboard.writeText(t), i(«success») } catch (e) { i(«error»), console.warn(«Not allowed to copy to clipboard. Make sure your website uses HTTPS.», { content: t }) } finally { setTimeout(( () => { i(«idle») } ), 2e3) } } }, React.createElement(«svg», { xmlns: «http://www.w3.org/2000/svg», viewBox: «0 0 24 24», dangerouslySetInnerHTML: { html: h } })))) } , components_ReplyActions = ReplyActions , {useState: ErrorReplyActions_useState} = wp.element , svgPathCopy = » , ErrorReplyActions_svgPathSuccess = » , ErrorReplyActions_svgPathError = » , svgPathRetry = » , svgPathDelete = » , ErrorReplyActions = ({enabled: e, content: t, children: a, className: n, message: s, …r}) => { const o = (0, helpers.gR)() , {actions: i, state: l} = (0, ChatbotContext.o)() , {setMessages: c, saveMessages: u, retryLastQuery: d} = i , {messages: m} = l , [p,h] = ErrorReplyActions_useState(«idle») , g = m.length > 0 && m[m.length – 1].id === s.id , = «success» === p ? ErrorReplyActions_svgPathSuccess : «error» === p ? ErrorReplyActions_svgPathError : svgPathCopy;
return React.createElement(«div», r, React.createElement(«span», {
className: n
}, a), React.createElement(«div», {
className: o(«mwai-reply-actions»)
}, React.createElement(«div», {
className: «mwai-copy-button»,
onClick: () => {
try {
navigator.clipboard.writeText(t),
h(«success»)
} catch (e) {
h(«error»),
console.warn(«Not allowed to copy to clipboard. Make sure your website uses HTTPS.», {
content: t
})
} finally {
setTimeout(( () => {
h(«idle»)
}
), 2e3)
}
}
,
title: «Copy»
}, React.createElement(«svg», {
xmlns: «http://www.w3.org/2000/svg»,
viewBox: «0 0 24 24»,
dangerouslySetInnerHTML: {
_html:
}
})), React.createElement(«div», {
className: «mwai-action-button»,
onClick: () => {
c((e => {
const t = e.findIndex((e => e.id === s.id));
let a;
return a = t > 0 ? e.filter(( (e, a) => a !== t && a !== t – 1)) : e.filter((e => e.id !== s.id)),
u(a),
a
}
))
}
,
title: «Delete»
}, React.createElement(«svg», {
xmlns: «http://www.w3.org/2000/svg»,
viewBox: «0 0 24 24»,
dangerouslySetInnerHTML: {
_html: svgPathDelete } })), s.failedQuery && g && React.createElement(«div», { className: «mwai-action-button», onClick: () => { s.failedQuery && d && (c((e => { const t = e.findIndex((e => e.id === s.id)); let a; return a = t > 0 ? e.filter(( (e, a) => a !== t && a !== t – 1)) : e.filter((e => e.id !== s.id)), u(a), a } )), d()) } , title: «Retry» }, React.createElement(«svg», { xmlns: «http://www.w3.org/2000/svg», viewBox: «0 0 24 24», dangerouslySetInnerHTML: { __html: svgPathRetry } })))) } , chatbot_ErrorReplyActions = ErrorReplyActions; var js_helpers = __webpack_require(678); const {useMemo} = wp.element , ChatbotName = ({role: e=»user»}) => { const {state: t} = (0, ChatbotContext.o)() , {pluginUrl: a, iconUrl: n, userData: s, userName: r, aiName: o, guestName: i, userAvatar: l, aiAvatar: c, guestAvatar: u, userAvatarUrl: d, aiAvatarUrl: m, guestAvatarUrl: p} = t , h = useMemo(( () => { const t = «assistant» === e , h = !s && !t , g = e => React.createElement(«div», { className: «mwai-name-text» }, e) , = (e, t, n, s, r=!1) => {
if (!e)
return null;
if ((0,
js_helpers.Ve)(t))
return o = t,
React.createElement(«div», {
className: «mwai-avatar mwai-emoji»,
style: {
fontSize: «32px»,
lineHeight: «32px»
}
}, o);
var o;
const i = ( (e, t=!1) => (0,
helpers.mv)(e) ? e : e && !(0,
js_helpers.Ve)(e) ? t ? e : ${a}/images/${e} : (t || (0,
js_helpers.Ve)(e) || console.warn(«Invalid URL for avatar:», e),
null))(t, r) || n;
return i ? ( (e, t) => React.createElement(«div», {
className: «mwai-avatar»
}, React.createElement(«img», {
width: «32»,
height: «32»,
src: e,
alt: t
})))(i, s) : null
}
;
if (t) {
const e = (c, m, n, «AI Avatar»); return e ? (null === m && n && console.warn(«Using iconUrl as a temporary fallback for AI avatar. Please set aiAvatarUrl.»), e) : g(o) } if (!h) { return (l, d, null == s ? void 0 : s.AVATAR_URL, «User Avatar», !0) || g(formatName(r, i, s))
}
if (h) {
return (u, p, null, «Guest Avatar») || g(i || «Guest») } } ), [e, o, r, i, s, n, c, l, u, m, d, p, a]); return React.createElement(«span», { className: «mwai-name» }, h) } ; function formatName(e, t, a) { return a && 0 !== Object.keys(a).length ? Object.entries(a).reduce(( (e, [t,a]) => { const n = {${t}}; return e.includes(n) ? e.replace(n, a) : e } ), e) : t || e || «Guest» } const chatbot_ChatbotName = ChatbotName; var external_React = webpack_require(594);
function t() {
return t = Object.assign ? Object.assign.bind() : function(e) {
for (var t = 1; t < arguments.length; t++) { var a = arguments[t]; for (var n in a) Object.prototype.hasOwnProperty.call(a, n) && (e[n] = a[n]) } return e } , t.apply(this, arguments) } const n = null , r = { blockQuote: «0», breakLine: «1», breakThematic: «2», codeBlock: «3», codeFenced: «4», codeInline: «5», footnote: «6», footnoteReference: «7», gfmTask: «8», heading: «9», headingSetext: «10», htmlBlock: «11», htmlComment: «12», htmlSelfClosing: «13», image: «14», link: «15», linkAngleBraceStyleDetector: «16», linkBareUrlDetector: «17», linkMailtoDetector: «18», newlineCoalescer: «19», orderedList: «20», paragraph: «21», ref: «22», refImage: «23», refLink: «24», table: «25», tableSeparator: «26», text: «27», textBolded: «28», textEmphasized: «29», textEscaped: «30», textMarked: «31», textStrikethroughed: «32», unorderedList: «33» }; var i; !function(e) { e[e.MAX = 0] = «MAX», e[e.HIGH = 1] = «HIGH», e[e.MED = 2] = «MED», e[e.LOW = 3] = «LOW», e[e.MIN = 4] = «MIN» }(i || (i = {})); const l = [«allowFullScreen», «allowTransparency», «autoComplete», «autoFocus», «autoPlay», «cellPadding», «cellSpacing», «charSet», «className», «classId», «colSpan», «contentEditable», «contextMenu», «crossOrigin», «encType», «formAction», «formEncType», «formMethod», «formNoValidate», «formTarget», «frameBorder», «hrefLang», «inputMode», «keyParams», «keyType», «marginHeight», «marginWidth», «maxLength», «mediaGroup», «minLength», «noValidate», «radioGroup», «readOnly», «rowSpan», «spellCheck», «srcDoc», «srcLang», «srcSet», «tabIndex», «useMap»].reduce(( (e, t) => (e[t.toLowerCase()] = t,
e)), {
for: «htmlFor»
})
, a = {
amp: «&»,
apos: «‘»,
gt: «>»,
lt: «<«, nbsp: » «, quot: «“» } , o = [«style», «script»] , c = /([-A-Z0-9_:]+)(?:\s=\s(?:(?:»((?:\.|[^»]))»)|(?:'((?:\.|[^’]))’)|(?:{((?:\.|{[^}]?}|[^}]))})))?/gi , s = /mailto:/i , d = /\n{2,}$/ , u = /^(\s>[\s\S]?)(?=\n{2,})/ , p = /^ *> ?/gm
, f = /^ {2,}\n/
, h = /^(?:( *[-*])){3,} *(?:\n )+\n/ , m = /^\s({3,}|~{3,}) *(\S+)?([^\n]*?)?\n([\s\S]+?)\s*\1 *(?:\n *)*\n?/ , g = /^(?: {4}[^\n]+\n*)+(?:\n *)+\n?/ , y = /^(+)\s([\s\S]?^])\s*\1(?!)/ , k = /^(?:\n )\n/ , x = /\r\n?/g , b = /^[\^([^]]+)((\n+ {4,}.)|(\n(?![\^).+)))/
, v = /^[\^([^]]+)]/
, S = /\f/g
, E = /^—[ \t]\n(.|\n)\n—[ \t]\n/ , $ = /^\s?[(x|\s)]/
, w = /^ *(#{1,6}) *([^\n]+?)(?: +#*)?(?:\n *)*(?:\n|$)/
, C = /^ *(#{1,6}) +([^\n]+?)(?: +#*)?(?:\n *)*(?:\n|$)/
, z = /^([^\n]+)\n *(=|-){3,} *(?:\n *)+\n/
, L = /^ (?!<[a-z][^ >/] ?\/>)<([a-z][^ >/]) ?((?:[^>][^/])?)>\n?(\s(?:<\1[^>]?>[\s\S]?<\/\1>|(?!<\1\b)[\s\S])?)<\/\1>(?!<\/\1>)\n/i , A = /&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-fA-F]{1,6});/gi , T = /^)/ , O = /^(data|aria|x)-[a-z][a-z\d_.-]$/
, B = /^ <([a-z][a-z0-9:])(?:\s+((?:<.?>|[^>])))?\/?>(?!<\/\1>)(\s\n)?/i , M = /^{.}$/
, R = /^(https?:\/\/[^\s<]+[^<.,:;»‘)]\s])/ , I = /^<([^ >]+@[^ >]+)>/
, U = /^<([^ >]+:\/[^ >]+)>/
, D = /-([a-z])?/gi
, j = /^(.|.)\n(?: *(|? *[-:]+ |[-| :])\n((?:.|.\n)))?\n?/ , N = /^[([^]])]:\s+]+)>?\s(«([^»])»)?/
, H = /^![([^]])] ?[([^]])]/
, F = /^[([^]])] ?[([^]])]/
, P = /([|])/g
, _ = /(\n|^[-*]\s|^#|^ {2,}|^-{2,}|^>\s)/
, W = /\t/g
, G = /(^ *||| *$)/g
, Z = /^ *:-+: *$/
, q = /^ *:-+ *$/
, Q = /^ *-+: $/ , V = «((?:\[.?\][([].?[)\]]|<.?>(?:.?<.?>)?|.*?|.?|==.?==|.|\n)?)» , X = new RegExp(^([*_])\\1${V}\\1\\1(?!\\1)) , J = new RegExp(^([*_])${V}\\1(?!\\1|\\w)) , K = new RegExp(^==${V}==) , Y = new RegExp(^~~${V}~~) , ee = /^\([^0-9A-Za-z\s])/ , te = /^[\s\S]+?(?=[^0-9A-Z\s\u00c0-\uffff&#;.()'»]|\d+.|\n\n| {2,}\n|\w+:\S|$)/i , ne = /^\n+/ , re = /^([ \t])/
, ie = /\([^\])/g
, le = / *\n+$/
, ae = /(?:^|\n)( *)$/
, oe = «(?:\d+\.)»
, ce = «(?:[*+-])»;
function se(e) {
return «( *)(» + (1 === e ? oe : ce) + «) +»
}
const de = se(1)
, ue = se(2);
function pe(e) {
return new RegExp(«^» + (1 === e ? de : ue))
}
const fe = pe(1)
, he = pe(2);
function me(e) {
return new RegExp(«^» + (1 === e ? de : ue) + «[^\n](?:\n(?!\1″ + (1 === e ? oe : ce) + » )[^\n])*(\n|$)»,»gm»)
}
const ge = me(1)
, ye = me(2);
function ke(e) {
const t = 1 === e ? oe : ce;
return new RegExp(«^( *)(» + t + «) [\s\S]+?(?:\n{2,}(?! )(?!\1″ + t + » (?!» + t + » ))\n|\s\n$)») } const xe = ke(1) , be = ke(2); function ve(e, t) { const a = 1 === t , n = a ? xe : be , s = a ? ge : ye , o = a ? fe : he; return { match(e, t, a) { const s = ae.exec(a); return s && (t.list || !t.inline && !t.simple) ? n.exec(e = s[1] + e) : null }, order: 1, parse(e, t, n) { const r = a ? +e[2] : void 0 , i = e[0].replace(d, «\n»).match(s); let l = !1; return { items: i.map((function(e, a) { const s = o.exec(e)[0].length , r = new RegExp(«^ {1,» + s + «}»,»gm») , c = e.replace(r, «»).replace(o, «») , u = a === i.length – 1 , d = -1 !== c.indexOf(«\n\n») || u && l; l = d; const m = n.inline , p = n.list; let h; n.list = !0, d ? (n.inline = !1, h = c.replace(le, «\n\n»)) : (n.inline = !0, h = c.replace(le, «»)); const g = t(h, n); return n.inline = m, n.list = p, g } )), ordered: a, start: r } }, render: (t, a, n) => e(t.ordered ? «ol» : «ul», { key: n.key, start: t.type === r.orderedList ? t.start : void 0 }, t.items.map((function(t, s) { return e(«li», { key: s }, a(t, n)) } ))) } } const Se = new RegExp(«^\[((?:\[[^\]]\]|[^\[\]]|\](?=[^\[]\])))\]\(\s\)|[^\s\\]|\\.)?)>?(?:\s+‘\»[‘\»])?\s\)»)
, Ee = /^])|[^() ])) «?([^)»])?»?)/
, $e = [u, m, g, w, z, C, T, j, ge, xe, ye, be]
, we = […$e, /^[^\n]+(?: \n|\n{2,})/, L, B];
function Ce(e) {
return e.replace(/[ÀÁÂÃÄÅàáâãä忯]/g, «a»).replace(/[çÇ]/g, «c»).replace(/[ðÐ]/g, «d»).replace(/[ÈÉÊËéèêë]/g, «e»).replace(/[ÏïÎîÍíÌì]/g, «i»).replace(/[Ññ]/g, «n»).replace(/[øØœŒÕõÔôÓóÒò]/g, «o»).replace(/[ÜüÛûÚúÙù]/g, «u»).replace(/[ŸÿÝý]/g, «y»).replace(/[^a-z0-9- ]/gi, «»).replace(/ /gi, «-«).toLowerCase()
}
function ze(e) {
return Q.test(e) ? «right» : Z.test(e) ? «center» : q.test(e) ? «left» : null
}
function Le(e, t, a, n) {
const s = a.inTable;
a.inTable = !0;
let o = e.trim().split(/( (?:[^]|<.*?>.*?<\/.*?>(?!<\/.*?>)|\\|||) *)/).reduce(( (e, s) => ("|" === s.trim() ? e.push(n ? { type: r.tableSeparator } : { type: r.text, text: s }) : "" !== s && e.push.apply(e, t(s, a)), e)), []); a.inTable = s; let i = [[]]; return o.forEach((function(e, t) { e.type === r.tableSeparator ? 0 !== t && t !== o.length - 1 && i.push([]) : (e.type !== r.text || null != o[t + 1] && o[t + 1].type !== r.tableSeparator || (e.text = e.text.trimEnd()), i[i.length - 1].push(e)) } )), i } function Ae(e, t, a) { a.inline = !0; const n = e[2] ? e[2].replace(G, "").split("|").map(ze) : [] , s = e[3] ? function(e, t, a) { return e.trim().split("\n").map((function(e) { return Le(e, t, a, !0) } )) }(e[3], t, a) : [] , o = Le(e[1], t, a, !!s.length); return a.inline = !1, s.length ? { align: n, cells: s, header: o, type: r.table } : { children: o, type: r.paragraph } } function Te(e, t) { return null == e.align[t] ? {} : { textAlign: e.align[t] } } function Oe(e) { return function(t, a) { return a.inline ? e.exec(t) : null } } function Be(e) { return function(t, a) { return a.inline || a.simple ? e.exec(t) : null } } function Me(e) { return function(t, a) { return a.inline || a.simple ? null : e.exec(t) } } function Re(e) { return function(t) { return e.exec(t) } } function Ie(e, t, a) { if (t.inline || t.simple) return null; if (a && !a.endsWith("\n")) return null; let n = ""; e.split("\n").every((e => !$e.some((t => t.test(e))) && (n += e + "\n", e.trim()))); const s = n.trimEnd(); return "" == s ? null : [n, s] } function Ue(e) { try { if (decodeURIComponent(e).replace(/[^A-Za-z0-9/:]/g, "").match(/^\s*(javascript|vbscript|data(?!:image)):/i)) return null } catch (e) { return null } return e } function De(e) { return e.replace(ie, "$1") } function je(e, t, a) { const n = a.inline || !1 , s = a.simple || !1; a.inline = !0, a.simple = !0; const r = e(t, a); return a.inline = n, a.simple = s, r } function Ne(e, t, a) { const n = a.inline || !1 , s = a.simple || !1; a.inline = !1, a.simple = !0; const r = e(t, a); return a.inline = n, a.simple = s, r } function He(e, t, a) { const n = a.inline || !1; a.inline = !1; const s = e(t, a); return a.inline = n, s } const Fe = (e, t, a) => ({ children: je(t, e[1], a) }); function Pe() { return {} } function _e() { return null } function We(...e) { return e.filter(Boolean).join(" ") } function Ge(e, t, a) { let n = e; const s = t.split("."); for (; s.length && (n = n[s[0]], void 0 !== n); ) s.shift(); return n || a } function Ze(e="", n={}) { function i(e, a, ...s) { const r = Ge(n.overrides,${e}.props, {}); return n.createElement(function(e, t) { const a = Ge(t, e); return a ? "function" == typeof a || "object" == typeof a && "render"in a ? a : Ge(t,${e}.component, e) : e }(e, n.overrides), t({}, a, r, { className: We(null == a ? void 0 : a.className, r.className) || void 0 }), ...s) } function d(e) { e = e.replace(E, ""); let t = !1; n.forceInline ? t = !0 : n.forceBlock || (t = !1 === _.test(e)); const a = ae(Z(t ? e :${e.trimEnd().replace(ne, «»)}\n\n, { inline: t })); for (; "string" == typeof a[a.length - 1] && !a[a.length - 1].trim(); ) a.pop(); if (null === n.wrapper) return a; const s = n.wrapper || (t ? "span" : "div"); let r; if (a.length > 1 || n.forceWrapper) r = a; else { if (1 === a.length) return r = a[0], "string" == typeof r ? i("span", { key: "outer" }, r) : r; r = null } return external_React_.createElement(s, { key: "outer" }, r) } function V(e, t) { const a = t.match(c); return a ? a.reduce((function(t, a, s) { const r = a.indexOf("="); if (-1 !== r) { const o = function(e) { return -1 !== e.indexOf("-") && null === e.match(O) && (e = e.replace(D, (function(e, t) { return t.toUpperCase() } ))), e }(a.slice(0, r)).trim() , i = function(e) { const t = e[0]; return ('"' === t || "'" === t) && e.length >= 2 && e[e.length - 1] === t ? e.slice(1, -1) : e }(a.slice(r + 1).trim()) , c = l[o] || o , u = t[c] = function(e, t, a, n) { return "style" === t ? a.split(/;\s?/).reduce((function(e, t) { const a = t.slice(0, t.indexOf(":")); return e[a.trim().replace(/(-[a-z])/g, (e => e[1].toUpperCase()))] = t.slice(a.length + 1).trim(), e } ), {}) : "href" === t || "src" === t ? n(a, e, t) : (a.match(M) && (a = a.slice(1, a.length - 1)), "true" === a || "false" !== a && a) }(e, o, i, n.sanitizer); "string" == typeof u && (L.test(u) || B.test(u)) && (t[c] = external_React_.cloneElement(d(u.trim()), { key: s })) } else "style" !== a && (t[l[a] || a] = !0); return t } ), {}) : null } n.overrides = n.overrides || {}, n.sanitizer = n.sanitizer || Ue, n.slugify = n.slugify || Ce, n.namedCodesToUnicode = n.namedCodesToUnicode ? t({}, a, n.namedCodesToUnicode) : a, n.createElement = n.createElement || external_React_.createElement; const q = [] , G = {} , Q = { [r.blockQuote]: { match: Me(u), order: 1, parse: (e, t, a) => ({ children: t(e[0].replace(p, ""), a) }), render: (e, t, a) => i("blockquote", { key: a.key }, t(e.children, a)) }, [r.breakLine]: { match: Re(f), order: 1, parse: Pe, render: (e, t, a) => i("br", { key: a.key }) }, [r.breakThematic]: { match: Me(h), order: 1, parse: Pe, render: (e, t, a) => i("hr", { key: a.key }) }, [r.codeBlock]: { match: Me(g), order: 0, parse: e => ({ lang: void 0, text: e[0].replace(/^ {4}/gm, "").replace(/\n+$/, "") }), render: (e, a, n) => i("pre", { key: n.key }, i("code", t({}, e.attrs, { className: e.lang ?lang-${e.lang}: "" }), e.text)) }, [r.codeFenced]: { match: Me(m), order: 0, parse: e => ({ attrs: V("code", e[3] || ""), lang: e[2] || void 0, text: e[4], type: r.codeBlock }) }, [r.codeInline]: { match: Be(y), order: 3, parse: e => ({ text: e[2] }), render: (e, t, a) => i("code", { key: a.key }, e.text) }, [r.footnote]: { match: Me(b), order: 0, parse: e => (q.push({ footnote: e[2], identifier: e[1] }), {}), render: _e }, [r.footnoteReference]: { match: Oe(v), order: 1, parse: e => ({ target:#${n.slugify(e[1], Ce)}, text: e[1] }), render: (e, t, a) => i("a", { key: a.key, href: n.sanitizer(e.target, "a", "href") }, i("sup", { key: a.key }, e.text)) }, [r.gfmTask]: { match: Oe($), order: 1, parse: e => ({ completed: "x" === e[1].toLowerCase() }), render: (e, t, a) => i("input", { checked: e.completed, key: a.key, readOnly: !0, type: "checkbox" }) }, [r.heading]: { match: Me(n.enforceAtxHeadings ? C : w), order: 1, parse: (e, t, a) => ({ children: je(t, e[2], a), id: n.slugify(e[2], Ce), level: e[1].length }), render: (e, t, a) => i(h${e.level}, { id: e.id, key: a.key }, t(e.children, a)) }, [r.headingSetext]: { match: Me(z), order: 0, parse: (e, t, a) => ({ children: je(t, e[1], a), level: "=" === e[2] ? 1 : 2, type: r.heading }) }, [r.htmlBlock]: { match: Re(L), order: 1, parse(e, t, a) { const [,n] = e[3].match(re) , s = new RegExp(^${n},"gm") , r = e[3].replace(s, "") , i = (l = r, we.some((e => e.test(l))) ? He : je); var l; const c = e[1].toLowerCase() , u = -1 !== o.indexOf(c) , d = (u ? c : e[1]).trim() , m = { attrs: V(d, e[2]), noInnerParse: u, tag: d }; return a.inAnchor = a.inAnchor || "a" === c, u ? m.text = e[3] : m.children = i(t, r, a), a.inAnchor = !1, m }, render: (e, a, n) => i(e.tag, t({ key: n.key }, e.attrs), e.text || a(e.children, n)) }, [r.htmlSelfClosing]: { match: Re(B), order: 1, parse(e) { const t = e[1].trim(); return { attrs: V(t, e[2] || ""), tag: t } }, render: (e, a, n) => i(e.tag, t({}, e.attrs, { key: n.key })) }, [r.htmlComment]: { match: Re(T), order: 1, parse: () => ({}), render: _e }, [r.image]: { match: Be(Ee), order: 1, parse: e => ({ alt: e[1], target: De(e[2]), title: e[3] }), render: (e, t, a) => i("img", { key: a.key, alt: e.alt || void 0, title: e.title || void 0, src: n.sanitizer(e.target, "img", "src") }) }, [r.link]: { match: Oe(Se), order: 3, parse: (e, t, a) => ({ children: Ne(t, e[1], a), target: De(e[2]), title: e[3] }), render: (e, t, a) => i("a", { key: a.key, href: n.sanitizer(e.target, "a", "href"), title: e.title }, t(e.children, a)) }, [r.linkAngleBraceStyleDetector]: { match: Oe(U), order: 0, parse: e => ({ children: [{ text: e[1], type: r.text }], target: e[1], type: r.link }) }, [r.linkBareUrlDetector]: { match: (e, t) => t.inAnchor ? null : Oe(R)(e, t), order: 0, parse: e => ({ children: [{ text: e[1], type: r.text }], target: e[1], title: void 0, type: r.link }) }, [r.linkMailtoDetector]: { match: Oe(I), order: 0, parse(e) { let t = e[1] , a = e[1]; return s.test(a) || (a = "mailto:" + a), { children: [{ text: t.replace("mailto:", ""), type: r.text }], target: a, type: r.link } } }, [r.orderedList]: ve(i, 1), [r.unorderedList]: ve(i, 2), [r.newlineCoalescer]: { match: Me(k), order: 3, parse: Pe, render: () => "\n" }, [r.paragraph]: { match: Ie, order: 3, parse: Fe, render: (e, t, a) => i("p", { key: a.key }, t(e.children, a)) }, [r.ref]: { match: Oe(N), order: 0, parse: e => (G[e[1]] = { target: e[2], title: e[4] }, {}), render: _e }, [r.refImage]: { match: Be(H), order: 0, parse: e => ({ alt: e[1] || void 0, ref: e[2] }), render: (e, t, a) => G[e.ref] ? i("img", { key: a.key, alt: e.alt, src: n.sanitizer(G[e.ref].target, "img", "src"), title: G[e.ref].title }) : null }, [r.refLink]: { match: Oe(F), order: 0, parse: (e, t, a) => ({ children: t(e[1], a), fallbackChildren: t(e[0].replace(P, "\\$1"), a), ref: e[2] }), render: (e, t, a) => G[e.ref] ? i("a", { key: a.key, href: n.sanitizer(G[e.ref].target, "a", "href"), title: G[e.ref].title }, t(e.children, a)) : i("span", { key: a.key }, t(e.fallbackChildren, a)) }, [r.table]: { match: Me(j), order: 1, parse: Ae, render(e, t, a) { const n = e; return i("table", { key: a.key }, i("thead", null, i("tr", null, n.header.map((function(e, s) { return i("th", { key: s, style: Te(n, s) }, t(e, a)) } )))), i("tbody", null, n.cells.map((function(e, s) { return i("tr", { key: s }, e.map((function(e, s) { return i("td", { key: s, style: Te(n, s) }, t(e, a)) } ))) } )))) } }, [r.text]: { match: Re(te), order: 4, parse: e => ({ text: e[0].replace(A, ( (e, t) => n.namedCodesToUnicode[t] ? n.namedCodesToUnicode[t] : e)) }), render: e => e.text }, [r.textBolded]: { match: Be(X), order: 2, parse: (e, t, a) => ({ children: t(e[2], a) }), render: (e, t, a) => i("strong", { key: a.key }, t(e.children, a)) }, [r.textEmphasized]: { match: Be(J), order: 3, parse: (e, t, a) => ({ children: t(e[2], a) }), render: (e, t, a) => i("em", { key: a.key }, t(e.children, a)) }, [r.textEscaped]: { match: Be(ee), order: 1, parse: e => ({ text: e[1], type: r.text }) }, [r.textMarked]: { match: Be(K), order: 3, parse: Fe, render: (e, t, a) => i("mark", { key: a.key }, t(e.children, a)) }, [r.textStrikethroughed]: { match: Be(Y), order: 3, parse: Fe, render: (e, t, a) => i("del", { key: a.key }, t(e.children, a)) } }; !0 === n.disableParsingRawHTML && (delete Q[r.htmlBlock], delete Q[r.htmlSelfClosing]); const Z = function(e) { let t = Object.keys(e); function a(n, s) { let r = [] , o = ""; for (; n; ) { let i = 0; for (; i < t.length; ) { const l = t[i] , c = e[l] , u = c.match(n, s, o); if (u) { const e = u[0]; n = n.substring(e.length); const t = c.parse(u, a, s); null == t.type && (t.type = l), r.push(t), o = e; break } i++ } } return r } return t.sort((function(t, a) { let n = e[t].order , s = e[a].order; return n !== s ? n - s : t < a ? -1 : 1 } )), function(e, t) { return a(function(e) { return e.replace(x, "\n").replace(S, "").replace(W, " ") }(e), t) } }(Q) , ae = (se = function(e, t) { return function(a, n, s) { const r = e[a.type].render; return t ? t(( () => r(a, n, s)), a, n, s) : r(a, n, s) } }(Q, n.renderRule), function e(t, a={}) { if (Array.isArray(t)) { const n = a.key , s = []; let r = !1; for (let n = 0; n < t.length; n++) { a.key = n; const o = e(t[n], a) , i = "string" == typeof o; i && r ? s[s.length - 1] += o : null !== o && s.push(o), r = i } return a.key = n, s } return se(t, e, a) } ); var se; const oe = d(e); return q.length ? i("div", null, oe, i("footer", { key: "footer" }, q.map((function(e) { return i("div", { id: n.slugify(e.identifier, Ce), key: e.identifier }, e.identifier, ae(Z(e.footnote, { inline: !0 }))) } )))) : oe } const index_modern = t => { let {children: a="", options: s} = t , r = function(e, t) { if (null == e) return {}; var a, n, s = {}, r = Object.keys(e); for (n = 0; n < r.length; n++) t.indexOf(a = r[n]) >= 0 || (s[a] = e[a]); return s }(t, n); return e.cloneElement(Ze(a, s), r) } , {useMemo: ChatbotContent_useMemo} = wp.element , LinkContainer = ({href: e, children: t}) => { if (!e) return React.createElement("span", null, t); const a = "_blank"; if ("Uploaded File" === String(t)) { const t = e.split("/").pop(); return React.createElement("a", { href: e, target: a, rel: "noopener noreferrer", className: "mwai-filename" }, React.createElement("span", null, "✓ ", t)) } return React.createElement("a", { href: e, target: a, rel: "noopener noreferrer" }, t) } , ChatbotContent = ({message: e}) => { let t = e.content ?? ""; (t.match(/```/g) || []).length % 2 != 0 && (t += "\n```"); const a = ChatbotContent_useMemo(( () => ({ overrides: { BlinkingCursor: { component: js_helpers.rn }, a: { component: LinkContainer }, img: { props: { onError: e => { null !== e.target.src.match(/\.(jpeg|jpg|gif|png)$/) && (e.target.src = "https://placehold.co/600x200?text=Expired+Image") } , className: "mwai-image" } } } })), []) , n = ChatbotContent_useMemo(( () => { let e = ""; try { e = Ze(t, a) } catch (a) { console.error("Crash in markdown-to-jsx! Reverting to plain text.", { e: a, content: t }), e = t } return e } ), [t, a]); return e.isStreaming ? React.createElement(React.Fragment, null, n, React.createElement(js_helpers.rn, null)) : n } , chatbot_ChatbotContent = ChatbotContent , {useState: ChatbotReply_useState, useMemo: ChatbotReply_useMemo, useEffect: ChatbotReply_useEffect, useRef: ChatbotReply_useRef} = wp.element , RawMessage = ({message: e, onRendered: t=( () => {} )}) => { const {state: a} = (0, ChatbotContext.o)() , {copyButton: n, debugMode: s} = a , [r] = ChatbotReply_useState(e.isQuerying || e.isStreaming) , o = e.isQuerying , i = e.isStreaming; if (ChatbotReply_useEffect(( () => { r && (!r || o || i) || t() } ), [r, o, i]), o) return React.createElement(BouncingDots, null); const l = e.isError || "error" === e.role ? chatbot_ErrorReplyActions : components_ReplyActions; return React.createElement(React.Fragment, null, React.createElement(chatbot_ChatbotName, { role: e.role }), React.createElement(l, { content: e.content, enabled: n, className: "mwai-text", message: e }, React.createElement(chatbot_ChatbotContent, { message: e }))) } , ImagesMessage = ({message: e, onRendered: t=( () => {} )}) => { const [a,n] = ChatbotReply_useState(null == e ? void 0 : e.images); return ChatbotReply_useEffect(( () => { t() } )), e.isQuerying ? React.createElement(BouncingDots, null) : React.createElement(React.Fragment, null, React.createElement(chatbot_ChatbotName, { role: e.role }), React.createElement("span", { className: "mwai-text" }, React.createElement("div", { className: "mwai-gallery" }, null == a ? void 0 : a.map(( (e, t) => React.createElement("a", { key: t, href: e, target: "_blank", rel: "noopener noreferrer" }, React.createElement("img", { key: t, src: e, onError: () => (e => { n((t => t.map(( (t, a) => a === e ? "https://placehold.co/600x200?text=Expired+Image" : t)))) } )(t) }))))))) } , ChatbotReply = ({message: e, conversationRef: t}) => { var a; const {state: n, actions: s} = (0, ChatbotContext.o)() , {typewriter: r} = n , {setMessages: o, retryLastQuery: i} = s , l = (0, helpers.gR)() , c = ChatbotReply_useRef() , u = l("mwai-reply", { "mwai-ai": "assistant" === e.role, "mwai-user": "user" === e.role, "mwai-system": "system" === e.role, "mwai-error": "error" === e.role || e.isError }) , d = (null == e || null === (a = e.images) || void 0 === a ? void 0 : a.length) > 0 , m = "error" === e.role || e.isError , p = () => { !c.current || e.isQuerying || c.current.classList.contains("mwai-rendered") || "undefined" == typeof hljs || (c.current.classList.add("mwai-rendered"), c.current.querySelectorAll("pre code").forEach((e => { hljs.highlightElement(e) } ))) } ; return ChatbotReply_useMemo(( () => { if ("user" === e.role) return React.createElement("div", { ref: c, className: u }, React.createElement(RawMessage, { message: e })); if ("assistant" === e.role) return d ? React.createElement("div", { ref: c, className: u }, React.createElement(ImagesMessage, { message: e, conversationRef: t, onRendered: p })) : React.createElement("div", { ref: c, className: u }, React.createElement(RawMessage, { message: e, conversationRef: t, onRendered: p })); if ("system" === e.role && !m) return React.createElement("div", { ref: c, className: u }, React.createElement(RawMessage, { message: e, conversationRef: t, onRendered: p })); if (m) { const a = { ...e, role: "assistant" }; return React.createElement("div", { ref: c, className: u }, React.createElement(RawMessage, { message: a, conversationRef: t, onRendered: p })) } return React.createElement("div", null, React.createElement("i", null, "Unhandled role.")) } ), [e, t, d, r]) } , chatbot_ChatbotReply = ChatbotReply , {useMemo: ChatbotHeader_useMemo} = wp.element; function formatAvatar(e, t, a, n) { if ((0, js_helpers.Ve)(n || a)) return s = n || a, React.createElement("div", { className: "mwai-avatar mwai-emoji", style: { fontSize: "48px", lineHeight: "48px" } }, s); var s; const r = (o = n, ((0, helpers.mv)(o) ? o : o ?${t}/images/${o}: null) || a ||${t}/images/chat-openai.svg); var o, i; return r ? (i = r, "AI Engine", React.createElement("div", { className: "mwai-avatar" }, React.createElement("img", { alt: "AI Engine", src: i }))) : React.createElement("div", { className: "mwai-name-text" }, e) } const ChatbotHeader = () => { const {state: e, actions: t} = (0, ChatbotContext.o)() , {theme: a, isWindow: n, fullscreen: s, aiName: r, pluginUrl: o, open: i, iconUrl: l, aiAvatarUrl: c, windowed: u, headerSubtitle: d} = e , {setOpen: m, setWindowed: p} = t , h = ChatbotHeader_useMemo(( () => { if (!n) return null; const e = "timeless" === (null == a ? void 0 : a.themeId) , t = e ? formatAvatar(r, o, l, c) : null , h = null == d ? "Discuss with" : d; return React.createElement(React.Fragment, null, e && React.createElement(React.Fragment, null, t, React.createElement("div", { className: "mwai-name" }, h && React.createElement("small", { className: "mwai-subtitle" }, h), React.createElement("div", null, r)), React.createElement("div", { style: { flex: "auto" } })), React.createElement("div", { className: "mwai-buttons" }, s && React.createElement("div", { className: "mwai-resize-button", onClick: () => p(!u) }), React.createElement("div", { className: "mwai-close-button", onClick: () => m(!i) }))) } ), [n, null == a ? void 0 : a.themeId, r, o, l, c, s, p, u, m, i, d]); return React.createElement("div", { className: "mwai-header" }, h) } , chatbot_ChatbotHeader = ChatbotHeader , {useMemo: ChatbotTrigger_useMemo, useEffect: ChatbotTrigger_useEffect} = wp.element , ChatbotTrigger = () => { const {state: e, actions: t} = (0, ChatbotContext.o)() , {isWindow: a, iconText: n, showIconMessage: s, iconAlt: r, iconUrl: o, open: i} = e , {setShowIconMessage: l, setOpen: c} = t; ChatbotTrigger_useEffect(( () => { i && s && l(!1) } ), [i, l, s]); const u = ChatbotTrigger_useMemo(( () => a ? React.createElement("div", { className: "mwai-trigger mwai-open-button" }, React.createElement(helpers.bE, { className: "mwai-icon-text-container", if: n && s }, React.createElement("div", { className: "mwai-icon-text-close", onClick: () => l(!1) }, "✕"), React.createElement("div", { className: "mwai-icon-text", onClick: () => c(!0) }, n)), React.createElement("div", { className: "mwai-icon-container", onClick: () => c(!0) }, (0, js_helpers.Ve)(o) ? React.createElement("div", { className: "mwai-icon mwai-emoji", style: { fontSize: "48px", lineHeight: "64px", width: "64px", height: "64px", display: "flex", justifyContent: "center", alignItems: "center" } }, o) : React.createElement("img", { className: "mwai-icon", width: "64", height: "64", alt: r, src: o }))) : null), [a, n, s, r, o, l, c]); return React.createElement(React.Fragment, null, u) } , chatbot_ChatbotTrigger = ChatbotTrigger; function extends_extends() { return extends_extends = Object.assign ? Object.assign.bind() : function(e) { for (var t = 1; t < arguments.length; t++) { var a = arguments[t]; for (var n in a) Object.prototype.hasOwnProperty.call(a, n) && (e[n] = a[n]) } return e } , extends_extends.apply(this, arguments) } function _objectWithoutPropertiesLoose(e, t) { if (null == e) return {}; var a, n, s = {}, r = Object.keys(e); for (n = 0; n < r.length; n++) a = r[n], t.indexOf(a) >= 0 || (s[a] = e[a]); return s } var index = external_React_.useLayoutEffect; const use_isomorphic_layout_effect_browser_esm = index; var useLatest = function(e) { var t = external_React_.useRef(e); return use_isomorphic_layout_effect_browser_esm((function() { t.current = e } )), t } , updateRef = function(e, t) { "function" != typeof e ? e.current = t : e(t) } , useComposedRef = function(e, t) { var a = (0, external_React_.useRef)(); return (0, external_React_.useCallback)((function(n) { e.current = n, a.current && updateRef(a.current, null), a.current = t, t && updateRef(t, n) } ), [t]) }; const use_composed_ref_esm = useComposedRef; var HIDDEN_TEXTAREA_STYLE = { "min-height": "0", "max-height": "none", height: "0", visibility: "hidden", overflow: "hidden", position: "absolute", "z-index": "-1000", top: "0", right: "0" } , forceHiddenStyles = function(e) { Object.keys(HIDDEN_TEXTAREA_STYLE).forEach((function(t) { e.style.setProperty(t, HIDDEN_TEXTAREA_STYLE[t], "important") } )) } , forceHiddenStyles$1 = forceHiddenStyles , hiddenTextarea = null , getHeight = function(e, t) { var a = e.scrollHeight; return "border-box" === t.sizingStyle.boxSizing ? a + t.borderSize : a - t.paddingSize }; function calculateNodeHeight(e, t, a, n) { void 0 === a && (a = 1), void 0 === n && (n = 1 / 0), hiddenTextarea || ((hiddenTextarea = document.createElement("textarea")).setAttribute("tabindex", "-1"), hiddenTextarea.setAttribute("aria-hidden", "true"), forceHiddenStyles$1(hiddenTextarea)), null === hiddenTextarea.parentNode && document.body.appendChild(hiddenTextarea); var s = e.paddingSize , r = e.borderSize , o = e.sizingStyle , i = o.boxSizing; Object.keys(o).forEach((function(e) { var t = e; hiddenTextarea.style[t] = o[t] } )), forceHiddenStyles$1(hiddenTextarea), hiddenTextarea.value = t; var l = getHeight(hiddenTextarea, e); hiddenTextarea.value = t, l = getHeight(hiddenTextarea, e), hiddenTextarea.value = "x"; var c = hiddenTextarea.scrollHeight - s , u = c * a; "border-box" === i && (u = u + s + r), l = Math.max(u, l); var d = c * n; return "border-box" === i && (d = d + s + r),
[l = Math.min(d, l), c]
} var noop = function() {} , pick = function(e, t) { return e.reduce((function(e, a) { return e[a] = t[a], e } ), {}) } , SIZING_STYLE = [«borderBottomWidth», «borderLeftWidth», «borderRightWidth», «borderTopWidth», «boxSizing», «fontFamily», «fontSize», «fontStyle», «fontWeight», «letterSpacing», «lineHeight», «paddingBottom», «paddingLeft», «paddingRight», «paddingTop», «tabSize», «textIndent», «textRendering», «textTransform», «width», «wordBreak»] , isIE = !!document.documentElement.currentStyle , getSizingData = function(e) { var t = window.getComputedStyle(e); if (null === t) return null; var a = pick(SIZING_STYLE, t) , n = a.boxSizing; return «» === n ? null : (isIE && «border-box» === n && (a.width = parseFloat(a.width) + parseFloat(a.borderRightWidth) + parseFloat(a.borderLeftWidth) + parseFloat(a.paddingRight) + parseFloat(a.paddingLeft) + «px»), { sizingStyle: a, paddingSize: parseFloat(a.paddingBottom) + parseFloat(a.paddingTop), borderSize: parseFloat(a.borderBottomWidth) + parseFloat(a.borderTopWidth) }) } , getSizingData$1 = getSizingData; function useListener(e, t, a) { var n = useLatest(a); external_React_.useLayoutEffect((function() { var a = function(e) { return n.current(e) }; if (e) return e.addEventListener(t, a), function() { return e.removeEventListener(t, a) } } ), []) } var useWindowResizeListener = function(e) { useListener(window, «resize», e) } , useFontsLoadedListener = function(e) { useListener(document.fonts, «loadingdone», e) } , _excluded = [«cacheMeasurements», «maxRows», «minRows», «onChange», «onHeightChange»] , TextareaAutosize = function(e, t) { var a = e.cacheMeasurements , n = e.maxRows , s = e.minRows , r = e.onChange , o = void 0 === r ? noop : r , i = e.onHeightChange , l = void 0 === i ? noop : i , c = _objectWithoutPropertiesLoose(e, _excluded) , u = void 0 !== c.value , d = external_React_.useRef(null) , m = use_composed_ref_esm(d, t) , p = external_React_.useRef(0) , h = external_React_.useRef() , g = function() { var e = d.current , t = a && h.current ? h.current : getSizingData$1(e); if (t) { h.current = t; var r = calculateNodeHeight(t, e.value || e.placeholder || «x», s, n) , o = r[0] , i = r[1]; p.current !== o && (p.current = o, e.style.setProperty(«height», o + «px», «important»), l(o, { rowHeight: i })) } }; return external_React_.useLayoutEffect(g), useWindowResizeListener(g), useFontsLoadedListener(g), external_React_.createElement(«textarea», extends_extends({}, c, { onChange: function(e) { u || g(), o(e) }, ref: m })) } , react_textarea_autosize_browser_esm_index = external_React_.forwardRef(TextareaAutosize); const {useState: ChatUploadIcon_useState, useMemo: ChatUploadIcon_useMemo, useRef: ChatUploadIcon_useRef} = wp.element , ChatUploadIcon = () => { const e = (0, helpers.gR)() , {state: t, actions: a} = (0, ChatbotContext.o)() , {uploadedFile: n, busy: s, imageUpload: r, fileUpload: o, fileSearch: i, draggingType: l} = t , {onUploadFile: c} = a , [u,d] = ChatUploadIcon_useState(!1) , m = ChatUploadIcon_useRef() , p = null == n ? void 0 : n.uploadedId , h = r || i || o , g = n , _ = ChatUploadIcon_useMemo(( () => null != g && g.localFile ? g.localFile.type.startsWith(«image/») ? «image» : «document» : l), [g, l]) , f = ChatUploadIcon_useMemo(( () => { let e = «idle»; return null != g && g.uploadProgress ? e = «up» : l ? e = «add» : u && p ? e = «del» : p ? e = «ok» : u && !p && (e = «add»), mwai-file-upload-icon mwai-${_ ? .toLowerCase() : «idle»}-${e} } ), [_, g, l, u, p]) , y = ChatUploadIcon_useMemo(( () => null != g && g.uploadProgress ? g.uploadProgress > 99 ? 99 : Math.round(g.uploadProgress) : ""), [g]); return h ? React.createElement("div", { disabled: s, onClick: () => { null != n && n.localFile ? c(null) : s || m.current.click() } , onMouseEnter: () => d(!0), onMouseLeave: () => d(!1), className: e("mwai-file-upload", { "mwai-enabled": null == n ? void 0 : n.uploadedId, "mwai-busy": (null == n ? void 0 : n.localFile) && !(null != n && n.uploadedId) }), style: { cursor: s ? "default" : "pointer" } }, React.createElement("div", { className: f }, React.createElement("span", { className: "mwai-file-upload-progress" }, y)), React.createElement("input", { type: "file", ref: m, onChange: e => { const t = e.target.files[0]; t && c(t) } , style: { display: "none" } })) : null } , chatbot_ChatUploadIcon = ChatUploadIcon , {useRef: ChatbotInput_useRef, useState: ChatbotInput_useState, useEffect: ChatbotInput_useEffect, useImperativeHandle} = wp.element , ChatbotInput = () => { const e = (0, helpers.gR)() , {state: t, actions: a} = (0, ChatbotContext.o)() , {inputText: n, textInputMaxLength: s, textInputPlaceholder: r, error: o, speechRecognitionAvailable: i, isMobile: l, conversationRef: c, open: u, uploadIconPosition: d, locked: m, isListening: p, busy: h, speechRecognition: g, chatbotInputRef: _} = t , {onSubmitAction: f, setIsListening: y, resetError: b, setInputText: v} = a , [E,R] = ChatbotInput_useState(!1) , w = ChatbotInput_useRef(); useImperativeHandle(_, ( () => ({ focusInput: () => { var e; null === (e = w.current) || void 0 === e || e.focus() } , currentElement: () => w.current }))), ChatbotInput_useEffect(( () => { !l && u && w.current.focus(), c.current && (c.current.scrollTop = c.current.scrollHeight) } ), [u, l, c]); const C = e("mwai-input-text", {}); return React.createElement("div", { ref: _, className: C }, "mwai-input" === d && React.createElement(chatbot_ChatUploadIcon, null), React.createElement(react_textarea_autosize_browser_esm_index, { ref: w, disabled: h || m, placeholder: r, value: n, maxLength: s, onCompositionStart: () => R(!0), onCompositionEnd: () => R(!1), onKeyDown: e => { E || "Enter" !== e.code || e.shiftKey || (e.preventDefault(), f()) } , onChange: e => { return t = e.target.value, p && y(!1), o && b(), void v(t); var t } }), g && React.createElement(helpers.tm, { active: p, disabled: !i || h, className: "mwai-microphone", onClick: () => y(!p) })) } , chatbot_ChatbotInput = ChatbotInput; var createLucideIcon = __webpack_require__(407); const Send = (0, createLucideIcon.A)("Send", [["path", { d: "M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z", key: "1ffxy3" }], ["path", { d: "m21.854 2.147-10.94 10.939", key: "12cjpa" }]]) , Eraser = (0, createLucideIcon.A)("Eraser", [["path", { d: "m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21", key: "182aya" }], ["path", { d: "M22 21H7", key: "t4ddhn" }], ["path", { d: "m5 11 9 9", key: "1mo9qw" }]]) , {useMemo: ChatbotSubmit_useMemo, useCallback: ChatbotSubmit_useCallback} = wp.element , ChatbotSubmit = () => { const {state: e, actions: t} = (0, ChatbotContext.o)() , {onClear: a, onSubmitAction: n, setIsListening: s} = t , {textClear: r, textSend: o, uploadedFile: i, inputText: l, messages: c, isListening: u, timeElapsed: d, busy: m, submitButtonConf: p, locked: h} = e , g = !(null == i || !i.uploadProgress) , _ = !(null != i && i.uploadedId) && l.length < 1 && (null == c ? void 0 : c.length) > 1 , f = ChatbotSubmit_useMemo(( () => m ? d ? React.createElement("div", { className: "mwai-timer" }, d) : null : null != p && p.imageSend && null != p && p.imageClear ? React.createElement("img", { src: _ ? p.imageClear : p.imageSend, alt: _ ? r : o }) : _ || o ? _ && !r ? React.createElement(Eraser, { size: "20" }) : React.createElement("span", null, _ ? r : o) : React.createElement(Send, { size: "20", style: { marginLeft: 10 } })), [m, d, _, r, o, p]) , y = ChatbotSubmit_useMemo(( () => "mwai-input-submit " + (m ? "mwai-busy" : "")), [m]) , b = ChatbotSubmit_useCallback(( () => { u && s(!1), _ ? a() : n() } ), [_, u, a, n, s]) , v = ChatbotSubmit_useCallback(( () => { m || b() } ), [m, b]); return React.createElement("button", { className: y, disabled: m || g || h, onClick: v }, f) } , chatbot_ChatbotSubmit = ChatbotSubmit , Play = (0, createLucideIcon.A)("Play", [["polygon", { points: "6 3 20 12 6 21 6 3", key: "1oa8hb" }]]) , Loader = (0, createLucideIcon.A)("Loader", [["path", { d: "M12 2v4", key: "3427ic" }], ["path", { d: "m16.2 7.8 2.9-2.9", key: "r700ao" }], ["path", { d: "M18 12h4", key: "wj9ykh" }], ["path", { d: "m16.2 16.2 2.9 2.9", key: "1bxg5t" }], ["path", { d: "M12 18v4", key: "jadmvz" }], ["path", { d: "m4.9 19.1 2.9-2.9", key: "bwix9q" }], ["path", { d: "M2 12h4", key: "j09sii" }], ["path", { d: "m4.9 4.9 2.9 2.9", key: "giyufr" }]]) , Square = (0, createLucideIcon.A)("Square", [["rect", { width: "18", height: "18", x: "3", y: "3", rx: "2", key: "afitv7" }]]) , Pause = (0, createLucideIcon.A)("Pause", [["rect", { x: "14", y: "4", width: "4", height: "16", rx: "1", key: "zuxfzm" }], ["rect", { x: "6", y: "4", width: "4", height: "16", rx: "1", key: "1okwgv" }]]) , Users = (0, createLucideIcon.A)("Users", [["path", { d: "M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2", key: "1yyitq" }], ["circle", { cx: "9", cy: "7", r: "4", key: "nufk8" }], ["path", { d: "M22 21v-2a4 4 0 0 0-3-3.87", key: "kshegd" }], ["path", { d: "M16 3.13a4 4 0 0 1 0 7.75", key: "1da9ce" }]]) , Captions = (0, createLucideIcon.A)("Captions", [["rect", { width: "18", height: "14", x: "3", y: "5", rx: "2", ry: "2", key: "12ruh7" }], ["path", { d: "M7 15h4M15 15h2M7 11h2M13 11h4", key: "1ueiar" }]]) , Bug = (0, createLucideIcon.A)("Bug", [["path", { d: "m8 2 1.88 1.88", key: "fmnt4t" }], ["path", { d: "M14.12 3.88 16 2", key: "qol33r" }], ["path", { d: "M9 7.13v-1a3.003 3.003 0 1 1 6 0v1", key: "d7y7pr" }], ["path", { d: "M12 20c-3.3 0-6-2.7-6-6v-3a4 4 0 0 1 4-4h4a4 4 0 0 1 4 4v3c0 3.3-2.7 6-6 6", key: "xs1cw7" }], ["path", { d: "M12 20v-9", key: "1qisl0" }], ["path", { d: "M6.53 9C4.6 8.8 3 7.1 3 5", key: "32zzws" }], ["path", { d: "M6 13H2", key: "82j7cp" }], ["path", { d: "M3 21c0-2.1 1.7-3.9 3.8-4", key: "4p0ekp" }], ["path", { d: "M20.97 5c0 2.1-1.6 3.8-3.5 4", key: "18gb23" }], ["path", { d: "M22 13h-4", key: "1jl80f" }], ["path", { d: "M17.2 17c2.1.1 3.8 1.9 3.8 4", key: "k3fwyw" }]]) , {useState: AudioVisualizer_useState, useRef: AudioVisualizer_useRef, useEffect: AudioVisualizer_useEffect} = wp.element; function measureVolume(e, t) { e.getByteTimeDomainData(t); let a = 0; for (let e = 0; e < t.length; e++) { const n = t[e] - 128; a += n * n } return Math.sqrt(a / t.length) } function AudioVisualizerTwoStreams({assistantStream: e=null, userStream: t=null, assistantColor: a=null, userColor: n=null, userUI: s={ emoji: null, text: null, image: null, use: "text" }, assistantUI: r={ emoji: null, text: null, image: null, use: "text" }, attackSpeed: o=.3, releaseSpeed: i=.05, circleSize: l=50, pulseMaxSize: c=30}) { const [u,d] = AudioVisualizer_useState(0) , [m,p] = AudioVisualizer_useState(0) , h = AudioVisualizer_useRef(0) , g = AudioVisualizer_useRef(0) , _ = AudioVisualizer_useRef(null) , f = AudioVisualizer_useRef(null) , y = AudioVisualizer_useRef(null) , b = AudioVisualizer_useRef(null) , v = AudioVisualizer_useRef(null); AudioVisualizer_useEffect(( () => { if (!e && !t) return; _.current || (_.current = new AudioContext); const a = _.current; let n, s, r; e && (n = a.createMediaStreamSource(e), f.current = a.createAnalyser(), f.current.fftSize = 1024, y.current = new Uint8Array(f.current.frequencyBinCount), n.connect(f.current)), t && (s = a.createMediaStreamSource(t), b.current = a.createAnalyser(), b.current.fftSize = 1024, v.current = new Uint8Array(b.current.frequencyBinCount), s.connect(b.current)); const l = () => { let e = 0; f.current && y.current && (e = measureVolume(f.current, y.current)); let t = 0; b.current && v.current && (t = measureVolume(b.current, v.current)), e > h.current ? h.current = h.current * (1 - o) + e * o : h.current = h.current * (1 - i) + e * i, t > g.current ? g.current = g.current * (1 - o) + t * o : g.current = g.current * (1 - i) + t * i, d(h.current), p(g.current), r = requestAnimationFrame(l) } ; return l(), () => { n && n.disconnect(), f.current && f.current.disconnect(), s && s.disconnect(), b.current && b.current.disconnect(), r && cancelAnimationFrame(r) } } ), [e, t, o, i]); const E = l + Math.min(u / 20, 1) * c , R = l + Math.min(m / 20, 1) * c , w = l + c , C = { width: R, height: R, borderRadius: "50%", position: "absolute", top: "50%", left: "50%", transform: "translate(-50%, -50%)", opacity: .5 }; n && (C.backgroundColor = n); const k = { width: E, height: E, borderRadius: "50%", position: "absolute", top: "50%", left: "50%", transform: "translate(-50%, -50%)", opacity: .5 }; a && (k.backgroundColor = a); const x = { width: l, height: l, borderRadius: "50%", position: "absolute", top: "50%", left: "50%", transform: "translate(-50%, -50%)", display: "flex", justifyContent: "center", alignItems: "center", overflow: "hidden", color: "#fff" }; n && (x.backgroundColor = n); const S = { width: l, height: l, borderRadius: "50%", position: "absolute", top: "50%", left: "50%", transform: "translate(-50%, -50%)", display: "flex", justifyContent: "center", alignItems: "center", overflow: "hidden", color: "#fff" }; a && (S.backgroundColor = a); let I = "mwai-visualizer"; m > u ? I += " mwai-user-talking" : u > m && (I += " mwai-assistant-talking"); const M = e => { if (!e) return null; const {emoji: t, text: a, image: n, use: s} = e; switch (s) { case "emoji": return t ? React.createElement("span", null, t) : a ? React.createElement("span", null, a.slice(0, 1)) : null; case "image": return n ? React.createElement("img", { src: n, alt: "", style: { width: "100%", height: "100%", borderRadius: "50%" } }) : t ? React.createElement("span", null, t) : a ? React.createElement("span", null, a.slice(0, 1)) : null; default: return a ? React.createElement("span", null, a.slice(0, 1)) : t ? React.createElement("span", null, t) : null } } ; return React.createElement("div", { className: I }, React.createElement("div", { className: "mwai-visualizer-user", style: { position: "relative", width: w, height: w, overflow: "visible" } }, React.createElement("div", { className: "mwai-animation", style: C }), React.createElement("div", { style: x }, M(s))), React.createElement("hr", { className: "mwai-visualizer-line" }), React.createElement("div", { className: "mwai-visualizer-assistant", style: { position: "relative", width: w, height: w, overflow: "visible" } }, React.createElement("div", { className: "mwai-animation", style: k }), React.createElement("div", { style: S }, M(r)))) } const STREAM_TYPES = { CONTENT: "content", THINKING: "thinking", CODE: "code", TOOL_CALL: "tool_call", TOOL_ARGS: "tool_args", TOOL_RESULT: "tool_result", MCP_DISCOVERY: "mcp_discovery", WEB_SEARCH: "web_search", FILE_SEARCH: "file_search", IMAGE_GEN: "image_gen", EMBEDDINGS: "embeddings", DEBUG: "debug", STATUS: "status", ERROR: "error", WARNING: "warning", TRANSCRIPT: "transcript", START: "start", END: "end", HEARTBEAT: "heartbeat" } , STREAM_VISIBILITY = { VISIBLE: "visible", HIDDEN: "hidden", COLLAPSED: "collapsed" } , getDefaultVisibility = e => { const t = [STREAM_TYPES.TOOL_ARGS, STREAM_TYPES.DEBUG, STREAM_TYPES.HEARTBEAT] , a = [STREAM_TYPES.THINKING, STREAM_TYPES.MCP_DISCOVERY, STREAM_TYPES.STATUS]; return t.includes(e) ? STREAM_VISIBILITY.HIDDEN : a.includes(e) ? STREAM_VISIBILITY.COLLAPSED : STREAM_VISIBILITY.VISIBLE } ; class RealtimeEventEmitter { constructor(e, t=!1) { this.onEvent = e, this.eventLogsEnabled = t, this.sessionStartTime = null } emit(e, t, a={}) { if (!this.eventLogsEnabled || !this.onEvent) return; const n = { type: "event", subtype: e, data: t, timestamp: (new Date).getTime(), ...a }; this.onEvent("", n) } sessionStarting() { this.sessionStartTime = (new Date).getTime(), this.emit(STREAM_TYPES.STATUS, "Starting realtime session...") } sessionConnected() { const e = this.sessionStartTime ? (new Date).getTime() - this.sessionStartTime : 0; this.emit(STREAM_TYPES.STATUS,Realtime session connected in ${e}ms.) } sessionEnding() { this.emit(STREAM_TYPES.STATUS, "Ending realtime session...") } sessionError(e) { this.emit(STREAM_TYPES.ERROR,Realtime session error: ${e}) } userStartedSpeaking() { this.emit(STREAM_TYPES.STATUS, "User speaking...", { visibility: "collapsed" }) } userStoppedSpeaking() { this.emit(STREAM_TYPES.STATUS, "User finished speaking.", { visibility: "collapsed" }) } assistantStartedSpeaking() { this.emit(STREAM_TYPES.STATUS, "Assistant speaking...", { visibility: "collapsed" }) } assistantStoppedSpeaking() { this.emit(STREAM_TYPES.STATUS, "Assistant finished speaking.", { visibility: "collapsed" }) } functionCalling(e, t) { this.emit(STREAM_TYPES.TOOL_CALL,Calling ${e}…, { metadata: { tool_name: e, arguments: t } }) } functionResult(e, t) { this.emit(STREAM_TYPES.TOOL_RESULT,Got result from ${e}., { metadata: { tool_name: e, result: t } }) } functionError(e, t) { this.emit(STREAM_TYPES.ERROR,Function ${e} failed: ${t}, { metadata: { tool_name: e } }) } userTranscribed(e) { this.emit(STREAM_TYPES.STATUS,User: «${e}», { visibility: "collapsed" }) } assistantTranscribed(e) { this.emit(STREAM_TYPES.STATUS,Assistant: «${e}», { visibility: "collapsed" }) } usageUpdated(e) { const {text_input_tokens: t, audio_input_tokens: a, text_output_tokens: n, audio_output_tokens: s} = e , r = t + a + n + s; this.emit(STREAM_TYPES.STATUS,Tokens used: ${r} (Text: ${t}/${n}, Audio: ${a}/${s}), { visibility: "collapsed", metadata: { usage: e } }) } } const helpers_RealtimeEventEmitter = RealtimeEventEmitter , {useState: ChatbotRealtime_useState, useRef: ChatbotRealtime_useRef, useCallback: ChatbotRealtime_useCallback, useMemo: ChatbotRealtime_useMemo, useEffect: ChatbotRealtime_useEffect} = wp.element , DEBUG_LEVELS = { none: 0, low: 1, normal: 2, high: 3, verbose: 4 } , CURRENT_DEBUG = DEBUG_LEVELS.low; function debugLog(e, ...t) { CURRENT_DEBUG >= e && console.log(...t) } function parseUsage(e) { if (!e) return null; const {input_token_details: {text_tokens: t=0, audio_tokens: a=0, cached_tokens_details: {text_tokens: n=0, audio_tokens: s=0}={}}={}, output_token_details: {text_tokens: r=0, audio_tokens: o=0}={}} = e; return { text_input_tokens: t, audio_input_tokens: a, text_output_tokens: r, audio_output_tokens: o, text_cached_tokens: n, audio_cached_tokens: s } } function getChatbotRepresentation(e, t="user") { const {pluginUrl: a, iconUrl: n, userData: s, userName: r, aiName: o, guestName: i, userAvatar: l, aiAvatar: c, guestAvatar: u, userAvatarUrl: d, aiAvatarUrl: m, guestAvatarUrl: p} = e , h = (e, t, n, s, r=!1) => { if (t) { const e = ( (e, t=!1) => (0, helpers.mv)(e) ? e : e && !(0, js_helpers.Ve)(e) ? t ? e :${a}/images/${e}: null)(n, r) || s; if (e) return { emoji: null, text: null, image: e, use: "image" } } return (0, js_helpers.Ve)(e) ? { emoji: e, text: null, image: null, use: "emoji" } : { emoji: null, text: e, image: null, use: "text" } } ; return "assistant" === t ? h(o, c, m, n) : s ? h(ChatbotRealtime_formatName(r, i, s), l, d, null == s ? void 0 : s.AVATAR_URL, !0) : s || "user" !== t ? { emoji: null, text: "Unknown", image: null, use: "text" } : h(i || "Guest", u, p, null) } function ChatbotRealtime_formatName(e, t, a) { return a && 0 !== Object.keys(a).length ? Object.entries(a).reduce(( (e, [t,a]) => { const n ={${t}}; return e.includes(n) ? e.replace(n, a) : e } ), e) : t || e || "Guest" } const ChatbotRealtime = ({onMessagesUpdate: e, onStreamEvent: t}) => { const {state: a, actions: n} = (0, ChatbotContext.o)() , {busy: s, locked: r, open: o, popup: i, system: l} = a , {onStartRealtimeSession: c, onRealtimeFunctionCallback: u, onCommitStats: d, onCommitDiscussions: m, setError: p} = n , h = (null == l || l.debugMode, (null == l ? void 0 : l.eventLogs) || !1) , [g,_] = ChatbotRealtime_useState(!1) , [f,y] = ChatbotRealtime_useState(!1) , [b,v] = ChatbotRealtime_useState(!1) , [E,R] = ChatbotRealtime_useState(null) , [w,C] = ChatbotRealtime_useState(null) , [k,x] = ChatbotRealtime_useState({ text_input_tokens: 0, audio_input_tokens: 0, text_output_tokens: 0, audio_output_tokens: 0, text_cached_tokens: 0, audio_cached_tokens: 0 }) , [S,I] = ChatbotRealtime_useState([]) , M = ChatbotRealtime_useRef(new Set) , T = ChatbotRealtime_useCallback(( (e, a) => { a && a.subtype && t && t({ ...a, timestamp: a.timestamp || (new Date).getTime(), messageId: "realtime-session" }) } ), [t]) , A = ChatbotRealtime_useRef(null); ChatbotRealtime_useEffect(( () => { A.current = new helpers_RealtimeEventEmitter(T,h) } ), [T, h]); const N = ChatbotRealtime_useRef(null) , L = ChatbotRealtime_useRef(null) , D = ChatbotRealtime_useRef(null) , U = ChatbotRealtime_useRef(null) , [P,O] = ChatbotRealtime_useState(!0) , [B,F] = ChatbotRealtime_useState(!0) , [z,$] = ChatbotRealtime_useState(!1) , [j,W] = ChatbotRealtime_useState(!1) , [H,V] = ChatbotRealtime_useState(null) , K = ChatbotRealtime_useRef([]) , q = ChatbotRealtime_useMemo(( () => getChatbotRepresentation(a, "user")), [a]) , G = ChatbotRealtime_useMemo(( () => getChatbotRepresentation(a, "assistant")), [a]); ChatbotRealtime_useEffect(( () => { !o && f && i && X() } ), [o, i, f]), ChatbotRealtime_useEffect(( () => { e && e(S) } ), [S, e]); const Y = ChatbotRealtime_useCallback((async e => { const t = await d(e); t.overLimit && (h && A.current && A.current.emit(STREAM_TYPES.ERROR, t.limitMessage || "Usage limit exceeded", { visibility: "visible", error: !0 }), console.warn("Usage limit exceeded, stopping realtime connection:", t.limitMessage), U.current && U.current()) } ), [d, h]) , Q = ChatbotRealtime_useCallback(( () => { L.current && "open" === L.current.readyState ? (L.current.send(JSON.stringify({ type: "session.update", session: { input_audio_transcription: { model: "whisper-1" } } })), debugLog(DEBUG_LEVELS.low, "Sent session.update to enable Whisper.")) : console.error("Data channel is not open yet; cannot enable transcription.") } ), []) , J = ChatbotRealtime_useCallback((async (e, t, a) => { let n = {}; try { n = JSON.parse(a || "{}") } catch (e) { console.error("Could not parse function arguments.", a) } const s = K.current.find((e => e.name === t)); if (s) try { var r; const a = await u(s.id, s.type, s.name, s.target, n); if (null == a || !a.success) return void console.error("Callback failed.", null == a ? void 0 : a.message); const o = a.data; if (h && A.current) { const a = "string" == typeof o ? o : JSON.stringify(o) , n = a.length > 100 ? a.substring(0, 100) + "..." : a; A.current.emit(STREAM_TYPES.TOOL_RESULT,Got result from ${t}.¨C67CNo match for callback: ‘${t}’.¨C68CCalling ${t.name}…¨C69Chttps://api.openai.com/v1/realtime?model=${o}¨C70CBearer ${e}¨C71C${e.content.slice(0, 256)}…¨C72C${e.messageId}-${t}¨C73C${B}px¨C74Cmwai-${null == i ? void 0 : i.themeId}-theme¨C75C ${c}¨C76Creturn (${t});¨C77CThis shortcut type is not supported: ${n}.¨C78CBlock type ${n} is not supported.¨C79Cmwai-chatbot-${c || l}¨C80C–mwai-${t}¨C81C${x}/mwai-ui/v1/discussions/list¨C82CCould not retrieve the discussions: ${h.message}¨C83C${x}/mwai-ui/v1/discussions/edit¨C84CCould not update the discussion: ${o.message}¨C85C${x}/mwai-ui/v1/discussions/delete¨C86CCould not delete the discussion: ${l.message}¨C87Cmwai-${null == r ? void 0 : r.themeId}-theme¨C88C${c.top}px¨C89C${c.left}px¨C90Cseparator-${t}¨C91Ctitle-${t}¨C92Cmwai-${null == t ? void 0 : t.themeId}-theme¨C93Cmwai-discussions-${l}¨C94CPage ${h + 1} of ${Math.ceil(g / .paging)}`), React.createElement(«button», {
onClick: () => {
const e = h + 1;
w(e),
R(!1, e, !0)
}
,
disabled: h >= Math.ceil(g / _.paging) – 1 || m || f
}, React.createElement(ChevronRight, {
size: 16
})))))
}
, chatbot_DiscussionsUI = DiscussionsUI
, DiscussionsSystem = e => React.createElement(DiscussionsContextProvider, e, React.createElement(chatbot_DiscussionsUI, e))
, chatbot_DiscussionsSystem = DiscussionsSystem
, {render} = wp.element;
function decodeHtmlEntities(e) {
const t = document.createElement(«textarea»);
return t.innerHTML = e,
t.value
}
function initializeMwai() {
function e(e, t) {
e.forEach((e => {
if (e.hasAttribute(«data-mwai-initialized»))
return;
const a = e.getAttribute(«data-params»)
, n = e.getAttribute(«data-system»)
, s = e.getAttribute(«data-theme»);
if (!a || !n || !s)
return void console.warn(«MWAI: Missing required attributes for initialization», e);
const r = JSON.parse(decodeHtmlEntities(a))
, o = JSON.parse(decodeHtmlEntities(n))
, i = JSON.parse(decodeHtmlEntities(s));
e.setAttribute(«data-mwai-initialized», «true»),
e.removeAttribute(«data-params»),
e.removeAttribute(«data-system»),
e.removeAttribute(«data-theme»),
render(t({
system: o,
params: r,
theme: i
}), e)
}
))
}
e(document.querySelectorAll(«.mwai-chatbot-container»), chatbot_ChatbotSystem),
e(document.querySelectorAll(«.mwai-discussions-container»), chatbot_DiscussionsSystem)
}
document.addEventListener(«DOMContentLoaded», initializeMwai),
window.mwaiInitialize = initializeMwai
}
)();
