@crestapps/ai-chat-ui 1.0.0-preview.11 → 1.0.0-preview.13

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.
@@ -1,2 +1,2 @@
1
- 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",s=n.toStringTag||"@@toStringTag";function a(n,i,s,a){var c=i&&i.prototype instanceof r?i:r,l=Object.create(c.prototype);return _regeneratorDefine2(l,"_invoke",function(n,i,s){var a,r,c,l=0,u=s||[],d=!1,h={p:0,n:0,v:e,a:f,f:f.bind(e,4),d:function(t,n){return a=t,r=0,c=e,h.n=n,o}};function f(n,i){for(r=n,c=i,t=0;!d&&l&&!s&&t<u.length;t++){var s,a=u[t],f=h.p,p=a[2];n>3?(s=p===i)&&(c=a[(r=a[4])?5:(r=3,3)],a[4]=a[5]=e):a[0]<=f&&((s=n<2&&f<a[1])?(r=0,h.v=i,h.n=a[1]):f<p&&(s=n<3||a[0]>i||i>p)&&(a[4]=n,a[5]=i,h.n=p,r=0))}if(s||n>1)return o;throw d=!0,i}return function(s,u,p){if(l>1)throw TypeError("Generator is already running");for(d&&1===u&&f(u,p),r=u,c=p;(t=r<2?e:c)||!d;){a||(r?r<3?(r>1&&(h.n=-1),f(r,c)):h.n=c:h.v=c);try{if(l=2,a){if(r||(s="next"),t=a[s]){if(!(t=t.call(a,c)))throw TypeError("iterator result is not an object");if(!t.done)return t;c=t.value,r<2&&(r=0)}else 1===r&&(t=a.return)&&t.call(a),r<2&&(c=TypeError("The iterator does not provide a '"+s+"' method"),r=1);a=e}else if((t=(d=h.n<0)?c:n.call(i,h))!==o)break}catch(t){a=e,r=1,c=t}finally{l=1}}return{value:t,done:d}}}(n,s,a),!0),l}var o={};function r(){}function c(){}function l(){}t=Object.getPrototypeOf;var u=[][i]?t(t([][i]())):(_regeneratorDefine2(t={},i,function(){return this}),t),d=l.prototype=r.prototype=Object.create(u);function h(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,l):(e.__proto__=l,_regeneratorDefine2(e,s,"GeneratorFunction")),e.prototype=Object.create(d),e}return c.prototype=l,_regeneratorDefine2(d,"constructor",l),_regeneratorDefine2(l,"constructor",c),c.displayName="GeneratorFunction",_regeneratorDefine2(l,s,"GeneratorFunction"),_regeneratorDefine2(d),_regeneratorDefine2(d,s,"Generator"),_regeneratorDefine2(d,i,function(){return this}),_regeneratorDefine2(d,"toString",function(){return"[object Generator]"}),(_regenerator=function(){return{w:a,m:h}})()}function _regeneratorDefine2(e,t,n,i){var s=Object.defineProperty;try{s({},"",{})}catch(e){s=0}_regeneratorDefine2=function(e,t,n,i){function a(t,n){_regeneratorDefine2(e,t,function(e){return this._invoke(t,n,e)})}t?s?s(e,t,{value:n,enumerable:!i,configurable:!i,writable:!i}):e[t]=n:(a("next",0),a("throw",1),a("return",2))},_regeneratorDefine2(e,t,n,i)}function asyncGeneratorStep(e,t,n,i,s,a,o){try{var r=e[a](o),c=r.value}catch(e){return void n(e)}r.done?t(c):Promise.resolve(c).then(i,s)}function _asyncToGenerator(e){return function(){var t=this,n=arguments;return new Promise(function(i,s){var a=e.apply(t,n);function o(e){asyncGeneratorStep(a,i,s,o,r,"next",e)}function r(e){asyncGeneratorStep(a,i,s,o,r,"throw",e)}o(void 0)})}}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,s=function(){};return{s:s,n:function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}},e:function(e){throw e},f:s}}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 a,o=!0,r=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){r=!0,a=e},f:function(){try{o||null==n.return||n.return()}finally{if(r)throw a}}}}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 _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,s,a,o,r=[],c=!0,l=!1;try{if(a=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;c=!1}else for(;!(c=(i=a.call(n)).done)&&(r.push(i.value),r.length!==t);c=!0);}catch(e){l=!0,s=e}finally{try{if(!c&&null!=n.return&&(o=n.return(),Object(o)!==o))return}finally{if(l)throw s}}return r}}function _arrayWithHoles(e){if(Array.isArray(e))return e}function _typeof(e){return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof(e)}window.openAIChatManager=function(){var e={generatedImageAltText:"Generated Image",generatedImageMaxWidth:400,downloadImageTitle:"Download image",downloadChartTitle:"Download chart as image",downloadChartButtonText:"Download",userLabel:"You",assistantLabel:"Assistant",thumbsUpTitle:"Thumbs up",thumbsDownTitle:"Thumbs down",copyTitle:"Click here to copy response to clipboard.",codeCopiedText:"Copied!",widget:{chatWidgetContainer:null,chatWidgetStateName:null,chatHistorySection:null,showHistoryButton:null,closeHistoryButton:null,newChatButton:null,toggleButtonSelector:null,resetSizeButtonSelector:null,dragHandleSelector:".ai-chat-widget-header",enableDragging:!0,enableResizing:!0,persistLayout:!0,defaultWidth:null,defaultHeight:null,minWidth:320,minHeight:420},messageTemplate:'\n <div class="ai-chat-messages">\n <div v-for="(message, index) in messages" :key="\'msg-\' + index" class="ai-chat-message-item">\n <div>\n <div v-if="message.role === \'user\'" class="ai-chat-msg-role ai-chat-msg-role-user">{{ userLabel }}</div>\n <div v-else-if="message.role !== \'indicator\'" :class="getAssistantRoleClasses(message)">\n <span :class="getAssistantIconClasses(message, index)"><span :class="getAssistantIcon(message)"></span></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 <span class="message-buttons-container" v-if="!isIndicator(message)">\n <template v-if="metricsEnabled && message.role === \'assistant\'">\n <span class="ai-chat-message-assistant-feedback" :data-message-id="message.id">\n <button class="btn btn-sm btn-link text-success p-0 me-2 button-message-toolbox rate-up-btn" @click="rateMessage(message, true, $event)" :title="thumbsUpTitle">\n <span class="fa-regular fa-thumbs-up"></span>\n </button>\n <button class="btn btn-sm btn-link text-danger p-0 me-2 button-message-toolbox rate-down-btn" @click="rateMessage(message, false, $event)" :title="thumbsDownTitle">\n <span class="fa-regular fa-thumbs-down"></span>\n </button>\n </span>\n </template>\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 <span :class="ttsPlayingMessageIndex === index ? \'fa-solid fa-circle-pause\' : \'fa-solid fa-circle-play\'"></span>\n </button>\n <button class="btn btn-sm btn-link text-secondary p-0 button-message-toolbox" @click="copyResponse(message.content)" :title="copyTitle">\n <span class="fa-solid fa-copy"></span>\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 <span v-if="notification.icon" :class="notification.icon" class="ai-chat-notification-icon"></span>\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 <span class="fa-solid fa-xmark"></span>\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 <span v-if="action.icon" :class="action.icon" class="me-1"></span>\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"><span class="fa fa-robot" style="display: inline-block;"></span></span>\n Assistant\n </div>\n '};function t(e){if(!e)return"";var t=e.trim();return/^javascript:/i.test(t)||/^vbscript:/i.test(t)||/^data:text\/html/i.test(t)?"":e}function n(e){var t=document.createElement("span");return t.textContent=e,t.innerHTML}function i(e){var t,n,i,s,a,o;if(!e||"object"!==_typeof(e))return null;var r=Object.assign({},e);return r.index=null!==(t=null!==(n=r.index)&&void 0!==n?n:r.Index)&&void 0!==t?t:0,r.text=null!==(i=null!==(s=r.text)&&void 0!==s?s:r.Text)&&void 0!==i?i:null,r.link=null!==(a=null!==(o=r.link)&&void 0!==o?o:r.Link)&&void 0!==a?a:null,r}function s(e){if(!e||"object"!==_typeof(e))return{};for(var t={},n=0,s=Object.entries(e);n<s.length;n++){var a,o=_slicedToArray(s[n],2),r=o[0],c=o[1];t[r]=null!==(a=i(c))&&void 0!==a?a:{}}return t}var a=new marked.Renderer;a.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||""},a.code=function(e){var t=e.text||"",i=(e.lang||"").trim(),s=t;if("undefined"!=typeof hljs)if(i&&hljs.getLanguage(i))try{s=hljs.highlight(t,{language:i}).value}catch(e){}else try{s=hljs.highlightAuto(t).value}catch(e){}else s=n(t);var a=i?n(i):"code";return'<div class="ai-code-block"><div class="ai-code-header"><span class="ai-code-lang"><span class="fa-solid fa-code"></span> '.concat(a,'</span><button type="button" class="ai-code-copy-btn" title="Copy code"><span class="fa-regular fa-copy"></span></button></div><pre><code class="hljs').concat(i?" language-"+i:"",'">').concat(s,"</code></pre></div>")},a.image=function(n){var i=t(n.href);if(!i)return"";var s=n.text||e.generatedImageAltText,a=e.generatedImageMaxWidth;return'<div class="generated-image-container">\n <img src="'.concat(i,'" alt="').concat(s,'" class="img-thumbnail" style="max-width: ').concat(a,'px; height: auto;" />\n <div class="mt-2">\n <a href="').concat(i,'" target="_blank" download="').concat(s,'" title="').concat(e.downloadImageTitle,'" class="btn btn-sm btn-outline-secondary ai-download-image">\n <span class="fa-solid fa-download"></span>\n </a>\n </div>\n </div>')};var o=0,r=[];function c(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;l(i.chartId,i.config)}}catch(e){n.e(e)}finally{n.f()}})}}function l(e,t){var n=document.getElementById(e);if(!n)return!1;if("undefined"==typeof Chart)return console.warn('Chart.js is not loaded. To render interactive charts, include the Chart.js library on the page (e.g., <script src="https://cdn.jsdelivr.net/npm/chart.js@4/dist/chart.umd.min.js"><\/script>).'),!1;if(null===n.offsetParent)return window.__chartConfigs[e]=t,!1;try{var i,s,a;n._chartInstance&&n._chartInstance.destroy();var o="string"==typeof t?JSON.parse(t):t;return null!==(i=o.options)&&void 0!==i||(o.options={}),o.options.responsive=!0,o.options.maintainAspectRatio=!0,null!==(a=(s=o.options).aspectRatio)&&void 0!==a||(s.aspectRatio=4/3),n._chartInstance=new Chart(n,o),delete window.__chartConfigs[e],!0}catch(e){return console.error("Error creating chart:",e),!1}}function u(e,t){r=[];var n=marked.parse(e,{renderer:a});return t._pendingCharts=r.length>0?_toConsumableArray(r):[],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,s=i;for(;s<e.length&&(" "===e[s]||"\n"===e[s]||"\r"===e[s]||"\t"===e[s]);)s++;if(s>=e.length||"{"!==e[s])return null;for(var a=0,o=!1,r=!1;s<e.length;s++){var c=e[s];if(o){if(r){r=!1;continue}if("\\"===c){r=!0;continue}'"'===c&&(o=!1)}else if('"'!==c){if("{"===c)a++;else if("}"===c&&0===--a){var l=s,u=e.indexOf("]",l+1);return u<0?null:{startIndex:n,endIndex:u+1,json:e.substring(i,l+1).trim()}}}else o=!0}return null}(e);if(t&&0===t.startIndex){var n="chat_chart_".concat(++o);return{type:"chart",raw:e.substring(0,t.endIndex),chartId:n,json:t.json}}},renderer:function(t){return r.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,'">')+'<span class="fa-solid fa-download"></span> '.concat(e.downloadChartButtonText)+"</button></div>";var n}}]}),window.renderPendingCharts=function(){if("undefined"!=typeof Chart){var e=window.__chartConfigs;e&&requestAnimationFrame(function(){for(var t=0,n=Object.keys(e);t<n.length;t++){var i=n[t];l(i,e[i])}})}};return{initialize:function(t){var n=Object.assign({},e,t);n.widget=Object.assign({},e.widget||{},t&&t.widget?t.widget:{});var a=!!(t&&t.widget&&t.widget.chatWidgetContainer&&t.widget.chatWidgetStateName),o=window.openAIChatWidgetBehavior||null;if(e=n,n.signalRHubUrl)if(n.appElementSelector)if(n.chatContainerElementSelector)if(n.inputElementSelector){if(n.sendButtonElementSelector){var r={data:function(){return{inputElement:null,buttonElement:null,chatContainer:null,placeholder:null,isSessionStarted:!1,isPlaceholderVisible:!0,isStreaming:!1,isNavigatingAway:!1,autoScroll:!0,stream:null,messages:[],notifications:[],prompt:"",documents:n.existingDocuments||[],isUploading:!1,uploadErrors:[],isDragOver:!1,documentBar:null,metricsEnabled:!!n.metricsEnabled,userLabel:n.userLabel,assistantLabel:n.assistantLabel,thumbsUpTitle:n.thumbsUpTitle,thumbsDownTitle:n.thumbsDownTitle,copyTitle:n.copyTitle,isRecording:!1,mediaRecorder:null,preRecordingPrompt:"",micButton:null,speechToTextEnabled:"AudioInput"===n.chatMode||"Conversation"===n.chatMode,textToSpeechEnabled:"Conversation"===n.chatMode||!!n.textToSpeechEnabled,ttsVoiceName:n.ttsVoiceName||null,audioChunks:[],audioPlayQueue:[],isPlayingAudio:!1,currentAudioElement:null,currentAudioUrl:null,ttsButton:null,ttsPlayingMessageIndex:-1,ttsAudioCache:{},ttsInstanceId:"ai-chat-"+Math.random().toString(36).slice(2),singleResponseMode:!!n.singleResponseMode,conversationModeEnabled:"Conversation"===n.chatMode,conversationButton:null,isConversationMode:!1,notificationDismissTimers:{}}},computed:{lastAssistantIndex:function(){for(var e=this.messages.length-1;e>=0;e--)if("assistant"===this.messages[e].role)return e;return-1}},methods:{handleBeforeUnload:function(){this.isNavigatingAway=!0},handleDragOver:function(e){if(n.sessionDocumentsEnabled){e.preventDefault(),e.stopPropagation(),this.isDragOver=!0;var t=this.inputElement?this.inputElement.closest(".ai-admin-widget-input, .text-bg-light"):null;t&&t.classList.add("ai-chat-drag-over")}},handleDragLeave:function(e){if(n.sessionDocumentsEnabled){e.preventDefault(),e.stopPropagation(),this.isDragOver=!1;var t=this.inputElement?this.inputElement.closest(".ai-admin-widget-input, .text-bg-light"):null;t&&t.classList.remove("ai-chat-drag-over")}},handleDrop:function(e){if(n.sessionDocumentsEnabled){e.preventDefault(),e.stopPropagation(),this.isDragOver=!1;var t=this.inputElement?this.inputElement.closest(".ai-admin-widget-input, .text-bg-light"):null;t&&t.classList.remove("ai-chat-drag-over"),e.dataTransfer&&e.dataTransfer.files&&e.dataTransfer.files.length>0&&this.uploadFiles(e.dataTransfer.files)}},triggerFileInput:function(){if(n.sessionDocumentsEnabled){var e=document.getElementById("ai-chat-doc-input");e&&e.click()}},handleFileInputChange:function(e){var t=e.target.files;t&&t.length>0&&this.uploadFiles(t),e.target.value=""},uploadFiles:function(e){var t=this;return _asyncToGenerator(_regenerator().m(function i(){var s,a,o,r,c,l,u,d,h,f;return _regenerator().w(function(i){for(;;)switch(i.p=i.n){case 0:if(n.uploadDocumentUrl){i.n=1;break}return i.a(2);case 1:if(s=t.getSessionId(),a=t.getProfileId(),s||a){i.n=2;break}return console.warn("Cannot upload documents without a session or profile."),i.a(2);case 2:for(t.isUploading=!0,t.uploadErrors=[],t.renderDocumentBar(),i.p=3,o=new FormData,s?o.append("sessionId",s):o.append("profileId",a),r=0;r<e.length;r++)o.append("files",e[r]);return i.n=4,fetch(n.uploadDocumentUrl,{method:"POST",body:o});case 4:if((c=i.v).ok){i.n=6;break}return i.n=5,c.text();case 5:return l=i.v,u=t.extractReadableErrorMessage(l,"Upload failed. Please try again."),console.error("Upload failed:",l),t.uploadErrors=[{fileName:"",error:u}],i.a(2);case 6:return i.n=7,c.json();case 7:if((d=i.v).sessionId&&!s&&t.initializeSession(d.sessionId),d.uploaded&&d.uploaded.length>0)for(h=0;h<d.uploaded.length;h++)t.documents.push(d.uploaded[h]);d.failed&&d.failed.length>0&&(t.uploadErrors=d.failed),i.n=9;break;case 8:i.p=8,f=i.v,console.error("Upload error:",f),t.uploadErrors=[{fileName:"",error:"Upload failed. Please try again."}];case 9:return i.p=9,t.isUploading=!1,t.renderDocumentBar(),i.f(9);case 10:return i.a(2)}},i,null,[[3,8,9,10]])}))()},removeDocument:function(e){var t=this;return _asyncToGenerator(_regenerator().m(function i(){var s,a,o,r,c,l;return _regenerator().w(function(i){for(;;)switch(i.p=i.n){case 0:if(n.removeDocumentUrl){i.n=1;break}return i.a(2);case 1:return i.p=1,s=t.getSessionId(),i.n=2,fetch(n.removeDocumentUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({itemId:s,documentId:e.documentId})});case 2:if(!(a=i.v).ok){i.n=3;break}(o=t.documents.indexOf(e))>-1&&t.documents.splice(o,1),i.n=5;break;case 3:return i.n=4,a.text();case 4:r=i.v,c=t.extractReadableErrorMessage(r,"Failed to remove document. Please try again."),console.error("Failed to remove document:",a.status,r),t.uploadErrors=[{fileName:e.fileName||"",error:c}],t.renderDocumentBar();case 5:i.n=7;break;case 6:i.p=6,l=i.v,console.error("Remove document error:",l),t.uploadErrors=[{fileName:e.fileName||"",error:"Failed to remove document. Please try again."}],t.renderDocumentBar();case 7:return i.a(2)}},i,null,[[1,6]])}))()},formatFileSize:function(e){return e<1024?e+" B":e<1048576?(e/1024).toFixed(1)+" KB":(e/1048576).toFixed(1)+" MB"},renderDocumentBar:function(){if(this.documentBar)if(n.sessionDocumentsEnabled){this.documentBar.classList.remove("d-none");var e='<div class="ai-chat-doc-bar p-2">';e+='<div class="d-flex flex-wrap align-items-center gap-1">';for(var t=0;t<this.documents.length;t++){var i=this.documents[t],s=i.fileName||"Document";s.length>20&&(s=s.substring(0,17)+"..."),e+='<span class="badge bg-secondary bg-opacity-25 text-dark d-inline-flex align-items-center gap-1 px-2 py-1" style="font-size: 0.8rem;" title="'+this.escapeHtml(i.fileName||"")+'">',e+='<span class="fa-solid fa-file-lines" style="font-size: 0.7rem;"></span> ',e+=this.escapeHtml(s),e+=' <button type="button" class="btn-close btn-close-sm ms-1" style="font-size: 0.5rem;" data-doc-index="'+t+'" aria-label="Remove"></button>',e+="</span>"}for(var a=0;a<this.uploadErrors.length;a++){var o=this.uploadErrors[a],r=o.fileName||"File",c=o.error||"Upload failed";r.length>15&&(r=r.substring(0,12)+"..."),e+='<span class="badge bg-danger bg-opacity-25 text-danger d-inline-flex align-items-center gap-1 px-2 py-1" style="font-size: 0.8rem;" title="'+this.escapeHtml((o.fileName||"")+": "+c)+'">',e+='<span class="fa-solid fa-circle-exclamation" style="font-size: 0.7rem;"></span> ',e+=this.escapeHtml(r),e+=' <button type="button" class="btn-close btn-close-sm ms-1" style="font-size: 0.5rem;" data-error-index="'+a+'" aria-label="Dismiss"></button>',e+="</span>"}this.isUploading&&(e+='<span class="badge bg-info bg-opacity-25 text-dark d-inline-flex align-items-center gap-1 px-2 py-1" style="font-size: 0.8rem;">',e+='<span class="spinner-border spinner-border-sm" style="width: 0.7rem; height: 0.7rem;"></span> Uploading...',e+="</span>"),e+='<button type="button" class="btn btn-sm btn-outline-secondary rounded-pill ai-chat-doc-add-btn d-inline-flex align-items-center gap-1" style="font-size: 0.75rem; padding: 0.15rem 0.5rem;" title="Attach documents">',e+='<span class="fa-solid fa-paperclip"></span>',0!==this.documents.length||this.isUploading||(e+=" <span>Attach files</span>"),e+="</button>",e+="</div>",n.supportedExtensionsText&&(e+='<div class="small text-muted mt-2">Supported formats: '+this.escapeHtml(n.supportedExtensionsText)+"</div>"),e+="</div>",this.documentBar.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0}));for(var l=this,u=this.documentBar.querySelectorAll("[data-doc-index]"),d=0;d<u.length;d++)u[d].addEventListener("click",function(e){return function(t){t.preventDefault(),t.stopPropagation();var n=l.documents[e];n&&l.removeDocument(n)}}(parseInt(u[d].getAttribute("data-doc-index"))));for(var h=this.documentBar.querySelectorAll("[data-error-index]"),f=0;f<h.length;f++)h[f].addEventListener("click",function(e){return function(t){t.preventDefault(),t.stopPropagation(),l.uploadErrors.splice(e,1),l.renderDocumentBar()}}(parseInt(h[f].getAttribute("data-error-index"))));var p=this.documentBar.querySelector(".ai-chat-doc-add-btn");p&&p.addEventListener("click",function(e){e.preventDefault(),l.triggerFileInput()})}else this.documentBar.classList.add("d-none")},escapeHtml:function(e){var t=document.createElement("div");return t.textContent=e,t.innerHTML},extractReadableErrorMessage:function(e,t){if(!e||"string"!=typeof e)return t;var n=e.trim();if(!n)return t;if(n.startsWith("{")||n.startsWith("["))try{var i=JSON.parse(n),s=(null==i?void 0:i.error)||(null==i?void 0:i.message)||(null==i?void 0:i.title)||(null==i?void 0:i.detail);return"string"==typeof s&&s.trim()?s.trim():t}catch(e){return t}return/<[^>]+>/.test(n)?t:n},normalizeAssistantAppearance:function(e){if(!e)return null;var t="string"==typeof e.label?e.label.trim():"",n="string"==typeof e.icon?e.icon.trim():"",i="string"==typeof e.cssClass?e.cssClass.trim():"",s=!!e.disableStreamingAnimation;return t||n||i||s?{label:t,icon:n,cssClass:i,disableStreamingAnimation:s}:null},getAssistantLabel:function(e){var t=e?this.normalizeAssistantAppearance(e.appearance):null;return t&&t.label?t.label:this.assistantLabel},getAssistantRoleClasses:function(e){var t=e?this.normalizeAssistantAppearance(e.appearance):null,n=["ai-chat-msg-role"];return t&&t.cssClass?n.push(t.cssClass):n.push("ai-chat-msg-role-assistant"),n},getAssistantIconClasses:function(e,t){var n=e?this.normalizeAssistantAppearance(e.appearance):null;return[this.shouldAnimateAssistantIcon(e,t)?"ai-streaming-icon":"ai-bot-icon",n&&n.cssClass?n.cssClass:""]},getAssistantIcon:function(e){var t=e?this.normalizeAssistantAppearance(e.appearance):null;return t&&t.icon?t.icon:"fa fa-robot"},shouldAnimateAssistantIcon:function(e,t){var n=e?this.normalizeAssistantAppearance(e.appearance):null;return!!e&&e.isStreaming&&t===this.lastAssistantIndex&&!(n&&n.disableStreamingAnimation)},startConnection:function(){var e=this;return _asyncToGenerator(_regenerator().m(function t(){var i;return _regenerator().w(function(t){for(;;)switch(t.p=t.n){case 0:return e.connection=(new signalR.HubConnectionBuilder).withUrl(n.signalRHubUrl).withAutomaticReconnect().build(),e.connection.serverTimeoutInMilliseconds=6e5,e.connection.keepAliveIntervalInMilliseconds=15e3,e.connection.on("LoadSession",function(t){var i;e.initializeSession(t.sessionId,!0),e.messages=[],e.documents=t.documents||[],e.uploadErrors=[],(null!==(i=t.messages)&&void 0!==i?i:[]).forEach(function(t){e.addMessage(t),e.$nextTick(function(){c(t)})}),e.$nextTick(function(){e.refreshAllFeedbackIcons()}),0===e.messages.length&&n.initialPrompt&&(e.prompt=n.initialPrompt,e.sendMessage())}),e.connection.on("ReceiveError",function(t){console.error("SignalR Error: ",t),e.isRecording&&e.stopRecording(),o&&"function"==typeof o.handleReceiveError&&o.handleReceiveError(e,t,n)}),e.connection.on("MessageRated",function(t,n){var i=e.messages.find(function(e){return e.id===t});i&&(i.userRating=n)}),e.connection.on("ReceiveTranscript",function(t,n,i){if(e.isConversationMode){if(!i&&n){e._conversationPartialTranscript=n;var s='<p class="ai-partial-transcript">'+n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")+"</p>";e._conversationPartialMessage?(e._conversationPartialMessage.content=n,e._conversationPartialMessage.htmlContent=s):(e.hidePlaceholder(),e._conversationPartialMessage={role:"user",content:n,htmlContent:s,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 s=n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");e._conversationPartialMessage.content=n,e._conversationPartialMessage.htmlContent="<p>"+s+"</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,s,a){if(!e._conversationAssistantMessage){e.stopAudio(),e.hideTypingIndicator();for(var o=0;o<e.messages.length;o++)e.messages[o].isStreaming&&(e.messages[o].isStreaming=!1);var r=e.messages.length,l={id:n,role:"assistant",content:"",htmlContent:"",isStreaming:!0,userRating:null,appearance:e.normalizeAssistantAppearance(a)};e.messages.push(l),e._conversationAssistantMessage={index:r,content:""}}e._conversationAssistantMessage.content+=i;var d=e.messages[e._conversationAssistantMessage.index];d&&(d.appearance||(d.appearance=e.normalizeAssistantAppearance(a)),d.content=e._conversationAssistantMessage.content,d.htmlContent=u(d.content,d),e.$nextTick(function(){c(d),e.scrollToBottom()}))}),e.connection.on("ReceiveConversationAssistantComplete",function(t,n){if(e._conversationAssistantMessage){var i=e.messages[e._conversationAssistantMessage.index];i&&(i.isStreaming=!1),e._conversationAssistantMessage=null}}),e.connection.on("ReceiveAudioChunk",function(t,n,i){if(n){for(var s=atob(n),a=new Uint8Array(s.length),o=0;o<s.length;o++)a[o]=s.charCodeAt(o);e.audioChunks.push(a)}}),e.connection.on("ReceiveAudioComplete",function(t){e.playCollectedAudio()}),e.connection.on("ReceiveNotification",function(t){e.receiveNotification(t)}),e.connection.on("UpdateNotification",function(t){e.updateNotification(t)}),e.connection.on("RemoveNotification",function(t){e.removeNotification(t)}),e.connection.onreconnecting(function(){console.warn("SignalR: reconnecting...")}),e.connection.onreconnected(function(){console.info("SignalR: reconnected."),e.isSessionStarted?e.reloadCurrentSession():n.autoCreateSession&&e.startNewSession()}),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,i=t.v,console.error("SignalR Connection Error: ",i);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=u(e.content,e)),this.fireEvent(new CustomEvent("addingOpenAIPromotMessage",{detail:{message:e}})),this.messages.push(e),this.$nextTick(function(){t.fireEvent(new CustomEvent("addedOpenAIPromotMessage",{detail:{message:e}}))})},addMessage:function(e){var t=this;if(void 0===e.userRating&&(e.userRating=null),e.content){var n=e.content.trim();if(e.references=s(e.references),e.references&&"object"===_typeof(e.references)&&Object.keys(e.references).length){var i=Object.entries(e.references).filter(function(e){var t=_slicedToArray(e,1)[0];return n.includes(t)});if(i.length){i.sort(function(e,t){var n=_slicedToArray(e,2)[1],i=_slicedToArray(t,2)[1];return n.index-i.index});var a,o=1,r=_createForOfIteratorHelper(i);try{for(r.s();!(a=r.n()).done;){var l=_slicedToArray(a.value,2),d=l[0],h=l[1],f="__CITE_".concat(h.index,"__");n=n.replaceAll(d,f),h._displayIndex=o++,h._placeholder=f}}catch(e){r.e(e)}finally{r.f()}var p,m=_createForOfIteratorHelper(i);try{for(m.s();!(p=m.n()).done;){var g=_slicedToArray(p.value,2)[1];n=n.replaceAll(g._placeholder,"<sup><strong>".concat(g._displayIndex,"</strong></sup>"))}}catch(e){m.e(e)}finally{m.f()}n=n.replaceAll("</strong></sup><sup>","</strong></sup><sup>,</sup><sup>"),n+="<br><br>";var v,y=_createForOfIteratorHelper(i);try{for(y.s();!(v=y.n()).done;){var b=_slicedToArray(v.value,2),A=b[0],S=b[1],E=S.text||A;n+=S.link?"**".concat(S._displayIndex,"**. [").concat(E,"](").concat(S.link,")<br>"):"**".concat(S._displayIndex,"**. ").concat(E,"<br>")}}catch(e){y.e(e)}finally{y.f()}}}e.content=n,e.htmlContent=u(n,e)}this.addMessageInternal(e),this.hidePlaceholder(),this.$nextTick(function(){c(e),t.scrollToBottom()})},addMessages:function(e){for(var t=this,n=0;n<e.length;n++)this.addMessageInternal(e[n]);this.hidePlaceholder(),this.$nextTick(function(){t.scrollToBottom()})},hidePlaceholder:function(){this.placeholder&&this.placeholder.classList.add("d-none"),this.isPlaceholderVisible=!1},showPlaceholder:function(){this.placeholder&&this.placeholder.classList.remove("d-none"),this.isPlaceholderVisible=!0},isOrchestratorAvailable:function(){return!1!==n.isOrchestratorAvailable},applyOrchestratorAvailability:function(){if(this.isOrchestratorAvailable())return!0;var e=n.orchestratorUnavailableMessage||"This orchestrator is not currently available.";return this.inputElement&&(this.inputElement.disabled=!0,this.inputElement.value="",this.inputElement.placeholder=e),this.buttonElement&&(this.buttonElement.disabled=!0),this.micButtonElement&&(this.micButtonElement.disabled=!0,this.micButtonElement.style.display="none"),this.conversationButtonElement&&(this.conversationButtonElement.disabled=!0,this.conversationButtonElement.style.display="none"),!1},fireEvent:function(e){document.dispatchEvent(e)},isIndicator:function(e){return"indicator"===e.role},sendMessage:function(){if(this.applyOrchestratorAvailability()){var e=this.prompt.trim();e&&(this.isRecording&&this.stopRecording(),this._audioInputSent=!0,this.singleResponseMode&&this.messages.splice(0,this.messages.length),this.addMessage({role:"user",content:e}),this.streamMessage(this.getProfileId(),e,null),this.inputElement.value="",this.prompt="")}},startRecording:function(){var e=this;!this.isRecording&&this.connection&&navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}}).then(function(t){var n=MediaRecorder.isTypeSupported("audio/ogg;codecs=opus")?"audio/ogg;codecs=opus":MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":"audio/webm";e.mediaRecorder=new MediaRecorder(t,{mimeType:n,audioBitsPerSecond:128e3}),e.preRecordingPrompt=e.prompt,e._audioInputSent=!1;var i=new signalR.Subject,s=e.getProfileId(),a=e.getSessionId()||"",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,s,a,o;return _regenerator().w(function(t){for(;;)switch(t.n){case 0:return t.n=1,e.data.arrayBuffer();case 1:n=t.v,s=new Uint8Array(n),a=s.reduce(function(e,t){return e+String.fromCharCode(t)},""),o=btoa(a),i.next(o);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",s,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='<span class="fa-solid fa-stop"></span>'):(this.micButton.classList.remove("stt-recording"),this.micButton.innerHTML='<span class="fa-solid fa-microphone"></span>'))},streamMessage:function(e,t,n){var s=this;this.stream&&(this.stream.dispose(),this.stream=null),this.streamingStarted(),this.showTypingIndicator(),this.autoScroll=!0;var a="",o={},r=null,l=this.messages.length,d=this.getSessionId();this.stream=this.connection.stream("SendMessage",e,t,d,n).subscribe({next:function(e){var t=s.messages[l];if(!t){e.sessionId&&!d&&s.initializeSession(e.sessionId),s.hideTypingIndicator(),l=s.messages.length;var n={id:e.messageId,role:"assistant",title:e.title,content:"",htmlContent:"",isStreaming:!0,userRating:null};s.messages.push(n),t=n}if(!e.title||t.title&&t.title===e.title||(t.title=e.title),e.references&&"object"===_typeof(e.references)&&Object.keys(e.references).length)for(var h=0,f=Object.entries(e.references);h<f.length;h++){var p,m=_slicedToArray(f[h],2),g=m[0],v=m[1];o[g]=null!==(p=i(v))&&void 0!==p?p:{}}if(e.content){e.responseId&&r&&e.responseId!==r&&(a+="\n\n"),e.responseId&&(r=e.responseId);for(var y=e.content,b=0,A=Object.entries(o);b<A.length;b++){var S=_slicedToArray(A[b],2),E=S[0],_=S[1];y=y.replaceAll(E,"<sup><strong>".concat(_.index,"</strong></sup>"))}a+=y.replaceAll("</strong></sup><sup>","</strong></sup><sup>,</sup><sup>")}t.content=a,t.htmlContent=u(a,t),s.messages[l]=t,s.$nextTick(function(){c(t),s.scrollToBottom()})},complete:function(){var e;s.processReferences(o,l),s.streamingFinished();var t=s.messages[l];t&&(t.isStreaming=!1),t&&t.content||s.hideTypingIndicator(),s.isConversationMode&&s.textToSpeechEnabled&&t&&t.content&&s.synthesizeSpeech(t.content),null===(e=s.stream)||void 0===e||e.dispose(),s.stream=null},error:function(e){var t;s.processReferences(o,l),s.streamingFinished();var n=s.messages[l];n&&(n.isStreaming=!1),s.hideTypingIndicator(),s.isNavigatingAway||s.addMessage(s.getServiceDownMessage()),null===(t=s.stream)||void 0===t||t.dispose(),s.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=this.messages[t],a=i.content||"",o=Object.entries(e).filter(function(e){var t=_slicedToArray(e,2),n=t[0],i=t[1];return a.includes(n)||a.includes("<sup><strong>".concat(i.index,"</strong></sup>"))});if(!o.length)return;o.sort(function(e,t){var n=_slicedToArray(e,2)[1],i=_slicedToArray(t,2)[1];return n.index-i.index});var r,l=a.trim(),d=1,h=_createForOfIteratorHelper(o);try{for(h.s();!(r=h.n()).done;){var f=_slicedToArray(r.value,2),p=f[0],m=f[1],g="__CITE_".concat(m.index,"__");l=(l=l.replaceAll(p,g)).replaceAll("<sup><strong>".concat(m.index,"</strong></sup>"),g),m._displayIndex=d++,m._placeholder=g}}catch(e){h.e(e)}finally{h.f()}var v,y=_createForOfIteratorHelper(o);try{for(y.s();!(v=y.n()).done;){var b=_slicedToArray(v.value,2)[1];l=l.replaceAll(b._placeholder,"<sup><strong>".concat(b._displayIndex,"</strong></sup>"))}}catch(e){y.e(e)}finally{y.f()}l=l.replaceAll("</strong></sup><sup>","</strong></sup><sup>,</sup><sup>"),l+="<br><br>";var A,S=_createForOfIteratorHelper(o);try{for(S.s();!(A=S.n()).done;){var E=_slicedToArray(A.value,2),_=E[0],T=E[1],C=T.text||_;l+=T.link?"**".concat(T._displayIndex,"**. [").concat(C,"](").concat(T.link,")<br>"):"**".concat(T._displayIndex,"**. ").concat(C,"<br>")}}catch(e){S.e(e)}finally{S.f()}i.content=l,i.htmlContent=u(l,i),this.messages[t]=i,this.$nextTick(function(){c(i),n.scrollToBottom()})}},streamingStarted:function(){var e=this.buttonElement.getAttribute("data-stop-icon");e&&this.buttonElement.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0})),this.inputElement&&this.inputElement.setAttribute("disabled","disabled")},streamingFinished:function(){var e=this.buttonElement.getAttribute("data-start-icon");if(e&&this.buttonElement.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0})),this.inputElement&&(this.inputElement.removeAttribute("disabled"),this.inputElement.focus()),this.chatContainer)for(var t=this.chatContainer.querySelectorAll(".ai-streaming-icon"),n=0;n<t.length;n++)t[n].classList.remove("ai-streaming-icon"),t[n].classList.add("ai-bot-icon");for(n=0;n<this.messages.length;n++)this.messages[n].isStreaming&&(this.messages[n].isStreaming=!1)},handleExternalTtsStop:function(e){var t;(null==e||null===(t=e.detail)||void 0===t?void 0:t.sourceId)!==this.ttsInstanceId&&this.stopAudio(!1)},updateTtsPlaybackButtons:function(){var e=this;this.chatContainer&&this.chatContainer.querySelectorAll("[data-tts-message-index]").forEach(function(t){var n=Number(t.getAttribute("data-tts-message-index"))===e.ttsPlayingMessageIndex,i=n?'<span class="fa-solid fa-circle-pause"></span>':'<span class="fa-solid fa-circle-play"></span>';t.classList.toggle("tts-playing",n),t.setAttribute("title",n?"Pause audio":"Read aloud"),t.replaceChildren(DOMPurify.sanitize(i,{RETURN_DOM_FRAGMENT:!0}))})},synthesizeSpeech:function(e,t){var n=this;this.textToSpeechEnabled&&e&&this.connection&&(this.audioChunks=[],this.isPlayingAudio=!0,this._ttsCacheIndex=void 0!==t?t:-1,this.connection.invoke("SynthesizeSpeech",this.getProfileId(),this.getSessionId(),e,this.ttsVoiceName).catch(function(e){console.error("TTS synthesis error:",e),n.isPlayingAudio=!1,n.ttsPlayingMessageIndex=-1,n._ttsCacheIndex=-1,n.$nextTick(function(){return n.updateTtsPlaybackButtons()})}))},toggleMessageTts:function(e,t){var n=this;this.ttsPlayingMessageIndex!==t?(this.stopAudio(!1),window.dispatchEvent(new CustomEvent("crestapps-ai-chat-stop-tts",{detail:{sourceId:this.ttsInstanceId}})),this.ttsPlayingMessageIndex=t,this.$nextTick(function(){return n.updateTtsPlaybackButtons()}),this.ttsAudioCache[t]?this.playAudioBlob(this.ttsAudioCache[t]):this.synthesizeSpeech(e.content,t)):this.stopAudio()},playCollectedAudio:function(){var e=this;if(0!==this.audioChunks.length){var t,n=this.audioChunks.reduce(function(e,t){return e+t.length},0),i=new Uint8Array(n),s=0,a=_createForOfIteratorHelper(this.audioChunks);try{for(a.s();!(t=a.n()).done;){var o=t.value;i.set(o,s),s+=o.length}}catch(e){a.e(e)}finally{a.f()}this.audioChunks=[];var r=new Blob([i],{type:"audio/mp3"});this._ttsCacheIndex>=0&&(this.ttsAudioCache[this._ttsCacheIndex]=r,this._ttsCacheIndex=-1),this.currentAudioElement?this.audioPlayQueue.push(r):this.playAudioBlob(r)}else this.currentAudioElement||0!==this.audioPlayQueue.length||(this.isPlayingAudio=!1,this.ttsPlayingMessageIndex=-1,this.$nextTick(function(){return e.updateTtsPlaybackButtons()}))},playAudioBlob:function(e){var t=this,n=URL.createObjectURL(e),i=new Audio(n);this.currentAudioUrl=n,this.currentAudioElement=i,this.isPlayingAudio=!0,i.addEventListener("ended",function(){t.currentAudioElement=null,t.currentAudioUrl=null,URL.revokeObjectURL(n),t.playNextInQueue()}),i.addEventListener("error",function(){t.currentAudioElement=null,t.currentAudioUrl=null,URL.revokeObjectURL(n),t.playNextInQueue()}),i.play().catch(function(e){console.error("Audio playback error:",e),t.currentAudioElement=null,t.currentAudioUrl=null,URL.revokeObjectURL(n),t.audioPlayQueue=[],t.isPlayingAudio=!1,t.ttsPlayingMessageIndex=-1,t.$nextTick(function(){return t.updateTtsPlaybackButtons()})})},playNextInQueue:function(){var e=this;if(this.audioPlayQueue.length>0){var t=this.audioPlayQueue.shift();this.playAudioBlob(t)}else this.isPlayingAudio=!1,this.ttsPlayingMessageIndex=-1,this.$nextTick(function(){return e.updateTtsPlaybackButtons()}),this.conversationModeOnAudioEnded()},stopAudio:function(){var e=this;this.currentAudioElement&&(this.currentAudioElement.pause(),this.currentAudioElement.currentTime=0,this.currentAudioElement=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.audioChunks=[],this.audioPlayQueue=[],this.isPlayingAudio=!1,this.ttsPlayingMessageIndex=-1,this.$nextTick(function(){return e.updateTtsPlaybackButtons()})},toggleConversationMode:function(){this.isConversationMode?this.stopConversationMode():this.startConversationMode()},startConversationMode:function(){var e=this;this.conversationModeEnabled&&!this.isConversationMode&&this.connection&&(this.isConversationMode=!0,this.updateConversationButton(),this._conversationPartialTranscript="",this._conversationAssistantMessage=null,this._conversationPartialMessage=null,this.removeNotification("conversation-ended"),navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}}).then(function(t){var n=MediaRecorder.isTypeSupported("audio/ogg;codecs=opus")?"audio/ogg;codecs=opus":MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":"audio/webm";e.mediaRecorder=new MediaRecorder(t,{mimeType:n,audioBitsPerSecond:128e3}),e._conversationSubject=new signalR.Subject,e._conversationStream=t;var i=window.AudioContext||window.webkitAudioContext;i&&(e._conversationAudioCtx=new i,e._conversationAnalyser=e._conversationAudioCtx.createAnalyser(),e._conversationAnalyser.fftSize=256,e._conversationAudioCtx.createMediaStreamSource(t).connect(e._conversationAnalyser));var s=Promise.resolve(),a=e._conversationAnalyser;e.mediaRecorder.addEventListener("dataavailable",function(t){if(t.data&&t.data.size>0){if(e.isPlayingAudio&&a){var n=new Uint8Array(a.frequencyBinCount);a.getByteFrequencyData(n);for(var i=0,o=0;o<n.length;o++)i+=n[o];i/n.length>=30&&e.stopAudio()}s=s.then(_asyncToGenerator(_regenerator().m(function n(){var i,s,a,o;return _regenerator().w(function(n){for(;;)switch(n.n){case 0:return n.n=1,t.data.arrayBuffer();case 1:i=n.v,s=new Uint8Array(i),a=s.reduce(function(e,t){return e+String.fromCharCode(t)},""),o=btoa(a);try{e._conversationSubject.next(o)}catch(e){}case 2:return n.a(2)}},n)})))}}),e.mediaRecorder.addEventListener("stop",function(){t.getTracks().forEach(function(e){return e.stop()}),s.then(function(){try{e._conversationSubject.complete()}catch(e){}})});var o=e.getProfileId(),r=e.getSessionId()||"",c=navigator.language||document.documentElement.lang||"en-US";e.connection.send("StartConversation",o,r,e._conversationSubject,n,c),e.mediaRecorder.start(250),e.isRecording=!0}).catch(function(t){console.error("Microphone access denied:",t),e.isConversationMode=!1,e.updateConversationButton()}))},stopConversationMode:function(){if(this.isConversationMode){if(this.isConversationMode=!1,this.updateConversationButton(),this.connection&&this.connection.invoke("StopConversation").catch(function(){}),this.isRecording&&this.mediaRecorder&&(this.mediaRecorder.stop(),this.isRecording=!1),this.stopAudio(),this._conversationPartialTranscript="",this._conversationPartialMessage=null,this._conversationAudioCtx&&(this._conversationAudioCtx.close().catch(function(){}),this._conversationAudioCtx=null,this._conversationAnalyser=null),this._conversationAssistantMessage){var e=this.messages[this._conversationAssistantMessage.index];e&&(e.isStreaming=!1),this._conversationAssistantMessage=null}for(var t=0;t<this.messages.length;t++)this.messages[t].isStreaming&&(this.messages[t].isStreaming=!1);this.receiveNotification({type:"conversation-ended",content:"Conversation ended.",icon:"fa-solid fa-circle-check",dismissible:!0,autoDismissMs:5e3})}},updateConversationButton:function(){if(this.conversationButton)if(this.isConversationMode){this.conversationButton.classList.add("active","btn-primary"),this.conversationButton.classList.remove("btn-dark","btn-outline-dark","btn-outline-secondary"),this.conversationButton.title=this.conversationButton.getAttribute("data-end-title")||"End Conversation";var e=this.conversationButton.getAttribute("data-end-html");e&&this.conversationButton.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0}))}else{this.conversationButton.classList.remove("active","btn-primary"),this.conversationButton.classList.remove("btn-dark","btn-outline-secondary"),this.conversationButton.classList.add("btn-outline-dark"),this.conversationButton.blur(),this.conversationButton.title=this.conversationButton.getAttribute("data-start-title")||"Start Conversation";var t=this.conversationButton.getAttribute("data-start-html");t&&this.conversationButton.replaceChildren(DOMPurify.sanitize(t,{RETURN_DOM_FRAGMENT:!0}))}},conversationModeSendPrompt:function(){},conversationModeOnAudioEnded:function(){},generatePrompt:function(e){if(e){var t=e.getAttribute("data-profile-id"),n=this.getSessionId(),i=this.getProfileId();t&&n?this.streamMessage(t,null,i):console.error("The given element is missing data-profile-id or the session has not yet started.")}else console.error("The element paramter is required.")},createSessionUrl:function(e,t,n){var i=e.toLowerCase().startsWith("http")?e:window.location.origin+e,s=new URL(i);return s.searchParams.set(t,n),s.toString()},showTypingIndicator:function(){this.addMessage({role:"indicator",htmlContent:n.indicatorTemplate})},hideTypingIndicator:function(){var e=this.messages.length;return this.messages=this.messages.filter(function(e){return"indicator"!==e.role}),e-this.messages.length},receiveNotification:function(e){var t=this;if(e&&e.type){this.clearNotificationDismiss(e.type);var n=this.notifications.findIndex(function(t){return t.type===e.type});n>=0?this.notifications.splice(n,1,e):this.notifications.push(e),this.scheduleNotificationDismiss(e),this.$nextTick(function(){t.scrollToBottom()})}},updateNotification:function(e){if(e&&e.type){this.clearNotificationDismiss(e.type);var t=this.notifications.findIndex(function(t){return t.type===e.type});t>=0&&(this.notifications.splice(t,1,e),this.scheduleNotificationDismiss(e))}},scheduleNotificationDismiss:function(e){var t=this;e&&e.type&&e.autoDismissMs&&!(e.autoDismissMs<=0)&&(this.notificationDismissTimers[e.type]=setTimeout(function(){t.removeNotification(e.type)},e.autoDismissMs))},clearNotificationDismiss:function(e){var t=this.notificationDismissTimers[e];t&&(clearTimeout(t),delete this.notificationDismissTimers[e])},removeNotification:function(e){this.clearNotificationDismiss(e),this.notifications=this.notifications.filter(function(t){return t.type!==e})},dismissNotification:function(e){this.removeNotification(e)},handleNotificationAction:function(e,t){if(this.connection){var n=this.getSessionId();this.connection.invoke("HandleNotificationAction",n,e,t).catch(function(e){console.error("Error handling notification action:",e)})}},scrollToBottom:function(){var e=this;this.autoScroll&&setTimeout(function(){e.chatContainer.scrollTop=e.chatContainer.scrollHeight-e.chatContainer.clientHeight},50)},handleUserInput:function(e){this.prompt=e.target.value},getProfileId:function(){return this.inputElement.getAttribute("data-profile-id")},setSessionId:function(e){this.inputElement.setAttribute("data-session-id",e||"")},resetSession:function(){this.stopRecording(),this.setSessionId(""),this.isSessionStarted=!1,this.sessionRating=null,this.messages=[],this.documents=[],n.autoCreateSession||this.showPlaceholder(),n.autoCreateSession&&this.startNewSession(),o&&"function"==typeof o.onSessionReset&&o.onSessionReset(this,n)},startNewSession:function(){if(this.applyOrchestratorAvailability()){var e=this.getProfileId();e&&this.connection&&this.connection.invoke("StartSession",e,null).catch(function(e){return console.error(e)})}},initializeApp:function(){var e=this;this.inputElement=document.querySelector(n.inputElementSelector),this.buttonElement=document.querySelector(n.sendButtonElementSelector),this.chatContainer=document.querySelector(n.chatContainerElementSelector),this.placeholder=document.querySelector(n.placeholderElementSelector),this.applyOrchestratorAvailability();var t=this.getSessionId();if(!a&&t?this.loadSession(t):this.isOrchestratorAvailable()&&n.autoCreateSession&&!a&&!t&&this.startNewSession(),n.sessionDocumentsEnabled&&n.documentBarSelector&&(this.documentBar=document.querySelector(n.documentBarSelector),this.documentBar)){this.renderDocumentBar();var i=document.createElement("input");i.type="file",i.id="ai-chat-doc-input",i.className="d-none",i.multiple=!0,n.allowedExtensions&&(i.accept=n.allowedExtensions),i.addEventListener("change",function(t){return e.handleFileInputChange(t)}),this.documentBar.parentElement.appendChild(i);var s=this.inputElement?this.inputElement.closest(".ai-admin-widget-input, .text-bg-light"):null;s&&(s.addEventListener("dragover",function(t){return e.handleDragOver(t)}),s.addEventListener("dragleave",function(t){return e.handleDragLeave(t)}),s.addEventListener("drop",function(t){return e.handleDrop(t)}))}this.chatContainer.addEventListener("scroll",function(){if(e.stream){var t=e.chatContainer.scrollHeight-e.chatContainer.clientHeight-e.chatContainer.scrollTop<=30;e.autoScroll=t}}),this.inputElement.addEventListener("keydown",function(t){null==e.stream&&("Enter"!==t.key||t.shiftKey||(t.preventDefault(),e.buttonElement.click()))}),this.inputElement.addEventListener("input",function(t){e.handleUserInput(t),t.target.value.trim()?e.buttonElement.removeAttribute("disabled"):e.buttonElement.setAttribute("disabled",!0)}),this.buttonElement.addEventListener("click",function(){if(null==e.stream)e.sendMessage();else if(e.stream.dispose(),e.stream=null,e.streamingFinished(),e.hideTypingIndicator(),e.messages.length>0){var t=e.messages[e.messages.length-1];"assistant"!==t.role||t.content?t.isStreaming&&(t.isStreaming=!1):e.messages.pop()}});for(var o=document.getElementsByClassName("profile-generated-prompt"),r=0;r<o.length;r++)o[r].addEventListener("click",function(t){t.preventDefault(),e.generatePrompt(t.target)});var c=document.getElementsByClassName("chat-session-history-item");for(r=0;r<c.length;r++)c[r].addEventListener("click",function(t){t.preventDefault();var n=t.target.getAttribute("data-session-id");n?(e.loadSession(n),e.showChatScreen()):console.error("an element with the class chat-session-history-item with no data-session-id set.")});for(var l=0;l<n.messages.length;l++)this.addMessage(n.messages[l]);this.$nextTick(function(){e.refreshAllFeedbackIcons()}),this.chatContainer&&this.chatContainer.addEventListener("click",function(e){var t=e.target.closest(".ai-code-copy-btn");if(t){var i=t.closest(".ai-code-block")||t.closest("pre");if(i){var s=i.querySelector("code");if(s){navigator.clipboard.writeText(s.textContent);var a=n.codeCopiedText||"Copied!";t.innerHTML='<span class="fa-solid fa-check"></span> '+a,setTimeout(function(){t.innerHTML='<span class="fa-regular fa-copy"></span>'},2e3)}}}}),this.speechToTextEnabled&&n.micButtonElementSelector&&(this.micButton=document.querySelector(n.micButtonElementSelector),this.micButton&&(this.micButton.style.display="",this.micButton.addEventListener("click",function(){e.toggleRecording()}))),this.conversationModeEnabled&&n.conversationButtonElementSelector&&(this.conversationButton=document.querySelector(n.conversationButtonElementSelector),this.conversationButton&&this.conversationButton.addEventListener("click",function(){e.toggleConversationMode()}))},loadSession:function(e){this.connection.invoke("LoadSession",e).catch(function(e){return console.error(e)})},reloadCurrentSession:function(){var e=this.getSessionId();e&&this.loadSession(e)},initializeSession:function(e,t){this.isSessionStarted&&!t||(this.fireEvent(new CustomEvent("initializingSessionOpenAIChat",{detail:{sessionId:e}})),this.setSessionId(e),this.isSessionStarted=!0,o&&"function"==typeof o.onSessionInitialized&&o.onSessionInitialized(this,e,n))},getSessionId:function(){var e=this.inputElement.getAttribute("data-session-id");return!e&&o&&"function"==typeof o.resolveSessionId&&(e=o.resolveSessionId(this,n)),e},copyResponse:function(e){navigator.clipboard.writeText(e)},updateFeedbackIcons:function(e,t){if(e){var n=e.querySelector(".rate-up-btn"),i=e.querySelector(".rate-down-btn");if(n){var s=!0===t?"fa-solid fa-thumbs-up":"fa-regular fa-thumbs-up",a=document.createElement("span");a.className=s,a.style.fontSize="0.9rem",n.textContent="",n.appendChild(a)}if(i){var o=!1===t?"fa-solid fa-thumbs-down":"fa-regular fa-thumbs-down",r=document.createElement("span");r.className=o,r.style.fontSize="0.9rem",i.textContent="",i.appendChild(r)}}},refreshAllFeedbackIcons:function(){for(var e=this.$el.querySelectorAll(".ai-chat-message-assistant-feedback"),t=0;t<e.length;t++){var n=e[t].getAttribute("data-message-id"),i=this.messages.find(function(e){return e.id===n});i&&this.updateFeedbackIcons(e[t],i.userRating)}},rateMessage:function(e,t,n){var i=this.getSessionId();if(i&&e.id&&this.connection){var s=e.userRating===t?null:t;e.userRating=s;var a=this.$el.querySelector('.ai-chat-message-assistant-feedback[data-message-id="'+e.id+'"]');this.updateFeedbackIcons(a,s),null!==s&&a&&setTimeout(function(){var e=t?".rate-up-btn":".rate-down-btn",n=a.querySelector(e);n&&(n.classList.remove("spark-effect"),n.offsetWidth,n.classList.add("spark-effect"),n.addEventListener("animationend",function e(){n.removeEventListener("animationend",e),n.classList.remove("spark-effect")}))},50),this.connection.invoke("RateMessage",i,e.id,t).catch(function(e){console.error("Failed to rate message:",e)})}}},watch:{documents:{handler:function(){this.renderDocumentBar(),o&&"function"==typeof o.onDocumentsChanged&&o.onDocumentsChanged(this,this.documents,n)},deep:!0},isUploading:function(){this.renderDocumentBar()},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=""))}},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(),a&&o&&"function"==typeof o.onMounted&&o.onMounted(e,n);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.stopAudio(!1),this.stream&&(this.stream.dispose(),this.stream=null),this.connection&&this.connection.stop(),o&&"function"==typeof o.onBeforeUnmount&&o.onBeforeUnmount(this,n)},template:n.messageTemplate},l=Vue.createApp(r).mount(n.appElementSelector);return o&&"function"==typeof o.attach&&o.attach(l,n),l}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.")}}}(),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 s=document.createElement("a");s.download="chart-"+n+".png",s.href=i.toDataURL("image/png"),s.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 s=i.src;s&&s.startsWith("data:")&&(e.preventDefault(),fetch(s).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
+ 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",s=n.toStringTag||"@@toStringTag";function o(n,i,s,o){var c=i&&i.prototype instanceof r?i:r,l=Object.create(c.prototype);return _regeneratorDefine2(l,"_invoke",function(n,i,s){var o,r,c,l=0,u=s||[],d=!1,h={p:0,n:0,v:e,a:p,f:p.bind(e,4),d:function(t,n){return o=t,r=0,c=e,h.n=n,a}};function p(n,i){for(r=n,c=i,t=0;!d&&l&&!s&&t<u.length;t++){var s,o=u[t],p=h.p,f=o[2];n>3?(s=f===i)&&(c=o[(r=o[4])?5:(r=3,3)],o[4]=o[5]=e):o[0]<=p&&((s=n<2&&p<o[1])?(r=0,h.v=i,h.n=o[1]):p<f&&(s=n<3||o[0]>i||i>f)&&(o[4]=n,o[5]=i,h.n=f,r=0))}if(s||n>1)return a;throw d=!0,i}return function(s,u,f){if(l>1)throw TypeError("Generator is already running");for(d&&1===u&&p(u,f),r=u,c=f;(t=r<2?e:c)||!d;){o||(r?r<3?(r>1&&(h.n=-1),p(r,c)):h.n=c:h.v=c);try{if(l=2,o){if(r||(s="next"),t=o[s]){if(!(t=t.call(o,c)))throw TypeError("iterator result is not an object");if(!t.done)return t;c=t.value,r<2&&(r=0)}else 1===r&&(t=o.return)&&t.call(o),r<2&&(c=TypeError("The iterator does not provide a '"+s+"' method"),r=1);o=e}else if((t=(d=h.n<0)?c:n.call(i,h))!==a)break}catch(t){o=e,r=1,c=t}finally{l=1}}return{value:t,done:d}}}(n,s,o),!0),l}var a={};function r(){}function c(){}function l(){}t=Object.getPrototypeOf;var u=[][i]?t(t([][i]())):(_regeneratorDefine2(t={},i,function(){return this}),t),d=l.prototype=r.prototype=Object.create(u);function h(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,l):(e.__proto__=l,_regeneratorDefine2(e,s,"GeneratorFunction")),e.prototype=Object.create(d),e}return c.prototype=l,_regeneratorDefine2(d,"constructor",l),_regeneratorDefine2(l,"constructor",c),c.displayName="GeneratorFunction",_regeneratorDefine2(l,s,"GeneratorFunction"),_regeneratorDefine2(d),_regeneratorDefine2(d,s,"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 s=Object.defineProperty;try{s({},"",{})}catch(e){s=0}_regeneratorDefine2=function(e,t,n,i){function o(t,n){_regeneratorDefine2(e,t,function(e){return this._invoke(t,n,e)})}t?s?s(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,s,o,a){try{var r=e[o](a),c=r.value}catch(e){return void n(e)}r.done?t(c):Promise.resolve(c).then(i,s)}function _asyncToGenerator(e){return function(){var t=this,n=arguments;return new Promise(function(i,s){var o=e.apply(t,n);function a(e){asyncGeneratorStep(o,i,s,a,r,"next",e)}function r(e){asyncGeneratorStep(o,i,s,a,r,"throw",e)}a(void 0)})}}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,s=function(){};return{s:s,n:function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}},e:function(e){throw e},f:s}}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,a=!0,r=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return a=e.done,e},e:function(e){r=!0,o=e},f:function(){try{a||null==n.return||n.return()}finally{if(r)throw o}}}}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 _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,s,o,a,r=[],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)&&(r.push(i.value),r.length!==t);c=!0);}catch(e){l=!0,s=e}finally{try{if(!c&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(l)throw s}}return r}}function _arrayWithHoles(e){if(Array.isArray(e))return e}function _typeof(e){return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof(e)}window.openAIChatManager=function(){var e={generatedImageAltText:"Generated Image",generatedImageMaxWidth:400,downloadImageTitle:"Download image",downloadChartTitle:"Download chart as image",downloadChartButtonText:"Download",userLabel:"You",assistantLabel:"Assistant",thumbsUpTitle:"Thumbs up",thumbsDownTitle:"Thumbs down",copyTitle:"Click here to copy response to clipboard.",codeCopiedText:"Copied!",widget:{chatWidgetContainer:null,chatWidgetStateName:null,chatHistorySection:null,showHistoryButton:null,closeHistoryButton:null,newChatButton:null,toggleButtonSelector:null,resetSizeButtonSelector:null,dragHandleSelector:".ai-chat-widget-header",enableDragging:!0,enableResizing:!0,persistLayout:!0,defaultWidth:null,defaultHeight:null,minWidth:320,minHeight:420},messageTemplate:'\n <div class="ai-chat-messages">\n <div v-for="(message, index) in messages" :key="\'msg-\' + index" class="ai-chat-message-item">\n <div>\n <div v-if="message.role === \'user\'" class="ai-chat-msg-role ai-chat-msg-role-user">{{ userLabel }}</div>\n <div v-else-if="message.role !== \'indicator\'" :class="getAssistantRoleClasses(message)">\n <span :class="getAssistantIconClasses(message, index)"><span :class="getAssistantIcon(message)"></span></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 <span class="message-buttons-container" v-if="!isIndicator(message)">\n <template v-if="metricsEnabled && message.role === \'assistant\'">\n <span class="ai-chat-message-assistant-feedback" :data-message-id="message.id">\n <button class="btn btn-sm btn-link text-success p-0 me-2 button-message-toolbox rate-up-btn" @click="rateMessage(message, true, $event)" :title="thumbsUpTitle">\n <span class="fa-regular fa-thumbs-up"></span>\n </button>\n <button class="btn btn-sm btn-link text-danger p-0 me-2 button-message-toolbox rate-down-btn" @click="rateMessage(message, false, $event)" :title="thumbsDownTitle">\n <span class="fa-regular fa-thumbs-down"></span>\n </button>\n </span>\n </template>\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 <span :class="ttsPlayingMessageIndex === index ? \'fa-solid fa-circle-pause\' : \'fa-solid fa-circle-play\'"></span>\n </button>\n <button class="btn btn-sm btn-link text-secondary p-0 button-message-toolbox" @click="copyResponse(message.content)" :title="copyTitle">\n <span class="fa-solid fa-copy"></span>\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 <span v-if="notification.icon" :class="notification.icon" class="ai-chat-notification-icon"></span>\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 <span class="fa-solid fa-xmark"></span>\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 <span v-if="action.icon" :class="action.icon" class="me-1"></span>\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"><span class="fa fa-robot" style="display: inline-block;"></span></span>\n Assistant\n </div>\n '};function t(e){if(!e)return"";var t=e.trim();return/^javascript:/i.test(t)||/^vbscript:/i.test(t)||/^data:text\/html/i.test(t)?"":e}function n(e){var t=document.createElement("span");return t.textContent=e,t.innerHTML}function i(e){var t,n,i,s,o,a;if(!e||"object"!==_typeof(e))return null;var r=Object.assign({},e);return r.index=null!==(t=null!==(n=r.index)&&void 0!==n?n:r.Index)&&void 0!==t?t:0,r.text=null!==(i=null!==(s=r.text)&&void 0!==s?s:r.Text)&&void 0!==i?i:null,r.link=null!==(o=null!==(a=r.link)&&void 0!==a?a:r.Link)&&void 0!==o?o:null,r}function s(e){if(!e||"object"!==_typeof(e))return{};for(var t={},n=0,s=Object.entries(e);n<s.length;n++){var o,a=_slicedToArray(s[n],2),r=a[0],c=a[1];t[r]=null!==(o=i(c))&&void 0!==o?o:{}}return t}var o=new marked.Renderer;o.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||""},o.code=function(e){var t=e.text||"",i=(e.lang||"").trim(),s=t;if("undefined"!=typeof hljs)if(i&&hljs.getLanguage(i))try{s=hljs.highlight(t,{language:i}).value}catch(e){}else try{s=hljs.highlightAuto(t).value}catch(e){}else s=n(t);var o=i?n(i):"code";return'<div class="ai-code-block"><div class="ai-code-header"><span class="ai-code-lang"><span class="fa-solid fa-code"></span> '.concat(o,'</span><button type="button" class="ai-code-copy-btn" title="Copy code"><span class="fa-regular fa-copy"></span></button></div><pre><code class="hljs').concat(i?" language-"+i:"",'">').concat(s,"</code></pre></div>")},o.image=function(n){var i=t(n.href);if(!i)return"";var s=n.text||e.generatedImageAltText,o=e.generatedImageMaxWidth;return'<div class="generated-image-container">\n <img src="'.concat(i,'" alt="').concat(s,'" 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(s,'" title="').concat(e.downloadImageTitle,'" class="btn btn-sm btn-outline-secondary ai-download-image">\n <span class="fa-solid fa-download"></span>\n </a>\n </div>\n </div>')};var a=0,r=[];function c(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;l(i.chartId,i.config)}}catch(e){n.e(e)}finally{n.f()}})}}function l(e,t){var n=document.getElementById(e);if(!n)return!1;if("undefined"==typeof Chart)return console.warn('Chart.js is not loaded. To render interactive charts, include the Chart.js library on the page (e.g., <script src="https://cdn.jsdelivr.net/npm/chart.js@4/dist/chart.umd.min.js"><\/script>).'),!1;if(null===n.offsetParent)return window.__chartConfigs[e]=t,!1;try{var i,s,o;n._chartInstance&&n._chartInstance.destroy();var a="string"==typeof t?JSON.parse(t):t;return null!==(i=a.options)&&void 0!==i||(a.options={}),a.options.responsive=!0,a.options.maintainAspectRatio=!0,null!==(o=(s=a.options).aspectRatio)&&void 0!==o||(s.aspectRatio=4/3),n._chartInstance=new Chart(n,a),delete window.__chartConfigs[e],!0}catch(e){return console.error("Error creating chart:",e),!1}}function u(e,t){r=[];var n=marked.parse(e,{renderer:o});return t._pendingCharts=r.length>0?_toConsumableArray(r):[],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,s=i;for(;s<e.length&&(" "===e[s]||"\n"===e[s]||"\r"===e[s]||"\t"===e[s]);)s++;if(s>=e.length||"{"!==e[s])return null;for(var o=0,a=!1,r=!1;s<e.length;s++){var c=e[s];if(a){if(r){r=!1;continue}if("\\"===c){r=!0;continue}'"'===c&&(a=!1)}else if('"'!==c){if("{"===c)o++;else if("}"===c&&0===--o){var l=s,u=e.indexOf("]",l+1);return u<0?null:{startIndex:n,endIndex:u+1,json:e.substring(i,l+1).trim()}}}else a=!0}return null}(e);if(t&&0===t.startIndex){var n="chat_chart_".concat(++a);return{type:"chart",raw:e.substring(0,t.endIndex),chartId:n,json:t.json}}},renderer:function(t){return r.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,'">')+'<span class="fa-solid fa-download"></span> '.concat(e.downloadChartButtonText)+"</button></div>";var n}}]}),window.renderPendingCharts=function(){if("undefined"!=typeof Chart){var e=window.__chartConfigs;e&&requestAnimationFrame(function(){for(var t=0,n=Object.keys(e);t<n.length;t++){var i=n[t];l(i,e[i])}})}};return{initialize:function(t){var n=Object.assign({},e,t);n.widget=Object.assign({},e.widget||{},t&&t.widget?t.widget:{});var o=!!(t&&t.widget&&t.widget.chatWidgetContainer&&t.widget.chatWidgetStateName),a=window.openAIChatWidgetBehavior||null;if(e=n,n.signalRHubUrl)if(n.appElementSelector)if(n.chatContainerElementSelector)if(n.inputElementSelector){if(n.sendButtonElementSelector){var r={data:function(){return{inputElement:null,buttonElement:null,chatContainer:null,placeholder:null,isSessionStarted:!1,isPlaceholderVisible:!0,isStreaming:!1,isNavigatingAway:!1,autoScroll:!0,stream:null,messages:[],notifications:[],prompt:"",documents:n.existingDocuments||[],isUploading:!1,isDocumentOperationPending:!1,documentOperationQueue:null,uploadErrors:[],isDragOver:!1,documentBar:null,metricsEnabled:!!n.metricsEnabled,userLabel:n.userLabel,assistantLabel:n.assistantLabel,thumbsUpTitle:n.thumbsUpTitle,thumbsDownTitle:n.thumbsDownTitle,copyTitle:n.copyTitle,isRecording:!1,mediaRecorder:null,preRecordingPrompt:"",micButton:null,speechToTextEnabled:"AudioInput"===n.chatMode||"Conversation"===n.chatMode,textToSpeechEnabled:"Conversation"===n.chatMode||!!n.textToSpeechEnabled,ttsVoiceName:n.ttsVoiceName||null,audioChunks:[],audioPlayQueue:[],isPlayingAudio:!1,currentAudioElement:null,currentAudioUrl:null,ttsButton:null,ttsPlayingMessageIndex:-1,ttsAudioCache:{},ttsInstanceId:"ai-chat-"+Math.random().toString(36).slice(2),singleResponseMode:!!n.singleResponseMode,conversationModeEnabled:"Conversation"===n.chatMode,conversationButton:null,isConversationMode:!1,notificationDismissTimers:{},pendingSessionPromise:null,pendingSessionResolver:null,pendingSessionRejector:null,pendingSessionTimeoutId:null}},computed:{lastAssistantIndex:function(){for(var e=this.messages.length-1;e>=0;e--)if("assistant"===this.messages[e].role)return e;return-1}},methods:{handleBeforeUnload:function(){this.isNavigatingAway=!0},handleDragOver:function(e){if(n.sessionDocumentsEnabled){e.preventDefault(),e.stopPropagation(),this.isDragOver=!0;var t=this.inputElement?this.inputElement.closest(".ai-admin-widget-input, .text-bg-light"):null;t&&t.classList.add("ai-chat-drag-over")}},handleDragLeave:function(e){if(n.sessionDocumentsEnabled){e.preventDefault(),e.stopPropagation(),this.isDragOver=!1;var t=this.inputElement?this.inputElement.closest(".ai-admin-widget-input, .text-bg-light"):null;t&&t.classList.remove("ai-chat-drag-over")}},handleDrop:function(e){if(n.sessionDocumentsEnabled){e.preventDefault(),e.stopPropagation(),this.isDragOver=!1;var t=this.inputElement?this.inputElement.closest(".ai-admin-widget-input, .text-bg-light"):null;t&&t.classList.remove("ai-chat-drag-over"),e.dataTransfer&&e.dataTransfer.files&&e.dataTransfer.files.length>0&&this.uploadFiles(Array.from(e.dataTransfer.files))}},triggerFileInput:function(){if(n.sessionDocumentsEnabled&&!this.isDocumentOperationPending){var e=document.getElementById("ai-chat-doc-input");e&&e.click()}},handleFileInputChange:function(e){var t=e.target.files?Array.from(e.target.files):[];t&&t.length>0&&this.uploadFiles(t),e.target.value=""},queueDocumentOperation:function(e){var t=this,n=(this.documentOperationQueue||Promise.resolve()).catch(function(){}).then(_asyncToGenerator(_regenerator().m(function n(){return _regenerator().w(function(n){for(;;)switch(n.p=n.n){case 0:return t.isDocumentOperationPending=!0,n.p=1,n.n=2,e();case 2:return n.a(2,n.v);case 3:return n.p=3,t.isDocumentOperationPending=!1,n.f(3);case 4:return n.a(2)}},n,null,[[1,,3,4]])})));return this.documentOperationQueue=n.finally(function(){t.documentOperationQueue===n&&(t.documentOperationQueue=null)}),this.documentOperationQueue},uploadFiles:function(e){var t=this;return _asyncToGenerator(_regenerator().m(function i(){var s;return _regenerator().w(function(i){for(;;)switch(i.n){case 0:if(n.uploadDocumentUrl){i.n=1;break}return i.a(2);case 1:if(0!==(s=Array.isArray(e)?e.slice():Array.from(e||[])).length){i.n=2;break}return i.a(2);case 2:return i.a(2,t.queueDocumentOperation(_asyncToGenerator(_regenerator().m(function e(){var i,o,a,r,c,l,u,d,h,p;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:if(i=t.getSessionId(),o=t.getProfileId(),i){e.n=4;break}return e.p=1,e.n=2,t.ensureSessionForDocuments(o);case 2:i=e.v,e.n=4;break;case 3:return e.p=3,h=e.v,console.error("Failed to create a chat session for document upload:",h),t.uploadErrors=[{fileName:"",error:"Could not create a chat session for the upload."}],t.renderDocumentBar(),e.a(2);case 4:if(i){e.n=5;break}return console.warn("Cannot upload documents without a session or profile."),t.uploadErrors=[{fileName:"",error:"Could not create a chat session for the upload."}],t.renderDocumentBar(),e.a(2);case 5:for(t.isUploading=!0,t.uploadErrors=[],t.renderDocumentBar(),e.p=6,(a=new FormData).append("sessionId",i),r=0;r<s.length;r++)a.append("files",s[r]);return e.n=7,fetch(n.uploadDocumentUrl,{method:"POST",body:a});case 7:if((c=e.v).ok){e.n=9;break}return e.n=8,c.text();case 8:return l=e.v,u=t.extractReadableErrorMessage(l,"Upload failed. Please try again."),console.error("Upload failed:",l),t.uploadErrors=[{fileName:"",error:u}],e.a(2);case 9:return e.n=10,c.json();case 10:(d=e.v).sessionId&&d.sessionId!==t.getSessionId()&&t.initializeSession(d.sessionId),Array.isArray(d.documents)?t.documents=d.documents:d.uploaded&&d.uploaded.length>0&&(t.documents=t.documents.concat(d.uploaded)),d.failed&&d.failed.length>0&&(t.uploadErrors=d.failed),e.n=12;break;case 11:e.p=11,p=e.v,console.error("Upload error:",p),t.uploadErrors=[{fileName:"",error:"Upload failed. Please try again."}],t.getSessionId()&&t.reloadCurrentSession();case 12:return e.p=12,t.isUploading=!1,t.renderDocumentBar(),e.f(12);case 13:return e.a(2)}},e,null,[[6,11,12,13],[1,3]])}))))}},i)}))()},removeDocument:function(e){var t=this;return _asyncToGenerator(_regenerator().m(function i(){return _regenerator().w(function(i){for(;;)switch(i.n){case 0:if(n.removeDocumentUrl){i.n=1;break}return i.a(2);case 1:return i.a(2,t.queueDocumentOperation(_asyncToGenerator(_regenerator().m(function i(){var s,o,a,r,c,l,u;return _regenerator().w(function(i){for(;;)switch(i.p=i.n){case 0:return i.p=0,s=t.getSessionId(),i.n=1,fetch(n.removeDocumentUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({itemId:s,documentId:e.documentId})});case 1:if(!(o=i.v).ok){i.n=3;break}return i.n=2,o.json();case 2:a=i.v,Array.isArray(a.documents)?t.documents=a.documents:(r=t.documents.indexOf(e))>-1&&t.documents.splice(r,1),i.n=5;break;case 3:return i.n=4,o.text();case 4:c=i.v,l=t.extractReadableErrorMessage(c,"Failed to remove document. Please try again."),console.error("Failed to remove document:",o.status,c),t.uploadErrors=[{fileName:e.fileName||"",error:l}],s&&t.reloadCurrentSession(),t.renderDocumentBar();case 5:i.n=7;break;case 6:i.p=6,u=i.v,console.error("Remove document error:",u),t.uploadErrors=[{fileName:e.fileName||"",error:"Failed to remove document. Please try again."}],t.getSessionId()&&t.reloadCurrentSession(),t.renderDocumentBar();case 7:return i.a(2)}},i,null,[[0,6]])}))))}},i)}))()},formatFileSize:function(e){return e<1024?e+" B":e<1048576?(e/1024).toFixed(1)+" KB":(e/1048576).toFixed(1)+" MB"},renderDocumentBar:function(){if(this.documentBar)if(n.sessionDocumentsEnabled){this.documentBar.classList.remove("d-none");var e='<div class="ai-chat-doc-bar p-2">';e+='<div class="d-flex flex-wrap align-items-center gap-1">';for(var t=0;t<this.documents.length;t++){var i=this.documents[t],s=i.fileName||"Document";s.length>20&&(s=s.substring(0,17)+"..."),e+='<span class="badge bg-secondary bg-opacity-25 text-dark d-inline-flex align-items-center gap-1 px-2 py-1" style="font-size: 0.8rem;" title="'+this.escapeHtml(i.fileName||"")+'">',e+='<span class="fa-solid fa-file-lines" style="font-size: 0.7rem;"></span> ',e+=this.escapeHtml(s),e+=' <button type="button" class="btn-close btn-close-sm ms-1" style="font-size: 0.5rem;" data-doc-index="'+t+'" aria-label="Remove"'+(this.isDocumentOperationPending?" disabled":"")+"></button>",e+="</span>"}for(var o=0;o<this.uploadErrors.length;o++){var a=this.uploadErrors[o],r=a.fileName||"File",c=a.error||"Upload failed";r.length>15&&(r=r.substring(0,12)+"..."),e+='<span class="badge bg-danger bg-opacity-25 text-danger d-inline-flex align-items-center gap-1 px-2 py-1" style="font-size: 0.8rem;" title="'+this.escapeHtml((a.fileName||"")+": "+c)+'">',e+='<span class="fa-solid fa-circle-exclamation" style="font-size: 0.7rem;"></span> ',e+=this.escapeHtml(r),e+=' <button type="button" class="btn-close btn-close-sm ms-1" style="font-size: 0.5rem;" data-error-index="'+o+'" aria-label="Dismiss"></button>',e+="</span>"}this.isUploading&&(e+='<span class="badge bg-info bg-opacity-25 text-dark d-inline-flex align-items-center gap-1 px-2 py-1" style="font-size: 0.8rem;">',e+='<span class="spinner-border spinner-border-sm" style="width: 0.7rem; height: 0.7rem;"></span> Uploading...',e+="</span>"),e+='<button type="button" class="btn btn-sm btn-outline-secondary rounded-pill ai-chat-doc-add-btn d-inline-flex align-items-center gap-1" style="font-size: 0.75rem; padding: 0.15rem 0.5rem;" title="Attach documents"'+(this.isDocumentOperationPending?" disabled":"")+">",e+='<span class="fa-solid fa-paperclip"></span>',0!==this.documents.length||this.isUploading||(e+=" <span>Attach files</span>"),e+="</button>",e+="</div>",n.supportedExtensionsText&&(e+='<div class="small text-muted mt-2">Supported formats: '+this.escapeHtml(n.supportedExtensionsText)+"</div>"),e+="</div>",this.documentBar.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0}));for(var l=this,u=this.documentBar.querySelectorAll("[data-doc-index]"),d=0;d<u.length;d++)u[d].addEventListener("click",function(e){return function(t){if(t.preventDefault(),t.stopPropagation(),!l.isDocumentOperationPending){var n=l.documents[e];n&&l.removeDocument(n)}}}(parseInt(u[d].getAttribute("data-doc-index"))));for(var h=this.documentBar.querySelectorAll("[data-error-index]"),p=0;p<h.length;p++)h[p].addEventListener("click",function(e){return function(t){t.preventDefault(),t.stopPropagation(),l.uploadErrors.splice(e,1),l.renderDocumentBar()}}(parseInt(h[p].getAttribute("data-error-index"))));var f=this.documentBar.querySelector(".ai-chat-doc-add-btn");f&&f.addEventListener("click",function(e){e.preventDefault(),l.isDocumentOperationPending||l.triggerFileInput()})}else this.documentBar.classList.add("d-none")},escapeHtml:function(e){var t=document.createElement("div");return t.textContent=e,t.innerHTML},extractReadableErrorMessage:function(e,t){if(!e||"string"!=typeof e)return t;var n=e.trim();if(!n)return t;if(n.startsWith("{")||n.startsWith("["))try{var i=JSON.parse(n),s=(null==i?void 0:i.error)||(null==i?void 0:i.message)||(null==i?void 0:i.title)||(null==i?void 0:i.detail);return"string"==typeof s&&s.trim()?s.trim():t}catch(e){return t}return/<[^>]+>/.test(n)?t:n},normalizeAssistantAppearance:function(e){if(!e)return null;var t="string"==typeof e.label?e.label.trim():"",n="string"==typeof e.icon?e.icon.trim():"",i="string"==typeof e.cssClass?e.cssClass.trim():"",s=!!e.disableStreamingAnimation;return t||n||i||s?{label:t,icon:n,cssClass:i,disableStreamingAnimation:s}:null},getAssistantLabel:function(e){var t=e?this.normalizeAssistantAppearance(e.appearance):null;return t&&t.label?t.label:this.assistantLabel},getAssistantRoleClasses:function(e){var t=e?this.normalizeAssistantAppearance(e.appearance):null,n=["ai-chat-msg-role"];return t&&t.cssClass?n.push(t.cssClass):n.push("ai-chat-msg-role-assistant"),n},getAssistantIconClasses:function(e,t){var n=e?this.normalizeAssistantAppearance(e.appearance):null;return[this.shouldAnimateAssistantIcon(e,t)?"ai-streaming-icon":"ai-bot-icon",n&&n.cssClass?n.cssClass:""]},getAssistantIcon:function(e){var t=e?this.normalizeAssistantAppearance(e.appearance):null;return t&&t.icon?t.icon:"fa fa-robot"},shouldAnimateAssistantIcon:function(e,t){var n=e?this.normalizeAssistantAppearance(e.appearance):null;return!!e&&e.isStreaming&&t===this.lastAssistantIndex&&!(n&&n.disableStreamingAnimation)},startConnection:function(){var e=this;return _asyncToGenerator(_regenerator().m(function t(){var i;return _regenerator().w(function(t){for(;;)switch(t.p=t.n){case 0:return e.connection=(new signalR.HubConnectionBuilder).withUrl(n.signalRHubUrl).withAutomaticReconnect().build(),e.connection.serverTimeoutInMilliseconds=6e5,e.connection.keepAliveIntervalInMilliseconds=15e3,e.connection.on("LoadSession",function(t){var i;e.initializeSession(t.sessionId,!0),e.messages=[],e.documents=t.documents||[],e.uploadErrors=[],(null!==(i=t.messages)&&void 0!==i?i:[]).forEach(function(t){e.addMessage(t),e.$nextTick(function(){c(t)})}),e.$nextTick(function(){e.refreshAllFeedbackIcons()}),0===e.messages.length&&n.initialPrompt&&(e.prompt=n.initialPrompt,e.sendMessage())}),e.connection.on("ReceiveError",function(t){console.error("SignalR Error: ",t),e.isRecording&&e.stopRecording(),a&&"function"==typeof a.handleReceiveError&&a.handleReceiveError(e,t,n)}),e.connection.on("MessageRated",function(t,n){var i=e.messages.find(function(e){return e.id===t});i&&(i.userRating=n)}),e.connection.on("ReceiveTranscript",function(t,n,i){if(e.isConversationMode){if(!i&&n){e._conversationPartialTranscript=n;var s='<p class="ai-partial-transcript">'+n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")+"</p>";e._conversationPartialMessage?(e._conversationPartialMessage.content=n,e._conversationPartialMessage.htmlContent=s):(e.hidePlaceholder(),e._conversationPartialMessage={role:"user",content:n,htmlContent:s,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 s=n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");e._conversationPartialMessage.content=n,e._conversationPartialMessage.htmlContent="<p>"+s+"</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,s,o){if(!e._conversationAssistantMessage){e.stopAudio(),e.hideTypingIndicator();for(var a=0;a<e.messages.length;a++)e.messages[a].isStreaming&&(e.messages[a].isStreaming=!1);var r=e.messages.length,l={id:n,role:"assistant",content:"",htmlContent:"",isStreaming:!0,userRating:null,appearance:e.normalizeAssistantAppearance(o)};e.messages.push(l),e._conversationAssistantMessage={index:r,content:""}}e._conversationAssistantMessage.content+=i;var d=e.messages[e._conversationAssistantMessage.index];d&&(d.appearance||(d.appearance=e.normalizeAssistantAppearance(o)),d.content=e._conversationAssistantMessage.content,d.htmlContent=u(d.content,d),e.$nextTick(function(){c(d),e.scrollToBottom()}))}),e.connection.on("ReceiveConversationAssistantComplete",function(t,n){if(e._conversationAssistantMessage){var i=e.messages[e._conversationAssistantMessage.index];i&&(i.isStreaming=!1),e._conversationAssistantMessage=null}}),e.connection.on("ReceiveAudioChunk",function(t,n,i){if(n){for(var s=atob(n),o=new Uint8Array(s.length),a=0;a<s.length;a++)o[a]=s.charCodeAt(a);e.audioChunks.push(o)}}),e.connection.on("ReceiveAudioComplete",function(t){e.playCollectedAudio()}),e.connection.on("ReceiveNotification",function(t){e.receiveNotification(t)}),e.connection.on("UpdateNotification",function(t){e.updateNotification(t)}),e.connection.on("RemoveNotification",function(t){e.removeNotification(t)}),e.connection.onreconnecting(function(){console.warn("SignalR: reconnecting...")}),e.connection.onreconnected(function(){console.info("SignalR: reconnected."),e.isSessionStarted?e.reloadCurrentSession():n.autoCreateSession&&e.startNewSession()}),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,i=t.v,console.error("SignalR Connection Error: ",i);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=u(e.content,e)),this.fireEvent(new CustomEvent("addingOpenAIPromotMessage",{detail:{message:e}})),this.messages.push(e),this.$nextTick(function(){t.fireEvent(new CustomEvent("addedOpenAIPromotMessage",{detail:{message:e}}))})},addMessage:function(e){var t=this;if(void 0===e.userRating&&(e.userRating=null),e.content){var n=e.content.trim();if(e.references=s(e.references),e.references&&"object"===_typeof(e.references)&&Object.keys(e.references).length){var i=Object.entries(e.references).filter(function(e){var t=_slicedToArray(e,1)[0];return n.includes(t)});if(i.length){i.sort(function(e,t){var n=_slicedToArray(e,2)[1],i=_slicedToArray(t,2)[1];return n.index-i.index});var o,a=1,r=_createForOfIteratorHelper(i);try{for(r.s();!(o=r.n()).done;){var l=_slicedToArray(o.value,2),d=l[0],h=l[1],p="__CITE_".concat(h.index,"__");n=n.replaceAll(d,p),h._displayIndex=a++,h._placeholder=p}}catch(e){r.e(e)}finally{r.f()}var f,m=_createForOfIteratorHelper(i);try{for(m.s();!(f=m.n()).done;){var g=_slicedToArray(f.value,2)[1];n=n.replaceAll(g._placeholder,"<sup><strong>".concat(g._displayIndex,"</strong></sup>"))}}catch(e){m.e(e)}finally{m.f()}n=n.replaceAll("</strong></sup><sup>","</strong></sup><sup>,</sup><sup>"),n+="<br><br>";var v,y=_createForOfIteratorHelper(i);try{for(y.s();!(v=y.n()).done;){var b=_slicedToArray(v.value,2),S=b[0],A=b[1],E=A.text||S;n+=A.link?"**".concat(A._displayIndex,"**. [").concat(E,"](").concat(A.link,")<br>"):"**".concat(A._displayIndex,"**. ").concat(E,"<br>")}}catch(e){y.e(e)}finally{y.f()}}}e.content=n,e.htmlContent=u(n,e)}this.addMessageInternal(e),this.hidePlaceholder(),this.$nextTick(function(){c(e),t.scrollToBottom()})},addMessages:function(e){for(var t=this,n=0;n<e.length;n++)this.addMessageInternal(e[n]);this.hidePlaceholder(),this.$nextTick(function(){t.scrollToBottom()})},hidePlaceholder:function(){this.placeholder&&this.placeholder.classList.add("d-none"),this.isPlaceholderVisible=!1},showPlaceholder:function(){this.placeholder&&this.placeholder.classList.remove("d-none"),this.isPlaceholderVisible=!0},isOrchestratorAvailable:function(){return!1!==n.isOrchestratorAvailable},applyOrchestratorAvailability:function(){if(this.isOrchestratorAvailable())return!0;var e=n.orchestratorUnavailableMessage||"This orchestrator is not currently available.";return this.inputElement&&(this.inputElement.disabled=!0,this.inputElement.value="",this.inputElement.placeholder=e),this.buttonElement&&(this.buttonElement.disabled=!0),this.micButtonElement&&(this.micButtonElement.disabled=!0,this.micButtonElement.style.display="none"),this.conversationButtonElement&&(this.conversationButtonElement.disabled=!0,this.conversationButtonElement.style.display="none"),!1},fireEvent:function(e){document.dispatchEvent(e)},isIndicator:function(e){return"indicator"===e.role},sendMessage:function(){if(this.applyOrchestratorAvailability()){var e=this.prompt.trim();e&&(this.isRecording&&this.stopRecording(),this._audioInputSent=!0,this.singleResponseMode&&this.messages.splice(0,this.messages.length),this.addMessage({role:"user",content:e}),this.streamMessage(this.getProfileId(),e,null),this.inputElement.value="",this.prompt="")}},startRecording:function(){var e=this;!this.isRecording&&this.connection&&navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}}).then(function(t){var n=MediaRecorder.isTypeSupported("audio/ogg;codecs=opus")?"audio/ogg;codecs=opus":MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":"audio/webm";e.mediaRecorder=new MediaRecorder(t,{mimeType:n,audioBitsPerSecond:128e3}),e.preRecordingPrompt=e.prompt,e._audioInputSent=!1;var i=new signalR.Subject,s=e.getProfileId(),o=e.getSessionId()||"",a=Promise.resolve();e.mediaRecorder.addEventListener("dataavailable",function(e){e.data&&e.data.size>0&&(a=a.then(_asyncToGenerator(_regenerator().m(function t(){var n,s,o,a;return _regenerator().w(function(t){for(;;)switch(t.n){case 0:return t.n=1,e.data.arrayBuffer();case 1:n=t.v,s=new Uint8Array(n),o=s.reduce(function(e,t){return e+String.fromCharCode(t)},""),a=btoa(o),i.next(a);case 2:return t.a(2)}},t)}))))}),e.mediaRecorder.addEventListener("stop",function(){t.getTracks().forEach(function(e){return e.stop()}),a.then(function(){return i.complete()})});var r=navigator.language||document.documentElement.lang||"en-US";e.connection.send("SendAudioStream",s,o,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='<span class="fa-solid fa-stop"></span>'):(this.micButton.classList.remove("stt-recording"),this.micButton.innerHTML='<span class="fa-solid fa-microphone"></span>'))},streamMessage:function(e,t,n){var s=this;this.stream&&(this.stream.dispose(),this.stream=null),this.streamingStarted(),this.showTypingIndicator(),this.autoScroll=!0;var o="",a={},r=null,l=this.messages.length,d=this.getSessionId();this.stream=this.connection.stream("SendMessage",e,t,d,n).subscribe({next:function(e){var t=s.messages[l];if(!t){e.sessionId&&!d&&s.initializeSession(e.sessionId),s.hideTypingIndicator(),l=s.messages.length;var n={id:e.messageId,role:"assistant",title:e.title,content:"",htmlContent:"",isStreaming:!0,userRating:null};s.messages.push(n),t=n}if(!e.title||t.title&&t.title===e.title||(t.title=e.title),e.references&&"object"===_typeof(e.references)&&Object.keys(e.references).length)for(var h=0,p=Object.entries(e.references);h<p.length;h++){var f,m=_slicedToArray(p[h],2),g=m[0],v=m[1];a[g]=null!==(f=i(v))&&void 0!==f?f:{}}if(e.content){e.responseId&&r&&e.responseId!==r&&(o+="\n\n"),e.responseId&&(r=e.responseId);for(var y=e.content,b=0,S=Object.entries(a);b<S.length;b++){var A=_slicedToArray(S[b],2),E=A[0],_=A[1];y=y.replaceAll(E,"<sup><strong>".concat(_.index,"</strong></sup>"))}o+=y.replaceAll("</strong></sup><sup>","</strong></sup><sup>,</sup><sup>")}t.content=o,t.htmlContent=u(o,t),s.messages[l]=t,s.$nextTick(function(){c(t),s.scrollToBottom()})},complete:function(){var e;s.processReferences(a,l),s.streamingFinished();var t=s.messages[l];t&&(t.isStreaming=!1),t&&t.content||s.hideTypingIndicator(),s.isConversationMode&&s.textToSpeechEnabled&&t&&t.content&&s.synthesizeSpeech(t.content),null===(e=s.stream)||void 0===e||e.dispose(),s.stream=null},error:function(e){var t;s.processReferences(a,l),s.streamingFinished();var n=s.messages[l];n&&(n.isStreaming=!1),s.hideTypingIndicator(),s.isNavigatingAway||s.addMessage(s.getServiceDownMessage()),null===(t=s.stream)||void 0===t||t.dispose(),s.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=this.messages[t],o=i.content||"",a=Object.entries(e).filter(function(e){var t=_slicedToArray(e,2),n=t[0],i=t[1];return o.includes(n)||o.includes("<sup><strong>".concat(i.index,"</strong></sup>"))});if(!a.length)return;a.sort(function(e,t){var n=_slicedToArray(e,2)[1],i=_slicedToArray(t,2)[1];return n.index-i.index});var r,l=o.trim(),d=1,h=_createForOfIteratorHelper(a);try{for(h.s();!(r=h.n()).done;){var p=_slicedToArray(r.value,2),f=p[0],m=p[1],g="__CITE_".concat(m.index,"__");l=(l=l.replaceAll(f,g)).replaceAll("<sup><strong>".concat(m.index,"</strong></sup>"),g),m._displayIndex=d++,m._placeholder=g}}catch(e){h.e(e)}finally{h.f()}var v,y=_createForOfIteratorHelper(a);try{for(y.s();!(v=y.n()).done;){var b=_slicedToArray(v.value,2)[1];l=l.replaceAll(b._placeholder,"<sup><strong>".concat(b._displayIndex,"</strong></sup>"))}}catch(e){y.e(e)}finally{y.f()}l=l.replaceAll("</strong></sup><sup>","</strong></sup><sup>,</sup><sup>"),l+="<br><br>";var S,A=_createForOfIteratorHelper(a);try{for(A.s();!(S=A.n()).done;){var E=_slicedToArray(S.value,2),_=E[0],T=E[1],C=T.text||_;l+=T.link?"**".concat(T._displayIndex,"**. [").concat(C,"](").concat(T.link,")<br>"):"**".concat(T._displayIndex,"**. ").concat(C,"<br>")}}catch(e){A.e(e)}finally{A.f()}i.content=l,i.htmlContent=u(l,i),this.messages[t]=i,this.$nextTick(function(){c(i),n.scrollToBottom()})}},streamingStarted:function(){var e=this.buttonElement.getAttribute("data-stop-icon");e&&this.buttonElement.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0})),this.inputElement&&this.inputElement.setAttribute("disabled","disabled")},streamingFinished:function(){var e=this.buttonElement.getAttribute("data-start-icon");if(e&&this.buttonElement.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0})),this.inputElement&&(this.inputElement.removeAttribute("disabled"),this.inputElement.focus()),this.chatContainer)for(var t=this.chatContainer.querySelectorAll(".ai-streaming-icon"),n=0;n<t.length;n++)t[n].classList.remove("ai-streaming-icon"),t[n].classList.add("ai-bot-icon");for(n=0;n<this.messages.length;n++)this.messages[n].isStreaming&&(this.messages[n].isStreaming=!1)},handleExternalTtsStop:function(e){var t;(null==e||null===(t=e.detail)||void 0===t?void 0:t.sourceId)!==this.ttsInstanceId&&this.stopAudio(!1)},updateTtsPlaybackButtons:function(){var e=this;this.chatContainer&&this.chatContainer.querySelectorAll("[data-tts-message-index]").forEach(function(t){var n=Number(t.getAttribute("data-tts-message-index"))===e.ttsPlayingMessageIndex,i=n?'<span class="fa-solid fa-circle-pause"></span>':'<span class="fa-solid fa-circle-play"></span>';t.classList.toggle("tts-playing",n),t.setAttribute("title",n?"Pause audio":"Read aloud"),t.replaceChildren(DOMPurify.sanitize(i,{RETURN_DOM_FRAGMENT:!0}))})},synthesizeSpeech:function(e,t){var n=this;this.textToSpeechEnabled&&e&&this.connection&&(this.audioChunks=[],this.isPlayingAudio=!0,this._ttsCacheIndex=void 0!==t?t:-1,this.connection.invoke("SynthesizeSpeech",this.getProfileId(),this.getSessionId(),e,this.ttsVoiceName).catch(function(e){console.error("TTS synthesis error:",e),n.isPlayingAudio=!1,n.ttsPlayingMessageIndex=-1,n._ttsCacheIndex=-1,n.$nextTick(function(){return n.updateTtsPlaybackButtons()})}))},toggleMessageTts:function(e,t){var n=this;this.ttsPlayingMessageIndex!==t?(this.stopAudio(!1),window.dispatchEvent(new CustomEvent("crestapps-ai-chat-stop-tts",{detail:{sourceId:this.ttsInstanceId}})),this.ttsPlayingMessageIndex=t,this.$nextTick(function(){return n.updateTtsPlaybackButtons()}),this.ttsAudioCache[t]?this.playAudioBlob(this.ttsAudioCache[t]):this.synthesizeSpeech(e.content,t)):this.stopAudio()},playCollectedAudio:function(){var e=this;if(0!==this.audioChunks.length){var t,n=this.audioChunks.reduce(function(e,t){return e+t.length},0),i=new Uint8Array(n),s=0,o=_createForOfIteratorHelper(this.audioChunks);try{for(o.s();!(t=o.n()).done;){var a=t.value;i.set(a,s),s+=a.length}}catch(e){o.e(e)}finally{o.f()}this.audioChunks=[];var r=new Blob([i],{type:"audio/mp3"});this._ttsCacheIndex>=0&&(this.ttsAudioCache[this._ttsCacheIndex]=r,this._ttsCacheIndex=-1),this.currentAudioElement?this.audioPlayQueue.push(r):this.playAudioBlob(r)}else this.currentAudioElement||0!==this.audioPlayQueue.length||(this.isPlayingAudio=!1,this.ttsPlayingMessageIndex=-1,this.$nextTick(function(){return e.updateTtsPlaybackButtons()}))},playAudioBlob:function(e){var t=this,n=URL.createObjectURL(e),i=new Audio(n);this.currentAudioUrl=n,this.currentAudioElement=i,this.isPlayingAudio=!0,i.addEventListener("ended",function(){t.currentAudioElement=null,t.currentAudioUrl=null,URL.revokeObjectURL(n),t.playNextInQueue()}),i.addEventListener("error",function(){t.currentAudioElement=null,t.currentAudioUrl=null,URL.revokeObjectURL(n),t.playNextInQueue()}),i.play().catch(function(e){console.error("Audio playback error:",e),t.currentAudioElement=null,t.currentAudioUrl=null,URL.revokeObjectURL(n),t.audioPlayQueue=[],t.isPlayingAudio=!1,t.ttsPlayingMessageIndex=-1,t.$nextTick(function(){return t.updateTtsPlaybackButtons()})})},playNextInQueue:function(){var e=this;if(this.audioPlayQueue.length>0){var t=this.audioPlayQueue.shift();this.playAudioBlob(t)}else this.isPlayingAudio=!1,this.ttsPlayingMessageIndex=-1,this.$nextTick(function(){return e.updateTtsPlaybackButtons()}),this.conversationModeOnAudioEnded()},stopAudio:function(){var e=this;this.currentAudioElement&&(this.currentAudioElement.pause(),this.currentAudioElement.currentTime=0,this.currentAudioElement=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.audioChunks=[],this.audioPlayQueue=[],this.isPlayingAudio=!1,this.ttsPlayingMessageIndex=-1,this.$nextTick(function(){return e.updateTtsPlaybackButtons()})},toggleConversationMode:function(){this.isConversationMode?this.stopConversationMode():this.startConversationMode()},startConversationMode:function(){var e=this;this.conversationModeEnabled&&!this.isConversationMode&&this.connection&&(this.isConversationMode=!0,this.updateConversationButton(),this._conversationPartialTranscript="",this._conversationAssistantMessage=null,this._conversationPartialMessage=null,this.removeNotification("conversation-ended"),navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}}).then(function(t){var n=MediaRecorder.isTypeSupported("audio/ogg;codecs=opus")?"audio/ogg;codecs=opus":MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":"audio/webm";e.mediaRecorder=new MediaRecorder(t,{mimeType:n,audioBitsPerSecond:128e3}),e._conversationSubject=new signalR.Subject,e._conversationStream=t;var i=window.AudioContext||window.webkitAudioContext;i&&(e._conversationAudioCtx=new i,e._conversationAnalyser=e._conversationAudioCtx.createAnalyser(),e._conversationAnalyser.fftSize=256,e._conversationAudioCtx.createMediaStreamSource(t).connect(e._conversationAnalyser));var s=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,a=0;a<n.length;a++)i+=n[a];i/n.length>=30&&e.stopAudio()}s=s.then(_asyncToGenerator(_regenerator().m(function n(){var i,s,o,a;return _regenerator().w(function(n){for(;;)switch(n.n){case 0:return n.n=1,t.data.arrayBuffer();case 1:i=n.v,s=new Uint8Array(i),o=s.reduce(function(e,t){return e+String.fromCharCode(t)},""),a=btoa(o);try{e._conversationSubject.next(a)}catch(e){}case 2:return n.a(2)}},n)})))}}),e.mediaRecorder.addEventListener("stop",function(){t.getTracks().forEach(function(e){return e.stop()}),s.then(function(){try{e._conversationSubject.complete()}catch(e){}})});var a=e.getProfileId(),r=e.getSessionId()||"",c=navigator.language||document.documentElement.lang||"en-US";e.connection.send("StartConversation",a,r,e._conversationSubject,n,c),e.mediaRecorder.start(250),e.isRecording=!0}).catch(function(t){console.error("Microphone access denied:",t),e.isConversationMode=!1,e.updateConversationButton()}))},stopConversationMode:function(){if(this.isConversationMode){if(this.isConversationMode=!1,this.updateConversationButton(),this.connection&&this.connection.invoke("StopConversation").catch(function(){}),this.isRecording&&this.mediaRecorder&&(this.mediaRecorder.stop(),this.isRecording=!1),this.stopAudio(),this._conversationPartialTranscript="",this._conversationPartialMessage=null,this._conversationAudioCtx&&(this._conversationAudioCtx.close().catch(function(){}),this._conversationAudioCtx=null,this._conversationAnalyser=null),this._conversationAssistantMessage){var e=this.messages[this._conversationAssistantMessage.index];e&&(e.isStreaming=!1),this._conversationAssistantMessage=null}for(var t=0;t<this.messages.length;t++)this.messages[t].isStreaming&&(this.messages[t].isStreaming=!1);this.receiveNotification({type:"conversation-ended",content:"Conversation ended.",icon:"fa-solid fa-circle-check",dismissible:!0,autoDismissMs:5e3})}},updateConversationButton:function(){if(this.conversationButton)if(this.isConversationMode){this.conversationButton.classList.add("active","btn-primary"),this.conversationButton.classList.remove("btn-dark","btn-outline-dark","btn-outline-secondary"),this.conversationButton.title=this.conversationButton.getAttribute("data-end-title")||"End Conversation";var e=this.conversationButton.getAttribute("data-end-html");e&&this.conversationButton.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0}))}else{this.conversationButton.classList.remove("active","btn-primary"),this.conversationButton.classList.remove("btn-dark","btn-outline-secondary"),this.conversationButton.classList.add("btn-outline-dark"),this.conversationButton.blur(),this.conversationButton.title=this.conversationButton.getAttribute("data-start-title")||"Start Conversation";var t=this.conversationButton.getAttribute("data-start-html");t&&this.conversationButton.replaceChildren(DOMPurify.sanitize(t,{RETURN_DOM_FRAGMENT:!0}))}},conversationModeSendPrompt:function(){},conversationModeOnAudioEnded:function(){},generatePrompt:function(e){if(e){var t=e.getAttribute("data-profile-id"),n=this.getSessionId(),i=this.getProfileId();t&&n?this.streamMessage(t,null,i):console.error("The given element is missing data-profile-id or the session has not yet started.")}else console.error("The element paramter is required.")},createSessionUrl:function(e,t,n){var i=e.toLowerCase().startsWith("http")?e:window.location.origin+e,s=new URL(i);return s.searchParams.set(t,n),s.toString()},showTypingIndicator:function(){this.addMessage({role:"indicator",htmlContent:n.indicatorTemplate})},hideTypingIndicator:function(){var e=this.messages.length;return this.messages=this.messages.filter(function(e){return"indicator"!==e.role}),e-this.messages.length},receiveNotification:function(e){var t=this;if(e&&e.type){this.clearNotificationDismiss(e.type);var n=this.notifications.findIndex(function(t){return t.type===e.type});n>=0?this.notifications.splice(n,1,e):this.notifications.push(e),this.scheduleNotificationDismiss(e),this.$nextTick(function(){t.scrollToBottom()})}},updateNotification:function(e){if(e&&e.type){this.clearNotificationDismiss(e.type);var t=this.notifications.findIndex(function(t){return t.type===e.type});t>=0&&(this.notifications.splice(t,1,e),this.scheduleNotificationDismiss(e))}},scheduleNotificationDismiss:function(e){var t=this;e&&e.type&&e.autoDismissMs&&!(e.autoDismissMs<=0)&&(this.notificationDismissTimers[e.type]=setTimeout(function(){t.removeNotification(e.type)},e.autoDismissMs))},clearNotificationDismiss:function(e){var t=this.notificationDismissTimers[e];t&&(clearTimeout(t),delete this.notificationDismissTimers[e])},removeNotification:function(e){this.clearNotificationDismiss(e),this.notifications=this.notifications.filter(function(t){return t.type!==e})},dismissNotification:function(e){this.removeNotification(e)},handleNotificationAction:function(e,t){if(this.connection){var n=this.getSessionId();this.connection.invoke("HandleNotificationAction",n,e,t).catch(function(e){console.error("Error handling notification action:",e)})}},scrollToBottom:function(){var e=this;this.autoScroll&&setTimeout(function(){e.chatContainer.scrollTop=e.chatContainer.scrollHeight-e.chatContainer.clientHeight},50)},handleUserInput:function(e){this.prompt=e.target.value},getProfileId:function(){return this.inputElement?this.inputElement.getAttribute("data-profile-id"):null},setSessionId:function(e){this.inputElement&&this.inputElement.setAttribute("data-session-id",e||"")},resetSession:function(){this.stopRecording(),this.rejectPendingSessionRequest("Session was reset."),this.setSessionId(""),this.isSessionStarted=!1,this.sessionRating=null,this.messages=[],this.documents=[],n.autoCreateSession||this.showPlaceholder(),n.autoCreateSession&&this.startNewSession(),a&&"function"==typeof a.onSessionReset&&a.onSessionReset(this,n)},startNewSession:function(){if(this.applyOrchestratorAvailability()){var e=this.getProfileId();e&&this.connection&&this.requestNewSession(e).catch(function(e){return console.error(e)})}},ensureSessionForDocuments:function(e){var t=this;return _asyncToGenerator(_regenerator().m(function n(){var i;return _regenerator().w(function(n){for(;;)switch(n.n){case 0:if(!(i=t.getSessionId())){n.n=1;break}return n.a(2,i);case 1:if(e&&t.connection){n.n=2;break}return n.a(2,null);case 2:return n.n=3,t.requestNewSession(e);case 3:return n.a(2,n.v)}},n)}))()},requestNewSession:function(e){var t=this;return this.pendingSessionPromise?this.pendingSessionPromise:e&&this.connection?(this.pendingSessionPromise=new Promise(function(e,n){t.pendingSessionResolver=e,t.pendingSessionRejector=n,t.pendingSessionTimeoutId=window.setTimeout(function(){t.rejectPendingSessionRequest("Timed out while creating a chat session.")},15e3)}),this.connection.invoke("StartSession",e,null).catch(function(e){t.rejectPendingSessionRequest(e)}),this.pendingSessionPromise):Promise.resolve(null)},resolvePendingSessionRequest:function(e){this.pendingSessionResolver&&this.pendingSessionResolver(e),this.clearPendingSessionRequest()},rejectPendingSessionRequest:function(e){this.pendingSessionRejector&&this.pendingSessionRejector(e),this.clearPendingSessionRequest()},clearPendingSessionRequest:function(){this.pendingSessionTimeoutId&&window.clearTimeout(this.pendingSessionTimeoutId),this.pendingSessionPromise=null,this.pendingSessionResolver=null,this.pendingSessionRejector=null,this.pendingSessionTimeoutId=null},initializeApp:function(){var e=this;if(this.inputElement=document.querySelector(n.inputElementSelector),this.buttonElement=document.querySelector(n.sendButtonElementSelector),this.chatContainer=document.querySelector(n.chatContainerElementSelector),this.placeholder=document.querySelector(n.placeholderElementSelector),!(this.inputElement&&this.buttonElement&&this.chatContainer&&this.placeholder))return console.error("AI chat app could not initialize because one or more required elements were not found.",{inputElementSelector:n.inputElementSelector,sendButtonElementSelector:n.sendButtonElementSelector,chatContainerElementSelector:n.chatContainerElementSelector,placeholderElementSelector:n.placeholderElementSelector}),!1;this.applyOrchestratorAvailability();var t=this.getSessionId();if(!o&&t?this.loadSession(t):this.isOrchestratorAvailable()&&n.autoCreateSession&&!o&&!t&&this.startNewSession(),n.sessionDocumentsEnabled&&n.documentBarSelector&&(this.documentBar=document.querySelector(n.documentBarSelector),this.documentBar)){this.renderDocumentBar();var i=document.createElement("input");i.type="file",i.id="ai-chat-doc-input",i.className="d-none",i.multiple=!0,n.allowedExtensions&&(i.accept=n.allowedExtensions),i.addEventListener("change",function(t){return e.handleFileInputChange(t)}),this.documentBar.parentElement.appendChild(i);var s=this.inputElement?this.inputElement.closest(".ai-admin-widget-input, .text-bg-light"):null;s&&(s.addEventListener("dragover",function(t){return e.handleDragOver(t)}),s.addEventListener("dragleave",function(t){return e.handleDragLeave(t)}),s.addEventListener("drop",function(t){return e.handleDrop(t)}))}this.chatContainer.addEventListener("scroll",function(){if(e.stream){var t=e.chatContainer.scrollHeight-e.chatContainer.clientHeight-e.chatContainer.scrollTop<=30;e.autoScroll=t}}),this.inputElement.addEventListener("keydown",function(t){null==e.stream&&("Enter"!==t.key||t.shiftKey||(t.preventDefault(),e.buttonElement.click()))}),this.inputElement.addEventListener("input",function(t){e.handleUserInput(t),t.target.value.trim()?e.buttonElement.removeAttribute("disabled"):e.buttonElement.setAttribute("disabled",!0)}),this.buttonElement.addEventListener("click",function(){if(null==e.stream)e.sendMessage();else if(e.stream.dispose(),e.stream=null,e.streamingFinished(),e.hideTypingIndicator(),e.messages.length>0){var t=e.messages[e.messages.length-1];"assistant"!==t.role||t.content?t.isStreaming&&(t.isStreaming=!1):e.messages.pop()}});for(var a=document.getElementsByClassName("profile-generated-prompt"),r=0;r<a.length;r++)a[r].addEventListener("click",function(t){t.preventDefault(),e.generatePrompt(t.target)});var c=document.getElementsByClassName("chat-session-history-item");for(r=0;r<c.length;r++)c[r].addEventListener("click",function(t){t.preventDefault();var n=t.target.getAttribute("data-session-id");n?(e.loadSession(n),e.showChatScreen()):console.error("an element with the class chat-session-history-item with no data-session-id set.")});for(var l=0;l<n.messages.length;l++)this.addMessage(n.messages[l]);return this.$nextTick(function(){e.refreshAllFeedbackIcons()}),this.chatContainer&&this.chatContainer.addEventListener("click",function(e){var t=e.target.closest(".ai-code-copy-btn");if(t){var i=t.closest(".ai-code-block")||t.closest("pre");if(i){var s=i.querySelector("code");if(s){navigator.clipboard.writeText(s.textContent);var o=n.codeCopiedText||"Copied!";t.innerHTML='<span class="fa-solid fa-check"></span> '+o,setTimeout(function(){t.innerHTML='<span class="fa-regular fa-copy"></span>'},2e3)}}}}),this.speechToTextEnabled&&n.micButtonElementSelector&&(this.micButton=document.querySelector(n.micButtonElementSelector),this.micButton&&(this.micButton.style.display="",this.micButton.addEventListener("click",function(){e.toggleRecording()}))),this.conversationModeEnabled&&n.conversationButtonElementSelector&&(this.conversationButton=document.querySelector(n.conversationButtonElementSelector),this.conversationButton&&this.conversationButton.addEventListener("click",function(){e.toggleConversationMode()})),!0},loadSession:function(e){this.connection.invoke("LoadSession",e).catch(function(e){return console.error(e)})},reloadCurrentSession:function(){var e=this.getSessionId();e&&this.loadSession(e)},initializeSession:function(e,t){!this.isSessionStarted||t?(this.fireEvent(new CustomEvent("initializingSessionOpenAIChat",{detail:{sessionId:e}})),this.setSessionId(e),this.isSessionStarted=!0,this.resolvePendingSessionRequest(e),a&&"function"==typeof a.onSessionInitialized&&a.onSessionInitialized(this,e,n)):e&&this.getSessionId()===e&&this.resolvePendingSessionRequest(e)},getSessionId:function(){var e=this.inputElement?this.inputElement.getAttribute("data-session-id"):null;return!e&&a&&"function"==typeof a.resolveSessionId&&(e=a.resolveSessionId(this,n)),e},copyResponse:function(e){navigator.clipboard.writeText(e)},updateFeedbackIcons:function(e,t){if(e){var n=e.querySelector(".rate-up-btn"),i=e.querySelector(".rate-down-btn");if(n){var s=!0===t?"fa-solid fa-thumbs-up":"fa-regular fa-thumbs-up",o=document.createElement("span");o.className=s,o.style.fontSize="0.9rem",n.textContent="",n.appendChild(o)}if(i){var a=!1===t?"fa-solid fa-thumbs-down":"fa-regular fa-thumbs-down",r=document.createElement("span");r.className=a,r.style.fontSize="0.9rem",i.textContent="",i.appendChild(r)}}},refreshAllFeedbackIcons:function(){for(var e=this.$el.querySelectorAll(".ai-chat-message-assistant-feedback"),t=0;t<e.length;t++){var n=e[t].getAttribute("data-message-id"),i=this.messages.find(function(e){return e.id===n});i&&this.updateFeedbackIcons(e[t],i.userRating)}},rateMessage:function(e,t,n){var i=this.getSessionId();if(i&&e.id&&this.connection){var s=e.userRating===t?null:t;e.userRating=s;var o=this.$el.querySelector('.ai-chat-message-assistant-feedback[data-message-id="'+e.id+'"]');this.updateFeedbackIcons(o,s),null!==s&&o&&setTimeout(function(){var e=t?".rate-up-btn":".rate-down-btn",n=o.querySelector(e);n&&(n.classList.remove("spark-effect"),n.offsetWidth,n.classList.add("spark-effect"),n.addEventListener("animationend",function e(){n.removeEventListener("animationend",e),n.classList.remove("spark-effect")}))},50),this.connection.invoke("RateMessage",i,e.id,t).catch(function(e){console.error("Failed to rate message:",e)})}}},watch:{documents:{handler:function(){this.renderDocumentBar(),a&&"function"==typeof a.onDocumentsChanged&&a.onDocumentsChanged(this,this.documents,n)},deep:!0},isUploading:function(){this.renderDocumentBar()},isDocumentOperationPending:function(){this.renderDocumentBar()},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=""))}},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()&&o&&a&&"function"==typeof a.onMounted&&a.onMounted(e,n);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.stopAudio(!1),this.stream&&(this.stream.dispose(),this.stream=null),this.connection&&this.connection.stop(),a&&"function"==typeof a.onBeforeUnmount&&a.onBeforeUnmount(this,n)},template:n.messageTemplate},l=Vue.createApp(r).mount(n.appElementSelector);return a&&"function"==typeof a.attach&&a.attach(l,n),l}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.")}}}(),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 s=document.createElement("a");s.download="chart-"+n+".png",s.href=i.toDataURL("image/png"),s.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 s=i.src;s&&s.startsWith("data:")&&(e.preventDefault(),fetch(s).then(function(e){return e.blob()}).then(function(e){var n=URL.createObjectURL(e),i=document.createElement("a");i.href=n,i.download=t.getAttribute("download")||"generated-image.png",document.body.appendChild(i),i.click(),document.body.removeChild(i),setTimeout(function(){URL.revokeObjectURL(n)},100)}).catch(function(e){console.error("Failed to download image:",e)}))}}});
2
2
  //# sourceMappingURL=ai-chat.min.js.map