@aikaara/chat-sdk 0.8.5 → 0.8.6
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-z47varff.cjs → MountTenant-CbQMTk-J.cjs} +1 -1
- package/dist/{MountTenant-DQwRihyN.mjs → MountTenant-DA_soQf0.mjs} +463 -455
- package/dist/cdn/aikaara-chat.iife.js +1 -1
- package/dist/headless.cjs +1 -1
- package/dist/headless.d.ts +15 -0
- package/dist/headless.mjs +2 -2
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +15 -0
- package/dist/index.mjs +2 -2
- package/dist/ui.cjs +1 -1
- package/dist/ui.mjs +1 -1
- package/package.json +1 -1
|
@@ -980,7 +980,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
980
980
|
<small>Tap to select</small>
|
|
981
981
|
</button>`}).join("")}
|
|
982
982
|
</div>
|
|
983
|
-
`,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 ao(c){return c.replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}function lo(){const c=[["aikaara-chat-widget",ol],["aikaara-chat-bubble",sl],["aikaara-chat-header",al],["aikaara-message-list",cl],["aikaara-message-bubble",hl],["aikaara-chat-input",dl],["aikaara-typing-indicator",pl],["aikaara-streaming-message",gl],["aikaara-error-banner",ml],["aikaara-template-renderer",kh],["aikaara-system-pill",xh],["aikaara-option-list",Ah],["aikaara-submit-action",Ih],["aikaara-modal-action",Ch],["aikaara-chat",Oh],["aikaara-link-modal",Ph],["aikaara-compare-plans",jh]];for(const[e,t]of c)customElements.get(e)||customElements.define(e,t)}lo();function co(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 Lh(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 Nr(c){return typeof c=="function"?await c():c}class vl{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 Nr(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 y=await s.text().catch(()=>"");throw new Error(`Session auth failed: ${s.status} ${y.slice(0,200)}`)}const o=await s.json().catch(()=>({})),l=co(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=co(o,this.descriptor.requestIdPath??"data.requestId"),b=this.cache?.requestId||p;if(!b)throw new Error("Session auth response missing requestId");const f=co(o,this.descriptor.fullNamePath??"data.fullName"),g=Lh(d)||Date.now()+3600*1e3;return this.cache={token:d,requestId:b,fullName:f,expiresAt:g},this.cache}}async function wl(c){const e={};for(const t of c.spec){const r=await Nh(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 Nh(c,e){const t=c.key??c.name;switch(c.source){case"cookie":return Uh(t);case"localStorage":return Ur(()=>window.localStorage.getItem(t)??void 0);case"sessionStorage":return Ur(()=>window.sessionStorage.getItem(t)??void 0);case"url_param":return Ur(()=>new URL(window.location.href).searchParams.get(t)??void 0);case"header_meta":return Ur(()=>document.querySelector(`meta[name="${Bh(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 Uh(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 Ur(c){try{return c()}catch{return}}function Bh(c){return c.replace(/["\\]/g,"\\$&")}const Fh=1800;class _l{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??Fh;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 Dh=3e4,$h=2e3,Wh=100;async function kl(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=qh(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=Hh(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=Yh(typeof t.origins=="string"?t.origins:""),i=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:Dh;return{token:await Gh({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=zh(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=Kh(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:$h,n=typeof t.intervalMs=="number"&&t.intervalMs>0?t.intervalMs:Wh,i=await Vh(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 Sl{constructor(e){this.opts=e}cached=null;get descriptor(){return this.opts.descriptor}async get(){if(this.cached)return this.cached;const e=await kl(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 qh(c){if(!(typeof window>"u"))try{return new URL(window.location.href).searchParams.get(c)??void 0}catch{return}}function Hh(c){if(!(typeof window>"u"))try{const e=window.location.hash.replace(/^#/,"");return new URLSearchParams(e).get(c)??void 0}catch{return}}function zh(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 Kh(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=El(n,t);return typeof i=="string"?i:void 0}catch{return}}async function Vh(c,e,t){if(typeof window>"u")return;const r=Date.now()+e;for(;Date.now()<r;){const a=El(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 Gh(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 Yh(c){return c?c.split(/[,\s]+/).map(e=>e.trim()).filter(Boolean):[]}function El(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 Qh(){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 Jh="aikaara_chat:requestId";function uo(c,e){return`${Jh}:${c}:${e}`}function Xh(c,e){try{return localStorage.getItem(uo(c,e))}catch{return null}}function Zh(c,e,t){try{localStorage.setItem(uo(c,e),t)}catch{}}function ef(c,e){try{localStorage.removeItem(uo(c,e))}catch{}}async function tf(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 Nr(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 y=o.authHeaderTemplate??"Bearer {token}";d.authorization=y.replace("{token}",n)}const p={method:u,headers:d};o.body&&(d["content-type"]="application/json",p.body=JSON.stringify(a(o.body)));let b=0,f="",g=0;for(;;)try{const y=await fetch(l,p);if(y.ok)break;if(b=y.status,f=await y.text().catch(()=>""),g<i.length&&rf(b,f)){const m=i[g++];console.warn(`[aikaara-chat-sdk] preflight #${s} ${u} ${l} → ${b} (transient). Retry #${g} in ${m}ms.`),await new Promise(w=>setTimeout(w,m));continue}const k=`Preflight #${s} ${u} ${l} → ${b} ${f.slice(0,200)}`;if(o.soft){console.warn("[aikaara-chat-sdk]",k);break}throw new Error(k)}catch(y){if(g<i.length){const k=i[g++];console.warn(`[aikaara-chat-sdk] preflight #${s} threw, retry #${g} in ${k}ms`,y),await new Promise(m=>setTimeout(m,k));continue}if(o.soft){console.warn(`[aikaara-chat-sdk] preflight #${s} soft-failed:`,y);break}throw y}}}function rf(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 xl(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 nf(c,e){return c.replace("{projectId}",e).replace("{uuid}",Qh().replace(/-/g,""))}async function Al(c){const e={...c.config??(c.configUrl?await xl(c.configUrl,c.configHeaders):{}),...c.overrides??{}},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:Xh(n,a),s=r?.requestIdTemplate??"support-group-{projectId}-{uuid}",o=c.conversationId??i??nf(s,a);(!i||c.forceNewConversation)&&a&&Zh(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,b=c.uploadAdapter??(e.uploadEndpoint?no({endpoint:e.uploadEndpoint,fieldName:e.uploadFieldName,extraFields:e.uploadExtraFields}):void 0),f=c.historyAdapter??(e.historyApiBase?il({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:b,historyAdapter:f,onError:c.onError,onMessage:c.onMessage},y=document.createElement("aikaara-chat-widget");return y.configure(g),g.title&&y.setAttribute("title",g.title),g.primaryColor&&y.setAttribute("primary-color",g.primaryColor),g.display&&y.setAttribute("display",g.display),g.display==="embed"&&(y.style.cssText="display:flex;flex-direction:column;width:100%;height:100%;min-height:0;"),c.container.appendChild(y),{widget:y,requestId:o,config:g,destroy(){y.remove()}}}function of(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 Il(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 xl(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(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},!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 Sl({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 _l({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 tf(a.preflight,{sessionToken:l,userId:i,projectId:a.tiledesk?.projectId??"",slug:c.slug,identity:c.user.identity});const d=new vl(a.auth,l),p=await d.get(),b=p.fullName||s||i,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,y=async()=>`Bearer ${g&&"tokenSource"in g&&g.tokenSource==="chat"?(await d.get()).token:await Nr(c.user.token)}`,k=c.hooks?.upload??(g&&g.mode==="presigned-3step"?nl({...g,authHeader:y}):g&&g.mode==="direct"?no({endpoint:g.endpoint,fieldName:g.fieldName,extraFields:g.extraFields,headers:async()=>({authorization:await y()})}):void 0),m=await Al({container:of(c.container),config:a,userToken:o||void 0,identity:{userId:i,userName:b,departmentId:c.user.departmentId,senderFullname:b},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:Nr(c.user.token)});return Object.assign(m,{fullName:b,requestId:p.requestId,descriptor:a,async refreshAuth(){d.reset(),await d.get()},async refreshPartnerAuth(){return f?f():null}})}function sf(c){lo();const e=document.createElement("aikaara-chat-widget"),t={baseUrl:"base-url",userToken:"user-token",apiKey:"api-key",title:"title",subtitle:"subtitle",theme:"theme",primaryColor:"primary-color",position:"position",width:"width",height:"height",placeholder:"placeholder",welcomeMessage:"welcome-message",avatarUrl:"avatar-url"};for(const[r,a]of Object.entries(t)){const n=c[r];n!=null&&e.setAttribute(a,String(n))}return e.configure(c),document.body.appendChild(e),e}function af(){const c=document.querySelector("aikaara-chat-widget");c&&c.remove()}class Tl extends HTMLElement{shadow;payload=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e){this.payload=e,this.render()}render(){const e=this.payload;this.shadow.innerHTML=`
|
|
983
|
+
`,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 ao(c){return c.replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}function lo(){const c=[["aikaara-chat-widget",ol],["aikaara-chat-bubble",sl],["aikaara-chat-header",al],["aikaara-message-list",cl],["aikaara-message-bubble",hl],["aikaara-chat-input",dl],["aikaara-typing-indicator",pl],["aikaara-streaming-message",gl],["aikaara-error-banner",ml],["aikaara-template-renderer",kh],["aikaara-system-pill",xh],["aikaara-option-list",Ah],["aikaara-submit-action",Ih],["aikaara-modal-action",Ch],["aikaara-chat",Oh],["aikaara-link-modal",Ph],["aikaara-compare-plans",jh]];for(const[e,t]of c)customElements.get(e)||customElements.define(e,t)}lo();function co(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 Lh(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 Nr(c){return typeof c=="function"?await c():c}class vl{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 Nr(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 y=await s.text().catch(()=>"");throw new Error(`Session auth failed: ${s.status} ${y.slice(0,200)}`)}const o=await s.json().catch(()=>({})),l=co(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=co(o,this.descriptor.requestIdPath??"data.requestId"),b=this.cache?.requestId||p;if(!b)throw new Error("Session auth response missing requestId");const f=co(o,this.descriptor.fullNamePath??"data.fullName"),g=Lh(d)||Date.now()+3600*1e3;return this.cache={token:d,requestId:b,fullName:f,expiresAt:g},this.cache}}async function wl(c){const e={};for(const t of c.spec){const r=await Nh(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 Nh(c,e){const t=c.key??c.name;switch(c.source){case"cookie":return Uh(t);case"localStorage":return Ur(()=>window.localStorage.getItem(t)??void 0);case"sessionStorage":return Ur(()=>window.sessionStorage.getItem(t)??void 0);case"url_param":return Ur(()=>new URL(window.location.href).searchParams.get(t)??void 0);case"header_meta":return Ur(()=>document.querySelector(`meta[name="${Bh(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 Uh(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 Ur(c){try{return c()}catch{return}}function Bh(c){return c.replace(/["\\]/g,"\\$&")}const Fh=1800;class _l{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??Fh;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 Dh=3e4,$h=2e3,Wh=100;async function kl(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=qh(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=Hh(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=Yh(typeof t.origins=="string"?t.origins:""),i=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:Dh;return{token:await Gh({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=zh(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=Kh(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:$h,n=typeof t.intervalMs=="number"&&t.intervalMs>0?t.intervalMs:Wh,i=await Vh(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 Sl{constructor(e){this.opts=e}cached=null;get descriptor(){return this.opts.descriptor}async get(){if(this.cached)return this.cached;const e=await kl(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 qh(c){if(!(typeof window>"u"))try{return new URL(window.location.href).searchParams.get(c)??void 0}catch{return}}function Hh(c){if(!(typeof window>"u"))try{const e=window.location.hash.replace(/^#/,"");return new URLSearchParams(e).get(c)??void 0}catch{return}}function zh(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 Kh(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=El(n,t);return typeof i=="string"?i:void 0}catch{return}}async function Vh(c,e,t){if(typeof window>"u")return;const r=Date.now()+e;for(;Date.now()<r;){const a=El(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 Gh(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 Yh(c){return c?c.split(/[,\s]+/).map(e=>e.trim()).filter(Boolean):[]}function El(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 Qh(){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 Jh="aikaara_chat:requestId";function uo(c,e){return`${Jh}:${c}:${e}`}function Xh(c,e){try{return localStorage.getItem(uo(c,e))}catch{return null}}function Zh(c,e,t){try{localStorage.setItem(uo(c,e),t)}catch{}}function ef(c,e){try{localStorage.removeItem(uo(c,e))}catch{}}async function tf(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 Nr(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 y=o.authHeaderTemplate??"Bearer {token}";d.authorization=y.replace("{token}",n)}const p={method:u,headers:d};o.body&&(d["content-type"]="application/json",p.body=JSON.stringify(a(o.body)));let b=0,f="",g=0;for(;;)try{const y=await fetch(l,p);if(y.ok)break;if(b=y.status,f=await y.text().catch(()=>""),g<i.length&&rf(b,f)){const m=i[g++];console.warn(`[aikaara-chat-sdk] preflight #${s} ${u} ${l} → ${b} (transient). Retry #${g} in ${m}ms.`),await new Promise(w=>setTimeout(w,m));continue}const k=`Preflight #${s} ${u} ${l} → ${b} ${f.slice(0,200)}`;if(o.soft){console.warn("[aikaara-chat-sdk]",k);break}throw new Error(k)}catch(y){if(g<i.length){const k=i[g++];console.warn(`[aikaara-chat-sdk] preflight #${s} threw, retry #${g} in ${k}ms`,y),await new Promise(m=>setTimeout(m,k));continue}if(o.soft){console.warn(`[aikaara-chat-sdk] preflight #${s} soft-failed:`,y);break}throw y}}}function rf(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 xl(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 nf(c,e){return c.replace("{projectId}",e).replace("{uuid}",Qh().replace(/-/g,""))}async function Al(c){const e={...c.config??(c.configUrl?await xl(c.configUrl,c.configHeaders):{}),...c.overrides??{}},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:Xh(n,a),s=r?.requestIdTemplate??"support-group-{projectId}-{uuid}",o=c.conversationId??i??nf(s,a);(!i||c.forceNewConversation)&&a&&Zh(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,b=c.uploadAdapter??(e.uploadEndpoint?no({endpoint:e.uploadEndpoint,fieldName:e.uploadFieldName,extraFields:e.uploadExtraFields}):void 0),f=c.historyAdapter??(e.historyApiBase?il({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:b,historyAdapter:f,onError:c.onError,onMessage:c.onMessage},y=document.createElement("aikaara-chat-widget");return y.configure(g),g.title&&y.setAttribute("title",g.title),g.primaryColor&&y.setAttribute("primary-color",g.primaryColor),g.display&&y.setAttribute("display",g.display),g.display==="embed"&&(y.style.cssText="display:flex;flex-direction:column;width:100%;height:100%;min-height:0;"),c.container.appendChild(y),{widget:y,requestId:o,config:g,destroy(){y.remove()}}}function of(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 Il(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 xl(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(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 Sl({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 _l({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 tf(a.preflight,{sessionToken:l,userId:i,projectId:a.tiledesk?.projectId??"",slug:c.slug,identity:c.user.identity});const d=new vl(a.auth,l),p=await d.get(),b=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,y=async()=>`Bearer ${g&&"tokenSource"in g&&g.tokenSource==="chat"?(await d.get()).token:await Nr(c.user.token)}`,k=c.hooks?.upload??(g&&g.mode==="presigned-3step"?nl({...g,authHeader:y}):g&&g.mode==="direct"?no({endpoint:g.endpoint,fieldName:g.fieldName,extraFields:g.extraFields,headers:async()=>({authorization:await y()})}):void 0),m=await Al({container:of(c.container),config:a,userToken:o||void 0,identity:{userId:i,userName:b,departmentId:c.user.departmentId,senderFullname:b},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:Nr(c.user.token)});return Object.assign(m,{fullName:b,requestId:p.requestId,descriptor:a,async refreshAuth(){d.reset(),await d.get()},async refreshPartnerAuth(){return f?f():null}})}function sf(c){lo();const e=document.createElement("aikaara-chat-widget"),t={baseUrl:"base-url",userToken:"user-token",apiKey:"api-key",title:"title",subtitle:"subtitle",theme:"theme",primaryColor:"primary-color",position:"position",width:"width",height:"height",placeholder:"placeholder",welcomeMessage:"welcome-message",avatarUrl:"avatar-url"};for(const[r,a]of Object.entries(t)){const n=c[r];n!=null&&e.setAttribute(a,String(n))}return e.configure(c),document.body.appendChild(e),e}function af(){const c=document.querySelector("aikaara-chat-widget");c&&c.remove()}class Tl extends HTMLElement{shadow;payload=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e){this.payload=e,this.render()}render(){const e=this.payload;this.shadow.innerHTML=`
|
|
984
984
|
<style>
|
|
985
985
|
:host { display: block; margin-top: 8px; }
|
|
986
986
|
button {
|
package/dist/headless.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./MountTenant-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./MountTenant-CbQMTk-J.cjs");class s extends e.EventEmitter{registration=null;pendingEdits=[];constructor(t){super(),this.setupListeners(t)}registerForm(t){this.registration=t;const i=this.pendingEdits.filter(r=>r.entity_type===t.entityType&&String(r.entity_id)===String(t.entityId));if(i.length>0){for(const r of i)t.onFieldUpdate(r.fields),this.emit("edit:applied",{entityType:r.entity_type,entityId:r.entity_id,fields:r.fields});this.pendingEdits=this.pendingEdits.filter(r=>!(r.entity_type===t.entityType&&String(r.entity_id)===String(t.entityId)))}}unregisterForm(t,i){this.registration?.entityType===t&&String(this.registration?.entityId)===String(i)&&(this.registration=null)}get currentForm(){return this.registration}pushFieldUpdates(t,i,r){this.registration&&this.registration.entityType===t&&String(this.registration.entityId)===String(i)?(this.registration.onFieldUpdate(r),this.emit("edit:applied",{entityType:t,entityId:i,fields:r})):(this.pendingEdits.push({action:"edit_entity",entity_type:t,entity_id:i,fields:r}),this.emit("edit:pending",{entityType:t,entityId:i,fields:r}))}async requestSave(){if(!this.registration)return{success:!1,error:"No form registered"};try{return await this.registration.onSave(),this.emit("save:success",{entityType:this.registration.entityType,entityId:this.registration.entityId}),{success:!0}}catch(t){const i=t instanceof Error?t.message:"Save failed";return this.emit("save:error",{entityType:this.registration.entityType,entityId:this.registration.entityId,error:i}),{success:!1,error:i}}}async requestTest(t){if(!this.registration?.onTest)return{success:!1,error:"Current form does not support testing"};try{return await this.registration.onTest(t),{success:!0}}catch(i){return{success:!1,error:i instanceof Error?i.message:"Test failed"}}}setupListeners(t){t.on("action:edit_entity",i=>{this.pushFieldUpdates(i.entity_type,i.entity_id,i.fields)}),t.on("action:save_entity",i=>{this.requestSave()}),t.on("action:test_tool",i=>{this.emit("test:triggered",{toolId:i.tool_id,parameters:i.parameters}),this.requestTest(i.parameters)})}}exports.ActionCableClient=e.ActionCableClient;exports.AikaaraChatClient=e.AikaaraChatClient;exports.ApiClient=e.ApiClient;exports.ChannelSubscription=e.ChannelSubscription;exports.ConnectionManager=e.ConnectionManager;exports.ConversationManager=e.ConversationManager;exports.EventEmitter=e.EventEmitter;exports.MessageStore=e.MessageStore;exports.SessionAuthAdapter=e.SessionAuthAdapter;exports.SsoExchangeAdapter=e.SsoExchangeAdapter;exports.TiledeskTransport=e.TiledeskTransport;exports.TokenDiscoveryError=e.TokenDiscoveryError;exports.TokenDiscoveryReader=e.TokenDiscoveryReader;exports.clearPersistedConversationId=e.clearPersistedConversationId;exports.collectSsoCredentials=e.collectSsoCredentials;exports.createFetchUploadAdapter=e.createFetchUploadAdapter;exports.createPresigned3StepUploadAdapter=e.createPresigned3StepUploadAdapter;exports.createTiledeskHistoryAdapter=e.createTiledeskHistoryAdapter;exports.discoverToken=e.discoverToken;exports.extractTiledeskFileEnvelope=e.extractTiledeskFileEnvelope;exports.inferTiledeskRole=e.inferTiledeskRole;exports.isTiledeskSelfEcho=e.isTiledeskSelfEcho;exports.mountFromSlug=e.mountFromSlug;exports.mountTenantWidget=e.mount;exports.parseTiledeskTemplate=e.parseTiledeskTemplate;exports.FormBridge=s;
|
package/dist/headless.d.ts
CHANGED
|
@@ -2287,6 +2287,21 @@ export declare interface WidgetConfigDescriptor {
|
|
|
2287
2287
|
/** Absolute base URL for tenant API calls. No trailing slash. */
|
|
2288
2288
|
baseUrl?: string;
|
|
2289
2289
|
};
|
|
2290
|
+
/**
|
|
2291
|
+
* Razorpay Checkout config consumed by the `payment_link` IIFE template.
|
|
2292
|
+
* `keyId` is the publishable key (safe to expose). `preferredBanksUrl`
|
|
2293
|
+
* (optional) is a tenant endpoint that returns the list of allowed
|
|
2294
|
+
* netbanking codes for an order, called as `GET <url>?orderId=<id>` with
|
|
2295
|
+
* the chat JWT as Bearer; when present the Razorpay UI is restricted to
|
|
2296
|
+
* netbanking with those banks.
|
|
2297
|
+
*/
|
|
2298
|
+
razorpay?: {
|
|
2299
|
+
keyId?: string;
|
|
2300
|
+
/** Merchant name shown on the Checkout sheet. Defaults to descriptor.title. */
|
|
2301
|
+
name?: string;
|
|
2302
|
+
/** Endpoint template; `{orderId}` is substituted, else appended as `?orderId=`. */
|
|
2303
|
+
preferredBanksUrl?: string;
|
|
2304
|
+
};
|
|
2290
2305
|
/**
|
|
2291
2306
|
* Unified slot map. Supersedes `templates` and the bespoke
|
|
2292
2307
|
* `linkHandlers[].render` mechanism. Each key is a slot id that some
|
package/dist/headless.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { E as s } from "./MountTenant-
|
|
2
|
-
import { A as p, b as l, k as g, C as c, l as h, m as y, M as u, S as m, n as f, T, o as S, p as _, q as v, s as E, t as C, u as F, v as k, w as A, x as I, y as x, z as U, B as q, D as M, F as b } from "./MountTenant-
|
|
1
|
+
import { E as s } from "./MountTenant-DA_soQf0.mjs";
|
|
2
|
+
import { A as p, b as l, k as g, C as c, l as h, m as y, M as u, S as m, n as f, T, o as S, p as _, q as v, s as E, t as C, u as F, v as k, w as A, x as I, y as x, z as U, B as q, D as M, F as b } from "./MountTenant-DA_soQf0.mjs";
|
|
3
3
|
class a extends s {
|
|
4
4
|
registration = null;
|
|
5
5
|
pendingEdits = [];
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./MountTenant-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./MountTenant-CbQMTk-J.cjs"),s=require("./headless.cjs");function l(a){e.registerComponents();const t=document.createElement("aikaara-chat-widget"),i={baseUrl:"base-url",userToken:"user-token",apiKey:"api-key",title:"title",subtitle:"subtitle",theme:"theme",primaryColor:"primary-color",position:"position",width:"width",height:"height",placeholder:"placeholder",welcomeMessage:"welcome-message",avatarUrl:"avatar-url"};for(const[o,n]of Object.entries(i)){const r=a[o];r!=null&&t.setAttribute(n,String(r))}return t.configure(a),document.body.appendChild(t),t}function d(){const a=document.querySelector("aikaara-chat-widget");a&&a.remove()}exports.ActionCableClient=e.ActionCableClient;exports.AikaaraChatBubble=e.AikaaraChatBubble;exports.AikaaraChatClient=e.AikaaraChatClient;exports.AikaaraChatHeader=e.AikaaraChatHeader;exports.AikaaraChatInput=e.AikaaraChatInput;exports.AikaaraChatWidget=e.AikaaraChatWidget;exports.AikaaraErrorBanner=e.AikaaraErrorBanner;exports.AikaaraMessageBubble=e.AikaaraMessageBubble;exports.AikaaraMessageList=e.AikaaraMessageList;exports.AikaaraStreamingMessage=e.AikaaraStreamingMessage;exports.AikaaraTypingIndicator=e.AikaaraTypingIndicator;exports.ApiClient=e.ApiClient;exports.ChannelSubscription=e.ChannelSubscription;exports.ConnectionManager=e.ConnectionManager;exports.ConversationManager=e.ConversationManager;exports.EventEmitter=e.EventEmitter;exports.MessageStore=e.MessageStore;exports.SessionAuthAdapter=e.SessionAuthAdapter;exports.SsoExchangeAdapter=e.SsoExchangeAdapter;exports.TiledeskTransport=e.TiledeskTransport;exports.TokenDiscoveryError=e.TokenDiscoveryError;exports.TokenDiscoveryReader=e.TokenDiscoveryReader;exports.clearPersistedConversationId=e.clearPersistedConversationId;exports.collectSsoCredentials=e.collectSsoCredentials;exports.createFetchUploadAdapter=e.createFetchUploadAdapter;exports.createPresigned3StepUploadAdapter=e.createPresigned3StepUploadAdapter;exports.createTiledeskHistoryAdapter=e.createTiledeskHistoryAdapter;exports.discoverToken=e.discoverToken;exports.extractTiledeskFileEnvelope=e.extractTiledeskFileEnvelope;exports.inferTiledeskRole=e.inferTiledeskRole;exports.isTiledeskSelfEcho=e.isTiledeskSelfEcho;exports.mountFromSlug=e.mountFromSlug;exports.mountTenantWidget=e.mount;exports.parseTiledeskTemplate=e.parseTiledeskTemplate;exports.registerComponents=e.registerComponents;exports.FormBridge=s.FormBridge;exports.mount=l;exports.unmount=d;
|
package/dist/index.d.ts
CHANGED
|
@@ -2049,6 +2049,21 @@ export declare interface WidgetConfigDescriptor {
|
|
|
2049
2049
|
/** Absolute base URL for tenant API calls. No trailing slash. */
|
|
2050
2050
|
baseUrl?: string;
|
|
2051
2051
|
};
|
|
2052
|
+
/**
|
|
2053
|
+
* Razorpay Checkout config consumed by the `payment_link` IIFE template.
|
|
2054
|
+
* `keyId` is the publishable key (safe to expose). `preferredBanksUrl`
|
|
2055
|
+
* (optional) is a tenant endpoint that returns the list of allowed
|
|
2056
|
+
* netbanking codes for an order, called as `GET <url>?orderId=<id>` with
|
|
2057
|
+
* the chat JWT as Bearer; when present the Razorpay UI is restricted to
|
|
2058
|
+
* netbanking with those banks.
|
|
2059
|
+
*/
|
|
2060
|
+
razorpay?: {
|
|
2061
|
+
keyId?: string;
|
|
2062
|
+
/** Merchant name shown on the Checkout sheet. Defaults to descriptor.title. */
|
|
2063
|
+
name?: string;
|
|
2064
|
+
/** Endpoint template; `{orderId}` is substituted, else appended as `?orderId=`. */
|
|
2065
|
+
preferredBanksUrl?: string;
|
|
2066
|
+
};
|
|
2052
2067
|
/**
|
|
2053
2068
|
* Unified slot map. Supersedes `templates` and the bespoke
|
|
2054
2069
|
* `linkHandlers[].render` mechanism. Each key is a slot id that some
|
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { r as o } from "./MountTenant-
|
|
2
|
-
import { A as u, a as m, b as k, c as g, d as h, e as A, f as C, g as T, h as b, i as v, j as f, k as y, C as S, l as w, m as E, E as M, M as x, S as B, n as F, T as U, o as D, p as I, q as j, s as q, t as H, u as P, v as R, w as W, x as z, y as K, z as L, B as O, D as G, F as J } from "./MountTenant-
|
|
1
|
+
import { r as o } from "./MountTenant-DA_soQf0.mjs";
|
|
2
|
+
import { A as u, a as m, b as k, c as g, d as h, e as A, f as C, g as T, h as b, i as v, j as f, k as y, C as S, l as w, m as E, E as M, M as x, S as B, n as F, T as U, o as D, p as I, q as j, s as q, t as H, u as P, v as R, w as W, x as z, y as K, z as L, B as O, D as G, F as J } from "./MountTenant-DA_soQf0.mjs";
|
|
3
3
|
import { FormBridge as Q } from "./headless.mjs";
|
|
4
4
|
function l(e) {
|
|
5
5
|
o();
|
package/dist/ui.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("./MountTenant-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("./MountTenant-CbQMTk-J.cjs");exports.AikaaraChat=a.AikaaraChat;exports.AikaaraChatBubble=a.AikaaraChatBubble;exports.AikaaraChatHeader=a.AikaaraChatHeader;exports.AikaaraChatInput=a.AikaaraChatInput;exports.AikaaraChatWidget=a.AikaaraChatWidget;exports.AikaaraComparePlans=a.AikaaraComparePlans;exports.AikaaraErrorBanner=a.AikaaraErrorBanner;exports.AikaaraLinkModal=a.AikaaraLinkModal;exports.AikaaraMessageBubble=a.AikaaraMessageBubble;exports.AikaaraMessageList=a.AikaaraMessageList;exports.AikaaraModalAction=a.AikaaraModalAction;exports.AikaaraOptionList=a.AikaaraOptionList;exports.AikaaraStreamingMessage=a.AikaaraStreamingMessage;exports.AikaaraSubmitAction=a.AikaaraSubmitAction;exports.AikaaraSystemPill=a.AikaaraSystemPill;exports.AikaaraTemplateRenderer=a.AikaaraTemplateRenderer;exports.AikaaraTypingIndicator=a.AikaaraTypingIndicator;exports.registerComponents=a.registerComponents;
|
package/dist/ui.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { G as i, a as s, c as e, d as t, e as A, H as k, f as n, I as o, g, h as l, J as d, K as m, i as p, L as C, N as h, O as b, j as M, r as c } from "./MountTenant-
|
|
1
|
+
import { G as i, a as s, c as e, d as t, e as A, H as k, f as n, I as o, g, h as l, J as d, K as m, i as p, L as C, N as h, O as b, j as M, r as c } from "./MountTenant-DA_soQf0.mjs";
|
|
2
2
|
export {
|
|
3
3
|
i as AikaaraChat,
|
|
4
4
|
s as AikaaraChatBubble,
|