@deway-ai/web-sdk 0.83.0 → 0.85.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/loader.es.js CHANGED
@@ -1,695 +1,637 @@
1
- const I = {
2
- debug: 0,
3
- info: 1,
4
- warn: 2,
5
- error: 3
6
- }, x = 4;
7
- function L(o) {
8
- if (typeof o == "bigint") return `${o}n`;
9
- if (typeof o == "symbol") return o.toString();
10
- if (typeof o == "function") return "[Function]";
1
+ //#region src/common/logger/sdk-logger.ts
2
+ var e = {
3
+ debug: 0,
4
+ info: 1,
5
+ warn: 2,
6
+ error: 3
7
+ }, t = 4, n = null;
8
+ function r(e) {
9
+ if (typeof e == "bigint") return `${e}n`;
10
+ if (typeof e == "symbol") return e.toString();
11
+ if (typeof e == "function") return "[Function]";
11
12
  }
12
- function U(o, e) {
13
- return o instanceof Error ? { name: o.name, message: o.message, stack: o.stack } : e.has(o) ? "[Circular]" : (e.add(o), o);
13
+ function i(e, t) {
14
+ return e instanceof Error ? {
15
+ name: e.name,
16
+ message: e.message,
17
+ stack: e.stack
18
+ } : t.has(e) ? "[Circular]" : (t.add(e), e);
14
19
  }
15
- function T(o) {
16
- const e = /* @__PURE__ */ new WeakSet();
17
- return JSON.stringify(o, (t, n) => {
18
- const i = L(n);
19
- return i !== void 0 ? i : typeof n == "object" && n !== null ? U(n, e) : n;
20
- });
20
+ function a(e) {
21
+ let t = /* @__PURE__ */ new WeakSet();
22
+ return JSON.stringify(e, (e, n) => {
23
+ let a = r(n);
24
+ return a === void 0 ? typeof n == "object" && n ? i(n, t) : n : a;
25
+ });
21
26
  }
22
- function O(o, e) {
23
- const t = o !== void 0 && Object.keys(o).length > 0, n = e !== void 0;
24
- if (!t && !n) return;
25
- const i = typeof e == "object" && e !== null && !Array.isArray(e) ? e : n ? { value: e } : {};
26
- return { ...o, ...i };
27
+ function o(e, t) {
28
+ let n = e !== void 0 && Object.keys(e).length > 0, r = t !== void 0;
29
+ if (!n && !r) return;
30
+ let i = typeof t == "object" && t && !Array.isArray(t) ? t : r ? { value: t } : {};
31
+ return {
32
+ ...e,
33
+ ...i
34
+ };
27
35
  }
28
- function w(o, e, t, n, i) {
29
- const r = e;
30
- if (I[o] < r) return;
31
- const s = {
32
- level: o,
33
- time: Date.now(),
34
- msg: t
35
- }, d = O(n, i);
36
- d !== void 0 && (s.ctx = d), T(s);
36
+ function s(t, r, i, s, c) {
37
+ let l = n === null ? r : n;
38
+ if (e[t] < l) return;
39
+ let u = {
40
+ level: t,
41
+ time: Date.now(),
42
+ msg: i
43
+ }, d = o(s, c);
44
+ d !== void 0 && (u.ctx = d);
45
+ let f = a(u);
46
+ console[t](f);
37
47
  }
38
- function u(o) {
39
- const e = o !== void 0 && "minLevel" in o ? o.minLevel : void 0, t = e === void 0 ? x : I[e], n = o?.context;
40
- return {
41
- debug(i, r) {
42
- w("debug", t, i, n, r);
43
- },
44
- info(i, r) {
45
- w("info", t, i, n, r);
46
- },
47
- warn(i, r) {
48
- w("warn", t, i, n, r);
49
- },
50
- error(i, r) {
51
- w("error", t, i, n, r);
52
- },
53
- child(i) {
54
- return u({
55
- minLevel: e,
56
- context: { ...n, ...i }
57
- });
58
- },
59
- alwaysOnLog(i) {
60
- }
61
- };
48
+ function c(n) {
49
+ let r = n !== void 0 && "minLevel" in n ? n.minLevel : void 0, i = r === void 0 ? t : e[r], a = n?.context;
50
+ return {
51
+ debug(e, t) {
52
+ s("debug", i, e, a, t);
53
+ },
54
+ info(e, t) {
55
+ s("info", i, e, a, t);
56
+ },
57
+ warn(e, t) {
58
+ s("warn", i, e, a, t);
59
+ },
60
+ error(e, t) {
61
+ s("error", i, e, a, t);
62
+ },
63
+ child(e) {
64
+ return c({
65
+ minLevel: r,
66
+ context: {
67
+ ...a,
68
+ ...e
69
+ }
70
+ });
71
+ },
72
+ alwaysOnLog(e) {
73
+ console.log(e);
74
+ }
75
+ };
62
76
  }
63
- const k = u({ context: { module: "sdk-config-store" } }), A = "deway-sdk-config", _ = ["Understanding intent", "Reading web page", "Browsing the docs", "Enriching context", "Validating understanding", "Crafting response"];
64
- class Q {
65
- saveConfig(e) {
66
- if (window?.localStorage)
67
- try {
68
- const t = JSON.stringify(e);
69
- window.localStorage.setItem(A, t);
70
- } catch (t) {
71
- k.warn("Failed to save SDK config to localStorage", t);
72
- }
73
- }
74
- loadConfig() {
75
- if (window?.localStorage)
76
- try {
77
- const e = window.localStorage.getItem(A);
78
- return e ? JSON.parse(e) : null;
79
- } catch (e) {
80
- return k.warn("Failed to load SDK config from localStorage", e), null;
81
- }
82
- return null;
83
- }
84
- getExcludedVendors() {
85
- return this.loadConfig()?.excludedVendors ?? [];
86
- }
87
- getAssistantName() {
88
- return this.loadConfig()?.assistantName ?? "Assistant";
89
- }
90
- getAiDisclaimer() {
91
- return this.loadConfig()?.aiDisclaimer;
92
- }
93
- getThinkingMessages() {
94
- return this.loadConfig()?.thinkingMessages ?? _;
95
- }
96
- /**
97
- * Get the support handoff configuration
98
- * @returns SupportHandoff config or null if not configured
99
- */
100
- getSupportHandoff() {
101
- return this.loadConfig()?.supportHandoff ?? null;
102
- }
103
- /**
104
- * Get the support handoff button text
105
- * @returns Custom button text or default "talk to Support"
106
- */
107
- getSupportHandoffButtonText() {
108
- return this.getSupportHandoff()?.button_text ?? "talk to Support";
109
- }
110
- getFeatureFlags() {
111
- return this.loadConfig()?.featureFlags ?? {};
112
- }
113
- getFeatureFlag(e) {
114
- return this.getFeatureFlags()[e] ?? !1;
115
- }
116
- getPromptSuggestions() {
117
- return this.loadConfig()?.promptSuggestions;
118
- }
119
- getWelcomeTitle() {
120
- return this.loadConfig()?.welcomeTitle ?? "How can I help you today?";
121
- }
122
- getWelcomeSubtitle() {
123
- return this.loadConfig()?.welcomeSubtitle ?? "I'm ready to help you navigate, learn, and get things done.";
124
- }
125
- getEntrypointWidgetAppearanceMode() {
126
- return this.loadConfig()?.entrypointWidgetAppearanceMode ?? "bookmark";
127
- }
128
- getChatAppearanceMode() {
129
- return this.loadConfig()?.chatAppearanceMode ?? "floating-window";
130
- }
131
- getTenantTheme() {
132
- return this.loadConfig()?.tenantTheme ?? null;
133
- }
134
- /**
135
- * Get the theme override for a specific mode
136
- * @param mode - "light" or "dark"
137
- * @returns ThemeOverride for the specified mode, or null if not available
138
- */
139
- getTenantThemeForMode(e) {
140
- const t = this.getTenantTheme();
141
- return t ? e === "dark" ? t.dark : t.light : null;
142
- }
143
- getCustomIcons() {
144
- return this.loadConfig()?.customIcons ?? null;
145
- }
146
- getEntrypointWidgetIconInlineSvg() {
147
- return this.getCustomIcons()?.entrypoint_widget_icon_inline_svg ?? void 0;
148
- }
149
- getEmptyChatStateIconInlineSvg() {
150
- return this.getCustomIcons()?.empty_chat_state_icon_inline_svg ?? void 0;
151
- }
152
- getUIAlignment() {
153
- return this.loadConfig()?.uiAlignment ?? null;
154
- }
155
- getUIAlignmentAnchorSelector() {
156
- return this.getUIAlignment()?.anchor_selector ?? null;
157
- }
158
- getUIAlignmentSide() {
159
- return this.getUIAlignment()?.side ?? "right";
160
- }
161
- /**
162
- * Whether the SDK should inject the `<html>` squeeze stylesheet when the
163
- * side-panel opens. Default is `true` — hosts can opt out via
164
- * `Deway.init({ sidePanel: { hostSqueeze: false } })`. When `false`, the
165
- * SDK still publishes the responsive contract (CSS custom properties +
166
- * `deway:panel-resize` event) but skips the squeeze.
167
- */
168
- getSidePanelHostSqueezeEnabled() {
169
- return this.loadConfig()?.sidePanel?.hostSqueeze ?? !0;
170
- }
77
+ //#endregion
78
+ //#region src/sdk/sdk-config-store.ts
79
+ var l = c({ context: { module: "sdk-config-store" } }), u = "deway-sdk-config", d = [
80
+ "Understanding intent",
81
+ "Reading web page",
82
+ "Browsing the docs",
83
+ "Enriching context",
84
+ "Validating understanding",
85
+ "Crafting response"
86
+ ], f = class {
87
+ saveConfig(e) {
88
+ if (window?.localStorage) try {
89
+ let t = JSON.stringify(e);
90
+ window.localStorage.setItem(u, t);
91
+ } catch (e) {
92
+ l.warn("Failed to save SDK config to localStorage", e);
93
+ }
94
+ }
95
+ loadConfig() {
96
+ if (window?.localStorage) try {
97
+ let e = window.localStorage.getItem(u);
98
+ return e ? JSON.parse(e) : null;
99
+ } catch (e) {
100
+ return l.warn("Failed to load SDK config from localStorage", e), null;
101
+ }
102
+ return null;
103
+ }
104
+ getExcludedVendors() {
105
+ return this.loadConfig()?.excludedVendors ?? [];
106
+ }
107
+ getAssistantName() {
108
+ return this.loadConfig()?.assistantName ?? "Assistant";
109
+ }
110
+ getAiDisclaimer() {
111
+ return this.loadConfig()?.aiDisclaimer;
112
+ }
113
+ getThinkingMessages() {
114
+ return this.loadConfig()?.thinkingMessages ?? d;
115
+ }
116
+ getSupportHandoff() {
117
+ return this.loadConfig()?.supportHandoff ?? null;
118
+ }
119
+ getSupportHandoffButtonText() {
120
+ return this.getSupportHandoff()?.button_text ?? "talk to Support";
121
+ }
122
+ getFeatureFlags() {
123
+ return this.loadConfig()?.featureFlags ?? {};
124
+ }
125
+ getFeatureFlag(e) {
126
+ return this.getFeatureFlags()[e] ?? !1;
127
+ }
128
+ getPromptSuggestions() {
129
+ return this.loadConfig()?.promptSuggestions;
130
+ }
131
+ getWelcomeTitle() {
132
+ return this.loadConfig()?.welcomeTitle ?? "How can I help you today?";
133
+ }
134
+ getWelcomeSubtitle() {
135
+ return this.loadConfig()?.welcomeSubtitle ?? "I'm ready to help you navigate, learn, and get things done.";
136
+ }
137
+ getEntrypointWidgetAppearanceMode() {
138
+ return this.loadConfig()?.entrypointWidgetAppearanceMode ?? "bookmark";
139
+ }
140
+ getChatAppearanceMode() {
141
+ return this.loadConfig()?.chatAppearanceMode ?? "floating-window";
142
+ }
143
+ getTenantTheme() {
144
+ return this.loadConfig()?.tenantTheme ?? null;
145
+ }
146
+ getTenantThemeForMode(e) {
147
+ let t = this.getTenantTheme();
148
+ return t ? e === "dark" ? t.dark : t.light : null;
149
+ }
150
+ getCustomIcons() {
151
+ return this.loadConfig()?.customIcons ?? null;
152
+ }
153
+ getEntrypointWidgetIconInlineSvg() {
154
+ return this.getCustomIcons()?.entrypoint_widget_icon_inline_svg ?? void 0;
155
+ }
156
+ getEmptyChatStateIconInlineSvg() {
157
+ return this.getCustomIcons()?.empty_chat_state_icon_inline_svg ?? void 0;
158
+ }
159
+ getUIAlignment() {
160
+ return this.loadConfig()?.uiAlignment ?? null;
161
+ }
162
+ getUIAlignmentAnchorSelector() {
163
+ return this.getUIAlignment()?.anchor_selector ?? null;
164
+ }
165
+ getUIAlignmentSide() {
166
+ return this.getUIAlignment()?.side ?? "right";
167
+ }
168
+ getSidePanelHostSqueezeEnabled() {
169
+ return this.loadConfig()?.sidePanel?.hostSqueeze ?? !0;
170
+ }
171
+ }, p = c({ context: { module: "sdk-cache-manager" } }), m = class e {
172
+ static CACHE_KEY = "deway-sdk-cache";
173
+ static DB_NAME = "DewaySdk";
174
+ static DB_VERSION = 1;
175
+ static STORE_NAME = "sdk";
176
+ async cacheSDK(t, n, r, i) {
177
+ try {
178
+ let a = (await this.openIndexedDB()).transaction([e.STORE_NAME], "readwrite").objectStore(e.STORE_NAME);
179
+ await new Promise((e, o) => {
180
+ let s = a.put({
181
+ id: "latest",
182
+ code: t,
183
+ version: n,
184
+ checksum: r,
185
+ signature: i,
186
+ timestamp: Date.now()
187
+ });
188
+ s.onsuccess = () => e(s.result), s.onerror = () => o(s.error);
189
+ }), p.debug("SDK cached in IndexedDB");
190
+ } catch {
191
+ try {
192
+ let a = JSON.stringify({
193
+ code: t,
194
+ version: n,
195
+ checksum: r,
196
+ signature: i,
197
+ timestamp: Date.now()
198
+ });
199
+ localStorage.setItem(e.CACHE_KEY, a), p.debug("SDK cached in localStorage");
200
+ } catch (e) {
201
+ p.warn("Unable to cache SDK", e);
202
+ }
203
+ }
204
+ }
205
+ async getCachedSDK() {
206
+ try {
207
+ let t = (await this.openIndexedDB()).transaction([e.STORE_NAME], "readonly").objectStore(e.STORE_NAME), n = await new Promise((e, n) => {
208
+ let r = t.get("latest");
209
+ r.onsuccess = () => e(r.result || null), r.onerror = () => n(r.error);
210
+ });
211
+ if (n) return p.debug("Found cached SDK in IndexedDB"), n;
212
+ } catch {
213
+ p.debug("IndexedDB unavailable, trying localStorage");
214
+ }
215
+ try {
216
+ let t = localStorage.getItem(e.CACHE_KEY);
217
+ if (t) return p.debug("Found cached SDK in localStorage"), JSON.parse(t);
218
+ } catch (e) {
219
+ p.warn("Failed to read from localStorage", e);
220
+ }
221
+ return null;
222
+ }
223
+ openIndexedDB() {
224
+ return new Promise((t, n) => {
225
+ let r = indexedDB.open(e.DB_NAME, e.DB_VERSION);
226
+ r.onerror = () => n(r.error), r.onsuccess = () => t(r.result), r.onupgradeneeded = (t) => {
227
+ let n = t.target.result;
228
+ n.objectStoreNames.contains(e.STORE_NAME) || n.createObjectStore(e.STORE_NAME, { keyPath: "id" });
229
+ };
230
+ });
231
+ }
232
+ }, h = c({ context: { module: "sdk-verifier" } });
233
+ async function g(e) {
234
+ let t = new TextEncoder().encode(e), n = await crypto.subtle.digest("SHA-256", t);
235
+ return Array.from(new Uint8Array(n)).map((e) => e.toString(16).padStart(2, "0")).join("");
171
236
  }
172
- const f = u({ context: { module: "sdk-cache-manager" } });
173
- class l {
174
- static CACHE_KEY = "deway-sdk-cache";
175
- static DB_NAME = "DewaySdk";
176
- static DB_VERSION = 1;
177
- static STORE_NAME = "sdk";
178
- async cacheSDK(e, t, n, i) {
179
- try {
180
- const d = (await this.openIndexedDB()).transaction([l.STORE_NAME], "readwrite").objectStore(l.STORE_NAME);
181
- await new Promise((E, K) => {
182
- const g = d.put({
183
- id: "latest",
184
- code: e,
185
- version: t,
186
- checksum: n,
187
- signature: i,
188
- timestamp: Date.now()
189
- });
190
- g.onsuccess = () => E(g.result), g.onerror = () => K(g.error);
191
- }), f.debug("SDK cached in IndexedDB");
192
- } catch {
193
- try {
194
- const s = JSON.stringify({
195
- code: e,
196
- version: t,
197
- checksum: n,
198
- signature: i,
199
- timestamp: Date.now()
200
- });
201
- localStorage.setItem(l.CACHE_KEY, s), f.debug("SDK cached in localStorage");
202
- } catch (s) {
203
- f.warn("Unable to cache SDK", s);
204
- }
205
- }
206
- }
207
- async getCachedSDK() {
208
- try {
209
- const n = (await this.openIndexedDB()).transaction([l.STORE_NAME], "readonly").objectStore(l.STORE_NAME), i = await new Promise((r, s) => {
210
- const d = n.get("latest");
211
- d.onsuccess = () => r(d.result || null), d.onerror = () => s(d.error);
212
- });
213
- if (i)
214
- return f.debug("Found cached SDK in IndexedDB"), i;
215
- } catch {
216
- f.debug("IndexedDB unavailable, trying localStorage");
217
- }
218
- try {
219
- const e = localStorage.getItem(l.CACHE_KEY);
220
- if (e)
221
- return f.debug("Found cached SDK in localStorage"), JSON.parse(e);
222
- } catch (e) {
223
- f.warn("Failed to read from localStorage", e);
224
- }
225
- return null;
226
- }
227
- openIndexedDB() {
228
- return new Promise((e, t) => {
229
- const n = indexedDB.open(l.DB_NAME, l.DB_VERSION);
230
- n.onerror = () => t(n.error), n.onsuccess = () => e(n.result), n.onupgradeneeded = (i) => {
231
- const r = i.target.result;
232
- r.objectStoreNames.contains(l.STORE_NAME) || r.createObjectStore(l.STORE_NAME, { keyPath: "id" });
233
- };
234
- });
235
- }
237
+ function _(e) {
238
+ let t = atob(e), n = new Uint8Array(t.length);
239
+ for (let e = 0; e < t.length; e++) n[e] = t.charCodeAt(e);
240
+ return n;
236
241
  }
237
- const N = u({ context: { module: "sdk-verifier" } });
238
- async function R(o) {
239
- const t = new TextEncoder().encode(o), n = await crypto.subtle.digest("SHA-256", t);
240
- return Array.from(new Uint8Array(n)).map((r) => r.toString(16).padStart(2, "0")).join("");
242
+ function v(e) {
243
+ let t = new Uint8Array(e.length / 2);
244
+ for (let n = 0; n < e.length; n += 2) t[n / 2] = Number.parseInt(e.substr(n, 2), 16);
245
+ return t;
241
246
  }
242
- function F(o) {
243
- const e = atob(o), t = new Uint8Array(e.length);
244
- for (let n = 0; n < e.length; n++)
245
- t[n] = e.charCodeAt(n);
246
- return t;
247
+ async function y(e, t, n) {
248
+ try {
249
+ let r = _(e), i = v(t), a = _(n), o = await crypto.subtle.importKey("raw", r, { name: "Ed25519" }, !1, ["verify"]);
250
+ return await crypto.subtle.verify("Ed25519", o, a, i);
251
+ } catch (e) {
252
+ return h.error("Ed25519 signature verification failed", e), !1;
253
+ }
247
254
  }
248
- function P(o) {
249
- const e = new Uint8Array(o.length / 2);
250
- for (let t = 0; t < o.length; t += 2)
251
- e[t / 2] = Number.parseInt(o.substr(t, 2), 16);
252
- return e;
255
+ async function b(e, t, n, r) {
256
+ if (!t || !n) throw Error("SDK verification failed: Missing security headers");
257
+ if (await g(e) !== t) throw Error("SDK verification failed: Checksum mismatch - content tampered");
258
+ if (!await y(r, t, n)) throw Error("SDK verification failed: Invalid signature - content tampered");
253
259
  }
254
- async function $(o, e, t) {
255
- try {
256
- const n = F(o), i = P(e), r = F(t), s = await crypto.subtle.importKey("raw", n, { name: "Ed25519" }, !1, ["verify"]);
257
- return await crypto.subtle.verify("Ed25519", s, r, i);
258
- } catch (n) {
259
- return N.error("Ed25519 signature verification failed", n), !1;
260
- }
261
- }
262
- async function q(o, e, t, n) {
263
- if (!e || !t)
264
- throw new Error("SDK verification failed: Missing security headers");
265
- if (await R(o) !== e)
266
- throw new Error("SDK verification failed: Checksum mismatch - content tampered");
267
- if (!await $(n, e, t))
268
- throw new Error("SDK verification failed: Invalid signature - content tampered");
269
- }
270
- const m = u({ context: { module: "sdk-fetcher" } });
271
- class z {
272
- cleanApiEndpoint(e) {
273
- return e.trim().replace(/\/+$/, "");
274
- }
275
- async fetchSDK(e, t, n) {
276
- try {
277
- m.info("Fetching Deway SDK from backend...");
278
- const i = this.cleanApiEndpoint(t), r = await fetch(`${i}/sdk-serve/sdk/v0`, {
279
- method: "GET",
280
- headers: {
281
- Accept: "application/javascript",
282
- "deway-app-key": e,
283
- Origin: window?.location?.origin || ""
284
- }
285
- });
286
- return r.ok ? this.handleSuccessfulFetch(r, n) : (m.warn(`Failed to fetch SDK: HTTP ${r.status}: ${r.statusText}`), null);
287
- } catch (i) {
288
- return m.warn("Failed to fetch SDK from server", i), null;
289
- }
290
- }
291
- async handleSuccessfulFetch(e, t) {
292
- const n = e.headers.get("x-sdk-checksum"), i = e.headers.get("x-sdk-version"), r = e.headers.get("x-sdk-signature"), s = await e.text();
293
- if (m.info(`Fetched Deway SDK version ${i}`), !i || !s || !n) {
294
- const d = Object.fromEntries(e.headers.entries());
295
- throw m.error("Failed to get required data from sdk fetch", { headers: d }), new Error("Invalid SDK response: missing version, code, or checksum");
296
- }
297
- return await q(s, n, r, t), { code: s, version: i, checksum: n, signature: r || "" };
298
- }
299
- }
300
- const h = u({ context: { module: "command-queue" } });
301
- class C {
302
- static MAX_QUEUE_SIZE = 50;
303
- commandQueue = [];
304
- queueCommand(e, ...t) {
305
- this.commandQueue.length >= C.MAX_QUEUE_SIZE && (h.warn(`Command queue full (${C.MAX_QUEUE_SIZE} commands). Discarding oldest command.`), this.commandQueue.shift()), this.commandQueue.push({ method: e, args: t }), h.debug(`Queued command: ${e} (queue size: ${this.commandQueue.length})`);
306
- }
307
- replayQueuedCommands() {
308
- if (this.commandQueue.length === 0)
309
- return;
310
- h.info(`Replaying ${this.commandQueue.length} queued commands`);
311
- const e = [...this.commandQueue];
312
- if (this.commandQueue = [], !this.isSDKAvailable()) {
313
- h.warn("Deway SDK not available for command replay");
314
- return;
315
- }
316
- for (const t of e)
317
- this.replayCommand(t);
318
- }
319
- clearQueue() {
320
- this.commandQueue = [];
321
- }
322
- isSDKAvailable() {
323
- return typeof window < "u" && "Deway" in window && !!window.Deway;
324
- }
325
- replayCommand(e) {
326
- try {
327
- const t = window.Deway, n = t?.[e.method];
328
- typeof n == "function" ? n.apply(t, e.args) : h.warn(`Method ${e.method} not found on Deway SDK`);
329
- } catch (t) {
330
- h.error(`Failed to replay command ${e.method}`, t);
331
- }
332
- }
333
- }
334
- const p = u({ context: { module: "remote-config-cache" } });
335
- class b {
336
- static CACHE_KEY = "deway-remote-config-cache";
337
- /**
338
- * Caches remote configuration in localStorage
339
- * TTL only controls fetch frequency, cached config is never deleted
340
- *
341
- * @param config - Remote configuration to cache
342
- * @param ttlSeconds - Time-to-live in seconds from server
343
- */
344
- async cacheRemoteConfig(e, t) {
345
- try {
346
- const n = {
347
- config: e,
348
- ttl_seconds: t,
349
- timestamp: Date.now()
350
- };
351
- localStorage.setItem(b.CACHE_KEY, JSON.stringify(n)), p.debug("Remote configuration cached in localStorage");
352
- } catch (n) {
353
- p.warn("Failed to cache remote config", n);
354
- }
355
- }
356
- /**
357
- * Retrieves cached remote configuration from localStorage
358
- * Returns null if no cache exists
359
- *
360
- * @returns Cached remote config or null
361
- */
362
- async getCachedRemoteConfig() {
363
- try {
364
- const e = localStorage.getItem(b.CACHE_KEY);
365
- if (!e)
366
- return null;
367
- const t = JSON.parse(e);
368
- return p.debug("Found cached remote configuration"), t;
369
- } catch (e) {
370
- return p.warn("Failed to read cached remote config", e), null;
371
- }
372
- }
373
- /**
374
- * Checks if the cached config is still valid based on TTL
375
- * Note: This only affects whether we fetch fresh config, not if we use cached config
376
- *
377
- * @param timestamp - Timestamp when config was cached (milliseconds)
378
- * @param ttlSeconds - TTL in seconds
379
- * @returns true if cache is still valid
380
- */
381
- isCacheValid(e, t) {
382
- const n = Date.now(), i = e + t * 1e3;
383
- return n < i;
384
- }
385
- }
386
- const S = u({ context: { module: "remote-config-fetcher" } });
387
- class M {
388
- cleanApiEndpoint(e) {
389
- return e.trim().replace(/\/+$/, "");
390
- }
391
- /**
392
- * Fetches remote configuration from the backend
393
- * Returns null if the fetch fails for any reason
394
- *
395
- * @param appKey - The application key for authentication
396
- * @param apiEndpoint - The API endpoint URL
397
- * @returns Remote config response or null on error
398
- */
399
- async fetchRemoteConfig(e, t) {
400
- try {
401
- S.info("Fetching remote configuration from backend...");
402
- const n = this.cleanApiEndpoint(t), i = await fetch(`${n}/sdk-remote-config-serve/`, {
403
- method: "GET",
404
- headers: {
405
- Accept: "application/json",
406
- "deway-app-key": e,
407
- Origin: window?.location?.origin || ""
408
- }
409
- });
410
- if (i.ok) {
411
- const r = await i.json();
412
- return S.info("Remote configuration fetched successfully"), r;
413
- }
414
- return S.warn(`Failed to fetch remote config: HTTP ${i.status}: ${i.statusText}`), null;
415
- } catch (n) {
416
- return S.warn("Failed to fetch remote config from server", n), null;
417
- }
418
- }
419
- }
420
- const y = u({ context: { module: "script-executor" } });
421
- class H {
422
- async executeSDK(e) {
423
- return new Promise((t) => {
424
- try {
425
- if (!this.isDocumentReady()) {
426
- y.error("Document is not available for script execution"), t(!1);
427
- return;
428
- }
429
- const n = document.createElement("script");
430
- n.textContent = e, n.type = "text/javascript";
431
- let i = !1;
432
- const r = (s) => {
433
- i || (i = !0, this.cleanupScript(n), t(s));
434
- };
435
- n.onerror = () => {
436
- y.error("Script execution failed"), r(!1);
437
- }, n.onload = () => r(!0), document.head.appendChild(n), setTimeout(() => {
438
- !i && this.verifySDKLoaded() ? r(!0) : i || (y.error("SDK execution timeout - Deway object not found"), r(!1));
439
- }, 100);
440
- } catch (n) {
441
- y.error("Failed to execute SDK script", n), t(!1);
442
- }
443
- });
444
- }
445
- isDocumentReady() {
446
- return typeof document < "u" && document.head != null;
447
- }
448
- verifySDKLoaded() {
449
- return typeof window < "u" && "Deway" in window && !!window.Deway;
450
- }
451
- cleanupScript(e) {
452
- try {
453
- e.parentNode && e.parentNode.removeChild(e);
454
- } catch (t) {
455
- y.debug("Failed to cleanup script element", t);
456
- }
457
- }
458
- }
459
- const D = u({ context: { module: "config-validator" } });
460
- class V {
461
- validateConfig(e) {
462
- return e ? !e.appKey || e.appKey.trim().length === 0 ? (D.error("Config.appKey is required and must be a non-empty string"), !1) : e.apiEndpoint !== void 0 && !this.isValidUrl(e.apiEndpoint) ? (D.error("Config.apiEndpoint must be a valid URL"), !1) : e.publicKey !== void 0 && e.publicKey.trim().length === 0 ? (D.error("Config.publicKey must be a non-empty string if provided"), !1) : !0 : (D.error("Config is required"), !1);
463
- }
464
- isValidUrl(e) {
465
- try {
466
- return new URL(e), !0;
467
- } catch {
468
- return !1;
469
- }
470
- }
471
- }
472
- const a = u({ context: { module: "sdk-loader" } }), v = {
473
- apiEndpoint: "https://service.deway.app",
474
- publicKey: "9d3dBUvqyUQ7egd5j5uORdHSqZ7VFWOu+ud/SWt9WUY="
475
- };
476
- class j {
477
- isLoaded = !1;
478
- isLoading = !1;
479
- cacheManager;
480
- scriptExecutor;
481
- commandQueue;
482
- sdkFetcher;
483
- configValidator;
484
- remoteConfigFetcher;
485
- remoteConfigCache;
486
- sdkConfigStore;
487
- constructor() {
488
- this.cacheManager = new l(), this.scriptExecutor = new H(), this.commandQueue = new C(), this.sdkFetcher = new z(), this.configValidator = new V(), this.sdkConfigStore = new Q(), this.remoteConfigFetcher = new M(), this.remoteConfigCache = new b();
489
- }
490
- init(e) {
491
- this.performInit(e).catch((t) => {
492
- a.error("Failed to initialize Deway SDK", t);
493
- });
494
- }
495
- async performInit(e) {
496
- try {
497
- if (!this.canInitialize())
498
- return;
499
- const t = this.isInitializationPayload(e), n = t ? e.localConfig : e;
500
- if (!this.configValidator.validateConfig(n)) {
501
- a.error("Invalid config provided to Deway SDK");
502
- return;
503
- }
504
- this.isLoading = !0;
505
- const i = n.apiEndpoint || v.apiEndpoint, r = n.publicKey || v.publicKey, [s, d] = await Promise.all([this.fetchOrLoadSDK(n.appKey, i, r), this.fetchRemoteConfigWithCache(n, i)]);
506
- if (!s)
507
- return;
508
- const E = t ? e : this.createInitializationPayload(d, n);
509
- if (!await this.scriptExecutor.executeSDK(s.code)) {
510
- a.error("SDK execution failed");
511
- return;
512
- }
513
- if (!this.initializeSDK(E))
514
- return;
515
- this.commandQueue.replayQueuedCommands(), this.isLoaded = !0;
516
- } finally {
517
- this.isLoading = !1;
518
- }
519
- }
520
- isInitializationPayload(e) {
521
- return "localConfig" in e && "remoteConfig" in e && "defaults" in e;
522
- }
523
- canInitialize() {
524
- return this.isLoaded ? (a.warn("Deway SDK already initialized"), !1) : this.isLoading ? (a.warn("Deway SDK initialization already in progress"), !1) : !0;
525
- }
526
- /**
527
- * Fetches remote config from backend with cache fallback
528
- * Returns null if both fetch and cache fail
529
- */
530
- async fetchRemoteConfigWithCache(e, t) {
531
- this.sdkConfigStore.saveConfig(e);
532
- const n = await this.remoteConfigFetcher.fetchRemoteConfig(e.appKey, t);
533
- if (n)
534
- return await this.remoteConfigCache.cacheRemoteConfig(n.config, n.ttl_seconds), n;
535
- a.info("Using cached remote config as fallback");
536
- const i = await this.remoteConfigCache.getCachedRemoteConfig();
537
- return i ? {
538
- config: i.config,
539
- ttl_seconds: i.ttl_seconds
540
- } : (a.warn("No remote config available (fetch failed and no cache)"), null);
541
- }
542
- /**
543
- * Creates initialization payload for backend SDK (NEW LOADER v0.29.0+)
544
- * Passes raw configuration data to backend for merging
545
- * This allows backend to own merge logic and handle all current/future config fields
546
- */
547
- createInitializationPayload(e, t) {
548
- return {
549
- localConfig: t,
550
- remoteConfig: e?.config ?? null,
551
- defaults: v
552
- };
553
- }
554
- async fetchOrLoadSDK(e, t, n) {
555
- const i = await this.sdkFetcher.fetchSDK(e, t, n);
556
- return i ? (await this.cacheManager.cacheSDK(i.code, i.version, i.checksum, i.signature), i) : (a.warn("Failed to fetch SDK from server, attempting cache fallback"), this.loadFromCache());
557
- }
558
- async loadFromCache() {
559
- const e = await this.cacheManager.getCachedSDK();
560
- return e ? (a.info(`Loading cached Deway SDK version ${e.version}`), { code: e.code, version: e.version }) : (a.error("SDK unavailable: Network error and no cached version found"), null);
561
- }
562
- initializeSDK(e) {
563
- if (!this.isSDKAvailable())
564
- return a.error("SDK execution failed: Deway object not found after loading"), !1;
565
- try {
566
- return window.Deway?.init(e), a.info("Deway SDK initialized successfully with payload"), !0;
567
- } catch (t) {
568
- return a.error("Failed to initialize SDK with payload", t), !1;
569
- }
570
- }
571
- identify(e) {
572
- try {
573
- this.isLoaded && this.isSDKAvailable() ? window.Deway?.identify(e) : this.commandQueue.queueCommand("identify", e);
574
- } catch (t) {
575
- a.error("Failed to identify user", t);
576
- }
577
- }
578
- reportEvent(e, t) {
579
- try {
580
- this.isLoaded && this.isSDKAvailable() ? window.Deway?.reportEvent(e, t) : this.commandQueue.queueCommand("reportEvent", e, t);
581
- } catch (n) {
582
- a.error("Failed to report event", n);
583
- }
584
- }
585
- setUserProfile(e) {
586
- try {
587
- this.isLoaded && this.isSDKAvailable() ? window.Deway?.setUserProfile(e) : this.commandQueue.queueCommand("setUserProfile", e);
588
- } catch (t) {
589
- a.error("Failed to set user profile", t);
590
- }
591
- }
592
- show(e) {
593
- try {
594
- this.isLoaded && this.isSDKAvailable() ? window.Deway?.show(e) : this.commandQueue.queueCommand("show", e);
595
- } catch (t) {
596
- a.error("Failed to show bookmark", t);
597
- }
598
- }
599
- hide() {
600
- try {
601
- this.isLoaded && this.isSDKAvailable() ? window.Deway?.hide() : this.commandQueue.queueCommand("hide");
602
- } catch (e) {
603
- a.error("Failed to hide bookmark", e);
604
- }
605
- }
606
- openChat() {
607
- try {
608
- this.isLoaded && this.isSDKAvailable() ? window.Deway?.openChat() : this.commandQueue.queueCommand("openChat");
609
- } catch (e) {
610
- a.error("Failed to open chat", e);
611
- }
612
- }
613
- resetUserLocally() {
614
- try {
615
- this.isLoaded && this.isSDKAvailable() ? window.Deway?.resetUserLocally() : this.commandQueue.queueCommand("resetUserLocally");
616
- } catch (e) {
617
- a.error("Failed to reset user locally", e);
618
- }
619
- }
620
- isVisible() {
621
- try {
622
- return this.isLoaded && this.isSDKAvailable() ? window.Deway?.isVisible() ?? !1 : !1;
623
- } catch (e) {
624
- return a.error("Failed to check bookmark visibility", e), !1;
625
- }
626
- }
627
- isInitialized() {
628
- try {
629
- return this.isLoaded && this.isSDKAvailable() ? window.Deway?.isInitialized() ?? !1 : !1;
630
- } catch (e) {
631
- return a.error("Failed to check initialization status", e), !1;
632
- }
633
- }
634
- /**
635
- * Returns the current side-panel state synchronously. This call must NOT be
636
- * queued — when the backend SDK isn't loaded yet, return the default
637
- * immediately so hosts can call this during render.
638
- */
639
- getPanelState() {
640
- try {
641
- if (this.isLoaded && this.isSDKAvailable()) {
642
- const e = window.Deway?.getPanelState;
643
- if (typeof e == "function")
644
- return e();
645
- }
646
- return { width: 0, side: "right", isOpen: !1 };
647
- } catch (e) {
648
- return a.error("Failed to read panel state", e), { width: 0, side: "right", isOpen: !1 };
649
- }
650
- }
651
- registerSupportCallback(e) {
652
- try {
653
- this.isLoaded && this.isSDKAvailable() ? window.Deway?.registerSupportCallback(e) : this.commandQueue.queueCommand("registerSupportCallback", e);
654
- } catch (t) {
655
- a.error("Failed to register support callback", t);
656
- }
657
- }
658
- unregisterSupportCallback() {
659
- try {
660
- this.isLoaded && this.isSDKAvailable() ? window.Deway?.unregisterSupportCallback() : this.commandQueue.queueCommand("unregisterSupportCallback");
661
- } catch (e) {
662
- a.error("Failed to unregister support callback", e);
663
- }
664
- }
665
- destroy() {
666
- try {
667
- this.isLoaded && this.isSDKAvailable() ? window.Deway?.destroy() : this.commandQueue.queueCommand("destroy"), this.commandQueue.clearQueue();
668
- } catch (e) {
669
- a.error("Failed to destroy SDK", e);
670
- }
671
- }
672
- isSDKAvailable() {
673
- return typeof window < "u" && "Deway" in window && !!window.Deway;
674
- }
675
- }
676
- const c = new j(), B = {
677
- init: (o) => c.init(o),
678
- identify: (o) => c.identify(o),
679
- reportEvent: (o, e) => c.reportEvent(o, e),
680
- setUserProfile: (o) => c.setUserProfile(o),
681
- show: (o) => c.show(o),
682
- hide: () => c.hide(),
683
- openChat: () => c.openChat(),
684
- resetUserLocally: () => c.resetUserLocally(),
685
- registerSupportCallback: (o) => c.registerSupportCallback(o),
686
- unregisterSupportCallback: () => c.unregisterSupportCallback(),
687
- isVisible: () => c.isVisible(),
688
- isInitialized: () => c.isInitialized(),
689
- destroy: () => c.destroy(),
690
- getPanelState: () => c.getPanelState()
691
- };
692
- typeof window < "u" && (window.Deway = B);
693
- export {
694
- B as default
260
+ //#endregion
261
+ //#region src/loader/fetcher/sdk-fetcher.ts
262
+ var x = c({ context: { module: "sdk-fetcher" } }), S = class {
263
+ cleanApiEndpoint(e) {
264
+ return e.trim().replace(/\/+$/, "");
265
+ }
266
+ async fetchSDK(e, t, n) {
267
+ try {
268
+ x.info("Fetching Deway SDK from backend...");
269
+ let r = this.cleanApiEndpoint(t), i = await fetch(`${r}/sdk-serve/sdk/v0`, {
270
+ method: "GET",
271
+ headers: {
272
+ Accept: "application/javascript",
273
+ "deway-app-key": e,
274
+ Origin: window?.location?.origin || ""
275
+ }
276
+ });
277
+ return i.ok ? this.handleSuccessfulFetch(i, n) : (x.warn(`Failed to fetch SDK: HTTP ${i.status}: ${i.statusText}`), null);
278
+ } catch (e) {
279
+ return x.warn("Failed to fetch SDK from server", e), null;
280
+ }
281
+ }
282
+ async handleSuccessfulFetch(e, t) {
283
+ let n = e.headers.get("x-sdk-checksum"), r = e.headers.get("x-sdk-version"), i = e.headers.get("x-sdk-signature"), a = await e.text();
284
+ if (x.info(`Fetched Deway SDK version ${r}`), !r || !a || !n) {
285
+ let t = Object.fromEntries(e.headers.entries());
286
+ throw x.error("Failed to get required data from sdk fetch", { headers: t }), Error("Invalid SDK response: missing version, code, or checksum");
287
+ }
288
+ return await b(a, n, i, t), {
289
+ code: a,
290
+ version: r,
291
+ checksum: n,
292
+ signature: i || ""
293
+ };
294
+ }
295
+ }, C = c({ context: { module: "command-queue" } }), w = class e {
296
+ static MAX_QUEUE_SIZE = 50;
297
+ commandQueue = [];
298
+ queueCommand(t, ...n) {
299
+ this.commandQueue.length >= e.MAX_QUEUE_SIZE && (C.warn(`Command queue full (${e.MAX_QUEUE_SIZE} commands). Discarding oldest command.`), this.commandQueue.shift()), this.commandQueue.push({
300
+ method: t,
301
+ args: n
302
+ }), C.debug(`Queued command: ${t} (queue size: ${this.commandQueue.length})`);
303
+ }
304
+ replayQueuedCommands() {
305
+ if (this.commandQueue.length === 0) return;
306
+ C.info(`Replaying ${this.commandQueue.length} queued commands`);
307
+ let e = [...this.commandQueue];
308
+ if (this.commandQueue = [], !this.isSDKAvailable()) {
309
+ C.warn("Deway SDK not available for command replay");
310
+ return;
311
+ }
312
+ for (let t of e) this.replayCommand(t);
313
+ }
314
+ clearQueue() {
315
+ this.commandQueue = [];
316
+ }
317
+ isSDKAvailable() {
318
+ return typeof window < "u" && "Deway" in window && !!window.Deway;
319
+ }
320
+ replayCommand(e) {
321
+ try {
322
+ let t = window.Deway, n = t?.[e.method];
323
+ typeof n == "function" ? n.apply(t, e.args) : C.warn(`Method ${e.method} not found on Deway SDK`);
324
+ } catch (t) {
325
+ C.error(`Failed to replay command ${e.method}`, t);
326
+ }
327
+ }
328
+ }, T = c({ context: { module: "remote-config-cache" } }), E = class e {
329
+ static CACHE_KEY = "deway-remote-config-cache";
330
+ async cacheRemoteConfig(t, n) {
331
+ try {
332
+ let r = {
333
+ config: t,
334
+ ttl_seconds: n,
335
+ timestamp: Date.now()
336
+ };
337
+ localStorage.setItem(e.CACHE_KEY, JSON.stringify(r)), T.debug("Remote configuration cached in localStorage");
338
+ } catch (e) {
339
+ T.warn("Failed to cache remote config", e);
340
+ }
341
+ }
342
+ async getCachedRemoteConfig() {
343
+ try {
344
+ let t = localStorage.getItem(e.CACHE_KEY);
345
+ if (!t) return null;
346
+ let n = JSON.parse(t);
347
+ return T.debug("Found cached remote configuration"), n;
348
+ } catch (e) {
349
+ return T.warn("Failed to read cached remote config", e), null;
350
+ }
351
+ }
352
+ isCacheValid(e, t) {
353
+ return Date.now() < e + t * 1e3;
354
+ }
355
+ }, D = c({ context: { module: "remote-config-fetcher" } }), O = class {
356
+ cleanApiEndpoint(e) {
357
+ return e.trim().replace(/\/+$/, "");
358
+ }
359
+ async fetchRemoteConfig(e, t) {
360
+ try {
361
+ D.info("Fetching remote configuration from backend...");
362
+ let n = this.cleanApiEndpoint(t), r = await fetch(`${n}/sdk-remote-config-serve/`, {
363
+ method: "GET",
364
+ headers: {
365
+ Accept: "application/json",
366
+ "deway-app-key": e,
367
+ Origin: window?.location?.origin || ""
368
+ }
369
+ });
370
+ if (r.ok) {
371
+ let e = await r.json();
372
+ return D.info("Remote configuration fetched successfully"), e;
373
+ }
374
+ return D.warn(`Failed to fetch remote config: HTTP ${r.status}: ${r.statusText}`), null;
375
+ } catch (e) {
376
+ return D.warn("Failed to fetch remote config from server", e), null;
377
+ }
378
+ }
379
+ }, k = c({ context: { module: "script-executor" } }), A = class {
380
+ async executeSDK(e) {
381
+ return new Promise((t) => {
382
+ try {
383
+ if (!this.isDocumentReady()) {
384
+ k.error("Document is not available for script execution"), t(!1);
385
+ return;
386
+ }
387
+ let n = document.createElement("script");
388
+ n.textContent = e, n.type = "text/javascript";
389
+ let r = !1, i = (e) => {
390
+ r || (r = !0, this.cleanupScript(n), t(e));
391
+ };
392
+ n.onerror = () => {
393
+ k.error("Script execution failed"), i(!1);
394
+ }, n.onload = () => i(!0), document.head.appendChild(n), setTimeout(() => {
395
+ !r && this.verifySDKLoaded() ? i(!0) : r || (k.error("SDK execution timeout - Deway object not found"), i(!1));
396
+ }, 100);
397
+ } catch (e) {
398
+ k.error("Failed to execute SDK script", e), t(!1);
399
+ }
400
+ });
401
+ }
402
+ isDocumentReady() {
403
+ return typeof document < "u" && document.head != null;
404
+ }
405
+ verifySDKLoaded() {
406
+ return typeof window < "u" && "Deway" in window && !!window.Deway;
407
+ }
408
+ cleanupScript(e) {
409
+ try {
410
+ e.parentNode && e.parentNode.removeChild(e);
411
+ } catch (e) {
412
+ k.debug("Failed to cleanup script element", e);
413
+ }
414
+ }
415
+ }, j = c({ context: { module: "config-validator" } }), M = class {
416
+ validateConfig(e) {
417
+ return e ? !e.appKey || e.appKey.trim().length === 0 ? (j.error("Config.appKey is required and must be a non-empty string"), !1) : e.apiEndpoint !== void 0 && !this.isValidUrl(e.apiEndpoint) ? (j.error("Config.apiEndpoint must be a valid URL"), !1) : e.publicKey !== void 0 && e.publicKey.trim().length === 0 ? (j.error("Config.publicKey must be a non-empty string if provided"), !1) : !0 : (j.error("Config is required"), !1);
418
+ }
419
+ isValidUrl(e) {
420
+ try {
421
+ return new URL(e), !0;
422
+ } catch {
423
+ return !1;
424
+ }
425
+ }
426
+ }, N = c({ context: { module: "sdk-loader" } }), P = {
427
+ apiEndpoint: "https://service.deway.app",
428
+ publicKey: "9d3dBUvqyUQ7egd5j5uORdHSqZ7VFWOu+ud/SWt9WUY="
429
+ }, F = new class {
430
+ isLoaded = !1;
431
+ isLoading = !1;
432
+ cacheManager;
433
+ scriptExecutor;
434
+ commandQueue;
435
+ sdkFetcher;
436
+ configValidator;
437
+ remoteConfigFetcher;
438
+ remoteConfigCache;
439
+ sdkConfigStore;
440
+ constructor() {
441
+ this.cacheManager = new m(), this.scriptExecutor = new A(), this.commandQueue = new w(), this.sdkFetcher = new S(), this.configValidator = new M(), this.sdkConfigStore = new f(), this.remoteConfigFetcher = new O(), this.remoteConfigCache = new E();
442
+ }
443
+ init(e) {
444
+ this.performInit(e).catch((e) => {
445
+ N.error("Failed to initialize Deway SDK", e);
446
+ });
447
+ }
448
+ async performInit(e) {
449
+ try {
450
+ if (!this.canInitialize()) return;
451
+ let t = this.isInitializationPayload(e), n = t ? e.localConfig : e;
452
+ if (!this.configValidator.validateConfig(n)) {
453
+ N.error("Invalid config provided to Deway SDK");
454
+ return;
455
+ }
456
+ this.isLoading = !0;
457
+ let r = n.apiEndpoint || P.apiEndpoint, i = n.publicKey || P.publicKey, [a, o] = await Promise.all([this.fetchOrLoadSDK(n.appKey, r, i), this.fetchRemoteConfigWithCache(n, r)]);
458
+ if (!a) return;
459
+ let s = t ? e : this.createInitializationPayload(o, n);
460
+ if (!await this.scriptExecutor.executeSDK(a.code)) {
461
+ N.error("SDK execution failed");
462
+ return;
463
+ }
464
+ if (!this.initializeSDK(s)) return;
465
+ this.commandQueue.replayQueuedCommands(), this.isLoaded = !0;
466
+ } finally {
467
+ this.isLoading = !1;
468
+ }
469
+ }
470
+ isInitializationPayload(e) {
471
+ return "localConfig" in e && "remoteConfig" in e && "defaults" in e;
472
+ }
473
+ canInitialize() {
474
+ return this.isLoaded ? (N.warn("Deway SDK already initialized"), !1) : this.isLoading ? (N.warn("Deway SDK initialization already in progress"), !1) : !0;
475
+ }
476
+ async fetchRemoteConfigWithCache(e, t) {
477
+ this.sdkConfigStore.saveConfig(e);
478
+ let n = await this.remoteConfigFetcher.fetchRemoteConfig(e.appKey, t);
479
+ if (n) return await this.remoteConfigCache.cacheRemoteConfig(n.config, n.ttl_seconds), n;
480
+ N.info("Using cached remote config as fallback");
481
+ let r = await this.remoteConfigCache.getCachedRemoteConfig();
482
+ return r ? {
483
+ config: r.config,
484
+ ttl_seconds: r.ttl_seconds
485
+ } : (N.warn("No remote config available (fetch failed and no cache)"), null);
486
+ }
487
+ createInitializationPayload(e, t) {
488
+ return {
489
+ localConfig: t,
490
+ remoteConfig: e?.config ?? null,
491
+ defaults: P
492
+ };
493
+ }
494
+ async fetchOrLoadSDK(e, t, n) {
495
+ let r = await this.sdkFetcher.fetchSDK(e, t, n);
496
+ return r ? (await this.cacheManager.cacheSDK(r.code, r.version, r.checksum, r.signature), r) : (N.warn("Failed to fetch SDK from server, attempting cache fallback"), this.loadFromCache());
497
+ }
498
+ async loadFromCache() {
499
+ let e = await this.cacheManager.getCachedSDK();
500
+ return e ? (N.info(`Loading cached Deway SDK version ${e.version}`), {
501
+ code: e.code,
502
+ version: e.version
503
+ }) : (N.error("SDK unavailable: Network error and no cached version found"), null);
504
+ }
505
+ initializeSDK(e) {
506
+ if (!this.isSDKAvailable()) return N.error("SDK execution failed: Deway object not found after loading"), !1;
507
+ try {
508
+ return window.Deway?.init(e), N.info("Deway SDK initialized successfully with payload"), !0;
509
+ } catch (e) {
510
+ return N.error("Failed to initialize SDK with payload", e), !1;
511
+ }
512
+ }
513
+ identify(e) {
514
+ try {
515
+ this.isLoaded && this.isSDKAvailable() ? window.Deway?.identify(e) : this.commandQueue.queueCommand("identify", e);
516
+ } catch (e) {
517
+ N.error("Failed to identify user", e);
518
+ }
519
+ }
520
+ reportEvent(e, t) {
521
+ try {
522
+ this.isLoaded && this.isSDKAvailable() ? window.Deway?.reportEvent(e, t) : this.commandQueue.queueCommand("reportEvent", e, t);
523
+ } catch (e) {
524
+ N.error("Failed to report event", e);
525
+ }
526
+ }
527
+ setUserProfile(e) {
528
+ try {
529
+ this.isLoaded && this.isSDKAvailable() ? window.Deway?.setUserProfile(e) : this.commandQueue.queueCommand("setUserProfile", e);
530
+ } catch (e) {
531
+ N.error("Failed to set user profile", e);
532
+ }
533
+ }
534
+ show(e) {
535
+ try {
536
+ this.isLoaded && this.isSDKAvailable() ? window.Deway?.show(e) : this.commandQueue.queueCommand("show", e);
537
+ } catch (e) {
538
+ N.error("Failed to show bookmark", e);
539
+ }
540
+ }
541
+ hide() {
542
+ try {
543
+ this.isLoaded && this.isSDKAvailable() ? window.Deway?.hide() : this.commandQueue.queueCommand("hide");
544
+ } catch (e) {
545
+ N.error("Failed to hide bookmark", e);
546
+ }
547
+ }
548
+ openChat() {
549
+ try {
550
+ this.isLoaded && this.isSDKAvailable() ? window.Deway?.openChat() : this.commandQueue.queueCommand("openChat");
551
+ } catch (e) {
552
+ N.error("Failed to open chat", e);
553
+ }
554
+ }
555
+ resetUserLocally() {
556
+ try {
557
+ this.isLoaded && this.isSDKAvailable() ? window.Deway?.resetUserLocally() : this.commandQueue.queueCommand("resetUserLocally");
558
+ } catch (e) {
559
+ N.error("Failed to reset user locally", e);
560
+ }
561
+ }
562
+ isVisible() {
563
+ try {
564
+ return this.isLoaded && this.isSDKAvailable() ? window.Deway?.isVisible() ?? !1 : !1;
565
+ } catch (e) {
566
+ return N.error("Failed to check bookmark visibility", e), !1;
567
+ }
568
+ }
569
+ isInitialized() {
570
+ try {
571
+ return this.isLoaded && this.isSDKAvailable() ? window.Deway?.isInitialized() ?? !1 : !1;
572
+ } catch (e) {
573
+ return N.error("Failed to check initialization status", e), !1;
574
+ }
575
+ }
576
+ getPanelState() {
577
+ try {
578
+ if (this.isLoaded && this.isSDKAvailable()) {
579
+ let e = window.Deway?.getPanelState;
580
+ if (typeof e == "function") return e();
581
+ }
582
+ return {
583
+ width: 0,
584
+ side: "right",
585
+ isOpen: !1
586
+ };
587
+ } catch (e) {
588
+ return N.error("Failed to read panel state", e), {
589
+ width: 0,
590
+ side: "right",
591
+ isOpen: !1
592
+ };
593
+ }
594
+ }
595
+ registerSupportCallback(e) {
596
+ try {
597
+ this.isLoaded && this.isSDKAvailable() ? window.Deway?.registerSupportCallback(e) : this.commandQueue.queueCommand("registerSupportCallback", e);
598
+ } catch (e) {
599
+ N.error("Failed to register support callback", e);
600
+ }
601
+ }
602
+ unregisterSupportCallback() {
603
+ try {
604
+ this.isLoaded && this.isSDKAvailable() ? window.Deway?.unregisterSupportCallback() : this.commandQueue.queueCommand("unregisterSupportCallback");
605
+ } catch (e) {
606
+ N.error("Failed to unregister support callback", e);
607
+ }
608
+ }
609
+ destroy() {
610
+ try {
611
+ this.isLoaded && this.isSDKAvailable() ? window.Deway?.destroy() : this.commandQueue.queueCommand("destroy"), this.commandQueue.clearQueue();
612
+ } catch (e) {
613
+ N.error("Failed to destroy SDK", e);
614
+ }
615
+ }
616
+ isSDKAvailable() {
617
+ return typeof window < "u" && "Deway" in window && !!window.Deway;
618
+ }
619
+ }(), I = {
620
+ init: (e) => F.init(e),
621
+ identify: (e) => F.identify(e),
622
+ reportEvent: (e, t) => F.reportEvent(e, t),
623
+ setUserProfile: (e) => F.setUserProfile(e),
624
+ show: (e) => F.show(e),
625
+ hide: () => F.hide(),
626
+ openChat: () => F.openChat(),
627
+ resetUserLocally: () => F.resetUserLocally(),
628
+ registerSupportCallback: (e) => F.registerSupportCallback(e),
629
+ unregisterSupportCallback: () => F.unregisterSupportCallback(),
630
+ isVisible: () => F.isVisible(),
631
+ isInitialized: () => F.isInitialized(),
632
+ destroy: () => F.destroy(),
633
+ getPanelState: () => F.getPanelState()
695
634
  };
635
+ typeof window < "u" && (window.Deway = I);
636
+ //#endregion
637
+ export { I as default };