@eka-care/medassist-widget-embed 0.2.119 → 0.2.120-dev.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +43 -0
- package/dist/eka-agents.html +4 -4
- package/dist/iframe.js +1 -1
- package/dist/index.d.ts +52 -0
- package/dist/index.js +11 -9
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -234,6 +234,49 @@ window.addEventListener("eka-medassist:side-panel-push", (e) => {
|
|
|
234
234
|
});
|
|
235
235
|
```
|
|
236
236
|
|
|
237
|
+
## Client tools
|
|
238
|
+
|
|
239
|
+
Give the agent functions that run **in your page** (read or edit your app's state). The page declares them; the backend tells the LLM they exist; when the LLM calls one, the SDK runs your `run` and sends the result back. Declarations follow MCP's `Tool` shape; only `name / description / inputSchema / outputSchema / annotations` leave the page — `run` never does.
|
|
240
|
+
|
|
241
|
+
```js
|
|
242
|
+
EkaMedAssist.init({
|
|
243
|
+
agentId: "<agent-id>",
|
|
244
|
+
tools: [
|
|
245
|
+
{
|
|
246
|
+
name: "read_note",
|
|
247
|
+
description: "Read the note the user has open.",
|
|
248
|
+
inputSchema: { type: "object", properties: { section_keys: { type: "array", items: { type: "string" } } } },
|
|
249
|
+
annotations: { title: "Reading the note", readOnlyHint: true },
|
|
250
|
+
run: async (input, ctx) => {
|
|
251
|
+
ctx.progress({ message: "Collecting sections…" });
|
|
252
|
+
return { sections: getSections(input.section_keys) }; // plain object → structured result
|
|
253
|
+
},
|
|
254
|
+
},
|
|
255
|
+
],
|
|
256
|
+
});
|
|
257
|
+
|
|
258
|
+
// Replace the list at any time (before or after the widget opens):
|
|
259
|
+
EkaMedAssist.registerTools([...]);
|
|
260
|
+
```
|
|
261
|
+
|
|
262
|
+
Rules:
|
|
263
|
+
|
|
264
|
+
- `run` must read live page state at call time — tools are registered once and reused.
|
|
265
|
+
- Return a plain object (becomes `structuredContent`) or a full MCP `CallToolResult`.
|
|
266
|
+
- Report a failure the model should handle by throwing an `Error` with `code` (string) and optional `data` (object); it becomes `{ isError: true, structuredContent: { code, message, ...data } }`.
|
|
267
|
+
- `annotations.title` is the label shown on the reply bubble while the tool runs; `ctx.progress({ message })` updates it live.
|
|
268
|
+
- `ctx.signal` aborts on timeout (`timeoutMs`, default 30 s), server cancel, or session end.
|
|
269
|
+
- Not supported in the iframe embed (functions cannot cross frames).
|
|
270
|
+
- Needs widget `0.2.x` (the React-SDK build). The legacy `0.1.x` widget ignores `tools`.
|
|
271
|
+
|
|
272
|
+
Protocol details: `docs/client-tools-plan.md` in the repo. Demo: `test-client-tools.html`.
|
|
273
|
+
|
|
274
|
+
## Environments
|
|
275
|
+
|
|
276
|
+
The SDK ships with the production backend only. The `environment` attribute / `init({ environment })` is kept for
|
|
277
|
+
backward compatibility but any value other than `production` is ignored; point at another backend with `base-url` /
|
|
278
|
+
`init({ baseUrl })`.
|
|
279
|
+
|
|
237
280
|
## How it works
|
|
238
281
|
|
|
239
282
|
1. **Initial load** – The script registers the custom element `<eka-medassist-widget>`.
|
package/dist/eka-agents.html
CHANGED
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
CORS mode — the browser would download it twice. -->
|
|
19
19
|
<link
|
|
20
20
|
rel="modulepreload"
|
|
21
|
-
href="https://cdn.jsdelivr.net/npm/@eka-care/medassist-widget@0.
|
|
21
|
+
href="https://cdn.jsdelivr.net/npm/@eka-care/medassist-widget@0.2.0-dev.2/dist/medassist-widget.js"
|
|
22
22
|
fetchpriority="high"
|
|
23
23
|
crossorigin
|
|
24
24
|
/>
|
|
@@ -27,14 +27,14 @@
|
|
|
27
27
|
<link
|
|
28
28
|
rel="preload"
|
|
29
29
|
as="style"
|
|
30
|
-
href="https://cdn.jsdelivr.net/npm/@eka-care/medassist-widget@0.
|
|
30
|
+
href="https://cdn.jsdelivr.net/npm/@eka-care/medassist-widget@0.2.0-dev.2/dist/medassist-widget.css"
|
|
31
31
|
onload="this.rel='stylesheet'"
|
|
32
32
|
crossorigin
|
|
33
33
|
/>
|
|
34
34
|
<noscript>
|
|
35
35
|
<link
|
|
36
36
|
rel="stylesheet"
|
|
37
|
-
href="https://cdn.jsdelivr.net/npm/@eka-care/medassist-widget@0.
|
|
37
|
+
href="https://cdn.jsdelivr.net/npm/@eka-care/medassist-widget@0.2.0-dev.2/dist/medassist-widget.css"
|
|
38
38
|
/>
|
|
39
39
|
</noscript>
|
|
40
40
|
|
|
@@ -149,7 +149,7 @@
|
|
|
149
149
|
window.renderMedAssist would never be set. -->
|
|
150
150
|
<script
|
|
151
151
|
type="module"
|
|
152
|
-
src="https://cdn.jsdelivr.net/npm/@eka-care/medassist-widget@0.
|
|
152
|
+
src="https://cdn.jsdelivr.net/npm/@eka-care/medassist-widget@0.2.0-dev.2/dist/medassist-widget.js"
|
|
153
153
|
onload="init()"
|
|
154
154
|
fetchpriority="high"
|
|
155
155
|
crossorigin
|
package/dist/iframe.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";(function(){const $=()=>{if(typeof document=="undefined")return null;const{currentScript:e}=document;if(e instanceof HTMLScriptElement)return e;const
|
|
1
|
+
"use strict";(function(){const $=()=>{if(typeof document=="undefined")return null;const{currentScript:e}=document;if(e instanceof HTMLScriptElement)return e;const n=document.getElementsByTagName("script");return n.length?n[n.length-1]:null},C=e=>{if(e==="production"||e==="development"||e==="staging")return e};function z(e){var n,r;if(!e)return;const t=e.mode==="dark"?"white":e.mode==="light"?"black":void 0;return{...e.background&&{background:e.background},...e.background_img&&{backgroundImage:e.background_img},...e.accent&&{primary:e.accent},...t&&{textColor:t},...e.mode&&{mode:e.mode},...e.header_tinted!==void 0&&{headerTinted:e.header_tinted},...e.title_img&&{titleImg:e.title_img},...e.tagline&&{tagline:e.tagline},...e.consent_content&&{consentContent:e.consent_content},...((n=e.tips)===null||n===void 0?void 0:n.length)&&{tips:e.tips},...((r=e.banner)===null||r===void 0?void 0:r.trim())&&{banner:e.banner},...e.feature!==void 0&&{feature:e.feature}}}function b(e){if(!(!e||typeof document=="undefined"))try{const n=document.createElement("link");n.rel="preload",n.as="image",n.href=e,document.head.appendChild(n)}catch{const n=new Image;n.src=e}}async function F(e,n,r){var t;try{return await v(),await((t=window.fetchAgentConfig)===null||t===void 0?void 0:t.call(window,{agentId:n,serverUrl:e,environment:r,channel:"web"}))}catch{return}}const S="https://cdn.jsdelivr.net/npm/@eka-care/medassist-widget@0.2.0-dev.2/dist/",s=$(),U=(()=>{if(!s)return"";try{return new URL(".",s.src||window.location.href).href}catch{return""}})(),u=(()=>{if(!s)return S;const e=s.dataset.widgetAssets;if(e==="local")return`${U}src/`;if(e&&e.length>0)try{return new URL(e,U).href}catch{return e.endsWith("/")?e:`${e}/`}return S})(),a=`${u}medassist-widget.js`,g=`${u}medassist-widget.css`;let f=null,m=null;const i=new URLSearchParams(typeof window!="undefined"?window.location.search:""),A=i.get("agentId"),w=i.get("baseUrl")||"https://matrix.eka.care/reloaded";if(typeof document!="undefined"&&document.head){try{const e=new URL(u).origin,n=new URL(w).origin,r=document.createElement("link");if(r.rel="preconnect",r.href=e,r.crossOrigin="anonymous",document.head.appendChild(r),e!==n){const c=document.createElement("link");c.rel="preconnect",c.href=n,c.crossOrigin="anonymous",document.head.appendChild(c)}const t=document.createElement("link");t.rel="modulepreload",t.href=a,document.head.appendChild(t);const d=document.createElement("link");d.rel="preload",d.as="style",d.href=g,document.head.appendChild(d)}catch{}M(),v()}const L=A&&w?F(w,A,C(i.get("environment"))):Promise.resolve(void 0);if(typeof document!="undefined"&&document.head){const e=i.get("theme");if(e)try{const n=JSON.parse(e);n.backgroundImage&&b(n.backgroundImage)}catch{}L.then(n=>{var r;const t=(r=n==null?void 0:n.theme)===null||r===void 0?void 0:r.background_img;t&&b(t)})}const I=async()=>{var e,n,r,t,d,c,h;const P=i.get("agentId");if(!P){console.error("Agent ID is required in URL parameters");return}let p=i.get("title")||"Medi Clinic",y=i.get("iconUrl")||void 0;const x=i.get("context"),G=i.get("baseUrl")||"https://matrix.eka.care/reloaded",O=i.get("auth-token")||void 0;let k=i.get("resize")==="true"?!0:void 0;const J=(e=C(i.get("environment")))!==null&&e!==void 0?e:"production",_=i.get("connectivity"),N=_==="http_stream"||_==="socket"?_:void 0,E=i.get("theme")?(()=>{try{return JSON.parse(i.get("theme")||"{}")}catch{return}})():void 0,q=document.getElementById("root")||document.body;try{const[,,o]=await Promise.all([M(),v(),L]);if(!(window!=null&&window.renderMedAssist)||typeof(window==null?void 0:window.renderMedAssist)!="function")throw new Error("renderMedAssist is not available on window");let l,W,R,B,D=!1;o&&(p=(n=o==null?void 0:o.name)!==null&&n!==void 0?n:p,y=(t=(r=o==null?void 0:o.theme)===null||r===void 0?void 0:r.icon_img)!==null&&t!==void 0?t:y,l=z((d=o==null?void 0:o.theme)!==null&&d!==void 0?d:void 0),W=o==null?void 0:o.allowed,R=o==null?void 0:o.connectivity,B=o==null?void 0:o.initial_message,D=(h=(c=o==null?void 0:o.theme)===null||c===void 0?void 0:c.hide_watermark)!==null&&h!==void 0?h:!1,k=k||(o==null?void 0:o.resize)||void 0);const H={title:p,iconUrl:y,environment:J,connectionType:R||N||"socket",onClose:()=>{window.parent!==window&&window.parent.postMessage({type:"WIDGET_CLOSE"},"*")},context:x?JSON.parse(x):void 0,baseUrl:G,displayMode:"full",allowed:W,showCloseButton:!1,resize:k,initialMessage:B,hideWatermark:D,...O&&{authToken:O},theme:{...l!=null?l:{},...E!=null?E:{}}};window.renderMedAssist(q,P,H)}catch(o){throw console.error("Failed to initialize MedAssist widget",o),o}};async function M(){document.querySelector("link[data-medassist-style='true']")||(m||(m=new Promise((n,r)=>{const t=document.createElement("link");t.rel="stylesheet",t.href=g,t.setAttribute("data-medassist-style","true"),t.onload=()=>{n("")},t.onerror=()=>{r(new Error(`Failed to load ${g}`))},document.head.appendChild(t)})),await m)}function v(){return f||(f=new Promise((e,n)=>{const r=document.querySelector(`script[src="${a}"]`);if(r){if(r.dataset.loaded==="true"){e();return}r.addEventListener("load",()=>e()),r.addEventListener("error",d=>n(d.error||new Error("Unknown script loading error")));return}const t=document.createElement("script");t.src=a,t.type="module",t.async=!0,t.dataset.widget="medassist",t.onload=()=>{t.dataset.loaded="true",e()},t.onerror=d=>{if(d instanceof ErrorEvent&&d.error){n(d.error);return}n(new Error(`Failed to load ${a}`))},document.head.appendChild(t)})),f}if(typeof document!="undefined")if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",I);else try{I()}catch(e){console.error("Failed to initialize MedAssist widget",e)}})();
|
package/dist/index.d.ts
CHANGED
|
@@ -36,6 +36,8 @@ type AgentConfig = {
|
|
|
36
36
|
upfront_consent?: boolean;
|
|
37
37
|
/** Tips shown while the bot works on a reply. Absent or empty -> the widget's built-in tips. */
|
|
38
38
|
tips?: string[];
|
|
39
|
+
/** Short inline markdown shown in a dismissible strip under the widget header. */
|
|
40
|
+
banner?: string;
|
|
39
41
|
/** Feature flag — currently gates the chat-history UI (session drawer + fullscreen sidebar). */
|
|
40
42
|
feature?: boolean;
|
|
41
43
|
/** Floating-widget width in px (desktop "widget" mode only). Clamped by the widget. */
|
|
@@ -69,7 +71,38 @@ type AgentConfig = {
|
|
|
69
71
|
/** Client-side flag set when the user clicks "Don't show again" on the feedback modal. */
|
|
70
72
|
feedback_hidden?: boolean;
|
|
71
73
|
};
|
|
74
|
+
/**
|
|
75
|
+
* Host-page function the LLM may call (MCP `Tool` declaration + `run`).
|
|
76
|
+
* Declared structurally — the loader is built without a bundler and cannot
|
|
77
|
+
* import the SDK. Kept in memory only, never serialised to an attribute.
|
|
78
|
+
*/
|
|
79
|
+
type MedAssistClientTool = {
|
|
80
|
+
name: string;
|
|
81
|
+
description: string;
|
|
82
|
+
inputSchema: Record<string, unknown>;
|
|
83
|
+
outputSchema?: Record<string, unknown>;
|
|
84
|
+
annotations?: {
|
|
85
|
+
title?: string;
|
|
86
|
+
readOnlyHint?: boolean;
|
|
87
|
+
destructiveHint?: boolean;
|
|
88
|
+
idempotentHint?: boolean;
|
|
89
|
+
};
|
|
90
|
+
run: (input: Record<string, unknown>, ctx: {
|
|
91
|
+
requestId: string | number;
|
|
92
|
+
messageId?: string;
|
|
93
|
+
signal: AbortSignal;
|
|
94
|
+
progress: (update: {
|
|
95
|
+
message: string;
|
|
96
|
+
progress?: number;
|
|
97
|
+
total?: number;
|
|
98
|
+
}) => void;
|
|
99
|
+
}) => unknown;
|
|
100
|
+
parse?: (input: unknown) => Record<string, unknown>;
|
|
101
|
+
timeoutMs?: number;
|
|
102
|
+
};
|
|
72
103
|
type MedAssistInitConfig = {
|
|
104
|
+
/** Client tools the LLM may call; replace later with `EkaMedAssist.registerTools()`. Not available in iframe mode. */
|
|
105
|
+
tools?: MedAssistClientTool[];
|
|
73
106
|
/** Partner JWT/JWE — the only host-supplied credential; absent -> guest. */
|
|
74
107
|
authToken?: string;
|
|
75
108
|
agentId?: string;
|
|
@@ -102,6 +135,7 @@ type MedAssistInitConfig = {
|
|
|
102
135
|
consentContent?: string | string[];
|
|
103
136
|
upfrontConsent?: boolean;
|
|
104
137
|
tips?: string[];
|
|
138
|
+
banner?: string;
|
|
105
139
|
feature?: boolean;
|
|
106
140
|
/** Floating-widget size (px) from the agent config. Overridden by the `override…` keys below. */
|
|
107
141
|
widgetWidth?: number;
|
|
@@ -125,6 +159,13 @@ declare function preloadImage(url: string): void;
|
|
|
125
159
|
type SynapseChannel = "widget" | "web" | "side_panel";
|
|
126
160
|
declare function channelFromDisplayMode(displayMode: string | null | undefined): SynapseChannel;
|
|
127
161
|
declare function prefersReducedMotion(): boolean;
|
|
162
|
+
/**
|
|
163
|
+
* Same rule as the widget's useIsMobile (packages/widget/src/hooks/useResolvedMode.ts),
|
|
164
|
+
* so the loader and the widget agree on "mobile": narrow or touch viewport, or a mobile UA.
|
|
165
|
+
*/
|
|
166
|
+
declare const MOBILE_QUERY = "(max-width: 768px), (pointer: coarse)";
|
|
167
|
+
declare const MOBILE_UA_REGEX: RegExp;
|
|
168
|
+
declare function isMobileViewport(): boolean;
|
|
128
169
|
declare function nextFrame(): Promise<void>;
|
|
129
170
|
/**
|
|
130
171
|
* Icon colour on the accent: near-black on light accents, near-white on dark
|
|
@@ -229,6 +270,8 @@ type SidePanelPushDetail = {
|
|
|
229
270
|
interface EkaMedAssistWindow extends Window {
|
|
230
271
|
EkaMedAssist?: {
|
|
231
272
|
init: (config: MedAssistInitConfig) => void;
|
|
273
|
+
/** Replace the client tools — before or after the widget renders. */
|
|
274
|
+
registerTools: (tools: MedAssistClientTool[]) => void;
|
|
232
275
|
onClose?: () => void;
|
|
233
276
|
/**
|
|
234
277
|
* Side-panel push mode only. Called with `true` when the panel opens and
|
|
@@ -241,6 +284,8 @@ interface EkaMedAssistWindow extends Window {
|
|
|
241
284
|
};
|
|
242
285
|
__ekaMedAssistConfig__?: MedAssistInitConfig;
|
|
243
286
|
renderMedAssist?: (container: HTMLElement, agentId: string, config: MedAssistInitConfig) => ReactRoot;
|
|
287
|
+
/** Exposed by the widget bundle once loaded; swaps tools in the running SDK. */
|
|
288
|
+
registerMedAssistTools?: (tools: MedAssistClientTool[]) => void;
|
|
244
289
|
}
|
|
245
290
|
declare const globalMedAssistConfig: MedAssistInitConfig;
|
|
246
291
|
declare const getWidgetElement: () => HTMLElement | null;
|
|
@@ -311,6 +356,13 @@ declare class MedAssistWidgetLoader extends HTMLElement {
|
|
|
311
356
|
* - "open" → both hidden (widget is mounted)
|
|
312
357
|
*/
|
|
313
358
|
private updateLauncherView;
|
|
359
|
+
/**
|
|
360
|
+
* Whether a tap on the chatbox opens the widget straight away instead of
|
|
361
|
+
* waiting for a typed message: always on mobile (the widget opens full
|
|
362
|
+
* screen there, so typing into the small bar first is a wasted step), and
|
|
363
|
+
* on any device once a chat is in progress ("Continue your chat…").
|
|
364
|
+
*/
|
|
365
|
+
private chatboxOpensOnTap;
|
|
314
366
|
/**
|
|
315
367
|
* `x-channel` for every request this loader makes, from how the widget is set
|
|
316
368
|
* to open. The attribute wins; `init({ displayMode })` covers calls made
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";const getCurrentScript=()=>{if(typeof document=="undefined")return console.error("document is not defined"),null;const{currentScript:s}=document;if(s instanceof HTMLScriptElement)return s;const t=Array.from(document.getElementsByTagName("script")),e=t.find(o=>o.hasAttribute("data-widget-assets"));if(e)return e;const i=t.filter(o=>/(^|\/)index\.js(\?.*)?$/.test(o.src));return i.length?i[i.length-1]:t.length?t[t.length-1]:null},getEnvironment=s=>{if(s==="production"||s==="development"||s==="staging")return s},scriptEl=getCurrentScript(),DEFAULT_WIDGET_ASSET_BASE=(()=>{var s;return!((s=scriptEl==null?void 0:scriptEl.src)===null||s===void 0)&&s.includes("@dev"),"https://cdn.jsdelivr.net/npm/@eka-care/medassist-widget@0.1.141/dist/"})();var FeedbackTypeEnum;(function(s){s.DEFAULT="default",s.NPS="nps"})(FeedbackTypeEnum||(FeedbackTypeEnum={}));function mapAgentConfigThemeToWidgetTheme(s){var t;if(!s)return;const e=s.mode==="dark"?"white":s.mode==="light"?"black":void 0;return{...s.background_img&&{backgroundImage:s.background_img},...s.accent&&{primary:s.accent},...e&&{textColor:e},...s.mode&&{mode:s.mode},...s.header_tinted!==void 0&&{headerTinted:s.header_tinted},...s.title_img&&{titleImg:s.title_img},...s.tagline&&{tagline:s.tagline},...s.hide_watermark&&{hideWatermark:s.hide_watermark},...s.explicit_disclaimer&&{explicitDisclaimer:s.explicit_disclaimer},...s.consent_content&&{consentContent:s.consent_content},...s.upfront_consent&&{upfrontConsent:s.upfront_consent},...((t=s.tips)===null||t===void 0?void 0:t.length)&&{tips:s.tips},...s.feature!==void 0&&{feature:s.feature},...typeof s.widget_width=="number"&&{widgetWidth:s.widget_width},...typeof s.widget_height=="number"&&{widgetHeight:s.widget_height}}}function preloadImage(s){if(!(!s||typeof document=="undefined"))try{const t=document.createElement("link");t.rel="preload",t.as="image",t.href=s,document.head.appendChild(t)}catch{const t=new Image;t.src=s}}function channelFromDisplayMode(s){return s==="full"?"web":s==="side_panel"?"side_panel":"widget"}function prefersReducedMotion(){var s;return typeof window!="undefined"&&!!(!((s=window.matchMedia)===null||s===void 0)&&s.call(window,"(prefers-reduced-motion: reduce)").matches)}function nextFrame(){return new Promise(s=>requestAnimationFrame(()=>s()))}function colorOnAccent(s){const t=s.trim().replace("#",""),e=t.length===3?t.split("").map(n=>n+n).join(""):t;if(!/^[0-9a-f]{6}$/i.test(e))return"#fafafa";const i=[0,2,4].map(n=>parseInt(e.slice(n,n+2),16)/255);return(Math.max(...i)+Math.min(...i))/2>.5?"#171717":"#fafafa"}function normalizeDisplayMode(s){return s==="full"?"full":s==="side_panel"?"side_panel":"widget"}const NUDGE_STORAGE_KEY="eka-medassist-nudges",AGENT_CONFIG_CACHE_KEY="eka-medassist-agent-config";function readAgentConfigCache(s){try{const t=localStorage.getItem(AGENT_CONFIG_CACHE_KEY);return(t?JSON.parse(t):{})[s]}catch{return}}function writeAgentConfigCache(s,t){try{const e=localStorage.getItem(AGENT_CONFIG_CACHE_KEY),i=e?JSON.parse(e):{};i[s]={...i[s]||{},...t},localStorage.setItem(AGENT_CONFIG_CACHE_KEY,JSON.stringify(i))}catch{}}function getNudgeStore(){try{const s=localStorage.getItem(NUDGE_STORAGE_KEY);return s?JSON.parse(s):{}}catch{return{}}}function setNudgeStore(s){try{localStorage.setItem(NUDGE_STORAGE_KEY,JSON.stringify(s))}catch{}}function normalizePath(s){let t=s.replace(/\/+$/,"");return t.startsWith("/")||(t="/"+t),t||"/"}function getNudgePathCandidates(s){const t=s.split("/").filter(Boolean),e=[];for(let i=t.length;i>=0;i--)e.push(i===0?"/":"/"+t.slice(0,i).join("/"));return e}function findCachedNudgeForCandidates(s,t,e){const o=getNudgeStore()[s];if(!o)return null;const n=t.host,a=o[n];if(!a)return null;for(const d of e){if(a[d]!==void 0)return{domain:n,path:d,data:a[d]};const r=d==="/"?"/*":d+"/*";if(a[r]!==void 0)return{domain:n,path:r,data:a[r]}}return null}function findFreshCachedNudge(s,t,e){const i=findCachedNudgeForCandidates(s,t,e);if(!i)return null;const o=Math.floor(Date.now()/1e3);return i.data.expiry<=o?(clearNudgeForPath(s,i.domain,i.path),null):i}function clearNudgeForPath(s,t,e){const i=getNudgeStore(),o=i[s];!o||!o[t]||(delete o[t][e],setNudgeStore(i))}function storeNudgeResponse(s,t,e){var i,o,n,a;const d=(i=t==null?void 0:t.url_pattern)===null||i===void 0?void 0:i.domain,r=(o=t==null?void 0:t.url_pattern)===null||o===void 0?void 0:o.path;if(!(!((n=t.nudges)===null||n===void 0)&&n.length)||!t.expiry||!d||!r)return;const l=getNudgeStore();l[s]||(l[s]={}),l[s][d]||(l[s][d]={});const c={nudges:t.nudges,expiry:t.expiry,delay:(a=t.delay)!==null&&a!==void 0?a:5};l[s][d][r]=c,e&&e!==r&&(l[s][d][e]=c),setNudgeStore(l)}const NUDGE_COOKIE_PREFIX="eka-nudge";function setNudgeCookie(s,t){const e=new Date(Date.now()+864e5).toUTCString();document.cookie=`${NUDGE_COOKIE_PREFIX}-${s}=${t}; expires=${e}; path=/; SameSite=Lax`}function getNudgeCookie(s){const t=document.cookie.split(";").map(i=>i.trim()).find(i=>i.startsWith(`${NUDGE_COOKIE_PREFIX}-${s}=`));if(!t)return null;const e=t.split("=")[1];return e==="open"||e==="closed"?e:null}const WIDGET_STORE_KEY_PREFIX="med-assist-store-";function readPersistedSessToken(s){var t,e;try{const i=sessionStorage.getItem(`${WIDGET_STORE_KEY_PREFIX}${s}`),o=i?(e=(t=JSON.parse(i))===null||t===void 0?void 0:t.state)===null||e===void 0?void 0:e.sessToken:void 0;return typeof o=="string"&&o?o:void 0}catch{return}}async function fetchNudgeData(s,t,e,i="widget"){const o=`${e}/med-assist/user-nudge`,n=[];typeof document!="undefined"&&document.querySelectorAll("meta").forEach(a=>{var d,r,l;const c=(d=a.getAttribute("name"))!==null&&d!==void 0?d:void 0,h=(r=a.getAttribute("property"))!==null&&r!==void 0?r:void 0,m=(l=a.getAttribute("content"))!==null&&l!==void 0?l:void 0;(c||h)&&n.push({name:c,property:h,content:m})});try{const a=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json","x-agent-id":s,"x-channel":i,referer:typeof window!="undefined"?window.location.href:"",Authorization:`Bearer ${t}`},body:JSON.stringify({meta_tags:n,url:typeof window!="undefined"?window.location.href:""})});return a.ok?await a.json():void 0}catch{return}}function withTrailingEllipsis(s){const t=s.trim();return/[…?!]$/.test(t)?t:`${t.replace(/\.+$/,"")}\u2026`}const SIDE_PANEL_PUSH_EVENT="eka-medassist:side-panel-push",globalMedAssistConfig={},getWidgetElement=()=>typeof document=="undefined"?null:document.querySelector("eka-medassist-widget");if(typeof window!="undefined"){const s=window;s.__ekaMedAssistConfig__=globalMedAssistConfig,s.EkaMedAssist={init(t){var e,i,o;Object.assign(globalMedAssistConfig,t);const n=getWidgetElement();if(n){if(t.agentId&&n.setAttribute("agent-id",t.agentId),t.authToken&&n.setAttribute("auth-token",t.authToken),t.title&&n.setAttribute("title",t.title),t.iconUrl&&n.setAttribute("icon-url",t.iconUrl),t.baseUrl&&n.setAttribute("base-url",t.baseUrl),t.resize!==void 0&&n.setAttribute("resize",String(t.resize)),(t.displayMode==="full"||t.displayMode==="widget"||t.displayMode==="side_panel")&&n.setAttribute("display-mode",t.displayMode),t.sidePanelMode&&n.setAttribute("side-panel-mode",t.sidePanelMode),t.sidePanelWidth!==void 0&&n.setAttribute("side-panel-width",String(t.sidePanelWidth)),t.side&&n.setAttribute("side",t.side),t.context)try{n.setAttribute("context",JSON.stringify(t.context))}catch{console.warn("Failed to stringify context passed to init")}typeof t.customLauncherStyles=="string"&&n.setAttribute("custom-launcher-styles",t.customLauncherStyles),t.launcherType&&n.setAttribute("launcher-type",t.launcherType),t.redirectUrl&&n.setAttribute("redirect-url",t.redirectUrl),!((e=t.theme)===null||e===void 0)&&e.backgroundImage&&preloadImage(t.theme.backgroundImage),(o=(i=n).openFromBridge)===null||o===void 0||o.call(i)}}}}const scriptBaseUrl=(()=>{if(!scriptEl)return"";try{return new URL(".",scriptEl.src||window.location.href).href}catch{return""}})(),widgetAssetBaseUrl=(()=>{if(!scriptEl)return DEFAULT_WIDGET_ASSET_BASE;const s=scriptEl.dataset.widgetAssets;if(s==="local")return`${scriptBaseUrl}src/`;if(s&&s.length>0)try{return new URL(s,scriptBaseUrl).href}catch{return s.endsWith("/")?s:`${s}/`}return DEFAULT_WIDGET_ASSET_BASE})(),WIDGET_JS_URL=`${widgetAssetBaseUrl}medassist-widget.js`,WIDGET_CSS_URL=`${widgetAssetBaseUrl}medassist-widget.css`;let widgetModulePromise=null,widgetCssTextPromise=null;function getWidgetCssTextPromise(){return widgetCssTextPromise||(widgetCssTextPromise=fetch(WIDGET_CSS_URL).then(s=>{if(!s.ok)throw new Error(`Unable to fetch widget styles from ${WIDGET_CSS_URL}`);return s.text()})),widgetCssTextPromise}class MedAssistWidgetLoader extends HTMLElement{setLauncherState(t){this.launcherState=t,this.updateLauncherView()}getLauncherType(){var t,e;if(this.displayMode!=="widget")return"button";const i=(typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{},o=this.getAgentId();return(this.getAttribute("launcher-type")||i.launcherType||(o?(e=(t=readAgentConfigCache(o))===null||t===void 0?void 0:t.theme)===null||e===void 0?void 0:e.launcher_type:void 0))==="chatbox"?"chatbox":"button"}isChatboxShown(){return this.getLauncherType()==="chatbox"}updateLauncherView(){const t=this.shadowRoot;if(!t)return;this.applyCustomLauncherStyles();const e=this.launcherState,i=this.isChatboxShown(),o=t.getElementById("medassist-open-btn");if(o){const a=e==="loading"&&!i;o.classList.toggle("loading",a),o.classList.toggle("hidden",e==="open"||i),a?o.setAttribute("aria-busy","true"):o.removeAttribute("aria-busy")}const n=t.getElementById("medassist-chatbox");if(n){this.applyChatboxTheme(n);const a=e==="loading"&&i;n.classList.toggle("hidden",e==="open"||!i),n.classList.toggle("sending",a);const d=this.chatStarted&&e==="idle";n.classList.toggle("continuing",d),this.syncChatboxPlaceholder(),this.syncChatboxPulse();const r=t.getElementById("medassist-chatbox-input");if(r){r.readOnly=a||d,e==="open"&&(r.value="",this.autosizeChatbox());const l=n.querySelector(".medassist-chatbox-send");l&&(l.disabled=!r.value.trim())}}}getChannel(){const t=this.getAttribute("display-mode");if(t)return channelFromDisplayMode(t);const e=typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0;return channelFromDisplayMode(e==null?void 0:e.displayMode)}getAgentConfig(){var t;if(!this.agentConfigPromise){const e=(typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{},i=e.baseUrl||this.getAttribute("base-url")||"https://matrix.eka.care/reloaded",o=e.agentId||this.getAttribute("agent-id")||"";if(!o)return Promise.resolve(void 0);const n=(t=getEnvironment(this.getAttribute("environment")))!==null&&t!==void 0?t:"production";this.agentConfigPromise=this.loadWidgetModule().then(a=>{var d;return(d=a.fetchAgentConfig)===null||d===void 0?void 0:d.call(a,{agentId:o,serverUrl:i,environment:n,channel:this.getChannel()})}).catch(()=>{this.agentConfigPromise=null})}return this.agentConfigPromise}constructor(){super(),this.hostPushStyleEl=null,this.hostPushState=null,this.reactRoot=null,this.agentConfigPromise=null,this.loading=!1,this.chatStarted=!1,this.placeholderTimer=null,this.placeholderIndex=0,this.launcherState="idle",this.authPrefetchPromise=null,this.launcherRenderSeq=0,this.attachShadow({mode:"open"}),this.widgetLoaded=!1,this.displayMode=normalizeDisplayMode(this.getAttribute("display-mode")),this.setupAuthExpirationListener()}static get observedAttributes(){return["icon-url","display-mode","custom-launcher-styles","redirect-url","side-panel-mode","side-panel-width","side","override-widget-width","override-widget-height","launcher-type"]}connectedCallback(){this.displayMode==="full"?(this.initializeFullMode(),this.loadAndRender().catch(t=>{console.error("Failed to load MedAssist widget in full mode",t)})):(this.renderLauncher(),this.scheduleIdle(()=>{this.preloadWidgetAssets(),this.prefetchAuthTokens(),this.initNudge()}))}disconnectedCallback(){var t,e,i,o,n;this.placeholderTimer&&clearInterval(this.placeholderTimer),this.placeholderTimer=null,(t=this.reactRoot)===null||t===void 0||t.unmount(),this.reactRoot=null,(e=document.body)===null||e===void 0||e.classList.remove("eka-medassist-pushed"),(i=document.documentElement)===null||i===void 0||i.style.removeProperty("--eka-medassist-panel-width"),(o=document.documentElement)===null||o===void 0||o.style.removeProperty("--eka-medassist-panel-side"),(n=this.hostPushStyleEl)===null||n===void 0||n.remove(),this.hostPushStyleEl=null,this.hostPushState=null}applyHostPush(t,e,i){var o;if(typeof document=="undefined")return;const n=t?{width:e,side:i}:null,a=this.hostPushState;if(a===n||a&&n&&a.width===n.width&&a.side===n.side)return;this.hostPushState=n,this.hostPushStyleEl||(this.hostPushStyleEl=document.createElement("style"),this.hostPushStyleEl.setAttribute("data-medassist-side-panel-push","true"),document.head.appendChild(this.hostPushStyleEl));const d=i==="left"?"margin-left":"margin-right";this.hostPushStyleEl.textContent=`
|
|
1
|
+
"use strict";const getCurrentScript=()=>{if(typeof document=="undefined")return console.error("document is not defined"),null;const{currentScript:n}=document;if(n instanceof HTMLScriptElement)return n;const t=Array.from(document.getElementsByTagName("script")),e=t.find(o=>o.hasAttribute("data-widget-assets"));if(e)return e;const i=t.filter(o=>/(^|\/)index\.js(\?.*)?$/.test(o.src));return i.length?i[i.length-1]:t.length?t[t.length-1]:null},getEnvironment=n=>{if(n==="production"||n==="development"||n==="staging")return n},scriptEl=getCurrentScript(),DEFAULT_WIDGET_ASSET_BASE=(()=>{var n;return!((n=scriptEl==null?void 0:scriptEl.src)===null||n===void 0)&&n.includes("@dev"),"https://cdn.jsdelivr.net/npm/@eka-care/medassist-widget@0.2.0-dev.2/dist/"})();var FeedbackTypeEnum;(function(n){n.DEFAULT="default",n.NPS="nps"})(FeedbackTypeEnum||(FeedbackTypeEnum={}));function mapAgentConfigThemeToWidgetTheme(n){var t,e;if(!n)return;const i=n.mode==="dark"?"white":n.mode==="light"?"black":void 0;return{...n.background_img&&{backgroundImage:n.background_img},...n.accent&&{primary:n.accent},...i&&{textColor:i},...n.mode&&{mode:n.mode},...n.header_tinted!==void 0&&{headerTinted:n.header_tinted},...n.title_img&&{titleImg:n.title_img},...n.tagline&&{tagline:n.tagline},...n.hide_watermark&&{hideWatermark:n.hide_watermark},...n.explicit_disclaimer&&{explicitDisclaimer:n.explicit_disclaimer},...n.consent_content&&{consentContent:n.consent_content},...n.upfront_consent&&{upfrontConsent:n.upfront_consent},...((t=n.tips)===null||t===void 0?void 0:t.length)&&{tips:n.tips},...((e=n.banner)===null||e===void 0?void 0:e.trim())&&{banner:n.banner},...n.feature!==void 0&&{feature:n.feature},...typeof n.widget_width=="number"&&{widgetWidth:n.widget_width},...typeof n.widget_height=="number"&&{widgetHeight:n.widget_height}}}function preloadImage(n){if(!(!n||typeof document=="undefined"))try{const t=document.createElement("link");t.rel="preload",t.as="image",t.href=n,document.head.appendChild(t)}catch{const t=new Image;t.src=n}}function channelFromDisplayMode(n){return n==="full"?"web":n==="side_panel"?"side_panel":"widget"}function prefersReducedMotion(){var n;return typeof window!="undefined"&&!!(!((n=window.matchMedia)===null||n===void 0)&&n.call(window,"(prefers-reduced-motion: reduce)").matches)}const MOBILE_QUERY="(max-width: 768px), (pointer: coarse)",MOBILE_UA_REGEX=/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i;function isMobileViewport(){var n,t,e;return typeof window=="undefined"?!1:!!(!((t=(n=window.matchMedia)===null||n===void 0?void 0:n.call(window,MOBILE_QUERY))===null||t===void 0)&&t.matches)||MOBILE_UA_REGEX.test((e=navigator==null?void 0:navigator.userAgent)!==null&&e!==void 0?e:"")}function nextFrame(){return new Promise(n=>requestAnimationFrame(()=>n()))}function colorOnAccent(n){const t=n.trim().replace("#",""),e=t.length===3?t.split("").map(s=>s+s).join(""):t;if(!/^[0-9a-f]{6}$/i.test(e))return"#fafafa";const i=[0,2,4].map(s=>parseInt(e.slice(s,s+2),16)/255);return(Math.max(...i)+Math.min(...i))/2>.5?"#171717":"#fafafa"}function normalizeDisplayMode(n){return n==="full"?"full":n==="side_panel"?"side_panel":"widget"}const NUDGE_STORAGE_KEY="eka-medassist-nudges",AGENT_CONFIG_CACHE_KEY="eka-medassist-agent-config";function readAgentConfigCache(n){try{const t=localStorage.getItem(AGENT_CONFIG_CACHE_KEY);return(t?JSON.parse(t):{})[n]}catch{return}}function writeAgentConfigCache(n,t){try{const e=localStorage.getItem(AGENT_CONFIG_CACHE_KEY),i=e?JSON.parse(e):{};i[n]={...i[n]||{},...t},localStorage.setItem(AGENT_CONFIG_CACHE_KEY,JSON.stringify(i))}catch{}}function getNudgeStore(){try{const n=localStorage.getItem(NUDGE_STORAGE_KEY);return n?JSON.parse(n):{}}catch{return{}}}function setNudgeStore(n){try{localStorage.setItem(NUDGE_STORAGE_KEY,JSON.stringify(n))}catch{}}function normalizePath(n){let t=n.replace(/\/+$/,"");return t.startsWith("/")||(t="/"+t),t||"/"}function getNudgePathCandidates(n){const t=n.split("/").filter(Boolean),e=[];for(let i=t.length;i>=0;i--)e.push(i===0?"/":"/"+t.slice(0,i).join("/"));return e}function findCachedNudgeForCandidates(n,t,e){const o=getNudgeStore()[n];if(!o)return null;const s=t.host,a=o[s];if(!a)return null;for(const d of e){if(a[d]!==void 0)return{domain:s,path:d,data:a[d]};const l=d==="/"?"/*":d+"/*";if(a[l]!==void 0)return{domain:s,path:l,data:a[l]}}return null}function findFreshCachedNudge(n,t,e){const i=findCachedNudgeForCandidates(n,t,e);if(!i)return null;const o=Math.floor(Date.now()/1e3);return i.data.expiry<=o?(clearNudgeForPath(n,i.domain,i.path),null):i}function clearNudgeForPath(n,t,e){const i=getNudgeStore(),o=i[n];!o||!o[t]||(delete o[t][e],setNudgeStore(i))}function storeNudgeResponse(n,t,e){var i,o,s,a;const d=(i=t==null?void 0:t.url_pattern)===null||i===void 0?void 0:i.domain,l=(o=t==null?void 0:t.url_pattern)===null||o===void 0?void 0:o.path;if(!(!((s=t.nudges)===null||s===void 0)&&s.length)||!t.expiry||!d||!l)return;const r=getNudgeStore();r[n]||(r[n]={}),r[n][d]||(r[n][d]={});const c={nudges:t.nudges,expiry:t.expiry,delay:(a=t.delay)!==null&&a!==void 0?a:5};r[n][d][l]=c,e&&e!==l&&(r[n][d][e]=c),setNudgeStore(r)}const NUDGE_COOKIE_PREFIX="eka-nudge";function setNudgeCookie(n,t){const e=new Date(Date.now()+864e5).toUTCString();document.cookie=`${NUDGE_COOKIE_PREFIX}-${n}=${t}; expires=${e}; path=/; SameSite=Lax`}function getNudgeCookie(n){const t=document.cookie.split(";").map(i=>i.trim()).find(i=>i.startsWith(`${NUDGE_COOKIE_PREFIX}-${n}=`));if(!t)return null;const e=t.split("=")[1];return e==="open"||e==="closed"?e:null}const WIDGET_STORE_KEY_PREFIX="med-assist-store-";function readPersistedSessToken(n){var t,e;try{const i=sessionStorage.getItem(`${WIDGET_STORE_KEY_PREFIX}${n}`),o=i?(e=(t=JSON.parse(i))===null||t===void 0?void 0:t.state)===null||e===void 0?void 0:e.sessToken:void 0;return typeof o=="string"&&o?o:void 0}catch{return}}async function fetchNudgeData(n,t,e,i="widget"){const o=`${e}/med-assist/user-nudge`,s=[];typeof document!="undefined"&&document.querySelectorAll("meta").forEach(a=>{var d,l,r;const c=(d=a.getAttribute("name"))!==null&&d!==void 0?d:void 0,u=(l=a.getAttribute("property"))!==null&&l!==void 0?l:void 0,m=(r=a.getAttribute("content"))!==null&&r!==void 0?r:void 0;(c||u)&&s.push({name:c,property:u,content:m})});try{const a=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json","x-agent-id":n,"x-channel":i,referer:typeof window!="undefined"?window.location.href:"",Authorization:`Bearer ${t}`},body:JSON.stringify({meta_tags:s,url:typeof window!="undefined"?window.location.href:""})});return a.ok?await a.json():void 0}catch{return}}function withTrailingEllipsis(n){const t=n.trim();return/[…?!]$/.test(t)?t:`${t.replace(/\.+$/,"")}\u2026`}const SIDE_PANEL_PUSH_EVENT="eka-medassist:side-panel-push",globalMedAssistConfig={},getWidgetElement=()=>typeof document=="undefined"?null:document.querySelector("eka-medassist-widget");if(typeof window!="undefined"){const n=window;n.__ekaMedAssistConfig__=globalMedAssistConfig,n.EkaMedAssist={registerTools(t){var e;globalMedAssistConfig.tools=t,(e=n.registerMedAssistTools)===null||e===void 0||e.call(n,t)},init(t){var e,i,o,s;Object.assign(globalMedAssistConfig,t),t.tools&&((e=n.registerMedAssistTools)===null||e===void 0||e.call(n,t.tools));const a=getWidgetElement();if(a){if(t.agentId&&a.setAttribute("agent-id",t.agentId),t.authToken&&a.setAttribute("auth-token",t.authToken),t.title&&a.setAttribute("title",t.title),t.iconUrl&&a.setAttribute("icon-url",t.iconUrl),t.baseUrl&&a.setAttribute("base-url",t.baseUrl),t.resize!==void 0&&a.setAttribute("resize",String(t.resize)),(t.displayMode==="full"||t.displayMode==="widget"||t.displayMode==="side_panel")&&a.setAttribute("display-mode",t.displayMode),t.sidePanelMode&&a.setAttribute("side-panel-mode",t.sidePanelMode),t.sidePanelWidth!==void 0&&a.setAttribute("side-panel-width",String(t.sidePanelWidth)),t.side&&a.setAttribute("side",t.side),t.context)try{a.setAttribute("context",JSON.stringify(t.context))}catch{console.warn("Failed to stringify context passed to init")}typeof t.customLauncherStyles=="string"&&a.setAttribute("custom-launcher-styles",t.customLauncherStyles),t.launcherType&&a.setAttribute("launcher-type",t.launcherType),t.redirectUrl&&a.setAttribute("redirect-url",t.redirectUrl),!((i=t.theme)===null||i===void 0)&&i.backgroundImage&&preloadImage(t.theme.backgroundImage),(s=(o=a).openFromBridge)===null||s===void 0||s.call(o)}}}}const scriptBaseUrl=(()=>{if(!scriptEl)return"";try{return new URL(".",scriptEl.src||window.location.href).href}catch{return""}})(),widgetAssetBaseUrl=(()=>{if(!scriptEl)return DEFAULT_WIDGET_ASSET_BASE;const n=scriptEl.dataset.widgetAssets;if(n==="local")return`${scriptBaseUrl}src/`;if(n&&n.length>0)try{return new URL(n,scriptBaseUrl).href}catch{return n.endsWith("/")?n:`${n}/`}return DEFAULT_WIDGET_ASSET_BASE})(),WIDGET_JS_URL=`${widgetAssetBaseUrl}medassist-widget.js`,WIDGET_CSS_URL=`${widgetAssetBaseUrl}medassist-widget.css`;let widgetModulePromise=null,widgetCssTextPromise=null;function getWidgetCssTextPromise(){return widgetCssTextPromise||(widgetCssTextPromise=fetch(WIDGET_CSS_URL).then(n=>{if(!n.ok)throw new Error(`Unable to fetch widget styles from ${WIDGET_CSS_URL}`);return n.text()})),widgetCssTextPromise}class MedAssistWidgetLoader extends HTMLElement{setLauncherState(t){this.launcherState=t,this.updateLauncherView()}getLauncherType(){var t,e;if(this.displayMode!=="widget")return"button";const i=(typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{},o=this.getAgentId();return(this.getAttribute("launcher-type")||i.launcherType||(o?(e=(t=readAgentConfigCache(o))===null||t===void 0?void 0:t.theme)===null||e===void 0?void 0:e.launcher_type:void 0))==="chatbox"?"chatbox":"button"}isChatboxShown(){return this.getLauncherType()==="chatbox"}updateLauncherView(){const t=this.shadowRoot;if(!t)return;this.applyCustomLauncherStyles();const e=this.launcherState,i=this.isChatboxShown(),o=t.getElementById("medassist-open-btn");if(o){const a=e==="loading"&&!i;o.classList.toggle("loading",a),o.classList.toggle("hidden",e==="open"||i),a?o.setAttribute("aria-busy","true"):o.removeAttribute("aria-busy")}const s=t.getElementById("medassist-chatbox");if(s){this.applyChatboxTheme(s);const a=e==="loading"&&i;s.classList.toggle("hidden",e==="open"||!i),s.classList.toggle("sending",a);const d=this.chatStarted&&e==="idle";s.classList.toggle("continuing",d);const l=e==="idle"&&this.chatboxOpensOnTap();s.classList.toggle("tap-open",l),this.syncChatboxPlaceholder(),this.syncChatboxPulse();const r=t.getElementById("medassist-chatbox-input");if(r){r.readOnly=a||d||l,e==="open"&&(r.value="",this.autosizeChatbox());const c=s.querySelector(".medassist-chatbox-send");c&&(c.disabled=!r.value.trim()&&!l)}}}chatboxOpensOnTap(){return this.chatStarted||isMobileViewport()}getChannel(){const t=this.getAttribute("display-mode");if(t)return channelFromDisplayMode(t);const e=typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0;return channelFromDisplayMode(e==null?void 0:e.displayMode)}getAgentConfig(){var t;if(!this.agentConfigPromise){const e=(typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{},i=e.baseUrl||this.getAttribute("base-url")||"https://matrix.eka.care/reloaded",o=e.agentId||this.getAttribute("agent-id")||"";if(!o)return Promise.resolve(void 0);const s=(t=getEnvironment(this.getAttribute("environment")))!==null&&t!==void 0?t:"production";this.agentConfigPromise=this.loadWidgetModule().then(a=>{var d;return(d=a.fetchAgentConfig)===null||d===void 0?void 0:d.call(a,{agentId:o,serverUrl:i,environment:s,channel:this.getChannel()})}).catch(()=>{this.agentConfigPromise=null})}return this.agentConfigPromise}constructor(){super(),this.hostPushStyleEl=null,this.hostPushState=null,this.reactRoot=null,this.agentConfigPromise=null,this.loading=!1,this.chatStarted=!1,this.placeholderTimer=null,this.placeholderIndex=0,this.launcherState="idle",this.authPrefetchPromise=null,this.launcherRenderSeq=0,this.attachShadow({mode:"open"}),this.widgetLoaded=!1,this.displayMode=normalizeDisplayMode(this.getAttribute("display-mode")),this.setupAuthExpirationListener()}static get observedAttributes(){return["icon-url","display-mode","custom-launcher-styles","redirect-url","side-panel-mode","side-panel-width","side","override-widget-width","override-widget-height","launcher-type"]}connectedCallback(){this.displayMode==="full"?(this.initializeFullMode(),this.loadAndRender().catch(t=>{console.error("Failed to load MedAssist widget in full mode",t)})):(this.renderLauncher(),this.scheduleIdle(()=>{this.preloadWidgetAssets(),this.prefetchAuthTokens(),this.initNudge()}))}disconnectedCallback(){var t,e,i,o,s;this.placeholderTimer&&clearInterval(this.placeholderTimer),this.placeholderTimer=null,(t=this.reactRoot)===null||t===void 0||t.unmount(),this.reactRoot=null,(e=document.body)===null||e===void 0||e.classList.remove("eka-medassist-pushed"),(i=document.documentElement)===null||i===void 0||i.style.removeProperty("--eka-medassist-panel-width"),(o=document.documentElement)===null||o===void 0||o.style.removeProperty("--eka-medassist-panel-side"),(s=this.hostPushStyleEl)===null||s===void 0||s.remove(),this.hostPushStyleEl=null,this.hostPushState=null}applyHostPush(t,e,i){var o;if(typeof document=="undefined")return;const s=t?{width:e,side:i}:null,a=this.hostPushState;if(a===s||a&&s&&a.width===s.width&&a.side===s.side)return;this.hostPushState=s,this.hostPushStyleEl||(this.hostPushStyleEl=document.createElement("style"),this.hostPushStyleEl.setAttribute("data-medassist-side-panel-push","true"),document.head.appendChild(this.hostPushStyleEl));const d=i==="left"?"margin-left":"margin-right";this.hostPushStyleEl.textContent=`
|
|
2
2
|
body.eka-medassist-pushed {
|
|
3
3
|
${d}: ${e}px;
|
|
4
4
|
transition: margin 300ms ease;
|
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
@media (prefers-reduced-motion: reduce) {
|
|
10
10
|
body.eka-medassist-pushed { transition: none !important; }
|
|
11
11
|
}
|
|
12
|
-
`;const
|
|
12
|
+
`;const l=document.documentElement.style;t?(l.setProperty("--eka-medassist-panel-width",`${e}px`),l.setProperty("--eka-medassist-panel-side",i),document.body.classList.add("eka-medassist-pushed")):(document.body.classList.remove("eka-medassist-pushed"),l.removeProperty("--eka-medassist-panel-width"),l.removeProperty("--eka-medassist-panel-side"),this.hostPushStyleEl.remove(),this.hostPushStyleEl=null);const r={pushed:t,width:e,side:i};if(typeof window!="undefined"){try{window.dispatchEvent(new CustomEvent(SIDE_PANEL_PUSH_EVENT,{detail:r}))}catch{}const c=(o=window.EkaMedAssist)===null||o===void 0?void 0:o.onSidePanelPushChange;if(typeof c=="function")try{c(t,e,i)}catch(u){console.error("EkaMedAssist.onSidePanelPushChange threw",u)}}}scheduleIdle(t){if(typeof window=="undefined"){t();return}const e=window.requestIdleCallback;typeof e=="function"?e(t,{timeout:3e3}):setTimeout(t,200)}attributeChangedCallback(t){if(t==="icon-url"&&this.displayMode!=="full"&&this.renderLauncher(),t==="display-mode"){const e=normalizeDisplayMode(this.getAttribute("display-mode"));e!==this.displayMode&&(this.displayMode=e,e==="full"?this.initializeFullMode():this.renderLauncher())}t==="custom-launcher-styles"&&this.applyCustomLauncherStyles(),t==="launcher-type"&&this.updateLauncherView()}preloadWidgetAssets(){getWidgetCssTextPromise(),this.loadWidgetModule(),this.preloadBackgroundImage()}prefetchAuthTokens(){var t;if(this.authPrefetchPromise)return this.authPrefetchPromise;const e=(typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{},i=e.agentId||this.getAttribute("agent-id")||"";if(!i)return Promise.resolve(void 0);const o=e.authToken||this.getAttribute("auth-token")||void 0,s=e.baseUrl||this.getAttribute("base-url")||"https://matrix.eka.care/reloaded",a=(t=getEnvironment(this.getAttribute("environment")))!==null&&t!==void 0?t:"production";return this.authPrefetchPromise=this.loadWidgetModule().then(d=>{var l;return(l=d.prefetchAuth)===null||l===void 0?void 0:l.call(d,{agentId:i,authToken:o,serverUrl:s,environment:a,channel:this.getChannel()})}).catch(()=>{this.authPrefetchPromise=null}),this.authPrefetchPromise}async resolveSessToken(t){const e=readPersistedSessToken(t);if(e)return e;const i=await this.prefetchAuthTokens();return(i==null?void 0:i.sess_token)||readPersistedSessToken(t)}preloadBackgroundImage(){var t;const e=typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0,i=this.getAttribute("theme")?(()=>{try{return JSON.parse(this.getAttribute("theme")||"{}")}catch{return}})():void 0,o=(t=e==null?void 0:e.theme)===null||t===void 0?void 0:t.backgroundImage,s=i==null?void 0:i.backgroundImage;o&&preloadImage(o),s&&s!==o&&preloadImage(s),this.getAgentConfig().then(a=>{var d;const l=(d=a==null?void 0:a.theme)===null||d===void 0?void 0:d.background_img;l&&preloadImage(l)}).catch(()=>{})}setupAuthExpirationListener(){if(typeof window=="undefined")return;const t=e=>{var i;((i=e.data)===null||i===void 0?void 0:i.type)==="AUTH_EXPIRED"&&window.parent!==window&&window.parent.postMessage({type:"AUTH_EXPIRED",message:"Authentication expired"},"*")};window.addEventListener("message",t)}openFromBridge(){if(this.displayMode=normalizeDisplayMode(this.getAttribute("display-mode")),this.displayMode==="full")this.initializeFullMode();else if(this.renderLauncher(),this.getLauncherType()==="chatbox")return;this.loadAndRender().catch(t=>{console.error("Failed to open MedAssist widget from bridge",t)})}async initNudge(){var t,e,i,o;const s=typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0,a=(s==null?void 0:s.agentId)||this.getAttribute("agent-id")||"";if(!a)return;const d=await this.getAgentConfig();if(!(d!=null&&d.nudge))return;const l=(e=(t=d==null?void 0:d.theme)===null||t===void 0?void 0:t.nudge_color)!==null&&e!==void 0?e:"#ffffff",r=typeof window!="undefined"?window.location.href:"";let c;try{c=new URL(r)}catch{return}const u=getNudgePathCandidates(c.pathname),m=u.slice(0,1),x=u.slice(1);let g=findFreshCachedNudge(a,c,m);if(!g){const y=(s==null?void 0:s.baseUrl)||this.getAttribute("base-url")||"https://matrix.eka.care/reloaded",_=await this.resolveSessToken(a).catch(()=>{});if(_){const f=await fetchNudgeData(a,_,y,this.getChannel()).catch(()=>{});!((i=f==null?void 0:f.nudges)===null||i===void 0)&&i.length&&(storeNudgeResponse(a,f,normalizePath(c.pathname)),g=findFreshCachedNudge(a,c,u))}}if(g||(g=findFreshCachedNudge(a,c,x)),!g)return;const C=g.data.nudges[Math.floor(Math.random()*g.data.nudges.length)],w=(o=g.data.delay)!==null&&o!==void 0?o:5;setTimeout(()=>{this.showNudgePopup(C,l)},w*1e3)}showNudgePopup(t,e){var i,o;const s=this.shadowRoot;if(!s||!(!((i=s.getElementById("medassist-widget-root"))===null||i===void 0)&&i.classList.contains("hidden")))return;const d=((typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{}).agentId||this.getAttribute("agent-id")||"";if(d&&getNudgeCookie(d)!==null||s.getElementById("medassist-nudge-popup"))return;const r=this.isChatboxShown()?s.getElementById("medassist-chatbox"):s.getElementById("medassist-open-btn"),c=r==null?void 0:r.getBoundingClientRect(),u=272,m=12,x=8,g=16,C=16;let w=window.innerWidth-u-m,y=76,_=u-g-x*2;if(c&&c.width>0){const b=c.left+c.width/2,p=b-u/2,E=window.innerWidth-u-m;w=Math.max(m,Math.min(p,E)),y=window.innerHeight-c.top+C,_=Math.max(g,Math.min(b-w-x,u-g-x*2))}const f=document.createElement("div");f.id="medassist-nudge-popup",f.innerHTML=`
|
|
13
13
|
<style>
|
|
14
14
|
@keyframes nudge-slide-up {
|
|
15
15
|
from { opacity: 0; transform: translateY(12px) scale(0.97); }
|
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
position: fixed;
|
|
20
20
|
bottom: ${y}px;
|
|
21
21
|
left: ${w}px;
|
|
22
|
-
width: ${
|
|
22
|
+
width: ${u}px;
|
|
23
23
|
background: ${e};
|
|
24
24
|
border-radius: 16px;
|
|
25
25
|
box-shadow: 0 8px 32px rgba(0,0,0,0.14), 0 2px 8px rgba(0,0,0,0.08);
|
|
@@ -37,7 +37,7 @@
|
|
|
37
37
|
content: '';
|
|
38
38
|
position: absolute;
|
|
39
39
|
bottom: -8px;
|
|
40
|
-
left: ${
|
|
40
|
+
left: ${_}px;
|
|
41
41
|
width: 16px;
|
|
42
42
|
height: 10px;
|
|
43
43
|
background: ${e};
|
|
@@ -90,7 +90,7 @@
|
|
|
90
90
|
<p class="nudge-text">${t.replace(/</g,"<").replace(/>/g,">")}</p>
|
|
91
91
|
<button class="nudge-close" aria-label="Dismiss">✕</button>
|
|
92
92
|
</div>
|
|
93
|
-
`,(o=f.querySelector(".nudge-close"))===null||o===void 0||o.addEventListener("click",b=>{b.stopPropagation(),d&&setNudgeCookie(d,"closed"),this.dismissNudgePopup()}),f.addEventListener("click",()=>{var b;if(d&&setNudgeCookie(d,"closed"),this.dismissNudgePopup(),this.isChatboxShown()){(b=
|
|
93
|
+
`,(o=f.querySelector(".nudge-close"))===null||o===void 0||o.addEventListener("click",b=>{b.stopPropagation(),d&&setNudgeCookie(d,"closed"),this.dismissNudgePopup()}),f.addEventListener("click",()=>{var b;if(d&&setNudgeCookie(d,"closed"),this.dismissNudgePopup(),this.isChatboxShown()){(b=s.getElementById("medassist-chatbox-input"))===null||b===void 0||b.focus();return}this.loadAndRender()}),s.appendChild(f)}dismissNudgePopup(){var t;const e=(t=this.shadowRoot)===null||t===void 0?void 0:t.getElementById("medassist-nudge-popup");e==null||e.remove()}applyCustomLauncherStyles(){var t,e,i,o;const s=this.shadowRoot;if(!s||this.displayMode==="full")return;const a=this.getAgentId(),d=(i=a?(e=(t=readAgentConfigCache(a))===null||t===void 0?void 0:t.theme)===null||e===void 0?void 0:e.launcher_styles:void 0)!==null&&i!==void 0?i:"";this.setLauncherStyleTag("data-medassist-config-launcher",d);const l=s.querySelector('style[data-medassist-custom-launcher="true"]'),r=(o=this.getAttribute("custom-launcher-styles"))!==null&&o!==void 0?o:"";if(!r){l==null||l.remove();return}if(l){l.textContent=r;return}const c=document.createElement("style");c.setAttribute("data-medassist-custom-launcher","true"),c.textContent=r,s.appendChild(c)}setLauncherStyleTag(t,e){const i=this.shadowRoot;if(!i)return;const o=i.querySelector(`style[${t}="true"]`);if(!e){o==null||o.remove();return}if(o){o.textContent=e;return}const s=document.createElement("style");s.setAttribute(t,"true"),s.textContent=e;const a=i.querySelector('style[data-medassist-custom-launcher="true"]');i.insertBefore(s,a)}getAgentId(){return((typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{}).agentId||this.getAttribute("agent-id")||""}async renderLauncher(){var t,e;if(this.displayMode==="full")return;const i=++this.launcherRenderSeq;this.renderButton();const o=this.getAttribute("icon-url");if(o){this.setLauncherIcon(o);const l=this.getAgentId();l&&this.scheduleIdle(()=>{this.getAgentConfig().then(r=>{!r||i!==this.launcherRenderSeq||(writeAgentConfigCache(l,r),this.updateLauncherView())})});return}const s=this.getAgentId();if(!s)return;const a=(e=(t=readAgentConfigCache(s))===null||t===void 0?void 0:t.theme)===null||e===void 0?void 0:e.icon_img;a&&this.setLauncherIcon(a);const d=async()=>{var l;const r=await this.getAgentConfig().catch(()=>{});i===this.launcherRenderSeq&&(r&&writeAgentConfigCache(s,r),this.setLauncherIcon(((l=r==null?void 0:r.theme)===null||l===void 0?void 0:l.icon_img)||a))};a?this.scheduleIdle(()=>{d()}):await d()}setLauncherIcon(t){var e,i;const o=this.shadowRoot;if(!o)return;const s=o.querySelector("#medassist-open-btn img");s&&(t?s.src=t:s.removeAttribute("src")),(e=o.getElementById("medassist-open-btn"))===null||e===void 0||e.classList.remove("pending"),(i=o.getElementById("medassist-chatbox"))===null||i===void 0||i.classList.remove("pending"),this.updateLauncherView()}applyChatboxTheme(t){var e;const i=((typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{}).theme;let o;try{o=JSON.parse(this.getAttribute("theme")||"{}")}catch{o=void 0}const s=this.getAgentId(),a=s?(e=readAgentConfigCache(s))===null||e===void 0?void 0:e.theme:void 0,d=(i==null?void 0:i.primary)||(o==null?void 0:o.primary)||(a==null?void 0:a.accent);d&&(t.style.setProperty("--medassist-chatbox-accent",d),t.style.setProperty("--medassist-chatbox-on-accent",colorOnAccent(d))),((i==null?void 0:i.mode)||(o==null?void 0:o.mode)||(a==null?void 0:a.mode))==="dark"?t.setAttribute("data-mode","dark"):t.removeAttribute("data-mode")}renderButton(){var t;const e=this.shadowRoot;if(!e){console.error("Shadow root was not created");return}if(!e.querySelector("button")){e.innerHTML=`
|
|
94
94
|
<style>
|
|
95
95
|
#medassist-open-btn {
|
|
96
96
|
width: 60px;
|
|
@@ -390,8 +390,10 @@
|
|
|
390
390
|
#medassist-chatbox-ph.in { opacity: 0; transform: translateY(8px); transition: none; }
|
|
391
391
|
#medassist-chatbox-ph.gone { display: none; }
|
|
392
392
|
/* Widget closed with a chat in progress: any click reopens it. */
|
|
393
|
-
#medassist-chatbox.continuing
|
|
394
|
-
#medassist-chatbox.
|
|
393
|
+
#medassist-chatbox.continuing,
|
|
394
|
+
#medassist-chatbox.tap-open { cursor: pointer; }
|
|
395
|
+
#medassist-chatbox.continuing #medassist-chatbox-input,
|
|
396
|
+
#medassist-chatbox.tap-open #medassist-chatbox-input { cursor: pointer; }
|
|
395
397
|
@media (prefers-reduced-motion: reduce) {
|
|
396
398
|
#medassist-chatbox, #medassist-chatbox-ph { transition: none; }
|
|
397
399
|
}
|
|
@@ -443,7 +445,7 @@
|
|
|
443
445
|
</button>
|
|
444
446
|
</form>
|
|
445
447
|
<div id="medassist-widget-root" class="hidden"></div>
|
|
446
|
-
`,(t=e.getElementById("medassist-open-btn"))===null||t===void 0||t.addEventListener("click",()=>{const r=this.getAgentId();r&&setNudgeCookie(r,"closed"),this.dismissNudgePopup(),this.loadAndRender()});const i=e.getElementById("medassist-chatbox-input");let o=!1;const
|
|
448
|
+
`,(t=e.getElementById("medassist-open-btn"))===null||t===void 0||t.addEventListener("click",()=>{const r=this.getAgentId();r&&setNudgeCookie(r,"closed"),this.dismissNudgePopup(),this.loadAndRender()});const i=e.getElementById("medassist-chatbox-input");let o=!1;const s=e.querySelector(".medassist-chatbox-send"),a=()=>{o||(o=!0,this.preloadWidgetAssets(),this.prefetchAuthTokens())};i==null||i.addEventListener("input",()=>{s&&(s.disabled=!i.value.trim()),this.syncChatboxPlaceholder(),this.syncChatboxPulse(),this.autosizeChatbox(),a()});const d=e.getElementById("medassist-chatbox"),l=()=>{if(!this.chatboxOpensOnTap()||this.loading||this.launcherState!=="idle")return!1;const r=this.getAgentId();return r&&setNudgeCookie(r,"closed"),this.dismissNudgePopup(),this.loadAndRender(),!0};d==null||d.addEventListener("pointerdown",()=>{this.chatboxOpensOnTap()&&a()}),d==null||d.addEventListener("click",r=>{l()&&r.preventDefault()}),i==null||i.addEventListener("scroll",()=>this.updateChatboxFades()),i==null||i.addEventListener("keydown",r=>{r.key!=="Enter"||r.shiftKey||r.isComposing||(r.preventDefault(),!l()&&i.value.trim()&&(d==null||d.requestSubmit()))}),this.startPlaceholderRotation(),d==null||d.addEventListener("submit",r=>{r.preventDefault();const c=i==null?void 0:i.value.trim();if(!c&&l()||!c||this.loading)return;const u=this.getAgentId();u&&setNudgeCookie(u,"closed"),this.dismissNudgePopup(),this.loadAndRender(c)})}this.applyCustomLauncherStyles()}initializeFullMode(){const t=this.shadowRoot;if(!t){console.error("Shadow root is not available");return}t.getElementById("medassist-widget-root")||(t.innerHTML=`
|
|
447
449
|
<style>
|
|
448
450
|
:host {
|
|
449
451
|
display: block;
|
|
@@ -460,4 +462,4 @@
|
|
|
460
462
|
}
|
|
461
463
|
</style>
|
|
462
464
|
<div id="medassist-widget-root"></div>
|
|
463
|
-
`)}async loadAndRender(t){var e,i,o,n;const a=this.shadowRoot;if(!a){console.error("Shadow root is not available");return}if(this.loading)return;this.prefetchAuthTokens(),this.style.display="";const d=a.getElementById("medassist-widget-root"),r=this.getAttribute("agent-id");let l=this.getAttribute("icon-url")||void 0;const c=(e=getEnvironment(this.getAttribute("environment")))!==null&&e!==void 0?e:"production",h=this.getAttribute("connectivity"),m=h==="http_stream"||h==="socket"?h:void 0,x=this.getAttribute("force-start")==="true";let p=this.getAttribute("title")||"Medi Clinic";const C=this.getAttribute("base-url")||"https://matrix.eka.care/reloaded",w=this.getAttribute("display-mode"),y=normalizeDisplayMode(w),A=this.getAttribute("context")?JSON.parse(this.getAttribute("context")||"{}"):void 0,f=this.getAttribute("theme")?(()=>{try{return JSON.parse(this.getAttribute("theme")||"{}")}catch{return}})():void 0,b=this.getAttribute("feedback")?(()=>{try{return JSON.parse(this.getAttribute("feedback")||"{}")}catch{return}})():void 0,g=(typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{},E=this.getAttribute("side-panel-mode"),J=g.sidePanelMode||(E==="overlay"?"overlay":"push"),R=this.getAttribute("side-panel-width"),Y=(i=g.sidePanelWidth)!==null&&i!==void 0?i:R?Number(R):void 0,j=g.side||this.getAttribute("side")||(typeof document!="undefined"&&document.dir==="rtl"?"left":"right"),N=u=>{const v=Number(this.getAttribute(u));return Number.isFinite(v)&&v>0?v:void 0},T=N("override-widget-width"),B=N("override-widget-height"),G={...T!==void 0&&{overrideWidgetWidth:T},...B!==void 0&&{overrideWidgetHeight:B}},V={...A||{},...g.context||{}},K=g.authToken||this.getAttribute("auth-token")||void 0,_=g.agentId||r,X=g.baseUrl||C,P=typeof window!="undefined"?(o=window.EkaMedAssist)===null||o===void 0?void 0:o.onClose:void 0,Z=this.getAttribute("redirect-url")||void 0,I=g.redirectUrl||Z,Q=!!I||g.showCloseButton===!0;if(!_){console.error("Agent ID is required");return}if(!d){console.error("Widget root element is missing");return}this.loading=!0,this.setLauncherState("loading"),d.classList.remove("hidden");let W,$,z,U=!1,F,O=!1,L;const D=u=>{var v,k,M;p=u.name||p,l=((v=u.theme)===null||v===void 0?void 0:v.icon_img)||l,W=mapAgentConfigThemeToWidgetTheme(u.theme||void 0),$=u.allowed,z=u.connectivity,U=u.resize||(g==null?void 0:g.resize)||!1,F=u.initial_message,O=(M=(k=u.theme)===null||k===void 0?void 0:k.hide_watermark)!==null&&M!==void 0?M:!1,L=u.feedback},H=readAgentConfigCache(_);if(H)D(H),this.getAgentConfig().then(u=>{u&&writeAgentConfigCache(_,u)}).catch(()=>{});else try{const u=await this.getAgentConfig();u&&(writeAgentConfigCache(_,u),D(u))}catch{}const tt=m||z||"socket",q={title:g.title||p,iconUrl:l||g.iconUrl,showCloseButton:Q,allowed:$,environment:c,connectionType:tt,onClose:()=>{var u;if((u=this.reactRoot)===null||u===void 0||u.unmount(),this.reactRoot=null,P&&typeof P=="function"&&P(),I){window.location.href=I;return}y==="full"?this.style.display="none":(this.setLauncherState("idle"),d.classList.add("hidden"))},baseUrl:X,context:V,displayMode:y,sidePanelMode:J,sidePanelWidth:Y,side:j,onSidePanelPushChange:(u,v,k)=>this.applyHostPush(u,v,k),resize:U||this.getAttribute("resize")==="true",authToken:K,force:x,initialMessage:F,hideWatermark:O,...(b||L)&&{feedback:b||L},...t&&{firstUserMessage:t},theme:{...this.isChatboxShown()&&{widgetWidth:520},...W||{},...f||{},...G,...g.theme||{},...this.isChatboxShown()&&{openFrom:"bottom-center"}}},et=window,S=this.isChatboxShown()?(n=a.getElementById("medassist-chatbox"))===null||n===void 0?void 0:n.getBoundingClientRect():void 0;if(this.widgetLoaded){this.reactRoot=et.renderMedAssist(d,_,q),this.chatStarted=!0,S&&await this.growWidgetFromChatbox(S),this.setLauncherState("open"),this.loading=!1;return}try{const[,u]=await Promise.all([this.loadWidgetCss(),this.loadWidgetModule()]);this.reactRoot=u.renderMedAssist(d,_,q),this.widgetLoaded=!0,this.chatStarted=!0,S&&await this.growWidgetFromChatbox(S),this.setLauncherState("open")}catch(u){console.error("Failed to load MedAssist widget",u),this.setLauncherState("idle"),d.classList.add("hidden")}finally{this.loading=!1}}getOpenAnimation(){const t=(typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{},e=this.getAttribute("open-animation")||t.openAnimation;return e==="unfold"||e==="pop"||e==="curtain"||e==="fade"||e==="none"?e:"rise"}async growWidgetFromChatbox(t){var e;try{const i=this.getOpenAnimation();if(i==="none"||prefersReducedMotion())return;const o=this.shadowRoot;let n=null;for(let c=0;c<30&&!n;c++)await nextFrame(),n=(e=o==null?void 0:o.querySelector(".synapse-chat-widget-container"))!==null&&e!==void 0?e:null;if(!n||typeof n.animate!="function")return;const a=n.getBoundingClientRect();if(!a.width||!a.height||!t.width)return;const d=a.width>=window.innerWidth-1?0:24,r="50% 100%";if(i==="rise")n.animate([{transform:"translateY(56px) scale(0.96)",opacity:0,transformOrigin:r},{transform:"translateY(0px) scale(1)",opacity:1,transformOrigin:r}],{duration:520,easing:"cubic-bezier(0.22, 1, 0.36, 1)"});else if(i==="pop")n.animate([{transform:"scale(0.4)",opacity:0,transformOrigin:r},{transform:"scale(1.04)",opacity:1,transformOrigin:r,offset:.6},{transform:"scale(1)",opacity:1,transformOrigin:r}],{duration:560,easing:"cubic-bezier(0.34, 1.2, 0.64, 1)"});else if(i==="curtain")n.animate([{transform:"translateY(20px)",clipPath:`inset(100% 0px 0px 0px round ${d}px)`},{transform:"translateY(0px)",clipPath:`inset(0px 0px 0px 0px round ${d}px)`}],{duration:560,easing:"cubic-bezier(0.65, 0, 0.35, 1)"});else if(i==="fade"){n.animate([{transform:"scale(0.97)",opacity:0,transformOrigin:r},{transform:"scale(1)",opacity:1,transformOrigin:r}],{duration:280,easing:"ease-out"});return}else{const c=t.left+t.width/2-(a.left+a.width/2),h=t.bottom-a.bottom,m=Math.max(0,a.height-t.height),x=Math.max(0,(a.width-t.width)/2),p=Math.min(t.height/2,28);n.animate([{transform:`translate(${c}px, ${h}px)`,clipPath:`inset(${m}px ${x}px 0px ${x}px round ${p}px)`},{transform:"translate(0px, 0px)",clipPath:`inset(0px 0px 0px 0px round ${d}px)`}],{duration:620,easing:"cubic-bezier(0.22, 1, 0.36, 1)"})}const l=Array.from(n.children).find(c=>c.tagName!=="STYLE");l==null||l.animate([{opacity:0,transform:"translateY(14px)"},{opacity:1,transform:"translateY(0px)"}],{duration:420,delay:140,easing:"cubic-bezier(0.22, 1, 0.36, 1)",fill:"backwards"})}catch{}}getChatboxPlaceholders(){return this.collectChatboxPlaceholders().map(withTrailingEllipsis)}collectChatboxPlaceholders(){var t,e,i;const o=(typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{};let n=o.chatboxPlaceholders;if(!Array.isArray(n))try{n=JSON.parse(this.getAttribute("chatbox-placeholders")||"null")}catch{n=null}const a=Array.isArray(n)?n.filter(l=>typeof l=="string"&&!!l.trim()):[];if(a.length)return a;const d=o.agentId||this.getAttribute("agent-id")||"",r=l=>Array.isArray(l)?l.filter(c=>typeof c=="string"&&!!c.trim()):[];if(d){try{const c=new URL(window.location.href),h=findFreshCachedNudge(d,c,getNudgePathCandidates(c.pathname)),m=r(h==null?void 0:h.data.nudges);if(m.length)return m}catch{}const l=r((i=(e=(t=readAgentConfigCache(d))===null||t===void 0?void 0:t.initial_message)===null||e===void 0?void 0:e.suggestions)===null||i===void 0?void 0:i.map(c=>c.label||c.value));if(l.length)return l}return["Ask me anything\u2026","Not sure what to ask? Just say hi\u2026","You can type in any language\u2026"]}autosizeChatbox(){var t;const e=(t=this.shadowRoot)===null||t===void 0?void 0:t.getElementById("medassist-chatbox-input");if(!e)return;e.style.height="auto";const i=parseFloat(getComputedStyle(e).maxHeight)||92;e.style.height=`${Math.min(e.scrollHeight,i)}px`,e.style.overflowY=e.scrollHeight>i?"auto":"hidden",this.updateChatboxFades()}updateChatboxFades(){var t;const e=(t=this.shadowRoot)===null||t===void 0?void 0:t.getElementById("medassist-chatbox-input");e&&(e.classList.toggle("fade-t",e.scrollTop>1),e.classList.toggle("fade-b",e.scrollHeight-e.clientHeight-e.scrollTop>1))}syncChatboxPulse(){const t=this.shadowRoot,e=t==null?void 0:t.getElementById("medassist-chatbox"),i=t==null?void 0:t.getElementById("medassist-chatbox-input");if(!e)return;const o=this.launcherState==="idle"&&!this.chatStarted&&!(i!=null&&i.value)&&!prefersReducedMotion();e.classList.toggle("pulse",o)}syncChatboxPlaceholder(){const t=this.shadowRoot,e=t==null?void 0:t.getElementById("medassist-chatbox-ph");if(!t||!e)return;const i=t.getElementById("medassist-chatbox-input"),o=this.chatStarted&&this.launcherState==="idle";e.classList.toggle("gone",!!(i!=null&&i.value));const n=o?"Continue your chat\u2026":this.getChatboxPlaceholders()[this.placeholderIndex%this.getChatboxPlaceholders().length];e.textContent!==n&&(e.textContent=n)}startPlaceholderRotation(){this.placeholderTimer||(this.syncChatboxPlaceholder(),!prefersReducedMotion()&&(this.placeholderTimer=setInterval(()=>{const t=this.shadowRoot,e=t==null?void 0:t.getElementById("medassist-chatbox-ph"),i=t==null?void 0:t.getElementById("medassist-chatbox-input");if(!t||!e||!i)return;const o=this.getChatboxPlaceholders();o.length<2||document.hidden||this.chatStarted||this.launcherState!=="idle"||i.value||t.activeElement===i||(e.classList.add("out"),setTimeout(()=>{this.placeholderIndex=(this.placeholderIndex+1)%o.length,e.classList.remove("out"),e.classList.add("in"),this.syncChatboxPlaceholder(),e.offsetWidth,e.classList.remove("in")},220))},3500)))}async loadWidgetCss(){const t=this.shadowRoot;if(!t)throw new Error("Shadow root is not available");if(t.querySelector("[data-medassist-style='true']"))return;const e=await getWidgetCssTextPromise(),i=document.createElement("style");i.setAttribute("data-medassist-style","true"),i.textContent=e,t.appendChild(i)}loadWidgetModule(){return widgetModulePromise||(widgetModulePromise=import(WIDGET_JS_URL)),widgetModulePromise}}customElements.define("eka-medassist-widget",MedAssistWidgetLoader);
|
|
465
|
+
`)}async loadAndRender(t){var e,i,o,s;const a=this.shadowRoot;if(!a){console.error("Shadow root is not available");return}if(this.loading)return;this.prefetchAuthTokens(),this.style.display="";const d=a.getElementById("medassist-widget-root"),l=this.getAttribute("agent-id");let r=this.getAttribute("icon-url")||void 0;const c=(e=getEnvironment(this.getAttribute("environment")))!==null&&e!==void 0?e:"production",u=this.getAttribute("connectivity"),m=u==="http_stream"||u==="socket"?u:void 0,x=this.getAttribute("force-start")==="true";let g=this.getAttribute("title")||"Medi Clinic";const C=this.getAttribute("base-url")||"https://matrix.eka.care/reloaded",w=this.getAttribute("display-mode"),y=normalizeDisplayMode(w),_=this.getAttribute("context")?JSON.parse(this.getAttribute("context")||"{}"):void 0,f=this.getAttribute("theme")?(()=>{try{return JSON.parse(this.getAttribute("theme")||"{}")}catch{return}})():void 0,b=this.getAttribute("feedback")?(()=>{try{return JSON.parse(this.getAttribute("feedback")||"{}")}catch{return}})():void 0,p=(typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{},E=this.getAttribute("side-panel-mode"),J=p.sidePanelMode||(E==="overlay"?"overlay":"push"),R=this.getAttribute("side-panel-width"),Y=(i=p.sidePanelWidth)!==null&&i!==void 0?i:R?Number(R):void 0,j=p.side||this.getAttribute("side")||(typeof document!="undefined"&&document.dir==="rtl"?"left":"right"),T=h=>{const v=Number(this.getAttribute(h));return Number.isFinite(v)&&v>0?v:void 0},B=T("override-widget-width"),N=T("override-widget-height"),G={...B!==void 0&&{overrideWidgetWidth:B},...N!==void 0&&{overrideWidgetHeight:N}},V={..._||{},...p.context||{}},X=p.authToken||this.getAttribute("auth-token")||void 0,A=p.agentId||l,K=p.baseUrl||C,I=typeof window!="undefined"?(o=window.EkaMedAssist)===null||o===void 0?void 0:o.onClose:void 0,Q=this.getAttribute("redirect-url")||void 0,P=p.redirectUrl||Q,Z=!!P||p.showCloseButton===!0;if(!A){console.error("Agent ID is required");return}if(!d){console.error("Widget root element is missing");return}this.loading=!0,this.setLauncherState("loading"),d.classList.remove("hidden");let O,W,U,$=!1,z,F=!1,L;const D=h=>{var v,k,M;g=h.name||g,r=((v=h.theme)===null||v===void 0?void 0:v.icon_img)||r,O=mapAgentConfigThemeToWidgetTheme(h.theme||void 0),W=h.allowed,U=h.connectivity,$=h.resize||(p==null?void 0:p.resize)||!1,z=h.initial_message,F=(M=(k=h.theme)===null||k===void 0?void 0:k.hide_watermark)!==null&&M!==void 0?M:!1,L=h.feedback},q=readAgentConfigCache(A);if(q)D(q),this.getAgentConfig().then(h=>{h&&writeAgentConfigCache(A,h)}).catch(()=>{});else try{const h=await this.getAgentConfig();h&&(writeAgentConfigCache(A,h),D(h))}catch{}const tt=m||U||"socket",H={title:p.title||g,iconUrl:r||p.iconUrl,showCloseButton:Z,allowed:W,environment:c,connectionType:tt,onClose:()=>{var h;if((h=this.reactRoot)===null||h===void 0||h.unmount(),this.reactRoot=null,I&&typeof I=="function"&&I(),P){window.location.href=P;return}y==="full"?this.style.display="none":(this.setLauncherState("idle"),d.classList.add("hidden"))},baseUrl:K,context:V,...p.tools&&{tools:p.tools},displayMode:y,sidePanelMode:J,sidePanelWidth:Y,side:j,onSidePanelPushChange:(h,v,k)=>this.applyHostPush(h,v,k),resize:$||this.getAttribute("resize")==="true",authToken:X,force:x,initialMessage:z,hideWatermark:F,...(b||L)&&{feedback:b||L},...t&&{firstUserMessage:t},theme:{...this.isChatboxShown()&&{widgetWidth:520},...O||{},...f||{},...G,...p.theme||{},...this.isChatboxShown()&&{openFrom:"bottom-center"}}},et=window,S=this.isChatboxShown()?(s=a.getElementById("medassist-chatbox"))===null||s===void 0?void 0:s.getBoundingClientRect():void 0;if(this.widgetLoaded){this.reactRoot=et.renderMedAssist(d,A,H),this.chatStarted=!0,S&&await this.growWidgetFromChatbox(S),this.setLauncherState("open"),this.loading=!1;return}try{const[,h]=await Promise.all([this.loadWidgetCss(),this.loadWidgetModule()]);this.reactRoot=h.renderMedAssist(d,A,H),this.widgetLoaded=!0,this.chatStarted=!0,S&&await this.growWidgetFromChatbox(S),this.setLauncherState("open")}catch(h){console.error("Failed to load MedAssist widget",h),this.setLauncherState("idle"),d.classList.add("hidden")}finally{this.loading=!1}}getOpenAnimation(){const t=(typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{},e=this.getAttribute("open-animation")||t.openAnimation;return e==="unfold"||e==="pop"||e==="curtain"||e==="fade"||e==="none"?e:"rise"}async growWidgetFromChatbox(t){var e;try{const i=this.getOpenAnimation();if(i==="none"||prefersReducedMotion())return;const o=this.shadowRoot;let s=null;for(let c=0;c<30&&!s;c++)await nextFrame(),s=(e=o==null?void 0:o.querySelector(".synapse-chat-widget-container"))!==null&&e!==void 0?e:null;if(!s||typeof s.animate!="function")return;const a=s.getBoundingClientRect();if(!a.width||!a.height||!t.width)return;const d=a.width>=window.innerWidth-1?0:24,l="50% 100%";if(i==="rise")s.animate([{transform:"translateY(56px) scale(0.96)",opacity:0,transformOrigin:l},{transform:"translateY(0px) scale(1)",opacity:1,transformOrigin:l}],{duration:520,easing:"cubic-bezier(0.22, 1, 0.36, 1)"});else if(i==="pop")s.animate([{transform:"scale(0.4)",opacity:0,transformOrigin:l},{transform:"scale(1.04)",opacity:1,transformOrigin:l,offset:.6},{transform:"scale(1)",opacity:1,transformOrigin:l}],{duration:560,easing:"cubic-bezier(0.34, 1.2, 0.64, 1)"});else if(i==="curtain")s.animate([{transform:"translateY(20px)",clipPath:`inset(100% 0px 0px 0px round ${d}px)`},{transform:"translateY(0px)",clipPath:`inset(0px 0px 0px 0px round ${d}px)`}],{duration:560,easing:"cubic-bezier(0.65, 0, 0.35, 1)"});else if(i==="fade"){s.animate([{transform:"scale(0.97)",opacity:0,transformOrigin:l},{transform:"scale(1)",opacity:1,transformOrigin:l}],{duration:280,easing:"ease-out"});return}else{const c=t.left+t.width/2-(a.left+a.width/2),u=t.bottom-a.bottom,m=Math.max(0,a.height-t.height),x=Math.max(0,(a.width-t.width)/2),g=Math.min(t.height/2,28);s.animate([{transform:`translate(${c}px, ${u}px)`,clipPath:`inset(${m}px ${x}px 0px ${x}px round ${g}px)`},{transform:"translate(0px, 0px)",clipPath:`inset(0px 0px 0px 0px round ${d}px)`}],{duration:620,easing:"cubic-bezier(0.22, 1, 0.36, 1)"})}const r=Array.from(s.children).find(c=>c.tagName!=="STYLE");r==null||r.animate([{opacity:0,transform:"translateY(14px)"},{opacity:1,transform:"translateY(0px)"}],{duration:420,delay:140,easing:"cubic-bezier(0.22, 1, 0.36, 1)",fill:"backwards"})}catch{}}getChatboxPlaceholders(){return this.collectChatboxPlaceholders().map(withTrailingEllipsis)}collectChatboxPlaceholders(){var t,e,i;const o=(typeof window!="undefined"?window.__ekaMedAssistConfig__:void 0)||{};let s=o.chatboxPlaceholders;if(!Array.isArray(s))try{s=JSON.parse(this.getAttribute("chatbox-placeholders")||"null")}catch{s=null}const a=Array.isArray(s)?s.filter(r=>typeof r=="string"&&!!r.trim()):[];if(a.length)return a;const d=o.agentId||this.getAttribute("agent-id")||"",l=r=>Array.isArray(r)?r.filter(c=>typeof c=="string"&&!!c.trim()):[];if(d){try{const c=new URL(window.location.href),u=findFreshCachedNudge(d,c,getNudgePathCandidates(c.pathname)),m=l(u==null?void 0:u.data.nudges);if(m.length)return m}catch{}const r=l((i=(e=(t=readAgentConfigCache(d))===null||t===void 0?void 0:t.initial_message)===null||e===void 0?void 0:e.suggestions)===null||i===void 0?void 0:i.map(c=>c.label||c.value));if(r.length)return r}return["Ask me anything\u2026","Not sure what to ask? Just say hi\u2026","You can type in any language\u2026"]}autosizeChatbox(){var t;const e=(t=this.shadowRoot)===null||t===void 0?void 0:t.getElementById("medassist-chatbox-input");if(!e)return;e.style.height="auto";const i=parseFloat(getComputedStyle(e).maxHeight)||92;e.style.height=`${Math.min(e.scrollHeight,i)}px`,e.style.overflowY=e.scrollHeight>i?"auto":"hidden",this.updateChatboxFades()}updateChatboxFades(){var t;const e=(t=this.shadowRoot)===null||t===void 0?void 0:t.getElementById("medassist-chatbox-input");e&&(e.classList.toggle("fade-t",e.scrollTop>1),e.classList.toggle("fade-b",e.scrollHeight-e.clientHeight-e.scrollTop>1))}syncChatboxPulse(){const t=this.shadowRoot,e=t==null?void 0:t.getElementById("medassist-chatbox"),i=t==null?void 0:t.getElementById("medassist-chatbox-input");if(!e)return;const o=this.launcherState==="idle"&&!this.chatStarted&&!(i!=null&&i.value)&&!prefersReducedMotion();e.classList.toggle("pulse",o)}syncChatboxPlaceholder(){const t=this.shadowRoot,e=t==null?void 0:t.getElementById("medassist-chatbox-ph");if(!t||!e)return;const i=t.getElementById("medassist-chatbox-input"),o=this.chatStarted&&this.launcherState==="idle";e.classList.toggle("gone",!!(i!=null&&i.value));const s=o?"Continue your chat\u2026":this.getChatboxPlaceholders()[this.placeholderIndex%this.getChatboxPlaceholders().length];e.textContent!==s&&(e.textContent=s)}startPlaceholderRotation(){this.placeholderTimer||(this.syncChatboxPlaceholder(),!prefersReducedMotion()&&(this.placeholderTimer=setInterval(()=>{const t=this.shadowRoot,e=t==null?void 0:t.getElementById("medassist-chatbox-ph"),i=t==null?void 0:t.getElementById("medassist-chatbox-input");if(!t||!e||!i)return;const o=this.getChatboxPlaceholders();o.length<2||document.hidden||this.chatStarted||this.launcherState!=="idle"||i.value||t.activeElement===i||(e.classList.add("out"),setTimeout(()=>{this.placeholderIndex=(this.placeholderIndex+1)%o.length,e.classList.remove("out"),e.classList.add("in"),this.syncChatboxPlaceholder(),e.offsetWidth,e.classList.remove("in")},220))},3500)))}async loadWidgetCss(){const t=this.shadowRoot;if(!t)throw new Error("Shadow root is not available");if(t.querySelector("[data-medassist-style='true']"))return;const e=await getWidgetCssTextPromise(),i=document.createElement("style");i.setAttribute("data-medassist-style","true"),i.textContent=e,t.appendChild(i)}loadWidgetModule(){return widgetModulePromise||(widgetModulePromise=import(WIDGET_JS_URL)),widgetModulePromise}}customElements.define("eka-medassist-widget",MedAssistWidgetLoader);
|