@aikaara/chat-sdk 0.9.4 → 0.9.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{MountTenant-B-CCyWWA.mjs → MountTenant-BFBaHtZU.mjs} +152 -131
- package/dist/{MountTenant-CLSvsaX7.cjs → MountTenant-Cz8W90_R.cjs} +10 -10
- package/dist/cdn/aikaara-chat.iife.js +15 -15
- package/dist/headless.cjs +1 -1
- package/dist/headless.d.ts +7 -4
- package/dist/headless.mjs +2 -2
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +10 -5
- package/dist/index.mjs +2 -2
- package/dist/ui.cjs +1 -1
- package/dist/ui.d.ts +4 -2
- package/dist/ui.mjs +1 -1
- package/package.json +1 -1
|
@@ -248,7 +248,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
248
248
|
</svg>
|
|
249
249
|
</button>
|
|
250
250
|
</div>
|
|
251
|
-
`}setStatus(e){this.setAttribute("status",e)}}const Ah=/<\s*(br|i|b|em|strong|small|sub|sup|p|div|span|ul|ol|li|a|img|code|pre)\b/i;function Rt(c){if(Ah.test(c))return c;let e=Ih(c);return e=e.replace(/```(\w*)\n([\s\S]*?)```/g,(t,r,a)=>`<pre><code>${a.trim()}</code></pre>`),e=e.replace(/`([^`]+)`/g,"<code>$1</code>"),e=e.replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>"),e=e.replace(/\*(.+?)\*/g,"<em>$1</em>"),e=e.replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,'<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>'),e=e.replace(/\n/g,"<br>"),e}function Ih(c){const e={"&":"&","<":"<",">":">",'"':""","'":"'"};return c.replace(/[&<>"']/g,t=>e[t])}const Th=new Set(["p","br","hr","strong","em","b","i","u","s","small","sub","sup","code","pre","a","img","ul","ol","li","blockquote","h1","h2","h3","h4","h5","h6","span","div","table","thead","tbody","tr","th","td"]),Ch={a:new Set(["href","target","rel"]),img:new Set(["src","alt","width","height"]),code:new Set(["class"]),pre:new Set(["class"]),span:new Set(["class"]),div:new Set(["class"])};function jt(c){const e=document.createElement("template");return e.innerHTML=c,Sl(e.content),e.innerHTML}function Sl(c){const e=Array.from(c.childNodes);for(const t of e)if(t.nodeType===Node.ELEMENT_NODE){const r=t,a=r.tagName.toLowerCase();if(!Th.has(a)){const s=document.createTextNode(r.textContent||"");c.replaceChild(s,t);continue}const n=Ch[a]||new Set,i=Array.from(r.attributes);for(const s of i)n.has(s.name)||r.removeAttribute(s.name);if(r.hasAttribute("href")){const s=r.getAttribute("href")||"";!s.startsWith("http://")&&!s.startsWith("https://")&&!s.startsWith("/")&&r.removeAttribute("href")}Sl(t)}}class El extends HTMLElement{shadow;container;welcomeMessage="";showTimestamps=!0;timestampFormat="time";hideSystemMessages=[];linkHandlers=[];getLinkBearer=null;setHideSystemMessages(e){this.hideSystemMessages=(e??[]).map(t=>t.toLowerCase())}setTimestampFormat(e){this.timestampFormat=e,e==="none"&&(this.showTimestamps=!1)}templateLayout="inside";setTemplateLayout(e){this.templateLayout=e}shouldHideMessage(e){if(!e)return!1;const t=e.trim().toLowerCase();return t==="chat_initiated"||t==="group created"||t==="file_uploaded"||t==="file_upload"?!0:this.hideSystemMessages.length?this.hideSystemMessages.some(r=>t.includes(r)):!1}setLinkConfig(e,t){this.linkHandlers=e,this.getLinkBearer=t??null}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.addEventListener("template-action",e=>{const t=e.detail;this.dispatchEvent(new CustomEvent("message-action",{detail:t,bubbles:!0,composed:!0}))}),this.addEventListener("click",e=>{const t=e.composedPath?.()??[],r=t.find(n=>n&&n.tagName==="A");!r||!r.href||r.dataset.noModal!==void 0||r.target==="_blank"||r.classList.contains("attachment")||t.some(n=>{if(!n||!n.classList)return!1;const i=n.classList;return i.contains("bubble")&&i.contains("user")})||/^https?:\/\//i.test(r.href)&&(e.preventDefault(),this.handleLinkClick(r.href,r.textContent?.trim()||void 0))}),this.shadow.innerHTML=`
|
|
251
|
+
`}setStatus(e){this.setAttribute("status",e)}}const Ah=/<\s*(br|i|b|em|strong|small|sub|sup|p|div|span|ul|ol|li|a|img|code|pre)\b/i;function Rt(c){if(Ah.test(c))return c;let e=Ih(c);return e=e.replace(/```(\w*)\n([\s\S]*?)```/g,(t,r,a)=>`<pre><code>${a.trim()}</code></pre>`),e=e.replace(/`([^`]+)`/g,"<code>$1</code>"),e=e.replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>"),e=e.replace(/\*(.+?)\*/g,"<em>$1</em>"),e=e.replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,'<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>'),e=e.replace(/\n/g,"<br>"),e}function Ih(c){const e={"&":"&","<":"<",">":">",'"':""","'":"'"};return c.replace(/[&<>"']/g,t=>e[t])}const Th=new Set(["p","br","hr","strong","em","b","i","u","s","small","sub","sup","code","pre","a","img","ul","ol","li","blockquote","h1","h2","h3","h4","h5","h6","span","div","table","thead","tbody","tr","th","td"]),Ch={a:new Set(["href","target","rel"]),img:new Set(["src","alt","width","height"]),code:new Set(["class"]),pre:new Set(["class"]),span:new Set(["class"]),div:new Set(["class"])};function jt(c){const e=document.createElement("template");return e.innerHTML=c,Sl(e.content),e.innerHTML}function Sl(c){const e=Array.from(c.childNodes);for(const t of e)if(t.nodeType===Node.ELEMENT_NODE){const r=t,a=r.tagName.toLowerCase();if(!Th.has(a)){const s=document.createTextNode(r.textContent||"");c.replaceChild(s,t);continue}const n=Ch[a]||new Set,i=Array.from(r.attributes);for(const s of i)n.has(s.name)||r.removeAttribute(s.name);if(r.hasAttribute("href")){const s=r.getAttribute("href")||"";!s.startsWith("http://")&&!s.startsWith("https://")&&!s.startsWith("/")&&r.removeAttribute("href")}Sl(t)}}function Oh(c){const e=Date.now()-c.getTime(),t=Math.round(e/1e3);if(t<5)return"just now";if(t<60)return`${t}s ago`;const r=Math.round(t/60);if(r<60)return`${r} min ago`;const a=Math.round(r/60);if(a<24)return`${a} hr ago`;const n=Math.round(a/24);return n===1?"Yesterday":n<7?`${n} d ago`:c.toLocaleDateString(void 0,{month:"short",day:"2-digit"})}class El extends HTMLElement{shadow;container;welcomeMessage="";showTimestamps=!0;timestampFormat="time";hideSystemMessages=[];linkHandlers=[];getLinkBearer=null;setHideSystemMessages(e){this.hideSystemMessages=(e??[]).map(t=>t.toLowerCase())}setTimestampFormat(e){this.timestampFormat=e,e==="none"&&(this.showTimestamps=!1)}templateLayout="inside";setTemplateLayout(e){this.templateLayout=e}shouldHideMessage(e){if(!e)return!1;const t=e.trim().toLowerCase();return t==="chat_initiated"||t==="group created"||t==="file_uploaded"||t==="file_upload"?!0:this.hideSystemMessages.length?this.hideSystemMessages.some(r=>t.includes(r)):!1}setLinkConfig(e,t){this.linkHandlers=e,this.getLinkBearer=t??null}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.addEventListener("template-action",e=>{const t=e.detail;this.dispatchEvent(new CustomEvent("message-action",{detail:t,bubbles:!0,composed:!0}))}),this.addEventListener("click",e=>{const t=e.composedPath?.()??[],r=t.find(n=>n&&n.tagName==="A");!r||!r.href||r.dataset.noModal!==void 0||r.target==="_blank"||r.classList.contains("attachment")||t.some(n=>{if(!n||!n.classList)return!1;const i=n.classList;return i.contains("bubble")&&i.contains("user")})||/^https?:\/\//i.test(r.href)&&(e.preventDefault(),this.handleLinkClick(r.href,r.textContent?.trim()||void 0))}),this.shadow.innerHTML=`
|
|
252
252
|
<style>
|
|
253
253
|
:host {
|
|
254
254
|
display: flex;
|
|
@@ -401,7 +401,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
401
401
|
}
|
|
402
402
|
</style>
|
|
403
403
|
<div class="message-list"></div>
|
|
404
|
-
`,this.container=this.shadow.querySelector(".message-list"),this.welcomeMessage&&this.renderMessages([])}setWelcomeMessage(e){this.welcomeMessage=e}setShowTimestamps(e){this.showTimestamps=e}renderMessages(e){if(!this.container)return;if(this.container.innerHTML="",e.length===0&&this.welcomeMessage){this.container.innerHTML=`<div class="welcome">${jt(Rt(this.welcomeMessage))}</div>`;return}const t=this.computeConsumedIds(e);for(const r of e)this.appendMessageElement(r,t.has(r.externalId??r.id));this.scrollToBottom()}computeConsumedIds(e){const t=new Set;let r=-1;for(let a=e.length-1;a>=0;a--)if(e[a].role==="user"){r=a;break}for(let a=0;a<e.length;a++){const n=e[a];if(n.role==="user"){const i=n.metadata?.attributes?.action;i?.message_id&&t.add(i.message_id)}n.role!=="user"&&n.template?.contentType&&a<r&&t.add(n.externalId??n.id)}return t}addMessage(e){const t=this.container.querySelector(".welcome");t&&t.remove(),this.appendMessageElement(e),this.scrollToBottom()}updateStreamingContent(e){const t=this.container.querySelector('[data-streaming="true"] .bubble');t&&(t.innerHTML=jt(Rt(e)),t.classList.add("streaming-cursor"),this.scrollToBottom())}finalizeStreaming(){const e=this.container.querySelector('[data-streaming="true"]');e&&(e.removeAttribute("data-streaming"),e.querySelector(".bubble")?.classList.remove("streaming-cursor"))}showTypingIndicator(){this.removeTypingIndicator();const e=document.createElement("div");e.classList.add("typing-indicator"),e.setAttribute("data-typing","true"),e.innerHTML='<span class="dot"></span><span class="dot"></span><span class="dot"></span>',this.container.appendChild(e),this.scrollToBottom()}removeTypingIndicator(){this.container.querySelector('[data-typing="true"]')?.remove()}appendMessageElement(e,t=!1){if(e.role==="user"&&e.content?.trim()==="CHAT_INITIATED"||this.shouldHideMessage(e.content))return;if(e.role==="system"){const o=document.createElement("div");o.classList.add("message-wrap","system"),o.dataset.messageId=e.id,e.externalId&&(o.dataset.externalId=e.externalId);const l=document.createElement("aikaara-system-pill");l.setAttribute("text",e.content||""),this.showTimestamps&&e.createdAt&&l.setAttribute("subtext",this.formatTime(e.createdAt)),o.appendChild(l),this.container.appendChild(o);return}const r=document.createElement("div");r.classList.add("message-wrap",e.role),e.status==="streaming"&&r.setAttribute("data-streaming","true"),e.externalId&&(r.dataset.externalId=e.externalId),r.dataset.messageId=e.id;const a=document.createElement("div");a.classList.add("bubble",e.role);const i=!!e.template?.contentType&&e.role!=="user";e.role==="user"?a.textContent=e.content:i?e.content&&(a.innerHTML=jt(Rt(e.content))):(a.innerHTML=jt(Rt(e.content||"")),e.status==="streaming"&&a.classList.add("streaming-cursor"));let s=null;if(e.template?.contentType){const o=document.createElement("aikaara-template-renderer");o.setAttribute("content-type",e.template.contentType),e.template.templateId&&o.setAttribute("template-id",e.template.templateId);const l=e.externalId??e.id;l&&o.setAttribute("message-id",l),o.setPayload(e.template.payload),t&&(o.dataset.consumed="true"),this.templateLayout==="outside"?(o.classList.add("template-outside"),s=o):a.appendChild(o)}if(e.attachments?.length){const o=document.createElement("div");o.classList.add("attachments");for(const l of e.attachments){const u=document.createElement("a");u.classList.add("attachment"),u.href=l.fileUrl,u.target="_blank",u.rel="noopener noreferrer",u.textContent=`📎 ${l.fileName}`,o.appendChild(u)}a.appendChild(o)}if(r.appendChild(a),s&&r.appendChild(s),this.showTimestamps&&e.createdAt||e.role==="user"&&e.status){const o=document.createElement("div");if(o.classList.add("timestamp"),this.showTimestamps&&e.createdAt&&(o.textContent=this.formatTime(e.createdAt)),e.role==="user"&&e.status){const l=document.createElement("span");l.classList.add("status-tick"),e.status==="read"&&l.classList.add("read"),l.textContent={sending:" ○",sent:" ✓",delivered:" ✓✓",read:" ✓✓"}[e.status]??"",o.appendChild(l)}r.appendChild(o)}this.container.appendChild(r)}upsertMessage(e){const t=this.findRenderedMessage(e);t&&t.remove(),this.appendMessageElement(e),this.scrollToBottom()}findRenderedMessage(e){if(e.externalId){const t=this.container.querySelector(`[data-external-id="${CSS.escape(e.externalId)}"]`);if(t)return t}return this.container.querySelector(`[data-message-id="${CSS.escape(e.id)}"]`)}scrollToBottom(){requestAnimationFrame(()=>{this.container.scrollTop=this.container.scrollHeight})}formatTime(e){try{const t=new Date(e);switch(this.timestampFormat){case"datetime":return`${t.
|
|
404
|
+
`,this.container=this.shadow.querySelector(".message-list"),this.welcomeMessage&&this.renderMessages([])}setWelcomeMessage(e){this.welcomeMessage=e}setShowTimestamps(e){this.showTimestamps=e}renderMessages(e){if(!this.container)return;if(this.container.innerHTML="",e.length===0&&this.welcomeMessage){this.container.innerHTML=`<div class="welcome">${jt(Rt(this.welcomeMessage))}</div>`;return}const t=this.computeConsumedIds(e);for(const r of e)this.appendMessageElement(r,t.has(r.externalId??r.id));this.scrollToBottom()}computeConsumedIds(e){const t=new Set;let r=-1;for(let a=e.length-1;a>=0;a--)if(e[a].role==="user"){r=a;break}for(let a=0;a<e.length;a++){const n=e[a];if(n.role==="user"){const i=n.metadata?.attributes?.action;i?.message_id&&t.add(i.message_id)}n.role!=="user"&&n.template?.contentType&&a<r&&t.add(n.externalId??n.id)}return t}addMessage(e){const t=this.container.querySelector(".welcome");t&&t.remove(),this.appendMessageElement(e),this.scrollToBottom()}updateStreamingContent(e){const t=this.container.querySelector('[data-streaming="true"] .bubble');t&&(t.innerHTML=jt(Rt(e)),t.classList.add("streaming-cursor"),this.scrollToBottom())}finalizeStreaming(){const e=this.container.querySelector('[data-streaming="true"]');e&&(e.removeAttribute("data-streaming"),e.querySelector(".bubble")?.classList.remove("streaming-cursor"))}showTypingIndicator(){this.removeTypingIndicator();const e=document.createElement("div");e.classList.add("typing-indicator"),e.setAttribute("data-typing","true"),e.innerHTML='<span class="dot"></span><span class="dot"></span><span class="dot"></span>',this.container.appendChild(e),this.scrollToBottom()}removeTypingIndicator(){this.container.querySelector('[data-typing="true"]')?.remove()}appendMessageElement(e,t=!1){if(e.role==="user"&&e.content?.trim()==="CHAT_INITIATED"||this.shouldHideMessage(e.content))return;if(e.role==="system"){const o=document.createElement("div");o.classList.add("message-wrap","system"),o.dataset.messageId=e.id,e.externalId&&(o.dataset.externalId=e.externalId);const l=document.createElement("aikaara-system-pill");l.setAttribute("text",e.content||""),this.showTimestamps&&e.createdAt&&l.setAttribute("subtext",this.formatTime(e.createdAt)),o.appendChild(l),this.container.appendChild(o);return}const r=document.createElement("div");r.classList.add("message-wrap",e.role),e.status==="streaming"&&r.setAttribute("data-streaming","true"),e.externalId&&(r.dataset.externalId=e.externalId),r.dataset.messageId=e.id;const a=document.createElement("div");a.classList.add("bubble",e.role);const i=!!e.template?.contentType&&e.role!=="user";e.role==="user"?a.textContent=e.content:i?e.content&&(a.innerHTML=jt(Rt(e.content))):(a.innerHTML=jt(Rt(e.content||"")),e.status==="streaming"&&a.classList.add("streaming-cursor"));let s=null;if(e.template?.contentType){const o=document.createElement("aikaara-template-renderer");o.setAttribute("content-type",e.template.contentType),e.template.templateId&&o.setAttribute("template-id",e.template.templateId);const l=e.externalId??e.id;l&&o.setAttribute("message-id",l),o.setPayload(e.template.payload),t&&(o.dataset.consumed="true"),this.templateLayout==="outside"?(o.classList.add("template-outside"),s=o):a.appendChild(o)}if(e.attachments?.length){const o=document.createElement("div");o.classList.add("attachments");for(const l of e.attachments){const u=document.createElement("a");u.classList.add("attachment"),u.href=l.fileUrl,u.target="_blank",u.rel="noopener noreferrer",u.textContent=`📎 ${l.fileName}`,o.appendChild(u)}a.appendChild(o)}if(r.appendChild(a),s&&r.appendChild(s),this.showTimestamps&&e.createdAt||e.role==="user"&&e.status){const o=document.createElement("div");if(o.classList.add("timestamp"),this.showTimestamps&&e.createdAt&&(o.textContent=this.formatTime(e.createdAt)),e.role==="user"&&e.status){const l=document.createElement("span");l.classList.add("status-tick"),e.status==="read"&&l.classList.add("read"),l.textContent={sending:" ○",sent:" ✓",delivered:" ✓✓",read:" ✓✓"}[e.status]??"",o.appendChild(l)}r.appendChild(o)}this.container.appendChild(r)}upsertMessage(e){const t=this.findRenderedMessage(e);t&&t.remove(),this.appendMessageElement(e),this.scrollToBottom()}findRenderedMessage(e){if(e.externalId){const t=this.container.querySelector(`[data-external-id="${CSS.escape(e.externalId)}"]`);if(t)return t}return this.container.querySelector(`[data-message-id="${CSS.escape(e.id)}"]`)}scrollToBottom(){requestAnimationFrame(()=>{this.container.scrollTop=this.container.scrollHeight})}formatTime(e){try{const t=new Date(e),r=t.toLocaleDateString(void 0,{month:"short",day:"2-digit"});switch(this.timestampFormat){case"datetime":return`${r}, ${t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}`;case"datetime-seconds":return`${r}, ${t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit"})}`;case"datetime-24":return`${r}, ${t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",hour12:!1})}`;case"date":return r;case"relative":return Oh(t);case"time-24":return t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",hour12:!1});case"time-seconds":return t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit"});case"none":return"";default:return t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}}catch{return""}}async handleLinkClick(e,t){const r=this.linkHandlers.find(y=>Ph(e,y.match)),a=r?.target??"iframe";if(a==="tab"){window.open(e,"_blank","noopener,noreferrer");return}const n=this.getOrCreateModal(),i=r?.title??t??"Link";if(a==="iframe"||!r?.fetch||!r.render){requestAnimationFrame(()=>n.show?.(e,i));return}const s=Mh(e),o=xl(r.fetch.url,s),l={accept:"application/json",...r.fetch.headers??{}},u=r.fetch.authHeader??"session";if(u!=="none"&&this.getLinkBearer){const y=await this.getLinkBearer(u);y&&(l.authorization=`Bearer ${y}`)}const d={method:r.fetch.method??"GET",headers:l};r.fetch.body&&(l["content-type"]="application/json",d.body=JSON.stringify(Ki(r.fetch.body,s)));let p=null;try{const y=await fetch(o,d);y.ok&&(p=await y.json().catch(()=>null))}catch(y){console.warn("[aikaara-chat-sdk] linkHandler fetch failed",y)}requestAnimationFrame(()=>{n.showElement?.(r.render,i,y=>{const f=r.props??{setData:p};for(const[b,k]of Object.entries(f)){const m=y[b];typeof m=="function"&&m.call(y,k)}const g=b=>{const k=b,m=k.detail?.message??k.detail?.label;m&&(n.close?.(),this.dispatchEvent(new CustomEvent("message-action",{detail:{text:m,attributes:{...k.detail?.attributes??{}}},bubbles:!0,composed:!0})))};y.addEventListener("aikaara-plan-select",g),y.addEventListener("aikaara-select",g)})})}getOrCreateModal(){let e=document.querySelector("aikaara-link-modal");return e||(e=document.createElement("aikaara-link-modal"),document.body.appendChild(e)),e}}function Ph(c,e){const t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+t.replace(/\*/g,".*").replace(/\?/g,".")+"$","i").test(c)}function Mh(c){try{const e=new URL(c),t={};return e.searchParams.forEach((r,a)=>{t[a]=r}),t}catch{return{}}}function xl(c,e){return c.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function Ki(c,e){if(typeof c=="string")return xl(c,e);if(Array.isArray(c))return c.map(t=>Ki(t,e));if(c&&typeof c=="object"){const t={};for(const[r,a]of Object.entries(c))t[r]=Ki(a,e);return t}return c}class Al extends HTMLElement{shadow;templatePayload=null;attachments=[];static get observedAttributes(){return["role","content","timestamp","content-type","template-id","inner-message","message-id","status"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}attributeChangedCallback(){this.render()}setTemplatePayload(e){this.templatePayload=e,this.render()}setAttachments(e){this.attachments=e,this.render()}render(){const e=this.getAttribute("role")||"user",t=this.getAttribute("content")||"",r=this.getAttribute("timestamp")||"",a=this.getAttribute("status")||"",n=this.getAttribute("content-type")||"",i=this.getAttribute("template-id")||"",s=this.getAttribute("inner-message")||"",o=e==="user"?document.createTextNode(t).textContent||"":jt(Rt(t)),l=e==="user"&&a,u=a==="sending"?"○":a==="sent"?"✓":a==="delivered"||a==="read"?"✓✓":"";this.shadow.innerHTML=`
|
|
405
405
|
<style>
|
|
406
406
|
:host { display: flex; flex-direction: column; }
|
|
407
407
|
:host([role="user"]) { align-items: flex-end; }
|
|
@@ -479,8 +479,8 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
479
479
|
</div>
|
|
480
480
|
`:""}
|
|
481
481
|
`;const d=this.shadow.querySelector("aikaara-template-renderer");d&&this.templatePayload!==null&&d.setPayload(this.templatePayload,s),d&&d.addEventListener("template-action",p=>{this.dispatchEvent(new CustomEvent("message-action",{detail:p.detail,bubbles:!0,composed:!0}))})}renderAttachments(){return this.attachments.length?`<div class="attachments">${this.attachments.map(t=>`<a class="attachment" href="${Ts(t.fileUrl)}" target="_blank" rel="noopener noreferrer">
|
|
482
|
-
📎 ${
|
|
483
|
-
</a>`).join("")}</div>`:""}}function Ts(c){return String(c).replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}function
|
|
482
|
+
📎 ${Rh(t.fileName)}
|
|
483
|
+
</a>`).join("")}</div>`:""}}function Ts(c){return String(c).replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}function Rh(c){return String(c).replace(/[&<>]/g,e=>({"&":"&","<":"<",">":">"})[e])}class Il extends HTMLElement{shadow;textarea;sendBtn;attachBtn;fileInput;_disabled=!1;_uploading=!1;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}static get observedAttributes(){return["placeholder","disable-attach","accept","multiple","attach-position","send-shape"]}connectedCallback(){const e=this.getAttribute("placeholder")||"Type a message...",t=!this.hasAttribute("disable-attach"),r=this.getAttribute("accept")??"",a=this.hasAttribute("multiple"),n=this.getAttribute("attach-position")==="right",i=this.getAttribute("send-shape")==="square",s=t?`
|
|
484
484
|
<button class="attach-btn" aria-label="Attach file" type="button">
|
|
485
485
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
486
486
|
<path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"/>
|
|
@@ -669,14 +669,14 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
669
669
|
<span class="message"></span>
|
|
670
670
|
<button class="dismiss">Dismiss</button>
|
|
671
671
|
</div>
|
|
672
|
-
`,this.container=this.shadow.querySelector(".banner"),this.shadow.querySelector(".dismiss")?.addEventListener("click",()=>this.hide())}show(e,t){const r=this.container.querySelector(".message");r&&(r.textContent=e),this.container.classList.add("visible"),this.dismissTimer&&clearTimeout(this.dismissTimer),t&&(this.dismissTimer=setTimeout(()=>this.hide(),t))}hide(){this.container.classList.remove("visible"),this.dismissTimer&&(clearTimeout(this.dismissTimer),this.dismissTimer=null)}}const qr=new Map;function Pl(c){const e=qr.get(c);if(e)return e;const t=new Promise((r,a)=>{const n=document.querySelector(`script[data-aikaara-src="${CSS.escape(c)}"]`);if(n){n.dataset.aikaaraReady==="1"?r():(n.addEventListener("load",()=>r(),{once:!0}),n.addEventListener("error",()=>a(new Error(`Failed to load ${c}`)),{once:!0}));return}const i=document.createElement("script");i.src=c,i.async=!0,i.crossOrigin="anonymous",i.dataset.aikaaraSrc=c,i.addEventListener("load",()=>{i.dataset.aikaaraReady="1",r()},{once:!0}),i.addEventListener("error",()=>{qr.delete(c),a(new Error(`Failed to load ${c}`))},{once:!0}),document.head.appendChild(i)});return qr.set(c,t),t}function
|
|
672
|
+
`,this.container=this.shadow.querySelector(".banner"),this.shadow.querySelector(".dismiss")?.addEventListener("click",()=>this.hide())}show(e,t){const r=this.container.querySelector(".message");r&&(r.textContent=e),this.container.classList.add("visible"),this.dismissTimer&&clearTimeout(this.dismissTimer),t&&(this.dismissTimer=setTimeout(()=>this.hide(),t))}hide(){this.container.classList.remove("visible"),this.dismissTimer&&(clearTimeout(this.dismissTimer),this.dismissTimer=null)}}const qr=new Map;function Pl(c){const e=qr.get(c);if(e)return e;const t=new Promise((r,a)=>{const n=document.querySelector(`script[data-aikaara-src="${CSS.escape(c)}"]`);if(n){n.dataset.aikaaraReady==="1"?r():(n.addEventListener("load",()=>r(),{once:!0}),n.addEventListener("error",()=>a(new Error(`Failed to load ${c}`)),{once:!0}));return}const i=document.createElement("script");i.src=c,i.async=!0,i.crossOrigin="anonymous",i.dataset.aikaaraSrc=c,i.addEventListener("load",()=>{i.dataset.aikaaraReady="1",r()},{once:!0}),i.addEventListener("error",()=>{qr.delete(c),a(new Error(`Failed to load ${c}`))},{once:!0}),document.head.appendChild(i)});return qr.set(c,t),t}function jh(c,e=5e3){return new Promise((t,r)=>{const a=setTimeout(()=>r(new Error(`Custom element <${c}> not registered within ${e}ms`)),e);customElements.whenDefined(c).then(()=>{clearTimeout(a),t()})})}function Lh(c){const e=`template:${c}`,t=window.__aikaara_descriptor__?.components?.[e];return t&&t.kind==="iife-element"?{render:t.tag,scriptUrl:t.scriptUrl,props:t.props}:window.__aikaara_descriptor__?.templates?.[c]}class Ml extends HTMLElement{shadow;payloadData=null;innerMessage="";renderGen=0;static get observedAttributes(){return["content-type","template-id","message-id"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render(),this.addEventListener("template-action",()=>{this.dataset.consumed="true"})}attributeChangedCallback(){this.render()}setPayload(e,t){this.payloadData=e,t!==void 0&&(this.innerMessage=t),this.render()}render(){const e=this.getAttribute("content-type")??"",t=this.getAttribute("template-id")??"";for(this.renderGen+=1,this.shadow.innerHTML=`
|
|
673
673
|
<style>
|
|
674
674
|
:host { display: block; }
|
|
675
675
|
:host([data-consumed]) ::slotted(*) { display: none !important; }
|
|
676
676
|
::slotted(*) { display: block; }
|
|
677
677
|
</style>
|
|
678
678
|
<slot></slot>
|
|
679
|
-
`;this.firstChild;)this.removeChild(this.firstChild);if(!e)return;const r=t?
|
|
679
|
+
`;this.firstChild;)this.removeChild(this.firstChild);if(!e)return;const r=t?Lh(t):void 0,a=r?.render??(t?`aikaara-template-${t}`:`aikaara-template-${e}`);if(r?.scriptUrl&&!customElements.get(a)&&Pl(r.scriptUrl).then(()=>jh(a)).then(()=>this.render()).catch(n=>console.warn(`[aikaara-template-renderer] failed to lazy-load ${r.scriptUrl}`,n)),customElements.get(a)){const n=document.createElement(a);if(r?.props){for(const[i,s]of Object.entries(r.props))if(typeof n[i]=="function")try{n[i](s)}catch(o){console.warn(`[aikaara-template-renderer] props.${i} threw on <${a}>`,o)}}n.setPayload?.(this.payloadData,this.innerMessage),this.appendChild(n);return}if(Array.isArray(this.payloadData)){const n=this.payloadData;if(n.length>0&&n.every(s=>s&&typeof s=="object"&&!Array.isArray(s)&&!("type"in s)&&!("data"in s)&&typeof s.message=="string")){const s=document.createElement("aikaara-option-list");s.setPayload({name:"quick-reply",type:"button",options:n.map(o=>{const l=typeof o.title=="string"?o.title:"",u=o.message;return{label:l||u,value:u}})}),this.appendChild(s);return}for(const s of n)this.mountField(s)}else if(this.payloadData&&typeof this.payloadData=="object"){const n=this.payloadData;typeof n.message=="string"&&(n.okLabel||n.action||n.ok)&&this.mountModal(n)}}mountField(e){if(!e||typeof e!="object")return;const t=e.type??e.data?.type;if(t==="link"){this.mountLinkButton(e);return}const r=e.data;if(r){if(t==="checkbox"||t==="radio"||t==="button"){const a=document.createElement("aikaara-option-list");a.setPayload({name:r.name??"",title:r.title,options:r.options??[],type:t}),this.appendChild(a);return}if(t==="submit"){const a=document.createElement("aikaara-submit-action"),n=this.getAttribute("message-id")??void 0;a.setPayload({name:r.name??"Submit",action:r.action??{message:r.name??"Submit"},messageId:n}),this.appendChild(a);return}t==="modal"&&this.mountModal({message:r.message??"",okLabel:r.okLabel,cancelLabel:r.cancelLabel,action:r.action})}}mountLinkButton(e){const t=this.renderGen;Promise.resolve().then(()=>require("./AikaaraLinkButton-VDNx7RfC.cjs")).then(({registerAikaaraLinkButton:r,AikaaraLinkButton:a})=>{if(t!==this.renderGen)return;r();const n=document.createElement("aikaara-link-button");n.setPayload({name:e.name??"Open",url:e.url??"",openLinkInNewTab:e.openLinkInNewTab,orderId:e.orderId,extra:Uh(e),messageId:this.getAttribute("message-id")??void 0}),this.appendChild(n)})}mountModal(e){const t=document.createElement("aikaara-modal-action");t.setPayload(e),this.appendChild(t)}}const Nh=new Set(["type","url","name","openLinkInNewTab","orderId"]);function Uh(c){const e={};for(const[t,r]of Object.entries(c))Nh.has(t)||(e[t]=r);return e}class Rl extends HTMLElement{shadow;static get observedAttributes(){return["text","subtext"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}attributeChangedCallback(){this.render()}render(){const e=this.getAttribute("text")??this.textContent??"",t=this.getAttribute("subtext")??"";this.shadow.innerHTML=`
|
|
680
680
|
<style>
|
|
681
681
|
:host {
|
|
682
682
|
display: flex;
|
|
@@ -807,8 +807,8 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
807
807
|
button:hover { background: var(--aikaara-submit-hover-bg, var(--aikaara-primary-hover, #4f46e5)); }
|
|
808
808
|
button:disabled { opacity: var(--aikaara-submit-disabled-opacity, 0.5); cursor: not-allowed; }
|
|
809
809
|
</style>
|
|
810
|
-
<button type="button">${
|
|
811
|
-
`,this.shadow.querySelector("button").addEventListener("click",()=>this.handleClick())}}function
|
|
810
|
+
<button type="button">${Bh(e)}</button>
|
|
811
|
+
`,this.shadow.querySelector("button").addEventListener("click",()=>this.handleClick())}}function Bh(c){return String(c).replace(/[&<>]/g,e=>({"&":"&","<":"<",">":">"})[e])}class Nl extends HTMLElement{shadow;data=null;dismissed=!1;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e){this.data=e,this.dismissed=!1,this.render()}dismiss(){this.dismissed=!0,this.render()}handleOk(){if(!this.data)return;const e=this.data.action;this.dispatchEvent(new CustomEvent("template-action",{detail:{text:e?.message??this.data.message,attributes:{action:{confirmed:!0,requestType:e?.requestType??"postBackToBotPlatform"}}},bubbles:!0,composed:!0})),this.dismiss()}render(){if(!this.data||this.dismissed){this.shadow.innerHTML="";return}const e=this.data.okLabel??"Ok",t=this.data.cancelLabel;this.shadow.innerHTML=`
|
|
812
812
|
<style>
|
|
813
813
|
:host { all: initial; }
|
|
814
814
|
.overlay {
|
|
@@ -906,7 +906,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
906
906
|
<div class="modal-body-element" style="display:none; flex:1; overflow:auto; padding:18px;"></div>
|
|
907
907
|
</div>
|
|
908
908
|
</div>
|
|
909
|
-
`,this.root=this.shadow.querySelector(".backdrop"),this.iframe=this.shadow.querySelector("iframe"),this.shadow.querySelector(".modal-close")?.addEventListener("click",()=>this.close()),this.root?.addEventListener("click",t=>{t.target===this.root&&this.close()}),document.addEventListener("keydown",t=>{t.key==="Escape"&&this.classList.contains("open")&&this.close()})}}const
|
|
909
|
+
`,this.root=this.shadow.querySelector(".backdrop"),this.iframe=this.shadow.querySelector("iframe"),this.shadow.querySelector(".modal-close")?.addEventListener("click",()=>this.close()),this.root?.addEventListener("click",t=>{t.target===this.root&&this.close()}),document.addEventListener("keydown",t=>{t.key==="Escape"&&this.classList.contains("open")&&this.close()})}}const Fh=[{label:"Self-filing guidance"},{label:"Smart tax suggestions"},{label:"Auto-fetch 26AS / AIS"},{label:"Notice management"},{label:"Dedicated tax expert"},{label:"End-to-end filing"},{label:"Document handling"}],Dh=[{label:"DIY",match:["DIY","DIY_SALARY"],selectLabel:"Select DIY — Without Notice (₹{price}/yr)",postback:"Without Notice",features:[!0,!0,!0,!1,!1,!1,!1]},{label:"DIY + Notice",match:["NOTICE_DIY","DIY_NOTICE"],selectLabel:"Select DIY — With Notice (₹{price}/yr)",postback:"With Notice",features:[!0,!0,!0,!0,!1,!1,!1]},{label:"Assisted",match:["ASSISTED"],selectLabel:"Switch to Assisted (₹{price}/yr)",postback:"Assisted",features:[!0,!0,!0,!0,!0,!0,!0]}];class Fl extends HTMLElement{shadow;data=null;columns=Dh;features=Fh;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setData(e){this.data=e,this.render()}setColumns(e){this.columns=e,this.render()}setFeatures(e){this.features=e,this.render()}priceFor(e){if(!this.data?.data)return null;for(const t of this.data.data)if(e.match.includes(t.planType))return t.planMaster?.basePrice??null;return null}render(){const e=this.columns,t=this.features;this.shadow.innerHTML=`
|
|
910
910
|
<style>
|
|
911
911
|
:host {
|
|
912
912
|
display: block;
|
|
@@ -983,4 +983,4 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
983
983
|
<small>Tap to select</small>
|
|
984
984
|
</button>`}).join("")}
|
|
985
985
|
</div>
|
|
986
|
-
`,this.shadow.querySelectorAll("button.action").forEach(r=>{r.addEventListener("click",()=>{const a=Number(r.dataset.col),n=e[a];n&&this.dispatchEvent(new CustomEvent("aikaara-plan-select",{detail:{planType:n.match[0],message:n.postback,label:n.label},bubbles:!0,composed:!0}))})})}}function zr(c){return c.replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}function Dl(){const c=[["aikaara-chat-widget",wl],["aikaara-chat-bubble",_l],["aikaara-chat-header",kl],["aikaara-message-list",El],["aikaara-message-bubble",Al],["aikaara-chat-input",Il],["aikaara-typing-indicator",Tl],["aikaara-streaming-message",Cl],["aikaara-error-banner",Ol],["aikaara-template-renderer",Ml],["aikaara-system-pill",Rl],["aikaara-option-list",jl],["aikaara-submit-action",Ll],["aikaara-modal-action",Nl],["aikaara-chat",Ul],["aikaara-link-modal",Bl],["aikaara-compare-plans",Fl]];for(const[e,t]of c)customElements.get(e)||customElements.define(e,t)}Dl();function Kr(c,e,t=""){if(!e)return t;const r=e.split(".");let a=c;for(const n of r)if(a&&typeof a=="object"&&n in a)a=a[n];else return t;return typeof a=="string"?a:t}function Dh(c){try{const e=c.split(".")[1];if(!e)return 0;const t=JSON.parse(atob(e.replace(/-/g,"+").replace(/_/g,"/")));return typeof t.exp=="number"?t.exp*1e3:0}catch{return 0}}async function Pr(c){return typeof c=="function"?await c():c}class $l{constructor(e,t){this.descriptor=e,this.sessionToken=t}cache=null;inflight=null;reset(){this.cache=null,this.inflight=null}async get(){const e=this.descriptor.expiryBufferMs??6e4,t=Date.now();return this.cache&&this.cache.expiresAt>t+e?this.cache:this.inflight?this.inflight:(this.inflight=this.fetchOnce().finally(()=>{this.inflight=null}),this.inflight)}async fetchOnce(){const e=await Pr(this.sessionToken),t=this.descriptor.authHeader??"Authorization",r=this.descriptor.authHeaderTemplate??"Bearer {token}",a={accept:"application/json",...this.descriptor.headers??{},[t]:r.replace("{token}",e)},n=this.descriptor.method??"POST",i={method:n,headers:a};n==="POST"&&(a["content-type"]="application/json",i.body=JSON.stringify(this.descriptor.body??{}));const s=await fetch(this.descriptor.endpoint,i);if(!s.ok){const b=await s.text().catch(()=>"");throw new Error(`Session auth failed: ${s.status} ${b.slice(0,200)}`)}const o=await s.json().catch(()=>({})),l=Kr(o,this.descriptor.tokenPath??"data.token"),u=this.descriptor.tokenStripPrefix,d=u?l.replace(new RegExp(`^${u}`,"i"),"").trim():l;if(!d)throw new Error("Session auth response missing token");const p=Kr(o,this.descriptor.requestIdPath??"data.requestId"),y=this.cache?.requestId||p;if(!y)throw new Error("Session auth response missing requestId");const f=Kr(o,this.descriptor.fullNamePath??"data.fullName"),g=Dh(d)||Date.now()+3600*1e3;return this.cache={token:d,requestId:y,fullName:f,expiresAt:g},this.cache}}async function Wl(c){const e={};for(const t of c.spec){const r=await $h(t,c.providers);if(r!==void 0&&r!=="")e[t.name]=r;else{if(t.required)throw new Error(`[aikaara-chat-sdk] SSO credential "${t.name}" is required but ${t.source}`+(t.key?`[${t.key}]`:"")+" returned no value");t.default!==void 0&&(e[t.name]=t.default)}}return e}async function $h(c,e){const t=c.key??c.name;switch(c.source){case"cookie":return Wh(t);case"localStorage":return nr(()=>window.localStorage.getItem(t)??void 0);case"sessionStorage":return nr(()=>window.sessionStorage.getItem(t)??void 0);case"url_param":return nr(()=>new URL(window.location.href).searchParams.get(t)??void 0);case"header_meta":return nr(()=>document.querySelector(`meta[name="${qh(t)}"]`)?.content??void 0);case"callback":{const r=e?.[c.name];if(!r)return;const a=await r();return typeof a=="string"?a:void 0}default:return}}function Wh(c){if(typeof document>"u")return;const e=encodeURIComponent(c),t=document.cookie?document.cookie.split("; "):[];for(const r of t){const a=r.indexOf("=");if(a===-1)continue;const n=r.slice(0,a);if(n===c||n===e)try{return decodeURIComponent(r.slice(a+1))}catch{return r.slice(a+1)}}}function nr(c){try{return c()}catch{return}}function qh(c){return c.replace(/["\\]/g,"\\$&")}const Hh=1800;class ql{constructor(e){this.opts=e,this.cache=this.loadCache()}cache=null;inflight=null;reset(){this.cache=null,this.inflight=null,this.clearCache()}async get(e=!1){if(!e){const t=this.cache;if(t&&(!t.expiresAt||t.expiresAt>Date.now()))return t}return this.inflight?this.inflight:(this.inflight=this.exchange().finally(()=>{this.inflight=null}),this.inflight)}async exchange(){if(!this.opts.descriptor.collect||this.opts.descriptor.collect.length===0)throw new Error("[aikaara-chat-sdk] SsoExchangeAdapter.exchange() requires descriptor.sso.collect; v2 partner-token flow should be handled by TokenDiscoveryReader instead.");const e=await Wl({spec:this.opts.descriptor.collect,providers:this.opts.providers}),t=JSON.stringify({credentials:e}),r={accept:"application/json","content-type":"application/json",...this.opts.descriptor.headers??{}};this.opts.descriptor.apiKey&&(r["X-Api-Key"]=this.opts.descriptor.apiKey);const a=this.opts.descriptor.exchangeEndpoint||this.opts.exchangeUrl;if(!a)throw new Error("[aikaara-chat-sdk] SSO exchange URL not resolved — set descriptor.sso.exchangeEndpoint or pass `exchangeUrl` (mountFromSlug derives it from configBase + slug).");const n=await fetch(a,{method:"POST",headers:r,body:t});if(!n.ok){const d=await n.text().catch(()=>"");throw new Error(`SSO exchange failed: ${n.status} ${d.slice(0,240)}`)}const s=(await n.json().catch(()=>({}))).user??{},o=String(s.ext_uid??s.extUid??""),l=String(s.token??s.user_token??s.userToken??"");if(!o)throw new Error("SSO exchange response missing user.ext_uid");if(!l)throw new Error("SSO exchange response missing user.token");const u={id:s.id,extUid:o,userToken:l,email:typeof s.email=="string"?s.email:void 0,displayName:typeof s.display_name=="string"?s.display_name:typeof s.displayName=="string"?s.displayName:void 0,properties:s.properties&&typeof s.properties=="object"?s.properties:void 0,expiresAt:this.computeExpiry()};return this.cache=u,this.persistCache(u),u}computeExpiry(){const e=this.opts.descriptor.cacheTtlSec??Hh;if(!(!this.opts.descriptor.cacheKey||e<=0))return Date.now()+e*1e3}loadCache(){const e=this.opts.descriptor.cacheKey;if(!e)return null;try{const t=window.localStorage.getItem(e);if(!t)return null;const r=JSON.parse(t);return r.expiresAt&&r.expiresAt<Date.now()?(window.localStorage.removeItem(e),null):r}catch{return null}}persistCache(e){const t=this.opts.descriptor.cacheKey;if(t)try{window.localStorage.setItem(t,JSON.stringify(e))}catch{}}clearCache(){const e=this.opts.descriptor.cacheKey;if(e)try{window.localStorage.removeItem(e)}catch{}}}const zh=3e4,Kh=2e3,Vh=100;async function Hl(c){const{descriptor:e}=c,t=e.tokenSourceConfig??{};switch(e.tokenSource){case"init":{if(!c.initToken)throw new Ke("init","No init token supplied to Aikaara.init({token})");return{token:c.initToken,source:"init"}}case"query":{const r=typeof t.key=="string"&&t.key?t.key:"token",a=Gh(r);if(!a)throw new Ke("query",`?${r}= not present`);return{token:a,source:"query"}}case"hash":{const r=typeof t.key=="string"&&t.key?t.key:"token",a=Yh(r);if(!a)throw new Ke("hash",`#${r}= not present`);return{token:a,source:"hash"}}case"postmsg":{const r=typeof t.type=="string"?t.type:"",a=typeof t.key=="string"&&t.key?t.key:"token",n=ef(typeof t.origins=="string"?t.origins:""),i=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:zh;return{token:await Zh({type:r,key:a,origins:n,timeoutMs:i}),source:"postmsg"}}case"cookie":{const r=typeof t.name=="string"&&t.name?t.name:"";if(!r)throw new Ke("cookie","cookie.name not configured");const a=Qh(r);if(!a)throw new Ke("cookie",`cookie "${r}" not set`);return{token:a,source:"cookie"}}case"storage":{const r=t.store==="session"?"session":"local",a=typeof t.key=="string"&&t.key?t.key:"",n=typeof t.path=="string"?t.path:"";if(!a)throw new Ke("storage","storage.key not configured");const i=Jh(r,a,n);if(!i)throw new Ke("storage",`${r}Storage["${a}"] not set`);return{token:i,source:"storage"}}case"global":{const r=typeof t.path=="string"?t.path:"";if(!r)throw new Ke("global","global.path not configured");const a=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:Kh,n=typeof t.intervalMs=="number"&&t.intervalMs>0?t.intervalMs:Vh,i=await Xh(r,a,n);if(!i)throw new Ke("global",`window.${r} not present`);return{token:i,source:"global"}}default:{const r=e.tokenSource;throw new Ke("unknown",`Unknown tokenSource ${JSON.stringify(r)}`)}}}class zl{constructor(e){this.opts=e}cached=null;get descriptor(){return this.opts.descriptor}async get(){if(this.cached)return this.cached;const e=await Hl(this.opts);return this.cached=e,e}async refresh(){return this.opts.descriptor.tokenSource==="init"?this.cached?this.cached:this.get():(this.cached=null,this.get())}}class Ke extends Error{constructor(e,t){super(`[aikaara-chat-sdk] token-discovery (${e}): ${t}`),this.source=e,this.name="TokenDiscoveryError"}}function Gh(c){if(!(typeof window>"u"))try{return new URL(window.location.href).searchParams.get(c)??void 0}catch{return}}function Yh(c){if(!(typeof window>"u"))try{const e=window.location.hash.replace(/^#/,"");return new URLSearchParams(e).get(c)??void 0}catch{return}}function Qh(c){if(typeof document>"u")return;const e=encodeURIComponent(c),t=document.cookie?document.cookie.split("; "):[];for(const r of t){const a=r.indexOf("=");if(a===-1)continue;const n=r.slice(0,a);if(n===c||n===e)try{return decodeURIComponent(r.slice(a+1))}catch{return r.slice(a+1)}}}function Jh(c,e,t){if(!(typeof window>"u"))try{const a=(c==="session"?window.sessionStorage:window.localStorage).getItem(e);if(a==null)return;if(!t)return a;let n;try{n=JSON.parse(a)}catch{return a}const i=Kl(n,t);return typeof i=="string"?i:void 0}catch{return}}async function Xh(c,e,t){if(typeof window>"u")return;const r=Date.now()+e;for(;Date.now()<r;){const a=Kl(window,c);if(typeof a=="string"&&a.length>0)return a;if(typeof a=="function")try{const n=a();if(typeof n=="string"&&n.length>0)return n}catch{}await new Promise(n=>setTimeout(n,t))}}function Zh(c){return new Promise((e,t)=>{if(typeof window>"u"){t(new Ke("postmsg","no window"));return}const r=()=>{window.removeEventListener("message",n),clearTimeout(a)},a=setTimeout(()=>{r(),t(new Ke("postmsg",`timeout after ${c.timeoutMs}ms`))},c.timeoutMs),n=i=>{if(c.origins.length>0&&!c.origins.includes(i.origin))return;const s=i.data;if(!s||typeof s!="object")return;const o=s;if(c.type&&o.type!==c.type)return;const l=o[c.key];typeof l=="string"&&l.length>0&&(r(),e(l))};window.addEventListener("message",n)})}function ef(c){return c?c.split(/[,\s]+/).map(e=>e.trim()).filter(Boolean):[]}function Kl(c,e){if(!e)return c;const t=e.split(".").filter(Boolean);let r=c;for(const a of t)if(r&&typeof r=="object"&&a in r)r=r[a];else return;return r}function tf(){const c=typeof crypto<"u"?crypto:null;if(c?.randomUUID)return c.randomUUID();if(c?.getRandomValues){const e=new Uint8Array(16);c.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;const t=[...e].map(r=>r.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}return"xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}const rf="aikaara_chat:requestId";function uo(c,e){return`${rf}:${c}:${e}`}function nf(c,e){try{return localStorage.getItem(uo(c,e))}catch{return null}}function of(c,e,t){try{localStorage.setItem(uo(c,e),t)}catch{}}function sf(c,e){try{localStorage.removeItem(uo(c,e))}catch{}}async function af(c,e){console.log("[aikaara-chat-sdk] preflight running",c.length,"steps");const t={userId:e.userId,projectId:e.projectId,slug:e.slug};if(e.identity)for(const[s,o]of Object.entries(e.identity))typeof o=="string"&&(t[s]=o);const r=s=>s.replace(/\{(\w+)\}/g,(o,l)=>l in t?t[l]:""),a=s=>{if(typeof s=="string")return r(s);if(Array.isArray(s))return s.map(a);if(s&&typeof s=="object"){const o={};for(const[l,u]of Object.entries(s))o[l]=a(u);return o}return s},n=await Pr(e.sessionToken),i=[800,1500,3e3,5e3,8e3];for(let s=0;s<c.length;s++){const o=c[s],l=r(o.url),u=o.method??(o.body?"POST":"GET"),d={accept:"application/json",...o.headers??{}};if((o.authHeader??"session")==="session"){const b=o.authHeaderTemplate??"Bearer {token}";d.authorization=b.replace("{token}",n)}const p={method:u,headers:d};o.body&&(d["content-type"]="application/json",p.body=JSON.stringify(a(o.body)));let y=0,f="",g=0;for(;;)try{const b=await fetch(l,p);if(b.ok)break;if(y=b.status,f=await b.text().catch(()=>""),g<i.length&&lf(y,f)){const m=i[g++];console.warn(`[aikaara-chat-sdk] preflight #${s} ${u} ${l} → ${y} (transient). Retry #${g} in ${m}ms.`),await new Promise(w=>setTimeout(w,m));continue}const k=`Preflight #${s} ${u} ${l} → ${y} ${f.slice(0,200)}`;if(o.soft){console.warn("[aikaara-chat-sdk]",k);break}throw new Error(k)}catch(b){if(g<i.length){const k=i[g++];console.warn(`[aikaara-chat-sdk] preflight #${s} threw, retry #${g} in ${k}ms`,b),await new Promise(m=>setTimeout(m,k));continue}if(o.soft){console.warn(`[aikaara-chat-sdk] preflight #${s} soft-failed:`,b);break}throw b}}}function lf(c,e){if(c===503||c===504||c===502)return!0;if(c===401||c===403)return e.trim().length===0;if(c===500){const t=e.toLowerCase();return t.includes("customernew")||t.includes("is null")||t.includes("not yet ready")}return!1}async function Vl(c,e){const t=await fetch(c,{method:"GET",headers:{accept:"application/json",...e??{}}});if(!t.ok){const a=await t.text().catch(()=>"");throw new Error(`Widget config fetch failed: ${t.status} ${t.statusText} ${a.slice(0,200)}`)}const r=await t.json();if(r&&typeof r=="object"){if("config"in r)return r.config;if("data"in r)return r.data}return r}function cf(c,e){return c.replace("{projectId}",e).replace("{uuid}",tf().replace(/-/g,""))}function Gl(c){const e=c._preload;if(!Array.isArray(e)||e.length===0)return;const t=Array.from(new Set(e.map(r=>r&&typeof r=="object"?r.scriptUrl:null).filter(r=>typeof r=="string"&&r.length>0)));t.length!==0&&Promise.allSettled(t.map(r=>Pl(r)))}async function Yl(c){const e={...c.config??(c.configUrl?await Vl(c.configUrl,c.configHeaders):{}),...c.overrides??{}};Gl(e);const t=e.transport??"tiledesk",r=e.tiledesk;if((t==="tiledesk"||t==="dual")&&!r)throw new Error("mount: descriptor.tiledesk is required for tiledesk/dual transport");const a=r?.projectId??"",n=c.identity.userId,i=c.forceNewConversation?null:nf(n,a),s=r?.requestIdTemplate??"support-group-{projectId}-{uuid}",o=c.conversationId??i??cf(s,a);(!i||c.forceNewConversation)&&a&&of(n,a,o);const l=await c.tokenProvider(),u=c.tokenProvider,d=c.historyTokenProvider??u,p=r?{mqttEndpoint:r.mqttEndpoint,jwtToken:l,userId:n,userName:c.identity.userName,projectId:r.projectId,appId:r.appId,mqttUsername:r.mqttUsername,protocolId:r.protocolId,protocolVersion:r.protocolVersion,keepAliveSec:r.keepAliveSec,connectTimeoutMs:r.connectTimeoutMs,maxReconnectAttempts:r.maxReconnectAttempts,reconnectMaxDelayMs:r.reconnectMaxDelayMs,wildcardSubscribe:r.wildcardSubscribe,enablePresence:r.enablePresence,autoInitiateOnEmpty:r.autoInitiateOnEmpty,chatInitiatedAttributes:r.chatInitiatedAttributes,messageDefaults:{...r.messageDefaults,...c.identity.departmentId?{departmentId:c.identity.departmentId}:r.messageDefaults?.departmentId?{departmentId:r.messageDefaults.departmentId}:{}},fileTemplate:r.fileTemplate,topicTemplates:r.topicTemplates,debug:r.debug,senderFullname:c.identity.senderFullname??c.identity.userName,tokenProvider:u}:void 0,y=c.uploadAdapter??(e.uploadEndpoint?co({endpoint:e.uploadEndpoint,fieldName:e.uploadFieldName,extraFields:e.uploadExtraFields}):void 0),f=c.historyAdapter??(e.historyApiBase?vl({apiBase:e.historyApiBase,pageSize:e.historyPageSize??200,pathTemplate:e.historyPathTemplate,extraHeaders:e.historyHeaders,getToken:d}):void 0),g={transport:t,baseUrl:"",userToken:c.userToken??n,conversationId:o,display:e.display??"embed",position:e.position,primaryColor:e.theme?.primary??e.primaryColor,title:e.title,subtitle:e.subtitle,avatarUrl:e.avatarUrl,width:e.width,height:e.height,borderRadius:e.theme?.radius??e.borderRadius,fontFamily:e.theme?.font??e.fontFamily,themeTokens:e.theme,linkHandlers:e.linkHandlers,getLinkBearer:c.getLinkBearer,welcomeMessage:e.welcomeMessage,placeholder:e.placeholder,showTimestamps:e.showTimestamps,persistConversation:e.persistConversation,showHeader:e.showHeader,hideSystemMessages:e.hideSystemMessages,timestampFormat:e.timestampFormat,input:e.input,templateLayout:e.templateLayout,tiledesk:p,tiledeskIdentity:{userId:n,userName:c.identity.userName,departmentId:c.identity.departmentId,senderFullname:c.identity.senderFullname??c.identity.userName},templateActionAttributes:e.templateActionAttributes,uploadAdapter:y,historyAdapter:f,onError:c.onError,onMessage:c.onMessage},b=document.createElement("aikaara-chat-widget");return b.configure(g),g.title&&b.setAttribute("title",g.title),g.primaryColor&&b.setAttribute("primary-color",g.primaryColor),g.display&&b.setAttribute("display",g.display),g.display==="embed"&&(b.style.cssText="display:flex;flex-direction:column;width:100%;height:100%;min-height:0;"),c.container.appendChild(b),{widget:b,requestId:o,config:g,destroy(){b.remove()}}}function uf(c){if(typeof c!="string")return c;const e=document.querySelector(c);if(!e)throw new Error(`mountFromSlug: container "${c}" not found`);return e}async function Ql(c){const e=(c.configBase??"https://api.aikaara.com").replace(/\/$/,""),t=`${e}/api/v1/widget_configs/${encodeURIComponent(c.slug)}`;let r=null;try{r=await Vl(t,c.configHeaders)}catch(w){if(!c.fallbackConfig)throw w;console.warn(`[aikaara-chat-sdk] Widget config fetch failed for slug "${c.slug}" — using fallbackConfig.`,w)}const a={...c.fallbackConfig??{},...r??{},...c.overrides??{}};if(Gl(a),a.templates&&Object.keys(a.templates).length>0){a.components={...a.components??{}};for(const[w,E]of Object.entries(a.templates)){const v=`template:${w}`;a.components[v]||!E?.scriptUrl||!E?.render||(a.components[v]={kind:"iife-element",scriptUrl:E.scriptUrl,tag:E.render,...E.props?{props:E.props}:{}})}}if(window.__aikaara_descriptor__={templates:a.templates,components:a.components,razorpay:a.razorpay,title:a.title},!a.auth)throw new Error(`mountFromSlug: widget_configs/${c.slug} descriptor must include "auth" block`);let n=null,i=c.user.id,s=c.user.name,o="",l=c.user.token,u=null;if(a.sso?.tokenSource){u=new zl({descriptor:{provider:a.sso.provider,flow:a.sso.flow,skipLogin:a.sso.skipLogin,autoRefresh:a.sso.autoRefresh,tokenSource:a.sso.tokenSource,tokenSourceConfig:a.sso.tokenSourceConfig,fallback:a.sso.fallback,map:a.sso.map},initToken:c.user.partnerToken});const w=await u.get();l=async()=>(await u.get()).token,c.user.identity&&!c.user.identity.partnerToken&&(c.user.identity.partnerToken=w.token)}else if(a.sso&&a.sso.collect&&a.sso.collect.length>0){const w=`${e}/api/v1/projects/by-slug/${encodeURIComponent(c.slug)}/sso_exchange`;n=await new ql({descriptor:a.sso,providers:c.user.credentialProviders,exchangeUrl:w}).get(),i=n.extUid||i,s=s??n.displayName,o=n.userToken}a.preflight&&a.preflight.length&&await af(a.preflight,{sessionToken:l,userId:i,projectId:a.tiledesk?.projectId??"",slug:c.slug,identity:c.user.identity});const d=new $l(a.auth,l),p=await d.get(),y=p.fullName||s||i;window.__aikaara_runtime__={getChatJwt:async()=>(await d.get()).token,identity:c.user.identity,slug:c.slug};const f=u&&a.sso?.autoRefresh?async()=>{try{return await u.refresh(),d.reset(),(await d.get()).token}catch(w){return console.warn("[aikaara-chat-sdk] partner auto-refresh failed",w),null}}:null,g=a.upload,b=async()=>`Bearer ${g&&"tokenSource"in g&&g.tokenSource==="chat"?(await d.get()).token:await Pr(c.user.token)}`,k=c.hooks?.upload??(g&&g.mode==="presigned-3step"?yl({...g,authHeader:b}):g&&g.mode==="direct"?co({endpoint:g.endpoint,fieldName:g.fieldName,extraFields:g.extraFields,headers:async()=>({authorization:await b()})}):void 0),m=await Yl({container:uf(c.container),config:a,userToken:o||void 0,identity:{userId:i,userName:y,departmentId:c.user.departmentId,senderFullname:y},tokenProvider:async()=>(await d.get()).token,historyTokenProvider:async()=>(await d.get()).token,uploadAdapter:k,historyAdapter:c.hooks?.history,conversationId:p.requestId,onError:c.hooks?.onError,onMessage:c.hooks?.onMessage,getLinkBearer:async w=>w==="none"?null:w==="chat"?(await d.get()).token:Pr(c.user.token)});return Object.assign(m,{fullName:y,requestId:p.requestId,descriptor:a,async refreshAuth(){d.reset(),await d.get()},async refreshPartnerAuth(){return f?f():null}})}exports.ActionCableClient=Vr;exports.AikaaraChat=Ul;exports.AikaaraChatBubble=_l;exports.AikaaraChatClient=bl;exports.AikaaraChatHeader=kl;exports.AikaaraChatInput=Il;exports.AikaaraChatWidget=wl;exports.AikaaraComparePlans=Fl;exports.AikaaraErrorBanner=Ol;exports.AikaaraLinkModal=Bl;exports.AikaaraMessageBubble=Al;exports.AikaaraMessageList=El;exports.AikaaraModalAction=Nl;exports.AikaaraOptionList=jl;exports.AikaaraStreamingMessage=Cl;exports.AikaaraSubmitAction=Ll;exports.AikaaraSystemPill=Rl;exports.AikaaraTemplateRenderer=Ml;exports.AikaaraTypingIndicator=Tl;exports.ApiClient=Rs;exports.ChannelSubscription=Ps;exports.ConnectionManager=Ms;exports.ConversationManager=Ls;exports.EventEmitter=Vi;exports.MessageStore=js;exports.SessionAuthAdapter=$l;exports.SsoExchangeAdapter=ql;exports.TiledeskTransport=dl;exports.TokenDiscoveryError=Ke;exports.TokenDiscoveryReader=zl;exports.clearPersistedConversationId=sf;exports.collectSsoCredentials=Wl;exports.createFetchUploadAdapter=co;exports.createPresigned3StepUploadAdapter=yl;exports.createTiledeskHistoryAdapter=vl;exports.discoverToken=Hl;exports.extractTiledeskFileEnvelope=ml;exports.inferTiledeskRole=gl;exports.isTiledeskSelfEcho=pl;exports.mount=Yl;exports.mountFromSlug=Ql;exports.parseTiledeskTemplate=lo;exports.registerComponents=Dl;
|
|
986
|
+
`,this.shadow.querySelectorAll("button.action").forEach(r=>{r.addEventListener("click",()=>{const a=Number(r.dataset.col),n=e[a];n&&this.dispatchEvent(new CustomEvent("aikaara-plan-select",{detail:{planType:n.match[0],message:n.postback,label:n.label},bubbles:!0,composed:!0}))})})}}function zr(c){return c.replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}function Dl(){const c=[["aikaara-chat-widget",wl],["aikaara-chat-bubble",_l],["aikaara-chat-header",kl],["aikaara-message-list",El],["aikaara-message-bubble",Al],["aikaara-chat-input",Il],["aikaara-typing-indicator",Tl],["aikaara-streaming-message",Cl],["aikaara-error-banner",Ol],["aikaara-template-renderer",Ml],["aikaara-system-pill",Rl],["aikaara-option-list",jl],["aikaara-submit-action",Ll],["aikaara-modal-action",Nl],["aikaara-chat",Ul],["aikaara-link-modal",Bl],["aikaara-compare-plans",Fl]];for(const[e,t]of c)customElements.get(e)||customElements.define(e,t)}Dl();function Kr(c,e,t=""){if(!e)return t;const r=e.split(".");let a=c;for(const n of r)if(a&&typeof a=="object"&&n in a)a=a[n];else return t;return typeof a=="string"?a:t}function $h(c){try{const e=c.split(".")[1];if(!e)return 0;const t=JSON.parse(atob(e.replace(/-/g,"+").replace(/_/g,"/")));return typeof t.exp=="number"?t.exp*1e3:0}catch{return 0}}async function Pr(c){return typeof c=="function"?await c():c}class $l{constructor(e,t){this.descriptor=e,this.sessionToken=t}cache=null;inflight=null;reset(){this.cache=null,this.inflight=null}async get(){const e=this.descriptor.expiryBufferMs??6e4,t=Date.now();return this.cache&&this.cache.expiresAt>t+e?this.cache:this.inflight?this.inflight:(this.inflight=this.fetchOnce().finally(()=>{this.inflight=null}),this.inflight)}async fetchOnce(){const e=await Pr(this.sessionToken),t=this.descriptor.authHeader??"Authorization",r=this.descriptor.authHeaderTemplate??"Bearer {token}",a={accept:"application/json",...this.descriptor.headers??{},[t]:r.replace("{token}",e)},n=this.descriptor.method??"POST",i={method:n,headers:a};n==="POST"&&(a["content-type"]="application/json",i.body=JSON.stringify(this.descriptor.body??{}));const s=await fetch(this.descriptor.endpoint,i);if(!s.ok){const b=await s.text().catch(()=>"");throw new Error(`Session auth failed: ${s.status} ${b.slice(0,200)}`)}const o=await s.json().catch(()=>({})),l=Kr(o,this.descriptor.tokenPath??"data.token"),u=this.descriptor.tokenStripPrefix,d=u?l.replace(new RegExp(`^${u}`,"i"),"").trim():l;if(!d)throw new Error("Session auth response missing token");const p=Kr(o,this.descriptor.requestIdPath??"data.requestId"),y=this.cache?.requestId||p;if(!y)throw new Error("Session auth response missing requestId");const f=Kr(o,this.descriptor.fullNamePath??"data.fullName"),g=$h(d)||Date.now()+3600*1e3;return this.cache={token:d,requestId:y,fullName:f,expiresAt:g},this.cache}}async function Wl(c){const e={};for(const t of c.spec){const r=await Wh(t,c.providers);if(r!==void 0&&r!=="")e[t.name]=r;else{if(t.required)throw new Error(`[aikaara-chat-sdk] SSO credential "${t.name}" is required but ${t.source}`+(t.key?`[${t.key}]`:"")+" returned no value");t.default!==void 0&&(e[t.name]=t.default)}}return e}async function Wh(c,e){const t=c.key??c.name;switch(c.source){case"cookie":return qh(t);case"localStorage":return nr(()=>window.localStorage.getItem(t)??void 0);case"sessionStorage":return nr(()=>window.sessionStorage.getItem(t)??void 0);case"url_param":return nr(()=>new URL(window.location.href).searchParams.get(t)??void 0);case"header_meta":return nr(()=>document.querySelector(`meta[name="${Hh(t)}"]`)?.content??void 0);case"callback":{const r=e?.[c.name];if(!r)return;const a=await r();return typeof a=="string"?a:void 0}default:return}}function qh(c){if(typeof document>"u")return;const e=encodeURIComponent(c),t=document.cookie?document.cookie.split("; "):[];for(const r of t){const a=r.indexOf("=");if(a===-1)continue;const n=r.slice(0,a);if(n===c||n===e)try{return decodeURIComponent(r.slice(a+1))}catch{return r.slice(a+1)}}}function nr(c){try{return c()}catch{return}}function Hh(c){return c.replace(/["\\]/g,"\\$&")}const zh=1800;class ql{constructor(e){this.opts=e,this.cache=this.loadCache()}cache=null;inflight=null;reset(){this.cache=null,this.inflight=null,this.clearCache()}async get(e=!1){if(!e){const t=this.cache;if(t&&(!t.expiresAt||t.expiresAt>Date.now()))return t}return this.inflight?this.inflight:(this.inflight=this.exchange().finally(()=>{this.inflight=null}),this.inflight)}async exchange(){if(!this.opts.descriptor.collect||this.opts.descriptor.collect.length===0)throw new Error("[aikaara-chat-sdk] SsoExchangeAdapter.exchange() requires descriptor.sso.collect; v2 partner-token flow should be handled by TokenDiscoveryReader instead.");const e=await Wl({spec:this.opts.descriptor.collect,providers:this.opts.providers}),t=JSON.stringify({credentials:e}),r={accept:"application/json","content-type":"application/json",...this.opts.descriptor.headers??{}};this.opts.descriptor.apiKey&&(r["X-Api-Key"]=this.opts.descriptor.apiKey);const a=this.opts.descriptor.exchangeEndpoint||this.opts.exchangeUrl;if(!a)throw new Error("[aikaara-chat-sdk] SSO exchange URL not resolved — set descriptor.sso.exchangeEndpoint or pass `exchangeUrl` (mountFromSlug derives it from configBase + slug).");const n=await fetch(a,{method:"POST",headers:r,body:t});if(!n.ok){const d=await n.text().catch(()=>"");throw new Error(`SSO exchange failed: ${n.status} ${d.slice(0,240)}`)}const s=(await n.json().catch(()=>({}))).user??{},o=String(s.ext_uid??s.extUid??""),l=String(s.token??s.user_token??s.userToken??"");if(!o)throw new Error("SSO exchange response missing user.ext_uid");if(!l)throw new Error("SSO exchange response missing user.token");const u={id:s.id,extUid:o,userToken:l,email:typeof s.email=="string"?s.email:void 0,displayName:typeof s.display_name=="string"?s.display_name:typeof s.displayName=="string"?s.displayName:void 0,properties:s.properties&&typeof s.properties=="object"?s.properties:void 0,expiresAt:this.computeExpiry()};return this.cache=u,this.persistCache(u),u}computeExpiry(){const e=this.opts.descriptor.cacheTtlSec??zh;if(!(!this.opts.descriptor.cacheKey||e<=0))return Date.now()+e*1e3}loadCache(){const e=this.opts.descriptor.cacheKey;if(!e)return null;try{const t=window.localStorage.getItem(e);if(!t)return null;const r=JSON.parse(t);return r.expiresAt&&r.expiresAt<Date.now()?(window.localStorage.removeItem(e),null):r}catch{return null}}persistCache(e){const t=this.opts.descriptor.cacheKey;if(t)try{window.localStorage.setItem(t,JSON.stringify(e))}catch{}}clearCache(){const e=this.opts.descriptor.cacheKey;if(e)try{window.localStorage.removeItem(e)}catch{}}}const Kh=3e4,Vh=2e3,Gh=100;async function Hl(c){const{descriptor:e}=c,t=e.tokenSourceConfig??{};switch(e.tokenSource){case"init":{if(!c.initToken)throw new Ke("init","No init token supplied to Aikaara.init({token})");return{token:c.initToken,source:"init"}}case"query":{const r=typeof t.key=="string"&&t.key?t.key:"token",a=Yh(r);if(!a)throw new Ke("query",`?${r}= not present`);return{token:a,source:"query"}}case"hash":{const r=typeof t.key=="string"&&t.key?t.key:"token",a=Qh(r);if(!a)throw new Ke("hash",`#${r}= not present`);return{token:a,source:"hash"}}case"postmsg":{const r=typeof t.type=="string"?t.type:"",a=typeof t.key=="string"&&t.key?t.key:"token",n=tf(typeof t.origins=="string"?t.origins:""),i=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:Kh;return{token:await ef({type:r,key:a,origins:n,timeoutMs:i}),source:"postmsg"}}case"cookie":{const r=typeof t.name=="string"&&t.name?t.name:"";if(!r)throw new Ke("cookie","cookie.name not configured");const a=Jh(r);if(!a)throw new Ke("cookie",`cookie "${r}" not set`);return{token:a,source:"cookie"}}case"storage":{const r=t.store==="session"?"session":"local",a=typeof t.key=="string"&&t.key?t.key:"",n=typeof t.path=="string"?t.path:"";if(!a)throw new Ke("storage","storage.key not configured");const i=Xh(r,a,n);if(!i)throw new Ke("storage",`${r}Storage["${a}"] not set`);return{token:i,source:"storage"}}case"global":{const r=typeof t.path=="string"?t.path:"";if(!r)throw new Ke("global","global.path not configured");const a=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:Vh,n=typeof t.intervalMs=="number"&&t.intervalMs>0?t.intervalMs:Gh,i=await Zh(r,a,n);if(!i)throw new Ke("global",`window.${r} not present`);return{token:i,source:"global"}}default:{const r=e.tokenSource;throw new Ke("unknown",`Unknown tokenSource ${JSON.stringify(r)}`)}}}class zl{constructor(e){this.opts=e}cached=null;get descriptor(){return this.opts.descriptor}async get(){if(this.cached)return this.cached;const e=await Hl(this.opts);return this.cached=e,e}async refresh(){return this.opts.descriptor.tokenSource==="init"?this.cached?this.cached:this.get():(this.cached=null,this.get())}}class Ke extends Error{constructor(e,t){super(`[aikaara-chat-sdk] token-discovery (${e}): ${t}`),this.source=e,this.name="TokenDiscoveryError"}}function Yh(c){if(!(typeof window>"u"))try{return new URL(window.location.href).searchParams.get(c)??void 0}catch{return}}function Qh(c){if(!(typeof window>"u"))try{const e=window.location.hash.replace(/^#/,"");return new URLSearchParams(e).get(c)??void 0}catch{return}}function Jh(c){if(typeof document>"u")return;const e=encodeURIComponent(c),t=document.cookie?document.cookie.split("; "):[];for(const r of t){const a=r.indexOf("=");if(a===-1)continue;const n=r.slice(0,a);if(n===c||n===e)try{return decodeURIComponent(r.slice(a+1))}catch{return r.slice(a+1)}}}function Xh(c,e,t){if(!(typeof window>"u"))try{const a=(c==="session"?window.sessionStorage:window.localStorage).getItem(e);if(a==null)return;if(!t)return a;let n;try{n=JSON.parse(a)}catch{return a}const i=Kl(n,t);return typeof i=="string"?i:void 0}catch{return}}async function Zh(c,e,t){if(typeof window>"u")return;const r=Date.now()+e;for(;Date.now()<r;){const a=Kl(window,c);if(typeof a=="string"&&a.length>0)return a;if(typeof a=="function")try{const n=a();if(typeof n=="string"&&n.length>0)return n}catch{}await new Promise(n=>setTimeout(n,t))}}function ef(c){return new Promise((e,t)=>{if(typeof window>"u"){t(new Ke("postmsg","no window"));return}const r=()=>{window.removeEventListener("message",n),clearTimeout(a)},a=setTimeout(()=>{r(),t(new Ke("postmsg",`timeout after ${c.timeoutMs}ms`))},c.timeoutMs),n=i=>{if(c.origins.length>0&&!c.origins.includes(i.origin))return;const s=i.data;if(!s||typeof s!="object")return;const o=s;if(c.type&&o.type!==c.type)return;const l=o[c.key];typeof l=="string"&&l.length>0&&(r(),e(l))};window.addEventListener("message",n)})}function tf(c){return c?c.split(/[,\s]+/).map(e=>e.trim()).filter(Boolean):[]}function Kl(c,e){if(!e)return c;const t=e.split(".").filter(Boolean);let r=c;for(const a of t)if(r&&typeof r=="object"&&a in r)r=r[a];else return;return r}function rf(){const c=typeof crypto<"u"?crypto:null;if(c?.randomUUID)return c.randomUUID();if(c?.getRandomValues){const e=new Uint8Array(16);c.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;const t=[...e].map(r=>r.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}return"xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}const nf="aikaara_chat:requestId";function uo(c,e){return`${nf}:${c}:${e}`}function of(c,e){try{return localStorage.getItem(uo(c,e))}catch{return null}}function sf(c,e,t){try{localStorage.setItem(uo(c,e),t)}catch{}}function af(c,e){try{localStorage.removeItem(uo(c,e))}catch{}}async function lf(c,e){console.log("[aikaara-chat-sdk] preflight running",c.length,"steps");const t={userId:e.userId,projectId:e.projectId,slug:e.slug};if(e.identity)for(const[s,o]of Object.entries(e.identity))typeof o=="string"&&(t[s]=o);const r=s=>s.replace(/\{(\w+)\}/g,(o,l)=>l in t?t[l]:""),a=s=>{if(typeof s=="string")return r(s);if(Array.isArray(s))return s.map(a);if(s&&typeof s=="object"){const o={};for(const[l,u]of Object.entries(s))o[l]=a(u);return o}return s},n=await Pr(e.sessionToken),i=[800,1500,3e3,5e3,8e3];for(let s=0;s<c.length;s++){const o=c[s],l=r(o.url),u=o.method??(o.body?"POST":"GET"),d={accept:"application/json",...o.headers??{}};if((o.authHeader??"session")==="session"){const b=o.authHeaderTemplate??"Bearer {token}";d.authorization=b.replace("{token}",n)}const p={method:u,headers:d};o.body&&(d["content-type"]="application/json",p.body=JSON.stringify(a(o.body)));let y=0,f="",g=0;for(;;)try{const b=await fetch(l,p);if(b.ok)break;if(y=b.status,f=await b.text().catch(()=>""),g<i.length&&cf(y,f)){const m=i[g++];console.warn(`[aikaara-chat-sdk] preflight #${s} ${u} ${l} → ${y} (transient). Retry #${g} in ${m}ms.`),await new Promise(w=>setTimeout(w,m));continue}const k=`Preflight #${s} ${u} ${l} → ${y} ${f.slice(0,200)}`;if(o.soft){console.warn("[aikaara-chat-sdk]",k);break}throw new Error(k)}catch(b){if(g<i.length){const k=i[g++];console.warn(`[aikaara-chat-sdk] preflight #${s} threw, retry #${g} in ${k}ms`,b),await new Promise(m=>setTimeout(m,k));continue}if(o.soft){console.warn(`[aikaara-chat-sdk] preflight #${s} soft-failed:`,b);break}throw b}}}function cf(c,e){if(c===503||c===504||c===502)return!0;if(c===401||c===403)return e.trim().length===0;if(c===500){const t=e.toLowerCase();return t.includes("customernew")||t.includes("is null")||t.includes("not yet ready")}return!1}async function Vl(c,e){const t=await fetch(c,{method:"GET",headers:{accept:"application/json",...e??{}}});if(!t.ok){const a=await t.text().catch(()=>"");throw new Error(`Widget config fetch failed: ${t.status} ${t.statusText} ${a.slice(0,200)}`)}const r=await t.json();if(r&&typeof r=="object"){if("config"in r)return r.config;if("data"in r)return r.data}return r}function uf(c,e){return c.replace("{projectId}",e).replace("{uuid}",rf().replace(/-/g,""))}function Gl(c){const e=c._preload;if(!Array.isArray(e)||e.length===0)return;const t=Array.from(new Set(e.map(r=>r&&typeof r=="object"?r.scriptUrl:null).filter(r=>typeof r=="string"&&r.length>0)));t.length!==0&&Promise.allSettled(t.map(r=>Pl(r)))}async function Yl(c){const e={...c.config??(c.configUrl?await Vl(c.configUrl,c.configHeaders):{}),...c.overrides??{}};Gl(e);const t=e.transport??"tiledesk",r=e.tiledesk;if((t==="tiledesk"||t==="dual")&&!r)throw new Error("mount: descriptor.tiledesk is required for tiledesk/dual transport");const a=r?.projectId??"",n=c.identity.userId,i=c.forceNewConversation?null:of(n,a),s=r?.requestIdTemplate??"support-group-{projectId}-{uuid}",o=c.conversationId??i??uf(s,a);(!i||c.forceNewConversation)&&a&&sf(n,a,o);const l=await c.tokenProvider(),u=c.tokenProvider,d=c.historyTokenProvider??u,p=r?{mqttEndpoint:r.mqttEndpoint,jwtToken:l,userId:n,userName:c.identity.userName,projectId:r.projectId,appId:r.appId,mqttUsername:r.mqttUsername,protocolId:r.protocolId,protocolVersion:r.protocolVersion,keepAliveSec:r.keepAliveSec,connectTimeoutMs:r.connectTimeoutMs,maxReconnectAttempts:r.maxReconnectAttempts,reconnectMaxDelayMs:r.reconnectMaxDelayMs,wildcardSubscribe:r.wildcardSubscribe,enablePresence:r.enablePresence,autoInitiateOnEmpty:r.autoInitiateOnEmpty,chatInitiatedAttributes:r.chatInitiatedAttributes,messageDefaults:{...r.messageDefaults,...c.identity.departmentId?{departmentId:c.identity.departmentId}:r.messageDefaults?.departmentId?{departmentId:r.messageDefaults.departmentId}:{}},fileTemplate:r.fileTemplate,topicTemplates:r.topicTemplates,debug:r.debug,senderFullname:c.identity.senderFullname??c.identity.userName,tokenProvider:u}:void 0,y=c.uploadAdapter??(e.uploadEndpoint?co({endpoint:e.uploadEndpoint,fieldName:e.uploadFieldName,extraFields:e.uploadExtraFields}):void 0),f=c.historyAdapter??(e.historyApiBase?vl({apiBase:e.historyApiBase,pageSize:e.historyPageSize??200,pathTemplate:e.historyPathTemplate,extraHeaders:e.historyHeaders,getToken:d}):void 0),g={transport:t,baseUrl:"",userToken:c.userToken??n,conversationId:o,display:e.display??"embed",position:e.position,primaryColor:e.theme?.primary??e.primaryColor,title:e.title,subtitle:e.subtitle,avatarUrl:e.avatarUrl,width:e.width,height:e.height,borderRadius:e.theme?.radius??e.borderRadius,fontFamily:e.theme?.font??e.fontFamily,themeTokens:e.theme,linkHandlers:e.linkHandlers,getLinkBearer:c.getLinkBearer,welcomeMessage:e.welcomeMessage,placeholder:e.placeholder,showTimestamps:e.showTimestamps,persistConversation:e.persistConversation,showHeader:e.showHeader,hideSystemMessages:e.hideSystemMessages,timestampFormat:e.timestampFormat,input:e.input,templateLayout:e.templateLayout,tiledesk:p,tiledeskIdentity:{userId:n,userName:c.identity.userName,departmentId:c.identity.departmentId,senderFullname:c.identity.senderFullname??c.identity.userName},templateActionAttributes:e.templateActionAttributes,uploadAdapter:y,historyAdapter:f,onError:c.onError,onMessage:c.onMessage},b=document.createElement("aikaara-chat-widget");return b.configure(g),g.title&&b.setAttribute("title",g.title),g.primaryColor&&b.setAttribute("primary-color",g.primaryColor),g.display&&b.setAttribute("display",g.display),g.display==="embed"&&(b.style.cssText="display:flex;flex-direction:column;width:100%;height:100%;min-height:0;"),c.container.appendChild(b),{widget:b,requestId:o,config:g,destroy(){b.remove()}}}function hf(c){if(typeof c!="string")return c;const e=document.querySelector(c);if(!e)throw new Error(`mountFromSlug: container "${c}" not found`);return e}async function Ql(c){const e=(c.configBase??"https://api.aikaara.com").replace(/\/$/,""),t=`${e}/api/v1/widget_configs/${encodeURIComponent(c.slug)}`;let r=null;try{r=await Vl(t,c.configHeaders)}catch(w){if(!c.fallbackConfig)throw w;console.warn(`[aikaara-chat-sdk] Widget config fetch failed for slug "${c.slug}" — using fallbackConfig.`,w)}const a={...c.fallbackConfig??{},...r??{},...c.overrides??{}};if(Gl(a),a.templates&&Object.keys(a.templates).length>0){a.components={...a.components??{}};for(const[w,E]of Object.entries(a.templates)){const v=`template:${w}`;a.components[v]||!E?.scriptUrl||!E?.render||(a.components[v]={kind:"iife-element",scriptUrl:E.scriptUrl,tag:E.render,...E.props?{props:E.props}:{}})}}if(window.__aikaara_descriptor__={templates:a.templates,components:a.components,razorpay:a.razorpay,title:a.title},!a.auth)throw new Error(`mountFromSlug: widget_configs/${c.slug} descriptor must include "auth" block`);let n=null,i=c.user.id,s=c.user.name,o="",l=c.user.token,u=null;if(a.sso?.tokenSource){u=new zl({descriptor:{provider:a.sso.provider,flow:a.sso.flow,skipLogin:a.sso.skipLogin,autoRefresh:a.sso.autoRefresh,tokenSource:a.sso.tokenSource,tokenSourceConfig:a.sso.tokenSourceConfig,fallback:a.sso.fallback,map:a.sso.map},initToken:c.user.partnerToken});const w=await u.get();l=async()=>(await u.get()).token,c.user.identity&&!c.user.identity.partnerToken&&(c.user.identity.partnerToken=w.token)}else if(a.sso&&a.sso.collect&&a.sso.collect.length>0){const w=`${e}/api/v1/projects/by-slug/${encodeURIComponent(c.slug)}/sso_exchange`;n=await new ql({descriptor:a.sso,providers:c.user.credentialProviders,exchangeUrl:w}).get(),i=n.extUid||i,s=s??n.displayName,o=n.userToken}a.preflight&&a.preflight.length&&await lf(a.preflight,{sessionToken:l,userId:i,projectId:a.tiledesk?.projectId??"",slug:c.slug,identity:c.user.identity});const d=new $l(a.auth,l),p=await d.get(),y=p.fullName||s||i;window.__aikaara_runtime__={getChatJwt:async()=>(await d.get()).token,identity:c.user.identity,slug:c.slug};const f=u&&a.sso?.autoRefresh?async()=>{try{return await u.refresh(),d.reset(),(await d.get()).token}catch(w){return console.warn("[aikaara-chat-sdk] partner auto-refresh failed",w),null}}:null,g=a.upload,b=async()=>`Bearer ${g&&"tokenSource"in g&&g.tokenSource==="chat"?(await d.get()).token:await Pr(c.user.token)}`,k=c.hooks?.upload??(g&&g.mode==="presigned-3step"?yl({...g,authHeader:b}):g&&g.mode==="direct"?co({endpoint:g.endpoint,fieldName:g.fieldName,extraFields:g.extraFields,headers:async()=>({authorization:await b()})}):void 0),m=await Yl({container:hf(c.container),config:a,userToken:o||void 0,identity:{userId:i,userName:y,departmentId:c.user.departmentId,senderFullname:y},tokenProvider:async()=>(await d.get()).token,historyTokenProvider:async()=>(await d.get()).token,uploadAdapter:k,historyAdapter:c.hooks?.history,conversationId:p.requestId,onError:c.hooks?.onError,onMessage:c.hooks?.onMessage,getLinkBearer:async w=>w==="none"?null:w==="chat"?(await d.get()).token:Pr(c.user.token)});return Object.assign(m,{fullName:y,requestId:p.requestId,descriptor:a,async refreshAuth(){d.reset(),await d.get()},async refreshPartnerAuth(){return f?f():null}})}exports.ActionCableClient=Vr;exports.AikaaraChat=Ul;exports.AikaaraChatBubble=_l;exports.AikaaraChatClient=bl;exports.AikaaraChatHeader=kl;exports.AikaaraChatInput=Il;exports.AikaaraChatWidget=wl;exports.AikaaraComparePlans=Fl;exports.AikaaraErrorBanner=Ol;exports.AikaaraLinkModal=Bl;exports.AikaaraMessageBubble=Al;exports.AikaaraMessageList=El;exports.AikaaraModalAction=Nl;exports.AikaaraOptionList=jl;exports.AikaaraStreamingMessage=Cl;exports.AikaaraSubmitAction=Ll;exports.AikaaraSystemPill=Rl;exports.AikaaraTemplateRenderer=Ml;exports.AikaaraTypingIndicator=Tl;exports.ApiClient=Rs;exports.ChannelSubscription=Ps;exports.ConnectionManager=Ms;exports.ConversationManager=Ls;exports.EventEmitter=Vi;exports.MessageStore=js;exports.SessionAuthAdapter=$l;exports.SsoExchangeAdapter=ql;exports.TiledeskTransport=dl;exports.TokenDiscoveryError=Ke;exports.TokenDiscoveryReader=zl;exports.clearPersistedConversationId=af;exports.collectSsoCredentials=Wl;exports.createFetchUploadAdapter=co;exports.createPresigned3StepUploadAdapter=yl;exports.createTiledeskHistoryAdapter=vl;exports.discoverToken=Hl;exports.extractTiledeskFileEnvelope=ml;exports.inferTiledeskRole=gl;exports.isTiledeskSelfEcho=pl;exports.mount=Yl;exports.mountFromSlug=Ql;exports.parseTiledeskTemplate=lo;exports.registerComponents=Dl;
|