@scalemule/nextjs 0.1.61 → 0.1.63

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 (41) hide show
  1. package/dist/audio.css +857 -0
  2. package/dist/audio.d.mts +334 -0
  3. package/dist/audio.d.ts +334 -0
  4. package/dist/audio.js +2178 -0
  5. package/dist/audio.mjs +2156 -0
  6. package/dist/client.d.mts +240 -0
  7. package/dist/client.d.ts +240 -0
  8. package/dist/client.js +938 -0
  9. package/dist/client.mjs +935 -0
  10. package/dist/index-CEi5Nd4L.d.mts +980 -0
  11. package/dist/index-CEi5Nd4L.d.ts +980 -0
  12. package/dist/index.d.mts +1354 -0
  13. package/dist/index.d.ts +1354 -0
  14. package/dist/index.js +6070 -0
  15. package/dist/index.mjs +6006 -0
  16. package/dist/ledvery-CxPzZpxP.d.mts +44 -0
  17. package/dist/ledvery-CxPzZpxP.d.ts +44 -0
  18. package/dist/listening-hub.global.js +1 -0
  19. package/dist/server/auth.d.mts +43 -0
  20. package/dist/server/auth.d.ts +43 -0
  21. package/dist/server/auth.js +2015 -0
  22. package/dist/server/auth.mjs +2009 -0
  23. package/dist/server/index.d.mts +1303 -0
  24. package/dist/server/index.d.ts +1303 -0
  25. package/dist/server/index.js +3660 -0
  26. package/dist/server/index.mjs +3581 -0
  27. package/dist/server/ledvery.d.mts +1 -0
  28. package/dist/server/ledvery.d.ts +1 -0
  29. package/dist/server/ledvery.js +336 -0
  30. package/dist/server/ledvery.mjs +333 -0
  31. package/dist/server/webhook-handler.d.mts +4 -0
  32. package/dist/server/webhook-handler.d.ts +4 -0
  33. package/dist/server/webhook-handler.js +60 -0
  34. package/dist/server/webhook-handler.mjs +58 -0
  35. package/dist/testing.d.mts +109 -0
  36. package/dist/testing.d.ts +109 -0
  37. package/dist/testing.js +144 -0
  38. package/dist/testing.mjs +138 -0
  39. package/dist/webhook-handler-CJm0sIZG.d.mts +856 -0
  40. package/dist/webhook-handler-CnQe9hm5.d.ts +856 -0
  41. package/package.json +2 -2
