@crestapps/ai-chat-ui 1.0.0-preview-22-preview.1

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.
@@ -0,0 +1 @@
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",o=n.toStringTag||"@@toStringTag";function s(n,i,o,s){var c=i&&i.prototype instanceof r?i:r,l=Object.create(c.prototype);return _regeneratorDefine2(l,"_invoke",function(n,i,o){var s,r,c,l=0,d=o||[],u=!1,h={p:0,n:0,v:e,a:f,f:f.bind(e,4),d:function(t,n){return s=t,r=0,c=e,h.n=n,a}};function f(n,i){for(r=n,c=i,t=0;!u&&l&&!o&&t<d.length;t++){var o,s=d[t],f=h.p,m=s[2];n>3?(o=m===i)&&(c=s[(r=s[4])?5:(r=3,3)],s[4]=s[5]=e):s[0]<=f&&((o=n<2&&f<s[1])?(r=0,h.v=i,h.n=s[1]):f<m&&(o=n<3||s[0]>i||i>m)&&(s[4]=n,s[5]=i,h.n=m,r=0))}if(o||n>1)return a;throw u=!0,i}return function(o,d,m){if(l>1)throw TypeError("Generator is already running");for(u&&1===d&&f(d,m),r=d,c=m;(t=r<2?e:c)||!u;){s||(r?r<3?(r>1&&(h.n=-1),f(r,c)):h.n=c:h.v=c);try{if(l=2,s){if(r||(o="next"),t=s[o]){if(!(t=t.call(s,c)))throw TypeError("iterator result is not an object");if(!t.done)return t;c=t.value,r<2&&(r=0)}else 1===r&&(t=s.return)&&t.call(s),r<2&&(c=TypeError("The iterator does not provide a '"+o+"' method"),r=1);s=e}else if((t=(u=h.n<0)?c:n.call(i,h))!==a)break}catch(t){s=e,r=1,c=t}finally{l=1}}return{value:t,done:u}}}(n,o,s),!0),l}var a={};function r(){}function c(){}function l(){}t=Object.getPrototypeOf;var d=[][i]?t(t([][i]())):(_regeneratorDefine2(t={},i,function(){return this}),t),u=l.prototype=r.prototype=Object.create(d);function h(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,l):(e.__proto__=l,_regeneratorDefine2(e,o,"GeneratorFunction")),e.prototype=Object.create(u),e}return c.prototype=l,_regeneratorDefine2(u,"constructor",l),_regeneratorDefine2(l,"constructor",c),c.displayName="GeneratorFunction",_regeneratorDefine2(l,o,"GeneratorFunction"),_regeneratorDefine2(u),_regeneratorDefine2(u,o,"Generator"),_regeneratorDefine2(u,i,function(){return this}),_regeneratorDefine2(u,"toString",function(){return"[object Generator]"}),(_regenerator=function(){return{w:s,m:h}})()}function _regeneratorDefine2(e,t,n,i){var o=Object.defineProperty;try{o({},"",{})}catch(e){o=0}_regeneratorDefine2=function(e,t,n,i){function s(t,n){_regeneratorDefine2(e,t,function(e){return this._invoke(t,n,e)})}t?o?o(e,t,{value:n,enumerable:!i,configurable:!i,writable:!i}):e[t]=n:(s("next",0),s("throw",1),s("return",2))},_regeneratorDefine2(e,t,n,i)}function asyncGeneratorStep(e,t,n,i,o,s,a){try{var r=e[s](a),c=r.value}catch(e){return void n(e)}r.done?t(c):Promise.resolve(c).then(i,o)}function _asyncToGenerator(e){return function(){var t=this,n=arguments;return new Promise(function(i,o){var s=e.apply(t,n);function a(e){asyncGeneratorStep(s,i,o,a,r,"next",e)}function r(e){asyncGeneratorStep(s,i,o,a,r,"throw",e)}a(void 0)})}}function _createForOfIteratorHelper(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=_unsupportedIterableToArray(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var i=0,o=function(){};return{s:o,n:function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}},e:function(e){throw e},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var s,a=!0,r=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return a=e.done,e},e:function(e){r=!0,s=e},f:function(){try{a||null==n.return||n.return()}finally{if(r)throw s}}}}function _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,o,s,a,r=[],c=!0,l=!1;try{if(s=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;c=!1}else for(;!(c=(i=s.call(n)).done)&&(r.push(i.value),r.length!==t);c=!0);}catch(e){l=!0,o=e}finally{try{if(!c&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(l)throw o}}return r}}function _arrayWithHoles(e){if(Array.isArray(e))return e}function _typeof(e){return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof(e)}window.openAIChatManager=function(){var e={generatedImageAltText:"Generated Image",generatedImageMaxWidth:400,generatedChartMaxWidth:900,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!",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)"><i :class="getAssistantIcon(message)"></i></span>\n {{ getAssistantLabel(message) }}\n </div>\n <div class="ai-chat-message-body lh-base">\n <h4 v-if="message.title">{{ message.title }}</h4>\n <div v-html="message.htmlContent"></div>\n <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 <i class="fa-regular fa-thumbs-up"></i>\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 <i class="fa-regular fa-thumbs-down"></i>\n </button>\n </span>\n </template>\n <button class="btn btn-sm btn-link text-secondary p-0 button-message-toolbox" @click="copyResponse(message.content)" :title="copyTitle">\n <i class="fa-solid fa-copy"></i>\n </button>\n </span>\n </div>\n </div>\n </div>\n <div v-for="notification in notifications" :key="\'notif-\' + notification.type" class="ai-chat-notification" :class="\'ai-chat-notification-\' + (notification.type || \'info\') + \' \' + (notification.cssClass || \'\')">\n <div class="ai-chat-notification-content">\n <i v-if="notification.icon" :class="notification.icon" class="ai-chat-notification-icon"></i>\n <span class="ai-chat-notification-text">{{ notification.content }}</span>\n <button v-if="notification.dismissible" class="btn btn-sm btn-link p-0 ms-2 ai-chat-notification-dismiss" @click="dismissNotification(notification.type)" title="Dismiss">\n <i class="fa-solid fa-xmark"></i>\n </button>\n </div>\n <div v-if="notification.actions && notification.actions.length" class="ai-chat-notification-actions">\n <button v-for="action in notification.actions" :key="action.name" class="btn btn-sm" :class="action.cssClass || \'btn-outline-secondary\'" @click="handleNotificationAction(notification.type, action.name)">\n <i v-if="action.icon" :class="action.icon" class="me-1"></i>\n {{ action.label }}\n </button>\n </div>\n </div>\n </div>\n ',indicatorTemplate:'\n <div class="ai-chat-msg-role ai-chat-msg-role-assistant">\n <span class="ai-streaming-icon"><i class="fa fa-robot" style="display: inline-block;"></i></span>\n Assistant\n </div>\n '};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,o,s,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!==(o=r.text)&&void 0!==o?o:r.Text)&&void 0!==i?i:null,r.link=null!==(s=null!==(a=r.link)&&void 0!==a?a:r.Link)&&void 0!==s?s:null,r}function o(e){if(!e||"object"!==_typeof(e))return{};for(var t={},n=0,o=Object.entries(e);n<o.length;n++){var s,a=_slicedToArray(o[n],2),r=a[0],c=a[1];t[r]=null!==(s=i(c))&&void 0!==s?s:{}}return t}var s=new marked.Renderer;s.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||""},s.code=function(e){var t=e.text||"",i=(e.lang||"").trim(),o=t;if("undefined"!=typeof hljs)if(i&&hljs.getLanguage(i))try{o=hljs.highlight(t,{language:i}).value}catch(e){}else try{o=hljs.highlightAuto(t).value}catch(e){}else o=n(t);var s=i?n(i):"code";return'<div class="ai-code-block"><div class="ai-code-header"><span class="ai-code-lang"><i class="fa-solid fa-code"></i> '.concat(s,'</span><button type="button" class="ai-code-copy-btn" title="Copy code"><i class="fa-regular fa-copy"></i></button></div><pre><code class="hljs').concat(i?" language-"+i:"",'">').concat(o,"</code></pre></div>")},s.image=function(n){var i=t(n.href);if(!i)return"";var o=n.text||e.generatedImageAltText,s=e.generatedImageMaxWidth;return'<div class="generated-image-container">\n <img src="'.concat(i,'" alt="').concat(o,'" class="img-thumbnail" style="max-width: ').concat(s,'px; height: auto;" />\n <div class="mt-2">\n <a href="').concat(i,'" target="_blank" download="').concat(o,'" title="').concat(e.downloadImageTitle,'" class="btn btn-sm btn-outline-secondary ai-download-image">\n <i class="fa-solid fa-download"></i>\n </a>\n </div>\n </div>')};var 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)if("undefined"!=typeof Chart)try{var i;n._chartInstance&&n._chartInstance.destroy();var o="string"==typeof t?JSON.parse(t):t;null!==(i=o.options)&&void 0!==i||(o.options={}),o.options.responsive=!0,o.options.maintainAspectRatio=!1,n._chartInstance=new Chart(n,o),delete window.__chartConfigs[e]}catch(e){console.error("Error creating chart:",e)}else console.warn('Chart.js is not loaded. To render interactive charts, include the Chart.js library on the page (e.g., <script src="https://cdn.jsdelivr.net/npm/chart.js@4/dist/chart.umd.min.js"><\/script>).')}function d(e,t){r=[];var n=marked.parse(e,{renderer:s});return t._pendingCharts=r.length>0?_toConsumableArray(r):[],DOMPurify.sanitize(n,{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,o=i;for(;o<e.length&&(" "===e[o]||"\n"===e[o]||"\r"===e[o]||"\t"===e[o]);)o++;if(o>=e.length||"{"!==e[o])return null;for(var s=0,a=!1,r=!1;o<e.length;o++){var c=e[o];if(a){if(r){r=!1;continue}if("\\"===c){r=!0;continue}'"'===c&&(a=!1)}else if('"'!==c){if("{"===c)s++;else if("}"===c&&0===--s){var l=o,d=e.indexOf("]",l+1);return d<0?null:{startIndex:n,endIndex:d+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,i=e.generatedChartMaxWidth,'<div class="chart-container" style="position: relative; width: 100%; max-width: '.concat(i,'px;">')+'<canvas id="'.concat(n,'" class="img-thumbnail"></canvas>')+'</div><div class="mt-2">'+'<button type="button" class="btn btn-sm btn-outline-secondary download-chart-btn" data-chart-id="'.concat(n,'" title="').concat(e.downloadChartTitle,'">')+'<i class="fa-solid fa-download"></i> '.concat(e.downloadChartButtonText)+"</button></div>";var n,i}}]}),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);if(e=n,n.signalRHubUrl)if(n.appElementSelector)if(n.chatContainerElementSelector)if(n.inputElementSelector){if(n.sendButtonElementSelector)return Vue.createApp({data:function(){return{inputElement:null,buttonElement:null,chatContainer:null,placeholder:null,isSessionStarted:!1,isPlaceholderVisible:!0,chatWidgetStateName:null,chatWidgetStateSession:null,chatHistorySection:null,widgetIsInitialized:!1,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,ttsVoiceName:n.ttsVoiceName||null,audioChunks:[],audioPlayQueue:[],isPlayingAudio:!1,currentAudioElement:null,ttsButton:null,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 o,s,a,r,c,l,d,u,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(o=t.getSessionId(),s=t.getProfileId(),o||s){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,a=new FormData,o?a.append("sessionId",o):a.append("profileId",s),r=0;r<e.length;r++)a.append("files",e[r]);return i.n=4,fetch(n.uploadDocumentUrl,{method:"POST",body:a});case 4:if((c=i.v).ok){i.n=6;break}return i.n=5,c.text();case 5:return l=i.v,d=t.extractReadableErrorMessage(l,"Upload failed. Please try again."),console.error("Upload failed:",l),t.uploadErrors=[{fileName:"",error:d}],i.a(2);case 6:return i.n=7,c.json();case 7:if((u=i.v).sessionId&&!o&&t.initializeSession(u.sessionId),u.uploaded&&u.uploaded.length>0)for(h=0;h<u.uploaded.length;h++)t.documents.push(u.uploaded[h]);u.failed&&u.failed.length>0&&(t.uploadErrors=u.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 o,s,a,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,o=t.getSessionId(),i.n=2,fetch(n.removeDocumentUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({itemId:o,documentId:e.documentId})});case 2:if(!(s=i.v).ok){i.n=3;break}(a=t.documents.indexOf(e))>-1&&t.documents.splice(a,1),i.n=5;break;case 3:return i.n=4,s.text();case 4:r=i.v,c=t.extractReadableErrorMessage(r,"Failed to remove document. Please try again."),console.error("Failed to remove document:",s.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],o=i.fileName||"Document";o.length>20&&(o=o.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+='<i class="fa-solid fa-file-lines" style="font-size: 0.7rem;"></i> ',e+=this.escapeHtml(o),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 s=0;s<this.uploadErrors.length;s++){var a=this.uploadErrors[s],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+='<i class="fa-solid fa-circle-exclamation" style="font-size: 0.7rem;"></i> ',e+=this.escapeHtml(r),e+=' <button type="button" class="btn-close btn-close-sm ms-1" style="font-size: 0.5rem;" data-error-index="'+s+'" 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+='<i class="fa-solid fa-paperclip"></i>',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,d=this.documentBar.querySelectorAll("[data-doc-index]"),u=0;u<d.length;u++)d[u].addEventListener("click",function(e){return function(t){t.preventDefault(),t.stopPropagation();var n=l.documents[e];n&&l.removeDocument(n)}}(parseInt(d[u].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 m=this.documentBar.querySelector(".ai-chat-doc-add-btn");m&&m.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),o=(null==i?void 0:i.error)||(null==i?void 0:i.message)||(null==i?void 0:i.title)||(null==i?void 0:i.detail);return"string"==typeof o&&o.trim()?o.trim():t}catch(e){return t}return/<[^>]+>/.test(n)?t:n},normalizeAssistantAppearance:function(e){if(!e)return null;var t="string"==typeof e.label?e.label.trim():"",n="string"==typeof e.icon?e.icon.trim():"",i="string"==typeof e.cssClass?e.cssClass.trim():"",o=!!e.disableStreamingAnimation;return t||n||i||o?{label:t,icon:n,cssClass:i,disableStreamingAnimation:o}:null},getAssistantLabel:function(e){var t=e?this.normalizeAssistantAppearance(e.appearance):null;return t&&t.label?t.label:this.assistantLabel},getAssistantRoleClasses:function(e){var t=e?this.normalizeAssistantAppearance(e.appearance):null,n=["ai-chat-msg-role"];return t&&t.cssClass?n.push(t.cssClass):n.push("ai-chat-msg-role-assistant"),n},getAssistantIconClasses:function(e,t){var n=e?this.normalizeAssistantAppearance(e.appearance):null;return[this.shouldAnimateAssistantIcon(e,t)?"ai-streaming-icon":"ai-bot-icon",n&&n.cssClass?n.cssClass:""]},getAssistantIcon:function(e){var t=e?this.normalizeAssistantAppearance(e.appearance):null;return t&&t.icon?t.icon:"fa fa-robot"},shouldAnimateAssistantIcon:function(e,t){var n=e?this.normalizeAssistantAppearance(e.appearance):null;return!!e&&e.isStreaming&&t===this.lastAssistantIndex&&!(n&&n.disableStreamingAnimation)},startConnection:function(){var e=this;return _asyncToGenerator(_regenerator().m(function t(){var 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||[],(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(),!e.widgetIsInitialized||e.isSessionStarted||e._attemptedSessionRecovery||(e._attemptedSessionRecovery=!0,localStorage.removeItem(e.chatWidgetStateSession),e.startNewSession())}),e.connection.on("MessageRated",function(t,n){var i=e.messages.find(function(e){return e.id===t});i&&(i.userRating=n)}),e.connection.on("ReceiveTranscript",function(t,n,i){if(e.isConversationMode){if(!i&&n){e._conversationPartialTranscript=n;var o='<p class="ai-partial-transcript">'+n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")+"</p>";e._conversationPartialMessage?(e._conversationPartialMessage.content=n,e._conversationPartialMessage.htmlContent=o):(e.hidePlaceholder(),e._conversationPartialMessage={role:"user",content:n,htmlContent:o,isPartial:!0},e.messages.push(e._conversationPartialMessage)),e.scrollToBottom()}}else n&&!e._audioInputSent&&(e.prompt=e.preRecordingPrompt+n,e.inputElement&&(e.inputElement.value=e.prompt,e.inputElement.dispatchEvent(new Event("input"))))}),e.connection.on("ReceiveConversationUserMessage",function(t,n){if(n){if(e.stopAudio(),e._conversationAssistantMessage){var i=e.messages[e._conversationAssistantMessage.index];i&&(i.isStreaming=!1),e._conversationAssistantMessage=null}if(e._conversationPartialMessage){var o=n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");e._conversationPartialMessage.content=n,e._conversationPartialMessage.htmlContent="<p>"+o+"</p>",e._conversationPartialMessage.isPartial=!1,e._conversationPartialMessage=null}else e.addMessage({role:"user",content:n});e.scrollToBottom()}}),e.connection.on("ReceiveConversationAssistantToken",function(t,n,i,o,s){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(s)};e.messages.push(l),e._conversationAssistantMessage={index:r,content:""}}e._conversationAssistantMessage.content+=i;var u=e.messages[e._conversationAssistantMessage.index];u&&(u.appearance||(u.appearance=e.normalizeAssistantAppearance(s)),u.content=e._conversationAssistantMessage.content,u.htmlContent=d(u.content,u),e.$nextTick(function(){c(u),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 o=atob(n),s=new Uint8Array(o.length),a=0;a<o.length;a++)s[a]=o.charCodeAt(a);e.audioChunks.push(s)}}),e.connection.on("ReceiveAudioComplete",function(t){e.playCollectedAudio()}),e.connection.on("ReceiveNotification",function(t){e.receiveNotification(t)}),e.connection.on("UpdateNotification",function(t){e.updateNotification(t)}),e.connection.on("RemoveNotification",function(t){e.removeNotification(t)}),e.connection.onreconnecting(function(){console.warn("SignalR: reconnecting...")}),e.connection.onreconnected(function(){console.info("SignalR: reconnected."),e.isSessionStarted?e.reloadCurrentSession():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=d(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=o(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 s,a=1,r=_createForOfIteratorHelper(i);try{for(r.s();!(s=r.n()).done;){var l=_slicedToArray(s.value,2),u=l[0],h=l[1],f="__CITE_".concat(h.index,"__");n=n.replaceAll(u,f),h._displayIndex=a++,h._placeholder=f}}catch(e){r.e(e)}finally{r.f()}var m,p=_createForOfIteratorHelper(i);try{for(p.s();!(m=p.n()).done;){var g=_slicedToArray(m.value,2)[1];n=n.replaceAll(g._placeholder,"<sup><strong>".concat(g._displayIndex,"</strong></sup>"))}}catch(e){p.e(e)}finally{p.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],_=A.text||S;n+=A.link?"**".concat(A._displayIndex,"**. [").concat(_,"](").concat(A.link,")<br>"):"**".concat(A._displayIndex,"**. ").concat(_,"<br>")}}catch(e){y.e(e)}finally{y.f()}}}e.content=n,e.htmlContent=d(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.addMessage({role:"user",content:e}),this.streamMessage(this.getProfileId(),e,null),this.inputElement.value="",this.prompt="")}},startRecording:function(){var e=this;!this.isRecording&&this.connection&&navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}}).then(function(t){var n=MediaRecorder.isTypeSupported("audio/ogg;codecs=opus")?"audio/ogg;codecs=opus":MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":"audio/webm";e.mediaRecorder=new MediaRecorder(t,{mimeType:n,audioBitsPerSecond:128e3}),e.preRecordingPrompt=e.prompt,e._audioInputSent=!1;var i=new signalR.Subject,o=e.getProfileId(),s=e.getSessionId()||"",a=Promise.resolve();e.mediaRecorder.addEventListener("dataavailable",function(e){e.data&&e.data.size>0&&(a=a.then(_asyncToGenerator(_regenerator().m(function t(){var n,o,s,a;return _regenerator().w(function(t){for(;;)switch(t.n){case 0:return t.n=1,e.data.arrayBuffer();case 1:n=t.v,o=new Uint8Array(n),s=o.reduce(function(e,t){return e+String.fromCharCode(t)},""),a=btoa(s),i.next(a);case 2:return t.a(2)}},t)}))))}),e.mediaRecorder.addEventListener("stop",function(){t.getTracks().forEach(function(e){return e.stop()}),a.then(function(){return i.complete()})});var r=navigator.language||document.documentElement.lang||"en-US";e.connection.send("SendAudioStream",o,s,i,n,r),e.mediaRecorder.start(250),e.isRecording=!0,e.updateMicButton()}).catch(function(e){console.error("Microphone access denied:",e)})},stopRecording:function(){this.isRecording&&this.mediaRecorder&&(this.mediaRecorder.stop(),this.isRecording=!1,this.updateMicButton())},toggleRecording:function(){this.isRecording?this.stopRecording():this.startRecording()},updateMicButton:function(){this.micButton&&(this.isRecording?(this.micButton.classList.add("stt-recording"),this.micButton.innerHTML='<i class="fa-solid fa-stop"></i>'):(this.micButton.classList.remove("stt-recording"),this.micButton.innerHTML='<i class="fa-solid fa-microphone"></i>'))},streamMessage:function(e,t,n){var o=this;this.stream&&(this.stream.dispose(),this.stream=null),this.streamingStarted(),this.showTypingIndicator(),this.autoScroll=!0;var s="",a={},r=null,l=this.messages.length,u=this.getSessionId();this.stream=this.connection.stream("SendMessage",e,t,u,n).subscribe({next:function(e){var t=o.messages[l];if(!t){e.sessionId&&!u&&o.initializeSession(e.sessionId),o.hideTypingIndicator(),l=o.messages.length;var n={id:e.messageId,role:"assistant",title:e.title,content:"",htmlContent:"",isStreaming:!0,userRating:null};o.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 m,p=_slicedToArray(f[h],2),g=p[0],v=p[1];a[g]=null!==(m=i(v))&&void 0!==m?m:{}}if(e.content){e.responseId&&r&&e.responseId!==r&&(s+="\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),_=A[0],E=A[1];y=y.replaceAll(_,"<sup><strong>".concat(E.index,"</strong></sup>"))}s+=y.replaceAll("</strong></sup><sup>","</strong></sup><sup>,</sup><sup>")}t.content=s,t.htmlContent=d(s,t),o.messages[l]=t,o.$nextTick(function(){c(t),o.scrollToBottom()})},complete:function(){var e;o.processReferences(a,l),o.streamingFinished();var t=o.messages[l];t&&(t.isStreaming=!1),t&&t.content||o.hideTypingIndicator(),o.isConversationMode&&o.textToSpeechEnabled&&t&&t.content&&o.synthesizeSpeech(t.content),null===(e=o.stream)||void 0===e||e.dispose(),o.stream=null},error:function(e){var t;o.processReferences(a,l),o.streamingFinished();var n=o.messages[l];n&&(n.isStreaming=!1),o.hideTypingIndicator(),o.isNavigatingAway||o.addMessage(o.getServiceDownMessage()),null===(t=o.stream)||void 0===t||t.dispose(),o.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=o(e),Object.keys(e).length){var i=this.messages[t],s=i.content||"",a=Object.entries(e).filter(function(e){var t=_slicedToArray(e,2),n=t[0],i=t[1];return s.includes(n)||s.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=s.trim(),u=1,h=_createForOfIteratorHelper(a);try{for(h.s();!(r=h.n()).done;){var f=_slicedToArray(r.value,2),m=f[0],p=f[1],g="__CITE_".concat(p.index,"__");l=(l=l.replaceAll(m,g)).replaceAll("<sup><strong>".concat(p.index,"</strong></sup>"),g),p._displayIndex=u++,p._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 _=_slicedToArray(S.value,2),E=_[0],w=_[1],C=w.text||E;l+=w.link?"**".concat(w._displayIndex,"**. [").concat(C,"](").concat(w.link,")<br>"):"**".concat(w._displayIndex,"**. ").concat(C,"<br>")}}catch(e){A.e(e)}finally{A.f()}i.content=l,i.htmlContent=d(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)},synthesizeSpeech:function(e){var t=this;this.textToSpeechEnabled&&e&&this.connection&&(this.audioChunks=[],this.isPlayingAudio=!0,this.connection.invoke("SynthesizeSpeech",this.getProfileId(),this.getSessionId(),e,this.ttsVoiceName).catch(function(e){console.error("TTS synthesis error:",e),t.isPlayingAudio=!1}))},playCollectedAudio:function(){if(0!==this.audioChunks.length){var e,t=this.audioChunks.reduce(function(e,t){return e+t.length},0),n=new Uint8Array(t),i=0,o=_createForOfIteratorHelper(this.audioChunks);try{for(o.s();!(e=o.n()).done;){var s=e.value;n.set(s,i),i+=s.length}}catch(e){o.e(e)}finally{o.f()}this.audioChunks=[];var a=new Blob([n],{type:"audio/mp3"});this.currentAudioElement?this.audioPlayQueue.push(a):this.playAudioBlob(a)}else this.currentAudioElement||0!==this.audioPlayQueue.length||(this.isPlayingAudio=!1)},playAudioBlob:function(e){var t=this,n=URL.createObjectURL(e),i=new Audio(n);this.currentAudioElement=i,this.isPlayingAudio=!0,i.addEventListener("ended",function(){URL.revokeObjectURL(n),t.currentAudioElement=null,t.playNextInQueue()}),i.addEventListener("error",function(){URL.revokeObjectURL(n),t.currentAudioElement=null,t.playNextInQueue()}),i.play().catch(function(e){console.error("Audio playback error:",e),URL.revokeObjectURL(n),t.currentAudioElement=null,t.isPlayingAudio=!1})},playNextInQueue:function(){if(this.audioPlayQueue.length>0){var e=this.audioPlayQueue.shift();this.playAudioBlob(e)}else this.isPlayingAudio=!1,this.conversationModeOnAudioEnded()},stopAudio:function(){this.currentAudioElement&&(this.currentAudioElement.pause(),this.currentAudioElement.currentTime=0,this.currentAudioElement=null),this.audioChunks=[],this.audioPlayQueue=[],this.isPlayingAudio=!1},toggleConversationMode:function(){this.isConversationMode?this.stopConversationMode():this.startConversationMode()},startConversationMode:function(){var e=this;this.conversationModeEnabled&&!this.isConversationMode&&this.connection&&(this.isConversationMode=!0,this.updateConversationButton(),this._conversationPartialTranscript="",this._conversationAssistantMessage=null,this._conversationPartialMessage=null,this.removeNotification("conversation-ended"),navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}}).then(function(t){var n=MediaRecorder.isTypeSupported("audio/ogg;codecs=opus")?"audio/ogg;codecs=opus":MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":"audio/webm";e.mediaRecorder=new MediaRecorder(t,{mimeType:n,audioBitsPerSecond:128e3}),e._conversationSubject=new signalR.Subject,e._conversationStream=t;var i=window.AudioContext||window.webkitAudioContext;i&&(e._conversationAudioCtx=new i,e._conversationAnalyser=e._conversationAudioCtx.createAnalyser(),e._conversationAnalyser.fftSize=256,e._conversationAudioCtx.createMediaStreamSource(t).connect(e._conversationAnalyser));var o=Promise.resolve(),s=e._conversationAnalyser;e.mediaRecorder.addEventListener("dataavailable",function(t){if(t.data&&t.data.size>0){if(e.isPlayingAudio&&s){var n=new Uint8Array(s.frequencyBinCount);s.getByteFrequencyData(n);for(var i=0,a=0;a<n.length;a++)i+=n[a];i/n.length>=30&&e.stopAudio()}o=o.then(_asyncToGenerator(_regenerator().m(function n(){var i,o,s,a;return _regenerator().w(function(n){for(;;)switch(n.n){case 0:return n.n=1,t.data.arrayBuffer();case 1:i=n.v,o=new Uint8Array(i),s=o.reduce(function(e,t){return e+String.fromCharCode(t)},""),a=btoa(s);try{e._conversationSubject.next(a)}catch(e){}case 2:return n.a(2)}},n)})))}}),e.mediaRecorder.addEventListener("stop",function(){t.getTracks().forEach(function(e){return e.stop()}),o.then(function(){try{e._conversationSubject.complete()}catch(e){}})});var a=e.getProfileId(),r=e.getSessionId()||"",c=navigator.language||document.documentElement.lang||"en-US";e.connection.send("StartConversation",a,r,e._conversationSubject,n,c),e.mediaRecorder.start(250),e.isRecording=!0}).catch(function(t){console.error("Microphone access denied:",t),e.isConversationMode=!1,e.updateConversationButton()}))},stopConversationMode:function(){if(this.isConversationMode){if(this.isConversationMode=!1,this.updateConversationButton(),this.connection&&this.connection.invoke("StopConversation").catch(function(){}),this.isRecording&&this.mediaRecorder&&(this.mediaRecorder.stop(),this.isRecording=!1),this.stopAudio(),this._conversationPartialTranscript="",this._conversationPartialMessage=null,this._conversationAudioCtx&&(this._conversationAudioCtx.close().catch(function(){}),this._conversationAudioCtx=null,this._conversationAnalyser=null),this._conversationAssistantMessage){var e=this.messages[this._conversationAssistantMessage.index];e&&(e.isStreaming=!1),this._conversationAssistantMessage=null}for(var t=0;t<this.messages.length;t++)this.messages[t].isStreaming&&(this.messages[t].isStreaming=!1);this.receiveNotification({type:"conversation-ended",content:"Conversation ended.",icon:"fa-solid fa-circle-check",dismissible:!0,autoDismissMs:5e3})}},updateConversationButton:function(){if(this.conversationButton)if(this.isConversationMode){this.conversationButton.classList.add("active","btn-primary"),this.conversationButton.classList.remove("btn-dark","btn-outline-dark","btn-outline-secondary"),this.conversationButton.title=this.conversationButton.getAttribute("data-end-title")||"End Conversation";var e=this.conversationButton.getAttribute("data-end-html");e&&this.conversationButton.replaceChildren(DOMPurify.sanitize(e,{RETURN_DOM_FRAGMENT:!0}))}else{this.conversationButton.classList.remove("active","btn-primary"),this.conversationButton.classList.remove("btn-dark","btn-outline-secondary"),this.conversationButton.classList.add("btn-outline-dark"),this.conversationButton.blur(),this.conversationButton.title=this.conversationButton.getAttribute("data-start-title")||"Start Conversation";var t=this.conversationButton.getAttribute("data-start-html");t&&this.conversationButton.replaceChildren(DOMPurify.sanitize(t,{RETURN_DOM_FRAGMENT:!0}))}},conversationModeSendPrompt:function(){},conversationModeOnAudioEnded:function(){},generatePrompt:function(e){if(e){var t=e.getAttribute("data-profile-id"),n=this.getSessionId(),i=this.getProfileId();t&&n?this.streamMessage(t,null,i):console.error("The given element is missing data-profile-id or the session has not yet started.")}else console.error("The element paramter is required.")},createSessionUrl:function(e,t,n){var i=e.toLowerCase().startsWith("http")?e:window.location.origin+e,o=new URL(i);return o.searchParams.set(t,n),o.toString()},showTypingIndicator:function(){this.addMessage({role:"indicator",htmlContent: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.widgetIsInitialized&&localStorage.removeItem(this.chatWidgetStateSession),this.messages=[],this.documents=[],n.autoCreateSession||this.showPlaceholder(),n.autoCreateSession&&this.startNewSession()},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(!n.widget&&t?this.loadSession(t):this.isOrchestratorAvailable()&&n.autoCreateSession&&!n.widget&&!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 o=this.inputElement?this.inputElement.closest(".ai-admin-widget-input, .text-bg-light"):null;o&&(o.addEventListener("dragover",function(t){return e.handleDragOver(t)}),o.addEventListener("dragleave",function(t){return e.handleDragLeave(t)}),o.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 s=document.getElementsByClassName("profile-generated-prompt"),a=0;a<s.length;a++)s[a].addEventListener("click",function(t){t.preventDefault(),e.generatePrompt(t.target)});var r=document.getElementsByClassName("chat-session-history-item");for(a=0;a<r.length;a++)r[a].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 c=0;c<n.messages.length;c++)this.addMessage(n.messages[c]);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 o=i.querySelector("code");if(o){navigator.clipboard.writeText(o.textContent);var s=n.codeCopiedText||"Copied!";t.innerHTML='<i class="fa-solid fa-check"></i> '+s,setTimeout(function(){t.innerHTML='<i class="fa-regular fa-copy"></i>'},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,this.widgetIsInitialized&&localStorage.setItem(this.chatWidgetStateSession,e))},initializeWidget:function(){var e=this;if(n.widget.chatWidgetContainer)if(n.widget.chatWidgetStateName){if(document.querySelector(n.widget.chatWidgetContainer)){if(n.widget.chatHistorySection&&(this.chatHistorySection=document.querySelector(n.widget.chatHistorySection)),this.chatWidgetStateName=n.widget.chatWidgetStateName,this.chatWidgetStateSession=n.widget.chatWidgetStateName+"Session",this.widgetIsInitialized=!0,this.reloadCurrentSession(),n.autoCreateSession&&!this.getSessionId()&&this.startNewSession(),n.widget.showHistoryButton&&this.chatHistorySection){var t=document.querySelector(n.widget.showHistoryButton);if(t&&t.addEventListener("click",function(){e.chatHistorySection.classList.toggle("show")}),n.widget.closeHistoryButton){var i=document.querySelector(n.widget.closeHistoryButton);i&&i.addEventListener("click",function(){e.showChatScreen()})}}if(n.widget.newChatButton){var o=document.querySelector(n.widget.newChatButton);o&&o.addEventListener("click",function(){e.resetSession(),e.showChatScreen()})}}}else console.error("The widget chatWidgetStateName is required.");else console.error("The widget chatWidgetContainer is required.")},showChatScreen:function(){this.chatHistorySection&&this.chatHistorySection.classList.remove("show")},getSessionId:function(){var e=this.inputElement.getAttribute("data-session-id");return!e&&this.widgetIsInitialized&&(e=localStorage.getItem(this.chatWidgetStateSession)),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 o=!0===t?"fa-solid fa-thumbs-up":"fa-regular fa-thumbs-up",s=document.createElement("i");s.className=o,s.style.fontSize="0.9rem",n.textContent="",n.appendChild(s)}if(i){var a=!1===t?"fa-solid fa-thumbs-down":"fa-regular fa-thumbs-down",r=document.createElement("i");r.className=a,r.style.fontSize="0.9rem",i.textContent="",i.appendChild(r)}window.FontAwesome&&FontAwesome.dom&&FontAwesome.dom.i2svg&&FontAwesome.dom.i2svg({node:e})}},refreshAllFeedbackIcons:function(){for(var e=this.$el.querySelectorAll(".ai-chat-message-assistant-feedback"),t=0;t<e.length;t++){var n=e[t].getAttribute("data-message-id"),i=this.messages.find(function(e){return e.id===n});i&&this.updateFeedbackIcons(e[t],i.userRating)}},rateMessage:function(e,t,n){var i=this.getSessionId();if(i&&e.id&&this.connection){var o=e.userRating===t?null:t;e.userRating=o;var s=this.$el.querySelector('.ai-chat-message-assistant-feedback[data-message-id="'+e.id+'"]');this.updateFeedbackIcons(s,o),null!==o&&s&&setTimeout(function(){var e=t?".rate-up-btn":".rate-down-btn",n=s.querySelector(e);n&&(n.classList.remove("spark-effect"),n.offsetWidth,n.classList.add("spark-effect"),n.addEventListener("animationend",function e(){n.removeEventListener("animationend",e),n.classList.remove("spark-effect")}))},50),this.connection.invoke("RateMessage",i,e.id,t).catch(function(e){console.error("Failed to rate message:",e)})}}},watch:{documents:{handler:function(){this.renderDocumentBar()},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(),n.widget&&e.initializeWidget();case 2:return t.a(2)}},t)}))(),window.addEventListener("beforeunload",this.handleBeforeUnload)},beforeUnmount:function(){window.removeEventListener("beforeunload",this.handleBeforeUnload),this.stream&&(this.stream.dispose(),this.stream=null),this.connection&&this.connection.stop()},template:n.messageTemplate}).mount(n.appElementSelector);console.error("The sendButtonElementSelector is required.")}else console.error("The inputElementSelector is required.");else console.error("The chatContainerElementSelector is required.");else console.error("The appElementSelector is required.");else console.error("The signalRHubUrl is required.")}}}(),document.addEventListener("click",function(e){var t=e.target.closest(".download-chart-btn");if(t){var n=t.getAttribute("data-chart-id"),i=n?document.getElementById(n):null;if(i){var o=document.createElement("a");o.download="chart-"+n+".png",o.href=i.toDataURL("image/png"),o.click()}else console.error("Chart canvas not found:",n)}}),document.addEventListener("click",function(e){var t=e.target.closest(".ai-download-image");if(t){var n=t.closest(".generated-image-container"),i=null==n?void 0:n.querySelector("img");if(i){var o=i.src;o&&o.startsWith("data:")&&(e.preventDefault(),fetch(o).then(function(e){return e.blob()}).then(function(e){var n=URL.createObjectURL(e),i=document.createElement("a");i.href=n,i.download=t.getAttribute("download")||"generated-image.png",document.body.appendChild(i),i.click(),document.body.removeChild(i),setTimeout(function(){URL.revokeObjectURL(n)},100)}).catch(function(e){console.error("Failed to download image:",e)}))}}});