@crestapps/ai-chat-ui 2.0.0-preview.154 → 2.0.0-preview.162
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-widget.js +4 -1
- package/dist/ai-chat-widget.js.map +1 -1
- package/dist/ai-chat-widget.min.js +1 -1
- package/dist/ai-chat-widget.min.js.map +1 -1
- package/dist/ai-chat.js +638 -320
- 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/dist/chat-interaction.js +323 -77
- package/dist/chat-interaction.js.map +1 -1
- package/dist/chat-interaction.min.js +1 -1
- package/dist/chat-interaction.min.js.map +1 -1
- package/dist/realtime-audio.js +2236 -0
- package/dist/realtime-audio.js.map +1 -0
- package/dist/realtime-audio.min.js +2 -0
- package/dist/realtime-audio.min.js.map +1 -0
- package/package.json +5 -1
|
@@ -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",a=n.toStringTag||"@@toStringTag";function o(n,i,a,o){var c=i&&i.prototype instanceof s?i:s,l=Object.create(c.prototype);return _regeneratorDefine2(l,"_invoke",function(n,i,a){var o,s,c,l=0,u=a||[],d=!1,h={p:0,n:0,v:e,a:f,f:f.bind(e,4),d:function(t,n){return o=t,s=0,c=e,h.n=n,r}};function f(n,i){for(s=n,c=i,t=0;!d&&l&&!a&&t<u.length;t++){var a,o=u[t],f=h.p,m=o[2];n>3?(a=m===i)&&(c=o[(s=o[4])?5:(s=3,3)],o[4]=o[5]=e):o[0]<=f&&((a=n<2&&f<o[1])?(s=0,h.v=i,h.n=o[1]):f<m&&(a=n<3||o[0]>i||i>m)&&(o[4]=n,o[5]=i,h.n=m,s=0))}if(a||n>1)return r;throw d=!0,i}return function(a,u,m){if(l>1)throw TypeError("Generator is already running");for(d&&1===u&&f(u,m),s=u,c=m;(t=s<2?e:c)||!d;){o||(s?s<3?(s>1&&(h.n=-1),f(s,c)):h.n=c:h.v=c);try{if(l=2,o){if(s||(a="next"),t=o[a]){if(!(t=t.call(o,c)))throw TypeError("iterator result is not an object");if(!t.done)return t;c=t.value,s<2&&(s=0)}else 1===s&&(t=o.return)&&t.call(o),s<2&&(c=TypeError("The iterator does not provide a '"+a+"' method"),s=1);o=e}else if((t=(d=h.n<0)?c:n.call(i,h))!==r)break}catch(t){o=e,s=1,c=t}finally{l=1}}return{value:t,done:d}}}(n,a,o),!0),l}var r={};function s(){}function c(){}function l(){}t=Object.getPrototypeOf;var u=[][i]?t(t([][i]())):(_regeneratorDefine2(t={},i,function(){return this}),t),d=l.prototype=s.prototype=Object.create(u);function h(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,l):(e.__proto__=l,_regeneratorDefine2(e,a,"GeneratorFunction")),e.prototype=Object.create(d),e}return c.prototype=l,_regeneratorDefine2(d,"constructor",l),_regeneratorDefine2(l,"constructor",c),c.displayName="GeneratorFunction",_regeneratorDefine2(l,a,"GeneratorFunction"),_regeneratorDefine2(d),_regeneratorDefine2(d,a,"Generator"),_regeneratorDefine2(d,i,function(){return this}),_regeneratorDefine2(d,"toString",function(){return"[object Generator]"}),(_regenerator=function(){return{w:o,m:h}})()}function _regeneratorDefine2(e,t,n,i){var a=Object.defineProperty;try{a({},"",{})}catch(e){a=0}_regeneratorDefine2=function(e,t,n,i){function o(t,n){_regeneratorDefine2(e,t,function(e){return this._invoke(t,n,e)})}t?a?a(e,t,{value:n,enumerable:!i,configurable:!i,writable:!i}):e[t]=n:(o("next",0),o("throw",1),o("return",2))},_regeneratorDefine2(e,t,n,i)}function asyncGeneratorStep(e,t,n,i,a,o,r){try{var s=e[o](r),c=s.value}catch(e){return void n(e)}s.done?t(c):Promise.resolve(c).then(i,a)}function _asyncToGenerator(e){return function(){var t=this,n=arguments;return new Promise(function(i,a){var o=e.apply(t,n);function r(e){asyncGeneratorStep(o,i,a,r,s,"next",e)}function s(e){asyncGeneratorStep(o,i,a,r,s,"throw",e)}r(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,a=_objectWithoutPropertiesLoose(e,t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(i=0;i<o.length;i++)n=o[i],-1===t.indexOf(n)&&{}.propertyIsEnumerable.call(e,n)&&(a[n]=e[n])}return a}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,a=function(){};return{s:a,n:function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}},e:function(e){throw e},f:a}}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 o,r=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return r=e.done,e},e:function(e){s=!0,o=e},f:function(){try{r||null==n.return||n.return()}finally{if(s)throw o}}}}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,a,o,r,s=[],c=!0,l=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;c=!1}else for(;!(c=(i=o.call(n)).done)&&(s.push(i.value),s.length!==t);c=!0);}catch(e){l=!0,a=e}finally{try{if(!c&&null!=n.return&&(r=n.return(),Object(r)!==r))return}finally{if(l)throw a}}return s}}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.chatInteractionManager=function(){var e={generatedImageAltText:"Generated Image",generatedImageMaxWidth:400,downloadImageTitle:"Download image",downloadChartTitle:"Download chart as image",downloadChartButtonText:"Download",codeCopiedText:"Copied!",copyTitle:"Click here to copy response to clipboard.",copiedTitle:"Response copied to clipboard.",copyResetDelayMs:2e3,assistantLabel:"Assistant",messageTemplate:'\n <div class="ai-chat-messages">\n <div v-for="(message, index) in messages" :key="index" class="ai-chat-message-item">\n <div>\n <div v-if="message.role === \'user\'" class="ai-chat-msg-role ai-chat-msg-role-user">You</div>\n <div v-else-if="message.role !== \'indicator\'" :class="getAssistantRoleClasses(message)">\n <span :class="getAssistantIconClasses(message, index)"><i :class="getAssistantIcon(message)"></i></span>\n {{ getAssistantLabel(message) }}\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 <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 <i :class="ttsPlayingMessageIndex === index ? \'fa-solid fa-circle-pause\' : \'fa-solid fa-circle-play\'"></i>\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 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 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-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 Assistant\n </div>\n ',untitledText:"Untitled",clearHistoryTitle:"Clear History",clearHistoryMessage:"Are you sure you want to clear the chat history? This action cannot be undone. Your documents, parameters, and tools will be preserved.",clearHistoryOkText:"Yes",clearHistoryCancelText:"Cancel"};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 a(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 o(e){var n,i,a,o,r,s,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!==(a=null!==(o=f.text)&&void 0!==o?o:f.Text)&&void 0!==a?a:null,f.title=null!==(r=null!==(s=f.title)&&void 0!==s?s:f.Title)&&void 0!==r?r: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 r(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 s(e){if(!e||"object"!==_typeof(e))return{};for(var t={},n=0,i=Object.entries(e);n<i.length;n++){var a,r=_slicedToArray(i[n],2),s=r[0],c=r[1];t[s]=null!==(a=o(c))&&void 0!==a?a:{}}return t}function c(e,t){return e.title||e.text||t}function l(e,t){var n=s(null!=t?t:e.references),i="string"==typeof e.rawContent?e.rawContent:"string"==typeof e.content?e.content:"",a=function(e,t){var n=(e||"").trim(),i=s(t),a=Object.entries(i);if(!a.length)return{content:n,citations:[]};var o=a.filter(function(e){var t=_slicedToArray(e,1)[0];return n.includes(t)}),l=a.filter(function(e){var t=_slicedToArray(e,2),i=t[0];return t[1].isGenerated&&!n.includes(i)});if(!o.length&&!l.length)return{content:n,citations:[]};o.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(o);try{for(f.s();!(u=f.n()).done;){var m=_slicedToArray(u.value,2),p=m[0],g=m[1],v="__CITE_".concat(h,"_").concat(g.index||h,"__");n=n.replaceAll(p,v),d.push({referenceKey:p,displayIndex:h,label:c(g,p),link:g.link||null,isDownload:r(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,I=_createForOfIteratorHelper(l);try{for(I.s();!(A=I.n()).done;){var C=_slicedToArray(A.value,2),T=C[0],x=C[1];d.push({referenceKey:T,displayIndex:h,label:c(x,T),link:x.link||null,isDownload:!0,placeholder:null}),h++}}catch(e){I.e(e)}finally{I.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=a.content,e.references=n,e.citationReferences=a.citations,e.copyContent=function(e,t){var n=(e||"").trim();if(!n||!Array.isArray(t)||0===t.length)return n;var i,a=_createForOfIteratorHelper(t);try{for(a.s();!(i=a.n()).done;){var o=i.value;n=n.replaceAll(o.referenceKey,"[".concat(o.displayIndex,"]"))}}catch(e){a.e(e)}finally{a.f()}n+="\n\nReferences:\n";var r,s=_createForOfIteratorHelper(t);try{for(s.s();!(r=s.n()).done;){var c=r.value;n+="".concat(c.displayIndex,". ").concat(c.label),c.link&&(n+=" - ".concat(c.link)),n+="\n"}}catch(e){s.e(e)}finally{s.f()}return n.trimEnd()}(i,a.citations),e.htmlContent=m(a.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(),a=t;if("undefined"!=typeof hljs)if(i&&hljs.getLanguage(i))try{a=hljs.highlight(t,{language:i}).value}catch(e){}else try{a=hljs.highlightAuto(t).value}catch(e){}else a=n(t);var o=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(o,'</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(a,"</code></pre></div>")},u.image=function(n){var i=t(n.href);if(!i)return"";var a=n.text||e.generatedImageAltText,o=e.generatedImageMaxWidth;return'<div class="generated-image-container">\n <img src="'.concat(i,'" alt="').concat(a,'" class="img-thumbnail" style="max-width: ').concat(o,'px; height: auto;" />\n <div class="mt-2">\n <a href="').concat(i,'" target="_blank" download="').concat(a,'" 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,a=document.getElementById(i.chartId);if(a)if("undefined"!=typeof Chart)if(null!==a.offsetParent)try{var o,r,s;a._chartInstance&&a._chartInstance.destroy();var c="string"==typeof i.config?JSON.parse(i.config):i.config;null!==(o=c.options)&&void 0!==o||(c.options={}),c.options.responsive=!0,c.options.maintainAspectRatio=!0,null!==(s=(r=c.options).aspectRatio)&&void 0!==s||(r.aspectRatio=4/3),a._chartInstance=new Chart(a,c)}catch(e){console.error("Error creating chart:",e)}else window.__chartConfigs[i.chartId]=i.config;else 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>).')}}catch(e){n.e(e)}finally{n.f()}})}}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"]})}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,a=i;for(;a<e.length&&(" "===e[a]||"\n"===e[a]||"\r"===e[a]||"\t"===e[a]);)a++;if(a>=e.length||"{"!==e[a])return null;for(var o=0,r=!1,s=!1;a<e.length;a++){var c=e[a];if(r){if(s){s=!1;continue}if("\\"===c){s=!0;continue}'"'===c&&(r=!1)}else if('"'!==c){if("{"===c)o++;else if("}"===c&&0===--o){var l=a,u=e.indexOf("]",l+1);return u<0?null:{startIndex:n,endIndex:u+1,json:e.substring(i,l+1).trim()}}}else r=!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}}]});var p=function(t){var n,r=Object.assign({},e,(n=t)&&"object"===_typeof(n)?Object.fromEntries(Object.entries(n).filter(function(e){return void 0!==_slicedToArray(e,2)[1]})):{});if(e=r,r.signalRHubUrl)if(r.appElementSelector)if(r.chatContainerElementSelector)if(r.inputElementSelector){if(r.sendButtonElementSelector)return Vue.createApp({data:function(){return{inputElement:null,buttonElement:null,chatContainer:null,placeholder:null,isInteractionStarted:!1,isPlaceholderVisible:!0,isStreaming:!1,isNavigatingAway:!1,autoScroll:!0,stream:null,messages:[],prompt:"",initialFieldValues:new Map,settingsDirty:!1,saveSettingsTimeout:null,saveIndicatorTimeout:null,isRecording:!1,mediaRecorder:null,preRecordingPrompt:"",micButton:null,speechToTextEnabled:"AudioInput"===r.chatMode||"Conversation"===r.chatMode,textToSpeechEnabled:"Conversation"===r.chatMode||!!r.textToSpeechEnabled,ttsVoiceName:r.ttsVoiceName||null,audioChunks:[],audioPlayQueue:[],isPlayingAudio:!1,currentAudioElement:null,currentAudioUrl:null,ttsPlayingMessageIndex:-1,ttsAudioCache:{},ttsInstanceId:"chat-interaction-"+Math.random().toString(36).slice(2),conversationModeEnabled:"Conversation"===r.chatMode,conversationButton:null,isConversationMode:!1,notifications:[],notificationDismissTimers:{},copyTitle:r.copyTitle,copiedTitle:r.copiedTitle,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},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(r.signalRHubUrl).withAutomaticReconnect().build(),e.connection.serverTimeoutInMilliseconds=6e5,e.connection.keepAliveIntervalInMilliseconds=15e3,e.connection.on("LoadInteraction",function(t){var n;e.initializeInteraction(t.itemId,!0),e.messages=[];var i=document.querySelector('[data-chat-interaction-title], .setting-input[data-setting="title"], input[name="ChatInteraction.Title"], input[name="Title"]');i&&t.title&&(i.value=t.title),(null!==(n=t.messages)&&void 0!==n?n:[]).forEach(function(t){e.addMessage(t),e.$nextTick(function(){f(t)})})}),e.connection.on("SettingsSaved",function(t,n){var i=document.querySelector('.chat-interaction-history-item[data-interaction-id="'.concat(t,'"]'));i&&(i.textContent=n||r.untitledText);var a=document.querySelector('[data-chat-interaction-title], .setting-input[data-setting="title"], input[name="ChatInteraction.Title"], input[name="Title"]');a&&n&&(a.value=n),e.showSaveIndicator("Saved","text-success")}),e.connection.on("ReceiveError",function(t){console.error("SignalR Error: ",t),e.showSaveIndicator("Save failed","text-danger"),e.isRecording&&e.stopRecording()}),e.connection.on("ReceiveTranscript",function(t,n,i){if(e.isConversationMode){if(!i&&n){e._conversationPartialTranscript=n;var a='<p class="ai-partial-transcript">'+n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")+"</p>";e._conversationPartialMessage?(e._conversationPartialMessage.content=n,e._conversationPartialMessage.htmlContent=a):(e.hidePlaceholder(),e._conversationPartialMessage={role:"user",content:n,htmlContent:a,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 a=n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">");e._conversationPartialMessage.content=n,e._conversationPartialMessage.htmlContent="<p>"+a+"</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,a,o,r){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,appearance:e.normalizeAssistantAppearance(r),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(r)),h.rawContent=e._conversationAssistantMessage.content,h.references=s(Object.assign({},h.references||{},o||{})),l(h,h.references),e.$nextTick(function(){f(h),e.scrollToBottom()}))}),e.connection.on("ReceiveConversationAssistantComplete",function(t,n,i){if(e._conversationAssistantMessage){var a=e.messages[e._conversationAssistantMessage.index];a&&(a.isStreaming=!1,a.references=s(Object.assign({},a.references||{},i||{})),l(a,a.references)),e._conversationAssistantMessage=null}}),e.connection.on("ReceiveAudioChunk",function(t,n,i){if(n){for(var a=atob(n),o=new Uint8Array(a.length),r=0;r<a.length;r++)o[r]=a.charCodeAt(r);e.audioChunks.push(o)}}),e.connection.on("ReceiveAudioComplete",function(t){e.playCollectedAudio()}),e.connection.on("HistoryCleared",function(t){e.messages=[],e.showPlaceholder();var n=document.getElementById("clearHistoryBtn");n&&n.classList.add("d-none")}),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.reloadCurrentInteraction()}),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("addingChatInteractionMessage",{detail:{message:e}})),this.messages.push(e),this.$nextTick(function(){t.fireEvent(new CustomEvent("addedChatInteractionMessage",{detail:{message:e}}))})},addMessage:function(e){var t,n=this;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()})},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},fireEvent:function(e){document.dispatchEvent(e)},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():"",a=!!e.disableStreamingAnimation;return t||n||i||a?{label:t,icon:n,cssClass:i,disableStreamingAnimation:a}:null},getAssistantLabel:function(t){var n=t?this.normalizeAssistantAppearance(t.appearance):null;return n&&n.label?n.label:e.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)},isIndicator:function(e){return"indicator"===e.role},sendMessage:function(){var e=this;return _asyncToGenerator(_regenerator().m(function t(){var n,i;return _regenerator().w(function(t){for(;;)switch(t.n){case 0:if(n=e.prompt.trim()){t.n=1;break}return t.a(2);case 1:return e.isRecording&&e.stopRecording(),e._audioInputSent=!0,t.n=2,e.flushPendingSave();case 2:e.addMessage({role:"user",content:n}),(i=document.getElementById("clearHistoryBtn"))&&i.classList.remove("d-none"),e.streamMessage(n),e.inputElement.value="",e.prompt="";case 3:return t.a(2)}},t)}))()},streamMessage:function(e){var t=this;this.stream&&(this.stream.dispose(),this.stream=null),this.streamingStarted(),this.showTypingIndicator(),this.autoScroll=!0;var n="",i={},a=null,r=this.messages.length,s=this.getItemId();this.stream=this.connection.stream("SendMessage",s,e).subscribe({next:function(e){var c=t.messages[r];if(!c){e.sessionId&&!s&&t.setItemId(e.sessionId),t.hideTypingIndicator(),r=t.messages.length;var u={role:"assistant",content:"",htmlContent:"",isStreaming:!0};t.messages.push(u),c=u}if(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 m,p=_slicedToArray(h[d],2),g=p[0],v=p[1];i[g]=null!==(m=o(v))&&void 0!==m?m:{}}e.content&&(e.responseId&&a&&e.responseId!==a&&(n+="\n\n"),e.responseId&&(a=e.responseId),n+=e.content),c.rawContent=n,l(c,i),t.messages[r]=c,t.$nextTick(function(){f(c),t.scrollToBottom()})},complete:function(){var e;t.processReferences(i,r),t.streamingFinished();var n=t.messages[r];n&&(n.isStreaming=!1),n&&n.content||t.hideTypingIndicator(),t.isConversationMode&&t.textToSpeechEnabled&&n&&n.content&&t.synthesizeSpeech(n.content),null===(e=t.stream)||void 0===e||e.dispose(),t.stream=null},error:function(e){var n;t.processReferences(i,r),t.streamingFinished();var a=t.messages[r];a&&(a.isStreaming=!1),t.hideTypingIndicator(),t.isNavigatingAway||t.addMessage(t.getServiceDownMessage()),null===(n=t.stream)||void 0===n||n.dispose(),t.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=s(e),Object.keys(e).length){var i,a,o=this.messages[t];o.rawContent=null!==(i=null!==(a=o.rawContent)&&void 0!==a?a:o.content)&&void 0!==i?i:"",l(o,e),this.messages[t]=o,this.$nextTick(function(){f(o),n.scrollToBottom()})}},streamingStarted:function(){var e=this.buttonElement.getAttribute("data-stop-icon");e&&this.buttonElement.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0}))},streamingFinished:function(){var e=this.buttonElement.getAttribute("data-start-icon");if(e&&this.buttonElement.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0})),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);this.settingsDirty&&this.debouncedSaveSettings()},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,i=n?'<i class="fa-solid fa-circle-pause"></i>':'<i class="fa-solid fa-circle-play"></i>';t.classList.toggle("tts-playing",n),t.setAttribute("title",n?"Pause audio":"Read aloud"),t.replaceChildren(DOMPurify.sanitize(i,{RETURN_DOM_FRAGMENT:!0}))})},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.getItemId(),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),a=0,o=_createForOfIteratorHelper(this.audioChunks);try{for(o.s();!(t=o.n()).done;){var r=t.value;i.set(r,a),a+=r.length}}catch(e){o.e(e)}finally{o.f()}this.audioChunks=[];var s=new Blob([i],{type:"audio/mp3"});this._ttsCacheIndex>=0&&(this.ttsAudioCache[this._ttsCacheIndex]=s,this._ttsCacheIndex=-1),this.isPlayingAudio&&this.currentAudioElement?this.audioPlayQueue.push(s):this.playAudioBlob(s)}else this.isPlayingAudio||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 a=Promise.resolve(),o=e._conversationAnalyser;e.mediaRecorder.addEventListener("dataavailable",function(t){if(t.data&&t.data.size>0){if(e.isPlayingAudio&&o){var n=new Uint8Array(o.frequencyBinCount);o.getByteFrequencyData(n);for(var i=0,r=0;r<n.length;r++)i+=n[r];i/n.length>=30&&e.stopAudio()}a=a.then(_asyncToGenerator(_regenerator().m(function n(){var i,a,o,r;return _regenerator().w(function(n){for(;;)switch(n.n){case 0:return n.n=1,t.data.arrayBuffer();case 1:i=n.v,a=new Uint8Array(i),o=a.reduce(function(e,t){return e+String.fromCharCode(t)},""),r=btoa(o);try{e._conversationSubject.next(r)}catch(e){}case 2:return n.a(2)}},n)})))}}),e.mediaRecorder.addEventListener("stop",function(){t.getTracks().forEach(function(e){return e.stop()}),a.then(function(){try{e._conversationSubject.complete()}catch(e){}})});var r=e.getItemId(),s=navigator.language||document.documentElement.lang||"en-US";e.connection.send("StartConversation",r,e._conversationSubject,n,s),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(){},showTypingIndicator:function(){this.addMessage({role:"indicator",htmlContent:r.indicatorTemplate})},hideTypingIndicator:function(){var e=this.messages.length;return this.messages=this.messages.filter(function(e){return"indicator"!==e.role}),e-this.messages.length},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},getItemId:function(){return this.inputElement.getAttribute("data-interaction-id")||this.inputElement.getAttribute("data-item-id")},getSaveIndicatorElement:function(){return r.saveIndicatorElementSelector?document.querySelector(r.saveIndicatorElementSelector):document.querySelector("[data-chat-interaction-save-indicator]")},showSaveIndicator:function(e,t){var n=this,i=this.getSaveIndicatorElement();i&&(i.textContent=e||"",i.className="settings-save-indicator "+(t||"text-muted"),this.saveIndicatorTimeout&&(clearTimeout(this.saveIndicatorTimeout),this.saveIndicatorTimeout=null),e&&(this.saveIndicatorTimeout=setTimeout(function(){i.textContent="",n.saveIndicatorTimeout=null},3e3)))},clearPendingSettingsSave:function(){this.saveSettingsTimeout&&(clearTimeout(this.saveSettingsTimeout),this.saveSettingsTimeout=null)},getFieldLabel:function(e){var t,n=null===(t=e.closest(".mb-3, .col-6, .col, .form-group, .form-floating"))||void 0===t?void 0:t.querySelector("label");return n?(n.textContent||"").replace(/\s+/g," ").trim()||e.dataset.setting||"This field":e.dataset.setting||"This field"},getValidationFeedbackElement:function(e){var t=e.nextElementSibling;return t&&t.classList.contains("invalid-feedback")||((t=document.createElement("div")).className="invalid-feedback",e.insertAdjacentElement("afterend",t)),t},clearSettingValidationError:function(e){e.classList.remove("is-invalid"),e.removeAttribute("aria-invalid");var t=e.nextElementSibling;t&&t.classList.contains("invalid-feedback")&&(t.textContent="")},setSettingValidationError:function(e,t){var n=this.getValidationFeedbackElement(e);e.classList.add("is-invalid"),e.setAttribute("aria-invalid","true"),n.textContent=t},getSettingValidationMessage:function(e){if(!e||e.disabled||"number"!==e.type)return null;var t=(e.value||"").trim();if(!t)return null;var n=Number(t),i=this.getFieldLabel(e);if(Number.isNaN(n))return"".concat(i," must be a valid number.");var a=e.getAttribute("min");if(null!==a&&n<Number(a))return"".concat(i," must be ").concat(a," or greater.");var o=e.getAttribute("max");return null!==o&&n>Number(o)?"".concat(i," must be ").concat(o," or less."):null},validateSettingInput:function(e){var t=this.getSettingValidationMessage(e);return t?(this.setSettingValidationError(e,t),!1):(this.clearSettingValidationError(e),!0)},validateSettings:function(){var e=this,t=!0;return this.getSettingInputs().forEach(function(n){t=e.validateSettingInput(n)&&t}),t},queueSettingsSave:function(){if(!this.validateSettings())return this.clearPendingSettingsSave(),this.settingsDirty=!1,void this.showSaveIndicator("Fix errors","text-danger");this.settingsDirty=!0,this.showSaveIndicator("Saving...","text-warning"),this.debouncedSaveSettings()},getSettingInputs:function(){var e=document.querySelectorAll(".setting-input[data-setting]");return e.length>0?e:document.querySelectorAll('input[name^="ChatInteraction."]:not([name*=".Tools["]):not([name*=".Connections["]), select[name^="ChatInteraction."]:not([name*=".Tools["]):not([name*=".Connections["]), textarea[name^="ChatInteraction."]:not([name*=".Tools["]):not([name*=".Connections["])')},getSelectedGroupValues:function(e,t){var n=document.querySelectorAll('.capability-checkbox[data-save-group="'.concat(e,'"]:checked, .capability-checkbox[data-group="').concat(e,'"]:checked'));if(n.length>0){var i=[];return n.forEach(function(e){var t=e.getAttribute("data-item-id")||e.value;t&&i.push(t)}),i}if(!t)return[];var a=[];return document.querySelectorAll(t).forEach(function(e){var t=e.name.replace(".IsSelected",".ItemId"),n=document.querySelector('input[type="hidden"][name="'.concat(t,'"]'));n&&n.value&&a.push(n.value)}),a},getPromptTemplateSelections:function(){var e=[];return document.querySelectorAll(".prompt-template-card").forEach(function(t){var n=t.querySelector(".prompt-template-id-input"),i=t.querySelector(".prompt-template-parameters-input"),a=n?n.value:t.getAttribute("data-template-id");a&&e.push({templateId:a,promptParameters:i?(i.value||"").trim():""})}),e},receiveNotification: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.notifications.push(e),this.scheduleNotificationDismiss(e),this.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),this.scrollToBottom())}},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.getItemId();this.connection.invoke("HandleNotificationAction",n,e,t).catch(function(e){return console.error("Failed to handle notification action:",e)})}},setItemId:function(e){this.inputElement.setAttribute("data-interaction-id",e||""),this.inputElement.setAttribute("data-item-id",e||"")},resetInteraction:function(){this.setItemId(""),this.isInteractionStarted=!1,this.messages=[],this.showPlaceholder()},initializeApp:function(){var e=this;this.inputElement=document.querySelector(r.inputElementSelector),this.buttonElement=document.querySelector(r.sendButtonElementSelector),this.chatContainer=document.querySelector(r.chatContainerElementSelector),this.placeholder=document.querySelector(r.placeholderElementSelector);var t=this.getItemId();t&&this.loadInteraction(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("keyup",function(t){null==e.stream&&("Enter"!==t.key||t.shiftKey||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.inputElement.addEventListener("paste",function(t){setTimeout(function(){e.prompt=e.inputElement.value,e.inputElement.value.trim()?e.buttonElement.removeAttribute("disabled"):e.buttonElement.setAttribute("disabled",!0)},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 n=document.getElementsByClassName("chat-interaction-history-item"),i=0;i<n.length;i++)n[i].addEventListener("click",function(t){t.preventDefault();var n=t.target.getAttribute("data-interaction-id");n?e.loadInteraction(n):console.error("An element with the class chat-interaction-history-item with no data-interaction-id set.")});for(var a=Array.isArray(r.messages)?r.messages:[],o=0;o<a.length;o++)this.addMessage(a[o]);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 a=r.codeCopiedText||"Copied!";t.innerHTML='<i class="fa-solid fa-check"></i> '+a,setTimeout(function(){t.innerHTML='<i class="fa-regular fa-copy"></i>'},2e3)}}}}),document.addEventListener("input",function(t){t.target.matches(".setting-input[data-setting]")&&(e.validateSettingInput(t.target),e.queueSettingsSave())}),document.addEventListener("change",function(t){if(t.target.matches(".setting-input[data-setting], .capability-checkbox[data-save-group], .capability-checkbox[data-group], .group-toggle, .ci-agent-global-toggle"))return t.target.matches(".setting-input[data-setting]")&&e.validateSettingInput(t.target),void e.queueSettingsSave();t.target.closest(".prompt-template-parameters-input, .prompt-template-id-input")&&e.queueSettingsSave()}),document.addEventListener("click",function(t){t.target.closest(".prompt-template-add-btn, .remove-prompt-template-btn")&&setTimeout(function(){e.queueSettingsSave()},0)});var s=document.getElementById("clearHistoryBtn");s&&s.addEventListener("click",function(){var t=s.getAttribute("data-interaction-id");t&&e.clearHistory(t)}),this.speechToTextEnabled&&r.micButtonElementSelector&&(this.micButton=document.querySelector(r.micButtonElementSelector),this.micButton&&(this.micButton.style.display="",this.micButton.addEventListener("click",function(){e.toggleRecording()}))),this.conversationModeEnabled&&r.conversationButtonElementSelector&&(this.conversationButton=document.querySelector(r.conversationButtonElementSelector),this.conversationButton&&this.conversationButton.addEventListener("click",function(){e.toggleConversationMode()}))},loadInteraction:function(e){this.connection.invoke("LoadInteraction",e).catch(function(e){return console.error(e)})},reloadCurrentInteraction:function(){var e=this.getItemId();e&&this.loadInteraction(e)},clearHistory:function(e){var t=this,n=function(){t.stream&&(t.stream.dispose(),t.stream=null,t.hideTypingIndicator(),t.streamingFinished()),t.connection.invoke("ClearHistory",e).catch(function(e){return console.error("Error clearing history:",e)})};"function"!=typeof confirmDialog?window.confirm(r.clearHistoryMessage||"Clear all messages?")&&n():confirmDialog({title:r.clearHistoryTitle,message:r.clearHistoryMessage,okText:r.clearHistoryOkText,cancelText:r.clearHistoryCancelText,callback:function(e){e&&n()}})},debouncedSaveSettings:function(){var e=this;this.clearPendingSettingsSave(),this.stream||(this.saveSettingsTimeout=setTimeout(function(){e.settingsDirty&&(e.saveSettings(),e.settingsDirty=!1),e.saveSettingsTimeout=null},850))},getSelectedToolNames:function(){return this.getSelectedGroupValues("toolNames",'input[type="checkbox"][name$="].IsSelected"][name^="ChatInteraction.Tools["]:checked')},getSelectedMcpConnectionIds:function(){return this.getSelectedGroupValues("mcpConnectionIds",'input[type="checkbox"][name$="].IsSelected"][name^="ChatInteraction.Connections["]:checked')},getSelectedA2AConnectionIds:function(){return this.getSelectedGroupValues("a2aConnectionIds")},getSelectedAgentNames:function(){return this.getSelectedGroupValues("agentNames",'input[type="checkbox"][name$="].IsSelected"][name^="ChatInteraction.Agents["]:checked')},saveSettings:function(){var e=this,t=this.getItemId();if(!t)return Promise.resolve();if(!this.validateSettings())return this.showSaveIndicator("Fix errors","text-danger"),Promise.resolve();var n={};this.getSettingInputs().forEach(function(e){var t=e.dataset.setting||(e.name||"").replace("ChatInteraction.","").replace(/^[A-Z]/,function(e){return e.toLowerCase()});t&&("checkbox"===e.type?n[t]=e.checked:"number"===e.type?n[t]=e.value?parseFloat(e.value):null:n[t]=e.value||null)}),n.toolNames=this.getSelectedToolNames(),n.mcpConnectionIds=this.getSelectedMcpConnectionIds(),n.a2aConnectionIds=this.getSelectedA2AConnectionIds(),n.agentNames=this.getSelectedAgentNames();var i=this.getPromptTemplateSelections();return i.length>0&&(n.promptTemplates=i,n.promptTemplateIds=i.map(function(e){return e.templateId})),this.connection.invoke("SaveSettings",t,n).catch(function(t){console.error("Error saving settings:",t),e.showSaveIndicator("Save failed","text-danger")})},flushPendingSave:function(){return this.saveSettingsTimeout&&(clearTimeout(this.saveSettingsTimeout),this.saveSettingsTimeout=null),this.settingsDirty?(this.settingsDirty=!1,this.saveSettings()):Promise.resolve()},initializeInteraction:function(e,t){this.isInteractionStarted&&!t||(this.fireEvent(new CustomEvent("initializingChatInteraction",{detail:{itemId:e}})),this.setItemId(e),this.isInteractionStarted=!0)},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,a,o,s,c=this,l=e&&"object"===_typeof(e)?null!==(i=null!==(a=e.copyContent)&&void 0!==a?a:e.content)&&void 0!==i?i:"":null!=e?e:"",u=(null==n?void 0:n.currentTarget)||(null==n||null===(o=n.target)||void 0===o||null===(s=o.closest)||void 0===s?void 0:s.call(o,"[data-copy-message-index]"))||null;navigator.clipboard.writeText(l).then(function(){c.clearCopiedMessageState(),c.copiedMessageIndex="number"==typeof t?t:-1,c.activeCopyButton=u,u?c.setCopyButtonState(u,!0):c.$nextTick(function(){return c.updateCopyButtons()}),c.copyResetTimeoutId=window.setTimeout(function(){c.clearCopiedMessageState(),c.$nextTick(function(){return c.updateCopyButtons()})},Number(r.copyResetDelayMs)||2e3)}).catch(function(e){return console.error("Failed to copy response:",e)})},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,a=e.getItemId(),o=Promise.resolve();e.mediaRecorder.addEventListener("dataavailable",function(e){e.data&&e.data.size>0&&(o=o.then(_asyncToGenerator(_regenerator().m(function t(){var n,a,o,r;return _regenerator().w(function(t){for(;;)switch(t.n){case 0:return t.n=1,e.data.arrayBuffer();case 1:n=t.v,a=new Uint8Array(n),o=a.reduce(function(e,t){return e+String.fromCharCode(t)},""),r=btoa(o),i.next(r);case 2:return t.a(2)}},t)}))))}),e.mediaRecorder.addEventListener("stop",function(){t.getTracks().forEach(function(e){return e.stop()}),o.then(function(){return i.complete()})});var r=navigator.language||document.documentElement.lang||"en-US";e.connection.send("SendAudioStream",a,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>'))}},watch:{isPlayingAudio:function(){},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=""))},copiedMessageIndex:function(){var e=this;this.$nextTick(function(){return e.updateCopyButtons()})}},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(),e.$nextTick(function(){e.updateCopyButtons(),i(e.$el),e.fontAwesomeObserver=a(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()},template:r.messageTemplate}).mount(r.appElementSelector);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.")},g="[data-chat-interaction-config]";function v(e){if(!e||"true"===e.dataset.chatInteractionInitialized)return e&&e.__chatInteractionApp||null;var t=function(e,t,n){var i=e.getAttribute(t);if(!i)return null;try{return JSON.parse(i)}catch(e){return console.error("Failed to parse "+n+" JSON.",e),null}}(e,"data-chat-interaction-config","chat interaction config");if(!t)return null;var n=p(t);return n?(e.dataset.chatInteractionInitialized="true",e.__chatInteractionApp=n,n):null}function y(e){e&&"function"==typeof e.querySelectorAll&&("function"==typeof e.matches&&e.matches(g)&&v(e),e.querySelectorAll(g).forEach(v))}function b(){(y(document),"undefined"!=typeof MutationObserver)&&new MutationObserver(function(e){e.forEach(function(e){e.addedNodes.forEach(function(e){e&&1===e.nodeType&&y(e)})})}).observe(document.body,{childList:!0,subtree:!0})}return"loading"===document.readyState?document.addEventListener("DOMContentLoaded",b,{once:!0}):b(),{initialize:p,initializeFromElement:v}}(),window.chatInteractionDocumentManager=function(){var e="__chatInteractionDocumentManagerState";function t(e){return e&&"object"===_typeof(e)?{documentId:e.documentId||e.DocumentId||"",fileName:e.fileName||e.FileName||"",fileSize:e.fileSize||e.FileSize||0}:null}function n(e){return!e||e<1024?(e||0)+" B":e<1048576?(e/1024).toFixed(1)+" KB":(e/1048576).toFixed(1)+" MB"}function i(e,t){return(e||"").trim().toLowerCase()+"::"+(t||0)}function a(e,t){return t.has(i(e.name,e.size))}function o(o){if(o&&o.itemId){var r=document.getElementById("chat-doc-upload"),s=document.getElementById("chat-documents-list"),c=document.getElementById("chat-doc-upload-status"),l=document.getElementById("chat-doc-upload-progress"),u=document.getElementById("chat-doc-upload-progress-bar"),d=document.getElementById("chat-doc-upload-queue");if(r&&s&&c&&l&&u&&d){var h=r[e];h&&"function"==typeof h.dispose&&h.dispose();var f,m=(Array.isArray(o.existingDocuments)?o.existingDocuments:[]).map(t).filter(function(e){return e&&e.documentId});0===m.length&&(m=(f=s)?Array.from(f.querySelectorAll("[data-chat-document-id]")).map(function(e){return t({documentId:e.dataset.chatDocumentId,fileName:e.dataset.chatDocumentName,fileSize:Number(e.dataset.chatDocumentSize||0)})}).filter(function(e){return e&&e.documentId}):[]);var p=[],g=!1,v=function(e){!function(e){E.apply(this,arguments)}(e.target.files?Array.from(e.target.files):[])};return r.addEventListener("change",v),r[e]={dispose:function(){r.removeEventListener("change",v)}},b(),I(),S(null),A(null),r[e]}}function y(e,t,n){var i=document.createElement(e);return t&&(i.className=t),i.textContent=n,i}function b(){s.innerHTML="",0!==m.length?m.forEach(function(e){var t=window.document.createElement("div");t.className="d-flex justify-content-between align-items-start gap-2 border rounded px-2 py-2 bg-white chat-document-row",t.dataset.chatDocumentId=e.documentId,t.dataset.chatDocumentName=e.fileName,t.dataset.chatDocumentSize=e.fileSize;var i=window.document.createElement("div");i.className="me-2 min-w-0";var a=y("div","fw-semibold small",e.fileName||"Document"),o=window.document.createElement("i");o.className="bi bi-file-earmark-text me-1",a.prepend(o);var r=y("div","text-muted small",n(e.fileSize));i.appendChild(a),i.appendChild(r);var c=y("button","btn btn-sm btn-outline-danger remove-chat-document-btn"," Remove");c.type="button",c.dataset.documentId=e.documentId;var l=window.document.createElement("i");l.className="bi bi-trash",c.prepend(l),c.addEventListener("click",function(){return function(e){return _.apply(this,arguments)}(e.documentId)}),t.appendChild(i),t.appendChild(c),s.appendChild(t)}):s.appendChild(y("div","text-muted small","No documents uploaded yet."))}function S(e,t){if(!e)return c.textContent="",void(c.className="small mt-2 d-none");c.textContent=e,c.className="small mt-2 "+(t||"text-muted")}function A(e,t,n){if(null==e)return l.className="progress mt-2 d-none",l.setAttribute("aria-valuenow","0"),u.className="progress-bar progress-bar-striped progress-bar-animated",u.style.width="0%",void(u.textContent="0%");var i=Math.max(0,Math.min(100,Math.round(e)));l.className="progress mt-2",l.setAttribute("aria-valuenow",i.toString()),u.className="progress-bar "+(n||"progress-bar-striped progress-bar-animated"),u.style.width=i+"%",u.textContent=t||i+"%"}function I(){d.innerHTML="",p.forEach(function(e){var t=function(e){switch(e){case"uploaded":return{label:"Uploaded",badgeClass:"text-bg-success",progressClass:"bg-success"};case"failed":return{label:"Failed",badgeClass:"text-bg-danger",progressClass:"bg-danger"};case"uploading":return{label:"Uploading",badgeClass:"text-bg-warning",progressClass:"bg-warning progress-bar-striped progress-bar-animated"};default:return{label:"Queued",badgeClass:"text-bg-secondary",progressClass:"bg-secondary progress-bar-striped progress-bar-animated"}}}(e.status),i=document.createElement("div");i.className="border rounded px-2 py-2 bg-white";var a=document.createElement("div");a.className="d-flex justify-content-between align-items-start gap-2";var o=document.createElement("div");o.className="flex-grow-1 min-w-0",o.appendChild(y("div","fw-semibold small",e.fileName)),o.appendChild(y("div","text-muted small",n(e.fileSize)));var r=y("span","badge "+t.badgeClass,t.label);a.appendChild(o),a.appendChild(r);var s=document.createElement("div");s.className="progress mt-2",s.setAttribute("role","progressbar"),s.setAttribute("aria-valuemin","0"),s.setAttribute("aria-valuemax","100"),s.setAttribute("aria-valuenow",e.progress.toString());var c=document.createElement("div");c.className="progress-bar "+t.progressClass,c.style.width=e.progress+"%",c.textContent=e.progress+"%",s.appendChild(c);var l=y("div","failed"===e.status?"small text-danger mt-2":"small text-muted mt-2",function(e){return"failed"===e.status&&e.error?e.error:"uploaded"===e.status?"Upload completed successfully.":"uploading"===e.status?e.progress+"% uploaded":"Waiting to upload..."}(e));i.appendChild(a),i.appendChild(s),i.appendChild(l),d.appendChild(i)})}function C(e,t){return{id:e.name+"::"+e.size+"::"+e.lastModified+"::"+t+"::"+Date.now(),fileName:e.name,fileSize:e.size,status:"queued",progress:0,error:null}}function T(e,t){p=p.map(function(n){return n.id===e?Object.assign({},n,t):n}),I()}function x(e){p=p.filter(function(t){return!e(t)}),I()}function w(e,t,n,i){return new Promise(function(a,r){var s=new FormData;s.append("chatInteractionId",o.itemId),s.append("files",e);var c=new XMLHttpRequest;c.open("POST",o.uploadDocumentUrl,!0),c.upload.addEventListener("progress",function(e){if(e.lengthComputable){var a=Math.round(e.loaded/e.total*100);T(t,{status:"uploading",progress:a}),A((n+e.loaded/e.total)/i*100,"Uploading "+(n+1)+" of "+i,"progress-bar-striped progress-bar-animated")}}),c.addEventListener("load",function(){if(c.status>=200&&c.status<300)try{a(JSON.parse(c.responseText))}catch(e){r(new Error("Upload failed: invalid server response."))}else r(new Error((c.responseText||"Upload failed.").trim()))}),c.addEventListener("error",function(){r(new Error("Upload failed. Please check your connection and try again."))}),c.send(s)})}function E(){return(E=_asyncToGenerator(_regenerator().m(function e(n){var s,c,l,u,d,h,f,v,y,E,_,M,k,R,P,N,B;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:if(o.uploadDocumentUrl&&n&&0!==n.length){e.n=1;break}return e.a(2);case 1:if(!g){e.n=2;break}return S("A document upload is already in progress.","text-warning"),e.a(2);case 2:if(g=!0,s=[],c=[],l=new Set(m.map(function(e){return i(e.fileName,e.fileSize)})),Array.from(n).forEach(function(e){a(e,l)?c.push(e):(l.add(i(e.name,e.size)),s.push(e))}),c.length>0&&(p=p.concat(c.map(function(e,t){return Object.assign(C(e,t),{status:"failed",progress:100,error:"This document is already attached."})})),I()),0!==s.length){e.n=3;break}return g=!1,S(c.map(function(e){return e.name+": This document is already attached."}).join(" | "),"text-warning"),A(null),e.a(2);case 3:u=s.map(C),p=p.concat(u),I(),A(0,"Preparing upload...","progress-bar-striped progress-bar-animated"),r.disabled=!0,e.p=4,d=0,h=c.map(function(e){return e.name+": This document is already attached."}),f=0;case 5:if(!(f<s.length)){e.n=10;break}return v=s[f],T((y=u[f]).id,{status:"uploading",progress:0,error:null}),S("Uploading "+(f+1)+" of "+s.length+" document(s)...","text-warning"),e.p=6,e.n=7,w(v,y.id,f,s.length);case 7:E=e.v,_=(Array.isArray(E.uploaded)?E.uploaded:[]).map(t).filter(function(e){return e&&e.documentId}),M=Array.isArray(E.failed)?E.failed:[],_.length>0?(d+=_.length,m=m.concat(_),T(y.id,{status:"uploaded",progress:100,error:null})):(k=M.length>0?M.map(function(e){return e.fileName+": "+e.error}).join(" | "):"The server did not confirm that the file was uploaded.",0===M.length&&h.push(k),T(y.id,{status:"failed",progress:100,error:k})),M.length>0&&(R=M.map(function(e){return e.fileName+": "+e.error}).join(" | "),h.push(R),T(y.id,{status:"failed",progress:100,error:R})),e.n=9;break;case 8:e.p=8,N=e.v,P=N&&N.message?N.message:"Upload failed. Please try again.",console.error("Upload failed:",N),h.push(v.name+": "+P),T(y.id,{status:"failed",progress:y.progress||0,error:P});case 9:f++,e.n=5;break;case 10:if(b(),!(h.length>0)){e.n=11;break}return x(function(e){return"uploaded"===e.status}),S((d>0?"Uploaded "+d+" document(s). ":"")+h.join(" | "),d>0?"text-warning":"text-danger"),A(null),e.a(2);case 11:x(function(){return!0}),S("Uploaded "+d+" document(s).","text-success"),A(null),e.n=13;break;case 12:e.p=12,B=e.v,console.error("Upload failed:",B),S("Upload failed. Please try again.","text-danger"),A(null);case 13:return e.p=13,g=!1,r.disabled=!1,r.value="",e.f(13);case 14:return e.a(2)}},e,null,[[6,8],[4,12,13,14]])}))).apply(this,arguments)}function _(){return(_=_asyncToGenerator(_regenerator().m(function e(n){var i,a,r,s,c;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:if(o.removeDocumentUrl&&n&&window.confirm("Remove this document?")){e.n=1;break}return e.a(2);case 1:return e.p=1,e.n=2,fetch(o.removeDocumentUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({itemId:o.itemId,documentId:n})});case 2:if((i=e.v).ok){e.n=4;break}return s=console,e.n=3,i.text();case 3:return s.error.call(s,"Failed to remove document:",e.v),S("Failed to remove document.","text-danger"),e.a(2);case 4:return e.n=5,i.json();case 5:a=e.v,r=(Array.isArray(a.documents)?a.documents:[]).map(t).filter(function(e){return e&&e.documentId}),m=r.length>0?r:m.filter(function(e){return e.documentId!==n}),b(),S("Document removed.","text-success"),e.n=7;break;case 6:e.p=6,c=e.v,console.error("Remove failed:",c),S("Failed to remove document.","text-danger");case 7:return e.a(2)}},e,null,[[1,6]])}))).apply(this,arguments)}}function r(t){if(!t||"true"===t.dataset.chatInteractionDocumentManagerInitialized)return t&&t[e]||null;var n=function(e,t,n){var i=e.getAttribute(t);if(!i)return null;try{return JSON.parse(i)}catch(e){return console.error("Failed to parse "+n+" JSON.",e),null}}(t,"data-chat-interaction-document-manager-config","chat interaction document manager config");if(!n)return null;var i=o(n);return i?(t.dataset.chatInteractionDocumentManagerInitialized="true",i):null}function s(e){e&&"function"==typeof e.querySelectorAll&&("function"==typeof e.matches&&e.matches("[data-chat-interaction-document-manager-config]")&&r(e),e.querySelectorAll("[data-chat-interaction-document-manager-config]").forEach(r))}function c(){(s(document),"undefined"!=typeof MutationObserver)&&new MutationObserver(function(e){e.forEach(function(e){e.addedNodes.forEach(function(e){e&&1===e.nodeType&&s(e)})})}).observe(document.body,{childList:!0,subtree:!0})}return"loading"===document.readyState?document.addEventListener("DOMContentLoaded",c,{once:!0}):c(),{initialize:o,initializeFromElement:r}}(),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 a=document.createElement("a");a.download="chart-"+n+".png",a.href=i.toDataURL("image/png"),a.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 a=i.src;a&&a.startsWith("data:")&&(e.preventDefault(),fetch(a).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",a=n.toStringTag||"@@toStringTag";function o(n,i,a,o){var c=i&&i.prototype instanceof s?i:s,l=Object.create(c.prototype);return _regeneratorDefine2(l,"_invoke",function(n,i,a){var o,s,c,l=0,u=a||[],d=!1,m={p:0,n:0,v:e,a:f,f:f.bind(e,4),d:function(t,n){return o=t,s=0,c=e,m.n=n,r}};function f(n,i){for(s=n,c=i,t=0;!d&&l&&!a&&t<u.length;t++){var a,o=u[t],f=m.p,h=o[2];n>3?(a=h===i)&&(c=o[(s=o[4])?5:(s=3,3)],o[4]=o[5]=e):o[0]<=f&&((a=n<2&&f<o[1])?(s=0,m.v=i,m.n=o[1]):f<h&&(a=n<3||o[0]>i||i>h)&&(o[4]=n,o[5]=i,m.n=h,s=0))}if(a||n>1)return r;throw d=!0,i}return function(a,u,h){if(l>1)throw TypeError("Generator is already running");for(d&&1===u&&f(u,h),s=u,c=h;(t=s<2?e:c)||!d;){o||(s?s<3?(s>1&&(m.n=-1),f(s,c)):m.n=c:m.v=c);try{if(l=2,o){if(s||(a="next"),t=o[a]){if(!(t=t.call(o,c)))throw TypeError("iterator result is not an object");if(!t.done)return t;c=t.value,s<2&&(s=0)}else 1===s&&(t=o.return)&&t.call(o),s<2&&(c=TypeError("The iterator does not provide a '"+a+"' method"),s=1);o=e}else if((t=(d=m.n<0)?c:n.call(i,m))!==r)break}catch(t){o=e,s=1,c=t}finally{l=1}}return{value:t,done:d}}}(n,a,o),!0),l}var r={};function s(){}function c(){}function l(){}t=Object.getPrototypeOf;var u=[][i]?t(t([][i]())):(_regeneratorDefine2(t={},i,function(){return this}),t),d=l.prototype=s.prototype=Object.create(u);function m(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,l):(e.__proto__=l,_regeneratorDefine2(e,a,"GeneratorFunction")),e.prototype=Object.create(d),e}return c.prototype=l,_regeneratorDefine2(d,"constructor",l),_regeneratorDefine2(l,"constructor",c),c.displayName="GeneratorFunction",_regeneratorDefine2(l,a,"GeneratorFunction"),_regeneratorDefine2(d),_regeneratorDefine2(d,a,"Generator"),_regeneratorDefine2(d,i,function(){return this}),_regeneratorDefine2(d,"toString",function(){return"[object Generator]"}),(_regenerator=function(){return{w:o,m:m}})()}function _regeneratorDefine2(e,t,n,i){var a=Object.defineProperty;try{a({},"",{})}catch(e){a=0}_regeneratorDefine2=function(e,t,n,i){function o(t,n){_regeneratorDefine2(e,t,function(e){return this._invoke(t,n,e)})}t?a?a(e,t,{value:n,enumerable:!i,configurable:!i,writable:!i}):e[t]=n:(o("next",0),o("throw",1),o("return",2))},_regeneratorDefine2(e,t,n,i)}function asyncGeneratorStep(e,t,n,i,a,o,r){try{var s=e[o](r),c=s.value}catch(e){return void n(e)}s.done?t(c):Promise.resolve(c).then(i,a)}function _asyncToGenerator(e){return function(){var t=this,n=arguments;return new Promise(function(i,a){var o=e.apply(t,n);function r(e){asyncGeneratorStep(o,i,a,r,s,"next",e)}function s(e){asyncGeneratorStep(o,i,a,r,s,"throw",e)}r(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,a=_objectWithoutPropertiesLoose(e,t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(i=0;i<o.length;i++)n=o[i],-1===t.indexOf(n)&&{}.propertyIsEnumerable.call(e,n)&&(a[n]=e[n])}return a}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,a=function(){};return{s:a,n:function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}},e:function(e){throw e},f:a}}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 o,r=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return r=e.done,e},e:function(e){s=!0,o=e},f:function(){try{r||null==n.return||n.return()}finally{if(s)throw o}}}}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,a,o,r,s=[],c=!0,l=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;c=!1}else for(;!(c=(i=o.call(n)).done)&&(s.push(i.value),s.length!==t);c=!0);}catch(e){l=!0,a=e}finally{try{if(!c&&null!=n.return&&(r=n.return(),Object(r)!==r))return}finally{if(l)throw a}}return s}}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.chatInteractionManager=function(){var e={generatedImageAltText:"Generated Image",generatedImageMaxWidth:400,downloadImageTitle:"Download image",downloadChartTitle:"Download chart as image",downloadChartButtonText:"Download",codeCopiedText:"Copied!",copyTitle:"Click here to copy response to clipboard.",copiedTitle:"Response copied to clipboard.",copyResetDelayMs:2e3,assistantLabel:"Assistant",messageTemplate:'\n <div class="ai-chat-messages">\n <div v-for="(message, index) in messages" :key="index" class="ai-chat-message-item">\n <div>\n <div v-if="message.role === \'user\'" class="ai-chat-msg-role ai-chat-msg-role-user">You</div>\n <div v-else-if="message.role !== \'indicator\'" :class="getAssistantRoleClasses(message)">\n <span :class="getAssistantIconClasses(message, index)"><i :class="getAssistantIcon(message)"></i></span>\n {{ getAssistantLabel(message) }}\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 <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 <i :class="ttsPlayingMessageIndex === index ? \'fa-solid fa-circle-pause\' : \'fa-solid fa-circle-play\'"></i>\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 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 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-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 Assistant\n </div>\n ',untitledText:"Untitled",clearHistoryTitle:"Clear History",clearHistoryMessage:"Are you sure you want to clear the chat history? This action cannot be undone. Your documents, parameters, and tools will be preserved.",clearHistoryOkText:"Yes",clearHistoryCancelText:"Cancel"};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 a(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 o(e){var n,i,a,o,r,s,c,l,u,d,m;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!==(a=null!==(o=f.text)&&void 0!==o?o:f.Text)&&void 0!==a?a:null,f.title=null!==(r=null!==(s=f.title)&&void 0!==s?s:f.Title)&&void 0!==r?r: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!==(m=f.isGenerated)&&void 0!==m?m:f.IsGenerated),f}function r(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 s(e){if(!e||"object"!==_typeof(e))return{};for(var t={},n=0,i=Object.entries(e);n<i.length;n++){var a,r=_slicedToArray(i[n],2),s=r[0],c=r[1];t[s]=null!==(a=o(c))&&void 0!==a?a:{}}return t}function c(e,t){return e.title||e.text||t}function l(e,t){var n=s(null!=t?t:e.references),i="string"==typeof e.rawContent?e.rawContent:"string"==typeof e.content?e.content:"",a=function(e,t){var n=(e||"").trim(),i=s(t),a=Object.entries(i);if(!a.length)return{content:n,citations:[]};var o=a.filter(function(e){var t=_slicedToArray(e,1)[0];return n.includes(t)}),l=a.filter(function(e){var t=_slicedToArray(e,2),i=t[0];return t[1].isGenerated&&!n.includes(i)});if(!o.length&&!l.length)return{content:n,citations:[]};o.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=[],m=1,f=_createForOfIteratorHelper(o);try{for(f.s();!(u=f.n()).done;){var h=_slicedToArray(u.value,2),p=h[0],g=h[1],v="__CITE_".concat(m,"_").concat(g.index||m,"__");n=n.replaceAll(p,v),d.push({referenceKey:p,displayIndex:m,label:c(g,p),link:g.link||null,isDownload:r(g),placeholder:v}),m++}}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,C=_createForOfIteratorHelper(l);try{for(C.s();!(A=C.n()).done;){var I=_slicedToArray(A.value,2),T=I[0],x=I[1];d.push({referenceKey:T,displayIndex:m,label:c(x,T),link:x.link||null,isDownload:!0,placeholder:null}),m++}}catch(e){C.e(e)}finally{C.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=a.content,e.references=n,e.citationReferences=a.citations,e.copyContent=function(e,t){var n=(e||"").trim();if(!n||!Array.isArray(t)||0===t.length)return n;var i,a=_createForOfIteratorHelper(t);try{for(a.s();!(i=a.n()).done;){var o=i.value;n=n.replaceAll(o.referenceKey,"[".concat(o.displayIndex,"]"))}}catch(e){a.e(e)}finally{a.f()}n+="\n\nReferences:\n";var r,s=_createForOfIteratorHelper(t);try{for(s.s();!(r=s.n()).done;){var c=r.value;n+="".concat(c.displayIndex,". ").concat(c.label),c.link&&(n+=" - ".concat(c.link)),n+="\n"}}catch(e){s.e(e)}finally{s.f()}return n.trimEnd()}(i,a.citations),e.htmlContent=h(a.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(),a=t;if("undefined"!=typeof hljs)if(i&&hljs.getLanguage(i))try{a=hljs.highlight(t,{language:i}).value}catch(e){}else try{a=hljs.highlightAuto(t).value}catch(e){}else a=n(t);var o=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(o,'</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(a,"</code></pre></div>")},u.image=function(n){var i=t(n.href);if(!i)return"";var a=n.text||e.generatedImageAltText,o=e.generatedImageMaxWidth;return'<div class="generated-image-container">\n <img src="'.concat(i,'" alt="').concat(a,'" class="img-thumbnail" style="max-width: ').concat(o,'px; height: auto;" />\n <div class="mt-2">\n <a href="').concat(i,'" target="_blank" download="').concat(a,'" 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,m=[];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,a=document.getElementById(i.chartId);if(a)if("undefined"!=typeof Chart)if(null!==a.offsetParent)try{var o,r,s;a._chartInstance&&a._chartInstance.destroy();var c="string"==typeof i.config?JSON.parse(i.config):i.config;null!==(o=c.options)&&void 0!==o||(c.options={}),c.options.responsive=!0,c.options.maintainAspectRatio=!0,null!==(s=(r=c.options).aspectRatio)&&void 0!==s||(r.aspectRatio=4/3),a._chartInstance=new Chart(a,c)}catch(e){console.error("Error creating chart:",e)}else window.__chartConfigs[i.chartId]=i.config;else 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>).')}}catch(e){n.e(e)}finally{n.f()}})}}function h(e,t){m=[];var n=marked.parse(e,{renderer:u});return t._pendingCharts=m.length>0?_toConsumableArray(m):[],DOMPurify.sanitize(n,{ADD_TAGS:["canvas"],ADD_ATTR:["target"]})}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,a=i;for(;a<e.length&&(" "===e[a]||"\n"===e[a]||"\r"===e[a]||"\t"===e[a]);)a++;if(a>=e.length||"{"!==e[a])return null;for(var o=0,r=!1,s=!1;a<e.length;a++){var c=e[a];if(r){if(s){s=!1;continue}if("\\"===c){s=!0;continue}'"'===c&&(r=!1)}else if('"'!==c){if("{"===c)o++;else if("}"===c&&0===--o){var l=a,u=e.indexOf("]",l+1);return u<0?null:{startIndex:n,endIndex:u+1,json:e.substring(i,l+1).trim()}}}else r=!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 m.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}}]});var p=function(t){var n,r=Object.assign({},e,(n=t)&&"object"===_typeof(n)?Object.fromEntries(Object.entries(n).filter(function(e){return void 0!==_slicedToArray(e,2)[1]})):{});if(e=r,r.signalRHubUrl)if(r.appElementSelector)if(r.chatContainerElementSelector)if(r.inputElementSelector){if(r.sendButtonElementSelector){var c=Vue.createApp({data:function(){return{inputElement:null,buttonElement:null,chatContainer:null,placeholder:null,isInteractionStarted:!1,isPlaceholderVisible:!0,isStreaming:!1,isNavigatingAway:!1,autoScroll:!0,stream:null,messages:[],prompt:"",initialFieldValues:new Map,settingsDirty:!1,saveSettingsTimeout:null,saveIndicatorTimeout:null,isRecording:!1,mediaRecorder:null,preRecordingPrompt:"",micButton:null,speechToTextEnabled:"AudioInput"===r.chatMode||"Conversation"===r.chatMode,textToSpeechEnabled:"Conversation"===r.chatMode||!!r.textToSpeechEnabled,ttsVoiceName:r.ttsVoiceName||null,audioChunks:[],audioPlayQueue:[],isPlayingAudio:!1,currentAudioElement:null,currentAudioUrl:null,ttsPlayingMessageIndex:-1,ttsAudioCache:{},ttsInstanceId:"chat-interaction-"+Math.random().toString(36).slice(2),conversationModeEnabled:"Conversation"===r.chatMode,conversationButton:null,isConversationMode:!1,realtimeController:null,notifications:[],notificationDismissTimers:{},copyTitle:r.copyTitle,copiedTitle:r.copiedTitle,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},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(r.signalRHubUrl).withAutomaticReconnect().build(),e.connection.serverTimeoutInMilliseconds=6e5,e.connection.keepAliveIntervalInMilliseconds=15e3,e.connection.on("LoadInteraction",function(t){var n;e.initializeInteraction(t.itemId,!0),e.messages=[];var i=document.querySelector('[data-chat-interaction-title], .setting-input[data-setting="title"], input[name="ChatInteraction.Title"], input[name="Title"]');i&&t.title&&(i.value=t.title),(null!==(n=t.messages)&&void 0!==n?n:[]).forEach(function(t){e.addMessage(t),e.$nextTick(function(){f(t)})})}),e.connection.on("SettingsSaved",function(t,n){var i=document.querySelector('.chat-interaction-history-item[data-interaction-id="'.concat(t,'"]'));i&&(i.textContent=n||r.untitledText);var a=document.querySelector('[data-chat-interaction-title], .setting-input[data-setting="title"], input[name="ChatInteraction.Title"], input[name="Title"]');a&&n&&(a.value=n),e.showSaveIndicator("Saved","text-success")}),e.connection.on("ReceiveError",function(t){console.error("SignalR Error: ",t),e.showSaveIndicator("Save failed","text-danger"),e.isRecording&&e.stopRecording()}),e.connection.on("ReceiveTranscript",function(t,n,i){if(e.isConversationMode){if(!i&&n){e._conversationPartialTranscript=n;var a='<p class="ai-partial-transcript">'+n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")+"</p>";e._conversationPartialMessage?(e._conversationPartialMessage.content=n,e._conversationPartialMessage.htmlContent=a):(e.hidePlaceholder(),e._conversationPartialMessage={role:"user",content:n,htmlContent:a,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,i){if(n&&e._realtimePendingTurns&&e._realtimePendingTurns[n]){var a=e._realtimePendingTurns[n];if(delete e._realtimePendingTurns[n],e.stopAudio(),i)a.content=i,a.rawContent=i,a.isPartial=!1,l(a,a.references);else{var o=e.messages.indexOf(a);o>=0&&e.messages.splice(o,1)}}else if(i){if(e.stopAudio(),e._conversationPartialMessage){var r=i.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">");e._conversationPartialMessage.content=i,e._conversationPartialMessage.htmlContent="<p>"+r+"</p>",e._conversationPartialMessage.isPartial=!1,e._conversationPartialMessage=null}else if(e._conversationAssistantMessage){var s=e._conversationAssistantMessage.index,c={role:"user",content:i,rawContent:i,references:{}};l(c,c.references),e.messages.splice(s,0,c),e._conversationAssistantMessage.index=s+1}else e.addMessage({role:"user",content:i});e.scrollToBottom()}}),e.connection.on("ReceiveConversationAssistantToken",function(t,n,i,a,o,r){if(e._conversationAssistantMessage&&e._conversationAssistantResponseId&&a&&e._conversationAssistantResponseId!==a){var c=e.messages[e._conversationAssistantMessage.index];c&&(c.isStreaming=!1),e._conversationAssistantMessage=null}if(!e._conversationAssistantMessage){e.stopAudio(),e.hideTypingIndicator();for(var u=0;u<e.messages.length;u++)e.messages[u].isStreaming&&(e.messages[u].isStreaming=!1);var d=e.messages.length,m={id:n,role:"assistant",content:"",htmlContent:"",isStreaming:!0,appearance:e.normalizeAssistantAppearance(r),references:{}};e.messages.push(m),e._conversationAssistantMessage={index:d,content:""},e._conversationAssistantResponseId=a}e._conversationAssistantMessage.content+=i;var h=e.messages[e._conversationAssistantMessage.index];h&&(h.appearance||(h.appearance=e.normalizeAssistantAppearance(r)),h.rawContent=e._conversationAssistantMessage.content,h.references=s(Object.assign({},h.references||{},o||{})),l(h,h.references),e.$nextTick(function(){f(h),e.scrollToBottom()}))}),e.connection.on("ReceiveConversationAssistantComplete",function(t,n,i){if(e._conversationAssistantMessage){var a=e.messages[e._conversationAssistantMessage.index];a&&(a.isStreaming=!1,a.references=s(Object.assign({},a.references||{},i||{})),l(a,a.references)),e._conversationAssistantMessage=null,e._conversationAssistantResponseId=null}}),e.connection.on("ReceiveAudioChunk",function(t,n,i){if(n){for(var a=atob(n),o=new Uint8Array(a.length),r=0;r<a.length;r++)o[r]=a.charCodeAt(r);"audio/pcm"===i&&e.realtimeController?e.realtimeController.receivePcm(o):e.audioChunks.push(o)}}),e.connection.on("ReceiveAudioComplete",function(t){e.playCollectedAudio()}),e.connection.on("HistoryCleared",function(t){e.messages=[],e.showPlaceholder();var n=document.getElementById("clearHistoryBtn");n&&n.classList.add("d-none")}),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.reloadCurrentInteraction()}),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=h(e.content,e)),this.fireEvent(new CustomEvent("addingChatInteractionMessage",{detail:{message:e}})),this.messages.push(e),this.$nextTick(function(){t.fireEvent(new CustomEvent("addedChatInteractionMessage",{detail:{message:e}}))})},addMessage:function(e){var t,n=this;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()})},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},fireEvent:function(e){document.dispatchEvent(e)},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():"",a=!!e.disableStreamingAnimation;return t||n||i||a?{label:t,icon:n,cssClass:i,disableStreamingAnimation:a}:null},getAssistantLabel:function(t){var n=t?this.normalizeAssistantAppearance(t.appearance):null;return n&&n.label?n.label:e.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)},isIndicator:function(e){return"indicator"===e.role},sendMessage:function(){var e=this;return _asyncToGenerator(_regenerator().m(function t(){var n,i;return _regenerator().w(function(t){for(;;)switch(t.n){case 0:if(n=e.prompt.trim()){t.n=1;break}return t.a(2);case 1:return e.isRecording&&e.stopRecording(),e._audioInputSent=!0,t.n=2,e.flushPendingSave();case 2:e.addMessage({role:"user",content:n}),(i=document.getElementById("clearHistoryBtn"))&&i.classList.remove("d-none"),e.streamMessage(n),e.inputElement.value="",e.prompt="";case 3:return t.a(2)}},t)}))()},streamMessage:function(e){var t=this;this.stream&&(this.stream.dispose(),this.stream=null),this.streamingStarted(),this.showTypingIndicator(),this.autoScroll=!0;var n="",i={},a=null,r=this.messages.length,s=this.getItemId();this.stream=this.connection.stream("SendMessage",s,e).subscribe({next:function(e){var c=t.messages[r];if(!c){e.sessionId&&!s&&t.setItemId(e.sessionId),t.hideTypingIndicator(),r=t.messages.length;var u={role:"assistant",content:"",htmlContent:"",isStreaming:!0};t.messages.push(u),c=u}if(e.references&&"object"===_typeof(e.references)&&Object.keys(e.references).length)for(var d=0,m=Object.entries(e.references);d<m.length;d++){var h,p=_slicedToArray(m[d],2),g=p[0],v=p[1];i[g]=null!==(h=o(v))&&void 0!==h?h:{}}e.content&&(e.responseId&&a&&e.responseId!==a&&(n+="\n\n"),e.responseId&&(a=e.responseId),n+=e.content),c.rawContent=n,l(c,i),t.messages[r]=c,t.$nextTick(function(){f(c),t.scrollToBottom()})},complete:function(){var e;t.processReferences(i,r),t.streamingFinished();var n=t.messages[r];n&&(n.isStreaming=!1),n&&n.content||t.hideTypingIndicator(),t.isConversationMode&&t.textToSpeechEnabled&&n&&n.content&&t.synthesizeSpeech(n.content),null===(e=t.stream)||void 0===e||e.dispose(),t.stream=null},error:function(e){var n;t.processReferences(i,r),t.streamingFinished();var a=t.messages[r];a&&(a.isStreaming=!1),t.hideTypingIndicator(),t.isNavigatingAway||t.addMessage(t.getServiceDownMessage()),null===(n=t.stream)||void 0===n||n.dispose(),t.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=s(e),Object.keys(e).length){var i,a,o=this.messages[t];o.rawContent=null!==(i=null!==(a=o.rawContent)&&void 0!==a?a:o.content)&&void 0!==i?i:"",l(o,e),this.messages[t]=o,this.$nextTick(function(){f(o),n.scrollToBottom()})}},streamingStarted:function(){var e=this.buttonElement.getAttribute("data-stop-icon");e&&this.buttonElement.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0}))},streamingFinished:function(){var e=this.buttonElement.getAttribute("data-start-icon");if(e&&this.buttonElement.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0})),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);this.settingsDirty&&this.debouncedSaveSettings()},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,i=n?'<i class="fa-solid fa-circle-pause"></i>':'<i class="fa-solid fa-circle-play"></i>';t.classList.toggle("tts-playing",n),t.setAttribute("title",n?"Pause audio":"Read aloud"),t.replaceChildren(DOMPurify.sanitize(i,{RETURN_DOM_FRAGMENT:!0}))})},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.getItemId(),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),a=0,o=_createForOfIteratorHelper(this.audioChunks);try{for(o.s();!(t=o.n()).done;){var r=t.value;i.set(r,a),a+=r.length}}catch(e){o.e(e)}finally{o.f()}this.audioChunks=[];var s=new Blob([i],{type:"audio/mp3"});this._ttsCacheIndex>=0&&(this.ttsAudioCache[this._ttsCacheIndex]=s,this._ttsCacheIndex=-1),this.isPlayingAudio&&this.currentAudioElement?this.audioPlayQueue.push(s):this.playAudioBlob(s)}else this.isPlayingAudio||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 a=Promise.resolve(),o=e._conversationAnalyser;e.mediaRecorder.addEventListener("dataavailable",function(t){if(t.data&&t.data.size>0){if(e.isPlayingAudio&&o){var n=new Uint8Array(o.frequencyBinCount);o.getByteFrequencyData(n);for(var i=0,r=0;r<n.length;r++)i+=n[r];i/n.length>=30&&e.stopAudio()}a=a.then(_asyncToGenerator(_regenerator().m(function n(){var i,a,o,r;return _regenerator().w(function(n){for(;;)switch(n.n){case 0:return n.n=1,t.data.arrayBuffer();case 1:i=n.v,a=new Uint8Array(i),o=a.reduce(function(e,t){return e+String.fromCharCode(t)},""),r=btoa(o);try{e._conversationSubject.next(r)}catch(e){}case 2:return n.a(2)}},n)})))}}),e.mediaRecorder.addEventListener("stop",function(){t.getTracks().forEach(function(e){return e.stop()}),a.then(function(){try{e._conversationSubject.complete()}catch(e){}})});var r=e.getItemId(),s=navigator.language||document.documentElement.lang||"en-US";e.connection.send("StartConversation",r,e._conversationSubject,n,s),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(){},showTypingIndicator:function(){this.addMessage({role:"indicator",htmlContent:r.indicatorTemplate})},hideTypingIndicator:function(){var e=this.messages.length;return this.messages=this.messages.filter(function(e){return"indicator"!==e.role}),e-this.messages.length},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},getItemId:function(){return this.inputElement.getAttribute("data-interaction-id")||this.inputElement.getAttribute("data-item-id")},getSaveIndicatorElement:function(){return r.saveIndicatorElementSelector?document.querySelector(r.saveIndicatorElementSelector):document.querySelector("[data-chat-interaction-save-indicator]")},showSaveIndicator:function(e,t){var n=this,i=this.getSaveIndicatorElement();i&&(i.textContent=e||"",i.className="settings-save-indicator "+(t||"text-muted"),this.saveIndicatorTimeout&&(clearTimeout(this.saveIndicatorTimeout),this.saveIndicatorTimeout=null),e&&(this.saveIndicatorTimeout=setTimeout(function(){i.textContent="",n.saveIndicatorTimeout=null},3e3)))},clearPendingSettingsSave:function(){this.saveSettingsTimeout&&(clearTimeout(this.saveSettingsTimeout),this.saveSettingsTimeout=null)},getFieldLabel:function(e){var t,n=null===(t=e.closest(".mb-3, .col-6, .col, .form-group, .form-floating"))||void 0===t?void 0:t.querySelector("label");return n?(n.textContent||"").replace(/\s+/g," ").trim()||e.dataset.setting||"This field":e.dataset.setting||"This field"},getValidationFeedbackElement:function(e){var t=e.nextElementSibling;return t&&t.classList.contains("invalid-feedback")||((t=document.createElement("div")).className="invalid-feedback",e.insertAdjacentElement("afterend",t)),t},clearSettingValidationError:function(e){e.classList.remove("is-invalid"),e.removeAttribute("aria-invalid");var t=e.nextElementSibling;t&&t.classList.contains("invalid-feedback")&&(t.textContent="")},setSettingValidationError:function(e,t){var n=this.getValidationFeedbackElement(e);e.classList.add("is-invalid"),e.setAttribute("aria-invalid","true"),n.textContent=t},getSettingValidationMessage:function(e){if(!e||e.disabled||"number"!==e.type)return null;var t=(e.value||"").trim();if(!t)return null;var n=Number(t),i=this.getFieldLabel(e);if(Number.isNaN(n))return"".concat(i," must be a valid number.");var a=e.getAttribute("min");if(null!==a&&n<Number(a))return"".concat(i," must be ").concat(a," or greater.");var o=e.getAttribute("max");return null!==o&&n>Number(o)?"".concat(i," must be ").concat(o," or less."):null},validateSettingInput:function(e){var t=this.getSettingValidationMessage(e);return t?(this.setSettingValidationError(e,t),!1):(this.clearSettingValidationError(e),!0)},validateSettings:function(){var e=this,t=!0;return this.getSettingInputs().forEach(function(n){t=e.validateSettingInput(n)&&t}),t},queueSettingsSave:function(){if(!this.validateSettings())return this.clearPendingSettingsSave(),this.settingsDirty=!1,void this.showSaveIndicator("Fix errors","text-danger");this.settingsDirty=!0,this.showSaveIndicator("Saving...","text-warning"),this.debouncedSaveSettings()},getSettingInputs:function(){var e=document.querySelectorAll(".setting-input[data-setting]");return e.length>0?e:document.querySelectorAll('input[name^="ChatInteraction."]:not([name*=".Tools["]):not([name*=".Connections["]), select[name^="ChatInteraction."]:not([name*=".Tools["]):not([name*=".Connections["]), textarea[name^="ChatInteraction."]:not([name*=".Tools["]):not([name*=".Connections["])')},getSelectedGroupValues:function(e,t){var n=document.querySelectorAll('.capability-checkbox[data-save-group="'.concat(e,'"]:checked, .capability-checkbox[data-group="').concat(e,'"]:checked'));if(n.length>0){var i=[];return n.forEach(function(e){var t=e.getAttribute("data-item-id")||e.value;t&&i.push(t)}),i}if(!t)return[];var a=[];return document.querySelectorAll(t).forEach(function(e){var t=e.name.replace(".IsSelected",".ItemId"),n=document.querySelector('input[type="hidden"][name="'.concat(t,'"]'));n&&n.value&&a.push(n.value)}),a},getPromptTemplateSelections:function(){var e=[];return document.querySelectorAll(".prompt-template-card").forEach(function(t){var n=t.querySelector(".prompt-template-id-input"),i=t.querySelector(".prompt-template-parameters-input"),a=n?n.value:t.getAttribute("data-template-id");a&&e.push({templateId:a,promptParameters:i?(i.value||"").trim():""})}),e},receiveNotification: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.notifications.push(e),this.scheduleNotificationDismiss(e),this.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),this.scrollToBottom())}},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.getItemId();this.connection.invoke("HandleNotificationAction",n,e,t).catch(function(e){return console.error("Failed to handle notification action:",e)})}},setItemId:function(e){this.inputElement.setAttribute("data-interaction-id",e||""),this.inputElement.setAttribute("data-item-id",e||"")},resetInteraction:function(){this.setItemId(""),this.isInteractionStarted=!1,this.messages=[],this.showPlaceholder()},initializeApp:function(){var e=this;this.inputElement=document.querySelector(r.inputElementSelector),this.buttonElement=document.querySelector(r.sendButtonElementSelector),this.chatContainer=document.querySelector(r.chatContainerElementSelector),this.placeholder=document.querySelector(r.placeholderElementSelector);var t=this.getItemId();t&&this.loadInteraction(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("keyup",function(t){null==e.stream&&("Enter"!==t.key||t.shiftKey||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.inputElement.addEventListener("paste",function(t){setTimeout(function(){e.prompt=e.inputElement.value,e.inputElement.value.trim()?e.buttonElement.removeAttribute("disabled"):e.buttonElement.setAttribute("disabled",!0)},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 n=document.getElementsByClassName("chat-interaction-history-item"),i=0;i<n.length;i++)n[i].addEventListener("click",function(t){t.preventDefault();var n=t.target.getAttribute("data-interaction-id");n?e.loadInteraction(n):console.error("An element with the class chat-interaction-history-item with no data-interaction-id set.")});for(var a=Array.isArray(r.messages)?r.messages:[],o=0;o<a.length;o++)this.addMessage(a[o]);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 a=r.codeCopiedText||"Copied!";t.innerHTML='<i class="fa-solid fa-check"></i> '+a,setTimeout(function(){t.innerHTML='<i class="fa-regular fa-copy"></i>'},2e3)}}}}),document.addEventListener("input",function(t){t.target.matches(".setting-input[data-setting]")&&(e.validateSettingInput(t.target),e.queueSettingsSave())}),document.addEventListener("change",function(t){if(t.target.matches(".setting-input[data-setting], .capability-checkbox[data-save-group], .capability-checkbox[data-group], .group-toggle, .ci-agent-global-toggle"))return t.target.matches(".setting-input[data-setting]")&&e.validateSettingInput(t.target),void e.queueSettingsSave();t.target.closest(".prompt-template-parameters-input, .prompt-template-id-input")&&e.queueSettingsSave()}),document.addEventListener("click",function(t){t.target.closest(".prompt-template-add-btn, .remove-prompt-template-btn")&&setTimeout(function(){e.queueSettingsSave()},0)});var s=document.getElementById("clearHistoryBtn");s&&s.addEventListener("click",function(){var t=s.getAttribute("data-interaction-id");t&&e.clearHistory(t)}),this.speechToTextEnabled&&r.micButtonElementSelector&&(this.micButton=document.querySelector(r.micButtonElementSelector),this.micButton&&(this.micButton.style.display="",this.micButton.addEventListener("click",function(){e.toggleRecording()}))),this.conversationModeEnabled&&r.conversationButtonElementSelector&&(this.conversationButton=document.querySelector(r.conversationButtonElementSelector),this.conversationButton&&this.conversationButton.addEventListener("click",function(){e.toggleConversationMode()})),window.CoreAIRealtime&&r.realtimeButtonElementSelector&&(this.realtimeController=window.CoreAIRealtime.attach({connection:this.connection,ensureConnected:function(){return Promise.resolve(e.connection)},sendStart:function(t,n,i,a,o,r){e.connection.send("StartRealtimeConversation",e.getItemId(),t,n,i,a,o,r)},webRtcEnabled:!0===r.realtimeWebRtcEnabled,sendStartWebRtc:function(t,n,i,a,o,r){e.connection.send("StartRealtimeWebRtc",e.getItemId(),t,n,i,a,o,r)},webRtcIceServers:Array.isArray(r.realtimeWebRtcIceServers)?r.realtimeWebRtcIceServers:void 0,voiceName:r.realtimeVoiceName||"",getVoiceName:function(){var e=r.realtimeVoiceSelectElementSelector?document.querySelector(r.realtimeVoiceSelectElementSelector):null;return e?e.value:""},capableDeployments:r.realtimeCapableDeployments||[],realtimeEnabled:!0===r.realtimeEnabled,selectors:{realtimeButton:r.realtimeButtonElementSelector,input:r.inputElementSelector,sendButton:r.sendButtonElementSelector,micButton:r.micButtonElementSelector,conversationButton:r.conversationButtonElementSelector,deploymentSelect:r.deploymentSelectElementSelector},onActivate:function(){e.isConversationMode=!0,e._conversationPartialMessage=null,e._conversationAssistantMessage=null},onDeactivate:function(){if(e.isConversationMode=!1,e._conversationAssistantMessage){var t=e.messages[e._conversationAssistantMessage.index];t&&(t.isStreaming=!1),e._conversationAssistantMessage=null}},onEnterRealtimeMode:function(){e.isRecording&&e.stopRecording(),!e.isConversationMode||e.realtimeController&&e.realtimeController.isActive()||e.stopConversationMode()},onUserTurnPending:function(t){if(t){var n={role:"user",content:"",rawContent:"",references:{},isPartial:!0};l(n,n.references),e._realtimePendingTurns=e._realtimePendingTurns||{},e._realtimePendingTurns[t]=n,e.messages.push(n),e.scrollToBottom()}},onUserTurnDropped:function(t){if(t&&e._realtimePendingTurns){var n=e._realtimePendingTurns[t];if(n){delete e._realtimePendingTurns[t];var i=e.messages.indexOf(n);i>=0&&e.messages.splice(i,1)}}}}),this.setupRealtimeVoicePicker(r))},setupRealtimeVoicePicker:function(e){if(e.realtimeVoiceSelectElementSelector&&e.realtimeVoicesUrl){var t=document.querySelector(e.realtimeVoiceSelectElementSelector);if(t){var n=e.realtimeVoiceGroupElementSelector?document.querySelector(e.realtimeVoiceGroupElementSelector):null,i=e.deploymentSelectElementSelector?document.querySelector(e.deploymentSelectElementSelector):null,a=(e.realtimeCapableDeployments||[]).map(function(e){return(e||"").toLowerCase()}),o=e.realtimeVoiceName||"";i&&i.addEventListener("change",s),s()}}function r(e){return e&&-1!==a.indexOf(e.toLowerCase())}function s(){return c.apply(this,arguments)}function c(){return(c=_asyncToGenerator(_regenerator().m(function a(){var s,c,l,u,d,m,f,h,p;return _regenerator().w(function(a){for(;;)switch(a.p=a.n){case 0:if(s=i?i.value:"",c=r(s),n&&n.classList.toggle("d-none",!c),c){a.n=1;break}return a.a(2);case 1:return t.innerHTML='<option value="">Default voice</option>',a.p=2,a.n=3,fetch(e.realtimeVoicesUrl+"?deploymentName="+encodeURIComponent(s),{credentials:"same-origin"});case 3:return l=a.v,a.n=4,l.json();case 4:if((u=a.v)&&Array.isArray(u.voices)){a.n=5;break}return a.a(2);case 5:d=new Map,m=_createForOfIteratorHelper(u.voices);try{for(m.s();!(f=m.n()).done;)h=f.value,p=h.gender||"Voices",d.has(p)||d.set(p,[]),d.get(p).push(h)}catch(e){m.e(e)}finally{m.f()}Array.from(d.keys()).sort(function(e,t){return e.localeCompare(t)}).forEach(function(e){var n=document.createElement("optgroup");n.label=e,d.get(e).forEach(function(e){var t=document.createElement("option");t.value=e.id,t.textContent=e.name,t.selected=e.id===o,n.appendChild(t)}),t.appendChild(n)}),a.n=7;break;case 6:a.p=6,a.v;case 7:return a.a(2)}},a,null,[[2,6]])}))).apply(this,arguments)}},loadInteraction:function(e){this.connection.invoke("LoadInteraction",e).catch(function(e){return console.error(e)})},reloadCurrentInteraction:function(){var e=this.getItemId();e&&this.loadInteraction(e)},clearHistory:function(e){var t=this,n=function(){t.realtimeController&&t.realtimeController.isActive()&&t.realtimeController.stop(),t.stream&&(t.stream.dispose(),t.stream=null,t.hideTypingIndicator(),t.streamingFinished()),t.connection.invoke("ClearHistory",e).catch(function(e){return console.error("Error clearing history:",e)})};"function"!=typeof confirmDialog?window.confirm(r.clearHistoryMessage||"Clear all messages?")&&n():confirmDialog({title:r.clearHistoryTitle,message:r.clearHistoryMessage,okText:r.clearHistoryOkText,cancelText:r.clearHistoryCancelText,callback:function(e){e&&n()}})},debouncedSaveSettings:function(){var e=this;this.clearPendingSettingsSave(),this.stream||(this.saveSettingsTimeout=setTimeout(function(){e.settingsDirty&&(e.saveSettings(),e.settingsDirty=!1),e.saveSettingsTimeout=null},850))},getSelectedToolNames:function(){return this.getSelectedGroupValues("toolNames",'input[type="checkbox"][name$="].IsSelected"][name^="ChatInteraction.Tools["]:checked')},getSelectedMcpConnectionIds:function(){return this.getSelectedGroupValues("mcpConnectionIds",'input[type="checkbox"][name$="].IsSelected"][name^="ChatInteraction.Connections["]:checked')},getSelectedA2AConnectionIds:function(){return this.getSelectedGroupValues("a2aConnectionIds")},getSelectedAgentNames:function(){return this.getSelectedGroupValues("agentNames",'input[type="checkbox"][name$="].IsSelected"][name^="ChatInteraction.Agents["]:checked')},saveSettings:function(){var e=this,t=this.getItemId();if(!t)return Promise.resolve();if(!this.validateSettings())return this.showSaveIndicator("Fix errors","text-danger"),Promise.resolve();var n={};this.getSettingInputs().forEach(function(e){var t=e.dataset.setting||(e.name||"").replace("ChatInteraction.","").replace(/^[A-Z]/,function(e){return e.toLowerCase()});t&&("checkbox"===e.type?n[t]=e.checked:"number"===e.type?n[t]=e.value?parseFloat(e.value):null:n[t]=e.value||null)}),n.toolNames=this.getSelectedToolNames(),n.mcpConnectionIds=this.getSelectedMcpConnectionIds(),n.a2aConnectionIds=this.getSelectedA2AConnectionIds(),n.agentNames=this.getSelectedAgentNames();var i=this.getPromptTemplateSelections();return i.length>0&&(n.promptTemplates=i,n.promptTemplateIds=i.map(function(e){return e.templateId})),this.connection.invoke("SaveSettings",t,n).catch(function(t){console.error("Error saving settings:",t),e.showSaveIndicator("Save failed","text-danger")})},flushPendingSave:function(){return this.saveSettingsTimeout&&(clearTimeout(this.saveSettingsTimeout),this.saveSettingsTimeout=null),this.settingsDirty?(this.settingsDirty=!1,this.saveSettings()):Promise.resolve()},initializeInteraction:function(e,t){this.isInteractionStarted&&!t||(this.fireEvent(new CustomEvent("initializingChatInteraction",{detail:{itemId:e}})),this.setItemId(e),this.isInteractionStarted=!0)},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,a,o,s,c=this,l=e&&"object"===_typeof(e)?null!==(i=null!==(a=e.copyContent)&&void 0!==a?a:e.content)&&void 0!==i?i:"":null!=e?e:"",u=(null==n?void 0:n.currentTarget)||(null==n||null===(o=n.target)||void 0===o||null===(s=o.closest)||void 0===s?void 0:s.call(o,"[data-copy-message-index]"))||null;navigator.clipboard.writeText(l).then(function(){c.clearCopiedMessageState(),c.copiedMessageIndex="number"==typeof t?t:-1,c.activeCopyButton=u,u?c.setCopyButtonState(u,!0):c.$nextTick(function(){return c.updateCopyButtons()}),c.copyResetTimeoutId=window.setTimeout(function(){c.clearCopiedMessageState(),c.$nextTick(function(){return c.updateCopyButtons()})},Number(r.copyResetDelayMs)||2e3)}).catch(function(e){return console.error("Failed to copy response:",e)})},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,a=e.getItemId(),o=Promise.resolve();e.mediaRecorder.addEventListener("dataavailable",function(e){e.data&&e.data.size>0&&(o=o.then(_asyncToGenerator(_regenerator().m(function t(){var n,a,o,r;return _regenerator().w(function(t){for(;;)switch(t.n){case 0:return t.n=1,e.data.arrayBuffer();case 1:n=t.v,a=new Uint8Array(n),o=a.reduce(function(e,t){return e+String.fromCharCode(t)},""),r=btoa(o),i.next(r);case 2:return t.a(2)}},t)}))))}),e.mediaRecorder.addEventListener("stop",function(){t.getTracks().forEach(function(e){return e.stop()}),o.then(function(){return i.complete()})});var r=navigator.language||document.documentElement.lang||"en-US";e.connection.send("SendAudioStream",a,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>'))}},watch:{isPlayingAudio:function(){},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=""))},copiedMessageIndex:function(){var e=this;this.$nextTick(function(){return e.updateCopyButtons()})}},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(),e.$nextTick(function(){e.updateCopyButtons(),i(e.$el),e.fontAwesomeObserver=a(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()},template:r.messageTemplate}).mount(r.appElementSelector);return c}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.")},g="[data-chat-interaction-config]";function v(e){if(!e||"true"===e.dataset.chatInteractionInitialized)return e&&e.__chatInteractionApp||null;var t=function(e,t,n){var i=e.getAttribute(t);if(!i)return null;try{return JSON.parse(i)}catch(e){return console.error("Failed to parse "+n+" JSON.",e),null}}(e,"data-chat-interaction-config","chat interaction config");if(!t)return null;var n=p(t);return n?(e.dataset.chatInteractionInitialized="true",e.__chatInteractionApp=n,n):null}function y(e){e&&"function"==typeof e.querySelectorAll&&("function"==typeof e.matches&&e.matches(g)&&v(e),e.querySelectorAll(g).forEach(v))}function b(){(y(document),"undefined"!=typeof MutationObserver)&&new MutationObserver(function(e){e.forEach(function(e){e.addedNodes.forEach(function(e){e&&1===e.nodeType&&y(e)})})}).observe(document.body,{childList:!0,subtree:!0})}return"loading"===document.readyState?document.addEventListener("DOMContentLoaded",b,{once:!0}):b(),{initialize:p,initializeFromElement:v}}(),window.chatInteractionDocumentManager=function(){var e="__chatInteractionDocumentManagerState";function t(e){return e&&"object"===_typeof(e)?{documentId:e.documentId||e.DocumentId||"",fileName:e.fileName||e.FileName||"",fileSize:e.fileSize||e.FileSize||0}:null}function n(e){return!e||e<1024?(e||0)+" B":e<1048576?(e/1024).toFixed(1)+" KB":(e/1048576).toFixed(1)+" MB"}function i(e,t){return(e||"").trim().toLowerCase()+"::"+(t||0)}function a(e,t){return t.has(i(e.name,e.size))}function o(o){if(o&&o.itemId){var r=document.getElementById("chat-doc-upload"),s=document.getElementById("chat-documents-list"),c=document.getElementById("chat-doc-upload-status"),l=document.getElementById("chat-doc-upload-progress"),u=document.getElementById("chat-doc-upload-progress-bar"),d=document.getElementById("chat-doc-upload-queue");if(r&&s&&c&&l&&u&&d){var m=r[e];m&&"function"==typeof m.dispose&&m.dispose();var f,h=(Array.isArray(o.existingDocuments)?o.existingDocuments:[]).map(t).filter(function(e){return e&&e.documentId});0===h.length&&(h=(f=s)?Array.from(f.querySelectorAll("[data-chat-document-id]")).map(function(e){return t({documentId:e.dataset.chatDocumentId,fileName:e.dataset.chatDocumentName,fileSize:Number(e.dataset.chatDocumentSize||0)})}).filter(function(e){return e&&e.documentId}):[]);var p=[],g=!1,v=function(e){!function(e){w.apply(this,arguments)}(e.target.files?Array.from(e.target.files):[])};return r.addEventListener("change",v),r[e]={dispose:function(){r.removeEventListener("change",v)}},b(),C(),S(null),A(null),r[e]}}function y(e,t,n){var i=document.createElement(e);return t&&(i.className=t),i.textContent=n,i}function b(){s.innerHTML="",0!==h.length?h.forEach(function(e){var t=window.document.createElement("div");t.className="d-flex justify-content-between align-items-start gap-2 border rounded px-2 py-2 bg-white chat-document-row",t.dataset.chatDocumentId=e.documentId,t.dataset.chatDocumentName=e.fileName,t.dataset.chatDocumentSize=e.fileSize;var i=window.document.createElement("div");i.className="me-2 min-w-0";var a=y("div","fw-semibold small",e.fileName||"Document"),o=window.document.createElement("i");o.className="bi bi-file-earmark-text me-1",a.prepend(o);var r=y("div","text-muted small",n(e.fileSize));i.appendChild(a),i.appendChild(r);var c=y("button","btn btn-sm btn-outline-danger remove-chat-document-btn"," Remove");c.type="button",c.dataset.documentId=e.documentId;var l=window.document.createElement("i");l.className="bi bi-trash",c.prepend(l),c.addEventListener("click",function(){return function(e){return _.apply(this,arguments)}(e.documentId)}),t.appendChild(i),t.appendChild(c),s.appendChild(t)}):s.appendChild(y("div","text-muted small","No documents uploaded yet."))}function S(e,t){if(!e)return c.textContent="",void(c.className="small mt-2 d-none");c.textContent=e,c.className="small mt-2 "+(t||"text-muted")}function A(e,t,n){if(null==e)return l.className="progress mt-2 d-none",l.setAttribute("aria-valuenow","0"),u.className="progress-bar progress-bar-striped progress-bar-animated",u.style.width="0%",void(u.textContent="0%");var i=Math.max(0,Math.min(100,Math.round(e)));l.className="progress mt-2",l.setAttribute("aria-valuenow",i.toString()),u.className="progress-bar "+(n||"progress-bar-striped progress-bar-animated"),u.style.width=i+"%",u.textContent=t||i+"%"}function C(){d.innerHTML="",p.forEach(function(e){var t=function(e){switch(e){case"uploaded":return{label:"Uploaded",badgeClass:"text-bg-success",progressClass:"bg-success"};case"failed":return{label:"Failed",badgeClass:"text-bg-danger",progressClass:"bg-danger"};case"uploading":return{label:"Uploading",badgeClass:"text-bg-warning",progressClass:"bg-warning progress-bar-striped progress-bar-animated"};default:return{label:"Queued",badgeClass:"text-bg-secondary",progressClass:"bg-secondary progress-bar-striped progress-bar-animated"}}}(e.status),i=document.createElement("div");i.className="border rounded px-2 py-2 bg-white";var a=document.createElement("div");a.className="d-flex justify-content-between align-items-start gap-2";var o=document.createElement("div");o.className="flex-grow-1 min-w-0",o.appendChild(y("div","fw-semibold small",e.fileName)),o.appendChild(y("div","text-muted small",n(e.fileSize)));var r=y("span","badge "+t.badgeClass,t.label);a.appendChild(o),a.appendChild(r);var s=document.createElement("div");s.className="progress mt-2",s.setAttribute("role","progressbar"),s.setAttribute("aria-valuemin","0"),s.setAttribute("aria-valuemax","100"),s.setAttribute("aria-valuenow",e.progress.toString());var c=document.createElement("div");c.className="progress-bar "+t.progressClass,c.style.width=e.progress+"%",c.textContent=e.progress+"%",s.appendChild(c);var l=y("div","failed"===e.status?"small text-danger mt-2":"small text-muted mt-2",function(e){return"failed"===e.status&&e.error?e.error:"uploaded"===e.status?"Upload completed successfully.":"uploading"===e.status?e.progress+"% uploaded":"Waiting to upload..."}(e));i.appendChild(a),i.appendChild(s),i.appendChild(l),d.appendChild(i)})}function I(e,t){return{id:e.name+"::"+e.size+"::"+e.lastModified+"::"+t+"::"+Date.now(),fileName:e.name,fileSize:e.size,status:"queued",progress:0,error:null}}function T(e,t){p=p.map(function(n){return n.id===e?Object.assign({},n,t):n}),C()}function x(e){p=p.filter(function(t){return!e(t)}),C()}function E(e,t,n,i){return new Promise(function(a,r){var s=new FormData;s.append("chatInteractionId",o.itemId),s.append("files",e);var c=new XMLHttpRequest;c.open("POST",o.uploadDocumentUrl,!0),c.upload.addEventListener("progress",function(e){if(e.lengthComputable){var a=Math.round(e.loaded/e.total*100);T(t,{status:"uploading",progress:a}),A((n+e.loaded/e.total)/i*100,"Uploading "+(n+1)+" of "+i,"progress-bar-striped progress-bar-animated")}}),c.addEventListener("load",function(){if(c.status>=200&&c.status<300)try{a(JSON.parse(c.responseText))}catch(e){r(new Error("Upload failed: invalid server response."))}else r(new Error((c.responseText||"Upload failed.").trim()))}),c.addEventListener("error",function(){r(new Error("Upload failed. Please check your connection and try again."))}),c.send(s)})}function w(){return(w=_asyncToGenerator(_regenerator().m(function e(n){var s,c,l,u,d,m,f,v,y,w,_,M,k,R,P,B,N;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:if(o.uploadDocumentUrl&&n&&0!==n.length){e.n=1;break}return e.a(2);case 1:if(!g){e.n=2;break}return S("A document upload is already in progress.","text-warning"),e.a(2);case 2:if(g=!0,s=[],c=[],l=new Set(h.map(function(e){return i(e.fileName,e.fileSize)})),Array.from(n).forEach(function(e){a(e,l)?c.push(e):(l.add(i(e.name,e.size)),s.push(e))}),c.length>0&&(p=p.concat(c.map(function(e,t){return Object.assign(I(e,t),{status:"failed",progress:100,error:"This document is already attached."})})),C()),0!==s.length){e.n=3;break}return g=!1,S(c.map(function(e){return e.name+": This document is already attached."}).join(" | "),"text-warning"),A(null),e.a(2);case 3:u=s.map(I),p=p.concat(u),C(),A(0,"Preparing upload...","progress-bar-striped progress-bar-animated"),r.disabled=!0,e.p=4,d=0,m=c.map(function(e){return e.name+": This document is already attached."}),f=0;case 5:if(!(f<s.length)){e.n=10;break}return v=s[f],T((y=u[f]).id,{status:"uploading",progress:0,error:null}),S("Uploading "+(f+1)+" of "+s.length+" document(s)...","text-warning"),e.p=6,e.n=7,E(v,y.id,f,s.length);case 7:w=e.v,_=(Array.isArray(w.uploaded)?w.uploaded:[]).map(t).filter(function(e){return e&&e.documentId}),M=Array.isArray(w.failed)?w.failed:[],_.length>0?(d+=_.length,h=h.concat(_),T(y.id,{status:"uploaded",progress:100,error:null})):(k=M.length>0?M.map(function(e){return e.fileName+": "+e.error}).join(" | "):"The server did not confirm that the file was uploaded.",0===M.length&&m.push(k),T(y.id,{status:"failed",progress:100,error:k})),M.length>0&&(R=M.map(function(e){return e.fileName+": "+e.error}).join(" | "),m.push(R),T(y.id,{status:"failed",progress:100,error:R})),e.n=9;break;case 8:e.p=8,B=e.v,P=B&&B.message?B.message:"Upload failed. Please try again.",console.error("Upload failed:",B),m.push(v.name+": "+P),T(y.id,{status:"failed",progress:y.progress||0,error:P});case 9:f++,e.n=5;break;case 10:if(b(),!(m.length>0)){e.n=11;break}return x(function(e){return"uploaded"===e.status}),S((d>0?"Uploaded "+d+" document(s). ":"")+m.join(" | "),d>0?"text-warning":"text-danger"),A(null),e.a(2);case 11:x(function(){return!0}),S("Uploaded "+d+" document(s).","text-success"),A(null),e.n=13;break;case 12:e.p=12,N=e.v,console.error("Upload failed:",N),S("Upload failed. Please try again.","text-danger"),A(null);case 13:return e.p=13,g=!1,r.disabled=!1,r.value="",e.f(13);case 14:return e.a(2)}},e,null,[[6,8],[4,12,13,14]])}))).apply(this,arguments)}function _(){return(_=_asyncToGenerator(_regenerator().m(function e(n){var i,a,r,s,c;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:if(o.removeDocumentUrl&&n&&window.confirm("Remove this document?")){e.n=1;break}return e.a(2);case 1:return e.p=1,e.n=2,fetch(o.removeDocumentUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({itemId:o.itemId,documentId:n})});case 2:if((i=e.v).ok){e.n=4;break}return s=console,e.n=3,i.text();case 3:return s.error.call(s,"Failed to remove document:",e.v),S("Failed to remove document.","text-danger"),e.a(2);case 4:return e.n=5,i.json();case 5:a=e.v,r=(Array.isArray(a.documents)?a.documents:[]).map(t).filter(function(e){return e&&e.documentId}),h=r.length>0?r:h.filter(function(e){return e.documentId!==n}),b(),S("Document removed.","text-success"),e.n=7;break;case 6:e.p=6,c=e.v,console.error("Remove failed:",c),S("Failed to remove document.","text-danger");case 7:return e.a(2)}},e,null,[[1,6]])}))).apply(this,arguments)}}function r(t){if(!t||"true"===t.dataset.chatInteractionDocumentManagerInitialized)return t&&t[e]||null;var n=function(e,t,n){var i=e.getAttribute(t);if(!i)return null;try{return JSON.parse(i)}catch(e){return console.error("Failed to parse "+n+" JSON.",e),null}}(t,"data-chat-interaction-document-manager-config","chat interaction document manager config");if(!n)return null;var i=o(n);return i?(t.dataset.chatInteractionDocumentManagerInitialized="true",i):null}function s(e){e&&"function"==typeof e.querySelectorAll&&("function"==typeof e.matches&&e.matches("[data-chat-interaction-document-manager-config]")&&r(e),e.querySelectorAll("[data-chat-interaction-document-manager-config]").forEach(r))}function c(){(s(document),"undefined"!=typeof MutationObserver)&&new MutationObserver(function(e){e.forEach(function(e){e.addedNodes.forEach(function(e){e&&1===e.nodeType&&s(e)})})}).observe(document.body,{childList:!0,subtree:!0})}return"loading"===document.readyState?document.addEventListener("DOMContentLoaded",c,{once:!0}):c(),{initialize:o,initializeFromElement:r}}(),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 a=document.createElement("a");a.download="chart-"+n+".png",a.href=i.toDataURL("image/png"),a.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 a=i.src;a&&a.startsWith("data:")&&(e.preventDefault(),fetch(a).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=chat-interaction.min.js.map
|