@pagelines/sdk 1.0.150 → 1.0.152

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.
Files changed (24) hide show
  1. package/dist/{AgentProvider.vue_vue_type_script_setup_true_lang-BGCgpGEW.js → AgentProvider.vue_vue_type_script_setup_true_lang-B0TWM6dY.js} +2 -2
  2. package/dist/{AgentProvider.vue_vue_type_script_setup_true_lang-BGCgpGEW.js.map → AgentProvider.vue_vue_type_script_setup_true_lang-B0TWM6dY.js.map} +1 -1
  3. package/dist/{AgentWidgetInline-pTCUPNqY.js → AgentWidgetInline-DAihjazO.js} +2 -2
  4. package/dist/{AgentWidgetInline-pTCUPNqY.js.map → AgentWidgetInline-DAihjazO.js.map} +1 -1
  5. package/dist/{AgentWidgetModal-BA74AH8E.js → AgentWidgetModal-C4MD7yII.js} +2 -2
  6. package/dist/{AgentWidgetModal-BA74AH8E.js.map → AgentWidgetModal-C4MD7yII.js.map} +1 -1
  7. package/dist/{AgentWidgetPopup-pe5CmJfa.js → AgentWidgetPopup-DpR4jkw4.js} +2 -2
  8. package/dist/{AgentWidgetPopup-pe5CmJfa.js.map → AgentWidgetPopup-DpR4jkw4.js.map} +1 -1
  9. package/dist/{AgentWrap.vue_vue_type_script_setup_true_lang-Bvik7Wdb.js → AgentWrap.vue_vue_type_script_setup_true_lang-Cr7I8qea.js} +2 -2
  10. package/dist/{AgentWrap.vue_vue_type_script_setup_true_lang-Bvik7Wdb.js.map → AgentWrap.vue_vue_type_script_setup_true_lang-Cr7I8qea.js.map} +1 -1
  11. package/dist/agent.js +3 -3
  12. package/dist/clients/AuthClient.d.ts +25 -0
  13. package/dist/clients/ChatClient.d.ts +33 -0
  14. package/dist/clients/UserClient.d.ts +38 -0
  15. package/dist/clients/types.d.ts +22 -0
  16. package/dist/index.d.ts +4 -0
  17. package/dist/sdk.js +9 -6
  18. package/dist/sdkClient-yg_rc4B7.js +1015 -0
  19. package/dist/sdkClient-yg_rc4B7.js.map +1 -0
  20. package/dist/sdkClient.d.ts +29 -91
  21. package/dist/widget.js +4 -4
  22. package/package.json +2 -2
  23. package/dist/sdkClient-BmWhfelO.js +0 -939
  24. package/dist/sdkClient-BmWhfelO.js.map +0 -1
