RenderMax
Understand how to improve the render rate of push messages with CleverTap RenderMax.
A delivered notification doesn't always mean a rendered notification. Some original equipment manufacturers (OEMs) suppress or bypass the Google (Firebase) push delivery service to optimize battery consumption. This configuration means low notification delivery and lower render rates to your users. Your users may never see your notifications and miss important communication. To avoid this, you may have to supplement your message with other messaging channels such as Email or SMS, which means additional cost.
CleverTap RenderMax improves mobile notification render rates significantly higher by determining the state of the device and adjusting the notification rendering accordingly. Now you can engage with users you could not before and elevate ROI from your push campaigns. For example, using RenderMax can ensure the delivery of your push notifications even if the device is in battery-saving mode on inactive devices.
This feature enables you to use the power of the following:
Pull Notifications
OEM Partnerships
RenderMax Push SDK
📘 The RenderMax SDK is supported only for Android.
Mobile notifications are a great way to engage customers despite the issue of low deliverability on certain device manufacturers.
With Pull Notifications at your disposal, you can counter this challenge by optimizing the delivery of Mobile notifications to devices that missed receiving them.
🚧 Pull notifications are enabled for all the Mobile Notification campaigns that are created after toggling the Pull Notifications feature. Similarly, no new campaigns are enabled for notification delivery after you turn off the toggle.
To enable this feature, navigate to Settings > Engage > Setup > Pull Notifications . Toggle _Enable Pull Notification _in the dashboard to activate the feature.
Enable Pull Notifications on Dashboard
After Pull Notification is enabled, your campaigns reach more users through notifications. You can check the boost in numbers in the Impressions and Clicks uplift on your campaign Stats tab.
Campaign Uplift
Each OEM has a unique ecosystem that impacts mobile push delivery. However, the push experience with CleverTap is seamless across all devices. It is possible because CleverTap has leveraged its state-of-the-art technology and partnerships with different OEMs such as Xiaomi , Huawei , and Baidu .
CleverTap RenderMax Push SDK is a powerful update that delivers and renders notifications on the user's device even if the Firebase Cloud Messaging (FCM) delivery fails. You can boost push notification render rates significantly higher using RenderMax.
RenderMax solves notification rendering in the following order:
Understands the user's device state - Battery optimized vs. Unrestricted
Determines the best payload mechanism for each device state
Renders push notifications on users' devices even in a battery-optimized state
The RenderMax SDK is supported only for Android Native and React Native. To install the RenderMax SDK, refer to RenderMax Integration with Android Native and RenderMax Integration with React Native
When creating a Mobile Push Campaign, you can enable the RenderMax feature by navigating to Android Advanced Settings > RenderMax from the What section of the campaign on the CleverTap dashboard.
Enable RenderMax
🚧 RenderMax Push SDK attempts to render the notification for all campaigns with the feature enabled. The notification is rendered by the CleverTap SDK and any custom rendering done by the app is ignored for devices where the app is Device Optimized State.
For more detail on the steps, refer to the RenderMax Push Integration .
After you send out the push campaign, you can check the uplift in your notification rendering from the Push Campaign Stats page.
The feature has shown negligible [<0.1%] battery usage over two months, with eight daily notifications sent per device.
The RenderMax SDK has a size of less than 120Kb.
The RenderMax SDK has higher level permission on the notification control hierarchy, which allows the core SDK to run for a longer duration and is of higher importance in ensuring the rendering of notifications.
The RenderMax SDK is compatible with the following SDK versions on Android 12 and below:
Android v4.6.6 and above
React Native v0.9.3 and above
CleverTap Ask AI Widget (CSP-Safe)
`},codespan(n){const r=U1.decodeHtmlEntities(n);return`
${U1.escapeHtml(r)}`}};s1.use({renderer:e}),this.markedConfigured=!0}catch(e){this.logError("Failed to configure marked",e)}}static encodeBase64Unicode(e){try{if(typeof TextEncoder<"u"){const r=new TextEncoder().encode(e),i=Array.from(r,o=>String.fromCharCode(o)).join("");return btoa(i)}return btoa(unescape(encodeURIComponent(e)))}catch(n){return this.logError("Failed to encode Base64 Unicode",n),""}}static decodeBase64Unicode(e){try{if(typeof TextDecoder<"u"){const n=atob(e),r=Uint8Array.from(n,o=>o.charCodeAt(0));return new TextDecoder().decode(r)}return decodeURIComponent(escape(atob(e)))}catch(n){return this.logError("Failed to decode Base64 Unicode",n),""}}static logError(e,n){console.error(`[MarkdownRenderer] ${e}:`,n)}static normalizeBasics(e){return e=String(e).replace(/\r\n?/g,`
`),e=e.replace(/"/g,'"').replace(/\\"/g,'"').replace(/[""]/g,'"').replace(/['']/g,"'").replace(/"{2,}/g,'"'),e=e.replace(/(^|[^a-zA-Z0-9*])\*\*([^*\n]+?) +\*\*/gm,"$1**$2**"),e}static extractTables(e){const n=[],r=/(\|[^\n]+\|\n)+(\|[-:| ]+\|\n)(\|[^\n]+\|\n?)*/g;return e=e.replace(r,i=>(n.push(i),`__TABLE_PLACEHOLDER_${n.length-1}__`)),[e,n]}static restoreTables(e,n){return n.forEach((r,i)=>{e=e.replace(`__TABLE_PLACEHOLDER_${i}__`,`
${r}
`)}),e}static extractCodeBlocks(e){const n=[];return[e.replace(/^```\w*\n[\s\S]*?^```\s*$/gm,i=>(n.push(i),`__CODE_BLOCK_PLACEHOLDER_${n.length-1}__`)),n]}static restoreCodeBlocks(e,n){return n.forEach((r,i)=>{e=e.replace(`__CODE_BLOCK_PLACEHOLDER_${i}__`,r)}),e}static normalizeCodeBlocks(e){return e=e.replace(/^([ \t]+)(```\w*)\n([\s\S]*?)\n\1```/gm,(n,r,i,o)=>{const s=o.split(`
`).map(a=>a.startsWith(r)?a.slice(r.length):a).join(`
`);return`${i}
${s}
\`\`\``}),e=e.replace(/^[ \t]+(```\w*)\n/gm,`$1
`).replace(/\n[ \t]+(```)[ \t]*$/gm,`
$1`).replace(/\n[ \t]+(```)[ \t]*\n/g,`
$1
`),e=e.replace(/\n`\s*$/g,"\n```\n").replace(/\n`\s*\n/g,"\n```\n"),e=e.replace(/([^\n])(```\w)/g,`$1
$2`),e=e.replace(/(```)(\d)/g,`$1
$2`).replace(/(```)((?!`)[^\s\n])/g,`$1
$2`).replace(/(```)\s+([^\n`])/g,`$1
$2`),e=e.replace(/(```)\n(\d+\.)/g,`$1
$2`).replace(/(```)\n([-*+]\s)/g,`$1
$2`).replace(/(```)\n([A-Za-z#[(])/g,`$1
$2`),e}static normalizeHeadings(e){return e=e.replace(/\*\*([^*\n:]{5,60})\*\*\s*-\s+\*\*/g,`## $1
- **`).replace(/\*\*([^*\n:]{5,60})\*\*\s*\n([-*+]\s+)/g,`## $1
$2`),e=e.replace(/([^\n])(#{1,6}\s)/g,`$1
$2`).replace(/([^\n])\n(#{1,6}\s)/g,`$1
$2`).replace(/^(#{1,6})([^\s#])/gm,"$1 $2"),e=e.replace(/^(#{1,6}\s+[^\n]*(?:tion|ment|ance|ence|ity|ies|les|ion|ure|ness))([A-Z][a-z])/gm,`$1
$2`),e=e.replace(/^(#{1,6}\s+[^\n]*(?:SDK|API|XML))((?:You|The|In|A|An|To|Run|Add|If|On|For|Is|It|Use|Get|See|Now|This|Then|Also|Next|Here)[a-z]*)/gm,`$1
$2`),e=e.replace(/^(#{1,6}\s+[^\n]*\.(?:xml|json|yaml|yml|gradle|kt|java|swift|plist))((?:Add|You|The|In|A|An|To|Run|If|On|For|Is|It|Use|Get|See|Now|This|Then|Also|Next|Here)[a-z]*)/gmi,`$1
$2`),e=e.replace(/^(#{1,6}\s+[^\n]*[\)\]])([A-Z][a-z]{2,})/gm,`$1
$2`),e=e.replace(/^(#{1,6}\s+[^\n]+[?!])\n([A-Z]\w)/gm,`$1
$2`).replace(/^(#{1,6}\s+[^\n]+[?!])([A-Z]\w)/gm,`$1
$2`).replace(/^(#{1,6}\s+[^\n]+\.)\n([A-Z]\w)/gm,`$1
$2`).replace(/^(#{1,6}\s+[^\n]+\.)([A-Z]\w)/gm,`$1
$2`),e=e.replace(/^(#{1,6}\s+[^\n]*:)(```)/gm,`$1
$2`),e=e.replace(/^(#{1,6}\s+[^\n]*:)([A-Z][a-z])/gm,`$1
$2`),e=e.replace(/^(#{1,6}\s+[^\n]*[?!.:])([-*+]\s+\*?\*?[A-Z])/gm,`$1
$2`).replace(/^(#{1,6}\s+[^\n]*[a-zA-Z0-9"'\)\]])([-*+]\s+)/gm,`$1
$2`).replace(/^(#{1,6}\s+[^\n]*[a-zA-Z0-9"'\)\]])(\d+\.\s+)/gm,`$1
$2`),e=e.replace(/^(#{1,6}\s[^\n]+)\n([^\n#\s])/gm,`$1
$2`).replace(/^(#{1,6}\s[^\n]+)\n{3,}([^\n#\s])/gm,`$1
$2`),e}static normalizeLists(e){return e=e.replace(/([^\n])\n((?![ \t])\d+\.\s+[*A-Z])/g,`$1
$2`).replace(/([.:!?)])(\s*)(?=\n(?![ \t])\d+\.\s+[*A-Z])/g,`$1
`).replace(/([a-zA-Z])(?=\n(?![ \t])\d+\.\s+[*A-Z])/g,`$1
`),e=e.replace(/([^\n])\n((?![ \t])[-*+]\s+[A-Za-z*])/g,`$1
$2`),e=e.replace(/([?!.:])(\s*)\n((?![ \t])[-*+]\s+\*?\*?[A-Z])/g,`$1
$3`),e=e.replace(/([?!.:\)\]])\s*((?![ \t])[-*+]\s+\*?\*?[A-Z])/g,`$1
$2`),e}static normalizeSpacing(e){return e=e.replace(/^\*{3}([^*\n]+)\*{3}\s*$/gm,"**$1**"),e=e.replace(/([^\s*:]\*\*)([A-Z][a-z])/g,`$1
$2`),e=e.replace(/([^\s*:]\*\*)(\d+\.\s)/g,`$1
$2`),e=e.replace(/([^\s*:]\*\*)([-*+]\s)/g,`$1
$2`),e=e.replace(/([a-zA-Z]\))(\d+\.\s)/g,`$1
$2`),e=e.replace(/([a-zA-Z]\])(\d+\.\s)/g,`$1
$2`),e=e.replace(/([^\n])\n(\*\*[A-Z0-9])/g,`$1
$2`),e=e.replace(/:[ \t]*\n?(\*\*[A-Za-z0-9])/g,`:
$1`),e=e.replace(/(\*{1,2})\.([A-Z][a-z])/g,`$1.
$2`).replace(/([a-z)])\.(\*\*[A-Z])/g,`$1.
$2`).replace(/([a-z])\.([A-Z][a-z])/g,`$1.
$2`).replace(/:(\d+\.\s)/g,`:
$1`),e=e.replace(/(\)\.)([A-Z][a-z])/g,"$1 $2"),e=e.replace(/(\]\([^)]+\)\.)([A-Z])/g,"$1 $2"),e}static preProcess(e){if(!e)return"";e=this.normalizeBasics(e);const[n,r]=this.extractTables(e);e=n,e=this.normalizeCodeBlocks(e);const[i,o]=this.extractCodeBlocks(e);return e=i,e=this.normalizeHeadings(e),e=this.normalizeLists(e),e=this.normalizeSpacing(e),e=this.restoreTables(e,r),e=this.restoreCodeBlocks(e,o),e}static postProcess(e){return e?(e=e.replace(/
]*>\s*<\/p>/g,""),e=e.replace(/]*>\s*<\/h\1>/gi,""),e=e.replace(/ {2,}/g," "),e=e.replace(/( ){3,}/gi," "),e=e.replace(/(<\/h[1-6]>)()/gi,`$1
$2`).replace(/(<\/h[1-6]>)(
)(
)()()()()(
)()()()/gi,`$1
$2`).replace(/(<\/ol>)(
)/gi,`$1
$2`),e):""}static render(e){if(!e)return"";const n=e;if(this.renderCache.has(n))return this.renderCache.get(n);this.configureMarked();const r=this.preProcess(e);try{const i=s1.parse(r),o=this.postProcess(i);if(this.renderCache.size>=this.CACHE_SIZE_LIMIT){const s=this.renderCache.keys().next().value;s&&this.renderCache.delete(s)}return this.renderCache.set(n,o),o}catch(i){return this.logError("Failed to render markdown",i),this.postProcess(U1.escapeHtml(e))}}static clearCache(){this.renderCache.clear()}static renderStreaming(e,n,r){if(!n)return"";this.cleanupStreamingCache();const i=this.streamingCache.get(e);if(i&&i.content===n)return i.html;if(i&&n.startsWith(i.content)&&n.length>i.content.length){const s=this.render(n);return r?this.streamingCache.set(e,{content:n,html:s,timestamp:Date.now()}):this.streamingCache.delete(e),s}const o=this.render(n);return r?this.streamingCache.set(e,{content:n,html:o,timestamp:Date.now()}):this.streamingCache.delete(e),o}static clearStreamingCache(e){e?this.streamingCache.delete(e):this.streamingCache.clear()}static cleanupStreamingCache(){const e=Date.now(),n=[];this.streamingCache.forEach((r,i)=>{e-r.timestamp>this.STREAMING_CACHE_TTL&&n.push(i)}),n.forEach(r=>this.streamingCache.delete(r))}};f1(St,"markedConfigured",!1),f1(St,"renderCache",new Map),f1(St,"CACHE_SIZE_LIMIT",100),f1(St,"streamingCache",new Map),f1(St,"STREAMING_CACHE_TTL",3e5);let J5=St;class He{static getFullPayload(){return{pageURL:window.location.href,sourceName:new URLSearchParams(window.location.search).get("utm_source")||void 0,sourceURL:document.referrer||void 0,timestamp:new Date().toISOString()}}static getMinimalPayload(){return{timestamp:new Date().toISOString()}}static initSession(){const e=Date.now();this.widgetOpened(),localStorage.setItem(this.lastActiveKey,String(e))}static truncateToWords(e,n=50){if(!e)return"";const r=e.trim().split(/\s+/);return r.length<=n?e:`${r.slice(0,n).join(" ")}...`}static track(e,n={},r=!1){const o={...r?this.getFullPayload():this.getMinimalPayload(),...n},s={timestamp:o.timestamp};for(const[a,l]of Object.entries(o))l!=null&&(s[a]=l);typeof clevertap<"u"&&clevertap?.event&&clevertap.event.push(e,s)}static widgetOpened(){this.track("widget_opened",{},!0)}static widgetClosed(){this.track("widget_closed",{},!0)}static questionAsked(e){this.track("question_asked",{question:e})}static responseGenerated(e){this.track("response_generated",{response:this.truncateToWords(e,50),responseLength:e?.length||0})}static noAnswerGiven(e,n="error"){this.track("no_answer_given",{question:e,reason:n})}static linkClicked(e,n){this.track("link_clicked",{url:e,linkText:n})}static conversationCleared(){this.track("conversation_cleared")}static findQuestionForResponse(e,n,r){if(!e||!n||n.length===0)return r||"";const i=n.findIndex(o=>o.id===e);if(i>0){for(let o=i-1;o>=0;o--)if(n[o].role==="user")return n[o].content}return r||""}static feedbackGiven(e){const n=this.findQuestionForResponse(e.messageId,e.messages,e.fallbackQuestion);this.track("feedback_given",{feedbackType:e.type,question:n,response:this.truncateToWords(e.response,50)})}static dailyLimitReached(e,n){this.track("daily_limit_reached",{currentUsage:e,limit:n})}}f1(He,"lastActiveKey","ct_chat_last_active"),f1(He,"sessionTimeout",27e5);const Xn="ct_chat_usage_count",z9="ct_chat_usage_date",G9=100;class m_{constructor(e){f1(this,"config");f1(this,"apiClient");f1(this,"voiceManager",null);f1(this,"initialized",!1);f1(this,"currentQuestion","");f1(this,"customProperties",new Map);f1(this,"_state");f1(this,"onStateChangeCallback",null);f1(this,"onVoiceStateCallback",null);f1(this,"onStreamingCallback",null);f1(this,"onErrorCallback",null);f1(this,"abortController",null);this.config=e,this.apiClient=new ML(e),this._state=l1.observable({threads:new Map,messages:new Map,currentThreadId:"",currentThread:null,currentMessages:[],isCurrentThreadStreaming:!1,randomQuestions:[],voiceState:{isListening:!1,isSpeaking:!1}})}updateThreadsMap(e,n){n===null?this._state.threads.delete(e):this._state.threads.set(e,n),this._state.threads=new Map(this._state.threads)}updateMessagesMap(e,n){n===null?this._state.messages.delete(e):this._state.messages.set(e,n),this._state.messages=new Map(this._state.messages),this._state.currentMessages=this._state.messages.get(this._state.currentThreadId)||[]}setCurrentThread(e,n){this._state.currentThreadId=e,this._state.currentThread=n,this._state.currentMessages=this._state.messages.get(e)||[]}async initialize(){if(this.initialized)return!0;try{return this.config.enableVoice&&(this.voiceManager=new SL,this.setupVoiceCallbacks()),this._state.randomQuestions=U1.getRandomItems(this.config.examples,this.config.examplesCount),this.createThread("New conversation"),He.initSession(),this.initialized=!0,this.emitStateChange("ready"),!0}catch(e){return this.emitError(`Failed to initialize: ${e.message}`),!1}}setupVoiceCallbacks(){this.voiceManager&&(this.voiceManager.onResultCallback=e=>{this.sendMessage(this._state.currentThreadId,e)},this.voiceManager.onErrorCallback=e=>{(e==="not-allowed"||e==="no-speech")&&this.emitError("Microphone access denied or no speech detected")},this.voiceManager.onStateChangeCallback=(e,n)=>{e==="listening"?(this._state.voiceState.isListening=n,this.onVoiceStateCallback?.("listening",n)):e==="speaking"&&(this._state.voiceState.isSpeaking=n,this.onVoiceStateCallback?.("speaking",n))})}get isInitialized(){return this.initialized}get isStreaming(){return this._state.isCurrentThreadStreaming}get isCurrentThreadStreaming(){return this._state.isCurrentThreadStreaming}get threads(){return Array.from(this._state.threads.values())}get currentThreadId(){return this._state.currentThreadId}get currentThread(){return this._state.currentThread}get currentMessages(){return this._state.currentMessages}get threadUpdatedAt(){return this._state.currentThread?.updatedAt??null}get threadCreatedAt(){return this._state.currentThread?.createdAt??null}get randomQuestions(){return this._state.randomQuestions}setCustomProperty(e,n){this.customProperties.set(e,n)}getCustomProperty(e){return this.customProperties.get(e)}getThread(e){return this._state.threads.get(e)||null}getThreads(){return this.threads}createThread(e="New conversation",n){this.cancelStreaming();const r=n??U1.generateId(),i={id:r,title:e,messages:[],createdAt:Date.now(),updatedAt:Date.now()};return this.updateThreadsMap(r,i),this.updateMessagesMap(r,[]),this.setCurrentThread(r,i),this._state.randomQuestions=U1.getRandomItems(this.config.examples,this.config.examplesCount),r}selectThread(e){this.cancelStreaming();const n=this._state.threads.get(e);this.updateMessagesMap(e,n?.messages||[]),this.setCurrentThread(e,n??null)}async updateThread(e,n){const r=this._state.threads.get(e);r&&(n&&(r.title=n),r.updatedAt=Date.now(),this.updateThreadsMap(e,r))}async deleteThread(e){if(this.updateThreadsMap(e,null),this.updateMessagesMap(e,null),this._state.currentThreadId===e){const n=this.threads;n.length>0?this.selectThread(n[0].id):this.createThread()}}async getThreadMessages(e){return this._state.messages.get(e)||[]}getLastMessage(e){const n=this._state.messages.get(e)||[];return n[n.length-1]||null}async sendMessage(e,n){if(this._state.isCurrentThreadStreaming||!n.trim())return;if(this.checkDailyReset(),this.hasReachedLimit()){const c=this.createMessage(e,"assistant","🚫 You've reached your daily question limit. Your limit will reset tomorrow. Thank you for using CleverTap Ask AI!");this.appendMessage(e,c),He.dailyLimitReached(this.getUsage(),G9);return}this.incrementUsage(),this.currentQuestion=n,He.questionAsked(n);const r=this.createMessage(e,"user",n);this.appendMessage(e,r);const i=this.getThread(e);if(i&&(!i.title||i.title==="New conversation")){const c=n.length>30?`${n.substring(0,30)}...`:n;await this.updateThread(e,c||"New conversation")}this._state.isCurrentThreadStreaming=!0;const o=this.createMessage(e,"assistant","",!0);this.appendMessage(e,o),this.emitStateChange("streaming_started");let s="",a=0;const l=30;this.abortController=new AbortController;try{const c=this.getFormattedHistory(e),u=await this.apiClient.sendPrompt(n,c,this.abortController.signal);for await(const d of this.apiClient.streamResponse(u))if(d.type==="chunk"&&d.content){s+=d.content;const g=Date.now(),C=g-a;(a===0||C>=l||/[.!?\n]$/.test(s.trim()))&&(this.updateMessage(e,o.id,s,!0),this.onStreamingCallback?.({type:"chunk",content:s}),a=g)}else d.type==="final"&&d.content&&d.content.length>s.length&&(s=d.content);s.trim()?(this.updateMessage(e,o.id,s.trim(),!1),He.responseGenerated(s.trim()),this.onStreamingCallback?.({type:"final",content:s.trim()})):(this.updateMessage(e,o.id,"⚠️ I couldn't process your request at this time. Please rephrase your question or try again shortly.",!1),He.noAnswerGiven(n,"empty_response"),this.onStreamingCallback?.({type:"error",error:"empty_response"}))}catch(c){if(c.name==="AbortError"){this._state.isCurrentThreadStreaming=!1;return}this.updateMessage(e,o.id,"⚠️ An error occurred. Please try again."),He.noAnswerGiven(n,c.message||"error"),this.onStreamingCallback?.({type:"error",error:c.message})}finally{this._state.isCurrentThreadStreaming=!1,this.abortController=null,this.emitStateChange("streaming_stopped")}}async clearThreadMessages(e){if(!this._state.isCurrentThreadStreaming){this.updateMessagesMap(e,[]);const n=this.getThread(e);n&&(n.messages=[],this.updateThreadsMap(e,n)),this.emitStateChange("messages_cleared"),He.conversationCleared()}}cancelStreaming(){this.abortController&&(this.abortController.abort(),this.abortController=null),this._state.isCurrentThreadStreaming=!1}startListening(){this.voiceManager?.startListening()}stopListening(){this.voiceManager?.stopListening()}speak(e){this.voiceManager?.isSpeaking?this.voiceManager.stopSpeaking():this.voiceManager?.speak(e)}stopSpeaking(){this.voiceManager?.stopSpeaking()}handleFeedback(e,n,r){const i=this._state.currentMessages;let o=this.currentQuestion;if(r){const s=i.findIndex(a=>a.id===r);if(s>0){for(let a=s-1;a>=0;a--)if(i[a].role==="user"){o=i[a].content;break}}}He.feedbackGiven({type:e,response:n,messageId:r,messages:i,fallbackQuestion:this.currentQuestion}),this.apiClient.sendFeedback({feedbackType:e,question:o,response:n,messageId:r})}handleLinkClick(e,n){He.linkClicked(e,n)}destroy(){this.voiceManager?.stopListening(),this.voiceManager?.stopSpeaking(),He.widgetClosed()}setOnStateChange(e){this.onStateChangeCallback=e}setOnVoiceState(e){this.onVoiceStateCallback=e}setOnStreaming(e){this.onStreamingCallback=e}setOnError(e){this.onErrorCallback=e}createMessage(e,n,r,i=!1){return{id:U1.generateId(),threadId:e,role:n,content:r,timestamp:Date.now(),isStreaming:i}}appendMessage(e,n){const r=[...this._state.messages.get(e)||[],n];this.updateMessagesMap(e,r);const i=this.getThread(e);i&&(i.messages=r,i.updatedAt=Date.now(),this.updateThreadsMap(e,i)),this.emitStateChange("messages_updated")}updateMessage(e,n,r,i=!1){const o=this._state.messages.get(e)||[],s=o.find(a=>a.id===n);if(s){s.content=r,s.isStreaming=i,this.updateMessagesMap(e,[...o]);const a=this.getThread(e);a&&(a.messages=o,this.updateThreadsMap(e,a)),this.emitStateChange("messages_updated")}}getFormattedHistory(e){return(this._state.messages.get(e)||[]).filter(r=>!r.isStreaming&&r.content.trim()).slice(-20).map(r=>[r.role,r.content])}emitStateChange(e){this.onStateChangeCallback?.(e)}emitError(e){this.onErrorCallback?.(e)}checkDailyReset(){const e=new Date().toDateString();U1.getCookie(z9)!==e&&(U1.setDailyCookie(z9,e),U1.setDailyCookie(Xn,"0"))}getUsage(){return Number(U1.getCookie(Xn)||0)}incrementUsage(){const e=this.getUsage()+1;return U1.setDailyCookie(Xn,String(e)),e}hasReachedLimit(){return this.getUsage()>=G9}}/*! @license DOMPurify 3.2.6 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.2.6/LICENSE */const{entries:W9,setPrototypeOf:j9,isFrozen:L_,getPrototypeOf:w_,getOwnPropertyDescriptor:b_}=Object;let{freeze:oe,seal:Ze,create:K9}=Object,{apply:Qn,construct:Jn}=typeof Reflect<"u"&&Reflect;oe||(oe=function(e){return e}),Ze||(Ze=function(e){return e}),Qn||(Qn=function(e,n,r){return e.apply(n,r)}),Jn||(Jn=function(e,n){return new e(...n)});const u3=ae(Array.prototype.forEach),__=ae(Array.prototype.lastIndexOf),q9=ae(Array.prototype.pop),e2=ae(Array.prototype.push),E_=ae(Array.prototype.splice),d3=ae(String.prototype.toLowerCase),e7=ae(String.prototype.toString),Y9=ae(String.prototype.match),t2=ae(String.prototype.replace),y_=ae(String.prototype.indexOf),x_=ae(String.prototype.trim),Fe=ae(Object.prototype.hasOwnProperty),se=ae(RegExp.prototype.test),n2=M_(TypeError);function ae(t){return function(e){e instanceof RegExp&&(e.lastIndex=0);for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i2&&arguments[2]!==void 0?arguments[2]:d3;j9&&j9(t,null);let r=e.length;for(;r--;){let i=e[r];if(typeof i=="string"){const o=n(i);o!==i&&(L_(e)||(e[r]=o),i=o)}t[i]=!0}return t}function S_(t){for(let e=0;e/gm),N_=Ze(/\$\{[\w\W]*/gm),R_=Ze(/^data-[\-\w.\u00B7-\uFFFF]+$/),I_=Ze(/^aria-[\-\w]+$/),t8=Ze(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),H_=Ze(/^(?:\w+script|data):/i),Z_=Ze(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),n8=Ze(/^html$/i),D_=Ze(/^[a-z][.\w]*(-[.\w]+)+$/i);var r8=Object.freeze({__proto__:null,ARIA_ATTR:I_,ATTR_WHITESPACE:Z_,CUSTOM_ELEMENT:D_,DATA_ATTR:R_,DOCTYPE_NAME:n8,ERB_EXPR:k_,IS_ALLOWED_URI:t8,IS_SCRIPT_OR_DATA:H_,MUSTACHE_EXPR:O_,TMPLIT_EXPR:N_});const i2={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},V_=function(){return typeof window>"u"?null:window},B_=function(e,n){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let r=null;const i="data-tt-policy-suffix";n&&n.hasAttribute(i)&&(r=n.getAttribute(i));const o="dompurify"+(r?"#"+r:"");try{return e.createPolicy(o,{createHTML(s){return s},createScriptURL(s){return s}})}catch{return console.warn("TrustedTypes policy "+o+" could not be created."),null}},i8=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function o8(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:V_();const e=i1=>o8(i1);if(e.version="3.2.6",e.removed=[],!t||!t.document||t.document.nodeType!==i2.document||!t.Element)return e.isSupported=!1,e;let{document:n}=t;const r=n,i=r.currentScript,{DocumentFragment:o,HTMLTemplateElement:s,Node:a,Element:l,NodeFilter:c,NamedNodeMap:u=t.NamedNodeMap||t.MozNamedAttrMap,HTMLFormElement:d,DOMParser:g,trustedTypes:C}=t,S=l.prototype,A=r2(S,"cloneNode"),k=r2(S,"remove"),Z=r2(S,"nextSibling"),$=r2(S,"childNodes"),P=r2(S,"parentNode");if(typeof s=="function"){const i1=n.createElement("template");i1.content&&i1.content.ownerDocument&&(n=i1.content.ownerDocument)}let O,U="";const{implementation:I,createNodeIterator:F,createDocumentFragment:Q,getElementsByTagName:r1}=n,{importNode:v1}=r;let a1=i8();e.isSupported=typeof W9=="function"&&typeof P=="function"&&I&&I.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:m,ERB_EXPR:h,TMPLIT_EXPR:E,DATA_ATTR:D,ARIA_ATTR:z,IS_SCRIPT_OR_DATA:b,ATTR_WHITESPACE:x,CUSTOM_ELEMENT:H}=r8;let{IS_ALLOWED_URI:B}=r8,N=null;const G=w1({},[...X9,...t7,...n7,...r7,...Q9]);let X=null;const p1=w1({},[...J9,...i7,...e8,...C3]);let t1=Object.seal(K9(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),b1=null,D1=null,O1=!0,A1=!0,ze=!1,ce=!0,ue=!1,L1=!0,V1=!1,ee=!1,P1=!1,Ae=!1,Ve=!1,o1=!1,de=!0,M1=!1;const E1="user-content-";let Ce=!0,L=!1,M={},R=null;const w=w1({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let T=null;const n1=w1({},["audio","video","img","source","image","track"]);let W=null;const e1=w1({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Y="http://www.w3.org/1998/Math/MathML",m1="http://www.w3.org/2000/svg",h1="http://www.w3.org/1999/xhtml";let pe=h1,w5=!1,a7=null;const P_=w1({},[Y,m1,h1],e7);let h3=w1({},["mi","mo","mn","ms","mtext"]),g3=w1({},["annotation-xml"]);const U_=w1({},["title","style","font","a","script"]);let a2=null;const F_=["application/xhtml+xml","text/html"],z_="text/html";let K1=null,b5=null;const G_=n.createElement("form"),g8=function(p){return p instanceof RegExp||p instanceof Function},l7=function(){let p=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(b5&&b5===p)){if((!p||typeof p!="object")&&(p={}),p=it(p),a2=F_.indexOf(p.PARSER_MEDIA_TYPE)===-1?z_:p.PARSER_MEDIA_TYPE,K1=a2==="application/xhtml+xml"?e7:d3,N=Fe(p,"ALLOWED_TAGS")?w1({},p.ALLOWED_TAGS,K1):G,X=Fe(p,"ALLOWED_ATTR")?w1({},p.ALLOWED_ATTR,K1):p1,a7=Fe(p,"ALLOWED_NAMESPACES")?w1({},p.ALLOWED_NAMESPACES,e7):P_,W=Fe(p,"ADD_URI_SAFE_ATTR")?w1(it(e1),p.ADD_URI_SAFE_ATTR,K1):e1,T=Fe(p,"ADD_DATA_URI_TAGS")?w1(it(n1),p.ADD_DATA_URI_TAGS,K1):n1,R=Fe(p,"FORBID_CONTENTS")?w1({},p.FORBID_CONTENTS,K1):w,b1=Fe(p,"FORBID_TAGS")?w1({},p.FORBID_TAGS,K1):it({}),D1=Fe(p,"FORBID_ATTR")?w1({},p.FORBID_ATTR,K1):it({}),M=Fe(p,"USE_PROFILES")?p.USE_PROFILES:!1,O1=p.ALLOW_ARIA_ATTR!==!1,A1=p.ALLOW_DATA_ATTR!==!1,ze=p.ALLOW_UNKNOWN_PROTOCOLS||!1,ce=p.ALLOW_SELF_CLOSE_IN_ATTR!==!1,ue=p.SAFE_FOR_TEMPLATES||!1,L1=p.SAFE_FOR_XML!==!1,V1=p.WHOLE_DOCUMENT||!1,Ae=p.RETURN_DOM||!1,Ve=p.RETURN_DOM_FRAGMENT||!1,o1=p.RETURN_TRUSTED_TYPE||!1,P1=p.FORCE_BODY||!1,de=p.SANITIZE_DOM!==!1,M1=p.SANITIZE_NAMED_PROPS||!1,Ce=p.KEEP_CONTENT!==!1,L=p.IN_PLACE||!1,B=p.ALLOWED_URI_REGEXP||t8,pe=p.NAMESPACE||h1,h3=p.MATHML_TEXT_INTEGRATION_POINTS||h3,g3=p.HTML_INTEGRATION_POINTS||g3,t1=p.CUSTOM_ELEMENT_HANDLING||{},p.CUSTOM_ELEMENT_HANDLING&&g8(p.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(t1.tagNameCheck=p.CUSTOM_ELEMENT_HANDLING.tagNameCheck),p.CUSTOM_ELEMENT_HANDLING&&g8(p.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(t1.attributeNameCheck=p.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),p.CUSTOM_ELEMENT_HANDLING&&typeof p.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(t1.allowCustomizedBuiltInElements=p.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),ue&&(A1=!1),Ve&&(Ae=!0),M&&(N=w1({},Q9),X=[],M.html===!0&&(w1(N,X9),w1(X,J9)),M.svg===!0&&(w1(N,t7),w1(X,i7),w1(X,C3)),M.svgFilters===!0&&(w1(N,n7),w1(X,i7),w1(X,C3)),M.mathMl===!0&&(w1(N,r7),w1(X,e8),w1(X,C3))),p.ADD_TAGS&&(N===G&&(N=it(N)),w1(N,p.ADD_TAGS,K1)),p.ADD_ATTR&&(X===p1&&(X=it(X)),w1(X,p.ADD_ATTR,K1)),p.ADD_URI_SAFE_ATTR&&w1(W,p.ADD_URI_SAFE_ATTR,K1),p.FORBID_CONTENTS&&(R===w&&(R=it(R)),w1(R,p.FORBID_CONTENTS,K1)),Ce&&(N["#text"]=!0),V1&&w1(N,["html","head","body"]),N.table&&(w1(N,["tbody"]),delete b1.tbody),p.TRUSTED_TYPES_POLICY){if(typeof p.TRUSTED_TYPES_POLICY.createHTML!="function")throw n2('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof p.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw n2('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');O=p.TRUSTED_TYPES_POLICY,U=O.createHTML("")}else O===void 0&&(O=B_(C,i)),O!==null&&typeof U=="string"&&(U=O.createHTML(""));oe&&oe(p),b5=p}},v8=w1({},[...t7,...n7,...A_]),m8=w1({},[...r7,...T_]),W_=function(p){let V=P(p);(!V||!V.tagName)&&(V={namespaceURI:pe,tagName:"template"});const J=d3(p.tagName),I1=d3(V.tagName);return a7[p.namespaceURI]?p.namespaceURI===m1?V.namespaceURI===h1?J==="svg":V.namespaceURI===Y?J==="svg"&&(I1==="annotation-xml"||h3[I1]):!!v8[J]:p.namespaceURI===Y?V.namespaceURI===h1?J==="math":V.namespaceURI===m1?J==="math"&&g3[I1]:!!m8[J]:p.namespaceURI===h1?V.namespaceURI===m1&&!g3[I1]||V.namespaceURI===Y&&!h3[I1]?!1:!m8[J]&&(U_[J]||!v8[J]):!!(a2==="application/xhtml+xml"&&a7[p.namespaceURI]):!1},Ye=function(p){e2(e.removed,{element:p});try{P(p).removeChild(p)}catch{k(p)}},_5=function(p,V){try{e2(e.removed,{attribute:V.getAttributeNode(p),from:V})}catch{e2(e.removed,{attribute:null,from:V})}if(V.removeAttribute(p),p==="is")if(Ae||Ve)try{Ye(V)}catch{}else try{V.setAttribute(p,"")}catch{}},L8=function(p){let V=null,J=null;if(P1)p=" "+p;else{const G1=Y9(p,/^[\r\n\t ]+/);J=G1&&G1[0]}a2==="application/xhtml+xml"&&pe===h1&&(p=''+p+"");const I1=O?O.createHTML(p):p;if(pe===h1)try{V=new g().parseFromString(I1,a2)}catch{}if(!V||!V.documentElement){V=I.createDocument(pe,"template",null);try{V.documentElement.innerHTML=w5?U:I1}catch{}}const te=V.body||V.documentElement;return p&&J&&te.insertBefore(n.createTextNode(J),te.childNodes[0]||null),pe===h1?r1.call(V,V1?"html":"body")[0]:V1?V.documentElement:te},w8=function(p){return F.call(p.ownerDocument||p,p,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},c7=function(p){return p instanceof d&&(typeof p.nodeName!="string"||typeof p.textContent!="string"||typeof p.removeChild!="function"||!(p.attributes instanceof u)||typeof p.removeAttribute!="function"||typeof p.setAttribute!="function"||typeof p.namespaceURI!="string"||typeof p.insertBefore!="function"||typeof p.hasChildNodes!="function")},b8=function(p){return typeof a=="function"&&p instanceof a};function at(i1,p,V){u3(i1,J=>{J.call(e,p,V,b5)})}const _8=function(p){let V=null;if(at(a1.beforeSanitizeElements,p,null),c7(p))return Ye(p),!0;const J=K1(p.nodeName);if(at(a1.uponSanitizeElement,p,{tagName:J,allowedTags:N}),L1&&p.hasChildNodes()&&!b8(p.firstElementChild)&&se(/<[/\w!]/g,p.innerHTML)&&se(/<[/\w!]/g,p.textContent)||p.nodeType===i2.progressingInstruction||L1&&p.nodeType===i2.comment&&se(/<[/\w]/g,p.data))return Ye(p),!0;if(!N[J]||b1[J]){if(!b1[J]&&y8(J)&&(t1.tagNameCheck instanceof RegExp&&se(t1.tagNameCheck,J)||t1.tagNameCheck instanceof Function&&t1.tagNameCheck(J)))return!1;if(Ce&&!R[J]){const I1=P(p)||p.parentNode,te=$(p)||p.childNodes;if(te&&I1){const G1=te.length;for(let be=G1-1;be>=0;--be){const lt=A(te[be],!0);lt.__removalCount=(p.__removalCount||0)+1,I1.insertBefore(lt,Z(p))}}}return Ye(p),!0}return p instanceof l&&!W_(p)||(J==="noscript"||J==="noembed"||J==="noframes")&&se(/<\/no(script|embed|frames)/i,p.innerHTML)?(Ye(p),!0):(ue&&p.nodeType===i2.text&&(V=p.textContent,u3([m,h,E],I1=>{V=t2(V,I1," ")}),p.textContent!==V&&(e2(e.removed,{element:p.cloneNode()}),p.textContent=V)),at(a1.afterSanitizeElements,p,null),!1)},E8=function(p,V,J){if(de&&(V==="id"||V==="name")&&(J in n||J in G_))return!1;if(!(A1&&!D1[V]&&se(D,V))){if(!(O1&&se(z,V))){if(!X[V]||D1[V]){if(!(y8(p)&&(t1.tagNameCheck instanceof RegExp&&se(t1.tagNameCheck,p)||t1.tagNameCheck instanceof Function&&t1.tagNameCheck(p))&&(t1.attributeNameCheck instanceof RegExp&&se(t1.attributeNameCheck,V)||t1.attributeNameCheck instanceof Function&&t1.attributeNameCheck(V))||V==="is"&&t1.allowCustomizedBuiltInElements&&(t1.tagNameCheck instanceof RegExp&&se(t1.tagNameCheck,J)||t1.tagNameCheck instanceof Function&&t1.tagNameCheck(J))))return!1}else if(!W[V]){if(!se(B,t2(J,x,""))){if(!((V==="src"||V==="xlink:href"||V==="href")&&p!=="script"&&y_(J,"data:")===0&&T[p])){if(!(ze&&!se(b,t2(J,x,"")))){if(J)return!1}}}}}}return!0},y8=function(p){return p!=="annotation-xml"&&Y9(p,H)},x8=function(p){at(a1.beforeSanitizeAttributes,p,null);const{attributes:V}=p;if(!V||c7(p))return;const J={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:X,forceKeepAttr:void 0};let I1=V.length;for(;I1--;){const te=V[I1],{name:G1,namespaceURI:be,value:lt}=te,l2=K1(G1),u7=lt;let ne=G1==="value"?u7:x_(u7);if(J.attrName=l2,J.attrValue=ne,J.keepAttr=!0,J.forceKeepAttr=void 0,at(a1.uponSanitizeAttribute,p,J),ne=J.attrValue,M1&&(l2==="id"||l2==="name")&&(_5(G1,p),ne=E1+ne),L1&&se(/((--!?|])>)|<\/(style|title)/i,ne)){_5(G1,p);continue}if(J.forceKeepAttr)continue;if(!J.keepAttr){_5(G1,p);continue}if(!ce&&se(/\/>/i,ne)){_5(G1,p);continue}ue&&u3([m,h,E],S8=>{ne=t2(ne,S8," ")});const M8=K1(p.nodeName);if(!E8(M8,l2,ne)){_5(G1,p);continue}if(O&&typeof C=="object"&&typeof C.getAttributeType=="function"&&!be)switch(C.getAttributeType(M8,l2)){case"TrustedHTML":{ne=O.createHTML(ne);break}case"TrustedScriptURL":{ne=O.createScriptURL(ne);break}}if(ne!==u7)try{be?p.setAttributeNS(be,G1,ne):p.setAttribute(G1,ne),c7(p)?Ye(p):q9(e.removed)}catch{_5(G1,p)}}at(a1.afterSanitizeAttributes,p,null)},j_=function i1(p){let V=null;const J=w8(p);for(at(a1.beforeSanitizeShadowDOM,p,null);V=J.nextNode();)at(a1.uponSanitizeShadowNode,V,null),_8(V),x8(V),V.content instanceof o&&i1(V.content);at(a1.afterSanitizeShadowDOM,p,null)};return e.sanitize=function(i1){let p=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},V=null,J=null,I1=null,te=null;if(w5=!i1,w5&&(i1="<\x21--\x3e"),typeof i1!="string"&&!b8(i1))if(typeof i1.toString=="function"){if(i1=i1.toString(),typeof i1!="string")throw n2("dirty is not a string, aborting")}else throw n2("toString is not a function");if(!e.isSupported)return i1;if(ee||l7(p),e.removed=[],typeof i1=="string"&&(L=!1),L){if(i1.nodeName){const lt=K1(i1.nodeName);if(!N[lt]||b1[lt])throw n2("root node is forbidden and cannot be sanitized in-place")}}else if(i1 instanceof a)V=L8("<\x21----\x3e"),J=V.ownerDocument.importNode(i1,!0),J.nodeType===i2.element&&J.nodeName==="BODY"||J.nodeName==="HTML"?V=J:V.appendChild(J);else{if(!Ae&&!ue&&!V1&&i1.indexOf("<")===-1)return O&&o1?O.createHTML(i1):i1;if(V=L8(i1),!V)return Ae?null:o1?U:""}V&&P1&&Ye(V.firstChild);const G1=w8(L?i1:V);for(;I1=G1.nextNode();)_8(I1),x8(I1),I1.content instanceof o&&j_(I1.content);if(L)return i1;if(Ae){if(Ve)for(te=Q.call(V.ownerDocument);V.firstChild;)te.appendChild(V.firstChild);else te=V;return(X.shadowroot||X.shadowrootmode)&&(te=v1.call(r,te,!0)),te}let be=V1?V.outerHTML:V.innerHTML;return V1&&N["!doctype"]&&V.ownerDocument&&V.ownerDocument.doctype&&V.ownerDocument.doctype.name&&se(n8,V.ownerDocument.doctype.name)&&(be="
`+be),ue&&u3([m,h,E],lt=>{be=t2(be,lt," ")}),O&&o1?O.createHTML(be):be},e.setConfig=function(){let i1=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};l7(i1),ee=!0},e.clearConfig=function(){b5=null,ee=!1},e.isValidAttribute=function(i1,p,V){b5||l7({});const J=K1(i1),I1=K1(p);return E8(J,I1,V)},e.addHook=function(i1,p){typeof p=="function"&&e2(a1[i1],p)},e.removeHook=function(i1,p){if(p!==void 0){const V=__(a1[i1],p);return V===-1?void 0:E_(a1[i1],V,1)[0]}return q9(a1[i1])},e.removeHooks=function(i1){a1[i1]=[]},e.removeAllHooks=function(){a1=i8()},e}var s8=o8();const a8={USE_PROFILES:{html:!0},ALLOWED_TAGS:["p","div","span","br","strong","em","u","a","ul","ol","li","code","pre","h1","h2","h3","h4","h5","h6","blockquote","hr","table","thead","tbody","tr","th","td","img","button","svg","rect","path"],ALLOWED_ATTR:["href","target","class","id","src","alt","width","height","rel","title","data-code","data-language","loading","viewBox","fill","stroke","stroke-width","d","x","y","rx","ry","xmlns","fill-rule","clip-rule"]},l8=(t,e)=>{t.innerHTML=s8.sanitize(e.value||"",a8)},$_={bind:l8,update:l8},c8=t=>s8.sanitize(t,a8);var xt;let Se=xt=class extends l1{constructor(){super(...arguments),Object.defineProperty(this,"message",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"enableVoice",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"isSpeaking",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"feedbackGiven",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"codeBlockInstances",{enumerable:!0,configurable:!0,writable:!0,value:[]})}get isUser(){return this.message.role==="user"}get isAssistant(){return this.message.role==="assistant"}get showLoadingIndicator(){return this.message.isStreaming===!0&&this.message.content.trim()===""}get isStreamingWithContent(){return this.message.isStreaming===!0&&this.message.content.trim().length>0}get sanitizedUserContent(){return c8(U1.escapeHtml(this.message.content))}get renderedAssistantContent(){const e=J5.renderStreaming(this.message.id,this.message.content,this.message.isStreaming??!1);return c8(e)}mounted(){this.$nextTick(()=>this.mountCodeBlocks())}updated(){this.$nextTick(()=>this.mountCodeBlocks())}beforeDestroy(){this.destroyCodeBlocks(),J5.clearStreamingCache(this.message.id)}render(){return this.isUser?this.renderUserMessage():this.renderAssistantMessage()}renderUserMessage(){const e=this.$createElement;return e("div",{class:"ct-user-message"},[e("div",{class:"ct-user-query",directives:[{name:"safe-html",value:this.sanitizedUserContent}],on:{click:this.handleLinkClick}})])}renderAssistantMessage(){const e=this.$createElement,n=this.message.content.trim().length>0;return e("div",{class:"ct-ai-message-container"},[e("div",{class:"ct-ai-message-content"},[(n||this.showLoadingIndicator)&&e("div",{class:"ct-ai-message-final"},[e("div",{class:"ct-ai-message-icon-container"},[e(j,{attrs:{type:j.Type.ASK_AI,size:xt.AVATAR_ICON_SIZE},class:"ct-ask-logo"})]),e("div",{class:"ct-ai-message-body"},[this.showLoadingIndicator&&e("i",{class:"ct-status-line"},["Thinking..."]),n&&e("div",{class:["ct-ai-message",{"ct-streaming":this.isStreamingWithContent}],directives:[{name:"safe-html",value:this.renderedAssistantContent}],on:{click:this.handleLinkClick}}),this.isStreamingWithContent&&e("span",{class:"ct-streaming-cursor"})])]),!this.message.isStreaming&&n&&this.renderMessageActions()])])}renderMessageActions(){const e=this.$createElement;return e("div",{class:"ct-message-actions"},[e("div",{class:"ct-actions-primary"},[e(Ft,{class:"ct-action-btn",attrs:{text:this.message.content,tooltipText:"Copy",tooltipTextCopied:"Copied!"}})]),e("div",{class:"ct-actions-feedback"},[e(q1,{class:["ct-fb-btn",{"ct-active-good":this.feedbackGiven==="good"}],attrs:{tooltip:"Good Answer",stopPropagation:!0,iconSize:xt.ACTION_ICON_SIZE,icon:j.Type.THUMBS_UP,color:this.feedbackGiven==="good"?K.Color.SUCCESS:K.Color.LIGHT,disabled:!!this.feedbackGiven},on:{click:()=>this.handleFeedback("good")}}),e(q1,{class:["ct-fb-btn",{"ct-active-bad":this.feedbackGiven==="bad"}],attrs:{tooltip:"Bad Answer",stopPropagation:!0,iconSize:xt.ACTION_ICON_SIZE,icon:j.Type.THUMBS_DOWN,color:this.feedbackGiven==="bad"?K.Color.DANGER:K.Color.LIGHT,disabled:!!this.feedbackGiven},on:{click:()=>this.handleFeedback("bad")}})])])}onContentChange(){this.message.isStreaming||this.$nextTick(()=>this.mountCodeBlocks())}onStreamingChange(e){e||this.$nextTick(()=>this.mountCodeBlocks())}handleSpeak(){this.$emit(xt.Event.SPEAK,this.message.content)}handleFeedback(e){this.feedbackGiven=e,this.$emit(xt.Event.FEEDBACK,e,this.message.content,this.message.id)}handleLinkClick(e){const r=e.target.closest("a");r?.href&&!r.closest(".ct-message-actions")&&(e.preventDefault(),window.open(r.href,"_blank","noopener,noreferrer"),this.$emit(xt.Event.LINK_CLICK,r.href,r.textContent?.trim()||r.href))}mountCodeBlocks(){if(!this.$el||this.isUser||this.message.isStreaming)return;const e=this.$el.querySelector(".ct-ai-message");if(!e)return;const n=e.querySelectorAll(".ct-code-placeholder");if(n.length===0)return;this.destroyCodeBlocks();const r=Array.from(n).map(i=>i.getAttribute("data-language")||"text").filter((i,o,s)=>s.indexOf(i)===o);v_(r),n.forEach(i=>{const o=i.getAttribute("data-code"),s=i.getAttribute("data-language")||"text";if(o)try{const a=J5.decodeBase64Unicode(o);if(!a)return;const l=document.createElement("div");l.className="ct-code-block-wrapper",i.parentNode?.replaceChild(l,i);const c=l1.extend(Ie),u=new c({propsData:{text:a,language:s,showCopyButton:!0,tooltipText:"Copy",tooltipTextCopied:"Copied!"}});u.$mount(),l.appendChild(u.$el),this.codeBlockInstances.push(u)}catch(a){console.error("[ChatMessage] Failed to mount code block:",a)}})}destroyCodeBlocks(){this.codeBlockInstances.forEach(e=>{e.$destroy()}),this.codeBlockInstances=[]}};Object.defineProperty(Se,"AVATAR_ICON_SIZE",{enumerable:!0,configurable:!0,writable:!0,value:20}),Object.defineProperty(Se,"ACTION_ICON_SIZE",{enumerable:!0,configurable:!0,writable:!0,value:16}),v([y({type:Object,required:!0,validator:t=>!!t&&["user","assistant"].includes(t.role)}),f("design:type",Object)],Se.prototype,"message",void 0),v([y({type:Boolean,default:!1}),f("design:type",Boolean)],Se.prototype,"enableVoice",void 0),v([y({type:Boolean,default:!1}),f("design:type",Boolean)],Se.prototype,"isSpeaking",void 0),v([ge("message.content"),f("design:type",Function),f("design:paramtypes",[]),f("design:returntype",void 0)],Se.prototype,"onContentChange",null),v([ge("message.isStreaming"),f("design:type",Function),f("design:paramtypes",[Boolean]),f("design:returntype",void 0)],Se.prototype,"onStreamingChange",null),Se=xt=v([Z1({name:"ChatMessage",directives:{"safe-html":$_}})],Se),function(t){(function(e){e.COPY="copy",e.SPEAK="speak",e.FEEDBACK="feedback",e.LINK_CLICK="link-click"})(t.Event||(t.Event={}))}(Se||(Se={}));var ot,u8;let $1=ot=class extends l1{constructor(){super(...arguments),Object.defineProperty(this,"projectName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sendMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stopRun",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"isStreaming",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"disabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"enableVoice",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"isListening",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hasMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"startingText",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"textareaRef",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"text",{enumerable:!0,configurable:!0,writable:!0,value:""})}get placeholder(){return this.isListening?"Listening...":this.isStreaming?"AI is thinking...":"Search or ask a question..."}get textValue(){return this.text||this.startingText}onTextChange(){this.$nextTick(()=>this.adjustTextareaHeight())}onStartingTextChange(e){this.$nextTick(()=>{e&&(this.focus(),this.adjustTextareaHeight())})}mounted(){this.adjustTextareaHeight()}focus(){this.textareaRef?.focus()}render(){const e=arguments[0];return e("div",{class:"ct-composer-footer drag-cancel"},[e("div",{class:"ct-composer-container"},[e(K,{class:"ct-action-btn ct-clear-btn",attrs:{tooltip:"Clear conversation",size:ot.DELETE_BUTTON_SIZE,iconSize:ot.DELETE_ICON_SIZE,icon:j.Type.DELETE,color:K.Color.LIGHT,disabled:this.isStreaming||!this.hasMessages},on:{click:this.handleClear}}),e("div",{class:"ct-input-wrapper"},[e("textarea",{ref:"textarea",class:"ct-input",attrs:{autocomplete:"none",placeholder:this.placeholder,disabled:this.disabled||this.isStreaming,rows:1},domProps:{value:this.textValue},on:{input:n=>{this.text=n.target.value},keydown:this.handleKeyDown}}),e("div",{class:"ct-input-actions"},[this.enableVoice&&e(q1,{class:["ct-action-btn ct-voice-btn",{"ct-listening":this.isListening}],attrs:{tooltip:"Voice input",iconSize:ot.DEFAULT_ICON_SIZE,icon:j.Type.MIC,color:this.isListening?K.Color.DANGER:K.Color.PRIMARY,appearance:this.isListening?K.Appearance.OUTLINE:K.Appearance.LIGHTEN},on:{click:this.handleVoice}}),this.isStreaming?e("button",{class:"ct-submit-btn",on:{click:this.handleStop}},[e(j,{attrs:{type:j.Type.ASK_AI_LOADING,size:24},class:"ct-ask-ai-icon"})]):e("button",{class:"ct-submit-btn",attrs:{disabled:this.disabled||!this.text.trim()},on:{click:this.handleSend}},[this.disabled?e(j,{attrs:{type:j.Type.ASK_AI_LOADING,size:24},class:"ct-ask-ai-icon"}):e(j,{attrs:{type:j.Type.ASK_AI,size:24},class:"ct-ask-ai-icon"})])])])]),e("div",{class:"ct-disclaimer"},["Powered by CleverAI. Responses may have inaccuracies. Please verify important info."])])}adjustTextareaHeight(){const e=this.textareaRef;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)}handleKeyDown(e){e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),this.handleSend())}handleSend(){const e=this.text.trim();e&&!this.disabled&&!this.isStreaming&&(this.sendMessage&&this.sendMessage(e),this.$emit(ot.Event.SEND,e),this.text="",this.$nextTick(()=>{this.adjustTextareaHeight()}))}handleStop(){this.stopRun&&this.stopRun(),this.$emit(ot.Event.STOP)}handleClear(){this.isStreaming||this.$emit(ot.Event.CLEAR)}handleVoice(){this.$emit(ot.Event.VOICE)}};Object.defineProperty($1,"DEFAULT_ICON_SIZE",{enumerable:!0,configurable:!0,writable:!0,value:16}),Object.defineProperty($1,"DELETE_BUTTON_SIZE",{enumerable:!0,configurable:!0,writable:!0,value:"48px"}),Object.defineProperty($1,"DELETE_ICON_SIZE",{enumerable:!0,configurable:!0,writable:!0,value:20}),v([y({type:String,required:!0}),f("design:type",String)],$1.prototype,"projectName",void 0),v([y({type:Function,required:!1}),f("design:type",Function)],$1.prototype,"sendMessage",void 0),v([y({type:Function,required:!1}),f("design:type",Function)],$1.prototype,"stopRun",void 0),v([y({type:Boolean,default:!1}),f("design:type",Boolean)],$1.prototype,"isStreaming",void 0),v([y({type:Boolean,default:!1}),f("design:type",Boolean)],$1.prototype,"disabled",void 0),v([y({type:Boolean,default:!1}),f("design:type",Boolean)],$1.prototype,"enableVoice",void 0),v([y({type:Boolean,default:!1}),f("design:type",Boolean)],$1.prototype,"isListening",void 0),v([y({type:Boolean,default:!1}),f("design:type",Boolean)],$1.prototype,"hasMessages",void 0),v([y({default:""}),f("design:type",String)],$1.prototype,"startingText",void 0),v([hn("textarea"),f("design:type",typeof(u8=typeof HTMLTextAreaElement<"u"&&HTMLTextAreaElement)=="function"?u8:Object)],$1.prototype,"textareaRef",void 0),v([ge("text"),f("design:type",Function),f("design:paramtypes",[]),f("design:returntype",void 0)],$1.prototype,"onTextChange",null),v([ge("startingText",{immediate:!0}),f("design:type",Function),f("design:paramtypes",[String]),f("design:returntype",void 0)],$1.prototype,"onStartingTextChange",null),$1=ot=v([Z1({name:"ChatComposer"})],$1),function(t){(function(e){e.SEND="send",e.STOP="stop",e.CLEAR="clear",e.VOICE="voice"})(t.Event||(t.Event={}))}($1||($1={}));var o7;let Kt=o7=class extends l1{constructor(){super(...arguments),Object.defineProperty(this,"question",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}render(){const e=arguments[0];return e("button",{class:"ct-query-pill",on:{click:this.handleClick}},[this.question])}handleClick(){this.$emit(o7.Event.SELECT,this.question)}};v([y({type:String,required:!0}),f("design:type",String)],Kt.prototype,"question",void 0),Kt=o7=v([Z1({name:"QueryPill"})],Kt),function(t){(function(e){e.SELECT="select"})(t.Event||(t.Event={}))}(Kt||(Kt={}));var o2,d8,C8,p8;let Y1=o2=class extends l1{constructor(){super(...arguments),Object.defineProperty(this,"messageContainerRef",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"widgetRuntime",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"projectName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"enableVoice",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"isAtBottom",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"isAtTop",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"messages",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"isStreaming",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"isListening",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"isSpeaking",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"randomQuestions",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"currentQuestionIndex",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"hasScrollableContent",{enumerable:!0,configurable:!0,writable:!0,value:!1})}get isEmpty(){return this.messages.length===0}checkScrollableContent(){const e=this.messageContainerRef;e?this.hasScrollableContent=e.scrollHeight>e.clientHeight:this.hasScrollableContent=!1}get questionIndices(){return this.messages.map((e,n)=>({message:e,index:n})).filter(({message:e})=>e.role==="user").map(({index:e})=>e)}onIsStreamingChange(e){this.isStreaming=e}onMessagesChange(e){e&&(this.messages=e),this.$nextTick(()=>{this.checkScrollableContent(),(this.isAtBottom||this.isStreaming)&&this.scrollToBottom()})}onThreadChange(){this.isAtBottom=!0,this.currentQuestionIndex=null,this.$nextTick(()=>{this.scrollToBottom()})}onRandomQuestionsChange(e){e&&(this.randomQuestions=e)}mounted(){this.randomQuestions=this.widgetRuntime.randomQuestions||[],this.$nextTick(()=>{this.checkScrollableContent(),this.scrollToBottom()})}render(){const e=arguments[0];return e("div",{class:"ct-thread"},[e("div",{class:"ct-message-area"},[e("div",{class:"ct-message-container",ref:"messageContainer",on:{scroll:this.handleScroll}},[this.isEmpty?this.renderEmptyState():this.renderMessages()]),!this.isEmpty&&this.renderScrollButton()]),e($1,{attrs:{projectName:this.projectName,isStreaming:this.isStreaming,hasMessages:!this.isEmpty,enableVoice:this.enableVoice,isListening:this.isListening},on:{send:this.handleSendMessage,stop:this.handleStopRun,clear:this.handleClear,voice:this.handleVoice}})])}renderEmptyState(){const e=this.$createElement;return e("div",{class:"ct-empty-state"},[e("div",{class:"ct-intro-header"},[e("div",{class:"ct-intro-icon-wrapper"},[e(j,{class:"ct-intro-icon",attrs:{type:j.Type.ASK_AI_BLUE,size:52}})]),e("div",{class:"ct-intro-heading"},["What do you want to ask?"])]),this.$slots.suggestions||e("div",{class:"ct-intro-queries"},[e("span",{class:"ct-intro-queries-label"},["Example queries"]),e("div",{class:"ct-intro-queries-list"},[this.randomQuestions.map(n=>e(Kt,{key:n,attrs:{question:n},on:{select:this.handleQueryPillSelect}}))])])])}renderMessages(){const e=this.$createElement;return e("div",{class:"ct-message-list"},[this.messages.map((n,r)=>e("div",{key:`${n.id}-${r}`,class:"ct-message-wrapper",ref:`message-${r}`,attrs:{"data-message-index":r,"data-is-question":n.role==="user"}},[e(Se,{attrs:{message:n,enableVoice:this.enableVoice,isSpeaking:this.isSpeaking},on:{copy:this.handleCopy,speak:this.handleSpeak,feedback:this.handleFeedback,linkClick:this.handleLinkClick}})]))])}renderScrollButton(){const e=this.$createElement;if(!this.hasScrollableContent)return null;const n=this.questionIndices,r=this.isAtTop&&n.length>0&&n[0]===0,i=this.currentQuestionIndex!==null&&n.length>0&&this.currentQuestionIndex===n[0];return this.isAtBottom?e("button",{class:"ct-scroll-button",on:{click:this.scrollToMostRecentQuestion},attrs:{"aria-label":"Scroll to most recent question"}},[e(j,{attrs:{type:j.Type.ARROW_UP,size:16}})]):r||i?e("button",{class:"ct-scroll-button",on:{click:this.scrollToBottom},attrs:{"aria-label":"Scroll to bottom"}},[e(j,{attrs:{type:j.Type.ARROW_DOWN,size:16}})]):this.currentQuestionIndex!==null?e("button",{class:"ct-scroll-button",on:{click:this.scrollToMostRecentQuestion},attrs:{"aria-label":"Scroll to previous question"}},[e(j,{attrs:{type:j.Type.ARROW_UP,size:16}})]):e("button",{class:"ct-scroll-button",on:{click:this.scrollToBottom},attrs:{"aria-label":"Scroll to bottom"}},[e(j,{attrs:{type:j.Type.ARROW_DOWN,size:16}})])}handleScroll(){const e=this.messageContainerRef;if(e){const{scrollTop:n,scrollHeight:r,clientHeight:i}=e;this.isAtTop=n0)r=n[i-1];else{this.scrollToTop(),this.currentQuestionIndex=null;return}}r!==null&&this.$nextTick(()=>{const i=e.querySelectorAll("[data-message-index]"),o=Array.from(i).find(s=>Number(s.dataset.messageIndex)===r);if(o){const s=o.offsetTop,a=parseInt(getComputedStyle(e).paddingTop,10)||0;e.scrollTo({top:s-a,behavior:"smooth"}),this.currentQuestionIndex=r,this.$nextTick(()=>{this.checkScrollableContent(),this.handleScroll()})}else this.scrollToTop(),this.currentQuestionIndex=null})}scrollToTop(){const e=this.messageContainerRef;e&&(e.scrollTo({top:0,behavior:"smooth"}),this.isAtTop=!0,this.currentQuestionIndex=null,this.$nextTick(()=>{this.checkScrollableContent(),this.isAtBottom=!this.hasScrollableContent}))}scrollToBottom(){const e=this.messageContainerRef;e&&(e.scrollTo({top:e.scrollHeight,behavior:"smooth"}),this.isAtBottom=!0,this.currentQuestionIndex=null,this.$nextTick(()=>{this.checkScrollableContent(),this.isAtTop=!this.hasScrollableContent}))}async handleSendMessage(e){await this.widgetRuntime.sendMessage(this.widgetRuntime.currentThreadId,e)}handleStopRun(){this.widgetRuntime.cancelStreaming?.()}handleClear(){this.widgetRuntime.clearThreadMessages?.(this.widgetRuntime.currentThreadId)}handleVoice(){this.widgetRuntime.startListening?.()}handleCopy(){this.$emit(o2.Event.COPY)}handleSpeak(e){this.widgetRuntime.speak?.(e)}handleFeedback(e,n,r){this.widgetRuntime.handleFeedback?.(e,n,r)}handleLinkClick(e,n){this.widgetRuntime.handleLinkClick?.(e,n)}handleQueryPillSelect(e){this.handleSendMessage(e)}setVoiceState(e,n){e==="listening"?this.isListening=n:e==="speaking"&&(this.isSpeaking=n)}};Object.defineProperty(Y1,"SCROLL_THRESHOLD",{enumerable:!0,configurable:!0,writable:!0,value:100}),v([hn("messageContainer"),f("design:type",typeof(d8=typeof HTMLDivElement<"u"&&HTMLDivElement)=="function"?d8:Object)],Y1.prototype,"messageContainerRef",void 0),v([r6("widgetRuntime"),f("design:type",Object)],Y1.prototype,"widgetRuntime",void 0),v([y({type:String,required:!0}),f("design:type",String)],Y1.prototype,"projectName",void 0),v([y({type:Boolean,default:!1}),f("design:type",Boolean)],Y1.prototype,"enableVoice",void 0),v([ge("widgetRuntime.isCurrentThreadStreaming",{immediate:!0,deep:!0}),f("design:type",Function),f("design:paramtypes",[Boolean]),f("design:returntype",void 0)],Y1.prototype,"onIsStreamingChange",null),v([ge("widgetRuntime.currentMessages",{immediate:!0,deep:!0}),f("design:type",Function),f("design:paramtypes",[typeof(C8=typeof Array<"u"&&Array)=="function"?C8:Object]),f("design:returntype",void 0)],Y1.prototype,"onMessagesChange",null),v([ge("widgetRuntime.currentThreadId",{immediate:!0,deep:!0}),f("design:type",Function),f("design:paramtypes",[]),f("design:returntype",void 0)],Y1.prototype,"onThreadChange",null),v([ge("widgetRuntime.randomQuestions",{immediate:!0}),f("design:type",Function),f("design:paramtypes",[typeof(p8=typeof Array<"u"&&Array)=="function"?p8:Object]),f("design:returntype",void 0)],Y1.prototype,"onRandomQuestionsChange",null),Y1=o2=v([Z1({name:"ChatThread",components:{ChatMessage:Se,ChatComposer:$1,QueryPill:Kt}})],Y1),function(t){(function(e){e.COPY="copy",e.MESSAGE_CLICK="message-click"})(t.Event||(t.Event={}))}(Y1||(Y1={}));let Mt=class extends l1{constructor(){super(...arguments),Object.defineProperty(this,"height",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"width",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"runtime",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}get widgetRuntime(){return this.runtime}render(){const e=arguments[0];return e("div",{class:"ct-runtime-container",style:{height:this.height,width:this.width}},[this.$slots.header,e("div",{class:"ct-runtime-body"},[this.$slots.default])])}};v([y({default:"100%"}),f("design:type",String)],Mt.prototype,"height",void 0),v([y({default:"100%"}),f("design:type",String)],Mt.prototype,"width",void 0),v([y({required:!0}),f("design:type",Object)],Mt.prototype,"runtime",void 0),v([us("widgetRuntime"),f("design:type",Object),f("design:paramtypes",[])],Mt.prototype,"widgetRuntime",null),Mt=v([Z1({name:"ChatRuntimeProvider"})],Mt);var qt,st;(function(t){t.SUCCESS="success",t.WARNING="warning",t.DANGER="danger",t.INFO="info"})(st||(st={}));let le=qt=class extends l1{render(){const e=arguments[0],{className:n,iconType:r}=qt.TYPE_METADATA[this.type];return e("div",{class:j1(`lp-info-panel ${n}`,{inline:this.inline,emphasize:this.emphasize})},[this.title&&e("div",{class:"flex-row"},[e(j,{class:"lp-info-panel-icon",attrs:{size:qt.ICON_SIZE,type:r}}),e("div",{class:"flex-column"},[e("p",{class:"lp-info-panel__title"},[this.title]),this.renderMessage(),this.$slots.default])]),!this.title&&e("div",{class:j1(`flex-row ${this.contentPosition||""}`)},[e(j,{class:"lp-info-panel-icon",attrs:{size:qt.ICON_SIZE,type:r}}),this.renderMessage(),this.$slots.default,this.renderCloseIcon()])])}renderMessage(){const e=this.$createElement;return e("div",[this.text&&e("p",{class:j1("lp-info-panel-text")},[this.text])])}renderCloseIcon(){const e=this.$createElement;return this.showClose?e("span",{class:"flex-row-left"},[e(j,{class:"lp-info-panel-close-icon",attrs:{type:j.Type.CLOSE,size:this.isToast?qt.ICON_SIZE:20},on:{click:this.onClose}})]):null}onClose(){this.$emit(qt.EVENT_CLOSE)}};le.ICON_SIZE=16,le.TYPE_METADATA={[st.SUCCESS]:{className:"lp-success",iconType:j.Type.CHECK_MEDIUM},[st.WARNING]:{className:"lp-warning",iconType:j.Type.EXCLAMATION_MEDIUM},[st.DANGER]:{className:"lp-danger",iconType:j.Type.EXCLAMATION_MEDIUM},[st.INFO]:{className:"lp-info",iconType:j.Type.EXCLAMATION_MEDIUM}},v([y({type:String,required:!1,default:null}),f("design:type",Object)],le.prototype,"title",void 0),v([y({type:String,default:"",required:!1}),f("design:type",String)],le.prototype,"text",void 0),v([y({type:Boolean,default:!1,required:!1}),f("design:type",Boolean)],le.prototype,"inline",void 0),v([y({type:Boolean,default:!0,required:!1}),f("design:type",Boolean)],le.prototype,"emphasize",void 0),v([y({type:Boolean,default:!1,required:!1}),f("design:type",Boolean)],le.prototype,"showClose",void 0),v([y({type:Boolean,default:!1,required:!1}),f("design:type",Boolean)],le.prototype,"isToast",void 0),v([y({type:String,default:"",required:!1}),f("design:type",String)],le.prototype,"contentPosition",void 0),v([y({type:String,default:st.SUCCESS,validator:t=>ye(st).indexOf(t)!==-1}),f("design:type",String)],le.prototype,"type",void 0),le=qt=v([Z1({name:"InfoPanel"})],le),function(t){t.EVENT_CLOSE="close",t.Type=st,function(e){e.RIGHT="right",e.BOTTOM="bottom"}(t.ContentPosition||(t.ContentPosition={}))}(le||(le={}));var L5;let N1=L5=class extends l1{constructor(){super(...arguments),this.hasScrolled=!1,this.hasScrolledToEnd=!0}static get hasOpenedModals(){return nt.openedInstances.filter(e=>e.$parent instanceof L5).length>0}mounted(){document.documentElement&&document.documentElement.classList.add("modal-open")}beforeDestroy(){document.documentElement&&document.documentElement.classList.remove("modal-open")}render(){const e=arguments[0];return e(nt,{on:{bodyKeyDown:this.onBodyKeyDown}},[e("transition",{attrs:{appear:!0},on:{appear:this.computeScrollState}},[e("div",{attrs:{"data-testid":this.dataTestId},class:j1("lp-modal",this.className,{"full-screen":this.fullScreen,"transparent-bg":this.noFade,"not-like-modal":this.allowBackgroundInteraction},this.position),on:{click:this.onOverlayClick}},[e("div",{class:j1("wrapper",{"not-like-modal":this.allowBackgroundInteraction})},[this.simple?this.$slots.default:this.renderContent()])])])])}renderContent(){const e=this.$createElement;return e("div",{attrs:{"data-testid":`${this.dataTestId}-content`},class:j1("content",this.spinnerClass),style:this.sizingStyles,on:{click:Wu,scroll:this.computeScrollState},ref:"content"},[this.hasHeader&&e("div",{class:j1("header",{scrolled:this.hasScrolled})},[e("div",{class:"header-container"},[e("div",{class:j1("title",{big:this.bigTitle})},[this.title]),e("div",{class:"header-slot-container"},[this.$slots.header])]),this.closeButton&&e(j,{class:"cross",attrs:{size:32,type:j.Type.CLEAR},on:{click:this.onClickCross}})]),e("div",{class:"body"},[this.$slots.default]),this.hasSpinner&&e("div",{class:"spinner-container",attrs:{"data-testid":"modal-spinner"}},[e("div",{class:"spinner"})]),this.hasFooter()?e("div",{class:j1("footer",{scrolled:!this.hasScrolledToEnd})},[this.$slots.footer]):e("div",{class:"footer-accommodation"})])}get hasHeader(){return this.closeButton||!!this.title}hasFooter(){return!u5(this.$slots.footer)}get sizingStyles(){const e={minWidth:this.width,width:this.width};return this.minHeight!==null&&(e.minHeight=this.minHeight),e}get hasSpinner(){return this.hasOverlaySpinner||this.hasContentReplacingSpinner}get spinnerClass(){return j1({"overlay-spinner":this.hasOverlaySpinner,"content-replacing-spinner":this.hasContentReplacingSpinner})}get hasOverlaySpinner(){return this.spinner===L5.Spinner.OVERLAY}get hasContentReplacingSpinner(){return this.spinner===L5.Spinner.REPLACE_CONTENT}onOverlayClick(){this.fadeClose&&this.emitClose()}onClickCross(){this.closeButton&&this.emitClose()}onBodyKeyDown(e){this.escClose&&e.key===U5.ESC_KEY&&(e.stopImmediatePropagation(),this.emitClose())}emitClose(){this.hasSpinner||this.$emit(L5.EVENT_CLOSE)}computeScrollState(){const e=this.$refs.content;e&&(this.hasScrolled=e.scrollTop>0,this.hasScrolledToEnd=e.scrollTop+e.clientHeight===e.scrollHeight)}};N1.SLOT_HEADER="header",N1.SLOT_FOOTER="footer",v([y({type:Boolean,required:!1,default:!1}),f("design:type",Boolean)],N1.prototype,"simple",void 0),v([y({type:String,required:!1,default:null}),f("design:type",Object)],N1.prototype,"title",void 0),v([y({type:String,required:!1,default:"480px"}),f("design:type",String)],N1.prototype,"width",void 0),v([y({type:String,required:!1,default:""}),f("design:type",String)],N1.prototype,"className",void 0),v([y({type:String,required:!1,default:"120px"}),f("design:type",String)],N1.prototype,"minHeight",void 0),v([y({type:Boolean,required:!1,default:!0}),f("design:type",Boolean)],N1.prototype,"fadeClose",void 0),v([y({type:Boolean,required:!1,default:!1}),f("design:type",Boolean)],N1.prototype,"escClose",void 0),v([y({type:Boolean,required:!1,default:!1}),f("design:type",Boolean)],N1.prototype,"closeButton",void 0),v([y({type:String,required:!1,default:"hidden"}),f("design:type",String)],N1.prototype,"spinner",void 0),v([y({type:Boolean,required:!1,default:!1}),f("design:type",Boolean)],N1.prototype,"fullScreen",void 0),v([y({type:Boolean,required:!1,default:!1}),f("design:type",Boolean)],N1.prototype,"bigTitle",void 0),v([y({type:Boolean,required:!1,default:!1}),f("design:type",Boolean)],N1.prototype,"noFade",void 0),v([y({type:String,required:!1,default:()=>N1.Position.AUTO}),f("design:type",String)],N1.prototype,"position",void 0),v([y({type:Boolean,default:!1}),f("design:type",Boolean)],N1.prototype,"allowBackgroundInteraction",void 0),v([y({type:String,default:"modal"}),f("design:type",String)],N1.prototype,"dataTestId",void 0),v([zu(100),f("design:type",Function),f("design:paramtypes",[]),f("design:returntype",void 0)],N1.prototype,"computeScrollState",null),N1=L5=v([Z1({name:"Modal"})],N1),function(t){t.EVENT_CLOSE="close",function(e){e.HIDDEN="hidden",e.OVERLAY="overlay",e.REPLACE_CONTENT="replace-content"}(t.Spinner||(t.Spinner={})),function(e){e.AUTO="auto",e.TOP="top",e.BOTTOM="bottom"}(t.Position||(t.Position={}))}(N1||(N1={}));var s7,s2;(function(t){t.SUCCESS="success",t.WARNING="warning",t.DANGER="danger",t.INFO="info"})(s2||(s2={}));let X1=s7=class extends l1{created(){(!this.showClose||this.hasTimeoutAndClose)&&(this.timeoutInternal=window.setTimeout(this.close,this.timeout))}beforeDestroy(){clearTimeout(this.timeoutInternal)}render(){const e=arguments[0];return e(N1,{attrs:{simple:!0,alignTop:!0,escClose:!0,noFade:!0,fadeClose:this.fadeClose,position:this.position,className:this.className},on:{close:this.close}},[e(le,{class:"lp-toast",attrs:{type:this.type,text:this.text,showClose:this.showClose,isToast:!0},on:{close:this.handleInfoClose}},[this.$slots.default])])}close(){this.$emit(s7.EVENT_CLOSE)}handleInfoClose(){this.close()}};v([y({type:String,required:!1,default:""}),f("design:type",String)],X1.prototype,"text",void 0),v([y({type:String,required:!1,default:s2.SUCCESS,validator:t=>ye(s2).indexOf(t)!==-1}),f("design:type",String)],X1.prototype,"type",void 0),v([y({type:Boolean,required:!1,default:!1}),f("design:type",Boolean)],X1.prototype,"showClose",void 0),v([y({type:String,required:!1,default:()=>X1.Position.TOP}),f("design:type",String)],X1.prototype,"position",void 0),v([y({type:String,default:""}),f("design:type",String)],X1.prototype,"className",void 0),v([y({type:Number,default:()=>X1.ToastOpenedTimeout}),f("design:type",Number)],X1.prototype,"timeout",void 0),v([y({type:Boolean,default:!0}),f("design:type",Boolean)],X1.prototype,"fadeClose",void 0),v([y({type:Boolean,default:!1}),f("design:type",Boolean)],X1.prototype,"hasTimeoutAndClose",void 0),X1=s7=v([Z1({name:"Toast"})],X1),function(t){t.EVENT_CLOSE="close",t.Type=s2,t.ToastOpenedTimeout=5e3,function(e){e.AUTO="auto",e.TOP="top",e.BOTTOM="bottom"}(t.Position||(t.Position={}))}(X1||(X1={}));let p3=class extends l1{render(){const e=arguments[0];return e(C0,{class:"lp-portal-target",attrs:{name:this.name||W2.TARGET_A,multiple:!0}})}};v([y({type:String,required:!1,default:""}),f("design:type",String)],p3.prototype,"name",void 0),p3=v([Z1({name:"StargateTarget"})],p3);var Yt;let De=Yt=class extends l1{constructor(){super(...arguments),Object.defineProperty(this,"title",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"windowState",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"allowMinimize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"allowMaximize",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}render(){const e=arguments[0];return e("div",{class:"ct-widget-header",on:{click:this.handleHeaderClick}},[e("div",{class:"ct-header-logo"},[e(q1,{class:"ct-logo-button",attrs:{iconSize:20,icon:j.Type.ASK_AI,appearance:K.Appearance.LIGHTEN,color:K.Color.PRIMARY}})]),e("div",{class:"ct-header-title"},[this.title]),e("div",{class:"ct-window-controls"},[this.allowMaximize&&this.renderMaximizeButton(),this.renderCloseButton()])])}renderMaximizeButton(){const e=this.$createElement;return e(j,{class:"ct-win-btn ct-maximize-btn",attrs:{type:this.windowState==="maximized"?j.Type.MINIMIZE:j.Type.MAXIMIZE,size:Yt.MAXIMIZE_ICON_SIZE,clickable:!0,stopPropagation:!0},on:{click:this.handleMaximize}})}renderCloseButton(){const e=this.$createElement;return e(j,{class:"ct-win-btn ct-close-btn",attrs:{clickable:!0,stopPropagation:!0,type:j.Type.CLOSE,size:Yt.CLOSE_ICON_SIZE},on:{click:this.handleClose}})}handleHeaderClick(){this.$emit(Yt.Event.HEADER_CLICK)}handleMaximize(){this.$emit(Yt.Event.MAXIMIZE)}handleClose(){this.$emit(Yt.Event.CLOSE)}};Object.defineProperty(De,"CLOSE_ICON_SIZE",{enumerable:!0,configurable:!0,writable:!0,value:20}),Object.defineProperty(De,"MAXIMIZE_ICON_SIZE",{enumerable:!0,configurable:!0,writable:!0,value:14}),v([y({type:String,required:!0}),f("design:type",String)],De.prototype,"title",void 0),v([y({type:String,default:"normal"}),f("design:type",Object)],De.prototype,"windowState",void 0),v([y({type:Boolean,default:!0}),f("design:type",Boolean)],De.prototype,"allowMinimize",void 0),v([y({type:Boolean,default:!0}),f("design:type",Boolean)],De.prototype,"allowMaximize",void 0),De=Yt=v([Z1({name:"WidgetHeader"})],De),function(t){(function(e){e.MINIMIZE="minimize",e.MAXIMIZE="maximize",e.CLOSE="close",e.HEADER_CLICK="headerClick"})(t.Event||(t.Event={}))}(De||(De={}));var f8;F1.Widget=class extends l1{constructor(){super(...arguments),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"debug",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"chatThreadRef",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"widgetRuntime",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"isOpen",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"windowState",{enumerable:!0,configurable:!0,writable:!0,value:"normal"}),Object.defineProperty(this,"isInitializing",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"initializationError",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"toastMessage",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"showToast",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"scrollPosition",{enumerable:!0,configurable:!0,writable:!0,value:0})}get runtime(){return this.widgetRuntime}get positionClass(){return`ct-pos-${this.config.position}`}logDebug(e,n,r="log"){(this.debug||r==="error"||r==="warn")&&console[r](`[Widget] ${e}`,n!==void 0?n:"")}async created(){try{if(this.logDebug("Initializing Widget"),this.widgetRuntime=new m_(this.config),this.setupRuntimeCallbacks(),!await this.widgetRuntime.initialize())throw new Error("Failed to initialize widget runtime");this.isInitializing=!1,this.logDebug("Widget initialized successfully")}catch(e){this.isInitializing=!1,this.initializationError=`Error initializing widget: ${e.message||"Unknown error"}`,this.logDebug("Failed to initialize Widget:",e,"error")}}mounted(){document.documentElement.style.setProperty("--ct-primary",this.config.color),document.documentElement.style.setProperty("--ct-primary-hover",this.config.colorHover),document.addEventListener("keydown",this.handleKeyDown)}beforeDestroy(){document.removeEventListener("keydown",this.handleKeyDown),this.isOpen&&this.unlockBodyScroll(),this.widgetRuntime?.destroy?.()}render(){const e=arguments[0];return e("div",{class:"ct-widget-container"},[this.renderLauncher(),this.renderModal(),this.renderToast(),e(p3)])}renderLauncher(){const e=this.$createElement;return e(K,{attrs:{id:"ct-launcher",text:"Ask",iconSize:20,prefixIcon:j.Type.ASK_AI,appearance:K.Appearance.LIGHTEN,color:K.Color.PRIMARY},class:"ct-widget-launcher",on:{click:this.open}})}renderModal(){const e=this.$createElement,n=["ct-widget-root",this.positionClass,{"ct-visible":this.isOpen,"ct-maximized":this.windowState==="maximized","ct-minimized":this.windowState==="minimized"}];return e("div",{class:n,attrs:{"aria-hidden":this.isOpen?"false":"true"}},[e("div",{class:"ct-widget-overlay",on:{click:this.handleOverlayClick}}),e("div",{class:"ct-widget-modal"},[this.renderModalContent()])])}renderModalContent(){return this.isInitializing?this.renderLoadingState():this.initializationError?this.renderErrorState():this.renderChatInterface()}renderLoadingState(){const e=this.$createElement;return e("div",{class:"ct-widget-loading"},[e(j,{attrs:{type:j.Type.ASK_AI,size:40}}),e("span",{class:"ct-loading-text"},["Initializing..."])])}renderErrorState(){const e=this.$createElement;return e("div",{class:"ct-widget-error"},[e(j,{attrs:{type:j.Type.ALERT,size:40}}),e("span",{class:"ct-error-text"},[this.initializationError]),e(K,{attrs:{text:"Retry",appearance:K.Appearance.OUTLINE,color:K.Color.PRIMARY},on:{click:this.retryInitialization}})])}renderChatInterface(){const e=this.$createElement;return this.widgetRuntime?e(Mt,{attrs:{runtime:this.widgetRuntime,height:"100%",width:"100%"}},[e("template",{slot:"header"},[e(De,{attrs:{title:this.config.name,windowState:this.windowState,allowMinimize:this.config.allowMinimize,allowMaximize:this.config.allowMaximize},on:{minimize:this.minimize,maximize:this.maximize,close:this.close,headerClick:this.handleHeaderClick}})]),e("div",{class:"ct-chat-interface"},[e(Y1,{ref:"chatThread",attrs:{projectName:this.config.name,enableVoice:this.config.enableVoice},on:{copy:this.handleCopy}})])]):this.renderLoadingState()}renderToast(){const e=this.$createElement;return this.showToast?e(X1,{attrs:{text:this.toastMessage,type:X1.Type.DANGER,position:X1.Position.TOP,showClose:!0},on:{close:this.handleToastClose}}):null}onRuntimeChange(){this.widgetRuntime&&this.setupRuntimeCallbacks()}handleKeyDown(e){e.key==="Escape"&&this.isOpen&&this.close()}open(){this.isOpen=!0,this.lockBodyScroll()}close(){this.isOpen=!1,this.windowState="normal",this.unlockBodyScroll(),this.widgetRuntime?.stopListening?.(),this.widgetRuntime?.stopSpeaking?.()}lockBodyScroll(){this.scrollPosition=window.pageYOffset||document.documentElement.scrollTop,document.body.classList.add("ct-widget-open"),document.body.style.top=`-${this.scrollPosition}px`}unlockBodyScroll(){document.body.classList.remove("ct-widget-open"),document.body.style.top="",window.scrollTo(0,this.scrollPosition)}minimize(){this.windowState=this.windowState==="minimized"?"normal":"minimized"}maximize(){this.windowState=this.windowState==="maximized"?"normal":"maximized"}restore(){this.windowState="normal"}async retryInitialization(){this.isInitializing=!0,this.initializationError=null;try{if(this.widgetRuntime&&!await this.widgetRuntime.initialize())throw new Error("Failed to initialize widget runtime");this.isInitializing=!1}catch(e){this.isInitializing=!1,this.initializationError=`Error initializing widget: ${e.message||"Unknown error"}`}}handleCopy(){this.logDebug("Copy action triggered")}handleOverlayClick(){this.close()}handleHeaderClick(){this.windowState==="minimized"&&this.restore()}displayToast(e){this.toastMessage=e,this.showToast=!0}handleToastClose(){this.showToast=!1,this.toastMessage=""}setupRuntimeCallbacks(){this.widgetRuntime&&(this.widgetRuntime.setOnStateChange(e=>{this.logDebug("Runtime state changed:",e),this.$forceUpdate()}),this.widgetRuntime.setOnVoiceState((e,n)=>{this.chatThreadRef?.setVoiceState(e,n)}),this.widgetRuntime.setOnError(e=>{this.logDebug("Runtime error:",e,"error"),this.displayToast(e)}),this.widgetRuntime.setOnStreaming(e=>{this.logDebug("Streaming event:",e)}))}},v([y({type:Object,required:!0}),f("design:type",Object)],F1.Widget.prototype,"config",void 0),v([y({type:Boolean,default:!1}),f("design:type",Boolean)],F1.Widget.prototype,"debug",void 0),v([hn("chatThread"),f("design:type",typeof(f8=typeof Y1<"u"&&Y1)=="function"?f8:Object)],F1.Widget.prototype,"chatThreadRef",void 0),v([ds("widgetRuntime"),f("design:type",Object),f("design:paramtypes",[])],F1.Widget.prototype,"runtime",null),v([ge("widgetRuntime",{immediate:!0}),f("design:type",Function),f("design:paramtypes",[]),f("design:returntype",void 0)],F1.Widget.prototype,"onRuntimeChange",null),F1.Widget=v([Z1({name:"Widget",components:{ChatThread:Y1,ChatRuntimeProvider:Mt,WidgetHeader:De}})],F1.Widget);function h8(){try{const t=new Fn,e=document.createElement("div");e.id="ask-ai-root",document.body.appendChild(e),new l1({render:n=>n(F1.Widget,{props:{config:t}})}).$mount("#ask-ai-root")}catch{}}return document.readyState==="loading"?document.addEventListener("DOMContentLoaded",h8):h8(),window.AskAIWidget={Widget:F1.Widget,WidgetConfig:Fn},F1.WidgetConfig=Fn,Object.defineProperty(F1,Symbol.toStringTag,{value:"Module"}),F1}({});