@tagadapay/plugin-sdk 3.0.2 → 3.0.9

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 (49) hide show
  1. package/build-cdn.js +113 -0
  2. package/dist/config/basisTheory.d.ts +26 -0
  3. package/dist/config/basisTheory.js +29 -0
  4. package/dist/external-tracker.js +4947 -0
  5. package/dist/external-tracker.min.js +11 -0
  6. package/dist/external-tracker.min.js.map +7 -0
  7. package/dist/react/config/payment.d.ts +8 -8
  8. package/dist/react/config/payment.js +17 -21
  9. package/dist/react/hooks/useApplePay.js +1 -1
  10. package/dist/react/hooks/usePayment.js +1 -3
  11. package/dist/react/hooks/useThreeds.js +2 -2
  12. package/dist/v2/core/client.d.ts +31 -3
  13. package/dist/v2/core/client.js +234 -9
  14. package/dist/v2/core/config/environment.d.ts +16 -3
  15. package/dist/v2/core/config/environment.js +72 -3
  16. package/dist/v2/core/funnelClient.d.ts +4 -0
  17. package/dist/v2/core/funnelClient.js +106 -4
  18. package/dist/v2/core/resources/funnel.d.ts +22 -0
  19. package/dist/v2/core/resources/offers.d.ts +64 -3
  20. package/dist/v2/core/resources/offers.js +112 -10
  21. package/dist/v2/core/resources/postPurchases.js +4 -1
  22. package/dist/v2/core/utils/configHotReload.d.ts +39 -0
  23. package/dist/v2/core/utils/configHotReload.js +75 -0
  24. package/dist/v2/core/utils/eventBus.d.ts +11 -0
  25. package/dist/v2/core/utils/eventBus.js +34 -0
  26. package/dist/v2/core/utils/pluginConfig.d.ts +14 -5
  27. package/dist/v2/core/utils/pluginConfig.js +74 -59
  28. package/dist/v2/core/utils/previewMode.d.ts +114 -0
  29. package/dist/v2/core/utils/previewMode.js +379 -0
  30. package/dist/v2/core/utils/sessionStorage.d.ts +5 -0
  31. package/dist/v2/core/utils/sessionStorage.js +22 -0
  32. package/dist/v2/index.d.ts +4 -1
  33. package/dist/v2/index.js +3 -1
  34. package/dist/v2/react/hooks/useOfferQuery.js +50 -17
  35. package/dist/v2/react/hooks/usePaymentQuery.js +1 -3
  36. package/dist/v2/react/hooks/usePreviewOffer.d.ts +84 -0
  37. package/dist/v2/react/hooks/usePreviewOffer.js +290 -0
  38. package/dist/v2/react/hooks/useThreeds.js +2 -2
  39. package/dist/v2/react/index.d.ts +2 -0
  40. package/dist/v2/react/index.js +1 -0
  41. package/dist/v2/react/providers/TagadaProvider.d.ts +1 -2
  42. package/dist/v2/react/providers/TagadaProvider.js +51 -34
  43. package/dist/v2/standalone/external-tracker.d.ts +119 -0
  44. package/dist/v2/standalone/external-tracker.js +260 -0
  45. package/dist/v2/standalone/index.d.ts +2 -0
  46. package/dist/v2/standalone/index.js +6 -0
  47. package/package.json +11 -3
  48. package/dist/v2/react/hooks/useOffersQuery.d.ts +0 -12
  49. package/dist/v2/react/hooks/useOffersQuery.js +0 -404