@@ -0,0 +1,935 @@
1
+ import { STORAGE_KEYS, ensureAnonymousId } from '@scalemule/sdk';
2
+
3
+ // src/client.ts
4
+
5
+ // src/types/index.ts
6
+ var ScaleMuleApiError = class extends Error {
7
+ constructor(error, status) {
8
+ super(error.message);
9
+ this.name = "ScaleMuleApiError";
10
+ this.code = error.code;
11
+ this.field = error.field;
12
+ this.status = status;
13
+ this.requestId = error.requestId;
14
+ this.traceId = error.traceId;
15
+ this.problem = error.problem;
16
+ }
17
+ };
18
+
19
+ // src/error-context.ts
20
+ function withErrorContext(error, responseData, headers) {
21
+ const enriched = { ...error };
22
+ const meta = responseData?.meta;
23
+ const requestId = meta?.request_id ?? headers?.get("x-request-id") ?? void 0;
24
+ if (requestId !== void 0 && enriched.requestId === void 0) {
25
+ enriched.requestId = requestId;
26
+ }
27
+ const traceId = meta?.trace_id;
28
+ if (traceId !== void 0 && enriched.traceId === void 0) {
29
+ enriched.traceId = traceId;
30
+ }
31
+ const rawError = responseData?.error;
32
+ if (rawError !== null && typeof rawError === "object" && enriched.problem === void 0) {
33
+ enriched.problem = rawError;
34
+ }
35
+ return enriched;
36
+ }
37
+
38
+ // src/client.ts
39
+ var GATEWAY_URLS = {
40
+ dev: "https://api-dev.scalemule.com",
41
+ prod: "https://api.scalemule.com"
42
+ };
43
+ var SESSION_STORAGE_KEY = STORAGE_KEYS.SESSION;
44
+ var USER_ID_STORAGE_KEY = STORAGE_KEYS.USER_ID;
45
+ var WORKSPACE_STORAGE_KEY = STORAGE_KEYS.WORKSPACE_ID;
46
+ var RETRYABLE_STATUS_CODES = /* @__PURE__ */ new Set([408, 429, 500, 502, 503, 504]);
47
+ function sleep(ms) {
48
+ return new Promise((resolve) => setTimeout(resolve, ms));
49
+ }
50
+ function getBackoffDelay(attempt, baseDelay = 1e3) {
51
+ const exponentialDelay = baseDelay * Math.pow(2, attempt);
52
+ const jitter = Math.random() * 0.3 * exponentialDelay;
53
+ return Math.min(exponentialDelay + jitter, 3e4);
54
+ }
55
+ function sanitizeFilename(filename) {
56
+ let sanitized = filename.replace(/[\x00-\x1f\x7f]/g, "");
57
+ sanitized = sanitized.replace(/["\\/\n\r]/g, "_").normalize("NFC").replace(/[\u200b-\u200f\ufeff\u2028\u2029]/g, "");
58
+ if (!sanitized || sanitized.trim() === "") {
59
+ sanitized = "unnamed";
60
+ }
61
+ if (sanitized.length > 200) {
62
+ const ext = sanitized.split(".").pop();
63
+ const base = sanitized.substring(0, 190);
64
+ sanitized = ext ? `${base}.${ext}` : base;
65
+ }
66
+ return sanitized.trim();
67
+ }
68
+ var RateLimitQueue = class {
69
+ constructor() {
70
+ this.queue = [];
71
+ this.processing = false;
72
+ this.rateLimitedUntil = 0;
73
+ this.requestsInWindow = 0;
74
+ this.windowStart = Date.now();
75
+ this.maxRequestsPerWindow = 100;
76
+ this.windowDurationMs = 6e4;
77
+ }
78
+ // 1 minute
79
+ /**
80
+ * Add request to queue
81
+ */
82
+ enqueue(execute, priority = 0) {
83
+ return new Promise((resolve, reject) => {
84
+ this.queue.push({
85
+ execute,
86
+ resolve,
87
+ reject,
88
+ priority
89
+ });
90
+ this.queue.sort((a, b) => b.priority - a.priority);
91
+ this.processQueue();
92
+ });
93
+ }
94
+ /**
95
+ * Process queued requests
96
+ */
97
+ async processQueue() {
98
+ if (this.processing || this.queue.length === 0) return;
99
+ this.processing = true;
100
+ while (this.queue.length > 0) {
101
+ const now = Date.now();
102
+ if (now < this.rateLimitedUntil) {
103
+ const waitTime = this.rateLimitedUntil - now;
104
+ await sleep(waitTime);
105
+ }
106
+ if (now - this.windowStart >= this.windowDurationMs) {
107
+ this.windowStart = now;
108
+ this.requestsInWindow = 0;
109
+ }
110
+ if (this.requestsInWindow >= this.maxRequestsPerWindow) {
111
+ const waitTime = this.windowDurationMs - (now - this.windowStart);
112
+ await sleep(waitTime);
113
+ this.windowStart = Date.now();
114
+ this.requestsInWindow = 0;
115
+ }
116
+ const request = this.queue.shift();
117
+ if (!request) continue;
118
+ try {
119
+ this.requestsInWindow++;
120
+ const result = await request.execute();
121
+ request.resolve(result);
122
+ } catch (error) {
123
+ if (error instanceof ScaleMuleApiError && error.code === "RATE_LIMITED") {
124
+ this.queue.unshift(request);
125
+ this.rateLimitedUntil = Date.now() + 6e4;
126
+ } else {
127
+ request.reject(error);
128
+ }
129
+ }
130
+ }
131
+ this.processing = false;
132
+ }
133
+ /**
134
+ * Update rate limit from response headers
135
+ */
136
+ updateFromHeaders(headers) {
137
+ const retryAfter = headers.get("Retry-After");
138
+ if (retryAfter) {
139
+ const seconds = parseInt(retryAfter, 10);
140
+ if (!isNaN(seconds)) {
141
+ this.rateLimitedUntil = Date.now() + seconds * 1e3;
142
+ }
143
+ }
144
+ const remaining = headers.get("X-RateLimit-Remaining");
145
+ if (remaining) {
146
+ const count = parseInt(remaining, 10);
147
+ if (!isNaN(count) && count === 0) {
148
+ const reset = headers.get("X-RateLimit-Reset");
149
+ if (reset) {
150
+ const resetTime = parseInt(reset, 10) * 1e3;
151
+ if (!isNaN(resetTime)) {
152
+ this.rateLimitedUntil = resetTime;
153
+ }
154
+ }
155
+ }
156
+ }
157
+ }
158
+ /**
159
+ * Get queue length
160
+ */
161
+ get length() {
162
+ return this.queue.length;
163
+ }
164
+ /**
165
+ * Check if rate limited
166
+ */
167
+ get isRateLimited() {
168
+ return Date.now() < this.rateLimitedUntil;
169
+ }
170
+ };
171
+ var OfflineQueue = class {
172
+ constructor(storage) {
173
+ this.queue = [];
174
+ this.storageKey = "scalemule_offline_queue";
175
+ this.isOnline = true;
176
+ this.onOnline = null;
177
+ this.storage = storage;
178
+ this.loadFromStorage();
179
+ this.setupOnlineListener();
180
+ }
181
+ /**
182
+ * Setup online/offline event listeners
183
+ */
184
+ setupOnlineListener() {
185
+ if (typeof window === "undefined") return;
186
+ this.isOnline = navigator.onLine;
187
+ window.addEventListener("online", () => {
188
+ this.isOnline = true;
189
+ if (this.onOnline) this.onOnline();
190
+ });
191
+ window.addEventListener("offline", () => {
192
+ this.isOnline = false;
193
+ });
194
+ }
195
+ /**
196
+ * Load queue from storage
197
+ */
198
+ async loadFromStorage() {
199
+ try {
200
+ const data = await this.storage.getItem(this.storageKey);
201
+ if (data) {
202
+ this.queue = JSON.parse(data);
203
+ }
204
+ } catch {
205
+ }
206
+ }
207
+ /**
208
+ * Save queue to storage
209
+ */
210
+ async saveToStorage() {
211
+ try {
212
+ await this.storage.setItem(this.storageKey, JSON.stringify(this.queue));
213
+ } catch {
214
+ }
215
+ }
216
+ /**
217
+ * Add request to offline queue
218
+ */
219
+ async add(method, path, body) {
220
+ const item = {
221
+ id: `${Date.now()}-${Math.random().toString(36).slice(2)}`,
222
+ method,
223
+ path,
224
+ body: body ? JSON.stringify(body) : void 0,
225
+ timestamp: Date.now()
226
+ };
227
+ this.queue.push(item);
228
+ await this.saveToStorage();
229
+ }
230
+ /**
231
+ * Get all queued requests
232
+ */
233
+ getAll() {
234
+ return [...this.queue];
235
+ }
236
+ /**
237
+ * Remove a request from queue
238
+ */
239
+ async remove(id) {
240
+ this.queue = this.queue.filter((item) => item.id !== id);
241
+ await this.saveToStorage();
242
+ }
243
+ /**
244
+ * Clear all queued requests
245
+ */
246
+ async clear() {
247
+ this.queue = [];
248
+ await this.saveToStorage();
249
+ }
250
+ /**
251
+ * Set callback for when coming back online
252
+ */
253
+ setOnlineCallback(callback) {
254
+ this.onOnline = callback;
255
+ }
256
+ /**
257
+ * Check if currently online
258
+ */
259
+ get online() {
260
+ return this.isOnline;
261
+ }
262
+ /**
263
+ * Get queue length
264
+ */
265
+ get length() {
266
+ return this.queue.length;
267
+ }
268
+ };
269
+ function resolveGatewayUrl(config) {
270
+ if (config.gatewayUrl) {
271
+ return config.gatewayUrl;
272
+ }
273
+ const env = config.environment || "prod";
274
+ return GATEWAY_URLS[env];
275
+ }
276
+ function createDefaultStorage() {
277
+ if (typeof window !== "undefined" && window.localStorage) {
278
+ return {
279
+ getItem: (key) => localStorage.getItem(key),
280
+ setItem: (key, value) => localStorage.setItem(key, value),
281
+ removeItem: (key) => localStorage.removeItem(key)
282
+ };
283
+ }
284
+ const memoryStorage = /* @__PURE__ */ new Map();
285
+ return {
286
+ getItem: (key) => memoryStorage.get(key) ?? null,
287
+ setItem: (key, value) => {
288
+ memoryStorage.set(key, value);
289
+ },
290
+ removeItem: (key) => {
291
+ memoryStorage.delete(key);
292
+ }
293
+ };
294
+ }
295
+ var ScaleMuleClient = class {
296
+ constructor(config) {
297
+ this.applicationId = null;
298
+ this.sessionToken = null;
299
+ this.userId = null;
300
+ this.rateLimitQueue = null;
301
+ this.offlineQueue = null;
302
+ this.sessionGate = null;
303
+ this.resolveSessionGate = null;
304
+ this.workspaceId = null;
305
+ // Anonymous visitor ID for identity linking. See `@scalemule/sdk/anonymous-id`
306
+ // for the contract. The base SDK and this client share the same canonical
307
+ // localStorage key so a visitor has exactly one ID across all packages.
308
+ this.anonymousId = null;
309
+ // Per-client single-flight cache for the lazy mint. Concurrent first-use
310
+ // callers receive the same promise — without this, two simultaneous
311
+ // unauthenticated requests on a fresh visitor could mint different IDs.
312
+ // The shared helper also single-flights at the storage-adapter level.
313
+ this.anonymousIdPromise = null;
314
+ this.refreshPromise = null;
315
+ this.cookieSession = config.cookieSession === true;
316
+ this.apiKey = config.apiKey;
317
+ this.applicationId = config.applicationId || null;
318
+ this.gatewayUrl = resolveGatewayUrl(config);
319
+ this.debug = config.debug || false;
320
+ this.storage = config.storage || createDefaultStorage();
321
+ this.enableRateLimitQueue = config.enableRateLimitQueue || false;
322
+ this.enableOfflineQueue = config.enableOfflineQueue || false;
323
+ this.onRefreshStart = config.onRefreshStart;
324
+ this.onRefreshEnd = config.onRefreshEnd;
325
+ this.onAutoRefreshFailed = config.onAutoRefreshFailed;
326
+ if (this.enableRateLimitQueue) {
327
+ this.rateLimitQueue = new RateLimitQueue();
328
+ }
329
+ if (this.enableOfflineQueue) {
330
+ this.offlineQueue = new OfflineQueue(this.storage);
331
+ this.offlineQueue.setOnlineCallback(() => this.syncOfflineQueue());
332
+ }
333
+ if (config.pendingSessionInit) {
334
+ this.setSessionPending();
335
+ }
336
+ }
337
+ /**
338
+ * Sync offline queue when coming back online
339
+ */
340
+ async syncOfflineQueue() {
341
+ if (!this.offlineQueue) return;
342
+ const items = this.offlineQueue.getAll();
343
+ if (this.debug && items.length > 0) {
344
+ console.log(`[ScaleMule] Syncing ${items.length} offline requests`);
345
+ }
346
+ for (const item of items) {
347
+ try {
348
+ await this.request(item.path, {
349
+ method: item.method,
350
+ body: item.body,
351
+ skipRetry: true
352
+ });
353
+ await this.offlineQueue.remove(item.id);
354
+ } catch (err) {
355
+ if (this.debug) {
356
+ console.error("[ScaleMule] Failed to sync offline request:", err);
357
+ }
358
+ break;
359
+ }
360
+ }
361
+ }
362
+ /**
363
+ * Check if client is online
364
+ */
365
+ isOnline() {
366
+ if (this.offlineQueue) {
367
+ return this.offlineQueue.online;
368
+ }
369
+ return typeof navigator === "undefined" || navigator.onLine;
370
+ }
371
+ /**
372
+ * Get number of pending offline requests
373
+ */
374
+ getOfflineQueueLength() {
375
+ return this.offlineQueue?.length || 0;
376
+ }
377
+ /**
378
+ * Get number of pending rate-limited requests
379
+ */
380
+ getRateLimitQueueLength() {
381
+ return this.rateLimitQueue?.length || 0;
382
+ }
383
+ /**
384
+ * Check if currently rate limited
385
+ */
386
+ isRateLimited() {
387
+ return this.rateLimitQueue?.isRateLimited || false;
388
+ }
389
+ /**
390
+ * Set the active workspace context. All subsequent requests will include
391
+ * x-sm-workspace-id header. Pass null to clear.
392
+ */
393
+ setWorkspaceContext(id) {
394
+ this.workspaceId = id;
395
+ if (id) {
396
+ this.storage.setItem(WORKSPACE_STORAGE_KEY, id);
397
+ } else {
398
+ this.storage.removeItem(WORKSPACE_STORAGE_KEY);
399
+ }
400
+ }
401
+ /**
402
+ * Get the current workspace ID
403
+ */
404
+ getWorkspaceId() {
405
+ return this.workspaceId;
406
+ }
407
+ /**
408
+ * Get the gateway URL
409
+ */
410
+ getGatewayUrl() {
411
+ return this.gatewayUrl;
412
+ }
413
+ /**
414
+ * Get the application ID (required for realtime features)
415
+ */
416
+ getApplicationId() {
417
+ return this.applicationId;
418
+ }
419
+ /**
420
+ * Signal that a session is being established asynchronously.
421
+ * API requests will wait until resolveSessionPending() is called.
422
+ */
423
+ setSessionPending() {
424
+ if (!this.sessionGate) {
425
+ this.sessionGate = new Promise((resolve) => {
426
+ this.resolveSessionGate = resolve;
427
+ });
428
+ }
429
+ }
430
+ /**
431
+ * Resolve the pending session gate, allowing queued API requests to proceed.
432
+ * Must be called after setSessionPending(), whether session was established or not.
433
+ */
434
+ resolveSessionPending() {
435
+ if (this.resolveSessionGate) {
436
+ this.resolveSessionGate();
437
+ this.resolveSessionGate = null;
438
+ this.sessionGate = null;
439
+ }
440
+ }
441
+ /**
442
+ * Initialize client by loading persisted session
443
+ */
444
+ async initialize() {
445
+ if (this.cookieSession) {
446
+ await this.storage.removeItem(SESSION_STORAGE_KEY);
447
+ await this.storage.removeItem(STORAGE_KEYS.SESSION_POOL);
448
+ await this.storage.removeItem(STORAGE_KEYS.ACTIVE_ACCOUNT);
449
+ }
450
+ const token = this.cookieSession ? null : await this.storage.getItem(SESSION_STORAGE_KEY);
451
+ const userId = this.cookieSession ? null : await this.storage.getItem(USER_ID_STORAGE_KEY);
452
+ if (token) this.sessionToken = token;
453
+ if (userId) this.userId = userId;
454
+ const wsId = await this.storage.getItem(WORKSPACE_STORAGE_KEY);
455
+ if (wsId) this.workspaceId = wsId;
456
+ try {
457
+ await this.ensureAnonymousId();
458
+ } catch {
459
+ }
460
+ if (token) {
461
+ this.resolveSessionPending();
462
+ }
463
+ if (this.debug) {
464
+ console.log("[ScaleMule] Initialized with session:", !!token);
465
+ }
466
+ }
467
+ /**
468
+ * Sync accessor for the cached anonymous ID. Returns `null` until either
469
+ * `initialize()` has run or `ensureAnonymousId()` has been awaited at
470
+ * least once. Use `ensureAnonymousId()` if you need a guaranteed value.
471
+ */
472
+ getAnonymousId() {
473
+ return this.anonymousId;
474
+ }
475
+ /**
476
+ * Lazy-mint or cache-then-return the anonymous ID via the shared
477
+ * `@scalemule/sdk` helper. Concurrent callers receive the same in-flight
478
+ * promise, so a burst of simultaneous first-use requests all see the
479
+ * same minted value.
480
+ */
481
+ async ensureAnonymousId() {
482
+ if (this.anonymousId) return this.anonymousId;
483
+ if (!this.anonymousIdPromise) {
484
+ this.anonymousIdPromise = ensureAnonymousId(this.storage).then((id) => {
485
+ this.anonymousId = id;
486
+ return id;
487
+ }).finally(() => {
488
+ this.anonymousIdPromise = null;
489
+ });
490
+ }
491
+ return this.anonymousIdPromise;
492
+ }
493
+ /**
494
+ * Set session after login
495
+ */
496
+ async setSession(token, userId) {
497
+ if (this.cookieSession) {
498
+ this.setCookieSession(userId);
499
+ await this.storage.removeItem(SESSION_STORAGE_KEY);
500
+ return;
501
+ }
502
+ this.sessionToken = token;
503
+ this.userId = userId;
504
+ await this.storage.setItem(SESSION_STORAGE_KEY, token);
505
+ await this.storage.setItem(USER_ID_STORAGE_KEY, userId);
506
+ if (this.debug) {
507
+ console.log("[ScaleMule] Session set for user:", userId);
508
+ }
509
+ }
510
+ /**
511
+ * Token-only setter for member-auth surfaces.
512
+ *
513
+ * Unlike `setSession(token, userId)`, this does NOT persist a userId or
514
+ * write to local storage — useful when the host platform owns identity
515
+ * (e.g. ScaleMule's member dashboards use `MemberAuthProvider` and the
516
+ * token comes from a `${env}_member_access_token` cookie). The token is
517
+ * applied in-memory and used as a `Bearer` Authorization header on
518
+ * subsequent requests.
519
+ *
520
+ * Pass `null` to clear without touching userId/storage.
521
+ */
522
+ setCookieSession(userId) {
523
+ if (!this.cookieSession) return;
524
+ this.sessionToken = null;
525
+ this.userId = userId;
526
+ this.resolveSessionPending();
527
+ }
528
+ usesCookieSession() {
529
+ return this.cookieSession;
530
+ }
531
+ setSessionToken(token) {
532
+ this.sessionToken = this.cookieSession ? null : token;
533
+ if (this.debug) {
534
+ console.log("[ScaleMule] Session token", token ? "set (token-only)" : "cleared (token-only)");
535
+ }
536
+ }
537
+ /**
538
+ * Clear session on logout
539
+ */
540
+ async clearSession() {
541
+ this.sessionToken = null;
542
+ this.userId = null;
543
+ this.workspaceId = null;
544
+ await this.storage.removeItem(SESSION_STORAGE_KEY);
545
+ await this.storage.removeItem(USER_ID_STORAGE_KEY);
546
+ await this.storage.removeItem(WORKSPACE_STORAGE_KEY);
547
+ if (this.debug) {
548
+ console.log("[ScaleMule] Session cleared");
549
+ }
550
+ }
551
+ /**
552
+ * Get current session token
553
+ */
554
+ getSessionToken() {
555
+ return this.sessionToken;
556
+ }
557
+ /**
558
+ * Get current user ID
559
+ */
560
+ getUserId() {
561
+ return this.userId;
562
+ }
563
+ /**
564
+ * Check if client has an active session
565
+ */
566
+ isAuthenticated() {
567
+ return (this.cookieSession || this.sessionToken !== null) && this.userId !== null;
568
+ }
569
+ /**
570
+ * Build headers for a request
571
+ */
572
+ buildHeaders(options) {
573
+ const headers = new Headers(options?.headers);
574
+ headers.set("x-api-key", this.apiKey);
575
+ if (!options?.skipAuth && this.sessionToken) {
576
+ headers.set("Authorization", `Bearer ${this.sessionToken}`);
577
+ }
578
+ if (this.workspaceId) {
579
+ headers.set("x-sm-workspace-id", this.workspaceId);
580
+ }
581
+ if (!options?.skipAuth && !this.sessionToken && this.anonymousId) {
582
+ headers.set("x-anonymous-id", this.anonymousId);
583
+ }
584
+ if (!headers.has("Content-Type") && options?.body && typeof options.body === "string") {
585
+ headers.set("Content-Type", "application/json");
586
+ }
587
+ return headers;
588
+ }
589
+ /**
590
+ * Make an HTTP request to the ScaleMule API
591
+ */
592
+ async request(path, options = {}) {
593
+ if (this.sessionGate) {
594
+ await this.sessionGate;
595
+ }
596
+ if (!options.skipAuth && !this.sessionToken && !this.anonymousId) {
597
+ try {
598
+ await this.ensureAnonymousId();
599
+ } catch {
600
+ }
601
+ }
602
+ const url = `${this.gatewayUrl}${path}`;
603
+ const headers = this.buildHeaders(options);
604
+ const maxRetries = options.skipRetry ? 0 : options.retries ?? 2;
605
+ const timeout = options.timeout || 3e4;
606
+ if (this.debug) {
607
+ console.log(`[ScaleMule] ${options.method || "GET"} ${path}`);
608
+ }
609
+ let lastError = null;
610
+ const MAX_REFRESH_ATTEMPTS = 1;
611
+ let refreshAttempts = 0;
612
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
613
+ const controller = new AbortController();
614
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
615
+ try {
616
+ const response = await fetch(url, {
617
+ ...options,
618
+ headers,
619
+ signal: controller.signal
620
+ });
621
+ clearTimeout(timeoutId);
622
+ const rotatedToken = response.headers.get("x-rotated-session-token");
623
+ if (rotatedToken && this.sessionToken && this.userId) {
624
+ this.setSession(rotatedToken, this.userId);
625
+ }
626
+ const text = await response.text();
627
+ let responseData = null;
628
+ try {
629
+ responseData = text ? JSON.parse(text) : null;
630
+ } catch {
631
+ }
632
+ if (!response.ok || responseData?.success === false) {
633
+ const rawError = responseData?.error;
634
+ const baseError = rawError && typeof rawError === "object" ? rawError : { code: `HTTP_${response.status}`, message: typeof rawError === "string" ? rawError : responseData?.message || text || response.statusText };
635
+ const error = withErrorContext(baseError, responseData, response.headers);
636
+ if (response.status === 401 && this.sessionToken && !options.isAutoRefresh && refreshAttempts < MAX_REFRESH_ATTEMPTS) {
637
+ refreshAttempts++;
638
+ if (this.debug) console.log("[ScaleMule] 401 received, attempting auto-refresh...");
639
+ if (!this.refreshPromise) {
640
+ this.onRefreshStart?.();
641
+ this.refreshPromise = this.post("/api/auth/refresh", {}, { isAutoRefresh: true });
642
+ }
643
+ try {
644
+ await this.refreshPromise;
645
+ if (this.debug) console.log("[ScaleMule] Auto-refresh succeeded, retrying original request...");
646
+ attempt--;
647
+ if (this.sessionToken) {
648
+ headers.set("Authorization", `Bearer ${this.sessionToken}`);
649
+ }
650
+ continue;
651
+ } catch (refreshErr) {
652
+ if (this.debug) console.error("[ScaleMule] Auto-refresh failed:", refreshErr);
653
+ const refreshApiError = refreshErr instanceof ScaleMuleApiError ? { code: refreshErr.code, message: refreshErr.message, field: refreshErr.field } : { code: "REFRESH_FAILED", message: "Auto-refresh failed" };
654
+ this.onAutoRefreshFailed?.(refreshApiError);
655
+ throw new ScaleMuleApiError(error);
656
+ } finally {
657
+ this.refreshPromise = null;
658
+ this.onRefreshEnd?.();
659
+ }
660
+ }
661
+ if (attempt < maxRetries && RETRYABLE_STATUS_CODES.has(response.status)) {
662
+ lastError = error;
663
+ const delay = getBackoffDelay(attempt);
664
+ if (this.debug) {
665
+ console.log(`[ScaleMule] Retrying in ${delay}ms (attempt ${attempt + 1}/${maxRetries})`);
666
+ }
667
+ await sleep(delay);
668
+ continue;
669
+ }
670
+ if (this.debug) {
671
+ console.error("[ScaleMule] Request failed:", ["LOGIN_CHALLENGE_REQUIRED", "MFA_REQUIRED"].includes(error.code) ? error.code : error);
672
+ }
673
+ throw new ScaleMuleApiError(error);
674
+ }
675
+ const data = responseData?.data !== void 0 ? responseData.data : responseData;
676
+ return data;
677
+ } catch (err) {
678
+ clearTimeout(timeoutId);
679
+ if (err instanceof ScaleMuleApiError) {
680
+ throw err;
681
+ }
682
+ const error = {
683
+ code: err instanceof Error && err.name === "AbortError" ? "TIMEOUT" : "NETWORK_ERROR",
684
+ message: err instanceof Error ? err.message : "Network request failed"
685
+ };
686
+ if (attempt < maxRetries) {
687
+ lastError = error;
688
+ const delay = getBackoffDelay(attempt);
689
+ if (this.debug) {
690
+ console.log(`[ScaleMule] Retrying after error in ${delay}ms (attempt ${attempt + 1}/${maxRetries})`);
691
+ }
692
+ await sleep(delay);
693
+ continue;
694
+ }
695
+ if (this.debug) {
696
+ console.error("[ScaleMule] Network error:", err);
697
+ }
698
+ throw new ScaleMuleApiError(error);
699
+ }
700
+ }
701
+ throw new ScaleMuleApiError(lastError || { code: "UNKNOWN", message: "Request failed" });
702
+ }
703
+ /**
704
+ * GET request
705
+ */
706
+ async get(path, options) {
707
+ return this.request(path, { ...options, method: "GET" });
708
+ }
709
+ /**
710
+ * POST request with JSON body
711
+ */
712
+ async post(path, body, options) {
713
+ return this.request(path, {
714
+ ...options,
715
+ method: "POST",
716
+ body: body ? JSON.stringify(body) : void 0
717
+ });
718
+ }
719
+ /**
720
+ * PUT request with JSON body
721
+ */
722
+ async put(path, body, options) {
723
+ return this.request(path, {
724
+ ...options,
725
+ method: "PUT",
726
+ body: body ? JSON.stringify(body) : void 0
727
+ });
728
+ }
729
+ /**
730
+ * PATCH request with JSON body
731
+ */
732
+ async patch(path, body, options) {
733
+ return this.request(path, {
734
+ ...options,
735
+ method: "PATCH",
736
+ body: body ? JSON.stringify(body) : void 0
737
+ });
738
+ }
739
+ /**
740
+ * DELETE request
741
+ */
742
+ async delete(path, options) {
743
+ return this.request(path, { ...options, method: "DELETE" });
744
+ }
745
+ /**
746
+ * Upload a file using multipart/form-data
747
+ *
748
+ * Automatically includes Authorization: Bearer header for user identity.
749
+ * Supports progress callback via XMLHttpRequest when onProgress is provided.
750
+ */
751
+ async upload(path, file, additionalFields, options) {
752
+ const sanitizedName = sanitizeFilename(file.name);
753
+ const sanitizedFile = sanitizedName !== file.name ? new File([file], sanitizedName, { type: file.type }) : file;
754
+ const formData = new FormData();
755
+ formData.append("file", sanitizedFile);
756
+ if (this.userId) {
757
+ formData.append("sm_user_id", this.userId);
758
+ }
759
+ if (additionalFields) {
760
+ for (const [key, value] of Object.entries(additionalFields)) {
761
+ formData.append(key, value);
762
+ }
763
+ }
764
+ const url = `${this.gatewayUrl}${path}`;
765
+ if (this.debug) {
766
+ console.log(`[ScaleMule] UPLOAD ${path}`);
767
+ }
768
+ if (options?.onProgress && typeof XMLHttpRequest !== "undefined") {
769
+ return this.uploadWithProgress(url, formData, options.onProgress);
770
+ }
771
+ const maxRetries = options?.retries ?? 2;
772
+ const headers = new Headers();
773
+ headers.set("x-api-key", this.apiKey);
774
+ if (this.sessionToken) {
775
+ headers.set("Authorization", `Bearer ${this.sessionToken}`);
776
+ }
777
+ if (this.workspaceId) {
778
+ headers.set("x-sm-workspace-id", this.workspaceId);
779
+ }
780
+ let lastError = null;
781
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
782
+ try {
783
+ const retryFormData = attempt === 0 ? formData : new FormData();
784
+ if (attempt > 0) {
785
+ retryFormData.append("file", sanitizedFile);
786
+ if (this.userId) {
787
+ retryFormData.append("sm_user_id", this.userId);
788
+ }
789
+ if (additionalFields) {
790
+ for (const [key, value] of Object.entries(additionalFields)) {
791
+ retryFormData.append(key, value);
792
+ }
793
+ }
794
+ }
795
+ const response = await fetch(url, {
796
+ method: "POST",
797
+ headers,
798
+ body: retryFormData
799
+ });
800
+ const uploadText = await response.text();
801
+ let responseData = null;
802
+ try {
803
+ responseData = uploadText ? JSON.parse(uploadText) : null;
804
+ } catch {
805
+ }
806
+ if (!response.ok) {
807
+ const error = responseData?.error || {
808
+ code: `HTTP_${response.status}`,
809
+ message: responseData?.message || uploadText || response.statusText
810
+ };
811
+ if (attempt < maxRetries && RETRYABLE_STATUS_CODES.has(response.status)) {
812
+ lastError = error;
813
+ const delay = getBackoffDelay(attempt);
814
+ if (this.debug) {
815
+ console.log(`[ScaleMule] Upload retry ${attempt + 1}/${maxRetries} after ${delay}ms`);
816
+ }
817
+ await sleep(delay);
818
+ continue;
819
+ }
820
+ throw new ScaleMuleApiError(error);
821
+ }
822
+ const data = responseData?.data !== void 0 ? responseData.data : responseData;
823
+ return data;
824
+ } catch (err) {
825
+ if (err instanceof ScaleMuleApiError) {
826
+ throw err;
827
+ }
828
+ lastError = {
829
+ code: "UPLOAD_ERROR",
830
+ message: err instanceof Error ? err.message : "Upload failed"
831
+ };
832
+ if (attempt < maxRetries) {
833
+ const delay = getBackoffDelay(attempt);
834
+ if (this.debug) {
835
+ console.log(`[ScaleMule] Upload retry ${attempt + 1}/${maxRetries} after ${delay}ms (network error)`);
836
+ }
837
+ await sleep(delay);
838
+ continue;
839
+ }
840
+ }
841
+ }
842
+ throw new ScaleMuleApiError(lastError || { code: "UPLOAD_ERROR", message: "Upload failed after retries" });
843
+ }
844
+ /**
845
+ * Upload with progress using XMLHttpRequest (with retry)
846
+ */
847
+ async uploadWithProgress(url, formData, onProgress, maxRetries = 2) {
848
+ let lastError = null;
849
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
850
+ try {
851
+ return await this.singleUploadWithProgress(url, formData, onProgress);
852
+ } catch (err) {
853
+ if (!(err instanceof ScaleMuleApiError)) {
854
+ throw err;
855
+ }
856
+ const errorCode = err.code;
857
+ const isNetworkError = errorCode === "UPLOAD_ERROR" || errorCode === "NETWORK_ERROR";
858
+ const isRetryableHttp = errorCode.startsWith("HTTP_") && RETRYABLE_STATUS_CODES.has(parseInt(errorCode.replace("HTTP_", ""), 10));
859
+ if (attempt < maxRetries && (isNetworkError || isRetryableHttp)) {
860
+ lastError = { code: err.code, message: err.message };
861
+ const delay = getBackoffDelay(attempt);
862
+ if (this.debug) {
863
+ console.log(`[ScaleMule] Upload retry ${attempt + 1}/${maxRetries} after ${delay}ms`);
864
+ }
865
+ await sleep(delay);
866
+ onProgress(0);
867
+ continue;
868
+ }
869
+ throw err;
870
+ }
871
+ }
872
+ throw new ScaleMuleApiError(lastError || { code: "UPLOAD_ERROR", message: "Upload failed after retries" });
873
+ }
874
+ /**
875
+ * Single upload attempt with progress using XMLHttpRequest
876
+ */
877
+ singleUploadWithProgress(url, formData, onProgress) {
878
+ return new Promise((resolve, reject) => {
879
+ const xhr = new XMLHttpRequest();
880
+ xhr.upload.addEventListener("progress", (event) => {
881
+ if (event.lengthComputable) {
882
+ const progress = Math.round(event.loaded / event.total * 100);
883
+ onProgress(progress);
884
+ }
885
+ });
886
+ xhr.addEventListener("load", () => {
887
+ try {
888
+ let data = null;
889
+ try {
890
+ data = xhr.responseText ? JSON.parse(xhr.responseText) : null;
891
+ } catch {
892
+ }
893
+ if (xhr.status >= 200 && xhr.status < 300) {
894
+ const unwrapped = data?.data !== void 0 ? data.data : data;
895
+ resolve(unwrapped);
896
+ } else {
897
+ const uploadError = data?.error || {
898
+ code: `HTTP_${xhr.status}`,
899
+ message: data?.message || xhr.responseText || "Upload failed"
900
+ };
901
+ reject(
902
+ new ScaleMuleApiError(
903
+ withErrorContext(uploadError, data, {
904
+ get: (name) => xhr.getResponseHeader(name)
905
+ })
906
+ )
907
+ );
908
+ }
909
+ } catch {
910
+ reject(new ScaleMuleApiError({ code: "PARSE_ERROR", message: "Failed to parse response" }));
911
+ }
912
+ });
913
+ xhr.addEventListener("error", () => {
914
+ reject(new ScaleMuleApiError({ code: "UPLOAD_ERROR", message: "Upload failed" }));
915
+ });
916
+ xhr.addEventListener("abort", () => {
917
+ reject(new ScaleMuleApiError({ code: "UPLOAD_ABORTED", message: "Upload cancelled" }));
918
+ });
919
+ xhr.open("POST", url);
920
+ xhr.setRequestHeader("x-api-key", this.apiKey);
921
+ if (this.sessionToken) {
922
+ xhr.setRequestHeader("Authorization", `Bearer ${this.sessionToken}`);
923
+ }
924
+ if (this.workspaceId) {
925
+ xhr.setRequestHeader("x-sm-workspace-id", this.workspaceId);
926
+ }
927
+ xhr.send(formData);
928
+ });
929
+ }
930
+ };
931
+ function createClient(config) {
932
+ return new ScaleMuleClient(config);
933
+ }
934
+
935
+ export { ScaleMuleClient, createClient };