copilot-chat-widget 0.1.5 → 0.1.7

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 CHANGED
@@ -8,65 +8,65 @@ Widget chat Copilot nay co the nhung bang 2 cach:
8
8
  ## Cai dat
9
9
 
10
10
  ```bash
11
- npm install copilot-chat-widget
12
- # hoac
13
- yarn add copilot-chat-widget
14
- ```
15
-
16
- ## Su dung voi NPM (import)
17
-
18
- ```js
19
- import { loadCopilotChatWidget } from "copilot-chat-widget";
20
-
21
- loadCopilotChatWidget({ token: "YOUR_WIDGET_TOKEN" });
22
- ```
23
-
11
+ npm install copilot-chat-widget
12
+ # hoac
13
+ yarn add copilot-chat-widget
14
+ ```
15
+
16
+ ## Su dung voi NPM (import)
17
+
18
+ ```js
19
+ import { loadCopilotChatWidget } from "copilot-chat-widget";
20
+
21
+ loadCopilotChatWidget({ token: "YOUR_WIDGET_TOKEN" });
22
+ ```
23
+
24
24
  Hàm này se gắn script `chat-widget.min.js` (IIFE) vào trang, đọc `token` từ options (hoặc `window.CopilotChatConfig` nếu bạn set trước).
25
- - Nếu backend widget không cùng origin với web hiện tại, truyền thêm `baseUrl: "https://your-backend-domain"` để gọi đúng API.
26
-
27
- ### React/Next.js
28
-
29
- ```jsx
30
- import { useEffect } from "react";
31
- import { loadCopilotChatWidget } from "copilot-chat-widget";
32
-
25
+ - Nếu backend widget không cùng origin với web hiện tại, truyền thêm `baseUrl: "https://your-backend-domain"` để gọi đúng API. Nếu không truyền, widget sẽ dùng giá trị build-time (`WIDGET_BASE_URL` hoặc `VITE_WIDGET_BASE_URL`), sau đó mới fallback sang origin của script/trang.
26
+
27
+ ### React/Next.js
28
+
29
+ ```jsx
30
+ import { useEffect } from "react";
31
+ import { loadCopilotChatWidget } from "copilot-chat-widget";
32
+
33
33
  export default function Page() {
34
34
  useEffect(() => {
35
35
  loadCopilotChatWidget({
36
36
  token: process.env.NEXT_PUBLIC_CHAT_WIDGET_TOKEN,
37
- baseUrl: process.env.NEXT_PUBLIC_WIDGET_BASE_URL // nếu backend khác origin
37
+ baseUrl: process.env.NEXT_PUBLIC_WIDGET_BASE_URL // nếu backend khác origin; nếu không, sẽ dùng giá trị build-time hoặc origin hiện tại
38
38
  });
39
39
  }, []);
40
-
41
- return <main>Your page content</main>;
42
- }
43
- ```
44
-
45
- ## Su dung qua the `<script>` (giu hanh vi cu)
46
-
47
- ```html
48
- <script
49
- src="https://cdn.example.com/chat-widget.min.js"
50
- data-token="YOUR_WIDGET_TOKEN"
51
- ></script>
52
- ```
53
-
54
- - `data-token`: bat buoc.
55
- - `data-autoload="false"`: neu muon chen script nhung tu goi `window.CopilotChat.init()` sau.
56
-
57
- ## API cau hinh
58
-
59
- - `token` (string, bat buoc): ma token widget.
60
- - `autoload` (boolean): dat `false` neu muon tu goi `window.CopilotChat.load()`.
61
- - `baseUrl` (string): host/backend cung cấp API `/api/chat-widget/config`. Can khi web embed khac origin.
62
-
63
- Khi script da load, co the goi:
64
-
65
- ```js
66
- window.CopilotChat.open(); // mo widget
67
- window.CopilotChat.close(); // dong widget
68
- window.CopilotChat.load(); // khoi tao lai neu autoload=false
69
- ```
40
+
41
+ return <main>Your page content</main>;
42
+ }
43
+ ```
44
+
45
+ ## Su dung qua the `<script>` (giu hanh vi cu)
46
+
47
+ ```html
48
+ <script
49
+ src="https://cdn.example.com/chat-widget.min.js"
50
+ data-token="YOUR_WIDGET_TOKEN"
51
+ ></script>
52
+ ```
53
+
54
+ - `data-token`: bat buoc.
55
+ - `data-autoload="false"`: neu muon chen script nhung tu goi `window.CopilotChat.init()` sau.
56
+
57
+ ## API cau hinh
58
+
59
+ - `token` (string, bat buoc): ma token widget.
60
+ - `autoload` (boolean): dat `false` neu muon tu goi `window.CopilotChat.load()`.
61
+ - `baseUrl` (string): host/backend cung cấp API `/api/chat-widget/config`. Can khi web embed khac origin.
62
+
63
+ Khi script da load, co the goi:
64
+
65
+ ```js
66
+ window.CopilotChat.open(); // mo widget
67
+ window.CopilotChat.close(); // dong widget
68
+ window.CopilotChat.load(); // khoi tao lai neu autoload=false
69
+ ```
70
70
 
71
71
  ## Build va publish package
72
72
 
@@ -1,7 +1,7 @@
1
- (function(){"use strict";(()=>{if(typeof window>"u"||typeof document>"u"||window.__copilotWidgetLoaded)return;window.__copilotWidgetLoaded=!0;const m=64,C=720,y=document.currentScript,x=t=>{if(!t?.src)return{};try{const o=new URL(t.src,window.location.href),n={};return o.searchParams.forEach((a,s)=>{n[s]=a}),n}catch(o){return console.warn("[CopilotChat] Failed to parse script query params:",o),{}}},E=t=>{document.readyState==="complete"||document.readyState==="interactive"?setTimeout(t,0):document.addEventListener("DOMContentLoaded",t)},U=t=>{if(!t?.src)return null;try{const o=new URL(t.src,window.location.href);return`${o.protocol}//${o.host}`}catch(o){return console.warn("[CopilotChat] Unable to infer base URL from script source.",o),null}},k=()=>y||Array.from(document.querySelectorAll("script")).reverse().find(n=>n.dataset?.token||n.src&&n.src.includes("chat-widget"))||null,S=({iframeUrl:t,launcherIcon:o})=>{const n=document.querySelector("[data-copilot-widget-root]");n&&n.remove();const a=document.createElement("div");a.setAttribute("data-copilot-widget-root","true");const s=a.attachShadow({mode:"open"});document.body.appendChild(a);const e=document.createElement("button");e.type="button",e.setAttribute("aria-label","Open Copilot chat"),e.innerHTML=`
1
+ (function(){"use strict";(()=>{if(typeof window>"u"||typeof document>"u"||window.__copilotWidgetLoaded)return;window.__copilotWidgetLoaded=!0;const E=void 0,m=64,C=720,y=document.currentScript,x=t=>{if(!t?.src)return{};try{const o=new URL(t.src,window.location.href),n={};return o.searchParams.forEach((a,s)=>{n[s]=a}),n}catch(o){return console.warn("[CopilotChat] Failed to parse script query params:",o),{}}},U=t=>{document.readyState==="complete"||document.readyState==="interactive"?setTimeout(t,0):document.addEventListener("DOMContentLoaded",t)},S=t=>{if(!t?.src)return null;try{const o=new URL(t.src,window.location.href);return`${o.protocol}//${o.host}`}catch(o){return console.warn("[CopilotChat] Unable to infer base URL from script source.",o),null}},k=()=>y||Array.from(document.querySelectorAll("script")).reverse().find(n=>n.dataset?.token||n.src&&n.src.includes("chat-widget"))||null,L=({iframeUrl:t,launcherIcon:o})=>{const n=document.querySelector("[data-copilot-widget-root]");n&&n.remove();const a=document.createElement("div");a.setAttribute("data-copilot-widget-root","true");const s=a.attachShadow({mode:"open"});document.body.appendChild(a);const e=document.createElement("button");e.type="button",e.setAttribute("aria-label","Open Copilot chat"),e.innerHTML=`
2
2
  <img
3
3
  src="${o}"
4
4
  alt="Copilot chat launcher"
5
5
  style="width: 38px; height: 38px; object-fit: contain; border-radius: 50%; pointer-events: none;"
6
6
  />
7
- `,Object.assign(e.style,{position:"fixed",bottom:"24px",right:"24px",width:`${m}px`,height:`${m}px`,borderRadius:"50%",border:"none",background:"linear-gradient(135deg, #0078ff, #00c6ff)",color:"white",cursor:"pointer",zIndex:999998,display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 6px 14px rgba(0,0,0,0.25)",transition:"all 0.25s ease"}),e.onmouseover=()=>{e.style.transform="scale(1.12)",e.style.boxShadow="0 10px 25px rgba(0,0,0,0.3)"},e.onmouseout=()=>{e.style.transform="scale(1)",e.style.boxShadow="0 6px 14px rgba(0,0,0,0.25)"};const r=document.createElement("div");r.setAttribute("data-copilot-widget-root","true"),Object.assign(r.style,{display:"none",position:"fixed",bottom:`${m+36}px`,right:"24px",zIndex:"999999",transformOrigin:"bottom right",transform:"scale(0.8) translateY(20px)",opacity:"0",transition:"all 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55)"});const i=document.createElement("div"),c=document.createElement("div"),b=document.createElement("div");Object.assign(i.style,{position:"absolute",bottom:"-14px",right:"28px",width:"30px",height:"20px",pointerEvents:"none",display:"none",zIndex:"1"}),Object.assign(c.style,{position:"absolute",bottom:"0",left:"0",right:"0",margin:"0 auto",width:"0",height:"0",borderLeft:"15px solid transparent",borderRight:"15px solid transparent",borderTop:"15px solid rgba(15,23,42,0.1)"}),Object.assign(b.style,{position:"absolute",bottom:"2px",left:"0",right:"0",margin:"0 auto",width:"0",height:"0",borderLeft:"13px solid transparent",borderRight:"13px solid transparent",borderTop:"13px solid white",boxShadow:"0 6px 16px rgba(15,23,42,0.12)",borderRadius:"2px"}),i.appendChild(c),i.appendChild(b);const d=document.createElement("div");Object.assign(d.style,{width:`${C}px`,maxWidth:"calc(100vw - 48px)",height:`${Math.min(C,Math.max(320,window.innerHeight-140))}px`,maxHeight:"calc(100vh - 150px)",borderRadius:"20px",background:"white",border:"1px solid rgba(15,23,42,0.12)",boxShadow:"0 18px 45px rgba(15,23,42,0.16)",overflow:"hidden"}),s.appendChild(d);const l=document.createElement("iframe");l.src=t,l.title="Copilot chat widget",l.allow="clipboard-read; clipboard-write; microphone; camera; display-capture",l.setAttribute("scrolling","no"),Object.assign(l.style,{width:"100%",height:"100%",border:"none",display:"block",background:"transparent",overflow:"hidden"}),s.appendChild(d),d.appendChild(l),r.appendChild(i),r.appendChild(d),document.body.appendChild(e),document.body.appendChild(r);let p=!1;const u=()=>{p&&(p=!1,r.style.opacity="0",r.style.transform="scale(0.8) translateY(20px)",i.style.display="none",setTimeout(()=>{r.style.display="none"},250),e.style.transform="scale(1)")};e.onclick=h=>{h.stopPropagation(),p=!p,p?(r.style.display="block",i.style.display="block",requestAnimationFrame(()=>{r.style.opacity="1",r.style.transform="scale(1) translateY(0)"})):u()},window.addEventListener("message",h=>{h?.data?.type==="CHAT_CLOSED"&&u()}),document.addEventListener("click",h=>{const g=h.target;g&&p&&!r.contains(g)&&g!==e&&u()});const w={close:u,open:()=>{p||e.click()}};return window.CopilotChat=window.CopilotChat||{},window.CopilotChat.close=w.close,window.CopilotChat.open=w.open,window.CopilotChat.controls=w,w},f=t=>{console.error(`[CopilotChat] ${t}`)},L=()=>{const t=k();if(!t)return!1;const o=x(t),n=t.dataset||{},a=n.token||o.token,s=typeof window<"u"&&window.CopilotChatConfig&&window.CopilotChatConfig.token;return(a||s)&&n.autoload!=="false"},v=async(t={})=>{const o=t.scriptEl||k(),n=window.CopilotChatConfig||{},a=o?.dataset||{},s=x(o),e=t.token||n.token||a.token||s.token;if(!e)return f("Missing token (provide via init config, window.CopilotChatConfig.token, or data-token attribute)."),null;const r=t.baseUrl||n.baseUrl||a.baseUrl||s.baseUrl||U(o)||typeof window<"u"&&window.location?.origin||null;if(!r)return f("Unable to resolve base URL from embedding script or window.location."),null;try{const i=await fetch(`${r}/api/chat-widget/config?token=${encodeURIComponent(e)}`,{credentials:"omit",mode:"cors"});if(!i.ok)throw new Error(`Server responded with ${i.status}`);const c=await i.json();if(!c?.iframeUrl||!c?.launcherIcon)throw new Error("Received incomplete widget configuration from server.");return window.CopilotChat=window.CopilotChat||{},window.CopilotChat.init=(d={})=>{const l={iframeUrl:d.iframeUrl||c.iframeUrl,launcherIcon:d.launcherIcon||c.launcherIcon};return S(l)},window.CopilotChat.init(t)}catch(i){return f(i instanceof Error?i.message:"Unknown error during widget bootstrap."),null}};L()&&E(()=>{v()}),window.CopilotChat=window.CopilotChat||{},window.CopilotChat.load=v})()})();
7
+ `,Object.assign(e.style,{position:"fixed",bottom:"24px",right:"24px",width:`${m}px`,height:`${m}px`,borderRadius:"50%",border:"none",background:"linear-gradient(135deg, #0078ff, #00c6ff)",color:"white",cursor:"pointer",zIndex:999998,display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 6px 14px rgba(0,0,0,0.25)",transition:"all 0.25s ease"}),e.onmouseover=()=>{e.style.transform="scale(1.12)",e.style.boxShadow="0 10px 25px rgba(0,0,0,0.3)"},e.onmouseout=()=>{e.style.transform="scale(1)",e.style.boxShadow="0 6px 14px rgba(0,0,0,0.25)"};const r=document.createElement("div");r.setAttribute("data-copilot-widget-root","true"),Object.assign(r.style,{display:"none",position:"fixed",bottom:`${m+36}px`,right:"24px",zIndex:"999999",transformOrigin:"bottom right",transform:"scale(0.8) translateY(20px)",opacity:"0",transition:"all 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55)"});const i=document.createElement("div"),l=document.createElement("div"),b=document.createElement("div");Object.assign(i.style,{position:"absolute",bottom:"-14px",right:"28px",width:"30px",height:"20px",pointerEvents:"none",display:"none",zIndex:"1"}),Object.assign(l.style,{position:"absolute",bottom:"0",left:"0",right:"0",margin:"0 auto",width:"0",height:"0",borderLeft:"15px solid transparent",borderRight:"15px solid transparent",borderTop:"15px solid rgba(15,23,42,0.1)"}),Object.assign(b.style,{position:"absolute",bottom:"2px",left:"0",right:"0",margin:"0 auto",width:"0",height:"0",borderLeft:"13px solid transparent",borderRight:"13px solid transparent",borderTop:"13px solid white",boxShadow:"0 6px 16px rgba(15,23,42,0.12)",borderRadius:"2px"}),i.appendChild(l),i.appendChild(b);const d=document.createElement("div");Object.assign(d.style,{width:`${C}px`,maxWidth:"calc(100vw - 48px)",height:`${Math.min(C,Math.max(320,window.innerHeight-140))}px`,maxHeight:"calc(100vh - 150px)",borderRadius:"20px",background:"white",border:"1px solid rgba(15,23,42,0.12)",boxShadow:"0 18px 45px rgba(15,23,42,0.16)",overflow:"hidden"}),s.appendChild(d);const c=document.createElement("iframe");c.src=t,c.title="Copilot chat widget",c.allow="clipboard-read; clipboard-write; microphone; camera; display-capture",c.setAttribute("scrolling","no"),Object.assign(c.style,{width:"100%",height:"100%",border:"none",display:"block",background:"transparent",overflow:"hidden"}),s.appendChild(d),d.appendChild(c),r.appendChild(i),r.appendChild(d),document.body.appendChild(e),document.body.appendChild(r);let p=!1;const u=()=>{p&&(p=!1,r.style.opacity="0",r.style.transform="scale(0.8) translateY(20px)",i.style.display="none",setTimeout(()=>{r.style.display="none"},250),e.style.transform="scale(1)")};e.onclick=h=>{h.stopPropagation(),p=!p,p?(r.style.display="block",i.style.display="block",requestAnimationFrame(()=>{r.style.opacity="1",r.style.transform="scale(1) translateY(0)"})):u()},window.addEventListener("message",h=>{h?.data?.type==="CHAT_CLOSED"&&u()}),document.addEventListener("click",h=>{const g=h.target;g&&p&&!r.contains(g)&&g!==e&&u()});const w={close:u,open:()=>{p||e.click()}};return window.CopilotChat=window.CopilotChat||{},window.CopilotChat.close=w.close,window.CopilotChat.open=w.open,window.CopilotChat.controls=w,w},f=t=>{console.error(`[CopilotChat] ${t}`)},R=()=>{const t=k();if(!t)return!1;const o=x(t),n=t.dataset||{},a=n.token||o.token,s=typeof window<"u"&&window.CopilotChatConfig&&window.CopilotChatConfig.token;return(a||s)&&n.autoload!=="false"},v=async(t={})=>{const o=t.scriptEl||k(),n=window.CopilotChatConfig||{},a=o?.dataset||{},s=x(o),e=t.token||n.token||a.token||s.token;if(!e)return f("Missing token (provide via init config, window.CopilotChatConfig.token, or data-token attribute)."),null;const r=t.baseUrl||n.baseUrl||a.baseUrl||s.baseUrl||E||S(o)||typeof window<"u"&&window.location?.origin||null;if(!r)return f("Unable to resolve base URL from embedding script or window.location."),null;try{const i=await fetch(`${r}/api/chat-widget/config?token=${encodeURIComponent(e)}`,{credentials:"omit",mode:"cors"});if(!i.ok)throw new Error(`Server responded with ${i.status}`);const l=await i.json();if(!l?.iframeUrl||!l?.launcherIcon)throw new Error("Received incomplete widget configuration from server.");return window.CopilotChat=window.CopilotChat||{},window.CopilotChat.init=(d={})=>{const c={iframeUrl:d.iframeUrl||l.iframeUrl,launcherIcon:d.launcherIcon||l.launcherIcon};return L(c)},window.CopilotChat.init(t)}catch(i){return f(i instanceof Error?i.message:"Unknown error during widget bootstrap."),null}};R()&&U(()=>{v()}),window.CopilotChat=window.CopilotChat||{},window.CopilotChat.load=v})()})();
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});var d=typeof document<"u"?document.currentScript:null;function l(n={}){if(typeof window>"u"||typeof document>"u")return null;const{token:o,autoload:i,baseUrl:a}=n;window.CopilotChatConfig={...window.CopilotChatConfig,...n};const t=document.getElementById("copilot-chat-widget-loader");if(t)return o&&(t.dataset.token=o),a&&(t.dataset.baseUrl=a),i===!1&&(t.dataset.autoload="false"),t;const e=document.createElement("script");return e.id="copilot-chat-widget-loader",e.src=new URL("./chat-widget.min.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:d&&d.tagName.toUpperCase()==="SCRIPT"&&d.src||new URL("index.cjs",document.baseURI).href).href,e.async=!0,o&&(e.dataset.token=o),a&&(e.dataset.baseUrl=a),i===!1&&(e.dataset.autoload="false"),document.body.appendChild(e),e}exports.default=l;exports.loadCopilotChatWidget=l;
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});var d=typeof document<"u"?document.currentScript:null;const r=void 0;function l(n={}){if(typeof window>"u"||typeof document>"u")return null;const{token:a,autoload:i,baseUrl:t=r}=n;window.CopilotChatConfig={...window.CopilotChatConfig,...n,baseUrl:t||window.CopilotChatConfig?.baseUrl||void 0};const o=document.getElementById("copilot-chat-widget-loader");if(o)return a&&(o.dataset.token=a),t&&(o.dataset.baseUrl=t),i===!1&&(o.dataset.autoload="false"),o;const e=document.createElement("script");return e.id="copilot-chat-widget-loader",e.src=new URL("./chat-widget.min.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:d&&d.tagName.toUpperCase()==="SCRIPT"&&d.src||new URL("index.cjs",document.baseURI).href).href,e.async=!0,a&&(e.dataset.token=a),t&&(e.dataset.baseUrl=t),i===!1&&(e.dataset.autoload="false"),document.body.appendChild(e),e}exports.default=l;exports.loadCopilotChatWidget=l;
package/dist/index.mjs CHANGED
@@ -1,16 +1,17 @@
1
- function n(d = {}) {
1
+ function n(i = {}) {
2
2
  if (typeof window > "u" || typeof document > "u")
3
3
  return null;
4
- const { token: a, autoload: i, baseUrl: o } = d;
4
+ const { token: a, autoload: d, baseUrl: e = void 0 } = i;
5
5
  window.CopilotChatConfig = {
6
6
  ...window.CopilotChatConfig,
7
- ...d
7
+ ...i,
8
+ baseUrl: e || window.CopilotChatConfig?.baseUrl || void 0
8
9
  };
9
- const e = document.getElementById("copilot-chat-widget-loader");
10
- if (e)
11
- return a && (e.dataset.token = a), o && (e.dataset.baseUrl = o), i === !1 && (e.dataset.autoload = "false"), e;
10
+ const o = document.getElementById("copilot-chat-widget-loader");
11
+ if (o)
12
+ return a && (o.dataset.token = a), e && (o.dataset.baseUrl = e), d === !1 && (o.dataset.autoload = "false"), o;
12
13
  const t = document.createElement("script");
13
- return t.id = "copilot-chat-widget-loader", t.src = new URL("./chat-widget.min.js", import.meta.url).href, t.async = !0, a && (t.dataset.token = a), o && (t.dataset.baseUrl = o), i === !1 && (t.dataset.autoload = "false"), document.body.appendChild(t), t;
14
+ return t.id = "copilot-chat-widget-loader", t.src = new URL("./chat-widget.min.js", import.meta.url).href, t.async = !0, a && (t.dataset.token = a), e && (t.dataset.baseUrl = e), d === !1 && (t.dataset.autoload = "false"), document.body.appendChild(t), t;
14
15
  }
15
16
  export {
16
17
  n as default,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "copilot-chat-widget",
3
- "version": "0.1.5",
3
+ "version": "0.1.7",
4
4
  "description": "Embeddable Copilot chat widget that can be loaded via NPM or a script tag.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
package/src/index.d.ts CHANGED
@@ -1,8 +1,8 @@
1
- export interface CopilotChatOptions {
2
- token: string;
3
- autoload?: boolean;
4
- baseUrl?: string;
5
- }
6
-
7
- export function loadCopilotChatWidget(options: CopilotChatOptions): HTMLScriptElement | null;
8
- export default loadCopilotChatWidget;
1
+ export interface CopilotChatOptions {
2
+ token: string;
3
+ autoload?: boolean;
4
+ baseUrl?: string;
5
+ }
6
+
7
+ export function loadCopilotChatWidget(options: CopilotChatOptions): HTMLScriptElement | null;
8
+ export default loadCopilotChatWidget;
package/src/index.js CHANGED
@@ -1,34 +1,40 @@
1
+ const BUILD_BASE_URL =
2
+ typeof __WIDGET_BASE_URL__ !== "undefined" && __WIDGET_BASE_URL__
3
+ ? __WIDGET_BASE_URL__
4
+ : undefined;
5
+
1
6
  export function loadCopilotChatWidget(options = {}) {
2
7
  if (typeof window === "undefined" || typeof document === "undefined") {
3
8
  return null;
4
9
  }
5
10
 
6
- const { token, autoload, baseUrl } = options;
11
+ const { token, autoload, baseUrl = BUILD_BASE_URL } = options;
7
12
 
8
13
  // persist config for runtime script
9
14
  window.CopilotChatConfig = {
10
15
  ...window.CopilotChatConfig,
11
16
  ...options,
17
+ baseUrl: baseUrl || window.CopilotChatConfig?.baseUrl || undefined,
12
18
  };
13
-
14
- const existing = document.getElementById("copilot-chat-widget-loader");
15
- if (existing) {
16
- if (token) existing.dataset.token = token;
17
- if (baseUrl) existing.dataset.baseUrl = baseUrl;
18
- if (autoload === false) existing.dataset.autoload = "false";
19
- return existing;
20
- }
21
-
22
- const script = document.createElement("script");
23
- script.id = "copilot-chat-widget-loader";
24
- script.src = new URL("./chat-widget.min.js", import.meta.url).href;
25
- script.async = true;
26
- if (token) script.dataset.token = token;
27
- if (baseUrl) script.dataset.baseUrl = baseUrl;
28
- if (autoload === false) script.dataset.autoload = "false";
29
-
30
- document.body.appendChild(script);
31
- return script;
32
- }
33
-
34
- export default loadCopilotChatWidget;
19
+
20
+ const existing = document.getElementById("copilot-chat-widget-loader");
21
+ if (existing) {
22
+ if (token) existing.dataset.token = token;
23
+ if (baseUrl) existing.dataset.baseUrl = baseUrl;
24
+ if (autoload === false) existing.dataset.autoload = "false";
25
+ return existing;
26
+ }
27
+
28
+ const script = document.createElement("script");
29
+ script.id = "copilot-chat-widget-loader";
30
+ script.src = new URL("./chat-widget.min.js", import.meta.url).href;
31
+ script.async = true;
32
+ if (token) script.dataset.token = token;
33
+ if (baseUrl) script.dataset.baseUrl = baseUrl;
34
+ if (autoload === false) script.dataset.autoload = "false";
35
+
36
+ document.body.appendChild(script);
37
+ return script;
38
+ }
39
+
40
+ export default loadCopilotChatWidget;
@@ -1,349 +1,354 @@
1
- (() => {
1
+ (() => {
2
2
  if (typeof window === "undefined" || typeof document === "undefined") return;
3
3
  if (window.__copilotWidgetLoaded) return;
4
4
  window.__copilotWidgetLoaded = true;
5
5
 
6
+ const BUILD_BASE_URL =
7
+ typeof __WIDGET_BASE_URL__ !== "undefined" && __WIDGET_BASE_URL__
8
+ ? __WIDGET_BASE_URL__
9
+ : undefined;
6
10
  const BUTTON_SIZE = 64;
7
11
  const IFRAME_SIZE = 720;
8
12
  const embeddingScript = document.currentScript;
9
-
10
- const readQueryConfig = (scriptEl) => {
11
- if (!scriptEl?.src) return {};
12
- try {
13
- const url = new URL(scriptEl.src, window.location.href);
14
- const params = {};
15
- url.searchParams.forEach((value, key) => {
16
- params[key] = value;
17
- });
18
- return params;
19
- } catch (error) {
20
- console.warn("[CopilotChat] Failed to parse script query params:", error);
21
- return {};
22
- }
23
- };
24
-
25
- const ready = (fn) => {
26
- if (document.readyState === "complete" || document.readyState === "interactive") {
27
- setTimeout(fn, 0);
28
- } else {
29
- document.addEventListener("DOMContentLoaded", fn);
30
- }
31
- };
32
-
33
- const inferBaseUrlFromScript = (scriptEl) => {
34
- if (!scriptEl?.src) return null;
35
- try {
36
- const srcUrl = new URL(scriptEl.src, window.location.href);
37
- return `${srcUrl.protocol}//${srcUrl.host}`;
38
- } catch (error) {
39
- console.warn("[CopilotChat] Unable to infer base URL from script source.", error);
40
- return null;
41
- }
42
- };
43
-
44
- const resolveEmbeddingScript = () => {
45
- if (embeddingScript) {
46
- return embeddingScript;
47
- }
48
-
49
- const scripts = Array.from(document.querySelectorAll("script"));
50
- const candidate = scripts
51
- .reverse()
52
- .find((script) => script.dataset?.token || (script.src && script.src.includes("chat-widget")));
53
-
54
- return candidate || null;
55
- };
56
-
57
- const buildWidget = ({ iframeUrl, launcherIcon }) => {
58
- const existingRoot = document.querySelector("[data-copilot-widget-root]");
59
- if (existingRoot) {
60
- existingRoot.remove();
61
- }
62
-
63
- // ---------- Shadow DOM container ----------
64
- const containerHost = document.createElement("div");
65
- containerHost.setAttribute("data-copilot-widget-root", "true");
66
- const shadow = containerHost.attachShadow({ mode: "open" });
67
- document.body.appendChild(containerHost);
68
-
69
- // ---------- Button ----------
70
- const btn = document.createElement("button");
71
- btn.type = "button";
72
- btn.setAttribute("aria-label", "Open Copilot chat");
73
- btn.innerHTML = `
74
- <img
75
- src="${launcherIcon}"
76
- alt="Copilot chat launcher"
77
- style="width: 38px; height: 38px; object-fit: contain; border-radius: 50%; pointer-events: none;"
78
- />
79
- `;
80
-
81
- Object.assign(btn.style, {
82
- position: "fixed",
83
- bottom: "24px",
84
- right: "24px",
85
- width: `${BUTTON_SIZE}px`,
86
- height: `${BUTTON_SIZE}px`,
87
- borderRadius: "50%",
88
- border: "none",
89
- background: "linear-gradient(135deg, #0078ff, #00c6ff)",
90
- color: "white",
91
- cursor: "pointer",
92
- zIndex: 999998,
93
- display: "flex",
94
- alignItems: "center",
95
- justifyContent: "center",
96
- boxShadow: "0 6px 14px rgba(0,0,0,0.25)",
97
- transition: "all 0.25s ease",
98
- });
99
-
100
- btn.onmouseover = () => {
101
- btn.style.transform = "scale(1.12)";
102
- btn.style.boxShadow = "0 10px 25px rgba(0,0,0,0.3)";
103
- };
104
- btn.onmouseout = () => {
105
- btn.style.transform = "scale(1)";
106
- btn.style.boxShadow = "0 6px 14px rgba(0,0,0,0.25)";
107
- };
108
-
109
- const container = document.createElement("div");
110
- container.setAttribute("data-copilot-widget-root", "true");
111
- Object.assign(container.style, {
112
- display: "none",
113
- position: "fixed",
114
- bottom: `${BUTTON_SIZE + 36}px`,
115
- right: "24px",
116
- zIndex: "999999",
117
- transformOrigin: "bottom right",
118
- transform: "scale(0.8) translateY(20px)",
119
- opacity: "0",
120
- transition: "all 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55)",
121
- });
122
-
123
- const arrow = document.createElement("div");
124
- const arrowBorder = document.createElement("div");
125
- const arrowFill = document.createElement("div");
126
-
127
- Object.assign(arrow.style, {
128
- position: "absolute",
129
- bottom: "-14px",
130
- right: "28px",
131
- width: "30px",
132
- height: "20px",
133
- pointerEvents: "none",
134
- display: "none",
135
- zIndex: "1",
136
- });
137
-
138
- Object.assign(arrowBorder.style, {
139
- position: "absolute",
140
- bottom: "0",
141
- left: "0",
142
- right: "0",
143
- margin: "0 auto",
144
- width: "0",
145
- height: "0",
146
- borderLeft: "15px solid transparent",
147
- borderRight: "15px solid transparent",
148
- borderTop: "15px solid rgba(15,23,42,0.1)",
149
- });
150
-
151
- Object.assign(arrowFill.style, {
152
- position: "absolute",
153
- bottom: "2px",
154
- left: "0",
155
- right: "0",
156
- margin: "0 auto",
157
- width: "0",
158
- height: "0",
159
- borderLeft: "13px solid transparent",
160
- borderRight: "13px solid transparent",
161
- borderTop: "13px solid white",
162
- boxShadow: "0 6px 16px rgba(15,23,42,0.12)",
163
- borderRadius: "2px",
164
- });
165
-
166
- arrow.appendChild(arrowBorder);
167
- arrow.appendChild(arrowFill);
168
-
169
- const frameWrapper = document.createElement("div");
170
- Object.assign(frameWrapper.style, {
171
- width: `${IFRAME_SIZE}px`,
172
- maxWidth: "calc(100vw - 48px)",
173
- // keep height responsive to viewport to avoid outer scrollbars
174
- height: `${Math.min(IFRAME_SIZE, Math.max(320, window.innerHeight - 140))}px`,
175
- maxHeight: "calc(100vh - 150px)",
176
- borderRadius: "20px",
177
- background: "white",
178
- border: "1px solid rgba(15,23,42,0.12)",
179
- boxShadow: "0 18px 45px rgba(15,23,42,0.16)",
180
- overflow: "hidden",
181
- });
182
- shadow.appendChild(frameWrapper);
183
-
184
- const iframe = document.createElement("iframe");
185
- iframe.src = iframeUrl;
186
- iframe.title = "Copilot chat widget";
187
- iframe.allow = "clipboard-read; clipboard-write; microphone; camera; display-capture";
188
- iframe.setAttribute("scrolling", "no");
189
- Object.assign(iframe.style, {
190
- width: "100%",
191
- height: "100%",
192
- border: "none",
193
- display: "block",
194
- background: "transparent",
195
- overflow: "hidden",
196
- });
197
-
198
- shadow.appendChild(frameWrapper);
199
- frameWrapper.appendChild(iframe);
200
-
201
- container.appendChild(arrow);
202
- container.appendChild(frameWrapper);
203
- document.body.appendChild(btn);
204
- document.body.appendChild(container);
205
-
206
- let isOpen = false;
207
-
208
- const closeChat = () => {
209
- if (!isOpen) return;
210
- isOpen = false;
211
- container.style.opacity = "0";
212
- container.style.transform = "scale(0.8) translateY(20px)";
213
- arrow.style.display = "none";
214
- setTimeout(() => {
215
- container.style.display = "none";
216
- }, 250);
217
- btn.style.transform = "scale(1)";
218
- };
219
-
220
- btn.onclick = (event) => {
221
- event.stopPropagation();
222
- isOpen = !isOpen;
223
- if (isOpen) {
224
- container.style.display = "block";
225
- arrow.style.display = "block";
226
- requestAnimationFrame(() => {
227
- container.style.opacity = "1";
228
- container.style.transform = "scale(1) translateY(0)";
229
- });
230
- } else {
231
- closeChat();
232
- }
233
- };
234
-
235
- window.addEventListener("message", (event) => {
236
- if (event?.data?.type === "CHAT_CLOSED") {
237
- closeChat();
238
- }
239
- });
240
-
241
- document.addEventListener("click", (event) => {
242
- const target = event.target;
243
- if (!target) return;
244
- if (isOpen && !container.contains(target) && target !== btn) {
245
- closeChat();
246
- }
247
- });
248
-
249
- const controls = {
250
- close: closeChat,
251
- open: () => {
252
- if (!isOpen) {
253
- btn.click();
254
- }
255
- },
256
- };
257
-
258
- window.CopilotChat = window.CopilotChat || {};
259
- window.CopilotChat.close = controls.close;
260
- window.CopilotChat.open = controls.open;
261
- window.CopilotChat.controls = controls;
262
-
263
- return controls;
264
- };
265
-
266
- const handleError = (message) => {
267
- console.error(`[CopilotChat] ${message}`);
268
- };
269
-
270
- const shouldAutoBootstrapFromScript = () => {
271
- const scriptEl = resolveEmbeddingScript();
272
- if (!scriptEl) return false;
273
- const queryConfig = readQueryConfig(scriptEl);
274
- const dataset = scriptEl.dataset || {};
275
- const hasTokenHint = dataset.token || queryConfig.token;
276
- const hasGlobalToken = typeof window !== "undefined" && window.CopilotChatConfig && window.CopilotChatConfig.token;
277
- return (hasTokenHint || hasGlobalToken) && dataset.autoload !== "false";
278
- };
279
-
280
- const initCopilotChatWidget = async (config = {}) => {
281
- const scriptEl = config.scriptEl || resolveEmbeddingScript();
282
- const globalConfig = window.CopilotChatConfig || {};
283
- const datasetConfig = scriptEl?.dataset || {};
284
- const queryConfig = readQueryConfig(scriptEl);
285
-
286
- const token = config.token || globalConfig.token || datasetConfig.token || queryConfig.token;
287
-
288
- if (!token) {
289
- handleError("Missing token (provide via init config, window.CopilotChatConfig.token, or data-token attribute).");
290
- return null;
291
- }
292
-
13
+
14
+ const readQueryConfig = (scriptEl) => {
15
+ if (!scriptEl?.src) return {};
16
+ try {
17
+ const url = new URL(scriptEl.src, window.location.href);
18
+ const params = {};
19
+ url.searchParams.forEach((value, key) => {
20
+ params[key] = value;
21
+ });
22
+ return params;
23
+ } catch (error) {
24
+ console.warn("[CopilotChat] Failed to parse script query params:", error);
25
+ return {};
26
+ }
27
+ };
28
+
29
+ const ready = (fn) => {
30
+ if (document.readyState === "complete" || document.readyState === "interactive") {
31
+ setTimeout(fn, 0);
32
+ } else {
33
+ document.addEventListener("DOMContentLoaded", fn);
34
+ }
35
+ };
36
+
37
+ const inferBaseUrlFromScript = (scriptEl) => {
38
+ if (!scriptEl?.src) return null;
39
+ try {
40
+ const srcUrl = new URL(scriptEl.src, window.location.href);
41
+ return `${srcUrl.protocol}//${srcUrl.host}`;
42
+ } catch (error) {
43
+ console.warn("[CopilotChat] Unable to infer base URL from script source.", error);
44
+ return null;
45
+ }
46
+ };
47
+
48
+ const resolveEmbeddingScript = () => {
49
+ if (embeddingScript) {
50
+ return embeddingScript;
51
+ }
52
+
53
+ const scripts = Array.from(document.querySelectorAll("script"));
54
+ const candidate = scripts
55
+ .reverse()
56
+ .find((script) => script.dataset?.token || (script.src && script.src.includes("chat-widget")));
57
+
58
+ return candidate || null;
59
+ };
60
+
61
+ const buildWidget = ({ iframeUrl, launcherIcon }) => {
62
+ const existingRoot = document.querySelector("[data-copilot-widget-root]");
63
+ if (existingRoot) {
64
+ existingRoot.remove();
65
+ }
66
+
67
+ // ---------- Shadow DOM container ----------
68
+ const containerHost = document.createElement("div");
69
+ containerHost.setAttribute("data-copilot-widget-root", "true");
70
+ const shadow = containerHost.attachShadow({ mode: "open" });
71
+ document.body.appendChild(containerHost);
72
+
73
+ // ---------- Button ----------
74
+ const btn = document.createElement("button");
75
+ btn.type = "button";
76
+ btn.setAttribute("aria-label", "Open Copilot chat");
77
+ btn.innerHTML = `
78
+ <img
79
+ src="${launcherIcon}"
80
+ alt="Copilot chat launcher"
81
+ style="width: 38px; height: 38px; object-fit: contain; border-radius: 50%; pointer-events: none;"
82
+ />
83
+ `;
84
+
85
+ Object.assign(btn.style, {
86
+ position: "fixed",
87
+ bottom: "24px",
88
+ right: "24px",
89
+ width: `${BUTTON_SIZE}px`,
90
+ height: `${BUTTON_SIZE}px`,
91
+ borderRadius: "50%",
92
+ border: "none",
93
+ background: "linear-gradient(135deg, #0078ff, #00c6ff)",
94
+ color: "white",
95
+ cursor: "pointer",
96
+ zIndex: 999998,
97
+ display: "flex",
98
+ alignItems: "center",
99
+ justifyContent: "center",
100
+ boxShadow: "0 6px 14px rgba(0,0,0,0.25)",
101
+ transition: "all 0.25s ease",
102
+ });
103
+
104
+ btn.onmouseover = () => {
105
+ btn.style.transform = "scale(1.12)";
106
+ btn.style.boxShadow = "0 10px 25px rgba(0,0,0,0.3)";
107
+ };
108
+ btn.onmouseout = () => {
109
+ btn.style.transform = "scale(1)";
110
+ btn.style.boxShadow = "0 6px 14px rgba(0,0,0,0.25)";
111
+ };
112
+
113
+ const container = document.createElement("div");
114
+ container.setAttribute("data-copilot-widget-root", "true");
115
+ Object.assign(container.style, {
116
+ display: "none",
117
+ position: "fixed",
118
+ bottom: `${BUTTON_SIZE + 36}px`,
119
+ right: "24px",
120
+ zIndex: "999999",
121
+ transformOrigin: "bottom right",
122
+ transform: "scale(0.8) translateY(20px)",
123
+ opacity: "0",
124
+ transition: "all 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55)",
125
+ });
126
+
127
+ const arrow = document.createElement("div");
128
+ const arrowBorder = document.createElement("div");
129
+ const arrowFill = document.createElement("div");
130
+
131
+ Object.assign(arrow.style, {
132
+ position: "absolute",
133
+ bottom: "-14px",
134
+ right: "28px",
135
+ width: "30px",
136
+ height: "20px",
137
+ pointerEvents: "none",
138
+ display: "none",
139
+ zIndex: "1",
140
+ });
141
+
142
+ Object.assign(arrowBorder.style, {
143
+ position: "absolute",
144
+ bottom: "0",
145
+ left: "0",
146
+ right: "0",
147
+ margin: "0 auto",
148
+ width: "0",
149
+ height: "0",
150
+ borderLeft: "15px solid transparent",
151
+ borderRight: "15px solid transparent",
152
+ borderTop: "15px solid rgba(15,23,42,0.1)",
153
+ });
154
+
155
+ Object.assign(arrowFill.style, {
156
+ position: "absolute",
157
+ bottom: "2px",
158
+ left: "0",
159
+ right: "0",
160
+ margin: "0 auto",
161
+ width: "0",
162
+ height: "0",
163
+ borderLeft: "13px solid transparent",
164
+ borderRight: "13px solid transparent",
165
+ borderTop: "13px solid white",
166
+ boxShadow: "0 6px 16px rgba(15,23,42,0.12)",
167
+ borderRadius: "2px",
168
+ });
169
+
170
+ arrow.appendChild(arrowBorder);
171
+ arrow.appendChild(arrowFill);
172
+
173
+ const frameWrapper = document.createElement("div");
174
+ Object.assign(frameWrapper.style, {
175
+ width: `${IFRAME_SIZE}px`,
176
+ maxWidth: "calc(100vw - 48px)",
177
+ // keep height responsive to viewport to avoid outer scrollbars
178
+ height: `${Math.min(IFRAME_SIZE, Math.max(320, window.innerHeight - 140))}px`,
179
+ maxHeight: "calc(100vh - 150px)",
180
+ borderRadius: "20px",
181
+ background: "white",
182
+ border: "1px solid rgba(15,23,42,0.12)",
183
+ boxShadow: "0 18px 45px rgba(15,23,42,0.16)",
184
+ overflow: "hidden",
185
+ });
186
+ shadow.appendChild(frameWrapper);
187
+
188
+ const iframe = document.createElement("iframe");
189
+ iframe.src = iframeUrl;
190
+ iframe.title = "Copilot chat widget";
191
+ iframe.allow = "clipboard-read; clipboard-write; microphone; camera; display-capture";
192
+ iframe.setAttribute("scrolling", "no");
193
+ Object.assign(iframe.style, {
194
+ width: "100%",
195
+ height: "100%",
196
+ border: "none",
197
+ display: "block",
198
+ background: "transparent",
199
+ overflow: "hidden",
200
+ });
201
+
202
+ shadow.appendChild(frameWrapper);
203
+ frameWrapper.appendChild(iframe);
204
+
205
+ container.appendChild(arrow);
206
+ container.appendChild(frameWrapper);
207
+ document.body.appendChild(btn);
208
+ document.body.appendChild(container);
209
+
210
+ let isOpen = false;
211
+
212
+ const closeChat = () => {
213
+ if (!isOpen) return;
214
+ isOpen = false;
215
+ container.style.opacity = "0";
216
+ container.style.transform = "scale(0.8) translateY(20px)";
217
+ arrow.style.display = "none";
218
+ setTimeout(() => {
219
+ container.style.display = "none";
220
+ }, 250);
221
+ btn.style.transform = "scale(1)";
222
+ };
223
+
224
+ btn.onclick = (event) => {
225
+ event.stopPropagation();
226
+ isOpen = !isOpen;
227
+ if (isOpen) {
228
+ container.style.display = "block";
229
+ arrow.style.display = "block";
230
+ requestAnimationFrame(() => {
231
+ container.style.opacity = "1";
232
+ container.style.transform = "scale(1) translateY(0)";
233
+ });
234
+ } else {
235
+ closeChat();
236
+ }
237
+ };
238
+
239
+ window.addEventListener("message", (event) => {
240
+ if (event?.data?.type === "CHAT_CLOSED") {
241
+ closeChat();
242
+ }
243
+ });
244
+
245
+ document.addEventListener("click", (event) => {
246
+ const target = event.target;
247
+ if (!target) return;
248
+ if (isOpen && !container.contains(target) && target !== btn) {
249
+ closeChat();
250
+ }
251
+ });
252
+
253
+ const controls = {
254
+ close: closeChat,
255
+ open: () => {
256
+ if (!isOpen) {
257
+ btn.click();
258
+ }
259
+ },
260
+ };
261
+
262
+ window.CopilotChat = window.CopilotChat || {};
263
+ window.CopilotChat.close = controls.close;
264
+ window.CopilotChat.open = controls.open;
265
+ window.CopilotChat.controls = controls;
266
+
267
+ return controls;
268
+ };
269
+
270
+ const handleError = (message) => {
271
+ console.error(`[CopilotChat] ${message}`);
272
+ };
273
+
274
+ const shouldAutoBootstrapFromScript = () => {
275
+ const scriptEl = resolveEmbeddingScript();
276
+ if (!scriptEl) return false;
277
+ const queryConfig = readQueryConfig(scriptEl);
278
+ const dataset = scriptEl.dataset || {};
279
+ const hasTokenHint = dataset.token || queryConfig.token;
280
+ const hasGlobalToken = typeof window !== "undefined" && window.CopilotChatConfig && window.CopilotChatConfig.token;
281
+ return (hasTokenHint || hasGlobalToken) && dataset.autoload !== "false";
282
+ };
283
+
284
+ const initCopilotChatWidget = async (config = {}) => {
285
+ const scriptEl = config.scriptEl || resolveEmbeddingScript();
286
+ const globalConfig = window.CopilotChatConfig || {};
287
+ const datasetConfig = scriptEl?.dataset || {};
288
+ const queryConfig = readQueryConfig(scriptEl);
289
+
290
+ const token = config.token || globalConfig.token || datasetConfig.token || queryConfig.token;
291
+
292
+ if (!token) {
293
+ handleError("Missing token (provide via init config, window.CopilotChatConfig.token, or data-token attribute).");
294
+ return null;
295
+ }
296
+
293
297
  const baseUrl =
294
298
  config.baseUrl ||
295
299
  globalConfig.baseUrl ||
296
300
  datasetConfig.baseUrl ||
297
301
  queryConfig.baseUrl ||
302
+ BUILD_BASE_URL ||
298
303
  inferBaseUrlFromScript(scriptEl) ||
299
304
  (typeof window !== "undefined" && window.location?.origin) ||
300
305
  null;
301
-
302
- if (!baseUrl) {
303
- handleError("Unable to resolve base URL from embedding script or window.location.");
304
- return null;
305
- }
306
-
307
- try {
308
- const response = await fetch(`${baseUrl}/api/chat-widget/config?token=${encodeURIComponent(token)}`, {
309
- credentials: "omit",
310
- mode: "cors",
311
- });
312
-
313
- if (!response.ok) {
314
- throw new Error(`Server responded with ${response.status}`);
315
- }
316
-
317
- const remoteConfig = await response.json();
318
- if (!remoteConfig?.iframeUrl || !remoteConfig?.launcherIcon) {
319
- throw new Error("Received incomplete widget configuration from server.");
320
- }
321
-
322
- window.CopilotChat = window.CopilotChat || {};
323
- window.CopilotChat.init = (overrides = {}) => {
324
- const mergedConfig = {
325
- iframeUrl: overrides.iframeUrl || remoteConfig.iframeUrl,
326
- launcherIcon: overrides.launcherIcon || remoteConfig.launcherIcon,
327
- };
328
-
329
- return buildWidget(mergedConfig);
330
- };
331
-
332
- const controls = window.CopilotChat.init(config);
333
- return controls;
334
- } catch (error) {
335
- handleError(error instanceof Error ? error.message : "Unknown error during widget bootstrap.");
336
- return null;
337
- }
338
- };
339
-
340
- if (shouldAutoBootstrapFromScript()) {
341
- ready(() => {
342
- initCopilotChatWidget();
343
- });
344
- }
345
-
346
- // expose for manual bootstrap if autoload=false
347
- window.CopilotChat = window.CopilotChat || {};
348
- window.CopilotChat.load = initCopilotChatWidget;
349
- })();
306
+
307
+ if (!baseUrl) {
308
+ handleError("Unable to resolve base URL from embedding script or window.location.");
309
+ return null;
310
+ }
311
+
312
+ try {
313
+ const response = await fetch(`${baseUrl}/api/chat-widget/config?token=${encodeURIComponent(token)}`, {
314
+ credentials: "omit",
315
+ mode: "cors",
316
+ });
317
+
318
+ if (!response.ok) {
319
+ throw new Error(`Server responded with ${response.status}`);
320
+ }
321
+
322
+ const remoteConfig = await response.json();
323
+ if (!remoteConfig?.iframeUrl || !remoteConfig?.launcherIcon) {
324
+ throw new Error("Received incomplete widget configuration from server.");
325
+ }
326
+
327
+ window.CopilotChat = window.CopilotChat || {};
328
+ window.CopilotChat.init = (overrides = {}) => {
329
+ const mergedConfig = {
330
+ iframeUrl: overrides.iframeUrl || remoteConfig.iframeUrl,
331
+ launcherIcon: overrides.launcherIcon || remoteConfig.launcherIcon,
332
+ };
333
+
334
+ return buildWidget(mergedConfig);
335
+ };
336
+
337
+ const controls = window.CopilotChat.init(config);
338
+ return controls;
339
+ } catch (error) {
340
+ handleError(error instanceof Error ? error.message : "Unknown error during widget bootstrap.");
341
+ return null;
342
+ }
343
+ };
344
+
345
+ if (shouldAutoBootstrapFromScript()) {
346
+ ready(() => {
347
+ initCopilotChatWidget();
348
+ });
349
+ }
350
+
351
+ // expose for manual bootstrap if autoload=false
352
+ window.CopilotChat = window.CopilotChat || {};
353
+ window.CopilotChat.load = initCopilotChatWidget;
354
+ })();