@@ -0,0 +1,4947 @@
1
+ /**
2
+ * TagadaPay External Tracker v3.0.9
3
+ * CDN Bundle - Standalone tracking for external pages (Debug Build)
4
+ * @license MIT
5
+ */
6
+ "use strict";
7
+ var TagadaTrackerBundle = (() => {
8
+ var __defProp = Object.defineProperty;
9
+ var __defProps = Object.defineProperties;
10
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
11
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
12
+ var __getOwnPropNames = Object.getOwnPropertyNames;
13
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
14
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
15
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
16
+ var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : Symbol.for("Symbol." + name);
17
+ var __typeError = (msg) => {
18
+ throw TypeError(msg);
19
+ };
20
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
21
+ var __spreadValues = (a, b) => {
22
+ for (var prop in b || (b = {}))
23
+ if (__hasOwnProp.call(b, prop))
24
+ __defNormalProp(a, prop, b[prop]);
25
+ if (__getOwnPropSymbols)
26
+ for (var prop of __getOwnPropSymbols(b)) {
27
+ if (__propIsEnum.call(b, prop))
28
+ __defNormalProp(a, prop, b[prop]);
29
+ }
30
+ return a;
31
+ };
32
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
33
+ var __export = (target, all3) => {
34
+ for (var name in all3)
35
+ __defProp(target, name, { get: all3[name], enumerable: true });
36
+ };
37
+ var __copyProps = (to, from, except, desc) => {
38
+ if (from && typeof from === "object" || typeof from === "function") {
39
+ for (let key of __getOwnPropNames(from))
40
+ if (!__hasOwnProp.call(to, key) && key !== except)
41
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
42
+ }
43
+ return to;
44
+ };
45
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
46
+ var __await = function(promise, isYieldStar) {
47
+ this[0] = promise;
48
+ this[1] = isYieldStar;
49
+ };
50
+ var __asyncGenerator = (__this, __arguments, generator) => {
51
+ var resume = (k, v, yes, no) => {
52
+ try {
53
+ var x = generator[k](v), isAwait = (v = x.value) instanceof __await, done = x.done;
54
+ Promise.resolve(isAwait ? v[0] : v).then((y) => isAwait ? resume(k === "return" ? k : "next", v[1] ? { done: y.done, value: y.value } : y, yes, no) : yes({ value: y, done })).catch((e) => resume("throw", e, yes, no));
55
+ } catch (e) {
56
+ no(e);
57
+ }
58
+ }, method = (k) => it[k] = (x) => new Promise((yes, no) => resume(k, x, yes, no)), it = {};
59
+ return generator = generator.apply(__this, __arguments), it[__knownSymbol("asyncIterator")] = () => it, method("next"), method("throw"), method("return"), it;
60
+ };
61
+ var __yieldStar = (value) => {
62
+ var obj = value[__knownSymbol("asyncIterator")], isAwait = false, method, it = {};
63
+ if (obj == null) {
64
+ obj = value[__knownSymbol("iterator")]();
65
+ method = (k) => it[k] = (x) => obj[k](x);
66
+ } else {
67
+ obj = obj.call(value);
68
+ method = (k) => it[k] = (v) => {
69
+ if (isAwait) {
70
+ isAwait = false;
71
+ if (k === "throw") throw v;
72
+ return v;
73
+ }
74
+ isAwait = true;
75
+ return {
76
+ done: false,
77
+ value: new __await(new Promise((resolve) => {
78
+ var x = obj[k](v);
79
+ if (!(x instanceof Object)) __typeError("Object expected");
80
+ resolve(x);
81
+ }), 1)
82
+ };
83
+ };
84
+ }
85
+ return it[__knownSymbol("iterator")] = () => it, method("next"), "throw" in obj ? method("throw") : it.throw = (x) => {
86
+ throw x;
87
+ }, "return" in obj && method("return"), it;
88
+ };
89
+ var __forAwait = (obj, it, method) => (it = obj[__knownSymbol("asyncIterator")]) ? it.call(obj) : (obj = obj[__knownSymbol("iterator")](), it = {}, method = (key, fn) => (fn = obj[key]) && (it[key] = (arg) => new Promise((yes, no, done) => (arg = fn.call(obj, arg), done = arg.done, Promise.resolve(arg.value).then((value) => yes({ value, done }), no)))), method("next"), method("return"), it);
90
+
91
+ // src/v2/standalone/external-tracker.ts
92
+ var external_tracker_exports = {};
93
+ __export(external_tracker_exports, {
94
+ TagadaExternalTracker: () => TagadaExternalTracker,
95
+ TagadaTracker: () => TagadaTracker
96
+ });
97
+
98
+ // src/v2/core/config/environment.ts
99
+ function getCookie(name) {
100
+ var _a;
101
+ if (typeof document === "undefined") return null;
102
+ const value = "; ".concat(document.cookie);
103
+ const parts = value.split("; ".concat(name, "="));
104
+ if (parts.length === 2) return ((_a = parts.pop()) == null ? void 0 : _a.split(";").shift()) || null;
105
+ return null;
106
+ }
107
+ var ENVIRONMENT_CONFIGS = {
108
+ production: {
109
+ baseUrl: "https://app.tagadapay.com",
110
+ endpoints: {
111
+ checkout: {
112
+ sessionInit: "/api/v1/checkout/session/init",
113
+ sessionStatus: "/api/v1/checkout/session/status"
114
+ },
115
+ customer: {
116
+ profile: "/api/v1/customer/profile",
117
+ session: "/api/v1/customer/session"
118
+ },
119
+ store: {
120
+ config: "/api/v1/store/config"
121
+ }
122
+ }
123
+ },
124
+ development: {
125
+ baseUrl: "https://app.tagadapay.dev",
126
+ endpoints: {
127
+ checkout: {
128
+ sessionInit: "/api/v1/checkout/session/init",
129
+ sessionStatus: "/api/v1/checkout/session/status"
130
+ },
131
+ customer: {
132
+ profile: "/api/v1/customer/profile",
133
+ session: "/api/v1/customer/session"
134
+ },
135
+ store: {
136
+ config: "/api/v1/store/config"
137
+ }
138
+ }
139
+ },
140
+ local: {
141
+ baseUrl: "http://app.localhost:3000",
142
+ endpoints: {
143
+ checkout: {
144
+ sessionInit: "/api/v1/checkout/session/init",
145
+ sessionStatus: "/api/v1/checkout/session/status"
146
+ },
147
+ customer: {
148
+ profile: "/api/v1/customer/profile",
149
+ session: "/api/v1/customer/session"
150
+ },
151
+ store: {
152
+ config: "/api/v1/store/config"
153
+ }
154
+ }
155
+ }
156
+ };
157
+ function getEnvironmentConfig(environment = "local") {
158
+ const apiConfig = ENVIRONMENT_CONFIGS[environment];
159
+ if (!apiConfig) {
160
+ console.warn("Unknown environment: ".concat(environment, ". Falling back to local."));
161
+ return {
162
+ environment: "local",
163
+ apiConfig: ENVIRONMENT_CONFIGS.local
164
+ };
165
+ }
166
+ let customBaseUrl = null;
167
+ if (typeof window !== "undefined") {
168
+ const urlParams = new URLSearchParams(window.location.search);
169
+ customBaseUrl = urlParams.get("tagadaClientBaseUrl");
170
+ if (!customBaseUrl) {
171
+ try {
172
+ customBaseUrl = localStorage.getItem("tgd_client_base_url") || getCookie("tgd_client_base_url");
173
+ } catch (e) {
174
+ }
175
+ }
176
+ }
177
+ if (customBaseUrl) {
178
+ console.log("[SDK] Using custom API base URL override: ".concat(customBaseUrl));
179
+ return {
180
+ environment,
181
+ apiConfig: __spreadProps(__spreadValues({}, apiConfig), {
182
+ baseUrl: customBaseUrl
183
+ })
184
+ };
185
+ }
186
+ return {
187
+ environment,
188
+ apiConfig
189
+ };
190
+ }
191
+ function detectEnvironment() {
192
+ var _a;
193
+ if (typeof window === "undefined") {
194
+ return "local";
195
+ }
196
+ const urlParams = new URLSearchParams(window.location.search);
197
+ const urlEnv = urlParams.get("tagadaClientEnv");
198
+ if (urlEnv && (urlEnv === "production" || urlEnv === "development" || urlEnv === "local")) {
199
+ console.log("[SDK] Using explicit environment override: ".concat(urlEnv));
200
+ return urlEnv;
201
+ }
202
+ try {
203
+ const storageEnv = localStorage.getItem("tgd_client_env") || getCookie("tgd_client_env");
204
+ if (storageEnv && (storageEnv === "production" || storageEnv === "development" || storageEnv === "local")) {
205
+ console.log("[SDK] Using persisted environment override: ".concat(storageEnv));
206
+ return storageEnv;
207
+ }
208
+ } catch (e) {
209
+ }
210
+ const hostname = window.location.hostname;
211
+ const href = window.location.href;
212
+ if (hostname === "localhost" || hostname.startsWith("127.") || hostname.startsWith("192.168.") || hostname.startsWith("10.") || hostname.includes(".local") || hostname === "" || hostname === "0.0.0.0") {
213
+ if (typeof window !== "undefined" && ((_a = window == null ? void 0 : window.__TAGADA_ENV__) == null ? void 0 : _a.TAGADA_ENVIRONMENT)) {
214
+ const override = window.__TAGADA_ENV__.TAGADA_ENVIRONMENT.toLowerCase();
215
+ if (override === "production" || override === "development" || override === "local") {
216
+ console.log("[SDK] Local override detected: ".concat(override));
217
+ return override;
218
+ }
219
+ }
220
+ return "local";
221
+ }
222
+ if (hostname === "app.tagadapay.com" || hostname.includes("tagadapay.com") || hostname.includes("yourproductiondomain.com")) {
223
+ return "production";
224
+ }
225
+ if (hostname === "app.tagadapay.dev" || hostname.includes("tagadapay.dev") || hostname.includes("vercel.app") || hostname.includes("netlify.app") || hostname.includes("surge.sh") || hostname.includes("github.io") || hostname.includes("herokuapp.com") || hostname.includes("railway.app") || href.includes("?env=dev") || href.includes("?dev=true") || href.includes("#dev")) {
226
+ return "development";
227
+ }
228
+ console.warn("[SDK] Unknown domain: ".concat(hostname, ", defaulting to production"));
229
+ return "production";
230
+ }
231
+ function isLocalEnvironment(excludeCdn = false) {
232
+ const env = detectEnvironment();
233
+ if (env !== "local") {
234
+ return false;
235
+ }
236
+ if (excludeCdn && typeof window !== "undefined") {
237
+ return !window.location.hostname.includes(".cdn.");
238
+ }
239
+ return true;
240
+ }
241
+
242
+ // src/v2/core/resources/funnel.ts
243
+ var FunnelResource = class {
244
+ constructor(apiClient) {
245
+ this.apiClient = apiClient;
246
+ }
247
+ /**
248
+ * Initialize a funnel session
249
+ */
250
+ async initialize(request) {
251
+ return this.apiClient.post("/api/v1/funnel/initialize", request);
252
+ }
253
+ /**
254
+ * Navigate to next step in funnel
255
+ */
256
+ async navigate(request) {
257
+ return this.apiClient.post("/api/v1/funnel/navigate", request);
258
+ }
259
+ /**
260
+ * Update funnel context
261
+ */
262
+ async updateContext(sessionId, request) {
263
+ return this.apiClient.patch("/api/v1/funnel/context/".concat(sessionId), request);
264
+ }
265
+ /**
266
+ * End funnel session
267
+ */
268
+ async endSession(sessionId) {
269
+ return this.apiClient.delete("/api/v1/funnel/session/".concat(sessionId));
270
+ }
271
+ /**
272
+ * Get funnel session by ID
273
+ * @param sessionId - The session ID to fetch
274
+ * @param currentUrl - Optional current URL for session synchronization on page load
275
+ */
276
+ async getSession(sessionId, currentUrl, includeDebugData) {
277
+ const params = new URLSearchParams();
278
+ if (currentUrl) {
279
+ params.append("currentUrl", currentUrl);
280
+ }
281
+ if (includeDebugData) {
282
+ params.append("includeDebugData", "true");
283
+ }
284
+ const url = "/api/v1/funnel/session/".concat(sessionId).concat(params.toString() ? "?".concat(params) : "");
285
+ return this.apiClient.get(url);
286
+ }
287
+ };
288
+
289
+ // src/v2/core/utils/eventDispatcher.ts
290
+ var EventDispatcher = class {
291
+ constructor() {
292
+ this.listeners = /* @__PURE__ */ new Set();
293
+ }
294
+ subscribe(listener) {
295
+ this.listeners.add(listener);
296
+ return () => {
297
+ this.listeners.delete(listener);
298
+ };
299
+ }
300
+ notify(data) {
301
+ this.listeners.forEach((listener) => {
302
+ try {
303
+ listener(data);
304
+ } catch (error) {
305
+ console.error("Error in event listener:", error);
306
+ }
307
+ });
308
+ }
309
+ clear() {
310
+ this.listeners.clear();
311
+ }
312
+ };
313
+
314
+ // src/v2/core/utils/sessionStorage.ts
315
+ var FUNNEL_SESSION_COOKIE_NAME = "tgd-funnel-session-id";
316
+ var SESSION_MAX_AGE = 30 * 24 * 60 * 60;
317
+ function setFunnelSessionCookie(sessionId) {
318
+ if (typeof document === "undefined") return;
319
+ document.cookie = "".concat(FUNNEL_SESSION_COOKIE_NAME, "=").concat(sessionId, "; path=/; max-age=").concat(SESSION_MAX_AGE, "; SameSite=Lax");
320
+ }
321
+ function getFunnelSessionCookie() {
322
+ if (typeof document === "undefined") return void 0;
323
+ const cookie = document.cookie.split("; ").find((row) => row.startsWith("".concat(FUNNEL_SESSION_COOKIE_NAME, "=")));
324
+ return cookie ? cookie.split("=")[1] : void 0;
325
+ }
326
+ function clearFunnelSessionCookie() {
327
+ if (typeof document === "undefined") return;
328
+ document.cookie = "".concat(FUNNEL_SESSION_COOKIE_NAME, "=; path=/; max-age=0");
329
+ }
330
+
331
+ // src/v2/core/utils/tokenStorage.ts
332
+ var TOKEN_KEY = "cms_token";
333
+ function setClientToken(token) {
334
+ if (typeof window !== "undefined") {
335
+ try {
336
+ localStorage.setItem(TOKEN_KEY, token);
337
+ window.dispatchEvent(new Event("storage"));
338
+ } catch (error) {
339
+ console.error("Failed to save token to localStorage:", error);
340
+ }
341
+ }
342
+ }
343
+ function getClientToken() {
344
+ if (typeof window !== "undefined") {
345
+ try {
346
+ return localStorage.getItem(TOKEN_KEY);
347
+ } catch (error) {
348
+ console.error("Failed to get token from localStorage:", error);
349
+ return null;
350
+ }
351
+ }
352
+ return null;
353
+ }
354
+ function clearClientToken() {
355
+ if (typeof window !== "undefined") {
356
+ try {
357
+ localStorage.removeItem(TOKEN_KEY);
358
+ } catch (error) {
359
+ console.error("Failed to clear token from localStorage:", error);
360
+ }
361
+ }
362
+ }
363
+
364
+ // src/v2/core/utils/previewMode.ts
365
+ var STORAGE_KEYS = {
366
+ DRAFT: "tgd_draft",
367
+ FUNNEL_TRACKING: "tgd_funnel_tracking",
368
+ FORCE_RESET: "tgd_force_reset",
369
+ CLIENT_ENV: "tgd_client_env",
370
+ CLIENT_BASE_URL: "tgd_client_base_url"
371
+ };
372
+ function getFromStorage(key) {
373
+ if (typeof window === "undefined") return null;
374
+ try {
375
+ return localStorage.getItem(key);
376
+ } catch (e) {
377
+ return null;
378
+ }
379
+ }
380
+ function setInStorage(key, value) {
381
+ if (typeof window === "undefined") return;
382
+ try {
383
+ localStorage.setItem(key, value);
384
+ } catch (e) {
385
+ }
386
+ }
387
+ function getFromCookie(key) {
388
+ var _a;
389
+ if (typeof document === "undefined") return null;
390
+ const cookies = document.cookie.split(";");
391
+ const cookie = cookies.find((c) => c.trim().startsWith("".concat(key, "=")));
392
+ return cookie ? (_a = cookie.split("=")[1]) == null ? void 0 : _a.trim() : null;
393
+ }
394
+ function setInCookie(key, value, maxAge = 86400) {
395
+ if (typeof document === "undefined") return;
396
+ document.cookie = "".concat(key, "=").concat(value, "; path=/; max-age=").concat(maxAge);
397
+ }
398
+ function clearFromCookie(key) {
399
+ if (typeof document === "undefined") return;
400
+ document.cookie = "".concat(key, "=; path=/; max-age=0");
401
+ }
402
+ function getSDKParams() {
403
+ if (typeof window === "undefined") {
404
+ return {};
405
+ }
406
+ const urlParams = new URLSearchParams(window.location.search);
407
+ let draft;
408
+ const urlDraft = urlParams.get("draft");
409
+ if (urlDraft !== null) {
410
+ draft = urlDraft === "true";
411
+ } else {
412
+ const storageDraft = getFromStorage(STORAGE_KEYS.DRAFT) || getFromCookie(STORAGE_KEYS.DRAFT);
413
+ if (storageDraft !== null) {
414
+ draft = storageDraft === "true";
415
+ }
416
+ }
417
+ let funnelTracking;
418
+ const urlTracking = urlParams.get("funnelTracking");
419
+ if (urlTracking !== null) {
420
+ funnelTracking = urlTracking !== "false";
421
+ } else {
422
+ const storageTracking = getFromStorage(STORAGE_KEYS.FUNNEL_TRACKING) || getFromCookie(STORAGE_KEYS.FUNNEL_TRACKING);
423
+ if (storageTracking !== null) {
424
+ funnelTracking = storageTracking !== "false";
425
+ }
426
+ }
427
+ const token = urlParams.get("token") || getClientToken() || null;
428
+ const funnelSessionId = urlParams.get("funnelSessionId") || null;
429
+ const funnelId = urlParams.get("funnelId") || null;
430
+ const forceReset = urlParams.get("forceReset") === "true";
431
+ let tagadaClientEnv;
432
+ const urlEnv = urlParams.get("tagadaClientEnv");
433
+ if (urlEnv && (urlEnv === "production" || urlEnv === "development" || urlEnv === "local")) {
434
+ tagadaClientEnv = urlEnv;
435
+ } else {
436
+ const storageEnv = getFromStorage(STORAGE_KEYS.CLIENT_ENV) || getFromCookie(STORAGE_KEYS.CLIENT_ENV);
437
+ if (storageEnv && (storageEnv === "production" || storageEnv === "development" || storageEnv === "local")) {
438
+ tagadaClientEnv = storageEnv;
439
+ }
440
+ }
441
+ let tagadaClientBaseUrl;
442
+ const urlBaseUrl = urlParams.get("tagadaClientBaseUrl");
443
+ if (urlBaseUrl) {
444
+ tagadaClientBaseUrl = urlBaseUrl;
445
+ } else {
446
+ const storageBaseUrl = getFromStorage(STORAGE_KEYS.CLIENT_BASE_URL) || getFromCookie(STORAGE_KEYS.CLIENT_BASE_URL);
447
+ if (storageBaseUrl) {
448
+ tagadaClientBaseUrl = storageBaseUrl;
449
+ }
450
+ }
451
+ return {
452
+ forceReset,
453
+ token,
454
+ funnelSessionId,
455
+ funnelId,
456
+ draft,
457
+ funnelTracking,
458
+ tagadaClientEnv,
459
+ tagadaClientBaseUrl
460
+ };
461
+ }
462
+ function isDraftMode() {
463
+ var _a;
464
+ const params = getSDKParams();
465
+ return (_a = params.draft) != null ? _a : false;
466
+ }
467
+ function setDraftMode(draft) {
468
+ if (typeof window === "undefined") return;
469
+ if (draft) {
470
+ setInStorage(STORAGE_KEYS.DRAFT, "true");
471
+ setInCookie(STORAGE_KEYS.DRAFT, "true", 86400);
472
+ } else {
473
+ setInStorage(STORAGE_KEYS.DRAFT, "false");
474
+ clearFromCookie(STORAGE_KEYS.DRAFT);
475
+ }
476
+ }
477
+ function handlePreviewMode(debugMode = false) {
478
+ const params = getSDKParams();
479
+ const shouldReset = params.forceReset || false;
480
+ if (!shouldReset && !params.token) {
481
+ persistSDKParamsFromURL();
482
+ return false;
483
+ }
484
+ if (debugMode) {
485
+ console.log("[SDK] Detected params:", params);
486
+ }
487
+ if (shouldReset) {
488
+ if (debugMode) {
489
+ console.log("[SDK] Force reset: Clearing all stored state");
490
+ }
491
+ clearClientToken();
492
+ clearFunnelSessionCookie();
493
+ if (typeof window !== "undefined" && window.localStorage) {
494
+ const keys = Object.keys(localStorage);
495
+ keys.forEach((key) => {
496
+ if (key.startsWith("tagadapay_") || key.startsWith("tgd_")) {
497
+ if (debugMode) {
498
+ console.log("[SDK] Clearing localStorage: ".concat(key));
499
+ }
500
+ localStorage.removeItem(key);
501
+ }
502
+ });
503
+ }
504
+ }
505
+ if (params.token !== null && params.token !== void 0) {
506
+ if (debugMode) {
507
+ console.log("[SDK] Using token from URL:", params.token.substring(0, 20) + "...");
508
+ }
509
+ if (params.token === "" || params.token === "null") {
510
+ clearClientToken();
511
+ } else {
512
+ setClientToken(params.token);
513
+ }
514
+ } else if (shouldReset) {
515
+ if (debugMode) {
516
+ console.log("[SDK] Force reset mode (no token)");
517
+ }
518
+ clearClientToken();
519
+ }
520
+ persistSDKParamsFromURL();
521
+ if (params.funnelSessionId && debugMode) {
522
+ console.log("[SDK] Using funnelSessionId from URL:", params.funnelSessionId);
523
+ }
524
+ return shouldReset;
525
+ }
526
+ function persistSDKParamsFromURL() {
527
+ if (typeof window === "undefined") return;
528
+ const urlParams = new URLSearchParams(window.location.search);
529
+ const urlDraft = urlParams.get("draft");
530
+ if (urlDraft !== null) {
531
+ setDraftMode(urlDraft === "true");
532
+ }
533
+ const urlTracking = urlParams.get("funnelTracking");
534
+ if (urlTracking !== null) {
535
+ setFunnelTracking(urlTracking !== "false");
536
+ }
537
+ const urlEnv = urlParams.get("tagadaClientEnv");
538
+ if (urlEnv && (urlEnv === "production" || urlEnv === "development" || urlEnv === "local")) {
539
+ setClientEnvironment(urlEnv);
540
+ }
541
+ const urlBaseUrl = urlParams.get("tagadaClientBaseUrl");
542
+ if (urlBaseUrl) {
543
+ setClientBaseUrl(urlBaseUrl);
544
+ }
545
+ }
546
+ function setFunnelTracking(enabled) {
547
+ if (typeof window === "undefined") return;
548
+ const value = enabled ? "true" : "false";
549
+ setInStorage(STORAGE_KEYS.FUNNEL_TRACKING, value);
550
+ setInCookie(STORAGE_KEYS.FUNNEL_TRACKING, value, 86400);
551
+ }
552
+ function setClientEnvironment(env) {
553
+ if (typeof window === "undefined") return;
554
+ setInStorage(STORAGE_KEYS.CLIENT_ENV, env);
555
+ setInCookie(STORAGE_KEYS.CLIENT_ENV, env, 86400);
556
+ }
557
+ function setClientBaseUrl(baseUrl) {
558
+ if (typeof window === "undefined") return;
559
+ setInStorage(STORAGE_KEYS.CLIENT_BASE_URL, baseUrl);
560
+ setInCookie(STORAGE_KEYS.CLIENT_BASE_URL, baseUrl, 86400);
561
+ }
562
+
563
+ // src/v2/core/funnelClient.ts
564
+ function getAssignedFunnelId() {
565
+ if (typeof window === "undefined") return void 0;
566
+ if (window.__TGD_FUNNEL_ID__) {
567
+ return window.__TGD_FUNNEL_ID__;
568
+ }
569
+ if (typeof document !== "undefined") {
570
+ const meta = document.querySelector('meta[name="x-funnel-id"]');
571
+ return (meta == null ? void 0 : meta.getAttribute("content")) || void 0;
572
+ }
573
+ return void 0;
574
+ }
575
+ function getAssignedFunnelVariant() {
576
+ if (typeof window === "undefined") return void 0;
577
+ if (window.__TGD_FUNNEL_VARIANT_ID__) {
578
+ return window.__TGD_FUNNEL_VARIANT_ID__;
579
+ }
580
+ if (typeof document !== "undefined") {
581
+ const meta = document.querySelector('meta[name="x-funnel-variant-id"]');
582
+ return (meta == null ? void 0 : meta.getAttribute("content")) || void 0;
583
+ }
584
+ return void 0;
585
+ }
586
+ function getAssignedFunnelStep() {
587
+ if (typeof window === "undefined") return void 0;
588
+ if (window.__TGD_FUNNEL_STEP_ID__) {
589
+ return window.__TGD_FUNNEL_STEP_ID__;
590
+ }
591
+ if (typeof document !== "undefined") {
592
+ const meta = document.querySelector('meta[name="x-funnel-step-id"]');
593
+ return (meta == null ? void 0 : meta.getAttribute("content")) || void 0;
594
+ }
595
+ return void 0;
596
+ }
597
+ var FunnelClient = class {
598
+ constructor(config) {
599
+ this.eventDispatcher = new EventDispatcher();
600
+ // Guards
601
+ this.isInitializing = false;
602
+ this.initializationAttempted = false;
603
+ this.config = config;
604
+ this.resource = new FunnelResource(config.apiClient);
605
+ this.state = {
606
+ context: null,
607
+ isLoading: false,
608
+ isInitialized: false,
609
+ isNavigating: false,
610
+ error: null,
611
+ sessionError: null
612
+ };
613
+ }
614
+ /**
615
+ * Update configuration (e.g. when plugin config loads)
616
+ */
617
+ setConfig(config) {
618
+ this.config = __spreadValues(__spreadValues({}, this.config), config);
619
+ }
620
+ /**
621
+ * Subscribe to state changes
622
+ */
623
+ subscribe(listener) {
624
+ return this.eventDispatcher.subscribe(listener);
625
+ }
626
+ /**
627
+ * Get current state
628
+ */
629
+ getState() {
630
+ return this.state;
631
+ }
632
+ /**
633
+ * Initialize session with automatic detection (cookies, URL, etc.)
634
+ */
635
+ async autoInitialize(authSession, store, funnelId) {
636
+ if (this.state.context) return this.state.context;
637
+ if (this.isInitializing) return null;
638
+ if (this.initializationAttempted) return null;
639
+ this.initializationAttempted = true;
640
+ this.isInitializing = true;
641
+ this.updateState({ isLoading: true, error: null });
642
+ try {
643
+ const params = new URLSearchParams(typeof window !== "undefined" ? window.location.search : "");
644
+ const urlFunnelId = params.get("funnelId");
645
+ const effectiveFunnelId = urlFunnelId || funnelId;
646
+ let existingSessionId = params.get("funnelSessionId");
647
+ if (!existingSessionId) {
648
+ existingSessionId = getFunnelSessionCookie() || null;
649
+ }
650
+ const injectedFunnelId = getAssignedFunnelId();
651
+ const funnelVariantId = getAssignedFunnelVariant();
652
+ const funnelStepId = getAssignedFunnelStep();
653
+ const sdkParams = getSDKParams();
654
+ const finalFunnelId = injectedFunnelId || effectiveFunnelId;
655
+ if (this.config.debugMode) {
656
+ console.log("\u{1F680} [FunnelClient] Auto-initializing...", {
657
+ existingSessionId,
658
+ effectiveFunnelId: finalFunnelId,
659
+ funnelVariantId,
660
+ // 🎯 Log variant ID for debugging
661
+ funnelStepId,
662
+ // 🎯 Log step ID for debugging
663
+ draft: sdkParams.draft,
664
+ // 🎯 Log draft mode
665
+ funnelTracking: sdkParams.funnelTracking
666
+ // 🎯 Log tracking flag
667
+ });
668
+ }
669
+ const response = await this.resource.initialize({
670
+ cmsSession: {
671
+ customerId: authSession.customerId,
672
+ sessionId: authSession.sessionId,
673
+ storeId: store.id,
674
+ accountId: store.accountId
675
+ },
676
+ funnelId: finalFunnelId,
677
+ existingSessionId: existingSessionId || void 0,
678
+ currentUrl: typeof window !== "undefined" ? window.location.href : void 0,
679
+ funnelVariantId,
680
+ // 🎯 Pass A/B test variant ID to backend
681
+ funnelStepId,
682
+ // 🎯 Pass step ID to backend
683
+ draft: sdkParams.draft,
684
+ // 🎯 Pass draft mode explicitly (more robust than URL parsing)
685
+ funnelTracking: sdkParams.funnelTracking
686
+ // 🎯 Pass funnel tracking flag explicitly
687
+ });
688
+ if (response.success && response.context) {
689
+ const enriched = this.enrichContext(response.context);
690
+ this.handleSessionSuccess(enriched);
691
+ return enriched;
692
+ } else {
693
+ throw new Error(response.error || "Failed to initialize funnel session");
694
+ }
695
+ } catch (error) {
696
+ const err = error instanceof Error ? error : new Error(String(error));
697
+ this.updateState({ error: err, isLoading: false });
698
+ if (this.config.debugMode) {
699
+ console.error("\u274C [FunnelClient] Init failed:", err);
700
+ }
701
+ throw err;
702
+ } finally {
703
+ this.isInitializing = false;
704
+ }
705
+ }
706
+ /**
707
+ * Manual initialization
708
+ */
709
+ async initialize(authSession, store, funnelId, entryStepId) {
710
+ this.updateState({ isLoading: true, error: null });
711
+ try {
712
+ const funnelVariantId = getAssignedFunnelVariant();
713
+ const funnelStepId = getAssignedFunnelStep();
714
+ if (this.config.debugMode) {
715
+ if (funnelVariantId) console.log("\u{1F3AF} [FunnelClient] Detected A/B test variant:", funnelVariantId);
716
+ if (funnelStepId) console.log("\u{1F3AF} [FunnelClient] Detected step ID:", funnelStepId);
717
+ }
718
+ const response = await this.resource.initialize({
719
+ cmsSession: {
720
+ customerId: authSession.customerId,
721
+ sessionId: authSession.sessionId,
722
+ storeId: store.id,
723
+ accountId: store.accountId
724
+ },
725
+ funnelId,
726
+ entryStepId,
727
+ currentUrl: typeof window !== "undefined" ? window.location.href : void 0,
728
+ funnelVariantId,
729
+ // 🎯 Pass A/B test variant ID to backend
730
+ funnelStepId
731
+ // 🎯 Pass step ID to backend
732
+ });
733
+ if (response.success && response.context) {
734
+ const enriched = this.enrichContext(response.context);
735
+ this.handleSessionSuccess(enriched);
736
+ return enriched;
737
+ } else {
738
+ throw new Error(response.error || "Failed to initialize");
739
+ }
740
+ } catch (error) {
741
+ const err = error instanceof Error ? error : new Error(String(error));
742
+ this.updateState({ error: err, isLoading: false });
743
+ throw err;
744
+ }
745
+ }
746
+ /**
747
+ * Navigate
748
+ */
749
+ async navigate(event) {
750
+ var _a;
751
+ if (!((_a = this.state.context) == null ? void 0 : _a.sessionId)) throw new Error("No active session");
752
+ this.updateState({ isNavigating: true, isLoading: true });
753
+ try {
754
+ const response = await this.resource.navigate({
755
+ sessionId: this.state.context.sessionId,
756
+ event
757
+ });
758
+ if (response.success && response.result) {
759
+ await this.refreshSession();
760
+ this.updateState({ isNavigating: false, isLoading: false });
761
+ const result = response.result;
762
+ const shouldAutoRedirect = this.config.autoRedirect !== false;
763
+ if (shouldAutoRedirect && (result == null ? void 0 : result.url) && typeof window !== "undefined") {
764
+ if (this.config.debugMode) {
765
+ console.log("\u{1F680} [FunnelClient] Auto-redirecting to:", result.url);
766
+ }
767
+ window.location.href = result.url;
768
+ }
769
+ return result;
770
+ }
771
+ throw new Error(response.error || "Navigation failed");
772
+ } catch (error) {
773
+ const err = error instanceof Error ? error : new Error(String(error));
774
+ this.updateState({ error: err, isNavigating: false, isLoading: false });
775
+ throw err;
776
+ }
777
+ }
778
+ /**
779
+ * Go to a specific step (direct navigation)
780
+ */
781
+ async goToStep(stepId) {
782
+ return this.navigate({
783
+ type: "direct_navigation" /* DIRECT_NAVIGATION */,
784
+ data: { targetStepId: stepId }
785
+ });
786
+ }
787
+ /**
788
+ * Refresh session data
789
+ */
790
+ async refreshSession() {
791
+ var _a;
792
+ if (!((_a = this.state.context) == null ? void 0 : _a.sessionId)) return;
793
+ try {
794
+ const response = await this.resource.getSession(this.state.context.sessionId);
795
+ if (response.success && response.context) {
796
+ const enriched = this.enrichContext(response.context);
797
+ this.updateState({ context: enriched, sessionError: null });
798
+ return enriched;
799
+ }
800
+ } catch (error) {
801
+ this.updateState({ sessionError: error instanceof Error ? error : new Error(String(error)) });
802
+ }
803
+ }
804
+ /**
805
+ * Update context data
806
+ */
807
+ async updateContext(updates) {
808
+ var _a;
809
+ if (!((_a = this.state.context) == null ? void 0 : _a.sessionId)) throw new Error("No active session");
810
+ this.updateState({ isLoading: true });
811
+ try {
812
+ const response = await this.resource.updateContext(this.state.context.sessionId, { contextUpdates: updates });
813
+ if (response.success) {
814
+ await this.refreshSession();
815
+ } else {
816
+ throw new Error(response.error || "Failed to update context");
817
+ }
818
+ } finally {
819
+ this.updateState({ isLoading: false });
820
+ }
821
+ }
822
+ /**
823
+ * End session
824
+ */
825
+ async endSession() {
826
+ var _a;
827
+ if (!((_a = this.state.context) == null ? void 0 : _a.sessionId)) return;
828
+ try {
829
+ await this.resource.endSession(this.state.context.sessionId);
830
+ } finally {
831
+ this.state.context = null;
832
+ this.updateState({ context: null, isInitialized: false });
833
+ if (typeof document !== "undefined") {
834
+ }
835
+ }
836
+ }
837
+ // Private helpers
838
+ updateState(updates) {
839
+ this.state = __spreadValues(__spreadValues({}, this.state), updates);
840
+ this.eventDispatcher.notify(this.state);
841
+ }
842
+ handleSessionSuccess(context) {
843
+ setFunnelSessionCookie(context.sessionId);
844
+ this.updateState({
845
+ context,
846
+ isLoading: false,
847
+ isInitialized: true,
848
+ error: null,
849
+ sessionError: null
850
+ });
851
+ }
852
+ enrichContext(ctx) {
853
+ var _a, _b;
854
+ const env = ((_a = this.config.environment) == null ? void 0 : _a.environment) || detectEnvironment();
855
+ if (env !== "local") return ctx;
856
+ const localResources = ((_b = this.config.pluginConfig) == null ? void 0 : _b.staticResources) || {};
857
+ if (Object.keys(localResources).length === 0) return ctx;
858
+ const existingStatic = ctx.static || {};
859
+ const hasAllResources = Object.keys(localResources).every(
860
+ (key) => existingStatic[key] === localResources[key]
861
+ );
862
+ if (hasAllResources && Object.keys(existingStatic).length === Object.keys(localResources).length) {
863
+ return ctx;
864
+ }
865
+ return __spreadProps(__spreadValues({}, ctx), {
866
+ static: __spreadValues(__spreadValues({}, localResources), existingStatic)
867
+ });
868
+ }
869
+ };
870
+
871
+ // ../../node_modules/.pnpm/axios@1.13.0/node_modules/axios/lib/helpers/bind.js
872
+ function bind(fn, thisArg) {
873
+ return function wrap() {
874
+ return fn.apply(thisArg, arguments);
875
+ };
876
+ }
877
+
878
+ // ../../node_modules/.pnpm/axios@1.13.0/node_modules/axios/lib/utils.js
879
+ var { toString } = Object.prototype;
880
+ var { getPrototypeOf } = Object;
881
+ var { iterator, toStringTag } = Symbol;
882
+ var kindOf = /* @__PURE__ */ ((cache) => (thing) => {
883
+ const str = toString.call(thing);
884
+ return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
885
+ })(/* @__PURE__ */ Object.create(null));
886
+ var kindOfTest = (type) => {
887
+ type = type.toLowerCase();
888
+ return (thing) => kindOf(thing) === type;
889
+ };
890
+ var typeOfTest = (type) => (thing) => typeof thing === type;
891
+ var { isArray } = Array;
892
+ var isUndefined = typeOfTest("undefined");
893
+ function isBuffer(val) {
894
+ return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val);
895
+ }
896
+ var isArrayBuffer = kindOfTest("ArrayBuffer");
897
+ function isArrayBufferView(val) {
898
+ let result;
899
+ if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView) {
900
+ result = ArrayBuffer.isView(val);
901
+ } else {
902
+ result = val && val.buffer && isArrayBuffer(val.buffer);
903
+ }
904
+ return result;
905
+ }
906
+ var isString = typeOfTest("string");
907
+ var isFunction = typeOfTest("function");
908
+ var isNumber = typeOfTest("number");
909
+ var isObject = (thing) => thing !== null && typeof thing === "object";
910
+ var isBoolean = (thing) => thing === true || thing === false;
911
+ var isPlainObject = (val) => {
912
+ if (kindOf(val) !== "object") {
913
+ return false;
914
+ }
915
+ const prototype3 = getPrototypeOf(val);
916
+ return (prototype3 === null || prototype3 === Object.prototype || Object.getPrototypeOf(prototype3) === null) && !(toStringTag in val) && !(iterator in val);
917
+ };
918
+ var isEmptyObject = (val) => {
919
+ if (!isObject(val) || isBuffer(val)) {
920
+ return false;
921
+ }
922
+ try {
923
+ return Object.keys(val).length === 0 && Object.getPrototypeOf(val) === Object.prototype;
924
+ } catch (e) {
925
+ return false;
926
+ }
927
+ };
928
+ var isDate = kindOfTest("Date");
929
+ var isFile = kindOfTest("File");
930
+ var isBlob = kindOfTest("Blob");
931
+ var isFileList = kindOfTest("FileList");
932
+ var isStream = (val) => isObject(val) && isFunction(val.pipe);
933
+ var isFormData = (thing) => {
934
+ let kind;
935
+ return thing && (typeof FormData === "function" && thing instanceof FormData || isFunction(thing.append) && ((kind = kindOf(thing)) === "formdata" || // detect form-data instance
936
+ kind === "object" && isFunction(thing.toString) && thing.toString() === "[object FormData]"));
937
+ };
938
+ var isURLSearchParams = kindOfTest("URLSearchParams");
939
+ var [isReadableStream, isRequest, isResponse, isHeaders] = ["ReadableStream", "Request", "Response", "Headers"].map(kindOfTest);
940
+ var trim = (str) => str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, "");
941
+ function forEach(obj, fn, { allOwnKeys = false } = {}) {
942
+ if (obj === null || typeof obj === "undefined") {
943
+ return;
944
+ }
945
+ let i;
946
+ let l;
947
+ if (typeof obj !== "object") {
948
+ obj = [obj];
949
+ }
950
+ if (isArray(obj)) {
951
+ for (i = 0, l = obj.length; i < l; i++) {
952
+ fn.call(null, obj[i], i, obj);
953
+ }
954
+ } else {
955
+ if (isBuffer(obj)) {
956
+ return;
957
+ }
958
+ const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
959
+ const len = keys.length;
960
+ let key;
961
+ for (i = 0; i < len; i++) {
962
+ key = keys[i];
963
+ fn.call(null, obj[key], key, obj);
964
+ }
965
+ }
966
+ }
967
+ function findKey(obj, key) {
968
+ if (isBuffer(obj)) {
969
+ return null;
970
+ }
971
+ key = key.toLowerCase();
972
+ const keys = Object.keys(obj);
973
+ let i = keys.length;
974
+ let _key;
975
+ while (i-- > 0) {
976
+ _key = keys[i];
977
+ if (key === _key.toLowerCase()) {
978
+ return _key;
979
+ }
980
+ }
981
+ return null;
982
+ }
983
+ var _global = (() => {
984
+ if (typeof globalThis !== "undefined") return globalThis;
985
+ return typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : global;
986
+ })();
987
+ var isContextDefined = (context) => !isUndefined(context) && context !== _global;
988
+ function merge() {
989
+ const { caseless, skipUndefined } = isContextDefined(this) && this || {};
990
+ const result = {};
991
+ const assignValue = (val, key) => {
992
+ const targetKey = caseless && findKey(result, key) || key;
993
+ if (isPlainObject(result[targetKey]) && isPlainObject(val)) {
994
+ result[targetKey] = merge(result[targetKey], val);
995
+ } else if (isPlainObject(val)) {
996
+ result[targetKey] = merge({}, val);
997
+ } else if (isArray(val)) {
998
+ result[targetKey] = val.slice();
999
+ } else if (!skipUndefined || !isUndefined(val)) {
1000
+ result[targetKey] = val;
1001
+ }
1002
+ };
1003
+ for (let i = 0, l = arguments.length; i < l; i++) {
1004
+ arguments[i] && forEach(arguments[i], assignValue);
1005
+ }
1006
+ return result;
1007
+ }
1008
+ var extend = (a, b, thisArg, { allOwnKeys } = {}) => {
1009
+ forEach(b, (val, key) => {
1010
+ if (thisArg && isFunction(val)) {
1011
+ a[key] = bind(val, thisArg);
1012
+ } else {
1013
+ a[key] = val;
1014
+ }
1015
+ }, { allOwnKeys });
1016
+ return a;
1017
+ };
1018
+ var stripBOM = (content) => {
1019
+ if (content.charCodeAt(0) === 65279) {
1020
+ content = content.slice(1);
1021
+ }
1022
+ return content;
1023
+ };
1024
+ var inherits = (constructor, superConstructor, props, descriptors2) => {
1025
+ constructor.prototype = Object.create(superConstructor.prototype, descriptors2);
1026
+ constructor.prototype.constructor = constructor;
1027
+ Object.defineProperty(constructor, "super", {
1028
+ value: superConstructor.prototype
1029
+ });
1030
+ props && Object.assign(constructor.prototype, props);
1031
+ };
1032
+ var toFlatObject = (sourceObj, destObj, filter2, propFilter) => {
1033
+ let props;
1034
+ let i;
1035
+ let prop;
1036
+ const merged = {};
1037
+ destObj = destObj || {};
1038
+ if (sourceObj == null) return destObj;
1039
+ do {
1040
+ props = Object.getOwnPropertyNames(sourceObj);
1041
+ i = props.length;
1042
+ while (i-- > 0) {
1043
+ prop = props[i];
1044
+ if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
1045
+ destObj[prop] = sourceObj[prop];
1046
+ merged[prop] = true;
1047
+ }
1048
+ }
1049
+ sourceObj = filter2 !== false && getPrototypeOf(sourceObj);
1050
+ } while (sourceObj && (!filter2 || filter2(sourceObj, destObj)) && sourceObj !== Object.prototype);
1051
+ return destObj;
1052
+ };
1053
+ var endsWith = (str, searchString, position) => {
1054
+ str = String(str);
1055
+ if (position === void 0 || position > str.length) {
1056
+ position = str.length;
1057
+ }
1058
+ position -= searchString.length;
1059
+ const lastIndex = str.indexOf(searchString, position);
1060
+ return lastIndex !== -1 && lastIndex === position;
1061
+ };
1062
+ var toArray = (thing) => {
1063
+ if (!thing) return null;
1064
+ if (isArray(thing)) return thing;
1065
+ let i = thing.length;
1066
+ if (!isNumber(i)) return null;
1067
+ const arr = new Array(i);
1068
+ while (i-- > 0) {
1069
+ arr[i] = thing[i];
1070
+ }
1071
+ return arr;
1072
+ };
1073
+ var isTypedArray = /* @__PURE__ */ ((TypedArray) => {
1074
+ return (thing) => {
1075
+ return TypedArray && thing instanceof TypedArray;
1076
+ };
1077
+ })(typeof Uint8Array !== "undefined" && getPrototypeOf(Uint8Array));
1078
+ var forEachEntry = (obj, fn) => {
1079
+ const generator = obj && obj[iterator];
1080
+ const _iterator = generator.call(obj);
1081
+ let result;
1082
+ while ((result = _iterator.next()) && !result.done) {
1083
+ const pair = result.value;
1084
+ fn.call(obj, pair[0], pair[1]);
1085
+ }
1086
+ };
1087
+ var matchAll = (regExp, str) => {
1088
+ let matches;
1089
+ const arr = [];
1090
+ while ((matches = regExp.exec(str)) !== null) {
1091
+ arr.push(matches);
1092
+ }
1093
+ return arr;
1094
+ };
1095
+ var isHTMLForm = kindOfTest("HTMLFormElement");
1096
+ var toCamelCase = (str) => {
1097
+ return str.toLowerCase().replace(
1098
+ /[-_\s]([a-z\d])(\w*)/g,
1099
+ function replacer(m, p1, p2) {
1100
+ return p1.toUpperCase() + p2;
1101
+ }
1102
+ );
1103
+ };
1104
+ var hasOwnProperty = (({ hasOwnProperty: hasOwnProperty2 }) => (obj, prop) => hasOwnProperty2.call(obj, prop))(Object.prototype);
1105
+ var isRegExp = kindOfTest("RegExp");
1106
+ var reduceDescriptors = (obj, reducer) => {
1107
+ const descriptors2 = Object.getOwnPropertyDescriptors(obj);
1108
+ const reducedDescriptors = {};
1109
+ forEach(descriptors2, (descriptor, name) => {
1110
+ let ret;
1111
+ if ((ret = reducer(descriptor, name, obj)) !== false) {
1112
+ reducedDescriptors[name] = ret || descriptor;
1113
+ }
1114
+ });
1115
+ Object.defineProperties(obj, reducedDescriptors);
1116
+ };
1117
+ var freezeMethods = (obj) => {
1118
+ reduceDescriptors(obj, (descriptor, name) => {
1119
+ if (isFunction(obj) && ["arguments", "caller", "callee"].indexOf(name) !== -1) {
1120
+ return false;
1121
+ }
1122
+ const value = obj[name];
1123
+ if (!isFunction(value)) return;
1124
+ descriptor.enumerable = false;
1125
+ if ("writable" in descriptor) {
1126
+ descriptor.writable = false;
1127
+ return;
1128
+ }
1129
+ if (!descriptor.set) {
1130
+ descriptor.set = () => {
1131
+ throw Error("Can not rewrite read-only method '" + name + "'");
1132
+ };
1133
+ }
1134
+ });
1135
+ };
1136
+ var toObjectSet = (arrayOrString, delimiter) => {
1137
+ const obj = {};
1138
+ const define = (arr) => {
1139
+ arr.forEach((value) => {
1140
+ obj[value] = true;
1141
+ });
1142
+ };
1143
+ isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));
1144
+ return obj;
1145
+ };
1146
+ var noop = () => {
1147
+ };
1148
+ var toFiniteNumber = (value, defaultValue) => {
1149
+ return value != null && Number.isFinite(value = +value) ? value : defaultValue;
1150
+ };
1151
+ function isSpecCompliantForm(thing) {
1152
+ return !!(thing && isFunction(thing.append) && thing[toStringTag] === "FormData" && thing[iterator]);
1153
+ }
1154
+ var toJSONObject = (obj) => {
1155
+ const stack = new Array(10);
1156
+ const visit = (source, i) => {
1157
+ if (isObject(source)) {
1158
+ if (stack.indexOf(source) >= 0) {
1159
+ return;
1160
+ }
1161
+ if (isBuffer(source)) {
1162
+ return source;
1163
+ }
1164
+ if (!("toJSON" in source)) {
1165
+ stack[i] = source;
1166
+ const target = isArray(source) ? [] : {};
1167
+ forEach(source, (value, key) => {
1168
+ const reducedValue = visit(value, i + 1);
1169
+ !isUndefined(reducedValue) && (target[key] = reducedValue);
1170
+ });
1171
+ stack[i] = void 0;
1172
+ return target;
1173
+ }
1174
+ }
1175
+ return source;
1176
+ };
1177
+ return visit(obj, 0);
1178
+ };
1179
+ var isAsyncFn = kindOfTest("AsyncFunction");
1180
+ var isThenable = (thing) => thing && (isObject(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing.catch);
1181
+ var _setImmediate = ((setImmediateSupported, postMessageSupported) => {
1182
+ if (setImmediateSupported) {
1183
+ return setImmediate;
1184
+ }
1185
+ return postMessageSupported ? ((token, callbacks) => {
1186
+ _global.addEventListener("message", ({ source, data }) => {
1187
+ if (source === _global && data === token) {
1188
+ callbacks.length && callbacks.shift()();
1189
+ }
1190
+ }, false);
1191
+ return (cb) => {
1192
+ callbacks.push(cb);
1193
+ _global.postMessage(token, "*");
1194
+ };
1195
+ })("axios@".concat(Math.random()), []) : (cb) => setTimeout(cb);
1196
+ })(
1197
+ typeof setImmediate === "function",
1198
+ isFunction(_global.postMessage)
1199
+ );
1200
+ var asap = typeof queueMicrotask !== "undefined" ? queueMicrotask.bind(_global) : typeof process !== "undefined" && process.nextTick || _setImmediate;
1201
+ var isIterable = (thing) => thing != null && isFunction(thing[iterator]);
1202
+ var utils_default = {
1203
+ isArray,
1204
+ isArrayBuffer,
1205
+ isBuffer,
1206
+ isFormData,
1207
+ isArrayBufferView,
1208
+ isString,
1209
+ isNumber,
1210
+ isBoolean,
1211
+ isObject,
1212
+ isPlainObject,
1213
+ isEmptyObject,
1214
+ isReadableStream,
1215
+ isRequest,
1216
+ isResponse,
1217
+ isHeaders,
1218
+ isUndefined,
1219
+ isDate,
1220
+ isFile,
1221
+ isBlob,
1222
+ isRegExp,
1223
+ isFunction,
1224
+ isStream,
1225
+ isURLSearchParams,
1226
+ isTypedArray,
1227
+ isFileList,
1228
+ forEach,
1229
+ merge,
1230
+ extend,
1231
+ trim,
1232
+ stripBOM,
1233
+ inherits,
1234
+ toFlatObject,
1235
+ kindOf,
1236
+ kindOfTest,
1237
+ endsWith,
1238
+ toArray,
1239
+ forEachEntry,
1240
+ matchAll,
1241
+ isHTMLForm,
1242
+ hasOwnProperty,
1243
+ hasOwnProp: hasOwnProperty,
1244
+ // an alias to avoid ESLint no-prototype-builtins detection
1245
+ reduceDescriptors,
1246
+ freezeMethods,
1247
+ toObjectSet,
1248
+ toCamelCase,
1249
+ noop,
1250
+ toFiniteNumber,
1251
+ findKey,
1252
+ global: _global,
1253
+ isContextDefined,
1254
+ isSpecCompliantForm,
1255
+ toJSONObject,
1256
+ isAsyncFn,
1257
+ isThenable,
1258
+ setImmediate: _setImmediate,
1259
+ asap,
1260
+ isIterable
1261
+ };
1262
+
1263
+ // ../../node_modules/.pnpm/axios@1.13.0/node_modules/axios/lib/core/AxiosError.js
1264
+ function AxiosError(message, code, config, request, response) {
1265
+ Error.call(this);
1266
+ if (Error.captureStackTrace) {
1267
+ Error.captureStackTrace(this, this.constructor);
1268
+ } else {
1269
+ this.stack = new Error().stack;
1270
+ }
1271
+ this.message = message;
1272
+ this.name = "AxiosError";
1273
+ code && (this.code = code);
1274
+ config && (this.config = config);
1275
+ request && (this.request = request);
1276
+ if (response) {
1277
+ this.response = response;
1278
+ this.status = response.status ? response.status : null;
1279
+ }
1280
+ }
1281
+ utils_default.inherits(AxiosError, Error, {
1282
+ toJSON: function toJSON() {
1283
+ return {
1284
+ // Standard
1285
+ message: this.message,
1286
+ name: this.name,
1287
+ // Microsoft
1288
+ description: this.description,
1289
+ number: this.number,
1290
+ // Mozilla
1291
+ fileName: this.fileName,
1292
+ lineNumber: this.lineNumber,
1293
+ columnNumber: this.columnNumber,
1294
+ stack: this.stack,
1295
+ // Axios
1296
+ config: utils_default.toJSONObject(this.config),
1297
+ code: this.code,
1298
+ status: this.status
1299
+ };
1300
+ }
1301
+ });
1302
+ var prototype = AxiosError.prototype;
1303
+ var descriptors = {};
1304
+ [
1305
+ "ERR_BAD_OPTION_VALUE",
1306
+ "ERR_BAD_OPTION",
1307
+ "ECONNABORTED",
1308
+ "ETIMEDOUT",
1309
+ "ERR_NETWORK",
1310
+ "ERR_FR_TOO_MANY_REDIRECTS",
1311
+ "ERR_DEPRECATED",
1312
+ "ERR_BAD_RESPONSE",
1313
+ "ERR_BAD_REQUEST",
1314
+ "ERR_CANCELED",
1315
+ "ERR_NOT_SUPPORT",
1316
+ "ERR_INVALID_URL"
1317
+ // eslint-disable-next-line func-names
1318
+ ].forEach((code) => {
1319
+ descriptors[code] = { value: code };
1320
+ });
1321
+ Object.defineProperties(AxiosError, descriptors);
1322
+ Object.defineProperty(prototype, "isAxiosError", { value: true });
1323
+ AxiosError.from = (error, code, config, request, response, customProps) => {
1324
+ const axiosError = Object.create(prototype);
1325
+ utils_default.toFlatObject(error, axiosError, function filter2(obj) {
1326
+ return obj !== Error.prototype;
1327
+ }, (prop) => {
1328
+ return prop !== "isAxiosError";
1329
+ });
1330
+ const msg = error && error.message ? error.message : "Error";
1331
+ const errCode = code == null && error ? error.code : code;
1332
+ AxiosError.call(axiosError, msg, errCode, config, request, response);
1333
+ if (error && axiosError.cause == null) {
1334
+ Object.defineProperty(axiosError, "cause", { value: error, configurable: true });
1335
+ }
1336
+ axiosError.name = error && error.name || "Error";
1337
+ customProps && Object.assign(axiosError, customProps);
1338
+ return axiosError;
1339
+ };
1340
+ var AxiosError_default = AxiosError;
1341
+
1342
+ // ../../node_modules/.pnpm/axios@1.13.0/node_modules/axios/lib/helpers/null.js
1343
+ var null_default = null;
1344
+
1345
+ // ../../node_modules/.pnpm/axios@1.13.0/node_modules/axios/lib/helpers/toFormData.js
1346
+ function isVisitable(thing) {
1347
+ return utils_default.isPlainObject(thing) || utils_default.isArray(thing);
1348
+ }
1349
+ function removeBrackets(key) {
1350
+ return utils_default.endsWith(key, "[]") ? key.slice(0, -2) : key;
1351
+ }
1352
+ function renderKey(path, key, dots) {
1353
+ if (!path) return key;
1354
+ return path.concat(key).map(function each(token, i) {
1355
+ token = removeBrackets(token);
1356
+ return !dots && i ? "[" + token + "]" : token;
1357
+ }).join(dots ? "." : "");
1358
+ }
1359
+ function isFlatArray(arr) {
1360
+ return utils_default.isArray(arr) && !arr.some(isVisitable);
1361
+ }
1362
+ var predicates = utils_default.toFlatObject(utils_default, {}, null, function filter(prop) {
1363
+ return /^is[A-Z]/.test(prop);
1364
+ });
1365
+ function toFormData(obj, formData, options) {
1366
+ if (!utils_default.isObject(obj)) {
1367
+ throw new TypeError("target must be an object");
1368
+ }
1369
+ formData = formData || new (null_default || FormData)();
1370
+ options = utils_default.toFlatObject(options, {
1371
+ metaTokens: true,
1372
+ dots: false,
1373
+ indexes: false
1374
+ }, false, function defined(option, source) {
1375
+ return !utils_default.isUndefined(source[option]);
1376
+ });
1377
+ const metaTokens = options.metaTokens;
1378
+ const visitor = options.visitor || defaultVisitor;
1379
+ const dots = options.dots;
1380
+ const indexes = options.indexes;
1381
+ const _Blob = options.Blob || typeof Blob !== "undefined" && Blob;
1382
+ const useBlob = _Blob && utils_default.isSpecCompliantForm(formData);
1383
+ if (!utils_default.isFunction(visitor)) {
1384
+ throw new TypeError("visitor must be a function");
1385
+ }
1386
+ function convertValue(value) {
1387
+ if (value === null) return "";
1388
+ if (utils_default.isDate(value)) {
1389
+ return value.toISOString();
1390
+ }
1391
+ if (utils_default.isBoolean(value)) {
1392
+ return value.toString();
1393
+ }
1394
+ if (!useBlob && utils_default.isBlob(value)) {
1395
+ throw new AxiosError_default("Blob is not supported. Use a Buffer instead.");
1396
+ }
1397
+ if (utils_default.isArrayBuffer(value) || utils_default.isTypedArray(value)) {
1398
+ return useBlob && typeof Blob === "function" ? new Blob([value]) : Buffer.from(value);
1399
+ }
1400
+ return value;
1401
+ }
1402
+ function defaultVisitor(value, key, path) {
1403
+ let arr = value;
1404
+ if (value && !path && typeof value === "object") {
1405
+ if (utils_default.endsWith(key, "{}")) {
1406
+ key = metaTokens ? key : key.slice(0, -2);
1407
+ value = JSON.stringify(value);
1408
+ } else if (utils_default.isArray(value) && isFlatArray(value) || (utils_default.isFileList(value) || utils_default.endsWith(key, "[]")) && (arr = utils_default.toArray(value))) {
1409
+ key = removeBrackets(key);
1410
+ arr.forEach(function each(el, index) {
1411
+ !(utils_default.isUndefined(el) || el === null) && formData.append(
1412
+ // eslint-disable-next-line no-nested-ternary
1413
+ indexes === true ? renderKey([key], index, dots) : indexes === null ? key : key + "[]",
1414
+ convertValue(el)
1415
+ );
1416
+ });
1417
+ return false;
1418
+ }
1419
+ }
1420
+ if (isVisitable(value)) {
1421
+ return true;
1422
+ }
1423
+ formData.append(renderKey(path, key, dots), convertValue(value));
1424
+ return false;
1425
+ }
1426
+ const stack = [];
1427
+ const exposedHelpers = Object.assign(predicates, {
1428
+ defaultVisitor,
1429
+ convertValue,
1430
+ isVisitable
1431
+ });
1432
+ function build(value, path) {
1433
+ if (utils_default.isUndefined(value)) return;
1434
+ if (stack.indexOf(value) !== -1) {
1435
+ throw Error("Circular reference detected in " + path.join("."));
1436
+ }
1437
+ stack.push(value);
1438
+ utils_default.forEach(value, function each(el, key) {
1439
+ const result = !(utils_default.isUndefined(el) || el === null) && visitor.call(
1440
+ formData,
1441
+ el,
1442
+ utils_default.isString(key) ? key.trim() : key,
1443
+ path,
1444
+ exposedHelpers
1445
+ );
1446
+ if (result === true) {
1447
+ build(el, path ? path.concat(key) : [key]);
1448
+ }
1449
+ });
1450
+ stack.pop();
1451
+ }
1452
+ if (!utils_default.isObject(obj)) {
1453
+ throw new TypeError("data must be an object");
1454
+ }
1455
+ build(obj);
1456
+ return formData;
1457
+ }
1458
+ var toFormData_default = toFormData;
1459
+
1460
+ // ../../node_modules/.pnpm/axios@1.13.0/node_modules/axios/lib/helpers/AxiosURLSearchParams.js
1461
+ function encode(str) {
1462
+ const charMap = {
1463
+ "!": "%21",
1464
+ "'": "%27",
1465
+ "(": "%28",
1466
+ ")": "%29",
1467
+ "~": "%7E",
1468
+ "%20": "+",
1469
+ "%00": "\0"
1470
+ };
1471
+ return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) {
1472
+ return charMap[match];
1473
+ });
1474
+ }
1475
+ function AxiosURLSearchParams(params, options) {
1476
+ this._pairs = [];
1477
+ params && toFormData_default(params, this, options);
1478
+ }
1479
+ var prototype2 = AxiosURLSearchParams.prototype;
1480
+ prototype2.append = function append(name, value) {
1481
+ this._pairs.push([name, value]);
1482
+ };
1483
+ prototype2.toString = function toString2(encoder) {
1484
+ const _encode = encoder ? function(value) {
1485
+ return encoder.call(this, value, encode);
1486
+ } : encode;
1487
+ return this._pairs.map(function each(pair) {
1488
+ return _encode(pair[0]) + "=" + _encode(pair[1]);
1489
+ }, "").join("&");
1490
+ };
1491
+ var AxiosURLSearchParams_default = AxiosURLSearchParams;
1492
+
1493
+ // ../../node_modules/.pnpm/axios@1.13.0/node_modules/axios/lib/helpers/buildURL.js
1494
+ function encode2(val) {
1495
+ return encodeURIComponent(val).replace(/%3A/gi, ":").replace(/%24/g, "$").replace(/%2C/gi, ",").replace(/%20/g, "+");
1496
+ }
1497
+ function buildURL(url, params, options) {
1498
+ if (!params) {
1499
+ return url;
1500
+ }
1501
+ const _encode = options && options.encode || encode2;
1502
+ if (utils_default.isFunction(options)) {
1503
+ options = {
1504
+ serialize: options
1505
+ };
1506
+ }
1507
+ const serializeFn = options && options.serialize;
1508
+ let serializedParams;
1509
+ if (serializeFn) {
1510
+ serializedParams = serializeFn(params, options);
1511
+ } else {
1512
+ serializedParams = utils_default.isURLSearchParams(params) ? params.toString() : new AxiosURLSearchParams_default(params, options).toString(_encode);
1513
+ }
1514
+ if (serializedParams) {
1515
+ const hashmarkIndex = url.indexOf("#");
1516
+ if (hashmarkIndex !== -1) {
1517
+ url = url.slice(0, hashmarkIndex);
1518
+ }
1519
+ url += (url.indexOf("?") === -1 ? "?" : "&") + serializedParams;
1520
+ }
1521
+ return url;
1522
+ }
1523
+
1524
+ // ../../node_modules/.pnpm/axios@1.13.0/node_modules/axios/lib/core/InterceptorManager.js
1525
+ var InterceptorManager = class {
1526
+ constructor() {
1527
+ this.handlers = [];
1528
+ }
1529
+ /**
1530
+ * Add a new interceptor to the stack
1531
+ *
1532
+ * @param {Function} fulfilled The function to handle `then` for a `Promise`
1533
+ * @param {Function} rejected The function to handle `reject` for a `Promise`
1534
+ *
1535
+ * @return {Number} An ID used to remove interceptor later
1536
+ */
1537
+ use(fulfilled, rejected, options) {
1538
+ this.handlers.push({
1539
+ fulfilled,
1540
+ rejected,
1541
+ synchronous: options ? options.synchronous : false,
1542
+ runWhen: options ? options.runWhen : null
1543
+ });
1544
+ return this.handlers.length - 1;
1545
+ }
1546
+ /**
1547
+ * Remove an interceptor from the stack
1548
+ *
1549
+ * @param {Number} id The ID that was returned by `use`
1550
+ *
1551
+ * @returns {void}
1552
+ */
1553
+ eject(id) {
1554
+ if (this.handlers[id]) {
1555
+ this.handlers[id] = null;
1556
+ }
1557
+ }
1558
+ /**
1559
+ * Clear all interceptors from the stack
1560
+ *
1561
+ * @returns {void}
1562
+ */
1563
+ clear() {
1564
+ if (this.handlers) {
1565
+ this.handlers = [];
1566
+ }
1567
+ }
1568
+ /**
1569
+ * Iterate over all the registered interceptors
1570
+ *
1571
+ * This method is particularly useful for skipping over any
1572
+ * interceptors that may have become `null` calling `eject`.
1573
+ *
1574
+ * @param {Function} fn The function to call for each interceptor
1575
+ *
1576
+ * @returns {void}
1577
+ */
1578
+ forEach(fn) {
1579
+ utils_default.forEach(this.handlers, function forEachHandler(h) {
1580
+ if (h !== null) {
1581
+ fn(h);
1582
+ }
1583
+ });
1584
+ }
1585
+ };
1586
+ var InterceptorManager_default = InterceptorManager;
1587
+
1588
+ // ../../node_modules/.pnpm/axios@1.13.0/node_modules/axios/lib/defaults/transitional.js
1589
+ var transitional_default = {
1590
+ silentJSONParsing: true,
1591
+ forcedJSONParsing: true,
1592
+ clarifyTimeoutError: false
1593
+ };
1594
+
1595
+ // ../../node_modules/.pnpm/axios@1.13.0/node_modules/axios/lib/platform/browser/classes/URLSearchParams.js
1596
+ var URLSearchParams_default = typeof URLSearchParams !== "undefined" ? URLSearchParams : AxiosURLSearchParams_default;
1597
+
1598
+ // ../../node_modules/.pnpm/axios@1.13.0/node_modules/axios/lib/platform/browser/classes/FormData.js
1599
+ var FormData_default = typeof FormData !== "undefined" ? FormData : null;
1600
+
1601
+ // ../../node_modules/.pnpm/axios@1.13.0/node_modules/axios/lib/platform/browser/classes/Blob.js
1602
+ var Blob_default = typeof Blob !== "undefined" ? Blob : null;
1603
+
1604
+ // ../../node_modules/.pnpm/axios@1.13.0/node_modules/axios/lib/platform/browser/index.js
1605
+ var browser_default = {
1606
+ isBrowser: true,
1607
+ classes: {
1608
+ URLSearchParams: URLSearchParams_default,
1609
+ FormData: FormData_default,
1610
+ Blob: Blob_default
1611
+ },
1612
+ protocols: ["http", "https", "file", "blob", "url", "data"]
1613
+ };
1614
+
1615
+ // ../../node_modules/.pnpm/axios@1.13.0/node_modules/axios/lib/platform/common/utils.js
1616
+ var utils_exports = {};
1617
+ __export(utils_exports, {
1618
+ hasBrowserEnv: () => hasBrowserEnv,
1619
+ hasStandardBrowserEnv: () => hasStandardBrowserEnv,
1620
+ hasStandardBrowserWebWorkerEnv: () => hasStandardBrowserWebWorkerEnv,
1621
+ navigator: () => _navigator,
1622
+ origin: () => origin
1623
+ });
1624
+ var hasBrowserEnv = typeof window !== "undefined" && typeof document !== "undefined";
1625
+ var _navigator = typeof navigator === "object" && navigator || void 0;
1626
+ var hasStandardBrowserEnv = hasBrowserEnv && (!_navigator || ["ReactNative", "NativeScript", "NS"].indexOf(_navigator.product) < 0);
1627
+ var hasStandardBrowserWebWorkerEnv = (() => {
1628
+ return typeof WorkerGlobalScope !== "undefined" && // eslint-disable-next-line no-undef
1629
+ self instanceof WorkerGlobalScope && typeof self.importScripts === "function";
1630
+ })();
1631
+ var origin = hasBrowserEnv && window.location.href || "http://localhost";
1632
+
1633
+ // ../../node_modules/.pnpm/axios@1.13.0/node_modules/axios/lib/platform/index.js
1634
+ var platform_default = __spreadValues(__spreadValues({}, utils_exports), browser_default);
1635
+
1636
+ // ../../node_modules/.pnpm/axios@1.13.0/node_modules/axios/lib/helpers/toURLEncodedForm.js
1637
+ function toURLEncodedForm(data, options) {
1638
+ return toFormData_default(data, new platform_default.classes.URLSearchParams(), __spreadValues({
1639
+ visitor: function(value, key, path, helpers) {
1640
+ if (platform_default.isNode && utils_default.isBuffer(value)) {
1641
+ this.append(key, value.toString("base64"));
1642
+ return false;
1643
+ }
1644
+ return helpers.defaultVisitor.apply(this, arguments);
1645
+ }
1646
+ }, options));
1647
+ }
1648
+
1649
+ // ../../node_modules/.pnpm/axios@1.13.0/node_modules/axios/lib/helpers/formDataToJSON.js
1650
+ function parsePropPath(name) {
1651
+ return utils_default.matchAll(/\w+|\[(\w*)]/g, name).map((match) => {
1652
+ return match[0] === "[]" ? "" : match[1] || match[0];
1653
+ });
1654
+ }
1655
+ function arrayToObject(arr) {
1656
+ const obj = {};
1657
+ const keys = Object.keys(arr);
1658
+ let i;
1659
+ const len = keys.length;
1660
+ let key;
1661
+ for (i = 0; i < len; i++) {
1662
+ key = keys[i];
1663
+ obj[key] = arr[key];
1664
+ }
1665
+ return obj;
1666
+ }
1667
+ function formDataToJSON(formData) {
1668
+ function buildPath(path, value, target, index) {
1669
+ let name = path[index++];
1670
+ if (name === "__proto__") return true;
1671
+ const isNumericKey = Number.isFinite(+name);
1672
+ const isLast = index >= path.length;
1673
+ name = !name && utils_default.isArray(target) ? target.length : name;
1674
+ if (isLast) {
1675
+ if (utils_default.hasOwnProp(target, name)) {
1676
+ target[name] = [target[name], value];
1677
+ } else {
1678
+ target[name] = value;
1679
+ }
1680
+ return !isNumericKey;
1681
+ }
1682
+ if (!target[name] || !utils_default.isObject(target[name])) {
1683
+ target[name] = [];
1684
+ }
1685
+ const result = buildPath(path, value, target[name], index);
1686
+ if (result && utils_default.isArray(target[name])) {
1687
+ target[name] = arrayToObject(target[name]);
1688
+ }
1689
+ return !isNumericKey;
1690
+ }
1691
+ if (utils_default.isFormData(formData) && utils_default.isFunction(formData.entries)) {
1692
+ const obj = {};
1693
+ utils_default.forEachEntry(formData, (name, value) => {
1694
+ buildPath(parsePropPath(name), value, obj, 0);
1695
+ });
1696
+ return obj;
1697
+ }
1698
+ return null;
1699
+ }
1700
+ var formDataToJSON_default = formDataToJSON;
1701
+
1702
+ // ../../node_modules/.pnpm/axios@1.13.0/node_modules/axios/lib/defaults/index.js
1703
+ function stringifySafely(rawValue, parser, encoder) {
1704
+ if (utils_default.isString(rawValue)) {
1705
+ try {
1706
+ (parser || JSON.parse)(rawValue);
1707
+ return utils_default.trim(rawValue);
1708
+ } catch (e) {
1709
+ if (e.name !== "SyntaxError") {
1710
+ throw e;
1711
+ }
1712
+ }
1713
+ }
1714
+ return (encoder || JSON.stringify)(rawValue);
1715
+ }
1716
+ var defaults = {
1717
+ transitional: transitional_default,
1718
+ adapter: ["xhr", "http", "fetch"],
1719
+ transformRequest: [function transformRequest(data, headers) {
1720
+ const contentType = headers.getContentType() || "";
1721
+ const hasJSONContentType = contentType.indexOf("application/json") > -1;
1722
+ const isObjectPayload = utils_default.isObject(data);
1723
+ if (isObjectPayload && utils_default.isHTMLForm(data)) {
1724
+ data = new FormData(data);
1725
+ }
1726
+ const isFormData2 = utils_default.isFormData(data);
1727
+ if (isFormData2) {
1728
+ return hasJSONContentType ? JSON.stringify(formDataToJSON_default(data)) : data;
1729
+ }
1730
+ if (utils_default.isArrayBuffer(data) || utils_default.isBuffer(data) || utils_default.isStream(data) || utils_default.isFile(data) || utils_default.isBlob(data) || utils_default.isReadableStream(data)) {
1731
+ return data;
1732
+ }
1733
+ if (utils_default.isArrayBufferView(data)) {
1734
+ return data.buffer;
1735
+ }
1736
+ if (utils_default.isURLSearchParams(data)) {
1737
+ headers.setContentType("application/x-www-form-urlencoded;charset=utf-8", false);
1738
+ return data.toString();
1739
+ }
1740
+ let isFileList2;
1741
+ if (isObjectPayload) {
1742
+ if (contentType.indexOf("application/x-www-form-urlencoded") > -1) {
1743
+ return toURLEncodedForm(data, this.formSerializer).toString();
1744
+ }
1745
+ if ((isFileList2 = utils_default.isFileList(data)) || contentType.indexOf("multipart/form-data") > -1) {
1746
+ const _FormData = this.env && this.env.FormData;
1747
+ return toFormData_default(
1748
+ isFileList2 ? { "files[]": data } : data,
1749
+ _FormData && new _FormData(),
1750
+ this.formSerializer
1751
+ );
1752
+ }
1753
+ }
1754
+ if (isObjectPayload || hasJSONContentType) {
1755
+ headers.setContentType("application/json", false);
1756
+ return stringifySafely(data);
1757
+ }
1758
+ return data;
1759
+ }],
1760
+ transformResponse: [function transformResponse(data) {
1761
+ const transitional2 = this.transitional || defaults.transitional;
1762
+ const forcedJSONParsing = transitional2 && transitional2.forcedJSONParsing;
1763
+ const JSONRequested = this.responseType === "json";
1764
+ if (utils_default.isResponse(data) || utils_default.isReadableStream(data)) {
1765
+ return data;
1766
+ }
1767
+ if (data && utils_default.isString(data) && (forcedJSONParsing && !this.responseType || JSONRequested)) {
1768
+ const silentJSONParsing = transitional2 && transitional2.silentJSONParsing;
1769
+ const strictJSONParsing = !silentJSONParsing && JSONRequested;
1770
+ try {
1771
+ return JSON.parse(data, this.parseReviver);
1772
+ } catch (e) {
1773
+ if (strictJSONParsing) {
1774
+ if (e.name === "SyntaxError") {
1775
+ throw AxiosError_default.from(e, AxiosError_default.ERR_BAD_RESPONSE, this, null, this.response);
1776
+ }
1777
+ throw e;
1778
+ }
1779
+ }
1780
+ }
1781
+ return data;
1782
+ }],
1783
+ /**
1784
+ * A timeout in milliseconds to abort a request. If set to 0 (default) a
1785
+ * timeout is not created.
1786
+ */
1787
+ timeout: 0,
1788
+ xsrfCookieName: "XSRF-TOKEN",
1789
+ xsrfHeaderName: "X-XSRF-TOKEN",
1790
+ maxContentLength: -1,
1791
+ maxBodyLength: -1,
1792
+ env: {
1793
+ FormData: platform_default.classes.FormData,
1794
+ Blob: platform_default.classes.Blob
1795
+ },
1796
+ validateStatus: function validateStatus(status) {
1797
+ return status >= 200 && status < 300;
1798
+ },
1799
+ headers: {
1800
+ common: {
1801
+ "Accept": "application/json, text/plain, */*",
1802
+ "Content-Type": void 0
1803
+ }
1804
+ }
1805
+ };
1806
+ utils_default.forEach(["delete", "get", "head", "post", "put", "patch"], (method) => {
1807
+ defaults.headers[method] = {};
1808
+ });
1809
+ var defaults_default = defaults;
1810
+
1811
+ // ../../node_modules/.pnpm/axios@1.13.0/node_modules/axios/lib/helpers/parseHeaders.js
1812
+ var ignoreDuplicateOf = utils_default.toObjectSet([
1813
+ "age",
1814
+ "authorization",
1815
+ "content-length",
1816
+ "content-type",
1817
+ "etag",
1818
+ "expires",
1819
+ "from",
1820
+ "host",
1821
+ "if-modified-since",
1822
+ "if-unmodified-since",
1823
+ "last-modified",
1824
+ "location",
1825
+ "max-forwards",
1826
+ "proxy-authorization",
1827
+ "referer",
1828
+ "retry-after",
1829
+ "user-agent"
1830
+ ]);
1831
+ var parseHeaders_default = (rawHeaders) => {
1832
+ const parsed = {};
1833
+ let key;
1834
+ let val;
1835
+ let i;
1836
+ rawHeaders && rawHeaders.split("\n").forEach(function parser(line) {
1837
+ i = line.indexOf(":");
1838
+ key = line.substring(0, i).trim().toLowerCase();
1839
+ val = line.substring(i + 1).trim();
1840
+ if (!key || parsed[key] && ignoreDuplicateOf[key]) {
1841
+ return;
1842
+ }
1843
+ if (key === "set-cookie") {
1844
+ if (parsed[key]) {
1845
+ parsed[key].push(val);
1846
+ } else {
1847
+ parsed[key] = [val];
1848
+ }
1849
+ } else {
1850
+ parsed[key] = parsed[key] ? parsed[key] + ", " + val : val;
1851
+ }
1852
+ });
1853
+ return parsed;
1854
+ };
1855
+
1856
+ // ../../node_modules/.pnpm/axios@1.13.0/node_modules/axios/lib/core/AxiosHeaders.js
1857
+ var $internals = Symbol("internals");
1858
+ function normalizeHeader(header) {
1859
+ return header && String(header).trim().toLowerCase();
1860
+ }
1861
+ function normalizeValue(value) {
1862
+ if (value === false || value == null) {
1863
+ return value;
1864
+ }
1865
+ return utils_default.isArray(value) ? value.map(normalizeValue) : String(value);
1866
+ }
1867
+ function parseTokens(str) {
1868
+ const tokens = /* @__PURE__ */ Object.create(null);
1869
+ const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;
1870
+ let match;
1871
+ while (match = tokensRE.exec(str)) {
1872
+ tokens[match[1]] = match[2];
1873
+ }
1874
+ return tokens;
1875
+ }
1876
+ var isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim());
1877
+ function matchHeaderValue(context, value, header, filter2, isHeaderNameFilter) {
1878
+ if (utils_default.isFunction(filter2)) {
1879
+ return filter2.call(this, value, header);
1880
+ }
1881
+ if (isHeaderNameFilter) {
1882
+ value = header;
1883
+ }
1884
+ if (!utils_default.isString(value)) return;
1885
+ if (utils_default.isString(filter2)) {
1886
+ return value.indexOf(filter2) !== -1;
1887
+ }
1888
+ if (utils_default.isRegExp(filter2)) {
1889
+ return filter2.test(value);
1890
+ }
1891
+ }
1892
+ function formatHeader(header) {
1893
+ return header.trim().toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => {
1894
+ return char.toUpperCase() + str;
1895
+ });
1896
+ }
1897
+ function buildAccessors(obj, header) {
1898
+ const accessorName = utils_default.toCamelCase(" " + header);
1899
+ ["get", "set", "has"].forEach((methodName) => {
1900
+ Object.defineProperty(obj, methodName + accessorName, {
1901
+ value: function(arg1, arg2, arg3) {
1902
+ return this[methodName].call(this, header, arg1, arg2, arg3);
1903
+ },
1904
+ configurable: true
1905
+ });
1906
+ });
1907
+ }
1908
+ var AxiosHeaders = class {
1909
+ constructor(headers) {
1910
+ headers && this.set(headers);
1911
+ }
1912
+ set(header, valueOrRewrite, rewrite) {
1913
+ const self2 = this;
1914
+ function setHeader(_value, _header, _rewrite) {
1915
+ const lHeader = normalizeHeader(_header);
1916
+ if (!lHeader) {
1917
+ throw new Error("header name must be a non-empty string");
1918
+ }
1919
+ const key = utils_default.findKey(self2, lHeader);
1920
+ if (!key || self2[key] === void 0 || _rewrite === true || _rewrite === void 0 && self2[key] !== false) {
1921
+ self2[key || _header] = normalizeValue(_value);
1922
+ }
1923
+ }
1924
+ const setHeaders = (headers, _rewrite) => utils_default.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite));
1925
+ if (utils_default.isPlainObject(header) || header instanceof this.constructor) {
1926
+ setHeaders(header, valueOrRewrite);
1927
+ } else if (utils_default.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {
1928
+ setHeaders(parseHeaders_default(header), valueOrRewrite);
1929
+ } else if (utils_default.isObject(header) && utils_default.isIterable(header)) {
1930
+ let obj = {}, dest, key;
1931
+ for (const entry of header) {
1932
+ if (!utils_default.isArray(entry)) {
1933
+ throw TypeError("Object iterator must return a key-value pair");
1934
+ }
1935
+ obj[key = entry[0]] = (dest = obj[key]) ? utils_default.isArray(dest) ? [...dest, entry[1]] : [dest, entry[1]] : entry[1];
1936
+ }
1937
+ setHeaders(obj, valueOrRewrite);
1938
+ } else {
1939
+ header != null && setHeader(valueOrRewrite, header, rewrite);
1940
+ }
1941
+ return this;
1942
+ }
1943
+ get(header, parser) {
1944
+ header = normalizeHeader(header);
1945
+ if (header) {
1946
+ const key = utils_default.findKey(this, header);
1947
+ if (key) {
1948
+ const value = this[key];
1949
+ if (!parser) {
1950
+ return value;
1951
+ }
1952
+ if (parser === true) {
1953
+ return parseTokens(value);
1954
+ }
1955
+ if (utils_default.isFunction(parser)) {
1956
+ return parser.call(this, value, key);
1957
+ }
1958
+ if (utils_default.isRegExp(parser)) {
1959
+ return parser.exec(value);
1960
+ }
1961
+ throw new TypeError("parser must be boolean|regexp|function");
1962
+ }
1963
+ }
1964
+ }
1965
+ has(header, matcher) {
1966
+ header = normalizeHeader(header);
1967
+ if (header) {
1968
+ const key = utils_default.findKey(this, header);
1969
+ return !!(key && this[key] !== void 0 && (!matcher || matchHeaderValue(this, this[key], key, matcher)));
1970
+ }
1971
+ return false;
1972
+ }
1973
+ delete(header, matcher) {
1974
+ const self2 = this;
1975
+ let deleted = false;
1976
+ function deleteHeader(_header) {
1977
+ _header = normalizeHeader(_header);
1978
+ if (_header) {
1979
+ const key = utils_default.findKey(self2, _header);
1980
+ if (key && (!matcher || matchHeaderValue(self2, self2[key], key, matcher))) {
1981
+ delete self2[key];
1982
+ deleted = true;
1983
+ }
1984
+ }
1985
+ }
1986
+ if (utils_default.isArray(header)) {
1987
+ header.forEach(deleteHeader);
1988
+ } else {
1989
+ deleteHeader(header);
1990
+ }
1991
+ return deleted;
1992
+ }
1993
+ clear(matcher) {
1994
+ const keys = Object.keys(this);
1995
+ let i = keys.length;
1996
+ let deleted = false;
1997
+ while (i--) {
1998
+ const key = keys[i];
1999
+ if (!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {
2000
+ delete this[key];
2001
+ deleted = true;
2002
+ }
2003
+ }
2004
+ return deleted;
2005
+ }
2006
+ normalize(format) {
2007
+ const self2 = this;
2008
+ const headers = {};
2009
+ utils_default.forEach(this, (value, header) => {
2010
+ const key = utils_default.findKey(headers, header);
2011
+ if (key) {
2012
+ self2[key] = normalizeValue(value);
2013
+ delete self2[header];
2014
+ return;
2015
+ }
2016
+ const normalized = format ? formatHeader(header) : String(header).trim();
2017
+ if (normalized !== header) {
2018
+ delete self2[header];
2019
+ }
2020
+ self2[normalized] = normalizeValue(value);
2021
+ headers[normalized] = true;
2022
+ });
2023
+ return this;
2024
+ }
2025
+ concat(...targets) {
2026
+ return this.constructor.concat(this, ...targets);
2027
+ }
2028
+ toJSON(asStrings) {
2029
+ const obj = /* @__PURE__ */ Object.create(null);
2030
+ utils_default.forEach(this, (value, header) => {
2031
+ value != null && value !== false && (obj[header] = asStrings && utils_default.isArray(value) ? value.join(", ") : value);
2032
+ });
2033
+ return obj;
2034
+ }
2035
+ [Symbol.iterator]() {
2036
+ return Object.entries(this.toJSON())[Symbol.iterator]();
2037
+ }
2038
+ toString() {
2039
+ return Object.entries(this.toJSON()).map(([header, value]) => header + ": " + value).join("\n");
2040
+ }
2041
+ getSetCookie() {
2042
+ return this.get("set-cookie") || [];
2043
+ }
2044
+ get [Symbol.toStringTag]() {
2045
+ return "AxiosHeaders";
2046
+ }
2047
+ static from(thing) {
2048
+ return thing instanceof this ? thing : new this(thing);
2049
+ }
2050
+ static concat(first, ...targets) {
2051
+ const computed = new this(first);
2052
+ targets.forEach((target) => computed.set(target));
2053
+ return computed;
2054
+ }
2055
+ static accessor(header) {
2056
+ const internals = this[$internals] = this[$internals] = {
2057
+ accessors: {}
2058
+ };
2059
+ const accessors = internals.accessors;
2060
+ const prototype3 = this.prototype;
2061
+ function defineAccessor(_header) {
2062
+ const lHeader = normalizeHeader(_header);
2063
+ if (!accessors[lHeader]) {
2064
+ buildAccessors(prototype3, _header);
2065
+ accessors[lHeader] = true;
2066
+ }
2067
+ }
2068
+ utils_default.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);
2069
+ return this;
2070
+ }
2071
+ };
2072
+ AxiosHeaders.accessor(["Content-Type", "Content-Length", "Accept", "Accept-Encoding", "User-Agent", "Authorization"]);
2073
+ utils_default.reduceDescriptors(AxiosHeaders.prototype, ({ value }, key) => {
2074
+ let mapped = key[0].toUpperCase() + key.slice(1);
2075
+ return {
2076
+ get: () => value,
2077
+ set(headerValue) {
2078
+ this[mapped] = headerValue;
2079
+ }
2080
+ };
2081
+ });
2082
+ utils_default.freezeMethods(AxiosHeaders);
2083
+ var AxiosHeaders_default = AxiosHeaders;
2084
+
2085
+ // ../../node_modules/.pnpm/axios@1.13.0/node_modules/axios/lib/core/transformData.js
2086
+ function transformData(fns, response) {
2087
+ const config = this || defaults_default;
2088
+ const context = response || config;
2089
+ const headers = AxiosHeaders_default.from(context.headers);
2090
+ let data = context.data;
2091
+ utils_default.forEach(fns, function transform(fn) {
2092
+ data = fn.call(config, data, headers.normalize(), response ? response.status : void 0);
2093
+ });
2094
+ headers.normalize();
2095
+ return data;
2096
+ }
2097
+
2098
+ // ../../node_modules/.pnpm/axios@1.13.0/node_modules/axios/lib/cancel/isCancel.js
2099
+ function isCancel(value) {
2100
+ return !!(value && value.__CANCEL__);
2101
+ }
2102
+
2103
+ // ../../node_modules/.pnpm/axios@1.13.0/node_modules/axios/lib/cancel/CanceledError.js
2104
+ function CanceledError(message, config, request) {
2105
+ AxiosError_default.call(this, message == null ? "canceled" : message, AxiosError_default.ERR_CANCELED, config, request);
2106
+ this.name = "CanceledError";
2107
+ }
2108
+ utils_default.inherits(CanceledError, AxiosError_default, {
2109
+ __CANCEL__: true
2110
+ });
2111
+ var CanceledError_default = CanceledError;
2112
+
2113
+ // ../../node_modules/.pnpm/axios@1.13.0/node_modules/axios/lib/core/settle.js
2114
+ function settle(resolve, reject, response) {
2115
+ const validateStatus2 = response.config.validateStatus;
2116
+ if (!response.status || !validateStatus2 || validateStatus2(response.status)) {
2117
+ resolve(response);
2118
+ } else {
2119
+ reject(new AxiosError_default(
2120
+ "Request failed with status code " + response.status,
2121
+ [AxiosError_default.ERR_BAD_REQUEST, AxiosError_default.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4],
2122
+ response.config,
2123
+ response.request,
2124
+ response
2125
+ ));
2126
+ }
2127
+ }
2128
+
2129
+ // ../../node_modules/.pnpm/axios@1.13.0/node_modules/axios/lib/helpers/parseProtocol.js
2130
+ function parseProtocol(url) {
2131
+ const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url);
2132
+ return match && match[1] || "";
2133
+ }
2134
+
2135
+ // ../../node_modules/.pnpm/axios@1.13.0/node_modules/axios/lib/helpers/speedometer.js
2136
+ function speedometer(samplesCount, min) {
2137
+ samplesCount = samplesCount || 10;
2138
+ const bytes = new Array(samplesCount);
2139
+ const timestamps = new Array(samplesCount);
2140
+ let head = 0;
2141
+ let tail = 0;
2142
+ let firstSampleTS;
2143
+ min = min !== void 0 ? min : 1e3;
2144
+ return function push(chunkLength) {
2145
+ const now = Date.now();
2146
+ const startedAt = timestamps[tail];
2147
+ if (!firstSampleTS) {
2148
+ firstSampleTS = now;
2149
+ }
2150
+ bytes[head] = chunkLength;
2151
+ timestamps[head] = now;
2152
+ let i = tail;
2153
+ let bytesCount = 0;
2154
+ while (i !== head) {
2155
+ bytesCount += bytes[i++];
2156
+ i = i % samplesCount;
2157
+ }
2158
+ head = (head + 1) % samplesCount;
2159
+ if (head === tail) {
2160
+ tail = (tail + 1) % samplesCount;
2161
+ }
2162
+ if (now - firstSampleTS < min) {
2163
+ return;
2164
+ }
2165
+ const passed = startedAt && now - startedAt;
2166
+ return passed ? Math.round(bytesCount * 1e3 / passed) : void 0;
2167
+ };
2168
+ }
2169
+ var speedometer_default = speedometer;
2170
+
2171
+ // ../../node_modules/.pnpm/axios@1.13.0/node_modules/axios/lib/helpers/throttle.js
2172
+ function throttle(fn, freq) {
2173
+ let timestamp = 0;
2174
+ let threshold = 1e3 / freq;
2175
+ let lastArgs;
2176
+ let timer;
2177
+ const invoke = (args, now = Date.now()) => {
2178
+ timestamp = now;
2179
+ lastArgs = null;
2180
+ if (timer) {
2181
+ clearTimeout(timer);
2182
+ timer = null;
2183
+ }
2184
+ fn(...args);
2185
+ };
2186
+ const throttled = (...args) => {
2187
+ const now = Date.now();
2188
+ const passed = now - timestamp;
2189
+ if (passed >= threshold) {
2190
+ invoke(args, now);
2191
+ } else {
2192
+ lastArgs = args;
2193
+ if (!timer) {
2194
+ timer = setTimeout(() => {
2195
+ timer = null;
2196
+ invoke(lastArgs);
2197
+ }, threshold - passed);
2198
+ }
2199
+ }
2200
+ };
2201
+ const flush = () => lastArgs && invoke(lastArgs);
2202
+ return [throttled, flush];
2203
+ }
2204
+ var throttle_default = throttle;
2205
+
2206
+ // ../../node_modules/.pnpm/axios@1.13.0/node_modules/axios/lib/helpers/progressEventReducer.js
2207
+ var progressEventReducer = (listener, isDownloadStream, freq = 3) => {
2208
+ let bytesNotified = 0;
2209
+ const _speedometer = speedometer_default(50, 250);
2210
+ return throttle_default((e) => {
2211
+ const loaded = e.loaded;
2212
+ const total = e.lengthComputable ? e.total : void 0;
2213
+ const progressBytes = loaded - bytesNotified;
2214
+ const rate = _speedometer(progressBytes);
2215
+ const inRange = loaded <= total;
2216
+ bytesNotified = loaded;
2217
+ const data = {
2218
+ loaded,
2219
+ total,
2220
+ progress: total ? loaded / total : void 0,
2221
+ bytes: progressBytes,
2222
+ rate: rate ? rate : void 0,
2223
+ estimated: rate && total && inRange ? (total - loaded) / rate : void 0,
2224
+ event: e,
2225
+ lengthComputable: total != null,
2226
+ [isDownloadStream ? "download" : "upload"]: true
2227
+ };
2228
+ listener(data);
2229
+ }, freq);
2230
+ };
2231
+ var progressEventDecorator = (total, throttled) => {
2232
+ const lengthComputable = total != null;
2233
+ return [(loaded) => throttled[0]({
2234
+ lengthComputable,
2235
+ total,
2236
+ loaded
2237
+ }), throttled[1]];
2238
+ };
2239
+ var asyncDecorator = (fn) => (...args) => utils_default.asap(() => fn(...args));
2240
+
2241
+ // ../../node_modules/.pnpm/axios@1.13.0/node_modules/axios/lib/helpers/isURLSameOrigin.js
2242
+ var isURLSameOrigin_default = platform_default.hasStandardBrowserEnv ? /* @__PURE__ */ ((origin2, isMSIE) => (url) => {
2243
+ url = new URL(url, platform_default.origin);
2244
+ return origin2.protocol === url.protocol && origin2.host === url.host && (isMSIE || origin2.port === url.port);
2245
+ })(
2246
+ new URL(platform_default.origin),
2247
+ platform_default.navigator && /(msie|trident)/i.test(platform_default.navigator.userAgent)
2248
+ ) : () => true;
2249
+
2250
+ // ../../node_modules/.pnpm/axios@1.13.0/node_modules/axios/lib/helpers/cookies.js
2251
+ var cookies_default = platform_default.hasStandardBrowserEnv ? (
2252
+ // Standard browser envs support document.cookie
2253
+ {
2254
+ write(name, value, expires, path, domain, secure, sameSite) {
2255
+ if (typeof document === "undefined") return;
2256
+ const cookie = ["".concat(name, "=").concat(encodeURIComponent(value))];
2257
+ if (utils_default.isNumber(expires)) {
2258
+ cookie.push("expires=".concat(new Date(expires).toUTCString()));
2259
+ }
2260
+ if (utils_default.isString(path)) {
2261
+ cookie.push("path=".concat(path));
2262
+ }
2263
+ if (utils_default.isString(domain)) {
2264
+ cookie.push("domain=".concat(domain));
2265
+ }
2266
+ if (secure === true) {
2267
+ cookie.push("secure");
2268
+ }
2269
+ if (utils_default.isString(sameSite)) {
2270
+ cookie.push("SameSite=".concat(sameSite));
2271
+ }
2272
+ document.cookie = cookie.join("; ");
2273
+ },
2274
+ read(name) {
2275
+ if (typeof document === "undefined") return null;
2276
+ const match = document.cookie.match(new RegExp("(?:^|; )" + name + "=([^;]*)"));
2277
+ return match ? decodeURIComponent(match[1]) : null;
2278
+ },
2279
+ remove(name) {
2280
+ this.write(name, "", Date.now() - 864e5, "/");
2281
+ }
2282
+ }
2283
+ ) : (
2284
+ // Non-standard browser env (web workers, react-native) lack needed support.
2285
+ {
2286
+ write() {
2287
+ },
2288
+ read() {
2289
+ return null;
2290
+ },
2291
+ remove() {
2292
+ }
2293
+ }
2294
+ );
2295
+
2296
+ // ../../node_modules/.pnpm/axios@1.13.0/node_modules/axios/lib/helpers/isAbsoluteURL.js
2297
+ function isAbsoluteURL(url) {
2298
+ return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
2299
+ }
2300
+
2301
+ // ../../node_modules/.pnpm/axios@1.13.0/node_modules/axios/lib/helpers/combineURLs.js
2302
+ function combineURLs(baseURL, relativeURL) {
2303
+ return relativeURL ? baseURL.replace(/\/?\/$/, "") + "/" + relativeURL.replace(/^\/+/, "") : baseURL;
2304
+ }
2305
+
2306
+ // ../../node_modules/.pnpm/axios@1.13.0/node_modules/axios/lib/core/buildFullPath.js
2307
+ function buildFullPath(baseURL, requestedURL, allowAbsoluteUrls) {
2308
+ let isRelativeUrl = !isAbsoluteURL(requestedURL);
2309
+ if (baseURL && (isRelativeUrl || allowAbsoluteUrls == false)) {
2310
+ return combineURLs(baseURL, requestedURL);
2311
+ }
2312
+ return requestedURL;
2313
+ }
2314
+
2315
+ // ../../node_modules/.pnpm/axios@1.13.0/node_modules/axios/lib/core/mergeConfig.js
2316
+ var headersToObject = (thing) => thing instanceof AxiosHeaders_default ? __spreadValues({}, thing) : thing;
2317
+ function mergeConfig(config1, config2) {
2318
+ config2 = config2 || {};
2319
+ const config = {};
2320
+ function getMergedValue(target, source, prop, caseless) {
2321
+ if (utils_default.isPlainObject(target) && utils_default.isPlainObject(source)) {
2322
+ return utils_default.merge.call({ caseless }, target, source);
2323
+ } else if (utils_default.isPlainObject(source)) {
2324
+ return utils_default.merge({}, source);
2325
+ } else if (utils_default.isArray(source)) {
2326
+ return source.slice();
2327
+ }
2328
+ return source;
2329
+ }
2330
+ function mergeDeepProperties(a, b, prop, caseless) {
2331
+ if (!utils_default.isUndefined(b)) {
2332
+ return getMergedValue(a, b, prop, caseless);
2333
+ } else if (!utils_default.isUndefined(a)) {
2334
+ return getMergedValue(void 0, a, prop, caseless);
2335
+ }
2336
+ }
2337
+ function valueFromConfig2(a, b) {
2338
+ if (!utils_default.isUndefined(b)) {
2339
+ return getMergedValue(void 0, b);
2340
+ }
2341
+ }
2342
+ function defaultToConfig2(a, b) {
2343
+ if (!utils_default.isUndefined(b)) {
2344
+ return getMergedValue(void 0, b);
2345
+ } else if (!utils_default.isUndefined(a)) {
2346
+ return getMergedValue(void 0, a);
2347
+ }
2348
+ }
2349
+ function mergeDirectKeys(a, b, prop) {
2350
+ if (prop in config2) {
2351
+ return getMergedValue(a, b);
2352
+ } else if (prop in config1) {
2353
+ return getMergedValue(void 0, a);
2354
+ }
2355
+ }
2356
+ const mergeMap = {
2357
+ url: valueFromConfig2,
2358
+ method: valueFromConfig2,
2359
+ data: valueFromConfig2,
2360
+ baseURL: defaultToConfig2,
2361
+ transformRequest: defaultToConfig2,
2362
+ transformResponse: defaultToConfig2,
2363
+ paramsSerializer: defaultToConfig2,
2364
+ timeout: defaultToConfig2,
2365
+ timeoutMessage: defaultToConfig2,
2366
+ withCredentials: defaultToConfig2,
2367
+ withXSRFToken: defaultToConfig2,
2368
+ adapter: defaultToConfig2,
2369
+ responseType: defaultToConfig2,
2370
+ xsrfCookieName: defaultToConfig2,
2371
+ xsrfHeaderName: defaultToConfig2,
2372
+ onUploadProgress: defaultToConfig2,
2373
+ onDownloadProgress: defaultToConfig2,
2374
+ decompress: defaultToConfig2,
2375
+ maxContentLength: defaultToConfig2,
2376
+ maxBodyLength: defaultToConfig2,
2377
+ beforeRedirect: defaultToConfig2,
2378
+ transport: defaultToConfig2,
2379
+ httpAgent: defaultToConfig2,
2380
+ httpsAgent: defaultToConfig2,
2381
+ cancelToken: defaultToConfig2,
2382
+ socketPath: defaultToConfig2,
2383
+ responseEncoding: defaultToConfig2,
2384
+ validateStatus: mergeDirectKeys,
2385
+ headers: (a, b, prop) => mergeDeepProperties(headersToObject(a), headersToObject(b), prop, true)
2386
+ };
2387
+ utils_default.forEach(Object.keys(__spreadValues(__spreadValues({}, config1), config2)), function computeConfigValue(prop) {
2388
+ const merge2 = mergeMap[prop] || mergeDeepProperties;
2389
+ const configValue = merge2(config1[prop], config2[prop], prop);
2390
+ utils_default.isUndefined(configValue) && merge2 !== mergeDirectKeys || (config[prop] = configValue);
2391
+ });
2392
+ return config;
2393
+ }
2394
+
2395
+ // ../../node_modules/.pnpm/axios@1.13.0/node_modules/axios/lib/helpers/resolveConfig.js
2396
+ var resolveConfig_default = (config) => {
2397
+ const newConfig = mergeConfig({}, config);
2398
+ let { data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth } = newConfig;
2399
+ newConfig.headers = headers = AxiosHeaders_default.from(headers);
2400
+ newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url, newConfig.allowAbsoluteUrls), config.params, config.paramsSerializer);
2401
+ if (auth) {
2402
+ headers.set(
2403
+ "Authorization",
2404
+ "Basic " + btoa((auth.username || "") + ":" + (auth.password ? unescape(encodeURIComponent(auth.password)) : ""))
2405
+ );
2406
+ }
2407
+ if (utils_default.isFormData(data)) {
2408
+ if (platform_default.hasStandardBrowserEnv || platform_default.hasStandardBrowserWebWorkerEnv) {
2409
+ headers.setContentType(void 0);
2410
+ } else if (utils_default.isFunction(data.getHeaders)) {
2411
+ const formHeaders = data.getHeaders();
2412
+ const allowedHeaders = ["content-type", "content-length"];
2413
+ Object.entries(formHeaders).forEach(([key, val]) => {
2414
+ if (allowedHeaders.includes(key.toLowerCase())) {
2415
+ headers.set(key, val);
2416
+ }
2417
+ });
2418
+ }
2419
+ }
2420
+ if (platform_default.hasStandardBrowserEnv) {
2421
+ withXSRFToken && utils_default.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig));
2422
+ if (withXSRFToken || withXSRFToken !== false && isURLSameOrigin_default(newConfig.url)) {
2423
+ const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies_default.read(xsrfCookieName);
2424
+ if (xsrfValue) {
2425
+ headers.set(xsrfHeaderName, xsrfValue);
2426
+ }
2427
+ }
2428
+ }
2429
+ return newConfig;
2430
+ };
2431
+
2432
+ // ../../node_modules/.pnpm/axios@1.13.0/node_modules/axios/lib/adapters/xhr.js
2433
+ var isXHRAdapterSupported = typeof XMLHttpRequest !== "undefined";
2434
+ var xhr_default = isXHRAdapterSupported && function(config) {
2435
+ return new Promise(function dispatchXhrRequest(resolve, reject) {
2436
+ const _config = resolveConfig_default(config);
2437
+ let requestData = _config.data;
2438
+ const requestHeaders = AxiosHeaders_default.from(_config.headers).normalize();
2439
+ let { responseType, onUploadProgress, onDownloadProgress } = _config;
2440
+ let onCanceled;
2441
+ let uploadThrottled, downloadThrottled;
2442
+ let flushUpload, flushDownload;
2443
+ function done() {
2444
+ flushUpload && flushUpload();
2445
+ flushDownload && flushDownload();
2446
+ _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled);
2447
+ _config.signal && _config.signal.removeEventListener("abort", onCanceled);
2448
+ }
2449
+ let request = new XMLHttpRequest();
2450
+ request.open(_config.method.toUpperCase(), _config.url, true);
2451
+ request.timeout = _config.timeout;
2452
+ function onloadend() {
2453
+ if (!request) {
2454
+ return;
2455
+ }
2456
+ const responseHeaders = AxiosHeaders_default.from(
2457
+ "getAllResponseHeaders" in request && request.getAllResponseHeaders()
2458
+ );
2459
+ const responseData = !responseType || responseType === "text" || responseType === "json" ? request.responseText : request.response;
2460
+ const response = {
2461
+ data: responseData,
2462
+ status: request.status,
2463
+ statusText: request.statusText,
2464
+ headers: responseHeaders,
2465
+ config,
2466
+ request
2467
+ };
2468
+ settle(function _resolve(value) {
2469
+ resolve(value);
2470
+ done();
2471
+ }, function _reject(err) {
2472
+ reject(err);
2473
+ done();
2474
+ }, response);
2475
+ request = null;
2476
+ }
2477
+ if ("onloadend" in request) {
2478
+ request.onloadend = onloadend;
2479
+ } else {
2480
+ request.onreadystatechange = function handleLoad() {
2481
+ if (!request || request.readyState !== 4) {
2482
+ return;
2483
+ }
2484
+ if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf("file:") === 0)) {
2485
+ return;
2486
+ }
2487
+ setTimeout(onloadend);
2488
+ };
2489
+ }
2490
+ request.onabort = function handleAbort() {
2491
+ if (!request) {
2492
+ return;
2493
+ }
2494
+ reject(new AxiosError_default("Request aborted", AxiosError_default.ECONNABORTED, config, request));
2495
+ request = null;
2496
+ };
2497
+ request.onerror = function handleError(event) {
2498
+ const msg = event && event.message ? event.message : "Network Error";
2499
+ const err = new AxiosError_default(msg, AxiosError_default.ERR_NETWORK, config, request);
2500
+ err.event = event || null;
2501
+ reject(err);
2502
+ request = null;
2503
+ };
2504
+ request.ontimeout = function handleTimeout() {
2505
+ let timeoutErrorMessage = _config.timeout ? "timeout of " + _config.timeout + "ms exceeded" : "timeout exceeded";
2506
+ const transitional2 = _config.transitional || transitional_default;
2507
+ if (_config.timeoutErrorMessage) {
2508
+ timeoutErrorMessage = _config.timeoutErrorMessage;
2509
+ }
2510
+ reject(new AxiosError_default(
2511
+ timeoutErrorMessage,
2512
+ transitional2.clarifyTimeoutError ? AxiosError_default.ETIMEDOUT : AxiosError_default.ECONNABORTED,
2513
+ config,
2514
+ request
2515
+ ));
2516
+ request = null;
2517
+ };
2518
+ requestData === void 0 && requestHeaders.setContentType(null);
2519
+ if ("setRequestHeader" in request) {
2520
+ utils_default.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) {
2521
+ request.setRequestHeader(key, val);
2522
+ });
2523
+ }
2524
+ if (!utils_default.isUndefined(_config.withCredentials)) {
2525
+ request.withCredentials = !!_config.withCredentials;
2526
+ }
2527
+ if (responseType && responseType !== "json") {
2528
+ request.responseType = _config.responseType;
2529
+ }
2530
+ if (onDownloadProgress) {
2531
+ [downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true);
2532
+ request.addEventListener("progress", downloadThrottled);
2533
+ }
2534
+ if (onUploadProgress && request.upload) {
2535
+ [uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress);
2536
+ request.upload.addEventListener("progress", uploadThrottled);
2537
+ request.upload.addEventListener("loadend", flushUpload);
2538
+ }
2539
+ if (_config.cancelToken || _config.signal) {
2540
+ onCanceled = (cancel) => {
2541
+ if (!request) {
2542
+ return;
2543
+ }
2544
+ reject(!cancel || cancel.type ? new CanceledError_default(null, config, request) : cancel);
2545
+ request.abort();
2546
+ request = null;
2547
+ };
2548
+ _config.cancelToken && _config.cancelToken.subscribe(onCanceled);
2549
+ if (_config.signal) {
2550
+ _config.signal.aborted ? onCanceled() : _config.signal.addEventListener("abort", onCanceled);
2551
+ }
2552
+ }
2553
+ const protocol = parseProtocol(_config.url);
2554
+ if (protocol && platform_default.protocols.indexOf(protocol) === -1) {
2555
+ reject(new AxiosError_default("Unsupported protocol " + protocol + ":", AxiosError_default.ERR_BAD_REQUEST, config));
2556
+ return;
2557
+ }
2558
+ request.send(requestData || null);
2559
+ });
2560
+ };
2561
+
2562
+ // ../../node_modules/.pnpm/axios@1.13.0/node_modules/axios/lib/helpers/composeSignals.js
2563
+ var composeSignals = (signals, timeout) => {
2564
+ const { length } = signals = signals ? signals.filter(Boolean) : [];
2565
+ if (timeout || length) {
2566
+ let controller = new AbortController();
2567
+ let aborted;
2568
+ const onabort = function(reason) {
2569
+ if (!aborted) {
2570
+ aborted = true;
2571
+ unsubscribe();
2572
+ const err = reason instanceof Error ? reason : this.reason;
2573
+ controller.abort(err instanceof AxiosError_default ? err : new CanceledError_default(err instanceof Error ? err.message : err));
2574
+ }
2575
+ };
2576
+ let timer = timeout && setTimeout(() => {
2577
+ timer = null;
2578
+ onabort(new AxiosError_default("timeout ".concat(timeout, " of ms exceeded"), AxiosError_default.ETIMEDOUT));
2579
+ }, timeout);
2580
+ const unsubscribe = () => {
2581
+ if (signals) {
2582
+ timer && clearTimeout(timer);
2583
+ timer = null;
2584
+ signals.forEach((signal2) => {
2585
+ signal2.unsubscribe ? signal2.unsubscribe(onabort) : signal2.removeEventListener("abort", onabort);
2586
+ });
2587
+ signals = null;
2588
+ }
2589
+ };
2590
+ signals.forEach((signal2) => signal2.addEventListener("abort", onabort));
2591
+ const { signal } = controller;
2592
+ signal.unsubscribe = () => utils_default.asap(unsubscribe);
2593
+ return signal;
2594
+ }
2595
+ };
2596
+ var composeSignals_default = composeSignals;
2597
+
2598
+ // ../../node_modules/.pnpm/axios@1.13.0/node_modules/axios/lib/helpers/trackStream.js
2599
+ var streamChunk = function* (chunk, chunkSize) {
2600
+ let len = chunk.byteLength;
2601
+ if (!chunkSize || len < chunkSize) {
2602
+ yield chunk;
2603
+ return;
2604
+ }
2605
+ let pos = 0;
2606
+ let end;
2607
+ while (pos < len) {
2608
+ end = pos + chunkSize;
2609
+ yield chunk.slice(pos, end);
2610
+ pos = end;
2611
+ }
2612
+ };
2613
+ var readBytes = function(iterable, chunkSize) {
2614
+ return __asyncGenerator(this, null, function* () {
2615
+ try {
2616
+ for (var iter = __forAwait(readStream(iterable)), more, temp, error; more = !(temp = yield new __await(iter.next())).done; more = false) {
2617
+ const chunk = temp.value;
2618
+ yield* __yieldStar(streamChunk(chunk, chunkSize));
2619
+ }
2620
+ } catch (temp) {
2621
+ error = [temp];
2622
+ } finally {
2623
+ try {
2624
+ more && (temp = iter.return) && (yield new __await(temp.call(iter)));
2625
+ } finally {
2626
+ if (error)
2627
+ throw error[0];
2628
+ }
2629
+ }
2630
+ });
2631
+ };
2632
+ var readStream = function(stream) {
2633
+ return __asyncGenerator(this, null, function* () {
2634
+ if (stream[Symbol.asyncIterator]) {
2635
+ yield* __yieldStar(stream);
2636
+ return;
2637
+ }
2638
+ const reader = stream.getReader();
2639
+ try {
2640
+ for (; ; ) {
2641
+ const { done, value } = yield new __await(reader.read());
2642
+ if (done) {
2643
+ break;
2644
+ }
2645
+ yield value;
2646
+ }
2647
+ } finally {
2648
+ yield new __await(reader.cancel());
2649
+ }
2650
+ });
2651
+ };
2652
+ var trackStream = (stream, chunkSize, onProgress, onFinish) => {
2653
+ const iterator2 = readBytes(stream, chunkSize);
2654
+ let bytes = 0;
2655
+ let done;
2656
+ let _onFinish = (e) => {
2657
+ if (!done) {
2658
+ done = true;
2659
+ onFinish && onFinish(e);
2660
+ }
2661
+ };
2662
+ return new ReadableStream({
2663
+ async pull(controller) {
2664
+ try {
2665
+ const { done: done2, value } = await iterator2.next();
2666
+ if (done2) {
2667
+ _onFinish();
2668
+ controller.close();
2669
+ return;
2670
+ }
2671
+ let len = value.byteLength;
2672
+ if (onProgress) {
2673
+ let loadedBytes = bytes += len;
2674
+ onProgress(loadedBytes);
2675
+ }
2676
+ controller.enqueue(new Uint8Array(value));
2677
+ } catch (err) {
2678
+ _onFinish(err);
2679
+ throw err;
2680
+ }
2681
+ },
2682
+ cancel(reason) {
2683
+ _onFinish(reason);
2684
+ return iterator2.return();
2685
+ }
2686
+ }, {
2687
+ highWaterMark: 2
2688
+ });
2689
+ };
2690
+
2691
+ // ../../node_modules/.pnpm/axios@1.13.0/node_modules/axios/lib/adapters/fetch.js
2692
+ var DEFAULT_CHUNK_SIZE = 64 * 1024;
2693
+ var { isFunction: isFunction2 } = utils_default;
2694
+ var globalFetchAPI = (({ Request, Response }) => ({
2695
+ Request,
2696
+ Response
2697
+ }))(utils_default.global);
2698
+ var {
2699
+ ReadableStream: ReadableStream2,
2700
+ TextEncoder
2701
+ } = utils_default.global;
2702
+ var test = (fn, ...args) => {
2703
+ try {
2704
+ return !!fn(...args);
2705
+ } catch (e) {
2706
+ return false;
2707
+ }
2708
+ };
2709
+ var factory = (env) => {
2710
+ env = utils_default.merge.call({
2711
+ skipUndefined: true
2712
+ }, globalFetchAPI, env);
2713
+ const { fetch: envFetch, Request, Response } = env;
2714
+ const isFetchSupported = envFetch ? isFunction2(envFetch) : typeof fetch === "function";
2715
+ const isRequestSupported = isFunction2(Request);
2716
+ const isResponseSupported = isFunction2(Response);
2717
+ if (!isFetchSupported) {
2718
+ return false;
2719
+ }
2720
+ const isReadableStreamSupported = isFetchSupported && isFunction2(ReadableStream2);
2721
+ const encodeText = isFetchSupported && (typeof TextEncoder === "function" ? /* @__PURE__ */ ((encoder) => (str) => encoder.encode(str))(new TextEncoder()) : async (str) => new Uint8Array(await new Request(str).arrayBuffer()));
2722
+ const supportsRequestStream = isRequestSupported && isReadableStreamSupported && test(() => {
2723
+ let duplexAccessed = false;
2724
+ const hasContentType = new Request(platform_default.origin, {
2725
+ body: new ReadableStream2(),
2726
+ method: "POST",
2727
+ get duplex() {
2728
+ duplexAccessed = true;
2729
+ return "half";
2730
+ }
2731
+ }).headers.has("Content-Type");
2732
+ return duplexAccessed && !hasContentType;
2733
+ });
2734
+ const supportsResponseStream = isResponseSupported && isReadableStreamSupported && test(() => utils_default.isReadableStream(new Response("").body));
2735
+ const resolvers = {
2736
+ stream: supportsResponseStream && ((res) => res.body)
2737
+ };
2738
+ isFetchSupported && (() => {
2739
+ ["text", "arrayBuffer", "blob", "formData", "stream"].forEach((type) => {
2740
+ !resolvers[type] && (resolvers[type] = (res, config) => {
2741
+ let method = res && res[type];
2742
+ if (method) {
2743
+ return method.call(res);
2744
+ }
2745
+ throw new AxiosError_default("Response type '".concat(type, "' is not supported"), AxiosError_default.ERR_NOT_SUPPORT, config);
2746
+ });
2747
+ });
2748
+ })();
2749
+ const getBodyLength = async (body) => {
2750
+ if (body == null) {
2751
+ return 0;
2752
+ }
2753
+ if (utils_default.isBlob(body)) {
2754
+ return body.size;
2755
+ }
2756
+ if (utils_default.isSpecCompliantForm(body)) {
2757
+ const _request = new Request(platform_default.origin, {
2758
+ method: "POST",
2759
+ body
2760
+ });
2761
+ return (await _request.arrayBuffer()).byteLength;
2762
+ }
2763
+ if (utils_default.isArrayBufferView(body) || utils_default.isArrayBuffer(body)) {
2764
+ return body.byteLength;
2765
+ }
2766
+ if (utils_default.isURLSearchParams(body)) {
2767
+ body = body + "";
2768
+ }
2769
+ if (utils_default.isString(body)) {
2770
+ return (await encodeText(body)).byteLength;
2771
+ }
2772
+ };
2773
+ const resolveBodyLength = async (headers, body) => {
2774
+ const length = utils_default.toFiniteNumber(headers.getContentLength());
2775
+ return length == null ? getBodyLength(body) : length;
2776
+ };
2777
+ return async (config) => {
2778
+ let {
2779
+ url,
2780
+ method,
2781
+ data,
2782
+ signal,
2783
+ cancelToken,
2784
+ timeout,
2785
+ onDownloadProgress,
2786
+ onUploadProgress,
2787
+ responseType,
2788
+ headers,
2789
+ withCredentials = "same-origin",
2790
+ fetchOptions
2791
+ } = resolveConfig_default(config);
2792
+ let _fetch = envFetch || fetch;
2793
+ responseType = responseType ? (responseType + "").toLowerCase() : "text";
2794
+ let composedSignal = composeSignals_default([signal, cancelToken && cancelToken.toAbortSignal()], timeout);
2795
+ let request = null;
2796
+ const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => {
2797
+ composedSignal.unsubscribe();
2798
+ });
2799
+ let requestContentLength;
2800
+ try {
2801
+ if (onUploadProgress && supportsRequestStream && method !== "get" && method !== "head" && (requestContentLength = await resolveBodyLength(headers, data)) !== 0) {
2802
+ let _request = new Request(url, {
2803
+ method: "POST",
2804
+ body: data,
2805
+ duplex: "half"
2806
+ });
2807
+ let contentTypeHeader;
2808
+ if (utils_default.isFormData(data) && (contentTypeHeader = _request.headers.get("content-type"))) {
2809
+ headers.setContentType(contentTypeHeader);
2810
+ }
2811
+ if (_request.body) {
2812
+ const [onProgress, flush] = progressEventDecorator(
2813
+ requestContentLength,
2814
+ progressEventReducer(asyncDecorator(onUploadProgress))
2815
+ );
2816
+ data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush);
2817
+ }
2818
+ }
2819
+ if (!utils_default.isString(withCredentials)) {
2820
+ withCredentials = withCredentials ? "include" : "omit";
2821
+ }
2822
+ const isCredentialsSupported = isRequestSupported && "credentials" in Request.prototype;
2823
+ const resolvedOptions = __spreadProps(__spreadValues({}, fetchOptions), {
2824
+ signal: composedSignal,
2825
+ method: method.toUpperCase(),
2826
+ headers: headers.normalize().toJSON(),
2827
+ body: data,
2828
+ duplex: "half",
2829
+ credentials: isCredentialsSupported ? withCredentials : void 0
2830
+ });
2831
+ request = isRequestSupported && new Request(url, resolvedOptions);
2832
+ let response = await (isRequestSupported ? _fetch(request, fetchOptions) : _fetch(url, resolvedOptions));
2833
+ const isStreamResponse = supportsResponseStream && (responseType === "stream" || responseType === "response");
2834
+ if (supportsResponseStream && (onDownloadProgress || isStreamResponse && unsubscribe)) {
2835
+ const options = {};
2836
+ ["status", "statusText", "headers"].forEach((prop) => {
2837
+ options[prop] = response[prop];
2838
+ });
2839
+ const responseContentLength = utils_default.toFiniteNumber(response.headers.get("content-length"));
2840
+ const [onProgress, flush] = onDownloadProgress && progressEventDecorator(
2841
+ responseContentLength,
2842
+ progressEventReducer(asyncDecorator(onDownloadProgress), true)
2843
+ ) || [];
2844
+ response = new Response(
2845
+ trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => {
2846
+ flush && flush();
2847
+ unsubscribe && unsubscribe();
2848
+ }),
2849
+ options
2850
+ );
2851
+ }
2852
+ responseType = responseType || "text";
2853
+ let responseData = await resolvers[utils_default.findKey(resolvers, responseType) || "text"](response, config);
2854
+ !isStreamResponse && unsubscribe && unsubscribe();
2855
+ return await new Promise((resolve, reject) => {
2856
+ settle(resolve, reject, {
2857
+ data: responseData,
2858
+ headers: AxiosHeaders_default.from(response.headers),
2859
+ status: response.status,
2860
+ statusText: response.statusText,
2861
+ config,
2862
+ request
2863
+ });
2864
+ });
2865
+ } catch (err) {
2866
+ unsubscribe && unsubscribe();
2867
+ if (err && err.name === "TypeError" && /Load failed|fetch/i.test(err.message)) {
2868
+ throw Object.assign(
2869
+ new AxiosError_default("Network Error", AxiosError_default.ERR_NETWORK, config, request),
2870
+ {
2871
+ cause: err.cause || err
2872
+ }
2873
+ );
2874
+ }
2875
+ throw AxiosError_default.from(err, err && err.code, config, request);
2876
+ }
2877
+ };
2878
+ };
2879
+ var seedCache = /* @__PURE__ */ new Map();
2880
+ var getFetch = (config) => {
2881
+ let env = config && config.env || {};
2882
+ const { fetch: fetch2, Request, Response } = env;
2883
+ const seeds = [
2884
+ Request,
2885
+ Response,
2886
+ fetch2
2887
+ ];
2888
+ let len = seeds.length, i = len, seed, target, map = seedCache;
2889
+ while (i--) {
2890
+ seed = seeds[i];
2891
+ target = map.get(seed);
2892
+ target === void 0 && map.set(seed, target = i ? /* @__PURE__ */ new Map() : factory(env));
2893
+ map = target;
2894
+ }
2895
+ return target;
2896
+ };
2897
+ var adapter = getFetch();
2898
+
2899
+ // ../../node_modules/.pnpm/axios@1.13.0/node_modules/axios/lib/adapters/adapters.js
2900
+ var knownAdapters = {
2901
+ http: null_default,
2902
+ xhr: xhr_default,
2903
+ fetch: {
2904
+ get: getFetch
2905
+ }
2906
+ };
2907
+ utils_default.forEach(knownAdapters, (fn, value) => {
2908
+ if (fn) {
2909
+ try {
2910
+ Object.defineProperty(fn, "name", { value });
2911
+ } catch (e) {
2912
+ }
2913
+ Object.defineProperty(fn, "adapterName", { value });
2914
+ }
2915
+ });
2916
+ var renderReason = (reason) => "- ".concat(reason);
2917
+ var isResolvedHandle = (adapter2) => utils_default.isFunction(adapter2) || adapter2 === null || adapter2 === false;
2918
+ function getAdapter(adapters, config) {
2919
+ adapters = utils_default.isArray(adapters) ? adapters : [adapters];
2920
+ const { length } = adapters;
2921
+ let nameOrAdapter;
2922
+ let adapter2;
2923
+ const rejectedReasons = {};
2924
+ for (let i = 0; i < length; i++) {
2925
+ nameOrAdapter = adapters[i];
2926
+ let id;
2927
+ adapter2 = nameOrAdapter;
2928
+ if (!isResolvedHandle(nameOrAdapter)) {
2929
+ adapter2 = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()];
2930
+ if (adapter2 === void 0) {
2931
+ throw new AxiosError_default("Unknown adapter '".concat(id, "'"));
2932
+ }
2933
+ }
2934
+ if (adapter2 && (utils_default.isFunction(adapter2) || (adapter2 = adapter2.get(config)))) {
2935
+ break;
2936
+ }
2937
+ rejectedReasons[id || "#" + i] = adapter2;
2938
+ }
2939
+ if (!adapter2) {
2940
+ const reasons = Object.entries(rejectedReasons).map(
2941
+ ([id, state]) => "adapter ".concat(id, " ") + (state === false ? "is not supported by the environment" : "is not available in the build")
2942
+ );
2943
+ let s = length ? reasons.length > 1 ? "since :\n" + reasons.map(renderReason).join("\n") : " " + renderReason(reasons[0]) : "as no adapter specified";
2944
+ throw new AxiosError_default(
2945
+ "There is no suitable adapter to dispatch the request " + s,
2946
+ "ERR_NOT_SUPPORT"
2947
+ );
2948
+ }
2949
+ return adapter2;
2950
+ }
2951
+ var adapters_default = {
2952
+ /**
2953
+ * Resolve an adapter from a list of adapter names or functions.
2954
+ * @type {Function}
2955
+ */
2956
+ getAdapter,
2957
+ /**
2958
+ * Exposes all known adapters
2959
+ * @type {Object<string, Function|Object>}
2960
+ */
2961
+ adapters: knownAdapters
2962
+ };
2963
+
2964
+ // ../../node_modules/.pnpm/axios@1.13.0/node_modules/axios/lib/core/dispatchRequest.js
2965
+ function throwIfCancellationRequested(config) {
2966
+ if (config.cancelToken) {
2967
+ config.cancelToken.throwIfRequested();
2968
+ }
2969
+ if (config.signal && config.signal.aborted) {
2970
+ throw new CanceledError_default(null, config);
2971
+ }
2972
+ }
2973
+ function dispatchRequest(config) {
2974
+ throwIfCancellationRequested(config);
2975
+ config.headers = AxiosHeaders_default.from(config.headers);
2976
+ config.data = transformData.call(
2977
+ config,
2978
+ config.transformRequest
2979
+ );
2980
+ if (["post", "put", "patch"].indexOf(config.method) !== -1) {
2981
+ config.headers.setContentType("application/x-www-form-urlencoded", false);
2982
+ }
2983
+ const adapter2 = adapters_default.getAdapter(config.adapter || defaults_default.adapter, config);
2984
+ return adapter2(config).then(function onAdapterResolution(response) {
2985
+ throwIfCancellationRequested(config);
2986
+ response.data = transformData.call(
2987
+ config,
2988
+ config.transformResponse,
2989
+ response
2990
+ );
2991
+ response.headers = AxiosHeaders_default.from(response.headers);
2992
+ return response;
2993
+ }, function onAdapterRejection(reason) {
2994
+ if (!isCancel(reason)) {
2995
+ throwIfCancellationRequested(config);
2996
+ if (reason && reason.response) {
2997
+ reason.response.data = transformData.call(
2998
+ config,
2999
+ config.transformResponse,
3000
+ reason.response
3001
+ );
3002
+ reason.response.headers = AxiosHeaders_default.from(reason.response.headers);
3003
+ }
3004
+ }
3005
+ return Promise.reject(reason);
3006
+ });
3007
+ }
3008
+
3009
+ // ../../node_modules/.pnpm/axios@1.13.0/node_modules/axios/lib/env/data.js
3010
+ var VERSION = "1.13.0";
3011
+
3012
+ // ../../node_modules/.pnpm/axios@1.13.0/node_modules/axios/lib/helpers/validator.js
3013
+ var validators = {};
3014
+ ["object", "boolean", "number", "function", "string", "symbol"].forEach((type, i) => {
3015
+ validators[type] = function validator(thing) {
3016
+ return typeof thing === type || "a" + (i < 1 ? "n " : " ") + type;
3017
+ };
3018
+ });
3019
+ var deprecatedWarnings = {};
3020
+ validators.transitional = function transitional(validator, version, message) {
3021
+ function formatMessage(opt, desc) {
3022
+ return "[Axios v" + VERSION + "] Transitional option '" + opt + "'" + desc + (message ? ". " + message : "");
3023
+ }
3024
+ return (value, opt, opts) => {
3025
+ if (validator === false) {
3026
+ throw new AxiosError_default(
3027
+ formatMessage(opt, " has been removed" + (version ? " in " + version : "")),
3028
+ AxiosError_default.ERR_DEPRECATED
3029
+ );
3030
+ }
3031
+ if (version && !deprecatedWarnings[opt]) {
3032
+ deprecatedWarnings[opt] = true;
3033
+ console.warn(
3034
+ formatMessage(
3035
+ opt,
3036
+ " has been deprecated since v" + version + " and will be removed in the near future"
3037
+ )
3038
+ );
3039
+ }
3040
+ return validator ? validator(value, opt, opts) : true;
3041
+ };
3042
+ };
3043
+ validators.spelling = function spelling(correctSpelling) {
3044
+ return (value, opt) => {
3045
+ console.warn("".concat(opt, " is likely a misspelling of ").concat(correctSpelling));
3046
+ return true;
3047
+ };
3048
+ };
3049
+ function assertOptions(options, schema, allowUnknown) {
3050
+ if (typeof options !== "object") {
3051
+ throw new AxiosError_default("options must be an object", AxiosError_default.ERR_BAD_OPTION_VALUE);
3052
+ }
3053
+ const keys = Object.keys(options);
3054
+ let i = keys.length;
3055
+ while (i-- > 0) {
3056
+ const opt = keys[i];
3057
+ const validator = schema[opt];
3058
+ if (validator) {
3059
+ const value = options[opt];
3060
+ const result = value === void 0 || validator(value, opt, options);
3061
+ if (result !== true) {
3062
+ throw new AxiosError_default("option " + opt + " must be " + result, AxiosError_default.ERR_BAD_OPTION_VALUE);
3063
+ }
3064
+ continue;
3065
+ }
3066
+ if (allowUnknown !== true) {
3067
+ throw new AxiosError_default("Unknown option " + opt, AxiosError_default.ERR_BAD_OPTION);
3068
+ }
3069
+ }
3070
+ }
3071
+ var validator_default = {
3072
+ assertOptions,
3073
+ validators
3074
+ };
3075
+
3076
+ // ../../node_modules/.pnpm/axios@1.13.0/node_modules/axios/lib/core/Axios.js
3077
+ var validators2 = validator_default.validators;
3078
+ var Axios = class {
3079
+ constructor(instanceConfig) {
3080
+ this.defaults = instanceConfig || {};
3081
+ this.interceptors = {
3082
+ request: new InterceptorManager_default(),
3083
+ response: new InterceptorManager_default()
3084
+ };
3085
+ }
3086
+ /**
3087
+ * Dispatch a request
3088
+ *
3089
+ * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)
3090
+ * @param {?Object} config
3091
+ *
3092
+ * @returns {Promise} The Promise to be fulfilled
3093
+ */
3094
+ async request(configOrUrl, config) {
3095
+ try {
3096
+ return await this._request(configOrUrl, config);
3097
+ } catch (err) {
3098
+ if (err instanceof Error) {
3099
+ let dummy = {};
3100
+ Error.captureStackTrace ? Error.captureStackTrace(dummy) : dummy = new Error();
3101
+ const stack = dummy.stack ? dummy.stack.replace(/^.+\n/, "") : "";
3102
+ try {
3103
+ if (!err.stack) {
3104
+ err.stack = stack;
3105
+ } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\n.+\n/, ""))) {
3106
+ err.stack += "\n" + stack;
3107
+ }
3108
+ } catch (e) {
3109
+ }
3110
+ }
3111
+ throw err;
3112
+ }
3113
+ }
3114
+ _request(configOrUrl, config) {
3115
+ if (typeof configOrUrl === "string") {
3116
+ config = config || {};
3117
+ config.url = configOrUrl;
3118
+ } else {
3119
+ config = configOrUrl || {};
3120
+ }
3121
+ config = mergeConfig(this.defaults, config);
3122
+ const { transitional: transitional2, paramsSerializer, headers } = config;
3123
+ if (transitional2 !== void 0) {
3124
+ validator_default.assertOptions(transitional2, {
3125
+ silentJSONParsing: validators2.transitional(validators2.boolean),
3126
+ forcedJSONParsing: validators2.transitional(validators2.boolean),
3127
+ clarifyTimeoutError: validators2.transitional(validators2.boolean)
3128
+ }, false);
3129
+ }
3130
+ if (paramsSerializer != null) {
3131
+ if (utils_default.isFunction(paramsSerializer)) {
3132
+ config.paramsSerializer = {
3133
+ serialize: paramsSerializer
3134
+ };
3135
+ } else {
3136
+ validator_default.assertOptions(paramsSerializer, {
3137
+ encode: validators2.function,
3138
+ serialize: validators2.function
3139
+ }, true);
3140
+ }
3141
+ }
3142
+ if (config.allowAbsoluteUrls !== void 0) {
3143
+ } else if (this.defaults.allowAbsoluteUrls !== void 0) {
3144
+ config.allowAbsoluteUrls = this.defaults.allowAbsoluteUrls;
3145
+ } else {
3146
+ config.allowAbsoluteUrls = true;
3147
+ }
3148
+ validator_default.assertOptions(config, {
3149
+ baseUrl: validators2.spelling("baseURL"),
3150
+ withXsrfToken: validators2.spelling("withXSRFToken")
3151
+ }, true);
3152
+ config.method = (config.method || this.defaults.method || "get").toLowerCase();
3153
+ let contextHeaders = headers && utils_default.merge(
3154
+ headers.common,
3155
+ headers[config.method]
3156
+ );
3157
+ headers && utils_default.forEach(
3158
+ ["delete", "get", "head", "post", "put", "patch", "common"],
3159
+ (method) => {
3160
+ delete headers[method];
3161
+ }
3162
+ );
3163
+ config.headers = AxiosHeaders_default.concat(contextHeaders, headers);
3164
+ const requestInterceptorChain = [];
3165
+ let synchronousRequestInterceptors = true;
3166
+ this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
3167
+ if (typeof interceptor.runWhen === "function" && interceptor.runWhen(config) === false) {
3168
+ return;
3169
+ }
3170
+ synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
3171
+ requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
3172
+ });
3173
+ const responseInterceptorChain = [];
3174
+ this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
3175
+ responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
3176
+ });
3177
+ let promise;
3178
+ let i = 0;
3179
+ let len;
3180
+ if (!synchronousRequestInterceptors) {
3181
+ const chain = [dispatchRequest.bind(this), void 0];
3182
+ chain.unshift(...requestInterceptorChain);
3183
+ chain.push(...responseInterceptorChain);
3184
+ len = chain.length;
3185
+ promise = Promise.resolve(config);
3186
+ while (i < len) {
3187
+ promise = promise.then(chain[i++], chain[i++]);
3188
+ }
3189
+ return promise;
3190
+ }
3191
+ len = requestInterceptorChain.length;
3192
+ let newConfig = config;
3193
+ while (i < len) {
3194
+ const onFulfilled = requestInterceptorChain[i++];
3195
+ const onRejected = requestInterceptorChain[i++];
3196
+ try {
3197
+ newConfig = onFulfilled(newConfig);
3198
+ } catch (error) {
3199
+ onRejected.call(this, error);
3200
+ break;
3201
+ }
3202
+ }
3203
+ try {
3204
+ promise = dispatchRequest.call(this, newConfig);
3205
+ } catch (error) {
3206
+ return Promise.reject(error);
3207
+ }
3208
+ i = 0;
3209
+ len = responseInterceptorChain.length;
3210
+ while (i < len) {
3211
+ promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
3212
+ }
3213
+ return promise;
3214
+ }
3215
+ getUri(config) {
3216
+ config = mergeConfig(this.defaults, config);
3217
+ const fullPath = buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls);
3218
+ return buildURL(fullPath, config.params, config.paramsSerializer);
3219
+ }
3220
+ };
3221
+ utils_default.forEach(["delete", "get", "head", "options"], function forEachMethodNoData(method) {
3222
+ Axios.prototype[method] = function(url, config) {
3223
+ return this.request(mergeConfig(config || {}, {
3224
+ method,
3225
+ url,
3226
+ data: (config || {}).data
3227
+ }));
3228
+ };
3229
+ });
3230
+ utils_default.forEach(["post", "put", "patch"], function forEachMethodWithData(method) {
3231
+ function generateHTTPMethod(isForm) {
3232
+ return function httpMethod(url, data, config) {
3233
+ return this.request(mergeConfig(config || {}, {
3234
+ method,
3235
+ headers: isForm ? {
3236
+ "Content-Type": "multipart/form-data"
3237
+ } : {},
3238
+ url,
3239
+ data
3240
+ }));
3241
+ };
3242
+ }
3243
+ Axios.prototype[method] = generateHTTPMethod();
3244
+ Axios.prototype[method + "Form"] = generateHTTPMethod(true);
3245
+ });
3246
+ var Axios_default = Axios;
3247
+
3248
+ // ../../node_modules/.pnpm/axios@1.13.0/node_modules/axios/lib/cancel/CancelToken.js
3249
+ var CancelToken = class _CancelToken {
3250
+ constructor(executor) {
3251
+ if (typeof executor !== "function") {
3252
+ throw new TypeError("executor must be a function.");
3253
+ }
3254
+ let resolvePromise;
3255
+ this.promise = new Promise(function promiseExecutor(resolve) {
3256
+ resolvePromise = resolve;
3257
+ });
3258
+ const token = this;
3259
+ this.promise.then((cancel) => {
3260
+ if (!token._listeners) return;
3261
+ let i = token._listeners.length;
3262
+ while (i-- > 0) {
3263
+ token._listeners[i](cancel);
3264
+ }
3265
+ token._listeners = null;
3266
+ });
3267
+ this.promise.then = (onfulfilled) => {
3268
+ let _resolve;
3269
+ const promise = new Promise((resolve) => {
3270
+ token.subscribe(resolve);
3271
+ _resolve = resolve;
3272
+ }).then(onfulfilled);
3273
+ promise.cancel = function reject() {
3274
+ token.unsubscribe(_resolve);
3275
+ };
3276
+ return promise;
3277
+ };
3278
+ executor(function cancel(message, config, request) {
3279
+ if (token.reason) {
3280
+ return;
3281
+ }
3282
+ token.reason = new CanceledError_default(message, config, request);
3283
+ resolvePromise(token.reason);
3284
+ });
3285
+ }
3286
+ /**
3287
+ * Throws a `CanceledError` if cancellation has been requested.
3288
+ */
3289
+ throwIfRequested() {
3290
+ if (this.reason) {
3291
+ throw this.reason;
3292
+ }
3293
+ }
3294
+ /**
3295
+ * Subscribe to the cancel signal
3296
+ */
3297
+ subscribe(listener) {
3298
+ if (this.reason) {
3299
+ listener(this.reason);
3300
+ return;
3301
+ }
3302
+ if (this._listeners) {
3303
+ this._listeners.push(listener);
3304
+ } else {
3305
+ this._listeners = [listener];
3306
+ }
3307
+ }
3308
+ /**
3309
+ * Unsubscribe from the cancel signal
3310
+ */
3311
+ unsubscribe(listener) {
3312
+ if (!this._listeners) {
3313
+ return;
3314
+ }
3315
+ const index = this._listeners.indexOf(listener);
3316
+ if (index !== -1) {
3317
+ this._listeners.splice(index, 1);
3318
+ }
3319
+ }
3320
+ toAbortSignal() {
3321
+ const controller = new AbortController();
3322
+ const abort = (err) => {
3323
+ controller.abort(err);
3324
+ };
3325
+ this.subscribe(abort);
3326
+ controller.signal.unsubscribe = () => this.unsubscribe(abort);
3327
+ return controller.signal;
3328
+ }
3329
+ /**
3330
+ * Returns an object that contains a new `CancelToken` and a function that, when called,
3331
+ * cancels the `CancelToken`.
3332
+ */
3333
+ static source() {
3334
+ let cancel;
3335
+ const token = new _CancelToken(function executor(c) {
3336
+ cancel = c;
3337
+ });
3338
+ return {
3339
+ token,
3340
+ cancel
3341
+ };
3342
+ }
3343
+ };
3344
+ var CancelToken_default = CancelToken;
3345
+
3346
+ // ../../node_modules/.pnpm/axios@1.13.0/node_modules/axios/lib/helpers/spread.js
3347
+ function spread(callback) {
3348
+ return function wrap(arr) {
3349
+ return callback.apply(null, arr);
3350
+ };
3351
+ }
3352
+
3353
+ // ../../node_modules/.pnpm/axios@1.13.0/node_modules/axios/lib/helpers/isAxiosError.js
3354
+ function isAxiosError(payload) {
3355
+ return utils_default.isObject(payload) && payload.isAxiosError === true;
3356
+ }
3357
+
3358
+ // ../../node_modules/.pnpm/axios@1.13.0/node_modules/axios/lib/helpers/HttpStatusCode.js
3359
+ var HttpStatusCode = {
3360
+ Continue: 100,
3361
+ SwitchingProtocols: 101,
3362
+ Processing: 102,
3363
+ EarlyHints: 103,
3364
+ Ok: 200,
3365
+ Created: 201,
3366
+ Accepted: 202,
3367
+ NonAuthoritativeInformation: 203,
3368
+ NoContent: 204,
3369
+ ResetContent: 205,
3370
+ PartialContent: 206,
3371
+ MultiStatus: 207,
3372
+ AlreadyReported: 208,
3373
+ ImUsed: 226,
3374
+ MultipleChoices: 300,
3375
+ MovedPermanently: 301,
3376
+ Found: 302,
3377
+ SeeOther: 303,
3378
+ NotModified: 304,
3379
+ UseProxy: 305,
3380
+ Unused: 306,
3381
+ TemporaryRedirect: 307,
3382
+ PermanentRedirect: 308,
3383
+ BadRequest: 400,
3384
+ Unauthorized: 401,
3385
+ PaymentRequired: 402,
3386
+ Forbidden: 403,
3387
+ NotFound: 404,
3388
+ MethodNotAllowed: 405,
3389
+ NotAcceptable: 406,
3390
+ ProxyAuthenticationRequired: 407,
3391
+ RequestTimeout: 408,
3392
+ Conflict: 409,
3393
+ Gone: 410,
3394
+ LengthRequired: 411,
3395
+ PreconditionFailed: 412,
3396
+ PayloadTooLarge: 413,
3397
+ UriTooLong: 414,
3398
+ UnsupportedMediaType: 415,
3399
+ RangeNotSatisfiable: 416,
3400
+ ExpectationFailed: 417,
3401
+ ImATeapot: 418,
3402
+ MisdirectedRequest: 421,
3403
+ UnprocessableEntity: 422,
3404
+ Locked: 423,
3405
+ FailedDependency: 424,
3406
+ TooEarly: 425,
3407
+ UpgradeRequired: 426,
3408
+ PreconditionRequired: 428,
3409
+ TooManyRequests: 429,
3410
+ RequestHeaderFieldsTooLarge: 431,
3411
+ UnavailableForLegalReasons: 451,
3412
+ InternalServerError: 500,
3413
+ NotImplemented: 501,
3414
+ BadGateway: 502,
3415
+ ServiceUnavailable: 503,
3416
+ GatewayTimeout: 504,
3417
+ HttpVersionNotSupported: 505,
3418
+ VariantAlsoNegotiates: 506,
3419
+ InsufficientStorage: 507,
3420
+ LoopDetected: 508,
3421
+ NotExtended: 510,
3422
+ NetworkAuthenticationRequired: 511,
3423
+ WebServerIsDown: 521,
3424
+ ConnectionTimedOut: 522,
3425
+ OriginIsUnreachable: 523,
3426
+ TimeoutOccurred: 524,
3427
+ SslHandshakeFailed: 525,
3428
+ InvalidSslCertificate: 526
3429
+ };
3430
+ Object.entries(HttpStatusCode).forEach(([key, value]) => {
3431
+ HttpStatusCode[value] = key;
3432
+ });
3433
+ var HttpStatusCode_default = HttpStatusCode;
3434
+
3435
+ // ../../node_modules/.pnpm/axios@1.13.0/node_modules/axios/lib/axios.js
3436
+ function createInstance(defaultConfig) {
3437
+ const context = new Axios_default(defaultConfig);
3438
+ const instance = bind(Axios_default.prototype.request, context);
3439
+ utils_default.extend(instance, Axios_default.prototype, context, { allOwnKeys: true });
3440
+ utils_default.extend(instance, context, null, { allOwnKeys: true });
3441
+ instance.create = function create(instanceConfig) {
3442
+ return createInstance(mergeConfig(defaultConfig, instanceConfig));
3443
+ };
3444
+ return instance;
3445
+ }
3446
+ var axios = createInstance(defaults_default);
3447
+ axios.Axios = Axios_default;
3448
+ axios.CanceledError = CanceledError_default;
3449
+ axios.CancelToken = CancelToken_default;
3450
+ axios.isCancel = isCancel;
3451
+ axios.VERSION = VERSION;
3452
+ axios.toFormData = toFormData_default;
3453
+ axios.AxiosError = AxiosError_default;
3454
+ axios.Cancel = axios.CanceledError;
3455
+ axios.all = function all(promises) {
3456
+ return Promise.all(promises);
3457
+ };
3458
+ axios.spread = spread;
3459
+ axios.isAxiosError = isAxiosError;
3460
+ axios.mergeConfig = mergeConfig;
3461
+ axios.AxiosHeaders = AxiosHeaders_default;
3462
+ axios.formToJSON = (thing) => formDataToJSON_default(utils_default.isHTMLForm(thing) ? new FormData(thing) : thing);
3463
+ axios.getAdapter = adapters_default.getAdapter;
3464
+ axios.HttpStatusCode = HttpStatusCode_default;
3465
+ axios.default = axios;
3466
+ var axios_default = axios;
3467
+
3468
+ // ../../node_modules/.pnpm/axios@1.13.0/node_modules/axios/index.js
3469
+ var {
3470
+ Axios: Axios2,
3471
+ AxiosError: AxiosError2,
3472
+ CanceledError: CanceledError2,
3473
+ isCancel: isCancel2,
3474
+ CancelToken: CancelToken2,
3475
+ VERSION: VERSION2,
3476
+ all: all2,
3477
+ Cancel,
3478
+ isAxiosError: isAxiosError2,
3479
+ spread: spread2,
3480
+ toFormData: toFormData2,
3481
+ AxiosHeaders: AxiosHeaders2,
3482
+ HttpStatusCode: HttpStatusCode2,
3483
+ formToJSON,
3484
+ getAdapter: getAdapter2,
3485
+ mergeConfig: mergeConfig2
3486
+ } = axios_default;
3487
+
3488
+ // src/v2/core/resources/apiClient.ts
3489
+ var ApiClient = class {
3490
+ // Max 30 requests per endpoint in window
3491
+ constructor(config) {
3492
+ this.currentToken = null;
3493
+ this.tokenProvider = null;
3494
+ // Circuit breaker state
3495
+ this.requestHistory = /* @__PURE__ */ new Map();
3496
+ this.WINDOW_MS = 5e3;
3497
+ // 5 seconds window
3498
+ this.MAX_REQUESTS = 30;
3499
+ this.axios = axios_default.create({
3500
+ baseURL: config.baseURL,
3501
+ timeout: config.timeout || 3e4,
3502
+ headers: __spreadValues({
3503
+ "Content-Type": "application/json"
3504
+ }, config.headers)
3505
+ });
3506
+ if (typeof setInterval !== "undefined") {
3507
+ setInterval(() => this.cleanupHistory(), 1e4);
3508
+ }
3509
+ this.axios.interceptors.request.use(
3510
+ async (config2) => {
3511
+ var _a, _b;
3512
+ if (config2.url) {
3513
+ try {
3514
+ this.checkRequestLimit("".concat((_a = config2.method) == null ? void 0 : _a.toUpperCase(), ":").concat(config2.url));
3515
+ } catch (error) {
3516
+ console.error("[SDK] \u{1F6D1} Request blocked by Circuit Breaker:", error);
3517
+ return Promise.reject(error);
3518
+ }
3519
+ }
3520
+ if (!config2.skipAuth && !this.currentToken && this.tokenProvider) {
3521
+ try {
3522
+ console.log("[SDK] Waiting for token...");
3523
+ const token = await this.tokenProvider();
3524
+ if (token) {
3525
+ this.updateToken(token);
3526
+ config2.headers["x-cms-token"] = token;
3527
+ }
3528
+ } catch (error) {
3529
+ console.error("[SDK] Failed to get token from provider:", error);
3530
+ }
3531
+ }
3532
+ if (!config2.skipAuth && this.currentToken) {
3533
+ config2.headers["x-cms-token"] = this.currentToken;
3534
+ }
3535
+ console.log("[SDK] Making ".concat((_b = config2.method) == null ? void 0 : _b.toUpperCase(), " request to: ").concat(config2.baseURL || "").concat(config2.url));
3536
+ return config2;
3537
+ },
3538
+ (error) => {
3539
+ console.error("[SDK] Request error:", error);
3540
+ return Promise.reject(error instanceof Error ? error : new Error(String(error)));
3541
+ }
3542
+ );
3543
+ this.axios.interceptors.response.use(
3544
+ (response) => {
3545
+ return response;
3546
+ },
3547
+ (error) => {
3548
+ console.error("[SDK] Response error:", error.message);
3549
+ return Promise.reject(error instanceof Error ? error : new Error(String(error)));
3550
+ }
3551
+ );
3552
+ }
3553
+ // Set a provider that returns a promise resolving to the token
3554
+ // This allows requests to wait until the token is ready
3555
+ setTokenProvider(provider) {
3556
+ this.tokenProvider = provider;
3557
+ }
3558
+ // Convenience methods
3559
+ async get(url, config) {
3560
+ const response = await this.axios.get(url, config);
3561
+ return response.data;
3562
+ }
3563
+ async post(url, data, config) {
3564
+ const response = await this.axios.post(url, data, config);
3565
+ return response.data;
3566
+ }
3567
+ async put(url, data, config) {
3568
+ const response = await this.axios.put(url, data, config);
3569
+ return response.data;
3570
+ }
3571
+ async patch(url, data, config) {
3572
+ const response = await this.axios.patch(url, data, config);
3573
+ return response.data;
3574
+ }
3575
+ async delete(url, config) {
3576
+ const response = await this.axios.delete(url, config);
3577
+ return response.data;
3578
+ }
3579
+ // Update headers (useful for auth tokens)
3580
+ setHeader(key, value) {
3581
+ this.axios.defaults.headers.common[key] = value;
3582
+ }
3583
+ removeHeader(key) {
3584
+ delete this.axios.defaults.headers.common[key];
3585
+ }
3586
+ // Token management methods (matching old ApiService pattern)
3587
+ updateToken(token) {
3588
+ this.currentToken = token;
3589
+ if (token) {
3590
+ this.setHeader("x-cms-token", token);
3591
+ } else {
3592
+ this.removeHeader("x-cms-token");
3593
+ console.log("[SDK] Token removed from ApiClient");
3594
+ }
3595
+ }
3596
+ getCurrentToken() {
3597
+ return this.currentToken;
3598
+ }
3599
+ // Update configuration (useful for environment changes)
3600
+ updateConfig(config) {
3601
+ if (config.baseURL) {
3602
+ this.axios.defaults.baseURL = config.baseURL;
3603
+ }
3604
+ if (config.timeout) {
3605
+ this.axios.defaults.timeout = config.timeout;
3606
+ }
3607
+ if (config.headers) {
3608
+ Object.assign(this.axios.defaults.headers.common, config.headers);
3609
+ }
3610
+ console.log("[SDK] ApiClient configuration updated");
3611
+ }
3612
+ // Circuit Breaker Implementation
3613
+ checkRequestLimit(key) {
3614
+ const now = Date.now();
3615
+ const history = this.requestHistory.get(key);
3616
+ if (!history) {
3617
+ this.requestHistory.set(key, { count: 1, firstRequestTime: now });
3618
+ return;
3619
+ }
3620
+ if (now - history.firstRequestTime > this.WINDOW_MS) {
3621
+ this.requestHistory.set(key, { count: 1, firstRequestTime: now });
3622
+ return;
3623
+ }
3624
+ history.count++;
3625
+ if (history.count > this.MAX_REQUESTS) {
3626
+ const error = new Error("Circuit Breaker: Too many requests to ".concat(key, " (").concat(history.count, " in ").concat(this.WINDOW_MS, "ms)"));
3627
+ error.isCircuitBreaker = true;
3628
+ throw error;
3629
+ }
3630
+ }
3631
+ cleanupHistory() {
3632
+ const now = Date.now();
3633
+ for (const [key, history] of this.requestHistory.entries()) {
3634
+ if (now - history.firstRequestTime > this.WINDOW_MS) {
3635
+ this.requestHistory.delete(key);
3636
+ }
3637
+ }
3638
+ }
3639
+ };
3640
+
3641
+ // src/v2/core/utils/deviceInfo.ts
3642
+ function getBrowserInfo() {
3643
+ const userAgent = navigator.userAgent;
3644
+ if (userAgent.includes("Chrome")) {
3645
+ const match = /Chrome\/(\d+)/.exec(userAgent);
3646
+ return { name: "Chrome", version: match ? match[1] : "unknown" };
3647
+ }
3648
+ if (userAgent.includes("Firefox")) {
3649
+ const match = /Firefox\/(\d+)/.exec(userAgent);
3650
+ return { name: "Firefox", version: match ? match[1] : "unknown" };
3651
+ }
3652
+ if (userAgent.includes("Safari") && !userAgent.includes("Chrome")) {
3653
+ const match = /Version\/(\d+)/.exec(userAgent);
3654
+ return { name: "Safari", version: match ? match[1] : "unknown" };
3655
+ }
3656
+ if (userAgent.includes("Edge")) {
3657
+ const match = /Edge\/(\d+)/.exec(userAgent);
3658
+ return { name: "Edge", version: match ? match[1] : "unknown" };
3659
+ }
3660
+ return { name: "unknown", version: "unknown" };
3661
+ }
3662
+ function getOSInfo() {
3663
+ const userAgent = navigator.userAgent;
3664
+ if (userAgent.includes("Windows")) {
3665
+ if (userAgent.includes("Windows NT 10.0")) return { name: "Windows", version: "10" };
3666
+ if (userAgent.includes("Windows NT 6.3")) return { name: "Windows", version: "8.1" };
3667
+ if (userAgent.includes("Windows NT 6.2")) return { name: "Windows", version: "8" };
3668
+ if (userAgent.includes("Windows NT 6.1")) return { name: "Windows", version: "7" };
3669
+ return { name: "Windows", version: "unknown" };
3670
+ }
3671
+ if (userAgent.includes("Mac OS X")) {
3672
+ const match = /Mac OS X (\d+[._]\d+)/.exec(userAgent);
3673
+ return { name: "macOS", version: match ? match[1].replace("_", ".") : "unknown" };
3674
+ }
3675
+ if (userAgent.includes("iPhone") || userAgent.includes("iPad")) {
3676
+ const match = /OS (\d+[._]\d+)/.exec(userAgent);
3677
+ return { name: "iOS", version: match ? match[1].replace("_", ".") : "unknown" };
3678
+ }
3679
+ if (userAgent.includes("Android")) {
3680
+ const match = /Android (\d+[.\d]*)/.exec(userAgent);
3681
+ return { name: "Android", version: match ? match[1] : "unknown" };
3682
+ }
3683
+ if (userAgent.includes("Linux")) {
3684
+ return { name: "Linux", version: "unknown" };
3685
+ }
3686
+ return { name: "unknown", version: "unknown" };
3687
+ }
3688
+ function getDeviceInfo() {
3689
+ const userAgent = navigator.userAgent;
3690
+ if (userAgent.includes("iPhone")) {
3691
+ return { type: "mobile", model: "iPhone" };
3692
+ }
3693
+ if (userAgent.includes("iPad")) {
3694
+ return { type: "tablet", model: "iPad" };
3695
+ }
3696
+ if (userAgent.includes("Android")) {
3697
+ if (userAgent.includes("Mobile")) {
3698
+ return { type: "mobile", model: "Android" };
3699
+ } else {
3700
+ return { type: "tablet", model: "Android" };
3701
+ }
3702
+ }
3703
+ return void 0;
3704
+ }
3705
+ function getScreenResolution() {
3706
+ return {
3707
+ width: window.screen.width,
3708
+ height: window.screen.height
3709
+ };
3710
+ }
3711
+ function getTimeZone() {
3712
+ try {
3713
+ return Intl.DateTimeFormat().resolvedOptions().timeZone;
3714
+ } catch (error) {
3715
+ console.error("Failed to get timezone:", error);
3716
+ return "UTC";
3717
+ }
3718
+ }
3719
+ function getBrowserLocale() {
3720
+ try {
3721
+ return navigator.language || "en-US";
3722
+ } catch (error) {
3723
+ console.error("Failed to get browser locale:", error);
3724
+ return "en-US";
3725
+ }
3726
+ }
3727
+ function collectDeviceInfo() {
3728
+ if (typeof window === "undefined") {
3729
+ return {
3730
+ userAgent: {
3731
+ browser: { name: "unknown", version: "unknown" },
3732
+ os: { name: "unknown", version: "unknown" }
3733
+ },
3734
+ screenResolution: { width: 0, height: 0 },
3735
+ timeZone: "UTC"
3736
+ };
3737
+ }
3738
+ return {
3739
+ userAgent: {
3740
+ browser: getBrowserInfo(),
3741
+ os: getOSInfo(),
3742
+ device: getDeviceInfo()
3743
+ },
3744
+ screenResolution: getScreenResolution(),
3745
+ timeZone: getTimeZone()
3746
+ };
3747
+ }
3748
+ function getUrlParams() {
3749
+ if (typeof window === "undefined") {
3750
+ return {};
3751
+ }
3752
+ const params = new URLSearchParams(window.location.search);
3753
+ return {
3754
+ locale: params.get("locale") || void 0,
3755
+ currency: params.get("currency") || void 0,
3756
+ utmSource: params.get("utm_source") || void 0,
3757
+ utmMedium: params.get("utm_medium") || void 0,
3758
+ utmCampaign: params.get("utm_campaign") || void 0
3759
+ };
3760
+ }
3761
+
3762
+ // src/v2/core/utils/eventBus.ts
3763
+ var EventBus = class {
3764
+ constructor() {
3765
+ this.listeners = /* @__PURE__ */ new Map();
3766
+ }
3767
+ on(event, callback) {
3768
+ if (!this.listeners.has(event)) {
3769
+ this.listeners.set(event, /* @__PURE__ */ new Set());
3770
+ }
3771
+ this.listeners.get(event).add(callback);
3772
+ return () => this.off(event, callback);
3773
+ }
3774
+ off(event, callback) {
3775
+ if (this.listeners.has(event)) {
3776
+ this.listeners.get(event).delete(callback);
3777
+ }
3778
+ }
3779
+ async emit(event, data) {
3780
+ if (this.listeners.has(event)) {
3781
+ const callbacks = Array.from(this.listeners.get(event));
3782
+ await Promise.all(callbacks.map((cb) => {
3783
+ try {
3784
+ return Promise.resolve(cb(data));
3785
+ } catch (e) {
3786
+ console.error('[EventBus] Error in listener for event "'.concat(event, '":'), e);
3787
+ return Promise.resolve();
3788
+ }
3789
+ }));
3790
+ }
3791
+ }
3792
+ clear() {
3793
+ this.listeners.clear();
3794
+ }
3795
+ };
3796
+
3797
+ // src/v2/core/utils/jwtDecoder.ts
3798
+ function decodeJWTClient(token) {
3799
+ try {
3800
+ const parts = token.split(".");
3801
+ if (parts.length !== 3) {
3802
+ console.error("Invalid JWT token format");
3803
+ return null;
3804
+ }
3805
+ const payload = parts[1];
3806
+ const paddedPayload = payload + "=".repeat((4 - payload.length % 4) % 4);
3807
+ const decoded = atob(paddedPayload);
3808
+ const parsedPayload = JSON.parse(decoded);
3809
+ if (parsedPayload.exp && Date.now() >= parsedPayload.exp * 1e3) {
3810
+ console.warn("JWT token is expired");
3811
+ return null;
3812
+ }
3813
+ return {
3814
+ sessionId: parsedPayload.sessionId,
3815
+ storeId: parsedPayload.storeId,
3816
+ accountId: parsedPayload.accountId,
3817
+ customerId: parsedPayload.customerId,
3818
+ role: parsedPayload.role,
3819
+ isValid: true,
3820
+ isLoading: false
3821
+ };
3822
+ } catch (error) {
3823
+ console.error("Failed to decode JWT token:", error);
3824
+ return null;
3825
+ }
3826
+ }
3827
+ function isTokenExpired(token) {
3828
+ try {
3829
+ const parts = token.split(".");
3830
+ if (parts.length !== 3) return true;
3831
+ const payload = parts[1];
3832
+ const paddedPayload = payload + "=".repeat((4 - payload.length % 4) % 4);
3833
+ const decoded = atob(paddedPayload);
3834
+ const parsedPayload = JSON.parse(decoded);
3835
+ if (parsedPayload.exp) {
3836
+ return Date.now() >= parsedPayload.exp * 1e3;
3837
+ }
3838
+ return false;
3839
+ } catch (error) {
3840
+ console.error("Failed to check token expiration:", error);
3841
+ return true;
3842
+ }
3843
+ }
3844
+
3845
+ // src/v2/core/utils/env.ts
3846
+ var import_meta = {};
3847
+ var DEFAULT_PREFIXES = ["", "VITE_", "REACT_APP_", "NEXT_PUBLIC_"];
3848
+ function resolveEnvValue(key, prefixes = DEFAULT_PREFIXES) {
3849
+ var _a, _b, _c;
3850
+ for (const prefix of prefixes) {
3851
+ const envKey = prefix ? "".concat(prefix).concat(key) : key;
3852
+ if (typeof process !== "undefined" && ((_a = process == null ? void 0 : process.env) == null ? void 0 : _a[envKey])) {
3853
+ console.log("process.env[".concat(envKey, "]"), process.env[envKey]);
3854
+ return process.env[envKey];
3855
+ }
3856
+ if (typeof import_meta !== "undefined" && ((_b = import_meta == null ? void 0 : import_meta.env) == null ? void 0 : _b[envKey])) {
3857
+ console.log("import.meta.env[".concat(envKey, "]"), import_meta.env[envKey]);
3858
+ return import_meta.env[envKey];
3859
+ }
3860
+ if (typeof window !== "undefined" && ((_c = window == null ? void 0 : window.__TAGADA_ENV__) == null ? void 0 : _c[envKey])) {
3861
+ console.log("window.__TAGADA_ENV__[".concat(envKey, "]"), window.__TAGADA_ENV__[envKey]);
3862
+ return window.__TAGADA_ENV__[envKey];
3863
+ }
3864
+ }
3865
+ return void 0;
3866
+ }
3867
+
3868
+ // src/v2/core/utils/pluginConfig.ts
3869
+ var loadLocalDevConfig = async (configVariant = "default") => {
3870
+ try {
3871
+ const env = resolveEnvValue("TAGADA_ENV") || resolveEnvValue("TAGADA_ENVIRONMENT");
3872
+ if (env === "production") {
3873
+ return null;
3874
+ }
3875
+ if (!isLocalEnvironment(true)) {
3876
+ return null;
3877
+ }
3878
+ const localResponse = await fetch("/.local.json");
3879
+ if (!localResponse.ok) {
3880
+ return null;
3881
+ }
3882
+ const localConfig = await localResponse.json();
3883
+ let config = {};
3884
+ let configLoaded = false;
3885
+ try {
3886
+ let deploymentResponse = await fetch("/config/".concat(configVariant, ".tgd.json"));
3887
+ if (!deploymentResponse.ok) {
3888
+ deploymentResponse = await fetch("/config/".concat(configVariant, ".json"));
3889
+ }
3890
+ if (deploymentResponse.ok) {
3891
+ config = await deploymentResponse.json();
3892
+ configLoaded = true;
3893
+ }
3894
+ } catch (e) {
3895
+ }
3896
+ if (!configLoaded && configVariant !== "default") {
3897
+ console.warn("\u26A0\uFE0F Config variant '".concat(configVariant, "' not found, falling back to 'default'"));
3898
+ try {
3899
+ let defaultResponse = await fetch("/config/default.tgd.json");
3900
+ if (!defaultResponse.ok) {
3901
+ defaultResponse = await fetch("/config/default.json");
3902
+ }
3903
+ if (defaultResponse.ok) {
3904
+ config = await defaultResponse.json();
3905
+ configLoaded = true;
3906
+ console.log("\u2705 Fallback to 'default' config successful");
3907
+ }
3908
+ } catch (e) {
3909
+ }
3910
+ }
3911
+ if (!configLoaded) {
3912
+ if (configVariant === "default") {
3913
+ console.warn("\u26A0\uFE0F No 'default' config found. Create /config/default.tgd.json");
3914
+ } else {
3915
+ console.warn("\u26A0\uFE0F Neither '".concat(configVariant, "' nor 'default' config found. Create /config/default.tgd.json"));
3916
+ }
3917
+ }
3918
+ const result = {
3919
+ storeId: localConfig.storeId,
3920
+ accountId: localConfig.accountId,
3921
+ basePath: localConfig.basePath,
3922
+ config
3923
+ };
3924
+ console.log("\u{1F6E0}\uFE0F Using local development plugin config:", result);
3925
+ return result;
3926
+ } catch (e) {
3927
+ return null;
3928
+ }
3929
+ };
3930
+ var loadStaticResources = async () => {
3931
+ try {
3932
+ const env = resolveEnvValue("TAGADA_ENV") || resolveEnvValue("TAGADA_ENVIRONMENT");
3933
+ if (env === "production") {
3934
+ return null;
3935
+ }
3936
+ if (!isLocalEnvironment(true)) {
3937
+ return null;
3938
+ }
3939
+ console.log("\u{1F6E0}\uFE0F [V2] Attempting to load /config/resources.static.json...");
3940
+ const response = await fetch("/config/resources.static.json");
3941
+ if (!response.ok) {
3942
+ console.log("\u{1F6E0}\uFE0F [V2] resources.static.json not found or failed to load");
3943
+ return null;
3944
+ }
3945
+ const staticResources = await response.json();
3946
+ console.log("\u{1F6E0}\uFE0F [V2] \u2705 Loaded local static resources:", staticResources);
3947
+ return staticResources;
3948
+ } catch (error) {
3949
+ console.error("\u{1F6E0}\uFE0F [V2] \u274C Error loading static resources:", error);
3950
+ return null;
3951
+ }
3952
+ };
3953
+ var getMetaContent = (name) => {
3954
+ const metaTag = document.querySelector('meta[name="'.concat(name, '"]'));
3955
+ return (metaTag == null ? void 0 : metaTag.getAttribute("content")) || void 0;
3956
+ };
3957
+ var loadProductionConfig = async () => {
3958
+ try {
3959
+ if (typeof document === "undefined") {
3960
+ return null;
3961
+ }
3962
+ const storeId = getMetaContent("x-plugin-store-id");
3963
+ const accountId = getMetaContent("x-plugin-account-id");
3964
+ if (!storeId) {
3965
+ return null;
3966
+ }
3967
+ const basePath = getMetaContent("x-plugin-base-path") || "/";
3968
+ let config = {};
3969
+ try {
3970
+ const encodedConfig = getMetaContent("x-plugin-config");
3971
+ if (encodedConfig) {
3972
+ const decodedConfig = decodeURIComponent(encodedConfig);
3973
+ config = JSON.parse(decodedConfig);
3974
+ }
3975
+ } catch (error) {
3976
+ console.warn("\u26A0\uFE0F Failed to parse plugin config from meta tag:", error);
3977
+ }
3978
+ if (!accountId) {
3979
+ console.warn("\u26A0\uFE0F Plugin config: Account ID not found in meta tags");
3980
+ }
3981
+ const result = { storeId, accountId, basePath, config };
3982
+ console.log("\u{1F680} [HIGHEST PRIORITY] Plugin config loaded from meta tags (runtime injected config):", {
3983
+ storeId,
3984
+ accountId,
3985
+ basePath,
3986
+ configKeys: Object.keys(config),
3987
+ configSize: JSON.stringify(config).length
3988
+ });
3989
+ return result;
3990
+ } catch (error) {
3991
+ console.warn("\u26A0\uFE0F Error loading production config from meta tags:", error);
3992
+ return null;
3993
+ }
3994
+ };
3995
+ var loadPluginConfig = async (configVariant = "default", rawConfig) => {
3996
+ var _a, _b;
3997
+ console.log("\u{1F527} [V2] loadPluginConfig called with variant:", configVariant);
3998
+ const staticResources = await loadStaticResources();
3999
+ const productionConfig = await loadProductionConfig();
4000
+ if (productionConfig) {
4001
+ const result = __spreadProps(__spreadValues({}, productionConfig), {
4002
+ staticResources: staticResources != null ? staticResources : void 0
4003
+ });
4004
+ console.log("\u2705 [V2] Using INJECTED config from meta tags (HIGHEST PRIORITY)");
4005
+ return result;
4006
+ }
4007
+ if (rawConfig) {
4008
+ const result = {
4009
+ storeId: rawConfig.storeId,
4010
+ accountId: rawConfig.accountId,
4011
+ basePath: (_a = rawConfig.basePath) != null ? _a : "/",
4012
+ config: (_b = rawConfig.config) != null ? _b : {},
4013
+ staticResources: staticResources != null ? staticResources : void 0
4014
+ };
4015
+ console.log("\u2705 [V2] Using raw config parameter (PRIORITY 2)");
4016
+ return result;
4017
+ }
4018
+ const envConfig = await createRawPluginConfig();
4019
+ if (envConfig) {
4020
+ const result = __spreadProps(__spreadValues({}, envConfig), {
4021
+ staticResources: staticResources != null ? staticResources : void 0
4022
+ });
4023
+ console.log("\u2705 [V2] Using environment variables config (PRIORITY 3 - build time)");
4024
+ return result;
4025
+ }
4026
+ const localConfig = await loadLocalDevConfig(configVariant);
4027
+ if (localConfig) {
4028
+ const result = __spreadProps(__spreadValues({}, localConfig), {
4029
+ staticResources: staticResources != null ? staticResources : void 0
4030
+ });
4031
+ console.log("\u2705 [V2] Using local dev config files (PRIORITY 4)");
4032
+ return result;
4033
+ }
4034
+ console.warn("\u26A0\uFE0F [V2] No plugin config found - using defaults");
4035
+ return {
4036
+ basePath: "/",
4037
+ config: {},
4038
+ staticResources: staticResources != null ? staticResources : void 0
4039
+ };
4040
+ };
4041
+ async function loadLocalConfig(configName = "default", defaultConfig) {
4042
+ try {
4043
+ if (!isLocalEnvironment()) {
4044
+ return null;
4045
+ }
4046
+ if (defaultConfig) {
4047
+ return defaultConfig;
4048
+ }
4049
+ const possiblePaths = [
4050
+ "/config/".concat(configName, ".config.json"),
4051
+ "/config/".concat(configName, ".tgd.json"),
4052
+ "/config/".concat(configName, ".json")
4053
+ ];
4054
+ for (const path of possiblePaths) {
4055
+ try {
4056
+ const response = await fetch(path);
4057
+ if (response.ok) {
4058
+ const config = await response.json();
4059
+ return config;
4060
+ }
4061
+ } catch (e) {
4062
+ continue;
4063
+ }
4064
+ }
4065
+ console.warn("\u26A0\uFE0F [loadLocalConfig] No config found for '".concat(configName, "'"));
4066
+ return null;
4067
+ } catch (error) {
4068
+ console.error("[loadLocalConfig] Error loading config:", error);
4069
+ return null;
4070
+ }
4071
+ }
4072
+ async function createRawPluginConfig() {
4073
+ try {
4074
+ if (!isLocalEnvironment()) {
4075
+ return void 0;
4076
+ }
4077
+ const storeId = resolveEnvValue("TAGADA_STORE_ID");
4078
+ const accountId = resolveEnvValue("TAGADA_ACCOUNT_ID");
4079
+ const basePath = resolveEnvValue("TAGADA_BASE_PATH");
4080
+ const configName = resolveEnvValue("TAGADA_CONFIG_NAME");
4081
+ if (!storeId || !accountId) {
4082
+ return void 0;
4083
+ }
4084
+ const resolvedConfig = await loadLocalConfig(configName);
4085
+ if (!resolvedConfig) {
4086
+ return void 0;
4087
+ }
4088
+ const rawConfig = {
4089
+ storeId,
4090
+ accountId,
4091
+ basePath: basePath || "/",
4092
+ config: resolvedConfig
4093
+ };
4094
+ console.log("\u{1F6E0}\uFE0F [createRawPluginConfig] Using environment variables (build-time config):", {
4095
+ hasStoreId: !!rawConfig.storeId,
4096
+ hasAccountId: !!rawConfig.accountId,
4097
+ basePath: rawConfig.basePath,
4098
+ hasConfig: !!rawConfig.config
4099
+ });
4100
+ return rawConfig;
4101
+ } catch (error) {
4102
+ console.error("[createRawPluginConfig] Error creating config:", error);
4103
+ return void 0;
4104
+ }
4105
+ }
4106
+
4107
+ // src/v2/core/client.ts
4108
+ var TagadaClient = class {
4109
+ constructor(config = {}) {
4110
+ /**
4111
+ * Event bus for domain events and coordination
4112
+ */
4113
+ this.bus = new EventBus();
4114
+ this.eventDispatcher = new EventDispatcher();
4115
+ this.tokenPromise = null;
4116
+ this.tokenResolver = null;
4117
+ // Track initialization state to prevent infinite loops
4118
+ this.isInitializingSession = false;
4119
+ this.lastSessionInitError = null;
4120
+ this.sessionInitRetryCount = 0;
4121
+ this.MAX_SESSION_INIT_RETRIES = 3;
4122
+ var _a, _b;
4123
+ this.config = config;
4124
+ this.instanceId = Math.random().toString(36).substr(2, 9);
4125
+ this.boundHandleStorageChange = this.handleStorageChange.bind(this);
4126
+ if (this.config.debugMode) {
4127
+ console.log("[TagadaClient ".concat(this.instanceId, "] Initializing..."));
4128
+ }
4129
+ const previewModeActive = handlePreviewMode(this.config.debugMode);
4130
+ if (previewModeActive && this.config.debugMode) {
4131
+ console.log("[TagadaClient ".concat(this.instanceId, "] Preview mode active - state cleared"));
4132
+ }
4133
+ const env = this.resolveEnvironment();
4134
+ let envConfig = getEnvironmentConfig(env);
4135
+ if (config.customApiConfig) {
4136
+ envConfig = __spreadProps(__spreadValues(__spreadValues({}, envConfig), config.customApiConfig), {
4137
+ apiConfig: __spreadValues(__spreadValues({}, envConfig.apiConfig), config.customApiConfig.apiConfig)
4138
+ });
4139
+ if (this.config.debugMode) {
4140
+ console.log("[TagadaClient ".concat(this.instanceId, "] Applied custom API config:"), envConfig.apiConfig.baseUrl);
4141
+ }
4142
+ }
4143
+ this.state = {
4144
+ auth: {
4145
+ isAuthenticated: false,
4146
+ isLoading: false,
4147
+ customer: null,
4148
+ session: null
4149
+ },
4150
+ session: null,
4151
+ customer: null,
4152
+ locale: {
4153
+ locale: "en-US",
4154
+ language: "en",
4155
+ region: "US",
4156
+ messages: {}
4157
+ },
4158
+ currency: {
4159
+ code: "USD",
4160
+ symbol: "$",
4161
+ name: "US Dollar"
4162
+ },
4163
+ store: null,
4164
+ environment: envConfig,
4165
+ isLoading: true,
4166
+ isInitialized: false,
4167
+ isSessionInitialized: false,
4168
+ pluginConfig: { basePath: "/", config: {} },
4169
+ pluginConfigLoading: !config.rawPluginConfig,
4170
+ debugMode: (_a = config.debugMode) != null ? _a : env !== "production",
4171
+ token: null
4172
+ };
4173
+ this.apiClient = new ApiClient({
4174
+ baseURL: envConfig.apiConfig.baseUrl
4175
+ });
4176
+ const funnelFeature = (_b = config.features) == null ? void 0 : _b.funnel;
4177
+ const funnelEnabled = funnelFeature !== false;
4178
+ if (funnelEnabled) {
4179
+ const funnelConfig = typeof funnelFeature === "object" ? funnelFeature : {};
4180
+ this.funnel = new FunnelClient({
4181
+ apiClient: this.apiClient,
4182
+ debugMode: this.state.debugMode,
4183
+ pluginConfig: this.state.pluginConfig,
4184
+ environment: this.state.environment,
4185
+ autoRedirect: funnelConfig.autoRedirect
4186
+ });
4187
+ }
4188
+ this.apiClient.setTokenProvider(this.waitForToken.bind(this));
4189
+ if (typeof window !== "undefined") {
4190
+ window.addEventListener("storage", this.boundHandleStorageChange);
4191
+ }
4192
+ this.setupConfigHotReload();
4193
+ this.initialize();
4194
+ }
4195
+ /**
4196
+ * Cleanup client resources
4197
+ */
4198
+ destroy() {
4199
+ if (typeof window !== "undefined") {
4200
+ window.removeEventListener("storage", this.boundHandleStorageChange);
4201
+ }
4202
+ if (this.state.debugMode) {
4203
+ console.log("[TagadaClient ".concat(this.instanceId, "] Destroyed"));
4204
+ }
4205
+ this.eventDispatcher.clear();
4206
+ this.bus.clear();
4207
+ }
4208
+ /**
4209
+ * Handle storage changes (e.g. token update in another tab)
4210
+ */
4211
+ handleStorageChange() {
4212
+ const storedToken = getClientToken();
4213
+ if (storedToken === this.state.token) {
4214
+ if (this.state.debugMode) {
4215
+ console.log("[TagadaClient ".concat(this.instanceId, "] Token unchanged (ignoring event)"));
4216
+ }
4217
+ return;
4218
+ }
4219
+ if (this.isInitializingSession) {
4220
+ if (this.state.debugMode) {
4221
+ console.log("[TagadaClient ".concat(this.instanceId, "] Session initialization in progress, skipping storage change"));
4222
+ }
4223
+ return;
4224
+ }
4225
+ if (this.sessionInitRetryCount >= this.MAX_SESSION_INIT_RETRIES && this.lastSessionInitError) {
4226
+ if (this.state.debugMode) {
4227
+ console.error("[TagadaClient ".concat(this.instanceId, "] Max session init retries reached, giving up"), this.lastSessionInitError);
4228
+ }
4229
+ return;
4230
+ }
4231
+ if (this.state.debugMode) {
4232
+ console.log("[TagadaClient ".concat(this.instanceId, "] Storage changed, re-initializing token..."));
4233
+ }
4234
+ this.initializeToken();
4235
+ }
4236
+ /**
4237
+ * Subscribe to state changes
4238
+ */
4239
+ subscribe(listener) {
4240
+ return this.eventDispatcher.subscribe(listener);
4241
+ }
4242
+ /**
4243
+ * Get current state
4244
+ */
4245
+ getState() {
4246
+ return this.state;
4247
+ }
4248
+ /**
4249
+ * Update state and notify listeners
4250
+ */
4251
+ updateState(updates) {
4252
+ this.state = __spreadValues(__spreadValues({}, this.state), updates);
4253
+ this.eventDispatcher.notify(this.state);
4254
+ }
4255
+ /**
4256
+ * Resolve environment
4257
+ */
4258
+ resolveEnvironment() {
4259
+ if (this.config.environment) return this.config.environment;
4260
+ return detectEnvironment();
4261
+ }
4262
+ /**
4263
+ * Main initialization flow
4264
+ */
4265
+ async initialize() {
4266
+ try {
4267
+ await this.initializePluginConfig();
4268
+ if (this.state.pluginConfig.storeId) {
4269
+ await this.initializeToken();
4270
+ } else {
4271
+ console.warn("[TagadaClient] No store ID found in plugin config. Skipping token initialization.");
4272
+ this.updateState({ isLoading: false, isInitialized: true });
4273
+ }
4274
+ } catch (error) {
4275
+ console.error("[TagadaClient] Initialization failed:", error);
4276
+ this.updateState({ isLoading: false, isInitialized: true });
4277
+ }
4278
+ }
4279
+ /**
4280
+ * Load plugin configuration
4281
+ */
4282
+ async initializePluginConfig() {
4283
+ if (!this.state.pluginConfigLoading) return;
4284
+ try {
4285
+ const configVariant = this.config.localConfig || "default";
4286
+ const config = await loadPluginConfig(configVariant, this.config.rawPluginConfig);
4287
+ this.updateState({
4288
+ pluginConfig: config,
4289
+ pluginConfigLoading: false
4290
+ });
4291
+ if (this.funnel) {
4292
+ this.funnel.setConfig({
4293
+ pluginConfig: config,
4294
+ environment: this.state.environment
4295
+ });
4296
+ }
4297
+ if (this.state.debugMode) {
4298
+ console.log("[TagadaClient] Plugin config loaded:", config);
4299
+ }
4300
+ } catch (error) {
4301
+ console.error("[TagadaClient] Failed to load plugin config:", error);
4302
+ this.updateState({
4303
+ pluginConfig: { basePath: "/", config: {} },
4304
+ pluginConfigLoading: false
4305
+ });
4306
+ }
4307
+ }
4308
+ /**
4309
+ * Initialize token and session
4310
+ */
4311
+ async initializeToken() {
4312
+ const existingToken = getClientToken();
4313
+ const urlParams = new URLSearchParams(typeof window !== "undefined" ? window.location.search : "");
4314
+ const queryToken = urlParams.get("token");
4315
+ if (this.state.debugMode) {
4316
+ console.log("[TagadaClient ".concat(this.instanceId, "] Initializing token..."), {
4317
+ hasExistingToken: !!existingToken,
4318
+ hasQueryToken: !!queryToken
4319
+ });
4320
+ }
4321
+ let tokenToUse = null;
4322
+ let shouldPersist = false;
4323
+ if (queryToken) {
4324
+ tokenToUse = queryToken;
4325
+ shouldPersist = true;
4326
+ } else if (existingToken && !isTokenExpired(existingToken)) {
4327
+ tokenToUse = existingToken;
4328
+ }
4329
+ if (tokenToUse) {
4330
+ this.setToken(tokenToUse);
4331
+ if (shouldPersist) {
4332
+ if (this.state.debugMode) {
4333
+ console.log("[TagadaClient ".concat(this.instanceId, "] Persisting query token to storage..."));
4334
+ }
4335
+ setClientToken(tokenToUse);
4336
+ }
4337
+ const decodedSession = decodeJWTClient(tokenToUse);
4338
+ if (decodedSession) {
4339
+ this.updateState({ session: decodedSession });
4340
+ await this.initializeSession(decodedSession);
4341
+ } else {
4342
+ console.error("[TagadaClient] Failed to decode token");
4343
+ this.updateState({ isInitialized: true, isLoading: false });
4344
+ }
4345
+ } else {
4346
+ const storeId = this.state.pluginConfig.storeId;
4347
+ if (storeId) {
4348
+ if (this.state.debugMode) {
4349
+ console.log("[TagadaClient ".concat(this.instanceId, "] Creating anonymous token for store:"), storeId);
4350
+ }
4351
+ await this.createAnonymousToken(storeId);
4352
+ } else {
4353
+ this.updateState({ isInitialized: true, isLoading: false });
4354
+ }
4355
+ }
4356
+ }
4357
+ /**
4358
+ * Set token and resolve waiting requests
4359
+ */
4360
+ setToken(token) {
4361
+ this.apiClient.updateToken(token);
4362
+ this.updateState({ token });
4363
+ if (this.tokenResolver) {
4364
+ this.tokenResolver(token);
4365
+ this.tokenPromise = null;
4366
+ this.tokenResolver = null;
4367
+ } else {
4368
+ }
4369
+ }
4370
+ /**
4371
+ * Wait for token to be available
4372
+ */
4373
+ waitForToken() {
4374
+ if (this.apiClient.getCurrentToken()) {
4375
+ return Promise.resolve(this.apiClient.getCurrentToken());
4376
+ }
4377
+ if (!this.tokenPromise) {
4378
+ this.tokenPromise = new Promise((resolve) => {
4379
+ this.tokenResolver = resolve;
4380
+ });
4381
+ }
4382
+ return this.tokenPromise;
4383
+ }
4384
+ /**
4385
+ * Create anonymous token
4386
+ */
4387
+ async createAnonymousToken(storeId) {
4388
+ if (this.isInitializingSession) {
4389
+ if (this.state.debugMode) {
4390
+ console.log("[TagadaClient ".concat(this.instanceId, "] Session initialization in progress, skipping anonymous token creation"));
4391
+ }
4392
+ return;
4393
+ }
4394
+ try {
4395
+ const draft = isDraftMode();
4396
+ if (this.state.debugMode) {
4397
+ console.log("[TagadaClient] Creating anonymous token for store:", storeId, { draft });
4398
+ }
4399
+ const response = await this.apiClient.post(
4400
+ "/api/v1/cms/session/anonymous",
4401
+ {
4402
+ storeId,
4403
+ role: "anonymous",
4404
+ draft
4405
+ // 🎯 Pass draft mode to anonymous login
4406
+ },
4407
+ { skipAuth: true }
4408
+ );
4409
+ this.setToken(response.token);
4410
+ setClientToken(response.token);
4411
+ const decodedSession = decodeJWTClient(response.token);
4412
+ if (decodedSession) {
4413
+ this.updateState({ session: decodedSession });
4414
+ await this.initializeSession(decodedSession);
4415
+ }
4416
+ this.updateState({ isSessionInitialized: true });
4417
+ } catch (error) {
4418
+ console.error("[TagadaClient] Failed to create anonymous token:", error);
4419
+ this.updateState({ isInitialized: true, isLoading: false });
4420
+ }
4421
+ }
4422
+ /**
4423
+ * Initialize session
4424
+ */
4425
+ async initializeSession(sessionData) {
4426
+ var _a, _b;
4427
+ if (this.isInitializingSession) {
4428
+ if (this.state.debugMode) {
4429
+ console.log("[TagadaClient ".concat(this.instanceId, "] Session initialization already in progress, skipping"));
4430
+ }
4431
+ return;
4432
+ }
4433
+ this.isInitializingSession = true;
4434
+ try {
4435
+ if (this.state.debugMode) {
4436
+ console.log("[TagadaClient ".concat(this.instanceId, "] Initializing session..."), { sessionId: sessionData.sessionId });
4437
+ }
4438
+ const deviceInfo = collectDeviceInfo();
4439
+ const urlParams = getUrlParams();
4440
+ const browserLocale = getBrowserLocale();
4441
+ const draft = isDraftMode();
4442
+ const draftParam = new URLSearchParams(window.location.search).get("draft");
4443
+ if (draftParam !== null) {
4444
+ setDraftMode(draftParam === "true");
4445
+ }
4446
+ const sessionInitData = {
4447
+ storeId: sessionData.storeId,
4448
+ accountId: sessionData.accountId,
4449
+ customerId: sessionData.customerId,
4450
+ role: sessionData.role,
4451
+ browserLocale,
4452
+ queryLocale: urlParams.locale,
4453
+ queryCurrency: urlParams.currency,
4454
+ utmSource: urlParams.utmSource,
4455
+ utmMedium: urlParams.utmMedium,
4456
+ utmCampaign: urlParams.utmCampaign,
4457
+ browser: deviceInfo.userAgent.browser.name,
4458
+ browserVersion: deviceInfo.userAgent.browser.version,
4459
+ os: deviceInfo.userAgent.os.name,
4460
+ osVersion: deviceInfo.userAgent.os.version,
4461
+ deviceType: (_a = deviceInfo.userAgent.device) == null ? void 0 : _a.type,
4462
+ deviceModel: (_b = deviceInfo.userAgent.device) == null ? void 0 : _b.model,
4463
+ screenWidth: deviceInfo.screenResolution.width,
4464
+ screenHeight: deviceInfo.screenResolution.height,
4465
+ timeZone: deviceInfo.timeZone,
4466
+ draft
4467
+ // 🎯 Pass draft mode to session init
4468
+ };
4469
+ const response = await this.apiClient.post(
4470
+ "/api/v1/cms/session/init",
4471
+ sessionInitData
4472
+ );
4473
+ this.lastSessionInitError = null;
4474
+ this.sessionInitRetryCount = 0;
4475
+ this.updateSessionState(response, sessionData);
4476
+ this.updateState({
4477
+ isInitialized: true,
4478
+ isSessionInitialized: true,
4479
+ isLoading: false
4480
+ });
4481
+ if (this.state.debugMode) console.log("[TagadaClient] Session initialized successfully");
4482
+ } catch (error) {
4483
+ this.lastSessionInitError = error;
4484
+ this.sessionInitRetryCount++;
4485
+ console.error("[TagadaClient] Error initializing session (attempt ".concat(this.sessionInitRetryCount, "/").concat(this.MAX_SESSION_INIT_RETRIES, "):"), error);
4486
+ this.updateState({
4487
+ isInitialized: true,
4488
+ isLoading: false
4489
+ });
4490
+ } finally {
4491
+ this.isInitializingSession = false;
4492
+ }
4493
+ }
4494
+ updateSessionState(response, sessionData) {
4495
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i;
4496
+ if (response.store) {
4497
+ const storeData = response.store;
4498
+ const storeConfig = __spreadProps(__spreadValues({}, response.store), {
4499
+ // Ensure accountId is included - fallback to plugin config or session accountId
4500
+ accountId: storeData.accountId || ((_a = this.state.pluginConfig) == null ? void 0 : _a.accountId) || sessionData.accountId || "",
4501
+ presentmentCurrencies: storeData.presentmentCurrencies || [response.store.currency || "USD"],
4502
+ chargeCurrencies: storeData.chargeCurrencies || [response.store.currency || "USD"]
4503
+ });
4504
+ this.updateState({ store: storeConfig });
4505
+ }
4506
+ const localeConfig = {
4507
+ locale: response.locale,
4508
+ language: response.locale.split("-")[0],
4509
+ region: (_b = response.locale.split("-")[1]) != null ? _b : "US",
4510
+ messages: (_c = response.messages) != null ? _c : {}
4511
+ };
4512
+ this.updateState({ locale: localeConfig });
4513
+ if (response.store) {
4514
+ const currencyConfig = {
4515
+ code: response.store.currency,
4516
+ symbol: this.getCurrencySymbol(response.store.currency),
4517
+ name: this.getCurrencyName(response.store.currency)
4518
+ };
4519
+ this.updateState({ currency: currencyConfig });
4520
+ }
4521
+ const authState = {
4522
+ isAuthenticated: (_e = (_d = response.customer) == null ? void 0 : _d.isAuthenticated) != null ? _e : false,
4523
+ isLoading: false,
4524
+ customer: (_f = response.customer) != null ? _f : null,
4525
+ session: sessionData
4526
+ };
4527
+ this.updateState({
4528
+ customer: (_g = response.customer) != null ? _g : null,
4529
+ auth: authState
4530
+ });
4531
+ if (this.funnel && sessionData.customerId && ((_h = response.store) == null ? void 0 : _h.id)) {
4532
+ const accountId = response.store.accountId || ((_i = this.state.pluginConfig) == null ? void 0 : _i.accountId) || sessionData.accountId || "";
4533
+ if (accountId) {
4534
+ const urlParams = new URLSearchParams(typeof window !== "undefined" ? window.location.search : "");
4535
+ const funnelId = urlParams.get("funnelId") || void 0;
4536
+ if (this.state.debugMode) {
4537
+ console.log("[TagadaClient] Auto-initializing funnel...", {
4538
+ customerId: sessionData.customerId,
4539
+ storeId: response.store.id,
4540
+ accountId,
4541
+ funnelId: funnelId || "auto-detect"
4542
+ });
4543
+ }
4544
+ this.funnel.autoInitialize(
4545
+ { customerId: sessionData.customerId, sessionId: sessionData.sessionId },
4546
+ { id: response.store.id, accountId },
4547
+ funnelId
4548
+ ).catch((err) => {
4549
+ console.error("[TagadaClient] Funnel auto-initialization failed:", err);
4550
+ });
4551
+ } else {
4552
+ console.warn("[TagadaClient] Cannot auto-initialize funnel: accountId is missing");
4553
+ }
4554
+ }
4555
+ }
4556
+ // Helper methods
4557
+ getCurrencySymbol(code) {
4558
+ const symbols = {
4559
+ USD: "$",
4560
+ EUR: "\u20AC",
4561
+ GBP: "\xA3",
4562
+ JPY: "\xA5",
4563
+ CAD: "C$",
4564
+ AUD: "A$"
4565
+ };
4566
+ return symbols[code] || code;
4567
+ }
4568
+ getCurrencyName(code) {
4569
+ const names = {
4570
+ USD: "US Dollar",
4571
+ EUR: "Euro",
4572
+ GBP: "British Pound",
4573
+ JPY: "Japanese Yen",
4574
+ CAD: "Canadian Dollar",
4575
+ AUD: "Australian Dollar"
4576
+ };
4577
+ return names[code] || code;
4578
+ }
4579
+ /**
4580
+ * Helper to get accountId with fallbacks
4581
+ */
4582
+ getAccountId() {
4583
+ var _a, _b, _c;
4584
+ return ((_a = this.state.store) == null ? void 0 : _a.accountId) || ((_b = this.state.pluginConfig) == null ? void 0 : _b.accountId) || ((_c = this.state.session) == null ? void 0 : _c.accountId) || "";
4585
+ }
4586
+ /**
4587
+ * Update plugin config dynamically (hot-reload)
4588
+ * Used for live config editing without page reload
4589
+ */
4590
+ updatePluginConfig(newConfig) {
4591
+ if (this.state.debugMode) {
4592
+ console.log("[TagadaClient] Hot-reloading config:", newConfig);
4593
+ }
4594
+ const updatedConfig = __spreadValues(__spreadValues({}, this.state.pluginConfig.config), newConfig);
4595
+ this.updateState({
4596
+ pluginConfig: __spreadProps(__spreadValues({}, this.state.pluginConfig), {
4597
+ config: updatedConfig
4598
+ })
4599
+ });
4600
+ this.bus.emit("CONFIG_UPDATED", updatedConfig);
4601
+ if (this.state.debugMode) {
4602
+ console.log("[TagadaClient] Config updated successfully");
4603
+ }
4604
+ }
4605
+ /**
4606
+ * Setup listener for config updates from parent window (config editor)
4607
+ * Enables live config editing via postMessage
4608
+ */
4609
+ setupConfigHotReload() {
4610
+ if (typeof window === "undefined") return;
4611
+ const handleMessage = (event) => {
4612
+ var _a, _b;
4613
+ if (((_a = event.data) == null ? void 0 : _a.type) === "TAGADAPAY_CONFIG_UPDATE") {
4614
+ const { config } = event.data;
4615
+ if (this.state.debugMode) {
4616
+ console.log("[TagadaClient] Received config update from parent:", config);
4617
+ }
4618
+ this.updatePluginConfig(config);
4619
+ } else if (((_b = event.data) == null ? void 0 : _b.type) === "APPLY_STYLES_TO_ELEMENT") {
4620
+ const { elementId, styles } = event.data;
4621
+ if (this.state.debugMode) {
4622
+ console.log("[TagadaClient] Received style application request:", { elementId, styles });
4623
+ }
4624
+ this.applyStylesToElement(elementId, styles);
4625
+ }
4626
+ };
4627
+ window.addEventListener("message", handleMessage);
4628
+ if (this.state.debugMode) {
4629
+ console.log("[TagadaClient] Config hot-reload and style manipulation listeners enabled");
4630
+ }
4631
+ }
4632
+ /**
4633
+ * Apply CSS properties to a real div child element for highlighting
4634
+ * Used by config editor to highlight elements in preview without altering the element's style
4635
+ */
4636
+ applyStylesToElement(elementId, styles) {
4637
+ var _a;
4638
+ if (typeof document === "undefined") return;
4639
+ const element = document.querySelector('[editor-id~="'.concat(elementId, '"]'));
4640
+ if (!element) {
4641
+ if (this.state.debugMode) {
4642
+ console.warn('[TagadaClient] Element with editor-id containing "'.concat(elementId, '" not found'));
4643
+ }
4644
+ return;
4645
+ }
4646
+ const voidElements = /* @__PURE__ */ new Set([
4647
+ "area",
4648
+ "base",
4649
+ "br",
4650
+ "col",
4651
+ "embed",
4652
+ "hr",
4653
+ "img",
4654
+ "input",
4655
+ "link",
4656
+ "meta",
4657
+ "param",
4658
+ "source",
4659
+ "track",
4660
+ "wbr"
4661
+ ]);
4662
+ const isVoidElement = voidElements.has(element.tagName.toLowerCase());
4663
+ let targetElement = element;
4664
+ let wrapper = null;
4665
+ if (isVoidElement) {
4666
+ const parent = element.parentElement;
4667
+ const existingWrapper = parent == null ? void 0 : parent.getAttribute("data-tagada-highlight-wrapper");
4668
+ if (existingWrapper === "true") {
4669
+ targetElement = parent;
4670
+ } else {
4671
+ wrapper = document.createElement("div");
4672
+ wrapper.setAttribute("data-tagada-highlight-wrapper", "true");
4673
+ const computedStyle2 = window.getComputedStyle(element);
4674
+ const elementDisplay = computedStyle2.display;
4675
+ if (elementDisplay === "inline") {
4676
+ wrapper.style.display = "inline-block";
4677
+ } else {
4678
+ wrapper.style.display = elementDisplay;
4679
+ }
4680
+ wrapper.style.position = "relative";
4681
+ if (elementDisplay === "inline" || elementDisplay.includes("inline")) {
4682
+ const verticalAlign = computedStyle2.verticalAlign;
4683
+ if (verticalAlign && verticalAlign !== "baseline") {
4684
+ wrapper.style.verticalAlign = verticalAlign;
4685
+ }
4686
+ }
4687
+ (_a = element.parentNode) == null ? void 0 : _a.insertBefore(wrapper, element);
4688
+ wrapper.appendChild(element);
4689
+ targetElement = wrapper;
4690
+ }
4691
+ }
4692
+ const computedStyle = getComputedStyle(isVoidElement ? element : targetElement);
4693
+ if (targetElement.style.position === "static" || !targetElement.style.position) {
4694
+ targetElement.style.position = "relative";
4695
+ }
4696
+ const staticHighlightId = "tagada-editor-highlight";
4697
+ const existingHighlight = document.getElementById(staticHighlightId);
4698
+ if (existingHighlight) {
4699
+ existingHighlight.remove();
4700
+ }
4701
+ const highlightDiv = document.createElement("div");
4702
+ highlightDiv.id = staticHighlightId;
4703
+ highlightDiv.style.position = "absolute";
4704
+ highlightDiv.style.inset = "0";
4705
+ highlightDiv.style.pointerEvents = "none";
4706
+ highlightDiv.style.zIndex = "9999";
4707
+ highlightDiv.style.boxSizing = "border-box";
4708
+ highlightDiv.style.background = "none";
4709
+ highlightDiv.style.border = "none";
4710
+ highlightDiv.style.outline = "none";
4711
+ const borderRadius = computedStyle.borderRadius;
4712
+ if (borderRadius) {
4713
+ highlightDiv.style.borderRadius = borderRadius;
4714
+ }
4715
+ targetElement.appendChild(highlightDiv);
4716
+ const stylesToApply = styles || { boxShadow: "0 0 0 2px rgb(239 68 68)" };
4717
+ Object.entries(stylesToApply).forEach(([property, value]) => {
4718
+ const camelProperty = property.includes("-") ? property.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase()) : property;
4719
+ if (property.includes("-")) {
4720
+ highlightDiv.style.setProperty(property, value);
4721
+ } else {
4722
+ highlightDiv.style[camelProperty] = value;
4723
+ }
4724
+ });
4725
+ element.scrollIntoView({ behavior: "smooth", block: "center" });
4726
+ if (this.state.debugMode) {
4727
+ const appliedStyles = Object.entries(stylesToApply).map(([k, v]) => "".concat(k, ": ").concat(v)).join("; ");
4728
+ console.log("[TagadaClient] Applied styles to highlight div of element #".concat(elementId, ":"), appliedStyles);
4729
+ }
4730
+ }
4731
+ };
4732
+
4733
+ // src/v2/standalone/index.ts
4734
+ function createTagadaClient(config = {}) {
4735
+ return new TagadaClient(config);
4736
+ }
4737
+
4738
+ // src/v2/standalone/external-tracker.ts
4739
+ function getUrlParam(name) {
4740
+ if (typeof window === "undefined") return null;
4741
+ const params = new URLSearchParams(window.location.search);
4742
+ return params.get(name);
4743
+ }
4744
+ function log(debug, ...args) {
4745
+ if (debug) {
4746
+ console.log("[TagadaTracker]", ...args);
4747
+ }
4748
+ }
4749
+ var TagadaExternalTracker = class {
4750
+ constructor() {
4751
+ this.config = null;
4752
+ this.client = null;
4753
+ this.initialized = false;
4754
+ this.initializing = false;
4755
+ }
4756
+ /**
4757
+ * Initialize the tracker using SDK infrastructure
4758
+ */
4759
+ async init(config) {
4760
+ var _a, _b, _c, _d;
4761
+ if (this.initialized || this.initializing) {
4762
+ log(config.debug || false, "Already initialized or initializing");
4763
+ return this.getSession();
4764
+ }
4765
+ this.initializing = true;
4766
+ this.config = __spreadValues({
4767
+ debug: false
4768
+ }, config);
4769
+ log(this.config.debug, "\u{1F680} Initializing external tracker with SDK...", config);
4770
+ try {
4771
+ const urlToken = getUrlParam("token");
4772
+ if (urlToken) {
4773
+ setClientToken(urlToken);
4774
+ log(this.config.debug, "\u{1F511} Bootstrapped token from URL");
4775
+ }
4776
+ this.client = createTagadaClient({
4777
+ debugMode: this.config.debug,
4778
+ features: { funnel: true }
4779
+ });
4780
+ await this.waitForClientReady();
4781
+ const funnelContext = await this.initializeFunnel();
4782
+ log(this.config.debug, "\u2705 Session initialized (tracking handled by orchestrator):", funnelContext);
4783
+ this.initialized = true;
4784
+ const session = this.getSession();
4785
+ if (session) {
4786
+ (_b = (_a = this.config).onReady) == null ? void 0 : _b.call(_a, session);
4787
+ }
4788
+ return session;
4789
+ } catch (error) {
4790
+ const err = error instanceof Error ? error : new Error(String(error));
4791
+ log(this.config.debug, "\u274C Initialization failed:", err);
4792
+ (_d = (_c = this.config).onError) == null ? void 0 : _d.call(_c, err);
4793
+ throw err;
4794
+ } finally {
4795
+ this.initializing = false;
4796
+ }
4797
+ }
4798
+ /**
4799
+ * Get current session from SDK state
4800
+ */
4801
+ getSession() {
4802
+ var _a, _b;
4803
+ if (!((_b = (_a = this.client) == null ? void 0 : _a.funnel) == null ? void 0 : _b.state.context)) return null;
4804
+ const ctx = this.client.funnel.state.context;
4805
+ return {
4806
+ sessionId: ctx.sessionId,
4807
+ customerId: ctx.customerId,
4808
+ storeId: ctx.storeId,
4809
+ funnelId: ctx.funnelId,
4810
+ currentStepId: ctx.currentStepId,
4811
+ cmsToken: this.client.state.token || void 0
4812
+ };
4813
+ }
4814
+ /**
4815
+ * Check if tracker is ready
4816
+ */
4817
+ isReady() {
4818
+ var _a, _b;
4819
+ return this.initialized && !!((_b = (_a = this.client) == null ? void 0 : _a.funnel) == null ? void 0 : _b.state.context);
4820
+ }
4821
+ /**
4822
+ * Navigate to next step in funnel using SDK's funnel client
4823
+ */
4824
+ async navigate(options) {
4825
+ if (!this.isReady()) {
4826
+ throw new Error("Tracker not initialized. Call init() first.");
4827
+ }
4828
+ log(this.config.debug, "\u{1F680} Navigating:", options);
4829
+ try {
4830
+ const result = await this.client.funnel.navigate({
4831
+ type: options.eventType,
4832
+ data: options.eventData || {}
4833
+ });
4834
+ if (result == null ? void 0 : result.url) {
4835
+ log(this.config.debug, "\u2705 Navigation result:", result.url);
4836
+ if (typeof window !== "undefined") {
4837
+ window.location.href = options.returnUrl || result.url;
4838
+ }
4839
+ return { url: result.url };
4840
+ }
4841
+ return null;
4842
+ } catch (error) {
4843
+ log(this.config.debug, "\u274C Navigation failed:", error);
4844
+ throw error;
4845
+ }
4846
+ }
4847
+ /**
4848
+ * Get customer ID (for identifying the user)
4849
+ */
4850
+ getCustomerId() {
4851
+ var _a, _b, _c, _d, _e;
4852
+ return ((_b = (_a = this.client) == null ? void 0 : _a.state.auth.customer) == null ? void 0 : _b.id) || ((_e = (_d = (_c = this.client) == null ? void 0 : _c.funnel) == null ? void 0 : _d.state.context) == null ? void 0 : _e.customerId) || null;
4853
+ }
4854
+ /**
4855
+ * Get funnel session ID
4856
+ */
4857
+ getFunnelSessionId() {
4858
+ var _a, _b, _c;
4859
+ return ((_c = (_b = (_a = this.client) == null ? void 0 : _a.funnel) == null ? void 0 : _b.state.context) == null ? void 0 : _c.sessionId) || null;
4860
+ }
4861
+ /**
4862
+ * Build a URL with funnel context parameters
4863
+ * Useful for linking to other external pages while preserving session
4864
+ */
4865
+ buildUrl(baseUrl, additionalParams) {
4866
+ const session = this.getSession();
4867
+ if (!session) {
4868
+ return baseUrl;
4869
+ }
4870
+ const url = new URL(baseUrl, typeof window !== "undefined" ? window.location.origin : void 0);
4871
+ url.searchParams.set("funnelSessionId", session.sessionId);
4872
+ if (session.cmsToken) {
4873
+ url.searchParams.set("token", session.cmsToken);
4874
+ }
4875
+ if (session.funnelId) {
4876
+ url.searchParams.set("funnelId", session.funnelId);
4877
+ }
4878
+ url.searchParams.set("storeId", session.storeId);
4879
+ if (additionalParams) {
4880
+ Object.entries(additionalParams).forEach(([key, value]) => {
4881
+ url.searchParams.set(key, value);
4882
+ });
4883
+ }
4884
+ return url.toString();
4885
+ }
4886
+ /**
4887
+ * Get the underlying SDK client (for advanced usage)
4888
+ */
4889
+ getClient() {
4890
+ return this.client;
4891
+ }
4892
+ // ========================================================================
4893
+ // PRIVATE METHODS
4894
+ // ========================================================================
4895
+ async waitForClientReady() {
4896
+ if (!this.client) return;
4897
+ return new Promise((resolve) => {
4898
+ let retries = 0;
4899
+ const checkReady = () => {
4900
+ var _a, _b;
4901
+ if (((_a = this.client) == null ? void 0 : _a.state.isInitialized) || ((_b = this.client) == null ? void 0 : _b.state.token)) {
4902
+ resolve();
4903
+ } else if (retries > 40) {
4904
+ resolve();
4905
+ } else {
4906
+ retries++;
4907
+ setTimeout(checkReady, 50);
4908
+ }
4909
+ };
4910
+ checkReady();
4911
+ });
4912
+ }
4913
+ async initializeFunnel() {
4914
+ var _a, _b, _c;
4915
+ if (!((_a = this.client) == null ? void 0 : _a.funnel)) return null;
4916
+ const authSession = {
4917
+ customerId: ((_b = this.client.state.auth.customer) == null ? void 0 : _b.id) || "anon_placeholder",
4918
+ sessionId: ((_c = this.client.state.auth.session) == null ? void 0 : _c.sessionId) || "sess_placeholder"
4919
+ };
4920
+ const store = {
4921
+ id: this.config.storeId,
4922
+ accountId: this.config.accountId || ""
4923
+ };
4924
+ const entryStepId = this.config.stepId;
4925
+ if (!entryStepId) {
4926
+ throw new Error("stepId is required for external page tracking (URL mapping does not work for external pages)");
4927
+ }
4928
+ log(this.config.debug, "\u{1F50D} Initializing external page at step:", entryStepId);
4929
+ return this.client.funnel.initialize(
4930
+ authSession,
4931
+ store,
4932
+ this.config.funnelId || getUrlParam("funnelId") || void 0,
4933
+ entryStepId
4934
+ // ✅ Explicitly tell orchestrator which step we're on
4935
+ );
4936
+ }
4937
+ };
4938
+ var TagadaTracker = new TagadaExternalTracker();
4939
+ if (typeof window !== "undefined") {
4940
+ window.TagadaTracker = TagadaTracker;
4941
+ }
4942
+ return __toCommonJS(external_tracker_exports);
4943
+ })();
4944
+ // Expose TagadaTracker globally
4945
+ if (typeof window !== 'undefined' && TagadaTrackerBundle && TagadaTrackerBundle.TagadaTracker) {
4946
+ window.TagadaTracker = TagadaTrackerBundle.TagadaTracker;
4947
+ }