@@ -0,0 +1,1015 @@
1
+ var X = Object.defineProperty;
2
+ var se = (h, e, t) => e in h ? X(h, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : h[e] = t;
3
+ var c = (h, e) => X(h, "name", { value: e, configurable: !0 });
4
+ var n = (h, e, t) => se(h, typeof e != "symbol" ? e + "" : e, t);
5
+ import { watch as Z, ref as E, computed as ee } from "vue";
6
+ import { APP_PORT as F, APP_PROD_URL as D } from "@pagelines/types";
7
+ import { hc as ie } from "hono/client";
8
+ function N(h = {}) {
9
+ const { prefix: e = "id_" } = h, t = e.length >= 3 ? e.substring(0, 3) : e.padEnd(3, "_"), r = Math.floor(Date.now() / 1e3).toString(16).padStart(8, "0");
10
+ let o = "";
11
+ for (let s = 0; s < 16; s++)
12
+ o += Math.floor(Math.random() * 16).toString(16);
13
+ return t + r + o;
14
+ }
15
+ c(N, "objectId");
16
+ const S = globalThis.process, m = typeof window < "u", B = typeof S < "u" && !m, x = m ? typeof window < "u" && window.location && !window.location.hostname.includes("localhost") : B && typeof S < "u" && S.env?.NODE_ENV === "production", ne = !x, A = {
17
+ error: { priority: 50, color: "#FF0000", nodeColor: "\x1B[31m" },
18
+ warn: { priority: 40, color: "#FFA500", nodeColor: "\x1B[33m" },
19
+ info: { priority: 30, color: "#00ABFF", nodeColor: "\x1B[36m" },
20
+ debug: { priority: 20, color: "#00BD0C", nodeColor: "\x1B[32m" },
21
+ trace: { priority: 10, color: "#5233FF", nodeColor: "\x1B[35m" }
22
+ }, ae = ["password", "token", "secret", "apikey", "api_key", "authorization", "cookie"], y = class y {
23
+ constructor(e = {}, t) {
24
+ n(this, "settings");
25
+ n(this, "enabledInBrowser", !1);
26
+ n(this, "context");
27
+ this.context = t, this.settings = {
28
+ enabled: e.enabled ?? !0,
29
+ minLevel: e.minLevel ?? this.getDefaultLevel(),
30
+ timestamps: e.timestamps ?? !0
31
+ }, m && this.initBrowserLogging();
32
+ }
33
+ getDefaultLevel() {
34
+ if (B && typeof S < "u" && S.env?.LOG_LEVEL)
35
+ return S.env.LOG_LEVEL;
36
+ if (m && typeof localStorage < "u" && typeof localStorage.getItem == "function") {
37
+ const e = localStorage.getItem("PAGELINES_LOG_LEVEL");
38
+ if (e)
39
+ return e;
40
+ }
41
+ return x ? "info" : "debug";
42
+ }
43
+ initBrowserLogging() {
44
+ if (!m)
45
+ return;
46
+ const t = typeof localStorage?.getItem == "function" && localStorage.getItem("PAGELINES_LOG") === "true", r = window.location?.hostname || "";
47
+ this.enabledInBrowser = ne || t || r === "localhost" || r.includes("127.0.0.1"), x && !t && !y.hasShownHelp && (console.log(
48
+ "%cPageLines Logger (disabled in production)",
49
+ "color: #888; font-size: 12px"
50
+ ), console.log(
51
+ '%cTo enable: localStorage.setItem("PAGELINES_LOG", "true")',
52
+ "color: #888; font-size: 11px"
53
+ ), y.hasShownHelp = !0);
54
+ }
55
+ shouldLog(e) {
56
+ if (!this.settings.enabled || m && !this.enabledInBrowser)
57
+ return !1;
58
+ const t = A[e].priority, r = A[this.settings.minLevel].priority;
59
+ return t >= r;
60
+ }
61
+ formatTimestamp() {
62
+ return (/* @__PURE__ */ new Date()).toLocaleTimeString("en-GB", {
63
+ hour12: !1,
64
+ hour: "2-digit",
65
+ minute: "2-digit",
66
+ second: "2-digit"
67
+ });
68
+ }
69
+ formatISOTimestamp() {
70
+ return (/* @__PURE__ */ new Date()).toISOString();
71
+ }
72
+ redactSensitive(e) {
73
+ if (typeof e != "object" || e === null)
74
+ return e;
75
+ if (Array.isArray(e))
76
+ return e.map((r) => this.redactSensitive(r));
77
+ const t = {};
78
+ for (const [r, o] of Object.entries(e)) {
79
+ const s = r.toLowerCase();
80
+ ae.some((i) => s.includes(i)) ? t[r] = "[REDACTED]" : typeof o == "object" && o !== null ? t[r] = this.redactSensitive(o) : t[r] = o;
81
+ }
82
+ return t;
83
+ }
84
+ formatData(e, t = 3, r = 0) {
85
+ if (r >= t)
86
+ return "[Max Depth]";
87
+ if (e == null)
88
+ return e;
89
+ if (e instanceof Error)
90
+ return {
91
+ name: e.name,
92
+ message: e.message,
93
+ stack: x ? e.stack?.split(`
94
+ `).slice(0, 3).join(`
95
+ `) : e.stack,
96
+ ...e
97
+ // Include any additional error properties
98
+ };
99
+ if (e instanceof Date)
100
+ return e.toISOString();
101
+ if (typeof e != "object")
102
+ return e;
103
+ if (Array.isArray(e))
104
+ return e.length > 20 && x ? `Array(${e.length}) [${e.slice(0, 3).map((o) => this.formatData(o, t, r + 1)).join(", ")}, ...]` : e.map((o) => this.formatData(o, t, r + 1));
105
+ try {
106
+ const o = {}, s = Object.entries(e), i = x ? 50 : 200;
107
+ for (const [l, u] of s.slice(0, i))
108
+ o[l] = this.formatData(u, t, r + 1);
109
+ return s.length > i && (o["..."] = `${s.length - i} more properties`), this.redactSensitive(o);
110
+ } catch {
111
+ return "[Unserializable]";
112
+ }
113
+ }
114
+ logToBrowser(e) {
115
+ if (!m || !this.shouldLog(e.level))
116
+ return;
117
+ const { level: t, description: r, context: o, data: s, error: i } = e, l = A[t], a = `[${o || this.context || "www"}] ${t.toUpperCase()}:`, d = `color: ${l.color}; font-weight: bold;`;
118
+ s !== void 0 ? console[t](`%c${a}`, d, r, this.formatData(s)) : console[t](`%c${a}`, d, r), i && (i instanceof Error ? console.error(i) : console.error("Error details:", i));
119
+ }
120
+ logToNode(e) {
121
+ if (!B || !this.shouldLog(e.level))
122
+ return;
123
+ const { level: t, description: r, context: o, data: s, error: i } = e, l = o || this.context || "www";
124
+ if (x) {
125
+ const u = {
126
+ timestamp: this.formatISOTimestamp(),
127
+ level: t.toUpperCase()
128
+ };
129
+ s && (u.data = this.formatData(s)), i && (u.error = this.formatData(i)), console[t](`${u.timestamp} ${u.level} [${l}] ${r}`, s || i ? JSON.stringify({ data: s, error: i }) : "");
130
+ } else {
131
+ const u = A[t], a = this.formatTimestamp(), d = "\x1B[0m", I = "\x1B[2m", g = u.nodeColor || "", k = `${I}${a}${d} ${g}${t.toUpperCase()} (${l}):${d} ${r}`;
132
+ console[t](k), s !== void 0 && console.log(JSON.stringify(this.formatData(s), null, 2)), i && (i instanceof Error ? (console.error(`\x1B[31mError:${d}`, i.message), i.stack && console.error(`\x1B[90m${i.stack}${d}`)) : console.error("Error:", i));
133
+ }
134
+ }
135
+ log(e) {
136
+ m ? this.logToBrowser(e) : B && this.logToNode(e);
137
+ }
138
+ error(e, t) {
139
+ this.log({ level: "error", description: e, data: t, context: this.context });
140
+ }
141
+ warn(e, t) {
142
+ this.log({ level: "warn", description: e, data: t, context: this.context });
143
+ }
144
+ info(e, t) {
145
+ this.log({ level: "info", description: e, data: t, context: this.context });
146
+ }
147
+ debug(e, t) {
148
+ this.log({ level: "debug", description: e, data: t, context: this.context });
149
+ }
150
+ trace(e, t) {
151
+ this.log({ level: "trace", description: e, data: t, context: this.context });
152
+ }
153
+ isEnabled() {
154
+ return m ? this.enabledInBrowser : !0;
155
+ }
156
+ setLevel(e) {
157
+ this.settings.minLevel = e;
158
+ }
159
+ createContextLogger(e) {
160
+ const t = new y(this.settings, e);
161
+ return {
162
+ error: /* @__PURE__ */ c((r, o) => t.error(r, o), "error"),
163
+ warn: /* @__PURE__ */ c((r, o) => t.warn(r, o), "warn"),
164
+ info: /* @__PURE__ */ c((r, o) => t.info(r, o), "info"),
165
+ debug: /* @__PURE__ */ c((r, o) => t.debug(r, o), "debug"),
166
+ trace: /* @__PURE__ */ c((r, o) => t.trace(r, o), "trace"),
167
+ isEnabled: /* @__PURE__ */ c(() => t.isEnabled(), "isEnabled"),
168
+ setLevel: /* @__PURE__ */ c((r) => t.setLevel(r), "setLevel")
169
+ };
170
+ }
171
+ };
172
+ c(y, "Logger"), n(y, "hasShownHelp", !1);
173
+ let P = y;
174
+ function re(h) {
175
+ return new P({}, h).createContextLogger(h);
176
+ }
177
+ c(re, "createLogger");
178
+ const p = new P();
179
+ p.error.bind(p);
180
+ p.warn.bind(p);
181
+ p.info.bind(p);
182
+ p.debug.bind(p);
183
+ p.trace.bind(p);
184
+ const K = class K {
185
+ constructor(e, t) {
186
+ n(this, "name");
187
+ n(this, "settings");
188
+ n(this, "logger");
189
+ this.name = e, this.settings = t, this.logger = re(e);
190
+ }
191
+ };
192
+ c(K, "SettingsObject");
193
+ let O = K;
194
+ const z = class z {
195
+ constructor() {
196
+ // Configuration properties
197
+ n(this, "tokenName", "auth-token");
198
+ n(this, "tokenMaxAge", 3600 * 24 * 7);
199
+ // 7 days
200
+ n(this, "fallbackStorageKey", "token");
201
+ // For localStorage migration
202
+ n(this, "productionDomain", ".pagelines.com");
203
+ }
204
+ /**
205
+ * Get cookie value by name
206
+ */
207
+ getCookie(e) {
208
+ if (typeof document > "u")
209
+ return null;
210
+ const t = document.cookie.split(";");
211
+ for (const r of t) {
212
+ const [o, s] = r.trim().split("=");
213
+ if (o === e)
214
+ return decodeURIComponent(s || "");
215
+ }
216
+ return null;
217
+ }
218
+ /**
219
+ * Set cookie with secure defaults
220
+ */
221
+ setCookie(e, t, r = {}) {
222
+ if (typeof document > "u")
223
+ return;
224
+ const {
225
+ secure: o = !0,
226
+ sameSite: s = "lax",
227
+ maxAge: i = 3600 * 24 * 7,
228
+ // 7 days default
229
+ domain: l,
230
+ path: u = "/"
231
+ } = r;
232
+ let a = `${e}=${encodeURIComponent(t)}`;
233
+ a += `; Path=${u}`, a += `; Max-Age=${i}`, a += `; SameSite=${s}`, o && (a += "; Secure"), l && (a += `; Domain=${l}`), document.cookie = a;
234
+ }
235
+ /**
236
+ * Remove cookie by setting expired date
237
+ */
238
+ removeCookie(e, t = {}) {
239
+ this.setCookie(e, "", { ...t, maxAge: 0 });
240
+ }
241
+ /**
242
+ * Check if localStorage is fully functional (some test environments provide partial mocks)
243
+ */
244
+ isLocalStorageFunctional() {
245
+ return typeof window < "u" && typeof window.localStorage?.getItem == "function" && typeof window.localStorage?.setItem == "function" && typeof window.localStorage?.removeItem == "function";
246
+ }
247
+ /**
248
+ * Get auth token with fallback to localStorage for migration
249
+ */
250
+ getAuthToken() {
251
+ const e = this.getCookie(this.tokenName);
252
+ if (e)
253
+ return e;
254
+ if (this.isLocalStorageFunctional()) {
255
+ const t = window.localStorage.getItem(this.fallbackStorageKey);
256
+ if (t)
257
+ return this.setAuthToken(t), window.localStorage.removeItem(this.fallbackStorageKey), t;
258
+ }
259
+ return null;
260
+ }
261
+ /**
262
+ * Set auth token in cookie with production-ready settings
263
+ */
264
+ setAuthToken(e) {
265
+ const t = typeof window < "u" && window.location.hostname !== "localhost";
266
+ this.setCookie(this.tokenName, e, {
267
+ secure: t,
268
+ sameSite: "lax",
269
+ maxAge: this.tokenMaxAge,
270
+ domain: t ? this.productionDomain : void 0,
271
+ path: "/"
272
+ });
273
+ }
274
+ /**
275
+ * Remove auth token
276
+ */
277
+ removeAuthToken() {
278
+ const e = typeof window < "u" && window.location.hostname !== "localhost";
279
+ this.removeCookie(this.tokenName, {
280
+ domain: e ? this.productionDomain : void 0,
281
+ path: "/"
282
+ }), this.isLocalStorageFunctional() && window.localStorage.removeItem(this.fallbackStorageKey);
283
+ }
284
+ };
285
+ c(z, "CookieUtil");
286
+ let M = z;
287
+ const C = new M();
288
+ function ce(h, e) {
289
+ const t = h.apiBase || (h.isDev ? `http://localhost:${F}` : D);
290
+ return ie(t, {
291
+ fetch: /* @__PURE__ */ c(async (o, s) => {
292
+ const i = C.getAuthToken(), l = await fetch(o, {
293
+ ...s,
294
+ headers: {
295
+ ...s?.headers,
296
+ "Content-Type": "application/json",
297
+ // Only include Authorization header if token exists
298
+ ...i && { Authorization: `Bearer ${i}` }
299
+ },
300
+ // Use 'omit' for Bearer tokens (not cookies) to allow CORS wildcard origin
301
+ credentials: "omit"
302
+ });
303
+ if (e) {
304
+ const u = l.json.bind(l);
305
+ l.json = async () => {
306
+ const a = await u();
307
+ return typeof a == "object" && a !== null && "ok" in a && ("user" in a || "token" in a) && e(a), a;
308
+ };
309
+ }
310
+ return l;
311
+ }, "fetch")
312
+ });
313
+ }
314
+ c(ce, "createApiClient");
315
+ let le = /* @__PURE__ */ Symbol("clean"), f = [], w = 0;
316
+ const $ = 4, oe = /* @__PURE__ */ c(/* @__NO_SIDE_EFFECTS__ */ (h) => {
317
+ let e = [], t = {
318
+ get() {
319
+ return t.lc || t.listen(() => {
320
+ })(), t.value;
321
+ },
322
+ lc: 0,
323
+ listen(r) {
324
+ return t.lc = e.push(r), () => {
325
+ for (let s = w + $; s < f.length; )
326
+ f[s] === r ? f.splice(s, $) : s += $;
327
+ let o = e.indexOf(r);
328
+ ~o && (e.splice(o, 1), --t.lc || t.off());
329
+ };
330
+ },
331
+ notify(r, o) {
332
+ let s = !f.length;
333
+ for (let i of e)
334
+ f.push(i, t.value, r, o);
335
+ if (s) {
336
+ for (w = 0; w < f.length; w += $)
337
+ f[w](
338
+ f[w + 1],
339
+ f[w + 2],
340
+ f[w + 3]
341
+ );
342
+ f.length = 0;
343
+ }
344
+ },
345
+ /* It will be called on last listener unsubscribing.
346
+ We will redefine it in onMount and onStop. */
347
+ off() {
348
+ },
349
+ set(r) {
350
+ let o = t.value;
351
+ o !== r && (t.value = r, t.notify(o));
352
+ },
353
+ subscribe(r) {
354
+ let o = t.listen(r);
355
+ return r(t.value), o;
356
+ },
357
+ value: h
358
+ };
359
+ return process.env.NODE_ENV !== "production" && (t[le] = () => {
360
+ e = [], t.lc = 0, t.off();
361
+ }), t;
362
+ }, "atom"), L = /* @__PURE__ */ oe(void 0), U = /* @__PURE__ */ oe(null), J = class J {
363
+ constructor() {
364
+ n(this, "logger", re("SDKStorage"));
365
+ }
366
+ /**
367
+ * Check if localStorage is fully functional (some test environments provide partial mocks)
368
+ */
369
+ isLocalStorageFunctional() {
370
+ return typeof window < "u" && typeof localStorage?.getItem == "function" && typeof localStorage?.setItem == "function" && typeof localStorage?.removeItem == "function";
371
+ }
372
+ /**
373
+ * Sync Vue reactive refs with global nanostores for cross-page persistence
374
+ */
375
+ syncWithGlobalStores(e, t) {
376
+ const r = L.get(), o = U.get();
377
+ r && (e.value = r), o && (t.value = o), Z(e, (s) => {
378
+ L.set(s);
379
+ }, { immediate: !0 }), Z(t, (s) => {
380
+ U.set(s);
381
+ }, { immediate: !0 }), L.subscribe((s) => {
382
+ s !== e.value && (e.value = s);
383
+ }), U.subscribe((s) => {
384
+ s !== t.value && (t.value = s);
385
+ });
386
+ }
387
+ /**
388
+ * Load user and token from browser storage on initialization
389
+ */
390
+ loadFromStorage(e, t) {
391
+ if (typeof window > "u")
392
+ return;
393
+ const r = C.getAuthToken();
394
+ if (r && (t.value = r), this.isLocalStorageFunctional())
395
+ try {
396
+ const o = localStorage.getItem("pagelines-user");
397
+ o && (e.value = JSON.parse(o));
398
+ } catch (o) {
399
+ this.logger.error("Failed to load user from localStorage", { data: o });
400
+ }
401
+ }
402
+ /**
403
+ * Save current user and token to browser storage
404
+ */
405
+ saveToStorage(e, t) {
406
+ if (!(typeof window > "u") && (t.value ? C.setAuthToken(t.value) : C.removeAuthToken(), this.isLocalStorageFunctional()))
407
+ try {
408
+ e.value ? localStorage.setItem("pagelines-user", JSON.stringify(e.value)) : localStorage.removeItem("pagelines-user");
409
+ } catch (r) {
410
+ this.logger.error("Failed to save user to localStorage", { data: r });
411
+ }
412
+ }
413
+ /**
414
+ * Clear all stored user data and tokens
415
+ */
416
+ clearStorage() {
417
+ if (!(typeof window > "u")) {
418
+ if (C.removeAuthToken(), this.isLocalStorageFunctional())
419
+ try {
420
+ localStorage.removeItem("pagelines-user");
421
+ } catch (e) {
422
+ this.logger.error("Failed to clear user from localStorage", { data: e });
423
+ }
424
+ L.set(void 0), U.set(null);
425
+ }
426
+ }
427
+ /**
428
+ * Generic localStorage getter
429
+ */
430
+ getItem(e) {
431
+ if (!this.isLocalStorageFunctional())
432
+ return null;
433
+ try {
434
+ return localStorage.getItem(e);
435
+ } catch (t) {
436
+ return this.logger.error("Failed to get item from localStorage", { key: e, error: t }), null;
437
+ }
438
+ }
439
+ /**
440
+ * Generic localStorage setter
441
+ */
442
+ setItem(e, t) {
443
+ if (this.isLocalStorageFunctional())
444
+ try {
445
+ localStorage.setItem(e, t);
446
+ } catch (r) {
447
+ this.logger.error("Failed to set item in localStorage", { key: e, error: r });
448
+ }
449
+ }
450
+ };
451
+ c(J, "SDKStorage");
452
+ let G = J;
453
+ const V = class V {
454
+ constructor(e) {
455
+ this.ctx = e;
456
+ }
457
+ async sendCode(e) {
458
+ this.ctx.loading.value = !0, this.ctx.error.value = null;
459
+ try {
460
+ const r = await (await this.ctx.api.auth["check-email"].$post({
461
+ json: { email: e }
462
+ })).json();
463
+ if (!r.ok)
464
+ throw this.ctx.error.value = r.error, new Error(r.error);
465
+ } catch (t) {
466
+ this.ctx.logger.error("Send code error", { data: t });
467
+ const r = t instanceof Error ? t.message : "Failed to send verification code";
468
+ throw this.ctx.error.value = r, t;
469
+ } finally {
470
+ this.ctx.loading.value = !1;
471
+ }
472
+ }
473
+ async verifyCode(e, t) {
474
+ this.ctx.loading.value = !0, this.ctx.error.value = null;
475
+ try {
476
+ const o = await (await this.ctx.api.auth["verify-code"].$post({
477
+ json: { email: e, code: t }
478
+ })).json();
479
+ if (!o.ok)
480
+ throw this.ctx.error.value = o.error, new Error(o.error);
481
+ } catch (r) {
482
+ this.ctx.logger.error("Verify code error", { data: r });
483
+ const o = r instanceof Error ? r.message : "Failed to verify code";
484
+ throw this.ctx.error.value = o, r;
485
+ } finally {
486
+ this.ctx.loading.value = !1;
487
+ }
488
+ }
489
+ async login(e, t) {
490
+ this.ctx.loading.value = !0, this.ctx.error.value = null;
491
+ try {
492
+ const o = await (await this.ctx.api.auth.login.$post({
493
+ json: { email: e, password: t }
494
+ })).json();
495
+ if (!o.ok)
496
+ throw this.ctx.error.value = o.error, new Error(o.error);
497
+ } catch (r) {
498
+ this.ctx.logger.error("Login error", { data: r });
499
+ const o = r instanceof Error ? r.message : "Login failed";
500
+ throw this.ctx.error.value = o, r;
501
+ } finally {
502
+ this.ctx.loading.value = !1;
503
+ }
504
+ }
505
+ async logout() {
506
+ this.ctx.loading.value = !0, this.ctx.error.value = null;
507
+ try {
508
+ await this.ctx.api.auth.logout.$post(), this.ctx.activeUser.value = void 0, this.ctx.token.value = null, this.ctx.storage.clearStorage();
509
+ } catch (e) {
510
+ this.ctx.logger.error("Logout error (user still logged out locally)", { data: e }), this.ctx.activeUser.value = void 0, this.ctx.token.value = null, this.ctx.storage.clearStorage();
511
+ } finally {
512
+ this.ctx.loading.value = !1;
513
+ }
514
+ }
515
+ async getCurrentUser() {
516
+ if (this.ctx.token.value) {
517
+ this.ctx.loading.value = !0;
518
+ try {
519
+ const t = await (await this.ctx.api.auth.me.$get()).json();
520
+ if (!t.ok) {
521
+ this.ctx.error.value = t.error, t.error.includes("Authentication") && (this.ctx.activeUser.value = void 0, this.ctx.token.value = null, this.ctx.storage.clearStorage());
522
+ return;
523
+ }
524
+ return t.user;
525
+ } catch (e) {
526
+ this.ctx.logger.error("Get current user error", { data: e }), this.ctx.error.value = e instanceof Error ? e.message : "Failed to get user info";
527
+ return;
528
+ } finally {
529
+ this.ctx.loading.value = !1;
530
+ }
531
+ }
532
+ }
533
+ async requestAuthCode(e) {
534
+ this.ctx.loading.value = !0, this.ctx.error.value = null;
535
+ try {
536
+ const r = await (await this.ctx.api.auth["check-email"].$post({
537
+ json: { email: e.email }
538
+ })).json();
539
+ return r.ok ? (this.ctx.logger.info("Auth code requested successfully", { email: e.email }), !0) : (this.ctx.error.value = r.error, this.ctx.logger.error("Failed to request auth code", { email: e.email, error: r.error }), !1);
540
+ } catch (t) {
541
+ return this.ctx.logger.error("Request auth code error", { email: e.email, error: t }), this.ctx.error.value = t instanceof Error ? t.message : "Failed to request auth code", !1;
542
+ } finally {
543
+ this.ctx.loading.value = !1;
544
+ }
545
+ }
546
+ async loginWithCode(e) {
547
+ this.ctx.loading.value = !0, this.ctx.error.value = null;
548
+ try {
549
+ const r = await (await this.ctx.api.auth["verify-code"].$post({
550
+ json: { email: e.email, code: e.code }
551
+ })).json();
552
+ return this.ctx.logger.info("Login with code response", {
553
+ hasUser: !!r.user,
554
+ hasToken: !!r.token,
555
+ ok: r.ok
556
+ }), r.ok ? (this.ctx.logger.info("Login successful", { email: e.email }), e.orgId && e.autoCreateContact !== !1 && this.ctx.activeUser.value?.userId && await this.autoCreateContact({
557
+ userId: this.ctx.activeUser.value.userId,
558
+ orgId: e.orgId
559
+ }), !0) : (this.ctx.error.value = r.error, this.ctx.logger.error("Login failed", { email: e.email, error: r.error }), !1);
560
+ } catch (t) {
561
+ return this.ctx.logger.error("Login with code error", { email: e.email, error: t }), this.ctx.error.value = t instanceof Error ? t.message : "Login failed", !1;
562
+ } finally {
563
+ this.ctx.loading.value = !1;
564
+ }
565
+ }
566
+ async autoCreateContact(e) {
567
+ try {
568
+ const r = await (await this.ctx.api.contact.resolve.$post({
569
+ json: { userId: e.userId, orgId: e.orgId }
570
+ })).json();
571
+ return r.ok ? (this.ctx.logger.info("Contact resolved", { userId: e.userId, orgId: e.orgId }), !0) : (this.ctx.logger.error("Failed to auto-create contact", { error: r.error, args: e }), !1);
572
+ } catch (t) {
573
+ return this.ctx.logger.error("Auto-create contact error", { error: t, args: e }), !1;
574
+ }
575
+ }
576
+ loginWithGoogle(e) {
577
+ if (typeof window > "u") {
578
+ this.ctx.logger.error("loginWithGoogle: Only available in browser");
579
+ return;
580
+ }
581
+ const t = this.ctx.apiBase || (this.ctx.isDev ? `http://localhost:${F}` : D), r = window.location.origin, o = `${t}/auth/google-popup?origin=${encodeURIComponent(r)}`, s = 500, i = 600, l = window.screenX + (window.outerWidth - s) / 2, u = window.screenY + (window.outerHeight - i) / 2, a = window.open(
582
+ o,
583
+ "google-auth",
584
+ `width=${s},height=${i},left=${l},top=${u},popup=yes`
585
+ );
586
+ if (!a) {
587
+ const g = "Popup was blocked. Please allow popups for this site.";
588
+ this.ctx.error.value = g, e?.onError?.(g);
589
+ return;
590
+ }
591
+ const d = /* @__PURE__ */ c((g) => {
592
+ const k = new URL(t).origin;
593
+ if (g.origin === k) {
594
+ if (g.data?.type === "auth-success") {
595
+ window.removeEventListener("message", d);
596
+ const { token: v, user: b } = g.data;
597
+ this.ctx.processApiResponse({ ok: !0, data: {}, token: v, user: b }), this.ctx.logger.info("Google login successful"), e?.onSuccess?.(b);
598
+ } else if (g.data?.type === "auth-error") {
599
+ window.removeEventListener("message", d);
600
+ const v = g.data.error || "Google authentication failed";
601
+ this.ctx.error.value = v, this.ctx.logger.error("Google login failed", { error: v }), e?.onError?.(v);
602
+ }
603
+ }
604
+ }, "handler");
605
+ window.addEventListener("message", d);
606
+ const I = setInterval(() => {
607
+ a.closed && (clearInterval(I), window.removeEventListener("message", d));
608
+ }, 500);
609
+ }
610
+ };
611
+ c(V, "AuthClient");
612
+ let R = V;
613
+ const H = class H {
614
+ constructor(e) {
615
+ this.ctx = e;
616
+ }
617
+ async chatStream(e) {
618
+ const r = `${this.ctx.apiBase || (this.ctx.isDev ? `http://localhost:${F}` : D)}/api/agent/public/${encodeURIComponent(e.handle)}/chat/stream`;
619
+ try {
620
+ const o = await fetch(r, {
621
+ method: "POST",
622
+ headers: { "Content-Type": "application/json" },
623
+ body: JSON.stringify({
624
+ message: e.message,
625
+ conversationId: e.conversationId,
626
+ history: e.history,
627
+ visitorId: e.visitorId
628
+ })
629
+ });
630
+ if (!o.ok) {
631
+ const a = await o.json().catch(() => ({ error: "Request failed" }));
632
+ e.onError(a.error || `HTTP ${o.status}`);
633
+ return;
634
+ }
635
+ const s = o.body?.getReader();
636
+ if (!s) {
637
+ e.onError("No response stream");
638
+ return;
639
+ }
640
+ const i = new TextDecoder();
641
+ let l = "", u = e.conversationId || "";
642
+ for (; ; ) {
643
+ const { done: a, value: d } = await s.read();
644
+ if (a)
645
+ break;
646
+ l += i.decode(d, { stream: !0 });
647
+ const I = l.split(`
648
+ `);
649
+ l = I.pop() || "";
650
+ for (const g of I) {
651
+ if (!g.startsWith("data: "))
652
+ continue;
653
+ const k = g.slice(6).trim();
654
+ if (k === "[DONE]") {
655
+ e.onDone(u);
656
+ return;
657
+ }
658
+ try {
659
+ const v = JSON.parse(k);
660
+ v.pl_metadata?.conversationId && (u = v.pl_metadata.conversationId);
661
+ const b = v.choices?.[0]?.delta;
662
+ b?.content && e.onDelta(b.content);
663
+ } catch {
664
+ }
665
+ }
666
+ }
667
+ e.onDone(u);
668
+ } catch (o) {
669
+ e.onError(o instanceof Error ? o.message : "Stream failed");
670
+ }
671
+ }
672
+ async chatMessage(e) {
673
+ const r = `${this.ctx.apiBase || (this.ctx.isDev ? `http://localhost:${F}` : D)}/api/agent/public/${encodeURIComponent(e.handle)}/chat`;
674
+ try {
675
+ const s = await (await fetch(r, {
676
+ method: "POST",
677
+ headers: { "Content-Type": "application/json" },
678
+ body: JSON.stringify({
679
+ message: e.message,
680
+ conversationId: e.conversationId,
681
+ visitorId: e.visitorId
682
+ })
683
+ })).json();
684
+ if (!s.ok || !s.data) {
685
+ this.ctx.logger.error("chatMessage failed", { error: !s.ok && "error" in s ? s.error : "Unknown" });
686
+ return;
687
+ }
688
+ return {
689
+ conversationId: s.data.conversationId,
690
+ content: s.data.message.content
691
+ };
692
+ } catch (o) {
693
+ this.ctx.logger.error("chatMessage error", { error: o });
694
+ return;
695
+ }
696
+ }
697
+ async saveMessage(e) {
698
+ try {
699
+ const r = await (await this.ctx.api.conversation.messages.$post({
700
+ json: {
701
+ sessionId: e.conversationId,
702
+ participantId: e.participantId,
703
+ content: e.content,
704
+ role: e.role
705
+ }
706
+ })).json();
707
+ return r.ok ? !0 : (this.ctx.logger.error("Failed to save message", { error: "error" in r ? r.error : "Unknown error", args: e }), !1);
708
+ } catch (t) {
709
+ return this.ctx.logger.error("Save message error", { error: t, args: e }), !1;
710
+ }
711
+ }
712
+ };
713
+ c(H, "ChatClient");
714
+ let _ = H;
715
+ const Q = class Q {
716
+ constructor(e) {
717
+ this.ctx = e;
718
+ }
719
+ async getPublicAgent(e) {
720
+ this.ctx.loading.value = !0, this.ctx.error.value = null;
721
+ try {
722
+ const r = await (await this.ctx.api.agent.public[":handle"].$get({
723
+ param: { handle: e.handle }
724
+ })).json();
725
+ if (!r.ok) {
726
+ this.ctx.error.value = r.error, this.ctx.logger.error("Failed to fetch public agent", { handle: e.handle, error: r.error });
727
+ return;
728
+ }
729
+ return r.data;
730
+ } catch (t) {
731
+ this.ctx.logger.error("Get public agent error", { handle: e.handle, error: t }), this.ctx.error.value = t instanceof Error ? t.message : "Failed to fetch agent";
732
+ return;
733
+ } finally {
734
+ this.ctx.loading.value = !1;
735
+ }
736
+ }
737
+ async getAgentByEmail(e) {
738
+ this.ctx.loading.value = !0, this.ctx.error.value = null;
739
+ try {
740
+ const r = await (await this.ctx.api.agent["by-email"][":email"].$get({
741
+ param: { email: e.email }
742
+ })).json();
743
+ if (!r.ok) {
744
+ this.ctx.error.value = r.error, this.ctx.logger.error("Failed to fetch agent by email", { email: e.email, error: r.error });
745
+ return;
746
+ }
747
+ return r.data;
748
+ } catch (t) {
749
+ this.ctx.logger.error("Get agent by email error", { email: e.email, error: t }), this.ctx.error.value = t instanceof Error ? t.message : "Failed to fetch agent";
750
+ return;
751
+ } finally {
752
+ this.ctx.loading.value = !1;
753
+ }
754
+ }
755
+ async trackUsage(e) {
756
+ try {
757
+ const t = this.ctx.currentAgent.value;
758
+ if (!t?.orgId)
759
+ return this.ctx.logger.error("Cannot track usage: no current agent with orgId", { args: e }), !1;
760
+ const o = await (await this.ctx.api.usage.record.$post({
761
+ json: {
762
+ orgId: t.orgId,
763
+ agentId: e.agentId,
764
+ sessionId: this.ctx.sessionId,
765
+ // Auto-managed by SDK
766
+ type: e.type,
767
+ quantity: e.quantity,
768
+ // Track the participant if provided, otherwise use current user or anonymous
769
+ userId: e.participantId || this.ctx.activeUser.value?.userId || "anonymous"
770
+ }
771
+ })).json();
772
+ return o.ok ? !0 : (this.ctx.logger.error("Failed to track usage", { error: o.error, args: e }), !1);
773
+ } catch (t) {
774
+ return this.ctx.logger.error("Track usage error", { error: t, args: e }), !1;
775
+ }
776
+ }
777
+ async startConversation(e) {
778
+ try {
779
+ const t = this.ctx.currentAgent.value;
780
+ if (!t?.orgId) {
781
+ this.ctx.logger.error("Cannot start conversation: no current agent with orgId", { args: e });
782
+ return;
783
+ }
784
+ const o = await (await this.ctx.api.conversation.start.$post({
785
+ json: {
786
+ orgId: t.orgId,
787
+ agentId: e.agentId,
788
+ userId: e.userId || this.ctx.activeUser.value?.userId,
789
+ anonId: e.anonId,
790
+ channel: e.channel
791
+ }
792
+ })).json();
793
+ if (!o.ok || !o.data) {
794
+ const s = o.ok ? "No conversation data returned" : "error" in o ? o.error : "Unknown error";
795
+ this.ctx.logger.error("Failed to start conversation", { error: s, args: e });
796
+ return;
797
+ }
798
+ return this.ctx.logger.info("Conversation started", { conversationId: o.data.conversationId }), o.data;
799
+ } catch (t) {
800
+ this.ctx.logger.error("Start conversation error", { error: t, args: e });
801
+ return;
802
+ }
803
+ }
804
+ async autoCreateContact(e) {
805
+ try {
806
+ const r = await (await this.ctx.api.contact.resolve.$post({
807
+ json: { userId: e.userId, orgId: e.orgId }
808
+ })).json();
809
+ return r.ok ? (this.ctx.logger.info("Contact resolved", { userId: e.userId, orgId: e.orgId }), !0) : (this.ctx.logger.error("Failed to auto-create contact", { error: r.error, args: e }), !1);
810
+ } catch (t) {
811
+ return this.ctx.logger.error("Auto-create contact error", { error: t, args: e }), !1;
812
+ }
813
+ }
814
+ generateAnonId() {
815
+ const e = "pagelinesAnonId";
816
+ let t = this.ctx.storage.getItem(e);
817
+ return t || (t = N({ prefix: "anon" }), this.ctx.storage.setItem(e, t)), t;
818
+ }
819
+ track(e) {
820
+ try {
821
+ typeof window < "u" && window.parent !== window && window.parent.postMessage({
822
+ type: "pagelines_track",
823
+ event: e.event,
824
+ agentId: e.agentId,
825
+ properties: e.properties || {}
826
+ }, "*"), this.ctx.logger.info("SDK event tracked", { event: e.event, agentId: e.agentId });
827
+ } catch (t) {
828
+ this.ctx.logger.error("Track event error", { error: t, args: e });
829
+ }
830
+ }
831
+ };
832
+ c(Q, "UserClient");
833
+ let q = Q;
834
+ const Y = class Y {
835
+ constructor() {
836
+ n(this, "key", "__PAGELINES_SDK__");
837
+ }
838
+ get() {
839
+ if (!(typeof window > "u"))
840
+ return globalThis[this.key];
841
+ }
842
+ set(e) {
843
+ typeof window < "u" && (globalThis[this.key] = e);
844
+ }
845
+ delete() {
846
+ typeof window < "u" && delete globalThis[this.key];
847
+ }
848
+ };
849
+ c(Y, "SDKGlobal");
850
+ let W = Y;
851
+ const T = new W(), j = class j extends O {
852
+ constructor(t = {}) {
853
+ const r = T.get();
854
+ if (r)
855
+ return console.debug("[PageLinesSDK] Returning existing singleton instance"), r;
856
+ super("PageLinesSDK", t);
857
+ // Vue reactive state
858
+ n(this, "activeUser", E());
859
+ n(this, "token", E(null));
860
+ n(this, "loading", E(!1));
861
+ n(this, "error", E(null));
862
+ n(this, "apiBase", this.settings.apiBase || void 0);
863
+ // Storage handler for persistence
864
+ n(this, "storage", new G());
865
+ // Auto-managed session ID for usage tracking
866
+ n(this, "sessionId", N({ prefix: "ses" }));
867
+ // Typed Hono RPC client - uses SDKAppType (auth/self/usage routes only)
868
+ // Initialized in constructor (definite assignment via singleton pattern)
869
+ n(this, "apiClient");
870
+ // Computed properties derived from activeUser (matches UserClient pattern)
871
+ n(this, "currentAgent", ee(() => {
872
+ const t = this.activeUser.value;
873
+ if (!t?.agents)
874
+ return;
875
+ const r = t.primaryAgentId || t.agents[0]?.agentId;
876
+ if (r)
877
+ return t.agents.find((o) => o.agentId === r);
878
+ }));
879
+ n(this, "currentOrg", ee(() => {
880
+ const t = this.currentAgent.value;
881
+ if (!t?.orgId)
882
+ return;
883
+ const r = this.activeUser.value;
884
+ if (r?.orgs)
885
+ return r.orgs.find((o) => o.orgId === t.orgId);
886
+ }));
887
+ // Initialization state
888
+ n(this, "initialized");
889
+ n(this, "resolveUser");
890
+ // Sub-clients (new preferred API surface)
891
+ n(this, "auth");
892
+ n(this, "chat");
893
+ n(this, "user");
894
+ T.set(this), this.apiClient = ce(
895
+ { isDev: this.isDev, apiBase: this.apiBase },
896
+ this.processApiResponse.bind(this)
897
+ );
898
+ const o = {
899
+ api: this.api,
900
+ apiBase: this.apiBase,
901
+ isDev: this.isDev,
902
+ activeUser: this.activeUser,
903
+ token: this.token,
904
+ loading: this.loading,
905
+ error: this.error,
906
+ currentAgent: this.currentAgent,
907
+ storage: this.storage,
908
+ sessionId: this.sessionId,
909
+ logger: this.logger,
910
+ processApiResponse: this.processApiResponse.bind(this)
911
+ };
912
+ this.auth = new R(o), this.chat = new _(o), this.user = new q(o), this.logger.info("PageLinesSDK initialized"), this.storage.loadFromStorage(this.activeUser, this.token), this.storage.syncWithGlobalStores(this.activeUser, this.token), this.initialized = new Promise((s) => {
913
+ this.resolveUser = s;
914
+ }), this.token.value && !this.activeUser.value ? this.getCurrentUser().then((s) => {
915
+ this.resolveUser && (this.resolveUser(s), this.resolveUser = void 0);
916
+ }).catch((s) => {
917
+ this.logger.error("Auto user fetch failed", { data: s }), this.resolveUser && (this.resolveUser(void 0), this.resolveUser = void 0);
918
+ }) : this.activeUser.value ? this.resolveUser?.(this.activeUser.value) : this.resolveUser?.(void 0);
919
+ }
920
+ /**
921
+ * Get singleton instance in browser (creates if doesn't exist)
922
+ * Node.js: Always creates new instance (no singleton)
923
+ * Recommended: Use this instead of constructor for shared state
924
+ */
925
+ static getInstance(t = {}) {
926
+ return T.get() || new j(t);
927
+ }
928
+ get isDev() {
929
+ return this.settings.isDev ?? (typeof window < "u" ? window.location.hostname === "localhost" || window.location.hostname.includes("127.0.0.1") : !1);
930
+ }
931
+ // Bypass stub typing for route access (production builds use SDKAppType stub)
932
+ // Runtime types are validated via Zod at API boundaries
933
+ get api() {
934
+ return this.apiClient.api;
935
+ }
936
+ // Process ApiResponse for automatic user/token updates - public for dependency injection
937
+ processApiResponse(t) {
938
+ t.ok && t.user && (this.activeUser.value = t.user, this.logger.info("User updated from API response", { data: t.user })), t.ok && t.token && (this.token.value = t.token, this.storage.saveToStorage(this.activeUser, this.token), this.logger.info("Token updated from API response")), this.resolveUser && t.ok && (this.resolveUser(t.user), this.resolveUser = void 0);
939
+ }
940
+ // Clear all user data and tokens
941
+ clearSession() {
942
+ this.logger.info("Clearing session"), this.activeUser.value = void 0, this.token.value = null, this.error.value = null, this.storage.clearStorage();
943
+ }
944
+ // Full reset - clears session + state + destroys singleton
945
+ clear() {
946
+ this.logger.info("Clearing SDK completely"), this.clearSession(), this.loading.value = !1, this.sessionId = N({ prefix: "ses" }), T.delete();
947
+ }
948
+ // Backward-compatible delegates -- these forward to sub-clients
949
+ // Can be removed in a future breaking change
950
+ async sendCode(t) {
951
+ return this.auth.sendCode(t);
952
+ }
953
+ async verifyCode(t, r) {
954
+ return this.auth.verifyCode(t, r);
955
+ }
956
+ async login(t, r) {
957
+ return this.auth.login(t, r);
958
+ }
959
+ async logout() {
960
+ return this.auth.logout();
961
+ }
962
+ async getCurrentUser() {
963
+ return this.auth.getCurrentUser();
964
+ }
965
+ async requestAuthCode(t) {
966
+ return this.auth.requestAuthCode(t);
967
+ }
968
+ async loginWithCode(t) {
969
+ return this.auth.loginWithCode(t);
970
+ }
971
+ loginWithGoogle(t) {
972
+ return this.auth.loginWithGoogle(t);
973
+ }
974
+ async chatStream(t) {
975
+ return this.chat.chatStream(t);
976
+ }
977
+ async chatMessage(t) {
978
+ return this.chat.chatMessage(t);
979
+ }
980
+ async saveMessage(t) {
981
+ return this.chat.saveMessage(t);
982
+ }
983
+ async getPublicAgent(t) {
984
+ return this.user.getPublicAgent(t);
985
+ }
986
+ async getAgentByEmail(t) {
987
+ return this.user.getAgentByEmail(t);
988
+ }
989
+ async trackUsage(t) {
990
+ return this.user.trackUsage(t);
991
+ }
992
+ async startConversation(t) {
993
+ return this.user.startConversation(t);
994
+ }
995
+ async autoCreateContact(t) {
996
+ return this.user.autoCreateContact(t);
997
+ }
998
+ generateAnonId() {
999
+ return this.user.generateAnonId();
1000
+ }
1001
+ track(t) {
1002
+ return this.user.track(t);
1003
+ }
1004
+ };
1005
+ c(j, "PageLinesSDK");
1006
+ let te = j;
1007
+ export {
1008
+ R as A,
1009
+ _ as C,
1010
+ te as P,
1011
+ O as S,
1012
+ q as U,
1013
+ re as c
1014
+ };
1015
+ //# sourceMappingURL=sdkClient-yg_rc4B7.js.map