@crestapps/ai-chat-ui 1.2.0 → 2.0.0-preview.154
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai-chat.js +29 -0
- package/dist/ai-chat.js.map +1 -1
- package/dist/ai-chat.min.js +1 -1
- package/dist/ai-chat.min.js.map +1 -1
- package/package.json +1 -1
package/dist/ai-chat.min.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var _excluded=["placeholder"];function _regenerator(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */var e,t,n="function"==typeof Symbol?Symbol:{},i=n.iterator||"@@iterator",o=n.toStringTag||"@@toStringTag";function s(n,i,o,s){var c=i&&i.prototype instanceof r?i:r,l=Object.create(c.prototype);return _regeneratorDefine2(l,"_invoke",function(n,i,o){var s,r,c,l=0,u=o||[],d=!1,h={p:0,n:0,v:e,a:f,f:f.bind(e,4),d:function(t,n){return s=t,r=0,c=e,h.n=n,a}};function f(n,i){for(r=n,c=i,t=0;!d&&l&&!o&&t<u.length;t++){var o,s=u[t],f=h.p,p=s[2];n>3?(o=p===i)&&(c=s[(r=s[4])?5:(r=3,3)],s[4]=s[5]=e):s[0]<=f&&((o=n<2&&f<s[1])?(r=0,h.v=i,h.n=s[1]):f<p&&(o=n<3||s[0]>i||i>p)&&(s[4]=n,s[5]=i,h.n=p,r=0))}if(o||n>1)return a;throw d=!0,i}return function(o,u,p){if(l>1)throw TypeError("Generator is already running");for(d&&1===u&&f(u,p),r=u,c=p;(t=r<2?e:c)||!d;){s||(r?r<3?(r>1&&(h.n=-1),f(r,c)):h.n=c:h.v=c);try{if(l=2,s){if(r||(o="next"),t=s[o]){if(!(t=t.call(s,c)))throw TypeError("iterator result is not an object");if(!t.done)return t;c=t.value,r<2&&(r=0)}else 1===r&&(t=s.return)&&t.call(s),r<2&&(c=TypeError("The iterator does not provide a '"+o+"' method"),r=1);s=e}else if((t=(d=h.n<0)?c:n.call(i,h))!==a)break}catch(t){s=e,r=1,c=t}finally{l=1}}return{value:t,done:d}}}(n,o,s),!0),l}var a={};function r(){}function c(){}function l(){}t=Object.getPrototypeOf;var u=[][i]?t(t([][i]())):(_regeneratorDefine2(t={},i,function(){return this}),t),d=l.prototype=r.prototype=Object.create(u);function h(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,l):(e.__proto__=l,_regeneratorDefine2(e,o,"GeneratorFunction")),e.prototype=Object.create(d),e}return c.prototype=l,_regeneratorDefine2(d,"constructor",l),_regeneratorDefine2(l,"constructor",c),c.displayName="GeneratorFunction",_regeneratorDefine2(l,o,"GeneratorFunction"),_regeneratorDefine2(d),_regeneratorDefine2(d,o,"Generator"),_regeneratorDefine2(d,i,function(){return this}),_regeneratorDefine2(d,"toString",function(){return"[object Generator]"}),(_regenerator=function(){return{w:s,m:h}})()}function _regeneratorDefine2(e,t,n,i){var o=Object.defineProperty;try{o({},"",{})}catch(e){o=0}_regeneratorDefine2=function(e,t,n,i){function s(t,n){_regeneratorDefine2(e,t,function(e){return this._invoke(t,n,e)})}t?o?o(e,t,{value:n,enumerable:!i,configurable:!i,writable:!i}):e[t]=n:(s("next",0),s("throw",1),s("return",2))},_regeneratorDefine2(e,t,n,i)}function asyncGeneratorStep(e,t,n,i,o,s,a){try{var r=e[s](a),c=r.value}catch(e){return void n(e)}r.done?t(c):Promise.resolve(c).then(i,o)}function _asyncToGenerator(e){return function(){var t=this,n=arguments;return new Promise(function(i,o){var s=e.apply(t,n);function a(e){asyncGeneratorStep(s,i,o,a,r,"next",e)}function r(e){asyncGeneratorStep(s,i,o,a,r,"throw",e)}a(void 0)})}}function _toConsumableArray(e){return _arrayWithoutHoles(e)||_iterableToArray(e)||_unsupportedIterableToArray(e)||_nonIterableSpread()}function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _iterableToArray(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}function _arrayWithoutHoles(e){if(Array.isArray(e))return _arrayLikeToArray(e)}function _objectWithoutProperties(e,t){if(null==e)return{};var n,i,o=_objectWithoutPropertiesLoose(e,t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);for(i=0;i<s.length;i++)n=s[i],-1===t.indexOf(n)&&{}.propertyIsEnumerable.call(e,n)&&(o[n]=e[n])}return o}function _objectWithoutPropertiesLoose(e,t){if(null==e)return{};var n={};for(var i in e)if({}.hasOwnProperty.call(e,i)){if(-1!==t.indexOf(i))continue;n[i]=e[i]}return n}function _createForOfIteratorHelper(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=_unsupportedIterableToArray(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var i=0,o=function(){};return{s:o,n:function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}},e:function(e){throw e},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var s,a=!0,r=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return a=e.done,e},e:function(e){r=!0,s=e},f:function(){try{a||null==n.return||n.return()}finally{if(r)throw s}}}}function _slicedToArray(e,t){return _arrayWithHoles(e)||_iterableToArrayLimit(e,t)||_unsupportedIterableToArray(e,t)||_nonIterableRest()}function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray(e,t):void 0}}function _arrayLikeToArray(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n<t;n++)i[n]=e[n];return i}function _iterableToArrayLimit(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var i,o,s,a,r=[],c=!0,l=!1;try{if(s=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;c=!1}else for(;!(c=(i=s.call(n)).done)&&(r.push(i.value),r.length!==t);c=!0);}catch(e){l=!0,o=e}finally{try{if(!c&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(l)throw o}}return r}}function _arrayWithHoles(e){if(Array.isArray(e))return e}function _typeof(e){return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof(e)}window.coreAIChatManager=function(){var e={generatedImageAltText:"Generated Image",generatedImageMaxWidth:400,downloadImageTitle:"Download image",downloadChartTitle:"Download chart as image",downloadChartButtonText:"Download",userLabel:"You",assistantLabel:"Assistant",thumbsUpTitle:"Thumbs up",thumbsDownTitle:"Thumbs down",copyTitle:"Click here to copy response to clipboard.",copiedTitle:"Response copied to clipboard.",codeCopiedText:"Copied!",copyResetDelayMs:2e3,widget:{chatWidgetContainer:null,chatWidgetStateName:null,chatHistorySection:null,showHistoryButton:null,closeHistoryButton:null,newChatButton:null,toggleButtonSelector:null,resetSizeButtonSelector:null,dragHandleSelector:".ai-chat-widget-header",enableDragging:!0,enableResizing:!0,persistLayout:!0,defaultWidth:null,defaultHeight:null,minWidth:320,minHeight:420},messageTemplate:'\n <div class="ai-chat-messages">\n <div v-for="(message, index) in messages" :key="\'msg-\' + index" class="ai-chat-message-item">\n <div>\n <div v-if="message.role === \'user\'" class="ai-chat-message-heading ai-chat-message-heading-user">\n <span class="ai-chat-msg-role ai-chat-msg-role-user">{{ userLabel }}</span>\n </div>\n <div v-else-if="message.role !== \'indicator\'" class="ai-chat-message-heading ai-chat-message-heading-assistant">\n <div :class="getAssistantRoleClasses(message)">\n <span :class="getAssistantIconClasses(message, index)"><i :class="getAssistantIcon(message)"></i></span>\n <span class="ai-chat-message-role-label">{{ getAssistantLabel(message) }}</span>\n </div>\n </div>\n <div class="ai-chat-message-body lh-base">\n <h4 v-if="message.title">{{ message.title }}</h4>\n <div v-html="message.htmlContent"></div>\n <ol v-if="message.citationReferences && message.citationReferences.length" class="ai-chat-citation-list">\n <li v-for="citation in message.citationReferences" :key="\'citation-\' + (citation.referenceKey || citation.displayIndex)" class="ai-chat-citation-item">\n <a v-if="citation.link" :href="citation.link" :target="citation.isDownload ? null : \'_blank\'" :rel="citation.isDownload ? null : \'noopener noreferrer\'">{{ citation.label }}</a>\n <span v-else>{{ citation.label }}</span>\n </li>\n </ol>\n <span class="message-buttons-container" v-if="!isIndicator(message)">\n <template v-if="metricsEnabled && message.role === \'assistant\'">\n <span class="ai-chat-message-assistant-feedback" :data-message-id="message.id">\n <button type="button" class="btn btn-sm btn-link text-success p-0 me-2 button-message-toolbox rate-up-btn" @click="rateMessage(message, true, $event)" :title="thumbsUpTitle">\n <i class="fa-regular fa-thumbs-up"></i>\n </button>\n <button type="button" class="btn btn-sm btn-link text-danger p-0 me-2 button-message-toolbox rate-down-btn" @click="rateMessage(message, false, $event)" :title="thumbsDownTitle">\n <i class="fa-regular fa-thumbs-down"></i>\n </button>\n </span>\n </template>\n <button type="button" v-if="textToSpeechEnabled && !isConversationMode && message.role === \'assistant\' && !message.isStreaming" class="btn btn-sm btn-link text-secondary p-0 me-1 button-message-toolbox" :class="{ \'tts-playing\': ttsPlayingMessageIndex === index }" :data-tts-message-index="index" @click="toggleMessageTts(message, index)" :title="ttsPlayingMessageIndex === index ? \'Pause audio\' : \'Read aloud\'">\n <span :class="ttsPlayingMessageIndex === index ? \'fa-solid fa-circle-pause\' : \'fa-solid fa-circle-play\'"></span>\n </button>\n <button type="button" class="btn btn-sm btn-link p-0 button-message-toolbox ai-response-copy-btn" :class="copiedMessageIndex === index ? \'text-success\' : \'text-secondary\'" :data-copy-message-index="index" @click="copyResponse(message, index, $event)" :title="copiedMessageIndex === index ? copiedTitle : copyTitle">\n <i :class="copiedMessageIndex === index ? \'fa-solid fa-check\' : \'fa-solid fa-copy\'"></i>\n </button>\n </span>\n </div>\n </div>\n </div>\n <div v-for="notification in notifications" :key="\'notif-\' + notification.type" class="ai-chat-notification" :class="\'ai-chat-notification-\' + (notification.type || \'info\') + \' \' + (notification.cssClass || \'\')">\n <div class="ai-chat-notification-content">\n <i v-if="notification.icon" :class="notification.icon" class="ai-chat-notification-icon"></i>\n <span class="ai-chat-notification-text">{{ notification.content }}</span>\n <button type="button" v-if="notification.dismissible" class="btn btn-sm btn-link p-0 ms-2 ai-chat-notification-dismiss" @click="dismissNotification(notification.type)" title="Dismiss">\n <i class="fa-solid fa-xmark"></i>\n </button>\n </div>\n <div v-if="notification.actions && notification.actions.length" class="ai-chat-notification-actions">\n <button type="button" v-for="action in notification.actions" :key="action.name" class="btn btn-sm" :class="action.cssClass || \'btn-outline-secondary\'" @click="handleNotificationAction(notification.type, action.name)">\n <i v-if="action.icon" :class="action.icon" class="me-1"></i>\n {{ action.label }}\n </button>\n </div>\n </div>\n </div>\n ',indicatorTemplate:'\n <div class="ai-chat-message-heading ai-chat-message-heading-assistant">\n <div class="ai-chat-msg-role ai-chat-msg-role-assistant">\n <span class="ai-streaming-icon"><i class="fa fa-robot" style="display: inline-block;"></i></span>\n <span class="ai-chat-message-role-label">Assistant</span>\n </div>\n </div>\n '};function t(e){if(!e)return"";var t=e.trim();return/^javascript:/i.test(t)||/^vbscript:/i.test(t)||/^data:text\/html/i.test(t)?"":e}function n(e){var t=document.createElement("span");return t.textContent=e,t.innerHTML}function i(e){var t=window.FontAwesome;(function(e){if(!e||1!==e.nodeType)return!1;var t='i[class*="fa-"],i.fa,i.fas,i.far,i.fab';return!("function"!=typeof e.matches||!e.matches(t))||"function"==typeof e.querySelector&&!!e.querySelector(t)})(e)&&t&&t.dom&&"function"==typeof t.dom.i2svg&&t.dom.i2svg({node:e})}function o(e){if(!e||"undefined"==typeof MutationObserver)return null;var t=new MutationObserver(function(e){e.forEach(function(e){e.addedNodes.forEach(function(e){i(e)})})});return t.observe(e,{childList:!0,subtree:!0}),t}function s(e){var n,i,o,s,a,r,c,l,u,d,h;if(!e||"object"!==_typeof(e))return null;var f=Object.assign({},e);return f.index=null!==(n=null!==(i=f.index)&&void 0!==i?i:f.Index)&&void 0!==n?n:0,f.text=null!==(o=null!==(s=f.text)&&void 0!==s?s:f.Text)&&void 0!==o?o:null,f.title=null!==(a=null!==(r=f.title)&&void 0!==r?r:f.Title)&&void 0!==a?a:null,f.link=t(null!==(c=null!==(l=f.link)&&void 0!==l?l:f.Link)&&void 0!==c?c:null),f.referenceType=null!==(u=null!==(d=f.referenceType)&&void 0!==d?d:f.ReferenceType)&&void 0!==u?u:null,f.isGenerated=!0===(null!==(h=f.isGenerated)&&void 0!==h?h:f.IsGenerated),f}function a(e){return!(!e||"object"!==_typeof(e))&&("string"==typeof e.referenceType&&"document"===e.referenceType.toLowerCase()||!("string"!=typeof e.link||!/\/ai\/documents\/.+\/download(?:$|\?)/i.test(e.link)))}function r(e){if(!e||"object"!==_typeof(e))return{};for(var t={},n=0,i=Object.entries(e);n<i.length;n++){var o,a=_slicedToArray(i[n],2),r=a[0],c=a[1];t[r]=null!==(o=s(c))&&void 0!==o?o:{}}return t}function c(e,t){return e.title||e.text||t}function l(e,t){var n=r(null!=t?t:e.references),i="string"==typeof e.rawContent?e.rawContent:"string"==typeof e.content?e.content:"",o=function(e,t){var n=(e||"").trim(),i=r(t),o=Object.entries(i);if(!o.length)return{content:n,citations:[]};var s=o.filter(function(e){var t=_slicedToArray(e,1)[0];return n.includes(t)}),l=o.filter(function(e){var t=_slicedToArray(e,2),i=t[0];return t[1].isGenerated&&!n.includes(i)});if(!s.length&&!l.length)return{content:n,citations:[]};s.sort(function(e,t){var n=_slicedToArray(e,2)[1],i=_slicedToArray(t,2)[1];return n.index-i.index}),l.sort(function(e,t){var n=_slicedToArray(e,2)[1],i=_slicedToArray(t,2)[1];return n.index-i.index});var u,d=[],h=1,f=_createForOfIteratorHelper(s);try{for(f.s();!(u=f.n()).done;){var p=_slicedToArray(u.value,2),m=p[0],g=p[1],v="__CITE_".concat(h,"_").concat(g.index||h,"__");n=n.replaceAll(m,v),d.push({referenceKey:m,displayIndex:h,label:c(g,m),link:g.link||null,isDownload:a(g),placeholder:v}),h++}}catch(e){f.e(e)}finally{f.f()}for(var y=0,b=d;y<b.length;y++){var S=b[y];n=n.replaceAll(S.placeholder,"<sup>".concat(S.displayIndex,"</sup>"))}n=n.replaceAll("</sup><sup>","</sup><sup>,</sup><sup>");var A,E=_createForOfIteratorHelper(l);try{for(E.s();!(A=E.n()).done;){var T=_slicedToArray(A.value,2),C=T[0],w=T[1];d.push({referenceKey:C,displayIndex:h,label:c(w,C),link:w.link||null,isDownload:!0,placeholder:null}),h++}}catch(e){E.e(e)}finally{E.f()}return{content:n,citations:d.map(function(e){return e.placeholder,_objectWithoutProperties(e,_excluded)})}}(i,n);return e.rawContent=i,e.content=i,e.displayContent=o.content,e.references=n,e.citationReferences=o.citations,e.copyContent=function(e,t){var n=(e||"").trim();if(!n||!Array.isArray(t)||0===t.length)return n;var i,o=_createForOfIteratorHelper(t);try{for(o.s();!(i=o.n()).done;){var s=i.value;n=n.replaceAll(s.referenceKey,"[".concat(s.displayIndex,"]"))}}catch(e){o.e(e)}finally{o.f()}n+="\n\nReferences:\n";var a,r=_createForOfIteratorHelper(t);try{for(r.s();!(a=r.n()).done;){var c=a.value;n+="".concat(c.displayIndex,". ").concat(c.label),c.link&&(n+=" - ".concat(c.link)),n+="\n"}}catch(e){r.e(e)}finally{r.f()}return n.trimEnd()}(i,o.citations),e.htmlContent=m(o.content,e),e}var u=new marked.Renderer;u.link=function(e){var n=t(e.href);return n?'<a href="'.concat(n,'" target="_blank" rel="noopener noreferrer">').concat(e.text,"</a>"):e.text||""},u.code=function(e){var t=e.text||"",i=(e.lang||"").trim(),o=t;if("undefined"!=typeof hljs)if(i&&hljs.getLanguage(i))try{o=hljs.highlight(t,{language:i}).value}catch(e){}else try{o=hljs.highlightAuto(t).value}catch(e){}else o=n(t);var s=i?n(i):"code";return'<div class="ai-code-block"><div class="ai-code-header"><span class="ai-code-lang"><i class="fa-solid fa-code"></i> '.concat(s,'</span><button type="button" class="ai-code-copy-btn" title="Copy code"><i class="fa-regular fa-copy"></i></button></div><pre><code class="hljs').concat(i?" language-"+i:"",'">').concat(o,"</code></pre></div>")},u.image=function(n){var i=t(n.href);if(!i)return"";var o=n.text||e.generatedImageAltText,s=e.generatedImageMaxWidth;return'<div class="generated-image-container">\n <img src="'.concat(i,'" alt="').concat(o,'" class="img-thumbnail" style="max-width: ').concat(s,'px; height: auto;" />\n <div class="mt-2">\n <a href="').concat(i,'" target="_blank" download="').concat(o,'" title="').concat(e.downloadImageTitle,'" class="btn btn-sm btn-outline-secondary ai-download-image">\n <i class="fa-solid fa-download"></i>\n </a>\n </div>\n </div>')};var d=0,h=[];function f(e){if(e&&e._pendingCharts&&e._pendingCharts.length){var t=_toConsumableArray(e._pendingCharts);e._pendingCharts=[],requestAnimationFrame(function(){var e,n=_createForOfIteratorHelper(t);try{for(n.s();!(e=n.n()).done;){var i=e.value;p(i.chartId,i.config)}}catch(e){n.e(e)}finally{n.f()}})}}function p(e,t){var n=document.getElementById(e);if(!n)return!1;if("undefined"==typeof Chart)return console.warn('Chart.js is not loaded. To render interactive charts, include the Chart.js library on the page (e.g., <script src="https://cdn.jsdelivr.net/npm/chart.js@4/dist/chart.umd.min.js"><\/script>).'),!1;if(null===n.offsetParent)return window.__chartConfigs[e]=t,!1;try{var i,o,s;n._chartInstance&&n._chartInstance.destroy();var a="string"==typeof t?JSON.parse(t):t;return null!==(i=a.options)&&void 0!==i||(a.options={}),a.options.responsive=!0,a.options.maintainAspectRatio=!0,null!==(s=(o=a.options).aspectRatio)&&void 0!==s||(o.aspectRatio=4/3),n._chartInstance=new Chart(n,a),delete window.__chartConfigs[e],!0}catch(e){return console.error("Error creating chart:",e),!1}}function m(e,t){h=[];var n=marked.parse(e,{renderer:u});return t._pendingCharts=h.length>0?_toConsumableArray(h):[],DOMPurify.sanitize(n,{ADD_TAGS:["canvas"],ADD_ATTR:["target"]})}function g(e){return e&&"object"===_typeof(e)?Object.fromEntries(Object.entries(e).filter(function(e){return void 0!==_slicedToArray(e,2)[1]})):{}}window.__chartConfigs=window.__chartConfigs||{},marked.use({extensions:[{name:"chart",level:"block",start:function(e){var t=e.indexOf("[chart:");return t>=0?t:void 0},tokenizer:function(e){var t=function(e){var t="[chart:",n=e.indexOf(t);if(n<0)return null;var i=n+t.length,o=i;for(;o<e.length&&(" "===e[o]||"\n"===e[o]||"\r"===e[o]||"\t"===e[o]);)o++;if(o>=e.length||"{"!==e[o])return null;for(var s=0,a=!1,r=!1;o<e.length;o++){var c=e[o];if(a){if(r){r=!1;continue}if("\\"===c){r=!0;continue}'"'===c&&(a=!1)}else if('"'!==c){if("{"===c)s++;else if("}"===c&&0===--s){var l=o,u=e.indexOf("]",l+1);return u<0?null:{startIndex:n,endIndex:u+1,json:e.substring(i,l+1).trim()}}}else a=!0}return null}(e);if(t&&0===t.startIndex){var n="chat_chart_".concat(++d);return{type:"chart",raw:e.substring(0,t.endIndex),chartId:n,json:t.json}}},renderer:function(t){return h.push({chartId:t.chartId,config:t.json}),window.__chartConfigs[t.chartId]=t.json,n=t.chartId,'<div class="chart-container" style="position: relative; width: 100%; max-width: 560px; min-height: 420px;">'+'<canvas id="'.concat(n,'"></canvas>')+'</div><div class="mt-2">'+'<button type="button" class="btn btn-sm btn-outline-secondary download-chart-btn" data-chart-id="'.concat(n,'" title="').concat(e.downloadChartTitle,'">')+'<i class="fa-solid fa-download"></i> '.concat(e.downloadChartButtonText)+"</button></div>";var n}}]}),window.renderPendingCharts=function(){if("undefined"!=typeof Chart){var e=window.__chartConfigs;e&&requestAnimationFrame(function(){for(var t=0,n=Object.keys(e);t<n.length;t++){var i=n[t];p(i,e[i])}})}};var v=function(t){var a=g(t),c=g(a.widget),u=Object.assign({},e,a);u.widget=Object.assign({},e.widget||{},c),u.indicatorTemplate=function(e,t){if(!e)return e;var i=n(t||"Assistant");return e.replace(/\{\{\s*assistantLabel\s*\}\}/g,i)}(u.indicatorTemplate,u.assistantLabel);var d=!(!c.chatWidgetContainer||!c.chatWidgetStateName),h=window.coreAIChatWidgetBehavior||null;if(e=u,u.signalRHubUrl)if(u.appElementSelector)if(u.chatContainerElementSelector)if(u.inputElementSelector){if(u.sendButtonElementSelector){var p={data:function(){return{inputElement:null,buttonElement:null,chatContainer:null,placeholder:null,isSessionStarted:!1,isPlaceholderVisible:!0,isStreaming:!1,isNavigatingAway:!1,autoScroll:!0,stream:null,messages:[],notifications:[],prompt:"",documents:u.existingDocuments||[],isUploading:!1,isDocumentOperationPending:!1,documentOperationQueue:null,uploadErrors:[],isDragOver:!1,documentBar:null,metricsEnabled:!!u.metricsEnabled,userLabel:u.userLabel,assistantLabel:u.assistantLabel,thumbsUpTitle:u.thumbsUpTitle,thumbsDownTitle:u.thumbsDownTitle,copyTitle:u.copyTitle,copiedTitle:u.copiedTitle,isRecording:!1,mediaRecorder:null,preRecordingPrompt:"",micButton:null,speechToTextEnabled:"AudioInput"===u.chatMode||"Conversation"===u.chatMode,textToSpeechEnabled:"Conversation"===u.chatMode||!!u.textToSpeechEnabled,ttsVoiceName:u.ttsVoiceName||null,audioChunks:[],audioPlayQueue:[],isPlayingAudio:!1,currentAudioElement:null,currentAudioUrl:null,ttsButton:null,ttsPlayingMessageIndex:-1,ttsAudioCache:{},ttsInstanceId:"ai-chat-"+Math.random().toString(36).slice(2),singleResponseMode:!!u.singleResponseMode,conversationModeEnabled:"Conversation"===u.chatMode,conversationButton:null,isConversationMode:!1,notificationDismissTimers:{},pendingSessionPromise:null,pendingSessionResolver:null,pendingSessionRejector:null,pendingSessionTimeoutId:null,copiedMessageIndex:-1,copyResetTimeoutId:null,activeCopyButton:null}},computed:{lastAssistantIndex:function(){for(var e=this.messages.length-1;e>=0;e--)if("assistant"===this.messages[e].role)return e;return-1}},methods:{handleBeforeUnload:function(){this.isNavigatingAway=!0},handleDragOver:function(e){if(u.sessionDocumentsEnabled){e.preventDefault(),e.stopPropagation(),this.isDragOver=!0;var t=this.inputElement?this.inputElement.closest(".ai-admin-widget-input, .text-bg-light"):null;t&&t.classList.add("ai-chat-drag-over")}},handleDragLeave:function(e){if(u.sessionDocumentsEnabled){e.preventDefault(),e.stopPropagation(),this.isDragOver=!1;var t=this.inputElement?this.inputElement.closest(".ai-admin-widget-input, .text-bg-light"):null;t&&t.classList.remove("ai-chat-drag-over")}},handleDrop:function(e){if(u.sessionDocumentsEnabled){e.preventDefault(),e.stopPropagation(),this.isDragOver=!1;var t=this.inputElement?this.inputElement.closest(".ai-admin-widget-input, .text-bg-light"):null;t&&t.classList.remove("ai-chat-drag-over"),e.dataTransfer&&e.dataTransfer.files&&e.dataTransfer.files.length>0&&this.uploadFiles(Array.from(e.dataTransfer.files))}},triggerFileInput:function(){if(u.sessionDocumentsEnabled&&!this.isDocumentOperationPending){var e=document.getElementById("ai-chat-doc-input");e&&e.click()}},handleFileInputChange:function(e){var t=e.target.files?Array.from(e.target.files):[];t&&t.length>0&&this.uploadFiles(t),e.target.value=""},queueDocumentOperation:function(e){var t=this,n=(this.documentOperationQueue||Promise.resolve()).catch(function(){}).then(_asyncToGenerator(_regenerator().m(function n(){return _regenerator().w(function(n){for(;;)switch(n.p=n.n){case 0:return t.isDocumentOperationPending=!0,n.p=1,n.n=2,e();case 2:return n.a(2,n.v);case 3:return n.p=3,t.isDocumentOperationPending=!1,n.f(3);case 4:return n.a(2)}},n,null,[[1,,3,4]])})));return this.documentOperationQueue=n.finally(function(){t.documentOperationQueue===n&&(t.documentOperationQueue=null)}),this.documentOperationQueue},uploadFiles:function(e){var t=this;return _asyncToGenerator(_regenerator().m(function n(){var i;return _regenerator().w(function(n){for(;;)switch(n.n){case 0:if(u.uploadDocumentUrl){n.n=1;break}return n.a(2);case 1:if(0!==(i=Array.isArray(e)?e.slice():Array.from(e||[])).length){n.n=2;break}return n.a(2);case 2:return n.a(2,t.queueDocumentOperation(_asyncToGenerator(_regenerator().m(function e(){var n,o,s,a,r,c,l,d,h,f;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:if(n=t.getSessionId(),o=t.getProfileId(),n){e.n=4;break}return e.p=1,e.n=2,t.ensureSessionForDocuments(o);case 2:n=e.v,e.n=4;break;case 3:return e.p=3,h=e.v,console.error("Failed to create a chat session for document upload:",h),t.uploadErrors=[{fileName:"",error:"Could not create a chat session for the upload."}],t.renderDocumentBar(),e.a(2);case 4:if(n){e.n=5;break}return console.warn("Cannot upload documents without a session or profile."),t.uploadErrors=[{fileName:"",error:"Could not create a chat session for the upload."}],t.renderDocumentBar(),e.a(2);case 5:for(t.isUploading=!0,t.uploadErrors=[],t.renderDocumentBar(),e.p=6,(s=new FormData).append("sessionId",n),a=0;a<i.length;a++)s.append("files",i[a]);return e.n=7,fetch(u.uploadDocumentUrl,{method:"POST",body:s});case 7:if((r=e.v).ok){e.n=9;break}return e.n=8,r.text();case 8:return c=e.v,l=t.extractReadableErrorMessage(c,"Upload failed. Please try again."),console.error("Upload failed:",c),t.uploadErrors=[{fileName:"",error:l}],e.a(2);case 9:return e.n=10,r.json();case 10:(d=e.v).sessionId&&d.sessionId!==t.getSessionId()&&t.initializeSession(d.sessionId),Array.isArray(d.documents)?t.documents=d.documents:d.uploaded&&d.uploaded.length>0&&(t.documents=t.documents.concat(d.uploaded)),d.failed&&d.failed.length>0&&(t.uploadErrors=d.failed),e.n=12;break;case 11:e.p=11,f=e.v,console.error("Upload error:",f),t.uploadErrors=[{fileName:"",error:"Upload failed. Please try again."}],t.getSessionId()&&t.reloadCurrentSession();case 12:return e.p=12,t.isUploading=!1,t.renderDocumentBar(),e.f(12);case 13:return e.a(2)}},e,null,[[6,11,12,13],[1,3]])}))))}},n)}))()},removeDocument:function(e){var t=this;return _asyncToGenerator(_regenerator().m(function n(){return _regenerator().w(function(n){for(;;)switch(n.n){case 0:if(u.removeDocumentUrl){n.n=1;break}return n.a(2);case 1:return n.a(2,t.queueDocumentOperation(_asyncToGenerator(_regenerator().m(function n(){var i,o,s,a,r,c,l;return _regenerator().w(function(n){for(;;)switch(n.p=n.n){case 0:return n.p=0,i=t.getSessionId(),n.n=1,fetch(u.removeDocumentUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({itemId:i,documentId:e.documentId})});case 1:if(!(o=n.v).ok){n.n=3;break}return n.n=2,o.json();case 2:s=n.v,Array.isArray(s.documents)?t.documents=s.documents:(a=t.documents.indexOf(e))>-1&&t.documents.splice(a,1),n.n=5;break;case 3:return n.n=4,o.text();case 4:r=n.v,c=t.extractReadableErrorMessage(r,"Failed to remove document. Please try again."),console.error("Failed to remove document:",o.status,r),t.uploadErrors=[{fileName:e.fileName||"",error:c}],i&&t.reloadCurrentSession(),t.renderDocumentBar();case 5:n.n=7;break;case 6:n.p=6,l=n.v,console.error("Remove document error:",l),t.uploadErrors=[{fileName:e.fileName||"",error:"Failed to remove document. Please try again."}],t.getSessionId()&&t.reloadCurrentSession(),t.renderDocumentBar();case 7:return n.a(2)}},n,null,[[0,6]])}))))}},n)}))()},formatFileSize:function(e){return e<1024?e+" B":e<1048576?(e/1024).toFixed(1)+" KB":(e/1048576).toFixed(1)+" MB"},renderDocumentBar:function(){if(this.documentBar)if(u.sessionDocumentsEnabled){this.documentBar.classList.remove("d-none");var e='<div class="ai-chat-doc-bar p-2">';e+='<div class="d-flex flex-wrap align-items-center gap-1">';for(var t=0;t<this.documents.length;t++){var n=this.documents[t],i=n.fileName||"Document";i.length>20&&(i=i.substring(0,17)+"..."),e+='<span class="badge bg-secondary bg-opacity-25 text-dark d-inline-flex align-items-center gap-1 px-2 py-1" style="font-size: 0.8rem;" title="'+this.escapeHtml(n.fileName||"")+'">',e+='<i class="fa-solid fa-file-lines" style="font-size: 0.7rem;"></i> ',e+=this.escapeHtml(i),e+=' <button type="button" class="btn-close btn-close-sm ms-1" style="font-size: 0.5rem;" data-doc-index="'+t+'" aria-label="Remove"'+(this.isDocumentOperationPending?" disabled":"")+"></button>",e+="</span>"}for(var o=0;o<this.uploadErrors.length;o++){var s=this.uploadErrors[o],a=s.fileName||"File",r=s.error||"Upload failed";a.length>15&&(a=a.substring(0,12)+"..."),e+='<span class="badge bg-danger bg-opacity-25 text-danger d-inline-flex align-items-center gap-1 px-2 py-1" style="font-size: 0.8rem;" title="'+this.escapeHtml((s.fileName||"")+": "+r)+'">',e+='<i class="fa-solid fa-circle-exclamation" style="font-size: 0.7rem;"></i> ',e+=this.escapeHtml(a),e+=' <button type="button" class="btn-close btn-close-sm ms-1" style="font-size: 0.5rem;" data-error-index="'+o+'" aria-label="Dismiss"></button>',e+="</span>"}this.isUploading&&(e+='<span class="badge bg-info bg-opacity-25 text-dark d-inline-flex align-items-center gap-1 px-2 py-1" style="font-size: 0.8rem;">',e+='<span class="spinner-border spinner-border-sm" style="width: 0.7rem; height: 0.7rem;"></span> Uploading...',e+="</span>"),e+='<button type="button" class="btn btn-sm btn-outline-secondary rounded-pill ai-chat-doc-add-btn d-inline-flex align-items-center gap-1" style="font-size: 0.75rem; padding: 0.15rem 0.5rem;" title="Attach documents"'+(this.isDocumentOperationPending?" disabled":"")+">",e+='<i class="fa-solid fa-paperclip"></i>',0!==this.documents.length||this.isUploading||(e+=" <span>Attach files</span>"),e+="</button>",e+="</div>",u.supportedExtensionsText&&(e+='<div class="small text-muted mt-2">Supported formats: '+this.escapeHtml(u.supportedExtensionsText)+"</div>"),e+="</div>",this.documentBar.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0}));for(var c=this,l=this.documentBar.querySelectorAll("[data-doc-index]"),d=0;d<l.length;d++)l[d].addEventListener("click",function(e){return function(t){if(t.preventDefault(),t.stopPropagation(),!c.isDocumentOperationPending){var n=c.documents[e];n&&c.removeDocument(n)}}}(parseInt(l[d].getAttribute("data-doc-index"))));for(var h=this.documentBar.querySelectorAll("[data-error-index]"),f=0;f<h.length;f++)h[f].addEventListener("click",function(e){return function(t){t.preventDefault(),t.stopPropagation(),c.uploadErrors.splice(e,1),c.renderDocumentBar()}}(parseInt(h[f].getAttribute("data-error-index"))));var p=this.documentBar.querySelector(".ai-chat-doc-add-btn");p&&p.addEventListener("click",function(e){e.preventDefault(),c.isDocumentOperationPending||c.triggerFileInput()})}else this.documentBar.classList.add("d-none")},escapeHtml:function(e){var t=document.createElement("div");return t.textContent=e,t.innerHTML},extractReadableErrorMessage:function(e,t){if(!e||"string"!=typeof e)return t;var n=e.trim();if(!n)return t;if(n.startsWith("{")||n.startsWith("["))try{var i=JSON.parse(n),o=(null==i?void 0:i.error)||(null==i?void 0:i.message)||(null==i?void 0:i.title)||(null==i?void 0:i.detail);return"string"==typeof o&&o.trim()?o.trim():t}catch(e){return t}return/<[^>]+>/.test(n)?t:n},normalizeAssistantAppearance:function(e){if(!e)return null;var t="string"==typeof e.label?e.label.trim():"",n="string"==typeof e.icon?e.icon.trim():"",i="string"==typeof e.cssClass?e.cssClass.trim():"",o=!!e.disableStreamingAnimation;return t||n||i||o?{label:t,icon:n,cssClass:i,disableStreamingAnimation:o}:null},getAssistantLabel:function(e){var t=e?this.normalizeAssistantAppearance(e.appearance):null;return t&&t.label?t.label:this.assistantLabel},getAssistantRoleClasses:function(e){var t=e?this.normalizeAssistantAppearance(e.appearance):null,n=["ai-chat-msg-role"];return t&&t.cssClass?n.push(t.cssClass):n.push("ai-chat-msg-role-assistant"),n},getAssistantIconClasses:function(e,t){var n=e?this.normalizeAssistantAppearance(e.appearance):null;return[this.shouldAnimateAssistantIcon(e,t)?"ai-streaming-icon":"ai-bot-icon",n&&n.cssClass?n.cssClass:""]},getAssistantIcon:function(e){var t=e?this.normalizeAssistantAppearance(e.appearance):null;return t&&t.icon?t.icon:"fa fa-robot"},shouldAnimateAssistantIcon:function(e,t){var n=e?this.normalizeAssistantAppearance(e.appearance):null;return!!e&&e.isStreaming&&t===this.lastAssistantIndex&&!(n&&n.disableStreamingAnimation)},startConnection:function(){var e=this;return _asyncToGenerator(_regenerator().m(function t(){var n;return _regenerator().w(function(t){for(;;)switch(t.p=t.n){case 0:return e.connection=(new signalR.HubConnectionBuilder).withUrl(u.signalRHubUrl).withAutomaticReconnect().build(),e.connection.serverTimeoutInMilliseconds=6e5,e.connection.keepAliveIntervalInMilliseconds=15e3,e.connection.on("LoadSession",function(t){var n;e.initializeSession(t.sessionId,!0),e.messages=[],e.documents=t.documents||[],e.uploadErrors=[],(null!==(n=t.messages)&&void 0!==n?n:[]).forEach(function(t){e.addMessage(t),e.$nextTick(function(){f(t)})}),e.$nextTick(function(){e.refreshAllFeedbackIcons()}),0===e.messages.length&&u.initialPrompt&&e.addMessage({role:"assistant",content:u.initialPrompt})}),e.connection.on("ReceiveError",function(t){console.error("SignalR Error: ",t),e.isRecording&&e.stopRecording(),h&&"function"==typeof h.handleReceiveError&&h.handleReceiveError(e,t,u)}),e.connection.on("MessageRated",function(t,n){var i=e.messages.find(function(e){return e.id===t});i&&(i.userRating=n)}),e.connection.on("ReceiveTranscript",function(t,n,i){if(e.isConversationMode){if(!i&&n){e._conversationPartialTranscript=n;var o='<p class="ai-partial-transcript">'+n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")+"</p>";e._conversationPartialMessage?(e._conversationPartialMessage.content=n,e._conversationPartialMessage.htmlContent=o):(e.hidePlaceholder(),e._conversationPartialMessage={role:"user",content:n,htmlContent:o,isPartial:!0},e.messages.push(e._conversationPartialMessage)),e.scrollToBottom()}}else n&&!e._audioInputSent&&(e.prompt=e.preRecordingPrompt+n,e.inputElement&&(e.inputElement.value=e.prompt,e.inputElement.dispatchEvent(new Event("input"))))}),e.connection.on("ReceiveConversationUserMessage",function(t,n){if(n){if(e.stopAudio(),e._conversationAssistantMessage){var i=e.messages[e._conversationAssistantMessage.index];i&&(i.isStreaming=!1),e._conversationAssistantMessage=null}if(e._conversationPartialMessage){var o=n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">");e._conversationPartialMessage.content=n,e._conversationPartialMessage.htmlContent="<p>"+o+"</p>",e._conversationPartialMessage.isPartial=!1,e._conversationPartialMessage=null}else e.addMessage({role:"user",content:n});e.scrollToBottom()}}),e.connection.on("ReceiveConversationAssistantToken",function(t,n,i,o,s,a){if(!e._conversationAssistantMessage){e.stopAudio(),e.hideTypingIndicator();for(var c=0;c<e.messages.length;c++)e.messages[c].isStreaming&&(e.messages[c].isStreaming=!1);var u=e.messages.length,d={id:n,role:"assistant",content:"",htmlContent:"",isStreaming:!0,userRating:null,appearance:e.normalizeAssistantAppearance(a),references:{}};e.messages.push(d),e._conversationAssistantMessage={index:u,content:""}}e._conversationAssistantMessage.content+=i;var h=e.messages[e._conversationAssistantMessage.index];h&&(h.appearance||(h.appearance=e.normalizeAssistantAppearance(a)),h.rawContent=e._conversationAssistantMessage.content,h.references=r(Object.assign({},h.references||{},s||{})),l(h,h.references),e.$nextTick(function(){f(h),e.scrollToBottom()}))}),e.connection.on("ReceiveConversationAssistantComplete",function(t,n,i){if(e._conversationAssistantMessage){var o=e.messages[e._conversationAssistantMessage.index];o&&(o.isStreaming=!1,o.references=r(Object.assign({},o.references||{},i||{})),l(o,o.references)),e._conversationAssistantMessage=null}}),e.connection.on("ReceiveAudioChunk",function(t,n,i){if(n){for(var o=atob(n),s=new Uint8Array(o.length),a=0;a<o.length;a++)s[a]=o.charCodeAt(a);e.audioChunks.push(s)}}),e.connection.on("ReceiveAudioComplete",function(t){e.playCollectedAudio()}),e.connection.on("ReceiveNotification",function(t){e.receiveNotification(t)}),e.connection.on("UpdateNotification",function(t){e.updateNotification(t)}),e.connection.on("RemoveNotification",function(t){e.removeNotification(t)}),e.connection.onreconnecting(function(){console.warn("SignalR: reconnecting...")}),e.connection.onreconnected(function(){console.info("SignalR: reconnected."),e.isSessionStarted&&e.reloadCurrentSession()}),e.connection.onclose(function(t){e.isNavigatingAway||t&&console.warn("SignalR connection closed with error:",t.message||t)}),t.p=1,t.n=2,e.connection.start();case 2:t.n=4;break;case 3:t.p=3,n=t.v,console.error("SignalR Connection Error: ",n);case 4:return t.a(2)}},t,null,[[1,3]])}))()},addMessageInternal:function(e){var t=this;"assistant"===e.role&&(e.appearance=this.normalizeAssistantAppearance(e.appearance)),e.content&&!e.htmlContent&&(e.htmlContent=m(e.content,e)),this.fireEvent(new CustomEvent("addingCoreAIPromotMessage",{detail:{message:e}})),this.messages.push(e),this.$nextTick(function(){t.fireEvent(new CustomEvent("addedCoreAIPromotMessage",{detail:{message:e}}))})},addMessage:function(e){var t,n=this;(void 0===e.userRating&&(e.userRating=null),e.content)&&(e.rawContent=null!==(t=e.rawContent)&&void 0!==t?t:e.content,l(e,e.references));this.addMessageInternal(e),this.hidePlaceholder(),this.$nextTick(function(){f(e),n.scrollToBottom()})},addMessages:function(e){for(var t=this,n=0;n<e.length;n++)this.addMessageInternal(e[n]);this.hidePlaceholder(),this.$nextTick(function(){t.scrollToBottom()})},hidePlaceholder:function(){this.placeholder&&this.placeholder.classList.add("d-none"),this.isPlaceholderVisible=!1},showPlaceholder:function(){this.placeholder&&this.placeholder.classList.remove("d-none"),this.isPlaceholderVisible=!0},isOrchestratorAvailable:function(){return!1!==u.isOrchestratorAvailable},applyOrchestratorAvailability:function(){if(this.isOrchestratorAvailable())return!0;var e=u.orchestratorUnavailableMessage||"This orchestrator is not currently available.";return this.inputElement&&(this.inputElement.disabled=!0,this.inputElement.value="",this.inputElement.placeholder=e),this.buttonElement&&(this.buttonElement.disabled=!0),this.micButtonElement&&(this.micButtonElement.disabled=!0,this.micButtonElement.style.display="none"),this.conversationButtonElement&&(this.conversationButtonElement.disabled=!0,this.conversationButtonElement.style.display="none"),!1},fireEvent:function(e){document.dispatchEvent(e)},isIndicator:function(e){return"indicator"===e.role},sendMessage:function(){if(this.applyOrchestratorAvailability()){var e=this.prompt.trim();e&&(this.isRecording&&this.stopRecording(),this._audioInputSent=!0,this.singleResponseMode&&this.messages.splice(0,this.messages.length),this.addMessage({role:"user",content:e}),this.streamMessage(this.getProfileId(),e,null),this.inputElement.value="",this.prompt="")}},startRecording:function(){var e=this;!this.isRecording&&this.connection&&navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}}).then(function(t){var n=MediaRecorder.isTypeSupported("audio/ogg;codecs=opus")?"audio/ogg;codecs=opus":MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":"audio/webm";e.mediaRecorder=new MediaRecorder(t,{mimeType:n,audioBitsPerSecond:128e3}),e.preRecordingPrompt=e.prompt,e._audioInputSent=!1;var i=new signalR.Subject,o=e.getProfileId(),s=e.getSessionId()||"",a=Promise.resolve();e.mediaRecorder.addEventListener("dataavailable",function(e){e.data&&e.data.size>0&&(a=a.then(_asyncToGenerator(_regenerator().m(function t(){var n,o,s,a;return _regenerator().w(function(t){for(;;)switch(t.n){case 0:return t.n=1,e.data.arrayBuffer();case 1:n=t.v,o=new Uint8Array(n),s=o.reduce(function(e,t){return e+String.fromCharCode(t)},""),a=btoa(s),i.next(a);case 2:return t.a(2)}},t)}))))}),e.mediaRecorder.addEventListener("stop",function(){t.getTracks().forEach(function(e){return e.stop()}),a.then(function(){return i.complete()})});var r=navigator.language||document.documentElement.lang||"en-US";e.connection.send("SendAudioStream",o,s,i,n,r),e.mediaRecorder.start(250),e.isRecording=!0,e.updateMicButton()}).catch(function(e){console.error("Microphone access denied:",e)})},stopRecording:function(){this.isRecording&&this.mediaRecorder&&(this.mediaRecorder.stop(),this.isRecording=!1,this.updateMicButton())},toggleRecording:function(){this.isRecording?this.stopRecording():this.startRecording()},updateMicButton:function(){this.micButton&&(this.isRecording?(this.micButton.classList.add("stt-recording"),this.micButton.innerHTML='<i class="fa-solid fa-stop"></i>'):(this.micButton.classList.remove("stt-recording"),this.micButton.innerHTML='<i class="fa-solid fa-microphone"></i>'))},streamMessage:function(e,t,n){var i=this;this.stream&&(this.stream.dispose(),this.stream=null),this.streamingStarted(),this.showTypingIndicator(),this.autoScroll=!0;var o="",a={},r=null,c=this.messages.length,u=this.getSessionId();this.stream=this.connection.stream("SendMessage",e,t,u,n).subscribe({next:function(e){var t=i.messages[c];if(!t){e.sessionId&&!u&&i.initializeSession(e.sessionId),i.hideTypingIndicator(),c=i.messages.length;var n={id:e.messageId,role:"assistant",title:e.title,content:"",htmlContent:"",isStreaming:!0,userRating:null};i.messages.push(n),t=n}if(!e.title||t.title&&t.title===e.title||(t.title=e.title),e.references&&"object"===_typeof(e.references)&&Object.keys(e.references).length)for(var d=0,h=Object.entries(e.references);d<h.length;d++){var p,m=_slicedToArray(h[d],2),g=m[0],v=m[1];a[g]=null!==(p=s(v))&&void 0!==p?p:{}}e.content&&(e.responseId&&r&&e.responseId!==r&&(o+="\n\n"),e.responseId&&(r=e.responseId),o+=e.content),t.rawContent=o,l(t,a),i.messages[c]=t,i.$nextTick(function(){f(t),i.scrollToBottom()})},complete:function(){var e;i.processReferences(a,c),i.streamingFinished();var t=i.messages[c];t&&(t.isStreaming=!1),t&&t.content||i.hideTypingIndicator(),i.isConversationMode&&i.textToSpeechEnabled&&t&&t.content&&i.synthesizeSpeech(t.content),null===(e=i.stream)||void 0===e||e.dispose(),i.stream=null},error:function(e){var t;i.processReferences(a,c),i.streamingFinished();var n=i.messages[c];n&&(n.isStreaming=!1),i.hideTypingIndicator(),i.isNavigatingAway||i.addMessage(i.getServiceDownMessage()),null===(t=i.stream)||void 0===t||t.dispose(),i.stream=null,console.error("Stream error:",e)}})},getServiceDownMessage:function(){return{role:"assistant",content:"Our service is currently unavailable. Please try again later. We apologize for the inconvenience.",htmlContent:""}},processReferences:function(e,t){var n=this;if(e=r(e),Object.keys(e).length){var i,o,s=this.messages[t];s.rawContent=null!==(i=null!==(o=s.rawContent)&&void 0!==o?o:s.content)&&void 0!==i?i:"",l(s,e),this.messages[t]=s,this.$nextTick(function(){f(s),n.scrollToBottom()})}},streamingStarted:function(){var e=this.buttonElement.getAttribute("data-stop-icon");e&&this.buttonElement.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0})),this.inputElement&&this.inputElement.setAttribute("disabled","disabled")},streamingFinished:function(){var e=this.buttonElement.getAttribute("data-start-icon");if(e&&this.buttonElement.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0})),this.inputElement&&(this.inputElement.removeAttribute("disabled"),this.inputElement.focus()),this.chatContainer)for(var t=this.chatContainer.querySelectorAll(".ai-streaming-icon"),n=0;n<t.length;n++)t[n].classList.remove("ai-streaming-icon"),t[n].classList.add("ai-bot-icon");for(n=0;n<this.messages.length;n++)this.messages[n].isStreaming&&(this.messages[n].isStreaming=!1)},handleExternalTtsStop:function(e){var t;(null==e||null===(t=e.detail)||void 0===t?void 0:t.sourceId)!==this.ttsInstanceId&&this.stopAudio(!1)},updateTtsPlaybackButtons:function(){var e=this;this.chatContainer&&this.chatContainer.querySelectorAll("[data-tts-message-index]").forEach(function(t){var n=Number(t.getAttribute("data-tts-message-index"))===e.ttsPlayingMessageIndex;t.classList.toggle("tts-playing",n),t.setAttribute("title",n?"Pause audio":"Read aloud")})},updateCopyButtons:function(){var e=this;this.chatContainer&&this.chatContainer.querySelectorAll("[data-copy-message-index]").forEach(function(t){var n=Number(t.getAttribute("data-copy-message-index"))===e.copiedMessageIndex,i=n?'<i class="fa-solid fa-check"></i>':'<i class="fa-solid fa-copy"></i>';t.classList.toggle("text-success",n),t.classList.toggle("text-secondary",!n),t.setAttribute("title",n?e.copiedTitle:e.copyTitle),t.replaceChildren(DOMPurify.sanitize(i,{RETURN_DOM_FRAGMENT:!0}))})},setCopyButtonState:function(e,t){if(e){var n=t?'<i class="fa-solid fa-check"></i>':'<i class="fa-solid fa-copy"></i>';e.classList.toggle("text-success",t),e.classList.toggle("text-secondary",!t),e.setAttribute("title",t?this.copiedTitle:this.copyTitle),e.replaceChildren(DOMPurify.sanitize(n,{RETURN_DOM_FRAGMENT:!0}))}},synthesizeSpeech:function(e,t){var n=this;this.textToSpeechEnabled&&e&&this.connection&&(this.audioChunks=[],this.isPlayingAudio=!0,this._ttsCacheIndex=void 0!==t?t:-1,this.connection.invoke("SynthesizeSpeech",this.getProfileId(),this.getSessionId(),e,this.ttsVoiceName).catch(function(e){console.error("TTS synthesis error:",e),n.isPlayingAudio=!1,n.ttsPlayingMessageIndex=-1,n._ttsCacheIndex=-1,n.$nextTick(function(){return n.updateTtsPlaybackButtons()})}))},toggleMessageTts:function(e,t){var n=this;this.ttsPlayingMessageIndex!==t?(this.stopAudio(!1),window.dispatchEvent(new CustomEvent("crestapps-ai-chat-stop-tts",{detail:{sourceId:this.ttsInstanceId}})),this.ttsPlayingMessageIndex=t,this.$nextTick(function(){return n.updateTtsPlaybackButtons()}),this.ttsAudioCache[t]?this.playAudioBlob(this.ttsAudioCache[t]):this.synthesizeSpeech(e.content,t)):this.stopAudio()},playCollectedAudio:function(){var e=this;if(0!==this.audioChunks.length){var t,n=this.audioChunks.reduce(function(e,t){return e+t.length},0),i=new Uint8Array(n),o=0,s=_createForOfIteratorHelper(this.audioChunks);try{for(s.s();!(t=s.n()).done;){var a=t.value;i.set(a,o),o+=a.length}}catch(e){s.e(e)}finally{s.f()}this.audioChunks=[];var r=new Blob([i],{type:"audio/mp3"});this._ttsCacheIndex>=0&&(this.ttsAudioCache[this._ttsCacheIndex]=r,this._ttsCacheIndex=-1),this.currentAudioElement?this.audioPlayQueue.push(r):this.playAudioBlob(r)}else this.currentAudioElement||0!==this.audioPlayQueue.length||(this.isPlayingAudio=!1,this.ttsPlayingMessageIndex=-1,this.$nextTick(function(){return e.updateTtsPlaybackButtons()}))},playAudioBlob:function(e){var t=this,n=URL.createObjectURL(e),i=new Audio(n);this.currentAudioUrl=n,this.currentAudioElement=i,this.isPlayingAudio=!0,i.addEventListener("ended",function(){t.currentAudioElement=null,t.currentAudioUrl=null,URL.revokeObjectURL(n),t.playNextInQueue()}),i.addEventListener("error",function(){t.currentAudioElement=null,t.currentAudioUrl=null,URL.revokeObjectURL(n),t.playNextInQueue()}),i.play().catch(function(e){console.error("Audio playback error:",e),t.currentAudioElement=null,t.currentAudioUrl=null,URL.revokeObjectURL(n),t.audioPlayQueue=[],t.isPlayingAudio=!1,t.ttsPlayingMessageIndex=-1,t.$nextTick(function(){return t.updateTtsPlaybackButtons()})})},playNextInQueue:function(){var e=this;if(this.audioPlayQueue.length>0){var t=this.audioPlayQueue.shift();this.playAudioBlob(t)}else this.isPlayingAudio=!1,this.ttsPlayingMessageIndex=-1,this.$nextTick(function(){return e.updateTtsPlaybackButtons()}),this.conversationModeOnAudioEnded()},stopAudio:function(){var e=this;this.currentAudioElement&&(this.currentAudioElement.pause(),this.currentAudioElement.currentTime=0,this.currentAudioElement=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.audioChunks=[],this.audioPlayQueue=[],this.isPlayingAudio=!1,this.ttsPlayingMessageIndex=-1,this.$nextTick(function(){return e.updateTtsPlaybackButtons()})},toggleConversationMode:function(){this.isConversationMode?this.stopConversationMode():this.startConversationMode()},startConversationMode:function(){var e=this;this.conversationModeEnabled&&!this.isConversationMode&&this.connection&&(this.isConversationMode=!0,this.updateConversationButton(),this._conversationPartialTranscript="",this._conversationAssistantMessage=null,this._conversationPartialMessage=null,this.removeNotification("conversation-ended"),navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}}).then(function(t){var n=MediaRecorder.isTypeSupported("audio/ogg;codecs=opus")?"audio/ogg;codecs=opus":MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":"audio/webm";e.mediaRecorder=new MediaRecorder(t,{mimeType:n,audioBitsPerSecond:128e3}),e._conversationSubject=new signalR.Subject,e._conversationStream=t;var i=window.AudioContext||window.webkitAudioContext;i&&(e._conversationAudioCtx=new i,e._conversationAnalyser=e._conversationAudioCtx.createAnalyser(),e._conversationAnalyser.fftSize=256,e._conversationAudioCtx.createMediaStreamSource(t).connect(e._conversationAnalyser));var o=Promise.resolve(),s=e._conversationAnalyser;e.mediaRecorder.addEventListener("dataavailable",function(t){if(t.data&&t.data.size>0){if(e.isPlayingAudio&&s){var n=new Uint8Array(s.frequencyBinCount);s.getByteFrequencyData(n);for(var i=0,a=0;a<n.length;a++)i+=n[a];i/n.length>=30&&e.stopAudio()}o=o.then(_asyncToGenerator(_regenerator().m(function n(){var i,o,s,a;return _regenerator().w(function(n){for(;;)switch(n.n){case 0:return n.n=1,t.data.arrayBuffer();case 1:i=n.v,o=new Uint8Array(i),s=o.reduce(function(e,t){return e+String.fromCharCode(t)},""),a=btoa(s);try{e._conversationSubject.next(a)}catch(e){}case 2:return n.a(2)}},n)})))}}),e.mediaRecorder.addEventListener("stop",function(){t.getTracks().forEach(function(e){return e.stop()}),o.then(function(){try{e._conversationSubject.complete()}catch(e){}})});var a=e.getProfileId(),r=e.getSessionId()||"",c=navigator.language||document.documentElement.lang||"en-US";e.connection.send("StartConversation",a,r,e._conversationSubject,n,c),e.mediaRecorder.start(250),e.isRecording=!0}).catch(function(t){console.error("Microphone access denied:",t),e.isConversationMode=!1,e.updateConversationButton()}))},stopConversationMode:function(){if(this.isConversationMode){if(this.isConversationMode=!1,this.updateConversationButton(),this.connection&&this.connection.invoke("StopConversation").catch(function(){}),this.isRecording&&this.mediaRecorder&&(this.mediaRecorder.stop(),this.isRecording=!1),this.stopAudio(),this._conversationPartialTranscript="",this._conversationPartialMessage=null,this._conversationAudioCtx&&(this._conversationAudioCtx.close().catch(function(){}),this._conversationAudioCtx=null,this._conversationAnalyser=null),this._conversationAssistantMessage){var e=this.messages[this._conversationAssistantMessage.index];e&&(e.isStreaming=!1),this._conversationAssistantMessage=null}for(var t=0;t<this.messages.length;t++)this.messages[t].isStreaming&&(this.messages[t].isStreaming=!1);this.receiveNotification({type:"conversation-ended",content:"Conversation ended.",icon:"fa-solid fa-circle-check",dismissible:!0,autoDismissMs:5e3})}},updateConversationButton:function(){if(this.conversationButton)if(this.isConversationMode){this.conversationButton.classList.add("active","btn-primary"),this.conversationButton.classList.remove("btn-dark","btn-outline-dark","btn-outline-secondary"),this.conversationButton.title=this.conversationButton.getAttribute("data-end-title")||"End Conversation";var e=this.conversationButton.getAttribute("data-end-html");e&&this.conversationButton.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0}))}else{this.conversationButton.classList.remove("active","btn-primary"),this.conversationButton.classList.remove("btn-dark","btn-outline-secondary"),this.conversationButton.classList.add("btn-outline-dark"),this.conversationButton.blur(),this.conversationButton.title=this.conversationButton.getAttribute("data-start-title")||"Start Conversation";var t=this.conversationButton.getAttribute("data-start-html");t&&this.conversationButton.replaceChildren(DOMPurify.sanitize(t,{RETURN_DOM_FRAGMENT:!0}))}},conversationModeSendPrompt:function(){},conversationModeOnAudioEnded:function(){},generatePrompt:function(e){if(e){var t=e.getAttribute("data-profile-id"),n=this.getSessionId(),i=this.getProfileId();t&&n?this.streamMessage(t,null,i):console.error("The given element is missing data-profile-id or the session has not yet started.")}else console.error("The element paramter is required.")},createSessionUrl:function(e,t,n){var i=e.toLowerCase().startsWith("http")?e:window.location.origin+e,o=new URL(i);return o.searchParams.set(t,n),o.toString()},showTypingIndicator:function(){this.addMessage({role:"indicator",htmlContent:u.indicatorTemplate})},hideTypingIndicator:function(){var e=this.messages.length;return this.messages=this.messages.filter(function(e){return"indicator"!==e.role}),e-this.messages.length},receiveNotification:function(e){var t=this;if(e&&e.type){this.clearNotificationDismiss(e.type);var n=this.notifications.findIndex(function(t){return t.type===e.type});n>=0?this.notifications.splice(n,1,e):this.notifications.push(e),this.scheduleNotificationDismiss(e),this.$nextTick(function(){t.scrollToBottom()})}},updateNotification:function(e){if(e&&e.type){this.clearNotificationDismiss(e.type);var t=this.notifications.findIndex(function(t){return t.type===e.type});t>=0&&(this.notifications.splice(t,1,e),this.scheduleNotificationDismiss(e))}},scheduleNotificationDismiss:function(e){var t=this;e&&e.type&&e.autoDismissMs&&!(e.autoDismissMs<=0)&&(this.notificationDismissTimers[e.type]=setTimeout(function(){t.removeNotification(e.type)},e.autoDismissMs))},clearNotificationDismiss:function(e){var t=this.notificationDismissTimers[e];t&&(clearTimeout(t),delete this.notificationDismissTimers[e])},removeNotification:function(e){this.clearNotificationDismiss(e),this.notifications=this.notifications.filter(function(t){return t.type!==e})},dismissNotification:function(e){this.removeNotification(e)},handleNotificationAction:function(e,t){if(this.connection){var n=this.getSessionId();this.connection.invoke("HandleNotificationAction",n,e,t).catch(function(e){console.error("Error handling notification action:",e)})}},scrollToBottom:function(){var e=this;this.autoScroll&&setTimeout(function(){e.chatContainer.scrollTop=e.chatContainer.scrollHeight-e.chatContainer.clientHeight},50)},handleUserInput:function(e){this.prompt=e.target.value},getProfileId:function(){return this.inputElement?this.inputElement.getAttribute("data-profile-id"):null},setSessionId:function(e){this.inputElement&&this.inputElement.setAttribute("data-session-id",e||"")},resetSession:function(){this.stopRecording(),this.rejectPendingSessionRequest("Session was reset."),this.setSessionId(""),this.isSessionStarted=!1,this.sessionRating=null,this.messages=[],this.documents=[],u.initialPrompt?this.addMessage({role:"assistant",content:u.initialPrompt}):this.showPlaceholder(),h&&"function"==typeof h.onSessionReset&&h.onSessionReset(this,u)},startNewSession:function(){if(this.applyOrchestratorAvailability()){var e=this.getProfileId();e&&this.connection&&this.requestNewSession(e).catch(function(e){return console.error(e)})}},ensureSessionForDocuments:function(e){var t=this;return _asyncToGenerator(_regenerator().m(function n(){var i;return _regenerator().w(function(n){for(;;)switch(n.n){case 0:if(!(i=t.getSessionId())){n.n=1;break}return n.a(2,i);case 1:if(e&&t.connection){n.n=2;break}return n.a(2,null);case 2:return n.n=3,t.requestNewSession(e);case 3:return n.a(2,n.v)}},n)}))()},requestNewSession:function(e){var t=this;return this.pendingSessionPromise?this.pendingSessionPromise:e&&this.connection?(this.pendingSessionPromise=new Promise(function(e,n){t.pendingSessionResolver=e,t.pendingSessionRejector=n,t.pendingSessionTimeoutId=window.setTimeout(function(){t.rejectPendingSessionRequest("Timed out while creating a chat session.")},15e3)}),this.connection.invoke("StartSession",e,null).catch(function(e){t.rejectPendingSessionRequest(e)}),this.pendingSessionPromise):Promise.resolve(null)},resolvePendingSessionRequest:function(e){this.pendingSessionResolver&&this.pendingSessionResolver(e),this.clearPendingSessionRequest()},rejectPendingSessionRequest:function(e){this.pendingSessionRejector&&this.pendingSessionRejector(e),this.clearPendingSessionRequest()},clearPendingSessionRequest:function(){this.pendingSessionTimeoutId&&window.clearTimeout(this.pendingSessionTimeoutId),this.pendingSessionPromise=null,this.pendingSessionResolver=null,this.pendingSessionRejector=null,this.pendingSessionTimeoutId=null},initializeApp:function(){var e=this;if(this.inputElement=document.querySelector(u.inputElementSelector),this.buttonElement=document.querySelector(u.sendButtonElementSelector),this.chatContainer=document.querySelector(u.chatContainerElementSelector),this.placeholder=document.querySelector(u.placeholderElementSelector),!(this.inputElement&&this.buttonElement&&this.chatContainer&&this.placeholder))return console.error("AI chat app could not initialize because one or more required elements were not found.",{inputElementSelector:u.inputElementSelector,sendButtonElementSelector:u.sendButtonElementSelector,chatContainerElementSelector:u.chatContainerElementSelector,placeholderElementSelector:u.placeholderElementSelector}),!1;this.applyOrchestratorAvailability();var t=this.getSessionId();if(!d&&t&&this.loadSession(t),u.sessionDocumentsEnabled&&u.documentBarSelector&&(this.documentBar=document.querySelector(u.documentBarSelector),this.documentBar)){this.renderDocumentBar();var n=document.createElement("input");n.type="file",n.id="ai-chat-doc-input",n.className="d-none",n.multiple=!0,u.allowedExtensions&&(n.accept=u.allowedExtensions),n.addEventListener("change",function(t){return e.handleFileInputChange(t)}),this.documentBar.parentElement.appendChild(n);var i=this.inputElement?this.inputElement.closest(".ai-admin-widget-input, .text-bg-light"):null;i&&(i.addEventListener("dragover",function(t){return e.handleDragOver(t)}),i.addEventListener("dragleave",function(t){return e.handleDragLeave(t)}),i.addEventListener("drop",function(t){return e.handleDrop(t)}))}this.chatContainer.addEventListener("scroll",function(){if(e.stream){var t=e.chatContainer.scrollHeight-e.chatContainer.clientHeight-e.chatContainer.scrollTop<=30;e.autoScroll=t}}),this.inputElement.addEventListener("keydown",function(t){null==e.stream&&("Enter"!==t.key||t.shiftKey||(t.preventDefault(),e.buttonElement.click()))}),this.inputElement.addEventListener("input",function(t){e.handleUserInput(t),t.target.value.trim()?e.buttonElement.removeAttribute("disabled"):e.buttonElement.setAttribute("disabled",!0)}),this.buttonElement.addEventListener("click",function(){if(null==e.stream)e.sendMessage();else if(e.stream.dispose(),e.stream=null,e.streamingFinished(),e.hideTypingIndicator(),e.messages.length>0){var t=e.messages[e.messages.length-1];"assistant"!==t.role||t.content?t.isStreaming&&(t.isStreaming=!1):e.messages.pop()}});for(var o=document.getElementsByClassName("profile-generated-prompt"),s=0;s<o.length;s++)o[s].addEventListener("click",function(t){t.preventDefault(),e.generatePrompt(t.target)});var a=document.getElementsByClassName("chat-session-history-item");for(s=0;s<a.length;s++)a[s].addEventListener("click",function(t){t.preventDefault();var n=t.target.getAttribute("data-session-id");n?(e.loadSession(n),e.showChatScreen()):console.error("an element with the class chat-session-history-item with no data-session-id set.")});for(var r=Array.isArray(u.messages)?u.messages:[],c=0;c<r.length;c++)this.addMessage(r[c]);return 0===this.messages.length&&u.initialPrompt&&this.addMessage({role:"assistant",content:u.initialPrompt}),this.$nextTick(function(){e.refreshAllFeedbackIcons()}),this.chatContainer&&this.chatContainer.addEventListener("click",function(e){var t=e.target.closest(".ai-code-copy-btn");if(t){var n=t.closest(".ai-code-block")||t.closest("pre");if(n){var i=n.querySelector("code");if(i){navigator.clipboard.writeText(i.textContent);var o=u.codeCopiedText||"Copied!";t.innerHTML='<i class="fa-solid fa-check"></i> '+o,setTimeout(function(){t.innerHTML='<i class="fa-regular fa-copy"></i>'},2e3)}}}}),this.speechToTextEnabled&&u.micButtonElementSelector&&(this.micButton=document.querySelector(u.micButtonElementSelector),this.micButton&&(this.micButton.style.display="",this.micButton.addEventListener("click",function(){e.toggleRecording()}))),this.conversationModeEnabled&&u.conversationButtonElementSelector&&(this.conversationButton=document.querySelector(u.conversationButtonElementSelector),this.conversationButton&&this.conversationButton.addEventListener("click",function(){e.toggleConversationMode()})),!0},loadSession:function(e){this.connection.invoke("LoadSession",e).catch(function(e){return console.error(e)})},reloadCurrentSession:function(){var e=this.getSessionId();e&&this.loadSession(e)},initializeSession:function(e,t){if(!this.isSessionStarted||t){if(this.fireEvent(new CustomEvent("initializingSessionCoreAIChat",{detail:{sessionId:e}})),this.setSessionId(e),this.isSessionStarted=!0,this.resolvePendingSessionRequest(e),h&&"function"==typeof h.onSessionInitialized&&h.onSessionInitialized(this,e,u),!d&&e&&u.sessionUrlTemplate&&"undefined"!=typeof history&&history.replaceState){var n=u.sessionUrlTemplate.replace("{sessionId}",encodeURIComponent(e));history.replaceState(null,"",n)}}else e&&this.getSessionId()===e&&this.resolvePendingSessionRequest(e)},getSessionId:function(){var e=this.inputElement?this.inputElement.getAttribute("data-session-id"):null;return!e&&h&&"function"==typeof h.resolveSessionId&&(e=h.resolveSessionId(this,u)),e},clearCopiedMessageState:function(){this.copyResetTimeoutId&&(window.clearTimeout(this.copyResetTimeoutId),this.copyResetTimeoutId=null),this.activeCopyButton&&(this.setCopyButtonState(this.activeCopyButton,!1),this.activeCopyButton=null),this.copiedMessageIndex=-1},copyResponse:function(e,t,n){var i,o,s,a,r=this,c=e&&"object"===_typeof(e)?null!==(i=null!==(o=e.copyContent)&&void 0!==o?o:e.content)&&void 0!==i?i:"":null!=e?e:"",l=(null==n?void 0:n.currentTarget)||(null==n||null===(s=n.target)||void 0===s||null===(a=s.closest)||void 0===a?void 0:a.call(s,"[data-copy-message-index]"))||null;navigator.clipboard.writeText(c).then(function(){r.clearCopiedMessageState(),r.copiedMessageIndex="number"==typeof t?t:-1,r.activeCopyButton=l,l?r.setCopyButtonState(l,!0):r.$nextTick(function(){return r.updateCopyButtons()}),r.copyResetTimeoutId=window.setTimeout(function(){r.clearCopiedMessageState(),r.$nextTick(function(){return r.updateCopyButtons()})},Number(u.copyResetDelayMs)||2e3)}).catch(function(e){return console.error("Failed to copy response:",e)})},updateFeedbackIcons:function(e,t){if(e){var n=e.querySelector(".rate-up-btn"),i=e.querySelector(".rate-down-btn");if(n){var o=!0===t?"fa-solid fa-thumbs-up":"fa-regular fa-thumbs-up",s=document.createElement("span");s.className=o,s.style.fontSize="0.9rem",n.textContent="",n.appendChild(s)}if(i){var a=!1===t?"fa-solid fa-thumbs-down":"fa-regular fa-thumbs-down",r=document.createElement("span");r.className=a,r.style.fontSize="0.9rem",i.textContent="",i.appendChild(r)}}},refreshAllFeedbackIcons:function(){for(var e=this.$el.querySelectorAll(".ai-chat-message-assistant-feedback"),t=0;t<e.length;t++){var n=e[t].getAttribute("data-message-id"),i=this.messages.find(function(e){return e.id===n});i&&this.updateFeedbackIcons(e[t],i.userRating)}},rateMessage:function(e,t,n){var i=this.getSessionId();if(i&&e.id&&this.connection){var o=e.userRating===t?null:t;e.userRating=o;var s=this.$el.querySelector('.ai-chat-message-assistant-feedback[data-message-id="'+e.id+'"]');this.updateFeedbackIcons(s,o),null!==o&&s&&setTimeout(function(){var e=t?".rate-up-btn":".rate-down-btn",n=s.querySelector(e);n&&(n.classList.remove("spark-effect"),n.offsetWidth,n.classList.add("spark-effect"),n.addEventListener("animationend",function e(){n.removeEventListener("animationend",e),n.classList.remove("spark-effect")}))},50),this.connection.invoke("RateMessage",i,e.id,t).catch(function(e){console.error("Failed to rate message:",e)})}}},watch:{documents:{handler:function(){this.renderDocumentBar(),h&&"function"==typeof h.onDocumentsChanged&&h.onDocumentsChanged(this,this.documents,u)},deep:!0},isUploading:function(){this.renderDocumentBar()},isDocumentOperationPending:function(){this.renderDocumentBar()},isPlayingAudio:function(){},copiedMessageIndex:function(){var e=this;this.$nextTick(function(){return e.updateCopyButtons()})},isConversationMode:function(e){this.micButton&&(this.micButton.style.display=e?"none":this.speechToTextEnabled?"":"none"),this.buttonElement&&(this.buttonElement.style.display=e?"none":""),this.inputElement&&(this.inputElement.disabled=e,e&&(this.inputElement.placeholder=""))}},mounted:function(){var e=this;_asyncToGenerator(_regenerator().m(function t(){return _regenerator().w(function(t){for(;;)switch(t.n){case 0:return t.n=1,e.startConnection();case 1:e.initializeApp()&&d&&h&&"function"==typeof h.onMounted&&h.onMounted(e,u),e.$nextTick(function(){e.updateCopyButtons(),i(e.$el),e.fontAwesomeObserver=o(e.$el)});case 2:return t.a(2)}},t)}))(),window.addEventListener("beforeunload",this.handleBeforeUnload),window.addEventListener("crestapps-ai-chat-stop-tts",this.handleExternalTtsStop)},beforeUnmount:function(){window.removeEventListener("beforeunload",this.handleBeforeUnload),window.removeEventListener("crestapps-ai-chat-stop-tts",this.handleExternalTtsStop),this.fontAwesomeObserver&&(this.fontAwesomeObserver.disconnect(),this.fontAwesomeObserver=null),this.clearCopiedMessageState(),this.stopAudio(!1),this.stream&&(this.stream.dispose(),this.stream=null),this.connection&&this.connection.stop(),h&&"function"==typeof h.onBeforeUnmount&&h.onBeforeUnmount(this,u)},template:u.messageTemplate},v=Vue.createApp(p).mount(u.appElementSelector);return h&&"function"==typeof h.attach&&h.attach(v,u),v}console.error("The sendButtonElementSelector is required.")}else console.error("The inputElementSelector is required.");else console.error("The chatContainerElementSelector is required.");else console.error("The appElementSelector is required.");else console.error("The signalRHubUrl is required.")},y="[data-coreai-chat-config],[data-coreai-chat-app-element-selector]";function b(e,t){var n=e.getAttribute(t);return null===n||""===n?null:n}function S(e,t,n){var i=b(e,t);if(!i)return null;try{return JSON.parse(i)}catch(e){return console.error("Failed to parse "+n+" JSON.",e),null}}function A(e,t){var n,i,o=t||{};if(e.hasAttribute("data-coreai-chat-widget-container-selector")&&!0!==o.allowWidgetHost)return null;var s=b(e,"data-coreai-chat-app-element-selector");if(!s)return null;var a={signalRHubUrl:b(e,"data-coreai-chat-signalr-hub-url"),appElementSelector:s,chatContainerElementSelector:b(e,"data-coreai-chat-container-element-selector"),inputElementSelector:b(e,"data-coreai-chat-input-element-selector"),sendButtonElementSelector:b(e,"data-coreai-chat-send-button-element-selector"),placeholderElementSelector:b(e,"data-coreai-chat-placeholder-element-selector"),messages:null!==(n=S(e,"data-coreai-chat-messages","CoreAI chat messages"))&&void 0!==n?n:void 0,chatMode:b(e,"data-coreai-chat-mode"),micButtonElementSelector:b(e,"data-coreai-chat-mic-button-element-selector"),conversationButtonElementSelector:b(e,"data-coreai-chat-conversation-button-element-selector"),ttsVoiceName:b(e,"data-coreai-chat-tts-voice-name"),documentBarSelector:b(e,"data-coreai-chat-document-bar-selector"),uploadDocumentUrl:b(e,"data-coreai-chat-upload-document-url"),removeDocumentUrl:b(e,"data-coreai-chat-remove-document-url"),allowedExtensions:b(e,"data-coreai-chat-allowed-extensions"),supportedExtensionsText:b(e,"data-coreai-chat-supported-extensions-text"),existingDocuments:null!==(i=S(e,"data-coreai-chat-existing-documents","CoreAI chat existing documents"))&&void 0!==i?i:void 0,initialPrompt:b(e,"data-coreai-chat-initial-prompt"),sessionUrlTemplate:b(e,"data-coreai-chat-session-url-template"),userLabel:b(e,"data-coreai-chat-user-label"),assistantLabel:b(e,"data-coreai-chat-assistant-label"),copyTitle:b(e,"data-coreai-chat-copy-title"),copiedTitle:b(e,"data-coreai-chat-copied-title")},r={metricsEnabled:"data-coreai-chat-metrics-enabled",textToSpeechEnabled:"data-coreai-chat-text-to-speech-enabled",sessionDocumentsEnabled:"data-coreai-chat-session-documents-enabled",singleResponseMode:"data-coreai-chat-single-response-mode"};return Object.keys(r).forEach(function(t){var n=function(e){if(null==e)return null;if("boolean"==typeof e)return e;var t=String(e).trim().toLowerCase();return"true"===t||"false"!==t&&null}(b(e,r[t]));null!==n&&(a[t]=n)}),g(a)}function E(e,t){var n=S(e,"data-coreai-chat-config","CoreAI chat config"),i=A(e,t);return n||i?Object.assign({},n||{},i||{}):null}function T(e){if(!e||"true"===e.dataset.coreAiChatInitialized)return e&&e.__coreAIChatApp||null;var t=E(e);if(!t)return null;var n=v(t);return n?(e.dataset.coreAiChatInitialized="true",e.__coreAIChatApp=n,n):null}function C(e){e&&"function"==typeof e.querySelectorAll&&("function"==typeof e.matches&&e.matches(y)&&T(e),e.querySelectorAll(y).forEach(T))}function w(){(C(document),"undefined"!=typeof MutationObserver)&&new MutationObserver(function(e){e.forEach(function(e){e.addedNodes.forEach(function(e){e&&1===e.nodeType&&C(e)})})}).observe(document.body,{childList:!0,subtree:!0})}return"loading"===document.readyState?document.addEventListener("DOMContentLoaded",w,{once:!0}):w(),{initialize:v,initializeFromElement:T,buildConfigFromElement:E}}(),document.addEventListener("click",function(e){var t=e.target.closest(".download-chart-btn");if(t){var n=t.getAttribute("data-chart-id"),i=n?document.getElementById(n):null;if(i){var o=document.createElement("a");o.download="chart-"+n+".png",o.href=i.toDataURL("image/png"),o.click()}else console.error("Chart canvas not found:",n)}}),document.addEventListener("click",function(e){var t=e.target.closest(".ai-download-image");if(t){var n=t.closest(".generated-image-container"),i=null==n?void 0:n.querySelector("img");if(i){var o=i.src;o&&o.startsWith("data:")&&(e.preventDefault(),fetch(o).then(function(e){return e.blob()}).then(function(e){var n=URL.createObjectURL(e),i=document.createElement("a");i.href=n,i.download=t.getAttribute("download")||"generated-image.png",document.body.appendChild(i),i.click(),document.body.removeChild(i),setTimeout(function(){URL.revokeObjectURL(n)},100)}).catch(function(e){console.error("Failed to download image:",e)}))}}});
|
|
1
|
+
var _excluded=["placeholder"];function _regenerator(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */var e,t,n="function"==typeof Symbol?Symbol:{},i=n.iterator||"@@iterator",o=n.toStringTag||"@@toStringTag";function s(n,i,o,s){var c=i&&i.prototype instanceof r?i:r,l=Object.create(c.prototype);return _regeneratorDefine2(l,"_invoke",function(n,i,o){var s,r,c,l=0,u=o||[],d=!1,h={p:0,n:0,v:e,a:f,f:f.bind(e,4),d:function(t,n){return s=t,r=0,c=e,h.n=n,a}};function f(n,i){for(r=n,c=i,t=0;!d&&l&&!o&&t<u.length;t++){var o,s=u[t],f=h.p,p=s[2];n>3?(o=p===i)&&(c=s[(r=s[4])?5:(r=3,3)],s[4]=s[5]=e):s[0]<=f&&((o=n<2&&f<s[1])?(r=0,h.v=i,h.n=s[1]):f<p&&(o=n<3||s[0]>i||i>p)&&(s[4]=n,s[5]=i,h.n=p,r=0))}if(o||n>1)return a;throw d=!0,i}return function(o,u,p){if(l>1)throw TypeError("Generator is already running");for(d&&1===u&&f(u,p),r=u,c=p;(t=r<2?e:c)||!d;){s||(r?r<3?(r>1&&(h.n=-1),f(r,c)):h.n=c:h.v=c);try{if(l=2,s){if(r||(o="next"),t=s[o]){if(!(t=t.call(s,c)))throw TypeError("iterator result is not an object");if(!t.done)return t;c=t.value,r<2&&(r=0)}else 1===r&&(t=s.return)&&t.call(s),r<2&&(c=TypeError("The iterator does not provide a '"+o+"' method"),r=1);s=e}else if((t=(d=h.n<0)?c:n.call(i,h))!==a)break}catch(t){s=e,r=1,c=t}finally{l=1}}return{value:t,done:d}}}(n,o,s),!0),l}var a={};function r(){}function c(){}function l(){}t=Object.getPrototypeOf;var u=[][i]?t(t([][i]())):(_regeneratorDefine2(t={},i,function(){return this}),t),d=l.prototype=r.prototype=Object.create(u);function h(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,l):(e.__proto__=l,_regeneratorDefine2(e,o,"GeneratorFunction")),e.prototype=Object.create(d),e}return c.prototype=l,_regeneratorDefine2(d,"constructor",l),_regeneratorDefine2(l,"constructor",c),c.displayName="GeneratorFunction",_regeneratorDefine2(l,o,"GeneratorFunction"),_regeneratorDefine2(d),_regeneratorDefine2(d,o,"Generator"),_regeneratorDefine2(d,i,function(){return this}),_regeneratorDefine2(d,"toString",function(){return"[object Generator]"}),(_regenerator=function(){return{w:s,m:h}})()}function _regeneratorDefine2(e,t,n,i){var o=Object.defineProperty;try{o({},"",{})}catch(e){o=0}_regeneratorDefine2=function(e,t,n,i){function s(t,n){_regeneratorDefine2(e,t,function(e){return this._invoke(t,n,e)})}t?o?o(e,t,{value:n,enumerable:!i,configurable:!i,writable:!i}):e[t]=n:(s("next",0),s("throw",1),s("return",2))},_regeneratorDefine2(e,t,n,i)}function asyncGeneratorStep(e,t,n,i,o,s,a){try{var r=e[s](a),c=r.value}catch(e){return void n(e)}r.done?t(c):Promise.resolve(c).then(i,o)}function _asyncToGenerator(e){return function(){var t=this,n=arguments;return new Promise(function(i,o){var s=e.apply(t,n);function a(e){asyncGeneratorStep(s,i,o,a,r,"next",e)}function r(e){asyncGeneratorStep(s,i,o,a,r,"throw",e)}a(void 0)})}}function _toConsumableArray(e){return _arrayWithoutHoles(e)||_iterableToArray(e)||_unsupportedIterableToArray(e)||_nonIterableSpread()}function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _iterableToArray(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}function _arrayWithoutHoles(e){if(Array.isArray(e))return _arrayLikeToArray(e)}function _objectWithoutProperties(e,t){if(null==e)return{};var n,i,o=_objectWithoutPropertiesLoose(e,t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);for(i=0;i<s.length;i++)n=s[i],-1===t.indexOf(n)&&{}.propertyIsEnumerable.call(e,n)&&(o[n]=e[n])}return o}function _objectWithoutPropertiesLoose(e,t){if(null==e)return{};var n={};for(var i in e)if({}.hasOwnProperty.call(e,i)){if(-1!==t.indexOf(i))continue;n[i]=e[i]}return n}function _createForOfIteratorHelper(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=_unsupportedIterableToArray(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var i=0,o=function(){};return{s:o,n:function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}},e:function(e){throw e},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var s,a=!0,r=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return a=e.done,e},e:function(e){r=!0,s=e},f:function(){try{a||null==n.return||n.return()}finally{if(r)throw s}}}}function _slicedToArray(e,t){return _arrayWithHoles(e)||_iterableToArrayLimit(e,t)||_unsupportedIterableToArray(e,t)||_nonIterableRest()}function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray(e,t):void 0}}function _arrayLikeToArray(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n<t;n++)i[n]=e[n];return i}function _iterableToArrayLimit(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var i,o,s,a,r=[],c=!0,l=!1;try{if(s=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;c=!1}else for(;!(c=(i=s.call(n)).done)&&(r.push(i.value),r.length!==t);c=!0);}catch(e){l=!0,o=e}finally{try{if(!c&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(l)throw o}}return r}}function _arrayWithHoles(e){if(Array.isArray(e))return e}function _typeof(e){return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof(e)}window.coreAIChatManager=function(){var e={generatedImageAltText:"Generated Image",generatedImageMaxWidth:400,downloadImageTitle:"Download image",downloadChartTitle:"Download chart as image",downloadChartButtonText:"Download",userLabel:"You",assistantLabel:"Assistant",thumbsUpTitle:"Thumbs up",thumbsDownTitle:"Thumbs down",copyTitle:"Click here to copy response to clipboard.",copiedTitle:"Response copied to clipboard.",codeCopiedText:"Copied!",copyResetDelayMs:2e3,widget:{chatWidgetContainer:null,chatWidgetStateName:null,chatHistorySection:null,showHistoryButton:null,closeHistoryButton:null,newChatButton:null,toggleButtonSelector:null,resetSizeButtonSelector:null,dragHandleSelector:".ai-chat-widget-header",enableDragging:!0,enableResizing:!0,persistLayout:!0,defaultWidth:null,defaultHeight:null,minWidth:320,minHeight:420},messageTemplate:'\n <div class="ai-chat-messages">\n <div v-for="(message, index) in messages" :key="\'msg-\' + index" class="ai-chat-message-item">\n <div>\n <div v-if="message.role === \'user\'" class="ai-chat-message-heading ai-chat-message-heading-user">\n <span class="ai-chat-msg-role ai-chat-msg-role-user">{{ userLabel }}</span>\n </div>\n <div v-else-if="message.role !== \'indicator\'" class="ai-chat-message-heading ai-chat-message-heading-assistant">\n <div :class="getAssistantRoleClasses(message)">\n <span :class="getAssistantIconClasses(message, index)"><i :class="getAssistantIcon(message)"></i></span>\n <span class="ai-chat-message-role-label">{{ getAssistantLabel(message) }}</span>\n </div>\n </div>\n <div class="ai-chat-message-body lh-base">\n <h4 v-if="message.title">{{ message.title }}</h4>\n <div v-html="message.htmlContent"></div>\n <ol v-if="message.citationReferences && message.citationReferences.length" class="ai-chat-citation-list">\n <li v-for="citation in message.citationReferences" :key="\'citation-\' + (citation.referenceKey || citation.displayIndex)" class="ai-chat-citation-item">\n <a v-if="citation.link" :href="citation.link" :target="citation.isDownload ? null : \'_blank\'" :rel="citation.isDownload ? null : \'noopener noreferrer\'">{{ citation.label }}</a>\n <span v-else>{{ citation.label }}</span>\n </li>\n </ol>\n <span class="message-buttons-container" v-if="!isIndicator(message)">\n <template v-if="metricsEnabled && message.role === \'assistant\'">\n <span class="ai-chat-message-assistant-feedback" :data-message-id="message.id">\n <button type="button" class="btn btn-sm btn-link text-success p-0 me-2 button-message-toolbox rate-up-btn" @click="rateMessage(message, true, $event)" :title="thumbsUpTitle">\n <i class="fa-regular fa-thumbs-up"></i>\n </button>\n <button type="button" class="btn btn-sm btn-link text-danger p-0 me-2 button-message-toolbox rate-down-btn" @click="rateMessage(message, false, $event)" :title="thumbsDownTitle">\n <i class="fa-regular fa-thumbs-down"></i>\n </button>\n </span>\n </template>\n <button type="button" v-if="textToSpeechEnabled && !isConversationMode && message.role === \'assistant\' && !message.isStreaming" class="btn btn-sm btn-link text-secondary p-0 me-1 button-message-toolbox" :class="{ \'tts-playing\': ttsPlayingMessageIndex === index }" :data-tts-message-index="index" @click="toggleMessageTts(message, index)" :title="ttsPlayingMessageIndex === index ? \'Pause audio\' : \'Read aloud\'">\n <span :class="ttsPlayingMessageIndex === index ? \'fa-solid fa-circle-pause\' : \'fa-solid fa-circle-play\'"></span>\n </button>\n <button type="button" class="btn btn-sm btn-link p-0 button-message-toolbox ai-response-copy-btn" :class="copiedMessageIndex === index ? \'text-success\' : \'text-secondary\'" :data-copy-message-index="index" @click="copyResponse(message, index, $event)" :title="copiedMessageIndex === index ? copiedTitle : copyTitle">\n <i :class="copiedMessageIndex === index ? \'fa-solid fa-check\' : \'fa-solid fa-copy\'"></i>\n </button>\n </span>\n </div>\n </div>\n </div>\n <div v-for="notification in notifications" :key="\'notif-\' + notification.type" class="ai-chat-notification" :class="\'ai-chat-notification-\' + (notification.type || \'info\') + \' \' + (notification.cssClass || \'\')">\n <div class="ai-chat-notification-content">\n <i v-if="notification.icon" :class="notification.icon" class="ai-chat-notification-icon"></i>\n <span class="ai-chat-notification-text">{{ notification.content }}</span>\n <button type="button" v-if="notification.dismissible" class="btn btn-sm btn-link p-0 ms-2 ai-chat-notification-dismiss" @click="dismissNotification(notification.type)" title="Dismiss">\n <i class="fa-solid fa-xmark"></i>\n </button>\n </div>\n <div v-if="notification.actions && notification.actions.length" class="ai-chat-notification-actions">\n <button type="button" v-for="action in notification.actions" :key="action.name" class="btn btn-sm" :class="action.cssClass || \'btn-outline-secondary\'" @click="handleNotificationAction(notification.type, action.name)">\n <i v-if="action.icon" :class="action.icon" class="me-1"></i>\n {{ action.label }}\n </button>\n </div>\n </div>\n </div>\n ',indicatorTemplate:'\n <div class="ai-chat-message-heading ai-chat-message-heading-assistant">\n <div class="ai-chat-msg-role ai-chat-msg-role-assistant">\n <span class="ai-streaming-icon"><i class="fa fa-robot" style="display: inline-block;"></i></span>\n <span class="ai-chat-message-role-label">Assistant</span>\n </div>\n </div>\n '};function t(e){if(!e)return"";var t=e.trim();return/^javascript:/i.test(t)||/^vbscript:/i.test(t)||/^data:text\/html/i.test(t)?"":e}function n(e){var t=document.createElement("span");return t.textContent=e,t.innerHTML}function i(e){var t=window.FontAwesome;(function(e){if(!e||1!==e.nodeType)return!1;var t='i[class*="fa-"],i.fa,i.fas,i.far,i.fab';return!("function"!=typeof e.matches||!e.matches(t))||"function"==typeof e.querySelector&&!!e.querySelector(t)})(e)&&t&&t.dom&&"function"==typeof t.dom.i2svg&&t.dom.i2svg({node:e})}function o(e){if(!e||"undefined"==typeof MutationObserver)return null;var t=new MutationObserver(function(e){e.forEach(function(e){e.addedNodes.forEach(function(e){i(e)})})});return t.observe(e,{childList:!0,subtree:!0}),t}function s(e){var n,i,o,s,a,r,c,l,u,d,h;if(!e||"object"!==_typeof(e))return null;var f=Object.assign({},e);return f.index=null!==(n=null!==(i=f.index)&&void 0!==i?i:f.Index)&&void 0!==n?n:0,f.text=null!==(o=null!==(s=f.text)&&void 0!==s?s:f.Text)&&void 0!==o?o:null,f.title=null!==(a=null!==(r=f.title)&&void 0!==r?r:f.Title)&&void 0!==a?a:null,f.link=t(null!==(c=null!==(l=f.link)&&void 0!==l?l:f.Link)&&void 0!==c?c:null),f.referenceType=null!==(u=null!==(d=f.referenceType)&&void 0!==d?d:f.ReferenceType)&&void 0!==u?u:null,f.isGenerated=!0===(null!==(h=f.isGenerated)&&void 0!==h?h:f.IsGenerated),f}function a(e){return!(!e||"object"!==_typeof(e))&&("string"==typeof e.referenceType&&"document"===e.referenceType.toLowerCase()||!("string"!=typeof e.link||!/\/ai\/documents\/.+\/download(?:$|\?)/i.test(e.link)))}function r(e){if(!e||"object"!==_typeof(e))return{};for(var t={},n=0,i=Object.entries(e);n<i.length;n++){var o,a=_slicedToArray(i[n],2),r=a[0],c=a[1];t[r]=null!==(o=s(c))&&void 0!==o?o:{}}return t}function c(e,t){return e.title||e.text||t}function l(e,t){var n=r(null!=t?t:e.references),i="string"==typeof e.rawContent?e.rawContent:"string"==typeof e.content?e.content:"",o=function(e,t){var n=(e||"").trim(),i=r(t),o=Object.entries(i);if(!o.length)return{content:n,citations:[]};var s=o.filter(function(e){var t=_slicedToArray(e,1)[0];return n.includes(t)}),l=o.filter(function(e){var t=_slicedToArray(e,2),i=t[0];return t[1].isGenerated&&!n.includes(i)});if(!s.length&&!l.length)return{content:n,citations:[]};s.sort(function(e,t){var n=_slicedToArray(e,2)[1],i=_slicedToArray(t,2)[1];return n.index-i.index}),l.sort(function(e,t){var n=_slicedToArray(e,2)[1],i=_slicedToArray(t,2)[1];return n.index-i.index});var u,d=[],h=1,f=_createForOfIteratorHelper(s);try{for(f.s();!(u=f.n()).done;){var p=_slicedToArray(u.value,2),m=p[0],g=p[1],v="__CITE_".concat(h,"_").concat(g.index||h,"__");n=n.replaceAll(m,v),d.push({referenceKey:m,displayIndex:h,label:c(g,m),link:g.link||null,isDownload:a(g),placeholder:v}),h++}}catch(e){f.e(e)}finally{f.f()}for(var y=0,b=d;y<b.length;y++){var S=b[y];n=n.replaceAll(S.placeholder,"<sup>".concat(S.displayIndex,"</sup>"))}n=n.replaceAll("</sup><sup>","</sup><sup>,</sup><sup>");var A,E=_createForOfIteratorHelper(l);try{for(E.s();!(A=E.n()).done;){var T=_slicedToArray(A.value,2),C=T[0],w=T[1];d.push({referenceKey:C,displayIndex:h,label:c(w,C),link:w.link||null,isDownload:!0,placeholder:null}),h++}}catch(e){E.e(e)}finally{E.f()}return{content:n,citations:d.map(function(e){return e.placeholder,_objectWithoutProperties(e,_excluded)})}}(i,n);return e.rawContent=i,e.content=i,e.displayContent=o.content,e.references=n,e.citationReferences=o.citations,e.copyContent=function(e,t){var n=(e||"").trim();if(!n||!Array.isArray(t)||0===t.length)return n;var i,o=_createForOfIteratorHelper(t);try{for(o.s();!(i=o.n()).done;){var s=i.value;n=n.replaceAll(s.referenceKey,"[".concat(s.displayIndex,"]"))}}catch(e){o.e(e)}finally{o.f()}n+="\n\nReferences:\n";var a,r=_createForOfIteratorHelper(t);try{for(r.s();!(a=r.n()).done;){var c=a.value;n+="".concat(c.displayIndex,". ").concat(c.label),c.link&&(n+=" - ".concat(c.link)),n+="\n"}}catch(e){r.e(e)}finally{r.f()}return n.trimEnd()}(i,o.citations),e.htmlContent=m(o.content,e),e}var u=new marked.Renderer;u.link=function(e){var n=t(e.href);return n?'<a href="'.concat(n,'" target="_blank" rel="noopener noreferrer">').concat(e.text,"</a>"):e.text||""},u.code=function(e){var t=e.text||"",i=(e.lang||"").trim(),o=t;if("undefined"!=typeof hljs)if(i&&hljs.getLanguage(i))try{o=hljs.highlight(t,{language:i}).value}catch(e){}else try{o=hljs.highlightAuto(t).value}catch(e){}else o=n(t);var s=i?n(i):"code";return'<div class="ai-code-block"><div class="ai-code-header"><span class="ai-code-lang"><i class="fa-solid fa-code"></i> '.concat(s,'</span><button type="button" class="ai-code-copy-btn" title="Copy code"><i class="fa-regular fa-copy"></i></button></div><pre><code class="hljs').concat(i?" language-"+i:"",'">').concat(o,"</code></pre></div>")},u.image=function(n){var i=t(n.href);if(!i)return"";var o=n.text||e.generatedImageAltText,s=e.generatedImageMaxWidth;return'<div class="generated-image-container">\n <img src="'.concat(i,'" alt="').concat(o,'" class="img-thumbnail" style="max-width: ').concat(s,'px; height: auto;" />\n <div class="mt-2">\n <a href="').concat(i,'" target="_blank" download="').concat(o,'" title="').concat(e.downloadImageTitle,'" class="btn btn-sm btn-outline-secondary ai-download-image">\n <i class="fa-solid fa-download"></i>\n </a>\n </div>\n </div>')};var d=0,h=[];function f(e){if(e&&e._pendingCharts&&e._pendingCharts.length){var t=_toConsumableArray(e._pendingCharts);e._pendingCharts=[],requestAnimationFrame(function(){var e,n=_createForOfIteratorHelper(t);try{for(n.s();!(e=n.n()).done;){var i=e.value;p(i.chartId,i.config)}}catch(e){n.e(e)}finally{n.f()}})}}function p(e,t){var n=document.getElementById(e);if(!n)return!1;if("undefined"==typeof Chart)return console.warn('Chart.js is not loaded. To render interactive charts, include the Chart.js library on the page (e.g., <script src="https://cdn.jsdelivr.net/npm/chart.js@4/dist/chart.umd.min.js"><\/script>).'),!1;if(null===n.offsetParent)return window.__chartConfigs[e]=t,!1;try{var i,o,s;n._chartInstance&&n._chartInstance.destroy();var a="string"==typeof t?JSON.parse(t):t;return null!==(i=a.options)&&void 0!==i||(a.options={}),a.options.responsive=!0,a.options.maintainAspectRatio=!0,null!==(s=(o=a.options).aspectRatio)&&void 0!==s||(o.aspectRatio=4/3),n._chartInstance=new Chart(n,a),delete window.__chartConfigs[e],!0}catch(e){return console.error("Error creating chart:",e),!1}}function m(e,t){h=[];var n=marked.parse(e,{renderer:u});return t._pendingCharts=h.length>0?_toConsumableArray(h):[],DOMPurify.sanitize(n,{ADD_TAGS:["canvas"],ADD_ATTR:["target"]})}function g(e){return e&&"object"===_typeof(e)?Object.fromEntries(Object.entries(e).filter(function(e){return void 0!==_slicedToArray(e,2)[1]})):{}}window.__chartConfigs=window.__chartConfigs||{},marked.use({extensions:[{name:"chart",level:"block",start:function(e){var t=e.indexOf("[chart:");return t>=0?t:void 0},tokenizer:function(e){var t=function(e){var t="[chart:",n=e.indexOf(t);if(n<0)return null;var i=n+t.length,o=i;for(;o<e.length&&(" "===e[o]||"\n"===e[o]||"\r"===e[o]||"\t"===e[o]);)o++;if(o>=e.length||"{"!==e[o])return null;for(var s=0,a=!1,r=!1;o<e.length;o++){var c=e[o];if(a){if(r){r=!1;continue}if("\\"===c){r=!0;continue}'"'===c&&(a=!1)}else if('"'!==c){if("{"===c)s++;else if("}"===c&&0===--s){var l=o,u=e.indexOf("]",l+1);return u<0?null:{startIndex:n,endIndex:u+1,json:e.substring(i,l+1).trim()}}}else a=!0}return null}(e);if(t&&0===t.startIndex){var n="chat_chart_".concat(++d);return{type:"chart",raw:e.substring(0,t.endIndex),chartId:n,json:t.json}}},renderer:function(t){return h.push({chartId:t.chartId,config:t.json}),window.__chartConfigs[t.chartId]=t.json,n=t.chartId,'<div class="chart-container" style="position: relative; width: 100%; max-width: 560px; min-height: 420px;">'+'<canvas id="'.concat(n,'"></canvas>')+'</div><div class="mt-2">'+'<button type="button" class="btn btn-sm btn-outline-secondary download-chart-btn" data-chart-id="'.concat(n,'" title="').concat(e.downloadChartTitle,'">')+'<i class="fa-solid fa-download"></i> '.concat(e.downloadChartButtonText)+"</button></div>";var n}}]}),window.renderPendingCharts=function(){if("undefined"!=typeof Chart){var e=window.__chartConfigs;e&&requestAnimationFrame(function(){for(var t=0,n=Object.keys(e);t<n.length;t++){var i=n[t];p(i,e[i])}})}};var v=function(t){var a=g(t),c=g(a.widget),u=Object.assign({},e,a);u.widget=Object.assign({},e.widget||{},c),u.indicatorTemplate=function(e,t){if(!e)return e;var i=n(t||"Assistant");return e.replace(/\{\{\s*assistantLabel\s*\}\}/g,i)}(u.indicatorTemplate,u.assistantLabel);var d=!(!c.chatWidgetContainer||!c.chatWidgetStateName),h=window.coreAIChatWidgetBehavior||null;if(e=u,u.signalRHubUrl)if(u.appElementSelector)if(u.chatContainerElementSelector)if(u.inputElementSelector){if(u.sendButtonElementSelector){var p={data:function(){return{inputElement:null,buttonElement:null,chatContainer:null,placeholder:null,isSessionStarted:!1,isPlaceholderVisible:!0,isStreaming:!1,isNavigatingAway:!1,autoScroll:!0,stream:null,messages:[],notifications:[],prompt:"",documents:u.existingDocuments||[],isUploading:!1,isDocumentOperationPending:!1,documentOperationQueue:null,uploadErrors:[],isDragOver:!1,documentBar:null,metricsEnabled:!!u.metricsEnabled,userLabel:u.userLabel,assistantLabel:u.assistantLabel,thumbsUpTitle:u.thumbsUpTitle,thumbsDownTitle:u.thumbsDownTitle,copyTitle:u.copyTitle,copiedTitle:u.copiedTitle,isRecording:!1,mediaRecorder:null,preRecordingPrompt:"",micButton:null,speechToTextEnabled:"AudioInput"===u.chatMode||"Conversation"===u.chatMode,textToSpeechEnabled:"Conversation"===u.chatMode||!!u.textToSpeechEnabled,ttsVoiceName:u.ttsVoiceName||null,audioChunks:[],audioPlayQueue:[],isPlayingAudio:!1,currentAudioElement:null,currentAudioUrl:null,ttsButton:null,ttsPlayingMessageIndex:-1,ttsAudioCache:{},ttsInstanceId:"ai-chat-"+Math.random().toString(36).slice(2),singleResponseMode:!!u.singleResponseMode,conversationModeEnabled:"Conversation"===u.chatMode,conversationButton:null,isConversationMode:!1,notificationDismissTimers:{},pendingSessionPromise:null,pendingSessionResolver:null,pendingSessionRejector:null,pendingSessionTimeoutId:null,copiedMessageIndex:-1,copyResetTimeoutId:null,activeCopyButton:null}},computed:{lastAssistantIndex:function(){for(var e=this.messages.length-1;e>=0;e--)if("assistant"===this.messages[e].role)return e;return-1}},methods:{handleBeforeUnload:function(){this.isNavigatingAway=!0},handleDragOver:function(e){if(u.sessionDocumentsEnabled){e.preventDefault(),e.stopPropagation(),this.isDragOver=!0;var t=this.inputElement?this.inputElement.closest(".ai-admin-widget-input, .text-bg-light"):null;t&&t.classList.add("ai-chat-drag-over")}},handleDragLeave:function(e){if(u.sessionDocumentsEnabled){e.preventDefault(),e.stopPropagation(),this.isDragOver=!1;var t=this.inputElement?this.inputElement.closest(".ai-admin-widget-input, .text-bg-light"):null;t&&t.classList.remove("ai-chat-drag-over")}},handleDrop:function(e){if(u.sessionDocumentsEnabled){e.preventDefault(),e.stopPropagation(),this.isDragOver=!1;var t=this.inputElement?this.inputElement.closest(".ai-admin-widget-input, .text-bg-light"):null;t&&t.classList.remove("ai-chat-drag-over"),e.dataTransfer&&e.dataTransfer.files&&e.dataTransfer.files.length>0&&this.uploadFiles(Array.from(e.dataTransfer.files))}},triggerFileInput:function(){if(u.sessionDocumentsEnabled&&!this.isDocumentOperationPending){var e=document.getElementById("ai-chat-doc-input");e&&e.click()}},handleFileInputChange:function(e){var t=e.target.files?Array.from(e.target.files):[];t&&t.length>0&&this.uploadFiles(t),e.target.value=""},queueDocumentOperation:function(e){var t=this,n=(this.documentOperationQueue||Promise.resolve()).catch(function(){}).then(_asyncToGenerator(_regenerator().m(function n(){return _regenerator().w(function(n){for(;;)switch(n.p=n.n){case 0:return t.isDocumentOperationPending=!0,n.p=1,n.n=2,e();case 2:return n.a(2,n.v);case 3:return n.p=3,t.isDocumentOperationPending=!1,n.f(3);case 4:return n.a(2)}},n,null,[[1,,3,4]])})));return this.documentOperationQueue=n.finally(function(){t.documentOperationQueue===n&&(t.documentOperationQueue=null)}),this.documentOperationQueue},uploadFiles:function(e){var t=this;return _asyncToGenerator(_regenerator().m(function n(){var i;return _regenerator().w(function(n){for(;;)switch(n.n){case 0:if(u.uploadDocumentUrl){n.n=1;break}return n.a(2);case 1:if(0!==(i=Array.isArray(e)?e.slice():Array.from(e||[])).length){n.n=2;break}return n.a(2);case 2:return n.a(2,t.queueDocumentOperation(_asyncToGenerator(_regenerator().m(function e(){var n,o,s,a,r,c,l,d,h,f;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:if(n=t.getSessionId(),o=t.getProfileId(),n){e.n=4;break}return e.p=1,e.n=2,t.ensureSessionForDocuments(o);case 2:n=e.v,e.n=4;break;case 3:return e.p=3,h=e.v,console.error("Failed to create a chat session for document upload:",h),t.uploadErrors=[{fileName:"",error:"Could not create a chat session for the upload."}],t.renderDocumentBar(),e.a(2);case 4:if(n){e.n=5;break}return console.warn("Cannot upload documents without a session or profile."),t.uploadErrors=[{fileName:"",error:"Could not create a chat session for the upload."}],t.renderDocumentBar(),e.a(2);case 5:for(t.isUploading=!0,t.uploadErrors=[],t.renderDocumentBar(),e.p=6,(s=new FormData).append("sessionId",n),a=0;a<i.length;a++)s.append("files",i[a]);return e.n=7,fetch(u.uploadDocumentUrl,{method:"POST",body:s});case 7:if((r=e.v).ok){e.n=9;break}return e.n=8,r.text();case 8:return c=e.v,l=t.extractReadableErrorMessage(c,"Upload failed. Please try again."),console.error("Upload failed:",c),t.uploadErrors=[{fileName:"",error:l}],e.a(2);case 9:return e.n=10,r.json();case 10:(d=e.v).sessionId&&d.sessionId!==t.getSessionId()&&t.initializeSession(d.sessionId),Array.isArray(d.documents)?t.documents=d.documents:d.uploaded&&d.uploaded.length>0&&(t.documents=t.documents.concat(d.uploaded)),d.failed&&d.failed.length>0&&(t.uploadErrors=d.failed),e.n=12;break;case 11:e.p=11,f=e.v,console.error("Upload error:",f),t.uploadErrors=[{fileName:"",error:"Upload failed. Please try again."}],t.getSessionId()&&t.reloadCurrentSession();case 12:return e.p=12,t.isUploading=!1,t.renderDocumentBar(),e.f(12);case 13:return e.a(2)}},e,null,[[6,11,12,13],[1,3]])}))))}},n)}))()},removeDocument:function(e){var t=this;return _asyncToGenerator(_regenerator().m(function n(){return _regenerator().w(function(n){for(;;)switch(n.n){case 0:if(u.removeDocumentUrl){n.n=1;break}return n.a(2);case 1:return n.a(2,t.queueDocumentOperation(_asyncToGenerator(_regenerator().m(function n(){var i,o,s,a,r,c,l;return _regenerator().w(function(n){for(;;)switch(n.p=n.n){case 0:return n.p=0,i=t.getSessionId(),n.n=1,fetch(u.removeDocumentUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({itemId:i,documentId:e.documentId})});case 1:if(!(o=n.v).ok){n.n=3;break}return n.n=2,o.json();case 2:s=n.v,Array.isArray(s.documents)?t.documents=s.documents:(a=t.documents.indexOf(e))>-1&&t.documents.splice(a,1),n.n=5;break;case 3:return n.n=4,o.text();case 4:r=n.v,c=t.extractReadableErrorMessage(r,"Failed to remove document. Please try again."),console.error("Failed to remove document:",o.status,r),t.uploadErrors=[{fileName:e.fileName||"",error:c}],i&&t.reloadCurrentSession(),t.renderDocumentBar();case 5:n.n=7;break;case 6:n.p=6,l=n.v,console.error("Remove document error:",l),t.uploadErrors=[{fileName:e.fileName||"",error:"Failed to remove document. Please try again."}],t.getSessionId()&&t.reloadCurrentSession(),t.renderDocumentBar();case 7:return n.a(2)}},n,null,[[0,6]])}))))}},n)}))()},formatFileSize:function(e){return e<1024?e+" B":e<1048576?(e/1024).toFixed(1)+" KB":(e/1048576).toFixed(1)+" MB"},renderDocumentBar:function(){if(this.documentBar)if(u.sessionDocumentsEnabled){this.documentBar.classList.remove("d-none");var e='<div class="ai-chat-doc-bar p-2">';e+='<div class="d-flex flex-wrap align-items-center gap-1">';for(var t=0;t<this.documents.length;t++){var n=this.documents[t],i=n.fileName||"Document";i.length>20&&(i=i.substring(0,17)+"..."),e+='<span class="badge bg-secondary bg-opacity-25 text-dark d-inline-flex align-items-center gap-1 px-2 py-1" style="font-size: 0.8rem;" title="'+this.escapeHtml(n.fileName||"")+'">',e+='<i class="fa-solid fa-file-lines" style="font-size: 0.7rem;"></i> ',e+=this.escapeHtml(i),e+=' <button type="button" class="btn-close btn-close-sm ms-1" style="font-size: 0.5rem;" data-doc-index="'+t+'" aria-label="Remove"'+(this.isDocumentOperationPending?" disabled":"")+"></button>",e+="</span>"}for(var o=0;o<this.uploadErrors.length;o++){var s=this.uploadErrors[o],a=s.fileName||"File",r=s.error||"Upload failed";a.length>15&&(a=a.substring(0,12)+"..."),e+='<span class="badge bg-danger bg-opacity-25 text-danger d-inline-flex align-items-center gap-1 px-2 py-1" style="font-size: 0.8rem;" title="'+this.escapeHtml((s.fileName||"")+": "+r)+'">',e+='<i class="fa-solid fa-circle-exclamation" style="font-size: 0.7rem;"></i> ',e+=this.escapeHtml(a),e+=' <button type="button" class="btn-close btn-close-sm ms-1" style="font-size: 0.5rem;" data-error-index="'+o+'" aria-label="Dismiss"></button>',e+="</span>"}this.isUploading&&(e+='<span class="badge bg-info bg-opacity-25 text-dark d-inline-flex align-items-center gap-1 px-2 py-1" style="font-size: 0.8rem;">',e+='<span class="spinner-border spinner-border-sm" style="width: 0.7rem; height: 0.7rem;"></span> Uploading...',e+="</span>"),e+='<button type="button" class="btn btn-sm btn-outline-secondary rounded-pill ai-chat-doc-add-btn d-inline-flex align-items-center gap-1" style="font-size: 0.75rem; padding: 0.15rem 0.5rem;" title="Attach documents"'+(this.isDocumentOperationPending?" disabled":"")+">",e+='<i class="fa-solid fa-paperclip"></i>',0!==this.documents.length||this.isUploading||(e+=" <span>Attach files</span>"),e+="</button>",e+="</div>",u.supportedExtensionsText&&(e+='<div class="small text-muted mt-2">Supported formats: '+this.escapeHtml(u.supportedExtensionsText)+"</div>"),e+="</div>",this.documentBar.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0}));for(var c=this,l=this.documentBar.querySelectorAll("[data-doc-index]"),d=0;d<l.length;d++)l[d].addEventListener("click",function(e){return function(t){if(t.preventDefault(),t.stopPropagation(),!c.isDocumentOperationPending){var n=c.documents[e];n&&c.removeDocument(n)}}}(parseInt(l[d].getAttribute("data-doc-index"))));for(var h=this.documentBar.querySelectorAll("[data-error-index]"),f=0;f<h.length;f++)h[f].addEventListener("click",function(e){return function(t){t.preventDefault(),t.stopPropagation(),c.uploadErrors.splice(e,1),c.renderDocumentBar()}}(parseInt(h[f].getAttribute("data-error-index"))));var p=this.documentBar.querySelector(".ai-chat-doc-add-btn");p&&p.addEventListener("click",function(e){e.preventDefault(),c.isDocumentOperationPending||c.triggerFileInput()})}else this.documentBar.classList.add("d-none")},escapeHtml:function(e){var t=document.createElement("div");return t.textContent=e,t.innerHTML},extractReadableErrorMessage:function(e,t){if(!e||"string"!=typeof e)return t;var n=e.trim();if(!n)return t;if(n.startsWith("{")||n.startsWith("["))try{var i=JSON.parse(n),o=(null==i?void 0:i.error)||(null==i?void 0:i.message)||(null==i?void 0:i.title)||(null==i?void 0:i.detail);return"string"==typeof o&&o.trim()?o.trim():t}catch(e){return t}return/<[^>]+>/.test(n)?t:n},normalizeAssistantAppearance:function(e){if(!e)return null;var t="string"==typeof e.label?e.label.trim():"",n="string"==typeof e.icon?e.icon.trim():"",i="string"==typeof e.cssClass?e.cssClass.trim():"",o=!!e.disableStreamingAnimation;return t||n||i||o?{label:t,icon:n,cssClass:i,disableStreamingAnimation:o}:null},getAssistantLabel:function(e){var t=e?this.normalizeAssistantAppearance(e.appearance):null;return t&&t.label?t.label:this.assistantLabel},getAssistantRoleClasses:function(e){var t=e?this.normalizeAssistantAppearance(e.appearance):null,n=["ai-chat-msg-role"];return t&&t.cssClass?n.push(t.cssClass):n.push("ai-chat-msg-role-assistant"),n},getAssistantIconClasses:function(e,t){var n=e?this.normalizeAssistantAppearance(e.appearance):null;return[this.shouldAnimateAssistantIcon(e,t)?"ai-streaming-icon":"ai-bot-icon",n&&n.cssClass?n.cssClass:""]},getAssistantIcon:function(e){var t=e?this.normalizeAssistantAppearance(e.appearance):null;return t&&t.icon?t.icon:"fa fa-robot"},shouldAnimateAssistantIcon:function(e,t){var n=e?this.normalizeAssistantAppearance(e.appearance):null;return!!e&&e.isStreaming&&t===this.lastAssistantIndex&&!(n&&n.disableStreamingAnimation)},startConnection:function(){var e=this;return _asyncToGenerator(_regenerator().m(function t(){var n;return _regenerator().w(function(t){for(;;)switch(t.p=t.n){case 0:return e.connection=(new signalR.HubConnectionBuilder).withUrl(u.signalRHubUrl).withAutomaticReconnect().build(),e.connection.serverTimeoutInMilliseconds=6e5,e.connection.keepAliveIntervalInMilliseconds=15e3,e.connection.on("LoadSession",function(t){var n;e.initializeSession(t.sessionId,!0),e.messages=[],e.documents=t.documents||[],e.uploadErrors=[],(null!==(n=t.messages)&&void 0!==n?n:[]).forEach(function(t){e.addMessage(t),e.$nextTick(function(){f(t)})}),e.$nextTick(function(){e.refreshAllFeedbackIcons()}),0===e.messages.length&&u.initialPrompt&&e.addMessage({role:"assistant",content:u.initialPrompt})}),e.connection.on("ReceiveError",function(t){console.error("SignalR Error: ",t),e.isRecording&&e.stopRecording(),e.rejectPendingSessionRequest(t),e.hideTypingIndicator(),h&&"function"==typeof h.handleReceiveError?h.handleReceiveError(e,t,u):e.isNavigatingAway||e.addMessage(e.getErrorMessage(t))}),e.connection.on("ReceiveSessionStartRejected",function(t){e.rejectPendingSessionRequest(t),e.hideTypingIndicator(),e.isNavigatingAway||e.addMessage(e.getErrorMessage(t))}),e.connection.on("MessageRated",function(t,n){var i=e.messages.find(function(e){return e.id===t});i&&(i.userRating=n)}),e.connection.on("ReceiveTranscript",function(t,n,i){if(e.isConversationMode){if(!i&&n){e._conversationPartialTranscript=n;var o='<p class="ai-partial-transcript">'+n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")+"</p>";e._conversationPartialMessage?(e._conversationPartialMessage.content=n,e._conversationPartialMessage.htmlContent=o):(e.hidePlaceholder(),e._conversationPartialMessage={role:"user",content:n,htmlContent:o,isPartial:!0},e.messages.push(e._conversationPartialMessage)),e.scrollToBottom()}}else n&&!e._audioInputSent&&(e.prompt=e.preRecordingPrompt+n,e.inputElement&&(e.inputElement.value=e.prompt,e.inputElement.dispatchEvent(new Event("input"))))}),e.connection.on("ReceiveConversationUserMessage",function(t,n){if(n){if(e.stopAudio(),e._conversationAssistantMessage){var i=e.messages[e._conversationAssistantMessage.index];i&&(i.isStreaming=!1),e._conversationAssistantMessage=null}if(e._conversationPartialMessage){var o=n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">");e._conversationPartialMessage.content=n,e._conversationPartialMessage.htmlContent="<p>"+o+"</p>",e._conversationPartialMessage.isPartial=!1,e._conversationPartialMessage=null}else e.addMessage({role:"user",content:n});e.scrollToBottom()}}),e.connection.on("ReceiveConversationAssistantToken",function(t,n,i,o,s,a){if(!e._conversationAssistantMessage){e.stopAudio(),e.hideTypingIndicator();for(var c=0;c<e.messages.length;c++)e.messages[c].isStreaming&&(e.messages[c].isStreaming=!1);var u=e.messages.length,d={id:n,role:"assistant",content:"",htmlContent:"",isStreaming:!0,userRating:null,appearance:e.normalizeAssistantAppearance(a),references:{}};e.messages.push(d),e._conversationAssistantMessage={index:u,content:""}}e._conversationAssistantMessage.content+=i;var h=e.messages[e._conversationAssistantMessage.index];h&&(h.appearance||(h.appearance=e.normalizeAssistantAppearance(a)),h.rawContent=e._conversationAssistantMessage.content,h.references=r(Object.assign({},h.references||{},s||{})),l(h,h.references),e.$nextTick(function(){f(h),e.scrollToBottom()}))}),e.connection.on("ReceiveConversationAssistantComplete",function(t,n,i){if(e._conversationAssistantMessage){var o=e.messages[e._conversationAssistantMessage.index];o&&(o.isStreaming=!1,o.references=r(Object.assign({},o.references||{},i||{})),l(o,o.references)),e._conversationAssistantMessage=null}}),e.connection.on("ReceiveAudioChunk",function(t,n,i){if(n){for(var o=atob(n),s=new Uint8Array(o.length),a=0;a<o.length;a++)s[a]=o.charCodeAt(a);e.audioChunks.push(s)}}),e.connection.on("ReceiveAudioComplete",function(t){e.playCollectedAudio()}),e.connection.on("ReceiveNotification",function(t){e.receiveNotification(t)}),e.connection.on("UpdateNotification",function(t){e.updateNotification(t)}),e.connection.on("RemoveNotification",function(t){e.removeNotification(t)}),e.connection.onreconnecting(function(){console.warn("SignalR: reconnecting...")}),e.connection.onreconnected(function(){console.info("SignalR: reconnected."),e.isSessionStarted&&e.reloadCurrentSession()}),e.connection.onclose(function(t){e.isNavigatingAway||t&&console.warn("SignalR connection closed with error:",t.message||t)}),t.p=1,t.n=2,e.connection.start();case 2:t.n=4;break;case 3:t.p=3,n=t.v,console.error("SignalR Connection Error: ",n);case 4:return t.a(2)}},t,null,[[1,3]])}))()},addMessageInternal:function(e){var t=this;"assistant"===e.role&&(e.appearance=this.normalizeAssistantAppearance(e.appearance)),e.content&&!e.htmlContent&&(e.htmlContent=m(e.content,e)),this.fireEvent(new CustomEvent("addingCoreAIPromotMessage",{detail:{message:e}})),this.messages.push(e),this.$nextTick(function(){t.fireEvent(new CustomEvent("addedCoreAIPromotMessage",{detail:{message:e}}))})},addMessage:function(e){var t,n=this;(void 0===e.userRating&&(e.userRating=null),e.content)&&(e.rawContent=null!==(t=e.rawContent)&&void 0!==t?t:e.content,l(e,e.references));this.addMessageInternal(e),this.hidePlaceholder(),this.$nextTick(function(){f(e),n.scrollToBottom()})},addMessages:function(e){for(var t=this,n=0;n<e.length;n++)this.addMessageInternal(e[n]);this.hidePlaceholder(),this.$nextTick(function(){t.scrollToBottom()})},hidePlaceholder:function(){this.placeholder&&this.placeholder.classList.add("d-none"),this.isPlaceholderVisible=!1},showPlaceholder:function(){this.placeholder&&this.placeholder.classList.remove("d-none"),this.isPlaceholderVisible=!0},isOrchestratorAvailable:function(){return!1!==u.isOrchestratorAvailable},applyOrchestratorAvailability:function(){if(this.isOrchestratorAvailable())return!0;var e=u.orchestratorUnavailableMessage||"This orchestrator is not currently available.";return this.inputElement&&(this.inputElement.disabled=!0,this.inputElement.value="",this.inputElement.placeholder=e),this.buttonElement&&(this.buttonElement.disabled=!0),this.micButtonElement&&(this.micButtonElement.disabled=!0,this.micButtonElement.style.display="none"),this.conversationButtonElement&&(this.conversationButtonElement.disabled=!0,this.conversationButtonElement.style.display="none"),!1},fireEvent:function(e){document.dispatchEvent(e)},isIndicator:function(e){return"indicator"===e.role},sendMessage:function(){if(this.applyOrchestratorAvailability()){var e=this.prompt.trim();e&&(this.isRecording&&this.stopRecording(),this._audioInputSent=!0,this.singleResponseMode&&this.messages.splice(0,this.messages.length),this.addMessage({role:"user",content:e}),this.streamMessage(this.getProfileId(),e,null),this.inputElement.value="",this.prompt="")}},startRecording:function(){var e=this;!this.isRecording&&this.connection&&navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}}).then(function(t){var n=MediaRecorder.isTypeSupported("audio/ogg;codecs=opus")?"audio/ogg;codecs=opus":MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":"audio/webm";e.mediaRecorder=new MediaRecorder(t,{mimeType:n,audioBitsPerSecond:128e3}),e.preRecordingPrompt=e.prompt,e._audioInputSent=!1;var i=new signalR.Subject,o=e.getProfileId(),s=e.getSessionId()||"",a=Promise.resolve();e.mediaRecorder.addEventListener("dataavailable",function(e){e.data&&e.data.size>0&&(a=a.then(_asyncToGenerator(_regenerator().m(function t(){var n,o,s,a;return _regenerator().w(function(t){for(;;)switch(t.n){case 0:return t.n=1,e.data.arrayBuffer();case 1:n=t.v,o=new Uint8Array(n),s=o.reduce(function(e,t){return e+String.fromCharCode(t)},""),a=btoa(s),i.next(a);case 2:return t.a(2)}},t)}))))}),e.mediaRecorder.addEventListener("stop",function(){t.getTracks().forEach(function(e){return e.stop()}),a.then(function(){return i.complete()})});var r=navigator.language||document.documentElement.lang||"en-US";e.connection.send("SendAudioStream",o,s,i,n,r),e.mediaRecorder.start(250),e.isRecording=!0,e.updateMicButton()}).catch(function(e){console.error("Microphone access denied:",e)})},stopRecording:function(){this.isRecording&&this.mediaRecorder&&(this.mediaRecorder.stop(),this.isRecording=!1,this.updateMicButton())},toggleRecording:function(){this.isRecording?this.stopRecording():this.startRecording()},updateMicButton:function(){this.micButton&&(this.isRecording?(this.micButton.classList.add("stt-recording"),this.micButton.innerHTML='<i class="fa-solid fa-stop"></i>'):(this.micButton.classList.remove("stt-recording"),this.micButton.innerHTML='<i class="fa-solid fa-microphone"></i>'))},streamMessage:function(e,t,n){var i=this;this.stream&&(this.stream.dispose(),this.stream=null),this.streamingStarted(),this.showTypingIndicator(),this.autoScroll=!0;var o="",a={},r=null,c=this.messages.length,u=this.getSessionId();this.stream=this.connection.stream("SendMessage",e,t,u,n).subscribe({next:function(e){var t=i.messages[c];if(!t){e.sessionId&&!u&&i.initializeSession(e.sessionId),i.hideTypingIndicator(),c=i.messages.length;var n={id:e.messageId,role:"assistant",title:e.title,content:"",htmlContent:"",isStreaming:!0,userRating:null};i.messages.push(n),t=n}if(!e.title||t.title&&t.title===e.title||(t.title=e.title),e.references&&"object"===_typeof(e.references)&&Object.keys(e.references).length)for(var d=0,h=Object.entries(e.references);d<h.length;d++){var p,m=_slicedToArray(h[d],2),g=m[0],v=m[1];a[g]=null!==(p=s(v))&&void 0!==p?p:{}}e.content&&(e.responseId&&r&&e.responseId!==r&&(o+="\n\n"),e.responseId&&(r=e.responseId),o+=e.content),t.rawContent=o,l(t,a),i.messages[c]=t,i.$nextTick(function(){f(t),i.scrollToBottom()})},complete:function(){var e;i.processReferences(a,c),i.streamingFinished();var t=i.messages[c];t&&(t.isStreaming=!1),t&&t.content||i.hideTypingIndicator(),i.isConversationMode&&i.textToSpeechEnabled&&t&&t.content&&i.synthesizeSpeech(t.content),null===(e=i.stream)||void 0===e||e.dispose(),i.stream=null},error:function(e){var t;i.processReferences(a,c),i.streamingFinished();var n=i.messages[c];n&&(n.isStreaming=!1),i.hideTypingIndicator(),i.isNavigatingAway||i.addMessage(i.getServiceDownMessage()),null===(t=i.stream)||void 0===t||t.dispose(),i.stream=null,console.error("Stream error:",e)}})},getServiceDownMessage:function(){return{role:"assistant",content:"Our service is currently unavailable. Please try again later. We apologize for the inconvenience.",htmlContent:""}},getErrorMessage:function(e){return{role:"assistant",content:"string"==typeof e&&e.trim()?e:"Something went wrong. Please try again.",htmlContent:""}},processReferences:function(e,t){var n=this;if(e=r(e),Object.keys(e).length){var i,o,s=this.messages[t];s.rawContent=null!==(i=null!==(o=s.rawContent)&&void 0!==o?o:s.content)&&void 0!==i?i:"",l(s,e),this.messages[t]=s,this.$nextTick(function(){f(s),n.scrollToBottom()})}},streamingStarted:function(){var e=this.buttonElement.getAttribute("data-stop-icon");e&&this.buttonElement.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0})),this.inputElement&&this.inputElement.setAttribute("disabled","disabled")},streamingFinished:function(){var e=this.buttonElement.getAttribute("data-start-icon");if(e&&this.buttonElement.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0})),this.inputElement&&(this.inputElement.removeAttribute("disabled"),this.inputElement.focus()),this.chatContainer)for(var t=this.chatContainer.querySelectorAll(".ai-streaming-icon"),n=0;n<t.length;n++)t[n].classList.remove("ai-streaming-icon"),t[n].classList.add("ai-bot-icon");for(n=0;n<this.messages.length;n++)this.messages[n].isStreaming&&(this.messages[n].isStreaming=!1)},handleExternalTtsStop:function(e){var t;(null==e||null===(t=e.detail)||void 0===t?void 0:t.sourceId)!==this.ttsInstanceId&&this.stopAudio(!1)},updateTtsPlaybackButtons:function(){var e=this;this.chatContainer&&this.chatContainer.querySelectorAll("[data-tts-message-index]").forEach(function(t){var n=Number(t.getAttribute("data-tts-message-index"))===e.ttsPlayingMessageIndex;t.classList.toggle("tts-playing",n),t.setAttribute("title",n?"Pause audio":"Read aloud")})},updateCopyButtons:function(){var e=this;this.chatContainer&&this.chatContainer.querySelectorAll("[data-copy-message-index]").forEach(function(t){var n=Number(t.getAttribute("data-copy-message-index"))===e.copiedMessageIndex,i=n?'<i class="fa-solid fa-check"></i>':'<i class="fa-solid fa-copy"></i>';t.classList.toggle("text-success",n),t.classList.toggle("text-secondary",!n),t.setAttribute("title",n?e.copiedTitle:e.copyTitle),t.replaceChildren(DOMPurify.sanitize(i,{RETURN_DOM_FRAGMENT:!0}))})},setCopyButtonState:function(e,t){if(e){var n=t?'<i class="fa-solid fa-check"></i>':'<i class="fa-solid fa-copy"></i>';e.classList.toggle("text-success",t),e.classList.toggle("text-secondary",!t),e.setAttribute("title",t?this.copiedTitle:this.copyTitle),e.replaceChildren(DOMPurify.sanitize(n,{RETURN_DOM_FRAGMENT:!0}))}},synthesizeSpeech:function(e,t){var n=this;this.textToSpeechEnabled&&e&&this.connection&&(this.audioChunks=[],this.isPlayingAudio=!0,this._ttsCacheIndex=void 0!==t?t:-1,this.connection.invoke("SynthesizeSpeech",this.getProfileId(),this.getSessionId(),e,this.ttsVoiceName).catch(function(e){console.error("TTS synthesis error:",e),n.isPlayingAudio=!1,n.ttsPlayingMessageIndex=-1,n._ttsCacheIndex=-1,n.$nextTick(function(){return n.updateTtsPlaybackButtons()})}))},toggleMessageTts:function(e,t){var n=this;this.ttsPlayingMessageIndex!==t?(this.stopAudio(!1),window.dispatchEvent(new CustomEvent("crestapps-ai-chat-stop-tts",{detail:{sourceId:this.ttsInstanceId}})),this.ttsPlayingMessageIndex=t,this.$nextTick(function(){return n.updateTtsPlaybackButtons()}),this.ttsAudioCache[t]?this.playAudioBlob(this.ttsAudioCache[t]):this.synthesizeSpeech(e.content,t)):this.stopAudio()},playCollectedAudio:function(){var e=this;if(0!==this.audioChunks.length){var t,n=this.audioChunks.reduce(function(e,t){return e+t.length},0),i=new Uint8Array(n),o=0,s=_createForOfIteratorHelper(this.audioChunks);try{for(s.s();!(t=s.n()).done;){var a=t.value;i.set(a,o),o+=a.length}}catch(e){s.e(e)}finally{s.f()}this.audioChunks=[];var r=new Blob([i],{type:"audio/mp3"});this._ttsCacheIndex>=0&&(this.ttsAudioCache[this._ttsCacheIndex]=r,this._ttsCacheIndex=-1),this.currentAudioElement?this.audioPlayQueue.push(r):this.playAudioBlob(r)}else this.currentAudioElement||0!==this.audioPlayQueue.length||(this.isPlayingAudio=!1,this.ttsPlayingMessageIndex=-1,this.$nextTick(function(){return e.updateTtsPlaybackButtons()}))},playAudioBlob:function(e){var t=this,n=URL.createObjectURL(e),i=new Audio(n);this.currentAudioUrl=n,this.currentAudioElement=i,this.isPlayingAudio=!0,i.addEventListener("ended",function(){t.currentAudioElement=null,t.currentAudioUrl=null,URL.revokeObjectURL(n),t.playNextInQueue()}),i.addEventListener("error",function(){t.currentAudioElement=null,t.currentAudioUrl=null,URL.revokeObjectURL(n),t.playNextInQueue()}),i.play().catch(function(e){console.error("Audio playback error:",e),t.currentAudioElement=null,t.currentAudioUrl=null,URL.revokeObjectURL(n),t.audioPlayQueue=[],t.isPlayingAudio=!1,t.ttsPlayingMessageIndex=-1,t.$nextTick(function(){return t.updateTtsPlaybackButtons()})})},playNextInQueue:function(){var e=this;if(this.audioPlayQueue.length>0){var t=this.audioPlayQueue.shift();this.playAudioBlob(t)}else this.isPlayingAudio=!1,this.ttsPlayingMessageIndex=-1,this.$nextTick(function(){return e.updateTtsPlaybackButtons()}),this.conversationModeOnAudioEnded()},stopAudio:function(){var e=this;this.currentAudioElement&&(this.currentAudioElement.pause(),this.currentAudioElement.currentTime=0,this.currentAudioElement=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.audioChunks=[],this.audioPlayQueue=[],this.isPlayingAudio=!1,this.ttsPlayingMessageIndex=-1,this.$nextTick(function(){return e.updateTtsPlaybackButtons()})},toggleConversationMode:function(){this.isConversationMode?this.stopConversationMode():this.startConversationMode()},startConversationMode:function(){var e=this;this.conversationModeEnabled&&!this.isConversationMode&&this.connection&&(this.isConversationMode=!0,this.updateConversationButton(),this._conversationPartialTranscript="",this._conversationAssistantMessage=null,this._conversationPartialMessage=null,this.removeNotification("conversation-ended"),navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}}).then(function(t){var n=MediaRecorder.isTypeSupported("audio/ogg;codecs=opus")?"audio/ogg;codecs=opus":MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":"audio/webm";e.mediaRecorder=new MediaRecorder(t,{mimeType:n,audioBitsPerSecond:128e3}),e._conversationSubject=new signalR.Subject,e._conversationStream=t;var i=window.AudioContext||window.webkitAudioContext;i&&(e._conversationAudioCtx=new i,e._conversationAnalyser=e._conversationAudioCtx.createAnalyser(),e._conversationAnalyser.fftSize=256,e._conversationAudioCtx.createMediaStreamSource(t).connect(e._conversationAnalyser));var o=Promise.resolve(),s=e._conversationAnalyser;e.mediaRecorder.addEventListener("dataavailable",function(t){if(t.data&&t.data.size>0){if(e.isPlayingAudio&&s){var n=new Uint8Array(s.frequencyBinCount);s.getByteFrequencyData(n);for(var i=0,a=0;a<n.length;a++)i+=n[a];i/n.length>=30&&e.stopAudio()}o=o.then(_asyncToGenerator(_regenerator().m(function n(){var i,o,s,a;return _regenerator().w(function(n){for(;;)switch(n.n){case 0:return n.n=1,t.data.arrayBuffer();case 1:i=n.v,o=new Uint8Array(i),s=o.reduce(function(e,t){return e+String.fromCharCode(t)},""),a=btoa(s);try{e._conversationSubject.next(a)}catch(e){}case 2:return n.a(2)}},n)})))}}),e.mediaRecorder.addEventListener("stop",function(){t.getTracks().forEach(function(e){return e.stop()}),o.then(function(){try{e._conversationSubject.complete()}catch(e){}})});var a=e.getProfileId(),r=e.getSessionId()||"",c=navigator.language||document.documentElement.lang||"en-US";e.connection.send("StartConversation",a,r,e._conversationSubject,n,c),e.mediaRecorder.start(250),e.isRecording=!0}).catch(function(t){console.error("Microphone access denied:",t),e.isConversationMode=!1,e.updateConversationButton()}))},stopConversationMode:function(){if(this.isConversationMode){if(this.isConversationMode=!1,this.updateConversationButton(),this.connection&&this.connection.invoke("StopConversation").catch(function(){}),this.isRecording&&this.mediaRecorder&&(this.mediaRecorder.stop(),this.isRecording=!1),this.stopAudio(),this._conversationPartialTranscript="",this._conversationPartialMessage=null,this._conversationAudioCtx&&(this._conversationAudioCtx.close().catch(function(){}),this._conversationAudioCtx=null,this._conversationAnalyser=null),this._conversationAssistantMessage){var e=this.messages[this._conversationAssistantMessage.index];e&&(e.isStreaming=!1),this._conversationAssistantMessage=null}for(var t=0;t<this.messages.length;t++)this.messages[t].isStreaming&&(this.messages[t].isStreaming=!1);this.receiveNotification({type:"conversation-ended",content:"Conversation ended.",icon:"fa-solid fa-circle-check",dismissible:!0,autoDismissMs:5e3})}},updateConversationButton:function(){if(this.conversationButton)if(this.isConversationMode){this.conversationButton.classList.add("active","btn-primary"),this.conversationButton.classList.remove("btn-dark","btn-outline-dark","btn-outline-secondary"),this.conversationButton.title=this.conversationButton.getAttribute("data-end-title")||"End Conversation";var e=this.conversationButton.getAttribute("data-end-html");e&&this.conversationButton.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0}))}else{this.conversationButton.classList.remove("active","btn-primary"),this.conversationButton.classList.remove("btn-dark","btn-outline-secondary"),this.conversationButton.classList.add("btn-outline-dark"),this.conversationButton.blur(),this.conversationButton.title=this.conversationButton.getAttribute("data-start-title")||"Start Conversation";var t=this.conversationButton.getAttribute("data-start-html");t&&this.conversationButton.replaceChildren(DOMPurify.sanitize(t,{RETURN_DOM_FRAGMENT:!0}))}},conversationModeSendPrompt:function(){},conversationModeOnAudioEnded:function(){},generatePrompt:function(e){if(e){var t=e.getAttribute("data-profile-id"),n=this.getSessionId(),i=this.getProfileId();t&&n?this.streamMessage(t,null,i):console.error("The given element is missing data-profile-id or the session has not yet started.")}else console.error("The element paramter is required.")},createSessionUrl:function(e,t,n){var i=e.toLowerCase().startsWith("http")?e:window.location.origin+e,o=new URL(i);return o.searchParams.set(t,n),o.toString()},showTypingIndicator:function(){this.addMessage({role:"indicator",htmlContent:u.indicatorTemplate})},hideTypingIndicator:function(){var e=this.messages.length;return this.messages=this.messages.filter(function(e){return"indicator"!==e.role}),e-this.messages.length},receiveNotification:function(e){var t=this;if(e&&e.type){this.clearNotificationDismiss(e.type);var n=this.notifications.findIndex(function(t){return t.type===e.type});n>=0?this.notifications.splice(n,1,e):this.notifications.push(e),this.scheduleNotificationDismiss(e),this.$nextTick(function(){t.scrollToBottom()})}},updateNotification:function(e){if(e&&e.type){this.clearNotificationDismiss(e.type);var t=this.notifications.findIndex(function(t){return t.type===e.type});t>=0&&(this.notifications.splice(t,1,e),this.scheduleNotificationDismiss(e))}},scheduleNotificationDismiss:function(e){var t=this;e&&e.type&&e.autoDismissMs&&!(e.autoDismissMs<=0)&&(this.notificationDismissTimers[e.type]=setTimeout(function(){t.removeNotification(e.type)},e.autoDismissMs))},clearNotificationDismiss:function(e){var t=this.notificationDismissTimers[e];t&&(clearTimeout(t),delete this.notificationDismissTimers[e])},removeNotification:function(e){this.clearNotificationDismiss(e),this.notifications=this.notifications.filter(function(t){return t.type!==e})},dismissNotification:function(e){this.removeNotification(e)},handleNotificationAction:function(e,t){if(this.connection){var n=this.getSessionId();this.connection.invoke("HandleNotificationAction",n,e,t).catch(function(e){console.error("Error handling notification action:",e)})}},scrollToBottom:function(){var e=this;this.autoScroll&&setTimeout(function(){e.chatContainer.scrollTop=e.chatContainer.scrollHeight-e.chatContainer.clientHeight},50)},handleUserInput:function(e){this.prompt=e.target.value},getProfileId:function(){return this.inputElement?this.inputElement.getAttribute("data-profile-id"):null},setSessionId:function(e){this.inputElement&&this.inputElement.setAttribute("data-session-id",e||"")},resetSession:function(){this.stopRecording(),this.rejectPendingSessionRequest("Session was reset."),this.setSessionId(""),this.isSessionStarted=!1,this.sessionRating=null,this.messages=[],this.documents=[],u.initialPrompt?this.addMessage({role:"assistant",content:u.initialPrompt}):this.showPlaceholder(),h&&"function"==typeof h.onSessionReset&&h.onSessionReset(this,u)},startNewSession:function(){if(this.applyOrchestratorAvailability()){var e=this.getProfileId();e&&this.connection&&this.requestNewSession(e).catch(function(e){return console.error(e)})}},ensureSessionForDocuments:function(e){var t=this;return _asyncToGenerator(_regenerator().m(function n(){var i;return _regenerator().w(function(n){for(;;)switch(n.n){case 0:if(!(i=t.getSessionId())){n.n=1;break}return n.a(2,i);case 1:if(e&&t.connection){n.n=2;break}return n.a(2,null);case 2:return n.n=3,t.requestNewSession(e);case 3:return n.a(2,n.v)}},n)}))()},requestNewSession:function(e){var t=this;return this.pendingSessionPromise?this.pendingSessionPromise:e&&this.connection?(this.pendingSessionPromise=new Promise(function(e,n){t.pendingSessionResolver=e,t.pendingSessionRejector=n,t.pendingSessionTimeoutId=window.setTimeout(function(){t.rejectPendingSessionRequest("Timed out while creating a chat session.")},15e3)}),this.connection.invoke("StartSession",e,null).catch(function(e){t.rejectPendingSessionRequest(e)}),this.pendingSessionPromise):Promise.resolve(null)},resolvePendingSessionRequest:function(e){this.pendingSessionResolver&&this.pendingSessionResolver(e),this.clearPendingSessionRequest()},rejectPendingSessionRequest:function(e){this.pendingSessionRejector&&this.pendingSessionRejector(e),this.clearPendingSessionRequest()},clearPendingSessionRequest:function(){this.pendingSessionTimeoutId&&window.clearTimeout(this.pendingSessionTimeoutId),this.pendingSessionPromise=null,this.pendingSessionResolver=null,this.pendingSessionRejector=null,this.pendingSessionTimeoutId=null},initializeApp:function(){var e=this;if(this.inputElement=document.querySelector(u.inputElementSelector),this.buttonElement=document.querySelector(u.sendButtonElementSelector),this.chatContainer=document.querySelector(u.chatContainerElementSelector),this.placeholder=document.querySelector(u.placeholderElementSelector),!(this.inputElement&&this.buttonElement&&this.chatContainer&&this.placeholder))return console.error("AI chat app could not initialize because one or more required elements were not found.",{inputElementSelector:u.inputElementSelector,sendButtonElementSelector:u.sendButtonElementSelector,chatContainerElementSelector:u.chatContainerElementSelector,placeholderElementSelector:u.placeholderElementSelector}),!1;this.applyOrchestratorAvailability();var t=this.getSessionId();if(!d&&t&&this.loadSession(t),u.sessionDocumentsEnabled&&u.documentBarSelector&&(this.documentBar=document.querySelector(u.documentBarSelector),this.documentBar)){this.renderDocumentBar();var n=document.createElement("input");n.type="file",n.id="ai-chat-doc-input",n.className="d-none",n.multiple=!0,u.allowedExtensions&&(n.accept=u.allowedExtensions),n.addEventListener("change",function(t){return e.handleFileInputChange(t)}),this.documentBar.parentElement.appendChild(n);var i=this.inputElement?this.inputElement.closest(".ai-admin-widget-input, .text-bg-light"):null;i&&(i.addEventListener("dragover",function(t){return e.handleDragOver(t)}),i.addEventListener("dragleave",function(t){return e.handleDragLeave(t)}),i.addEventListener("drop",function(t){return e.handleDrop(t)}))}this.chatContainer.addEventListener("scroll",function(){if(e.stream){var t=e.chatContainer.scrollHeight-e.chatContainer.clientHeight-e.chatContainer.scrollTop<=30;e.autoScroll=t}}),this.inputElement.addEventListener("keydown",function(t){null==e.stream&&("Enter"!==t.key||t.shiftKey||(t.preventDefault(),e.buttonElement.click()))}),this.inputElement.addEventListener("input",function(t){e.handleUserInput(t),t.target.value.trim()?e.buttonElement.removeAttribute("disabled"):e.buttonElement.setAttribute("disabled",!0)}),this.buttonElement.addEventListener("click",function(){if(null==e.stream)e.sendMessage();else if(e.stream.dispose(),e.stream=null,e.streamingFinished(),e.hideTypingIndicator(),e.messages.length>0){var t=e.messages[e.messages.length-1];"assistant"!==t.role||t.content?t.isStreaming&&(t.isStreaming=!1):e.messages.pop()}});for(var o=document.getElementsByClassName("profile-generated-prompt"),s=0;s<o.length;s++)o[s].addEventListener("click",function(t){t.preventDefault(),e.generatePrompt(t.target)});var a=document.getElementsByClassName("chat-session-history-item");for(s=0;s<a.length;s++)a[s].addEventListener("click",function(t){t.preventDefault();var n=t.target.getAttribute("data-session-id");n?(e.loadSession(n),e.showChatScreen()):console.error("an element with the class chat-session-history-item with no data-session-id set.")});for(var r=Array.isArray(u.messages)?u.messages:[],c=0;c<r.length;c++)this.addMessage(r[c]);return 0===this.messages.length&&u.initialPrompt&&this.addMessage({role:"assistant",content:u.initialPrompt}),this.$nextTick(function(){e.refreshAllFeedbackIcons()}),this.chatContainer&&this.chatContainer.addEventListener("click",function(e){var t=e.target.closest(".ai-code-copy-btn");if(t){var n=t.closest(".ai-code-block")||t.closest("pre");if(n){var i=n.querySelector("code");if(i){navigator.clipboard.writeText(i.textContent);var o=u.codeCopiedText||"Copied!";t.innerHTML='<i class="fa-solid fa-check"></i> '+o,setTimeout(function(){t.innerHTML='<i class="fa-regular fa-copy"></i>'},2e3)}}}}),this.speechToTextEnabled&&u.micButtonElementSelector&&(this.micButton=document.querySelector(u.micButtonElementSelector),this.micButton&&(this.micButton.style.display="",this.micButton.addEventListener("click",function(){e.toggleRecording()}))),this.conversationModeEnabled&&u.conversationButtonElementSelector&&(this.conversationButton=document.querySelector(u.conversationButtonElementSelector),this.conversationButton&&this.conversationButton.addEventListener("click",function(){e.toggleConversationMode()})),!0},loadSession:function(e){this.connection.invoke("LoadSession",e).catch(function(e){return console.error(e)})},reloadCurrentSession:function(){var e=this.getSessionId();e&&this.loadSession(e)},initializeSession:function(e,t){if(!this.isSessionStarted||t){if(this.fireEvent(new CustomEvent("initializingSessionCoreAIChat",{detail:{sessionId:e}})),this.setSessionId(e),this.isSessionStarted=!0,this.resolvePendingSessionRequest(e),h&&"function"==typeof h.onSessionInitialized&&h.onSessionInitialized(this,e,u),!d&&e&&u.sessionUrlTemplate&&"undefined"!=typeof history&&history.replaceState){var n=u.sessionUrlTemplate.replace("{sessionId}",encodeURIComponent(e));history.replaceState(null,"",n)}}else e&&this.getSessionId()===e&&this.resolvePendingSessionRequest(e)},getSessionId:function(){var e=this.inputElement?this.inputElement.getAttribute("data-session-id"):null;return!e&&h&&"function"==typeof h.resolveSessionId&&(e=h.resolveSessionId(this,u)),e},clearCopiedMessageState:function(){this.copyResetTimeoutId&&(window.clearTimeout(this.copyResetTimeoutId),this.copyResetTimeoutId=null),this.activeCopyButton&&(this.setCopyButtonState(this.activeCopyButton,!1),this.activeCopyButton=null),this.copiedMessageIndex=-1},copyResponse:function(e,t,n){var i,o,s,a,r=this,c=e&&"object"===_typeof(e)?null!==(i=null!==(o=e.copyContent)&&void 0!==o?o:e.content)&&void 0!==i?i:"":null!=e?e:"",l=(null==n?void 0:n.currentTarget)||(null==n||null===(s=n.target)||void 0===s||null===(a=s.closest)||void 0===a?void 0:a.call(s,"[data-copy-message-index]"))||null;navigator.clipboard.writeText(c).then(function(){r.clearCopiedMessageState(),r.copiedMessageIndex="number"==typeof t?t:-1,r.activeCopyButton=l,l?r.setCopyButtonState(l,!0):r.$nextTick(function(){return r.updateCopyButtons()}),r.copyResetTimeoutId=window.setTimeout(function(){r.clearCopiedMessageState(),r.$nextTick(function(){return r.updateCopyButtons()})},Number(u.copyResetDelayMs)||2e3)}).catch(function(e){return console.error("Failed to copy response:",e)})},updateFeedbackIcons:function(e,t){if(e){var n=e.querySelector(".rate-up-btn"),i=e.querySelector(".rate-down-btn");if(n){var o=!0===t?"fa-solid fa-thumbs-up":"fa-regular fa-thumbs-up",s=document.createElement("span");s.className=o,s.style.fontSize="0.9rem",n.textContent="",n.appendChild(s)}if(i){var a=!1===t?"fa-solid fa-thumbs-down":"fa-regular fa-thumbs-down",r=document.createElement("span");r.className=a,r.style.fontSize="0.9rem",i.textContent="",i.appendChild(r)}}},refreshAllFeedbackIcons:function(){for(var e=this.$el.querySelectorAll(".ai-chat-message-assistant-feedback"),t=0;t<e.length;t++){var n=e[t].getAttribute("data-message-id"),i=this.messages.find(function(e){return e.id===n});i&&this.updateFeedbackIcons(e[t],i.userRating)}},rateMessage:function(e,t,n){var i=this.getSessionId();if(i&&e.id&&this.connection){var o=e.userRating===t?null:t;e.userRating=o;var s=this.$el.querySelector('.ai-chat-message-assistant-feedback[data-message-id="'+e.id+'"]');this.updateFeedbackIcons(s,o),null!==o&&s&&setTimeout(function(){var e=t?".rate-up-btn":".rate-down-btn",n=s.querySelector(e);n&&(n.classList.remove("spark-effect"),n.offsetWidth,n.classList.add("spark-effect"),n.addEventListener("animationend",function e(){n.removeEventListener("animationend",e),n.classList.remove("spark-effect")}))},50),this.connection.invoke("RateMessage",i,e.id,t).catch(function(e){console.error("Failed to rate message:",e)})}}},watch:{documents:{handler:function(){this.renderDocumentBar(),h&&"function"==typeof h.onDocumentsChanged&&h.onDocumentsChanged(this,this.documents,u)},deep:!0},isUploading:function(){this.renderDocumentBar()},isDocumentOperationPending:function(){this.renderDocumentBar()},isPlayingAudio:function(){},copiedMessageIndex:function(){var e=this;this.$nextTick(function(){return e.updateCopyButtons()})},isConversationMode:function(e){this.micButton&&(this.micButton.style.display=e?"none":this.speechToTextEnabled?"":"none"),this.buttonElement&&(this.buttonElement.style.display=e?"none":""),this.inputElement&&(this.inputElement.disabled=e,e&&(this.inputElement.placeholder=""))}},mounted:function(){var e=this;_asyncToGenerator(_regenerator().m(function t(){return _regenerator().w(function(t){for(;;)switch(t.n){case 0:return t.n=1,e.startConnection();case 1:e.initializeApp()&&d&&h&&"function"==typeof h.onMounted&&h.onMounted(e,u),e.$nextTick(function(){e.updateCopyButtons(),i(e.$el),e.fontAwesomeObserver=o(e.$el)});case 2:return t.a(2)}},t)}))(),window.addEventListener("beforeunload",this.handleBeforeUnload),window.addEventListener("crestapps-ai-chat-stop-tts",this.handleExternalTtsStop)},beforeUnmount:function(){window.removeEventListener("beforeunload",this.handleBeforeUnload),window.removeEventListener("crestapps-ai-chat-stop-tts",this.handleExternalTtsStop),this.fontAwesomeObserver&&(this.fontAwesomeObserver.disconnect(),this.fontAwesomeObserver=null),this.clearCopiedMessageState(),this.stopAudio(!1),this.stream&&(this.stream.dispose(),this.stream=null),this.connection&&this.connection.stop(),h&&"function"==typeof h.onBeforeUnmount&&h.onBeforeUnmount(this,u)},template:u.messageTemplate},v=Vue.createApp(p).mount(u.appElementSelector);return h&&"function"==typeof h.attach&&h.attach(v,u),v}console.error("The sendButtonElementSelector is required.")}else console.error("The inputElementSelector is required.");else console.error("The chatContainerElementSelector is required.");else console.error("The appElementSelector is required.");else console.error("The signalRHubUrl is required.")},y="[data-coreai-chat-config],[data-coreai-chat-app-element-selector]";function b(e,t){var n=e.getAttribute(t);return null===n||""===n?null:n}function S(e,t,n){var i=b(e,t);if(!i)return null;try{return JSON.parse(i)}catch(e){return console.error("Failed to parse "+n+" JSON.",e),null}}function A(e,t){var n,i,o=t||{};if(e.hasAttribute("data-coreai-chat-widget-container-selector")&&!0!==o.allowWidgetHost)return null;var s=b(e,"data-coreai-chat-app-element-selector");if(!s)return null;var a={signalRHubUrl:b(e,"data-coreai-chat-signalr-hub-url"),appElementSelector:s,chatContainerElementSelector:b(e,"data-coreai-chat-container-element-selector"),inputElementSelector:b(e,"data-coreai-chat-input-element-selector"),sendButtonElementSelector:b(e,"data-coreai-chat-send-button-element-selector"),placeholderElementSelector:b(e,"data-coreai-chat-placeholder-element-selector"),messages:null!==(n=S(e,"data-coreai-chat-messages","CoreAI chat messages"))&&void 0!==n?n:void 0,chatMode:b(e,"data-coreai-chat-mode"),micButtonElementSelector:b(e,"data-coreai-chat-mic-button-element-selector"),conversationButtonElementSelector:b(e,"data-coreai-chat-conversation-button-element-selector"),ttsVoiceName:b(e,"data-coreai-chat-tts-voice-name"),documentBarSelector:b(e,"data-coreai-chat-document-bar-selector"),uploadDocumentUrl:b(e,"data-coreai-chat-upload-document-url"),removeDocumentUrl:b(e,"data-coreai-chat-remove-document-url"),allowedExtensions:b(e,"data-coreai-chat-allowed-extensions"),supportedExtensionsText:b(e,"data-coreai-chat-supported-extensions-text"),existingDocuments:null!==(i=S(e,"data-coreai-chat-existing-documents","CoreAI chat existing documents"))&&void 0!==i?i:void 0,initialPrompt:b(e,"data-coreai-chat-initial-prompt"),sessionUrlTemplate:b(e,"data-coreai-chat-session-url-template"),userLabel:b(e,"data-coreai-chat-user-label"),assistantLabel:b(e,"data-coreai-chat-assistant-label"),copyTitle:b(e,"data-coreai-chat-copy-title"),copiedTitle:b(e,"data-coreai-chat-copied-title")},r={metricsEnabled:"data-coreai-chat-metrics-enabled",textToSpeechEnabled:"data-coreai-chat-text-to-speech-enabled",sessionDocumentsEnabled:"data-coreai-chat-session-documents-enabled",singleResponseMode:"data-coreai-chat-single-response-mode"};return Object.keys(r).forEach(function(t){var n=function(e){if(null==e)return null;if("boolean"==typeof e)return e;var t=String(e).trim().toLowerCase();return"true"===t||"false"!==t&&null}(b(e,r[t]));null!==n&&(a[t]=n)}),g(a)}function E(e,t){var n=S(e,"data-coreai-chat-config","CoreAI chat config"),i=A(e,t);return n||i?Object.assign({},n||{},i||{}):null}function T(e){if(!e||"true"===e.dataset.coreAiChatInitialized)return e&&e.__coreAIChatApp||null;var t=E(e);if(!t)return null;var n=v(t);return n?(e.dataset.coreAiChatInitialized="true",e.__coreAIChatApp=n,n):null}function C(e){e&&"function"==typeof e.querySelectorAll&&("function"==typeof e.matches&&e.matches(y)&&T(e),e.querySelectorAll(y).forEach(T))}function w(){(C(document),"undefined"!=typeof MutationObserver)&&new MutationObserver(function(e){e.forEach(function(e){e.addedNodes.forEach(function(e){e&&1===e.nodeType&&C(e)})})}).observe(document.body,{childList:!0,subtree:!0})}return"loading"===document.readyState?document.addEventListener("DOMContentLoaded",w,{once:!0}):w(),{initialize:v,initializeFromElement:T,buildConfigFromElement:E}}(),document.addEventListener("click",function(e){var t=e.target.closest(".download-chart-btn");if(t){var n=t.getAttribute("data-chart-id"),i=n?document.getElementById(n):null;if(i){var o=document.createElement("a");o.download="chart-"+n+".png",o.href=i.toDataURL("image/png"),o.click()}else console.error("Chart canvas not found:",n)}}),document.addEventListener("click",function(e){var t=e.target.closest(".ai-download-image");if(t){var n=t.closest(".generated-image-container"),i=null==n?void 0:n.querySelector("img");if(i){var o=i.src;o&&o.startsWith("data:")&&(e.preventDefault(),fetch(o).then(function(e){return e.blob()}).then(function(e){var n=URL.createObjectURL(e),i=document.createElement("a");i.href=n,i.download=t.getAttribute("download")||"generated-image.png",document.body.appendChild(i),i.click(),document.body.removeChild(i),setTimeout(function(){URL.revokeObjectURL(n)},100)}).catch(function(e){console.error("Failed to download image:",e)}))}}});
|
|
2
2
|
//# sourceMappingURL=ai-chat.min.js.map
|