@djangocfg/api 2.1.87 → 2.1.88

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.
@@ -5,13 +5,13 @@ var __name = (target, value) => __defProp(target, "name", { value, configurable:
5
5
  import { NextResponse } from "next/server";
6
6
  function proxyMiddleware(request) {
7
7
  const { pathname, search } = request.nextUrl;
8
- const apiUrl = process.env.NEXT_PUBLIC_API_URL;
8
+ const apiUrl2 = process.env.NEXT_PUBLIC_API_URL;
9
9
  if (pathname.startsWith("/media/")) {
10
- const targetUrl = `${apiUrl}${pathname}${search}`;
10
+ const targetUrl = `${apiUrl2}${pathname}${search}`;
11
11
  return NextResponse.rewrite(targetUrl, { request: { headers: request.headers } });
12
12
  }
13
13
  if (pathname.startsWith("/api/")) {
14
- const targetUrl = `${apiUrl}${pathname}${search}`;
14
+ const targetUrl = `${apiUrl2}${pathname}${search}`;
15
15
  return NextResponse.rewrite(targetUrl, { request: { headers: request.headers } });
16
16
  }
17
17
  return NextResponse.next();
@@ -20,8 +20,1942 @@ __name(proxyMiddleware, "proxyMiddleware");
20
20
  var proxyMiddlewareConfig = {
21
21
  matcher: ["/media/:path*", "/api/:path*"]
22
22
  };
23
+
24
+ // src/generated/cfg_accounts/accounts__auth/client.ts
25
+ var Auth = class {
26
+ static {
27
+ __name(this, "Auth");
28
+ }
29
+ constructor(client) {
30
+ this.client = client;
31
+ }
32
+ /**
33
+ * Refresh JWT token.
34
+ */
35
+ async accountsTokenRefreshCreate(data) {
36
+ const response = await this.client.request("POST", "/cfg/accounts/token/refresh/", { body: data });
37
+ return response;
38
+ }
39
+ };
40
+
41
+ // src/generated/cfg_accounts/accounts__oauth/client.ts
42
+ var Oauth = class {
43
+ static {
44
+ __name(this, "Oauth");
45
+ }
46
+ constructor(client) {
47
+ this.client = client;
48
+ }
49
+ /**
50
+ * List OAuth connections
51
+ *
52
+ * Get all OAuth connections for the current user.
53
+ */
54
+ async accountsOauthConnectionsList() {
55
+ const response = await this.client.request("GET", "/cfg/accounts/oauth/connections/");
56
+ return response;
57
+ }
58
+ /**
59
+ * Disconnect OAuth provider
60
+ *
61
+ * Remove OAuth connection for the specified provider.
62
+ */
63
+ async accountsOauthDisconnectCreate(data) {
64
+ const response = await this.client.request("POST", "/cfg/accounts/oauth/disconnect/", { body: data });
65
+ return response;
66
+ }
67
+ /**
68
+ * Start GitHub OAuth
69
+ *
70
+ * Generate GitHub OAuth authorization URL. Redirect user to this URL to
71
+ * start authentication.
72
+ */
73
+ async accountsOauthGithubAuthorizeCreate(data) {
74
+ const response = await this.client.request("POST", "/cfg/accounts/oauth/github/authorize/", { body: data });
75
+ return response;
76
+ }
77
+ /**
78
+ * Complete GitHub OAuth
79
+ *
80
+ * Exchange authorization code for JWT tokens. Call this after GitHub
81
+ * redirects back with code.
82
+ */
83
+ async accountsOauthGithubCallbackCreate(data) {
84
+ const response = await this.client.request("POST", "/cfg/accounts/oauth/github/callback/", { body: data });
85
+ return response;
86
+ }
87
+ /**
88
+ * List OAuth providers
89
+ *
90
+ * Get list of available OAuth providers for authentication.
91
+ */
92
+ async accountsOauthProvidersRetrieve() {
93
+ const response = await this.client.request("GET", "/cfg/accounts/oauth/providers/");
94
+ return response;
95
+ }
96
+ };
97
+
98
+ // src/generated/cfg_accounts/accounts__user_profile/client.ts
99
+ var UserProfile = class {
100
+ static {
101
+ __name(this, "UserProfile");
102
+ }
103
+ constructor(client) {
104
+ this.client = client;
105
+ }
106
+ /**
107
+ * Get current user profile
108
+ *
109
+ * Retrieve the current authenticated user's profile information.
110
+ */
111
+ async accountsProfileRetrieve() {
112
+ const response = await this.client.request("GET", "/cfg/accounts/profile/");
113
+ return response;
114
+ }
115
+ /**
116
+ * Upload user avatar
117
+ *
118
+ * Upload avatar image for the current authenticated user. Accepts
119
+ * multipart/form-data with 'avatar' field.
120
+ */
121
+ async accountsProfileAvatarCreate(data) {
122
+ const response = await this.client.request("POST", "/cfg/accounts/profile/avatar/", { formData: data });
123
+ return response;
124
+ }
125
+ /**
126
+ * Partial update user profile
127
+ *
128
+ * Partially update the current authenticated user's profile information.
129
+ * Supports avatar upload.
130
+ */
131
+ async accountsProfilePartialUpdate(data) {
132
+ const response = await this.client.request("PUT", "/cfg/accounts/profile/partial/", { body: data });
133
+ return response;
134
+ }
135
+ /**
136
+ * Partial update user profile
137
+ *
138
+ * Partially update the current authenticated user's profile information.
139
+ * Supports avatar upload.
140
+ */
141
+ async accountsProfilePartialPartialUpdate(data) {
142
+ const response = await this.client.request("PATCH", "/cfg/accounts/profile/partial/", { body: data });
143
+ return response;
144
+ }
145
+ /**
146
+ * Update user profile
147
+ *
148
+ * Update the current authenticated user's profile information.
149
+ */
150
+ async accountsProfileUpdateUpdate(data) {
151
+ const response = await this.client.request("PUT", "/cfg/accounts/profile/update/", { body: data });
152
+ return response;
153
+ }
154
+ /**
155
+ * Update user profile
156
+ *
157
+ * Update the current authenticated user's profile information.
158
+ */
159
+ async accountsProfileUpdatePartialUpdate(data) {
160
+ const response = await this.client.request("PATCH", "/cfg/accounts/profile/update/", { body: data });
161
+ return response;
162
+ }
163
+ };
164
+
165
+ // src/generated/cfg_accounts/accounts/client.ts
166
+ var Accounts = class {
167
+ static {
168
+ __name(this, "Accounts");
169
+ }
170
+ constructor(client) {
171
+ this.client = client;
172
+ }
173
+ /**
174
+ * Request OTP code to email or phone.
175
+ */
176
+ async otpRequestCreate(data) {
177
+ const response = await this.client.request("POST", "/cfg/accounts/otp/request/", { body: data });
178
+ return response;
179
+ }
180
+ /**
181
+ * Verify OTP code and return JWT tokens or 2FA session. If user has 2FA
182
+ * enabled: - Returns requires_2fa=True with session_id - Client must
183
+ * complete 2FA verification at /cfg/totp/verify/ If user has no 2FA: -
184
+ * Returns JWT tokens and user data directly
185
+ */
186
+ async otpVerifyCreate(data) {
187
+ const response = await this.client.request("POST", "/cfg/accounts/otp/verify/", { body: data });
188
+ return response;
189
+ }
190
+ };
191
+
192
+ // src/generated/cfg_accounts/http.ts
193
+ var FetchAdapter = class {
194
+ static {
195
+ __name(this, "FetchAdapter");
196
+ }
197
+ async request(request) {
198
+ const { method, url, headers, body, params, formData, binaryBody } = request;
199
+ let finalUrl = url;
200
+ if (params) {
201
+ const searchParams = new URLSearchParams();
202
+ Object.entries(params).forEach(([key, value]) => {
203
+ if (value !== null && value !== void 0) {
204
+ searchParams.append(key, String(value));
205
+ }
206
+ });
207
+ const queryString = searchParams.toString();
208
+ if (queryString) {
209
+ finalUrl = url.includes("?") ? `${url}&${queryString}` : `${url}?${queryString}`;
210
+ }
211
+ }
212
+ const finalHeaders = { ...headers };
213
+ let requestBody;
214
+ if (formData) {
215
+ requestBody = formData;
216
+ } else if (binaryBody) {
217
+ finalHeaders["Content-Type"] = "application/octet-stream";
218
+ requestBody = binaryBody;
219
+ } else if (body) {
220
+ finalHeaders["Content-Type"] = "application/json";
221
+ requestBody = JSON.stringify(body);
222
+ }
223
+ const response = await fetch(finalUrl, {
224
+ method,
225
+ headers: finalHeaders,
226
+ body: requestBody,
227
+ credentials: "include"
228
+ // Include Django session cookies
229
+ });
230
+ let data = null;
231
+ const contentType = response.headers.get("content-type");
232
+ if (response.status !== 204 && contentType?.includes("application/json")) {
233
+ data = await response.json();
234
+ } else if (response.status !== 204) {
235
+ data = await response.text();
236
+ }
237
+ const responseHeaders = {};
238
+ response.headers.forEach((value, key) => {
239
+ responseHeaders[key] = value;
240
+ });
241
+ return {
242
+ data,
243
+ status: response.status,
244
+ statusText: response.statusText,
245
+ headers: responseHeaders
246
+ };
247
+ }
248
+ };
249
+
250
+ // src/generated/cfg_accounts/errors.ts
251
+ var APIError = class extends Error {
252
+ constructor(statusCode, statusText, response, url, message) {
253
+ super(message || `HTTP ${statusCode}: ${statusText}`);
254
+ this.statusCode = statusCode;
255
+ this.statusText = statusText;
256
+ this.response = response;
257
+ this.url = url;
258
+ this.name = "APIError";
259
+ }
260
+ static {
261
+ __name(this, "APIError");
262
+ }
263
+ /**
264
+ * Get error details from response.
265
+ * DRF typically returns: { "detail": "Error message" } or { "field": ["error1", "error2"] }
266
+ */
267
+ get details() {
268
+ if (typeof this.response === "object" && this.response !== null) {
269
+ return this.response;
270
+ }
271
+ return null;
272
+ }
273
+ /**
274
+ * Get field-specific validation errors from DRF.
275
+ * Returns: { "field_name": ["error1", "error2"], ... }
276
+ */
277
+ get fieldErrors() {
278
+ const details = this.details;
279
+ if (!details) return null;
280
+ const fieldErrors = {};
281
+ for (const [key, value] of Object.entries(details)) {
282
+ if (Array.isArray(value)) {
283
+ fieldErrors[key] = value;
284
+ }
285
+ }
286
+ return Object.keys(fieldErrors).length > 0 ? fieldErrors : null;
287
+ }
288
+ /**
289
+ * Get single error message from DRF.
290
+ * Checks for "detail", "message", or first field error.
291
+ */
292
+ get errorMessage() {
293
+ const details = this.details;
294
+ if (!details) return this.message;
295
+ if (details.detail) {
296
+ return Array.isArray(details.detail) ? details.detail.join(", ") : String(details.detail);
297
+ }
298
+ if (details.message) {
299
+ return String(details.message);
300
+ }
301
+ const fieldErrors = this.fieldErrors;
302
+ if (fieldErrors) {
303
+ const firstField = Object.keys(fieldErrors)[0];
304
+ if (firstField) {
305
+ return `${firstField}: ${fieldErrors[firstField]?.join(", ")}`;
306
+ }
307
+ }
308
+ return this.message;
309
+ }
310
+ // Helper methods for common HTTP status codes
311
+ get isValidationError() {
312
+ return this.statusCode === 400;
313
+ }
314
+ get isAuthError() {
315
+ return this.statusCode === 401;
316
+ }
317
+ get isPermissionError() {
318
+ return this.statusCode === 403;
319
+ }
320
+ get isNotFoundError() {
321
+ return this.statusCode === 404;
322
+ }
323
+ get isServerError() {
324
+ return this.statusCode >= 500 && this.statusCode < 600;
325
+ }
326
+ };
327
+ var NetworkError = class extends Error {
328
+ constructor(message, url, originalError) {
329
+ super(message);
330
+ this.url = url;
331
+ this.originalError = originalError;
332
+ this.name = "NetworkError";
333
+ }
334
+ static {
335
+ __name(this, "NetworkError");
336
+ }
337
+ };
338
+
339
+ // src/generated/cfg_accounts/logger.ts
340
+ import { createConsola } from "consola";
341
+ var DEFAULT_CONFIG = {
342
+ enabled: process.env.NODE_ENV !== "production",
343
+ logRequests: true,
344
+ logResponses: true,
345
+ logErrors: true,
346
+ logBodies: true,
347
+ logHeaders: false
348
+ };
349
+ var SENSITIVE_HEADERS = [
350
+ "authorization",
351
+ "cookie",
352
+ "set-cookie",
353
+ "x-api-key",
354
+ "x-csrf-token"
355
+ ];
356
+ var APILogger = class {
357
+ static {
358
+ __name(this, "APILogger");
359
+ }
360
+ constructor(config = {}) {
361
+ this.config = { ...DEFAULT_CONFIG, ...config };
362
+ this.consola = config.consola || createConsola({
363
+ level: this.config.enabled ? 4 : 0
364
+ });
365
+ }
366
+ /**
367
+ * Enable logging
368
+ */
369
+ enable() {
370
+ this.config.enabled = true;
371
+ }
372
+ /**
373
+ * Disable logging
374
+ */
375
+ disable() {
376
+ this.config.enabled = false;
377
+ }
378
+ /**
379
+ * Update configuration
380
+ */
381
+ setConfig(config) {
382
+ this.config = { ...this.config, ...config };
383
+ }
384
+ /**
385
+ * Filter sensitive headers
386
+ */
387
+ filterHeaders(headers) {
388
+ if (!headers) return {};
389
+ const filtered = {};
390
+ Object.keys(headers).forEach((key) => {
391
+ const lowerKey = key.toLowerCase();
392
+ if (SENSITIVE_HEADERS.includes(lowerKey)) {
393
+ filtered[key] = "***";
394
+ } else {
395
+ filtered[key] = headers[key] || "";
396
+ }
397
+ });
398
+ return filtered;
399
+ }
400
+ /**
401
+ * Log request
402
+ */
403
+ logRequest(request) {
404
+ if (!this.config.enabled || !this.config.logRequests) return;
405
+ const { method, url, headers, body } = request;
406
+ this.consola.start(`${method} ${url}`);
407
+ if (this.config.logHeaders && headers) {
408
+ this.consola.debug("Headers:", this.filterHeaders(headers));
409
+ }
410
+ if (this.config.logBodies && body) {
411
+ this.consola.debug("Body:", body);
412
+ }
413
+ }
414
+ /**
415
+ * Log response
416
+ */
417
+ logResponse(request, response) {
418
+ if (!this.config.enabled || !this.config.logResponses) return;
419
+ const { method, url } = request;
420
+ const { status, statusText, data, duration } = response;
421
+ const statusColor = status >= 500 ? "red" : status >= 400 ? "yellow" : status >= 300 ? "cyan" : "green";
422
+ this.consola.success(
423
+ `${method} ${url} ${status} ${statusText} (${duration}ms)`
424
+ );
425
+ if (this.config.logBodies && data) {
426
+ this.consola.debug("Response:", data);
427
+ }
428
+ }
429
+ /**
430
+ * Log error
431
+ */
432
+ logError(request, error) {
433
+ if (!this.config.enabled || !this.config.logErrors) return;
434
+ const { method, url } = request;
435
+ const { message, statusCode, fieldErrors, duration } = error;
436
+ this.consola.error(
437
+ `${method} ${url} ${statusCode || "Network"} Error (${duration}ms)`
438
+ );
439
+ this.consola.error("Message:", message);
440
+ if (fieldErrors && Object.keys(fieldErrors).length > 0) {
441
+ this.consola.error("Field Errors:");
442
+ Object.entries(fieldErrors).forEach(([field, errors]) => {
443
+ errors.forEach((err) => {
444
+ this.consola.error(` \u2022 ${field}: ${err}`);
445
+ });
446
+ });
447
+ }
448
+ }
449
+ /**
450
+ * Log general info
451
+ */
452
+ info(message, ...args) {
453
+ if (!this.config.enabled) return;
454
+ this.consola.info(message, ...args);
455
+ }
456
+ /**
457
+ * Log warning
458
+ */
459
+ warn(message, ...args) {
460
+ if (!this.config.enabled) return;
461
+ this.consola.warn(message, ...args);
462
+ }
463
+ /**
464
+ * Log error
465
+ */
466
+ error(message, ...args) {
467
+ if (!this.config.enabled) return;
468
+ this.consola.error(message, ...args);
469
+ }
470
+ /**
471
+ * Log debug
472
+ */
473
+ debug(message, ...args) {
474
+ if (!this.config.enabled) return;
475
+ this.consola.debug(message, ...args);
476
+ }
477
+ /**
478
+ * Log success
479
+ */
480
+ success(message, ...args) {
481
+ if (!this.config.enabled) return;
482
+ this.consola.success(message, ...args);
483
+ }
484
+ /**
485
+ * Create a sub-logger with prefix
486
+ */
487
+ withTag(tag) {
488
+ return this.consola.withTag(tag);
489
+ }
490
+ };
491
+ var defaultLogger = new APILogger();
492
+
493
+ // src/generated/cfg_accounts/retry.ts
494
+ import pRetry, { AbortError } from "p-retry";
495
+ var DEFAULT_RETRY_CONFIG = {
496
+ retries: 3,
497
+ factor: 2,
498
+ minTimeout: 1e3,
499
+ maxTimeout: 6e4,
500
+ randomize: true,
501
+ onFailedAttempt: /* @__PURE__ */ __name(() => {
502
+ }, "onFailedAttempt")
503
+ };
504
+ function shouldRetry(error) {
505
+ if (error instanceof NetworkError) {
506
+ return true;
507
+ }
508
+ if (error instanceof APIError) {
509
+ const status = error.statusCode;
510
+ if (status >= 500 && status < 600) {
511
+ return true;
512
+ }
513
+ if (status === 429) {
514
+ return true;
515
+ }
516
+ return false;
517
+ }
518
+ return true;
519
+ }
520
+ __name(shouldRetry, "shouldRetry");
521
+ async function withRetry(fn, config) {
522
+ const finalConfig = { ...DEFAULT_RETRY_CONFIG, ...config };
523
+ return pRetry(
524
+ async () => {
525
+ try {
526
+ return await fn();
527
+ } catch (error) {
528
+ if (!shouldRetry(error)) {
529
+ throw new AbortError(error);
530
+ }
531
+ throw error;
532
+ }
533
+ },
534
+ {
535
+ retries: finalConfig.retries,
536
+ factor: finalConfig.factor,
537
+ minTimeout: finalConfig.minTimeout,
538
+ maxTimeout: finalConfig.maxTimeout,
539
+ randomize: finalConfig.randomize,
540
+ onFailedAttempt: finalConfig.onFailedAttempt ? (error) => {
541
+ const pRetryError = error;
542
+ finalConfig.onFailedAttempt({
543
+ error: pRetryError,
544
+ attemptNumber: pRetryError.attemptNumber,
545
+ retriesLeft: pRetryError.retriesLeft
546
+ });
547
+ } : void 0
548
+ }
549
+ );
550
+ }
551
+ __name(withRetry, "withRetry");
552
+
553
+ // src/generated/cfg_accounts/client.ts
554
+ var APIClient = class {
555
+ constructor(baseUrl, options) {
556
+ this.logger = null;
557
+ this.retryConfig = null;
558
+ this.baseUrl = baseUrl.replace(/\/$/, "");
559
+ this.httpClient = options?.httpClient || new FetchAdapter();
560
+ if (options?.loggerConfig !== void 0) {
561
+ this.logger = new APILogger(options.loggerConfig);
562
+ }
563
+ if (options?.retryConfig !== void 0) {
564
+ this.retryConfig = options.retryConfig;
565
+ }
566
+ this.auth = new Auth(this);
567
+ this.oauth = new Oauth(this);
568
+ this.user_profile = new UserProfile(this);
569
+ this.accounts = new Accounts(this);
570
+ }
571
+ static {
572
+ __name(this, "APIClient");
573
+ }
574
+ /**
575
+ * Get CSRF token from cookies (for SessionAuthentication).
576
+ *
577
+ * Returns null if cookie doesn't exist (JWT-only auth).
578
+ */
579
+ getCsrfToken() {
580
+ const name = "csrftoken";
581
+ const value = `; ${document.cookie}`;
582
+ const parts = value.split(`; ${name}=`);
583
+ if (parts.length === 2) {
584
+ return parts.pop()?.split(";").shift() || null;
585
+ }
586
+ return null;
587
+ }
588
+ /**
589
+ * Make HTTP request with Django CSRF and session handling.
590
+ * Automatically retries on network errors and 5xx server errors.
591
+ */
592
+ async request(method, path, options) {
593
+ if (this.retryConfig) {
594
+ return withRetry(() => this._makeRequest(method, path, options), {
595
+ ...this.retryConfig,
596
+ onFailedAttempt: /* @__PURE__ */ __name((info) => {
597
+ if (this.logger) {
598
+ this.logger.warn(
599
+ `Retry attempt ${info.attemptNumber}/${info.retriesLeft + info.attemptNumber} for ${method} ${path}: ${info.error.message}`
600
+ );
601
+ }
602
+ this.retryConfig?.onFailedAttempt?.(info);
603
+ }, "onFailedAttempt")
604
+ });
605
+ }
606
+ return this._makeRequest(method, path, options);
607
+ }
608
+ /**
609
+ * Internal request method (without retry wrapper).
610
+ * Used by request() method with optional retry logic.
611
+ */
612
+ async _makeRequest(method, path, options) {
613
+ const url = this.baseUrl ? `${this.baseUrl}${path}` : path;
614
+ const startTime = Date.now();
615
+ const headers = {
616
+ ...options?.headers || {}
617
+ };
618
+ if (!options?.formData && !options?.binaryBody && !headers["Content-Type"]) {
619
+ headers["Content-Type"] = "application/json";
620
+ }
621
+ if (this.logger) {
622
+ this.logger.logRequest({
623
+ method,
624
+ url,
625
+ headers,
626
+ body: options?.formData || options?.body,
627
+ timestamp: startTime
628
+ });
629
+ }
630
+ try {
631
+ const response = await this.httpClient.request({
632
+ method,
633
+ url,
634
+ headers,
635
+ params: options?.params,
636
+ body: options?.body,
637
+ formData: options?.formData,
638
+ binaryBody: options?.binaryBody
639
+ });
640
+ const duration = Date.now() - startTime;
641
+ if (response.status >= 400) {
642
+ const error = new APIError(
643
+ response.status,
644
+ response.statusText,
645
+ response.data,
646
+ url
647
+ );
648
+ if (this.logger) {
649
+ this.logger.logError(
650
+ {
651
+ method,
652
+ url,
653
+ headers,
654
+ body: options?.formData || options?.body,
655
+ timestamp: startTime
656
+ },
657
+ {
658
+ message: error.message,
659
+ statusCode: response.status,
660
+ duration,
661
+ timestamp: Date.now()
662
+ }
663
+ );
664
+ }
665
+ throw error;
666
+ }
667
+ if (this.logger) {
668
+ this.logger.logResponse(
669
+ {
670
+ method,
671
+ url,
672
+ headers,
673
+ body: options?.formData || options?.body,
674
+ timestamp: startTime
675
+ },
676
+ {
677
+ status: response.status,
678
+ statusText: response.statusText,
679
+ data: response.data,
680
+ duration,
681
+ timestamp: Date.now()
682
+ }
683
+ );
684
+ }
685
+ return response.data;
686
+ } catch (error) {
687
+ const duration = Date.now() - startTime;
688
+ if (error instanceof APIError) {
689
+ throw error;
690
+ }
691
+ const isCORSError = error instanceof TypeError && (error.message.toLowerCase().includes("cors") || error.message.toLowerCase().includes("failed to fetch") || error.message.toLowerCase().includes("network request failed"));
692
+ if (this.logger) {
693
+ if (isCORSError) {
694
+ this.logger.error(`\u{1F6AB} CORS Error: ${method} ${url}`);
695
+ this.logger.error(` \u2192 ${error instanceof Error ? error.message : String(error)}`);
696
+ this.logger.error(` \u2192 Configure security_domains parameter on the server`);
697
+ } else {
698
+ this.logger.error(`\u26A0\uFE0F Network Error: ${method} ${url}`);
699
+ this.logger.error(` \u2192 ${error instanceof Error ? error.message : String(error)}`);
700
+ }
701
+ }
702
+ if (typeof window !== "undefined") {
703
+ try {
704
+ if (isCORSError) {
705
+ window.dispatchEvent(new CustomEvent("cors-error", {
706
+ detail: {
707
+ url,
708
+ method,
709
+ error: error instanceof Error ? error.message : String(error),
710
+ timestamp: /* @__PURE__ */ new Date()
711
+ },
712
+ bubbles: true,
713
+ cancelable: false
714
+ }));
715
+ } else {
716
+ window.dispatchEvent(new CustomEvent("network-error", {
717
+ detail: {
718
+ url,
719
+ method,
720
+ error: error instanceof Error ? error.message : String(error),
721
+ timestamp: /* @__PURE__ */ new Date()
722
+ },
723
+ bubbles: true,
724
+ cancelable: false
725
+ }));
726
+ }
727
+ } catch (eventError) {
728
+ }
729
+ }
730
+ const networkError = error instanceof Error ? new NetworkError(error.message, url, error) : new NetworkError("Unknown error", url);
731
+ if (this.logger) {
732
+ this.logger.logError(
733
+ {
734
+ method,
735
+ url,
736
+ headers,
737
+ body: options?.formData || options?.body,
738
+ timestamp: startTime
739
+ },
740
+ {
741
+ message: networkError.message,
742
+ duration,
743
+ timestamp: Date.now()
744
+ }
745
+ );
746
+ }
747
+ throw networkError;
748
+ }
749
+ }
750
+ };
751
+
752
+ // src/generated/cfg_accounts/storage.ts
753
+ var LocalStorageAdapter = class {
754
+ static {
755
+ __name(this, "LocalStorageAdapter");
756
+ }
757
+ constructor(logger2) {
758
+ this.logger = logger2;
759
+ }
760
+ getItem(key) {
761
+ try {
762
+ if (typeof window !== "undefined" && window.localStorage) {
763
+ const value = localStorage.getItem(key);
764
+ this.logger?.debug(`LocalStorage.getItem("${key}"): ${value ? "found" : "not found"}`);
765
+ return value;
766
+ }
767
+ this.logger?.warn("LocalStorage not available: window.localStorage is undefined");
768
+ } catch (error) {
769
+ this.logger?.error("LocalStorage.getItem failed:", error);
770
+ }
771
+ return null;
772
+ }
773
+ setItem(key, value) {
774
+ try {
775
+ if (typeof window !== "undefined" && window.localStorage) {
776
+ localStorage.setItem(key, value);
777
+ this.logger?.debug(`LocalStorage.setItem("${key}"): success`);
778
+ } else {
779
+ this.logger?.warn("LocalStorage not available: window.localStorage is undefined");
780
+ }
781
+ } catch (error) {
782
+ this.logger?.error("LocalStorage.setItem failed:", error);
783
+ }
784
+ }
785
+ removeItem(key) {
786
+ try {
787
+ if (typeof window !== "undefined" && window.localStorage) {
788
+ localStorage.removeItem(key);
789
+ this.logger?.debug(`LocalStorage.removeItem("${key}"): success`);
790
+ } else {
791
+ this.logger?.warn("LocalStorage not available: window.localStorage is undefined");
792
+ }
793
+ } catch (error) {
794
+ this.logger?.error("LocalStorage.removeItem failed:", error);
795
+ }
796
+ }
797
+ };
798
+
799
+ // src/generated/cfg_accounts/enums.ts
800
+ var OAuthConnectionProvider = /* @__PURE__ */ ((OAuthConnectionProvider2) => {
801
+ OAuthConnectionProvider2["GITHUB"] = "github";
802
+ return OAuthConnectionProvider2;
803
+ })(OAuthConnectionProvider || {});
804
+ var OAuthDisconnectRequestRequestProvider = /* @__PURE__ */ ((OAuthDisconnectRequestRequestProvider2) => {
805
+ OAuthDisconnectRequestRequestProvider2["GITHUB"] = "github";
806
+ return OAuthDisconnectRequestRequestProvider2;
807
+ })(OAuthDisconnectRequestRequestProvider || {});
808
+ var OTPRequestRequestChannel = /* @__PURE__ */ ((OTPRequestRequestChannel2) => {
809
+ OTPRequestRequestChannel2["EMAIL"] = "email";
810
+ OTPRequestRequestChannel2["PHONE"] = "phone";
811
+ return OTPRequestRequestChannel2;
812
+ })(OTPRequestRequestChannel || {});
813
+ var OTPVerifyRequestChannel = /* @__PURE__ */ ((OTPVerifyRequestChannel2) => {
814
+ OTPVerifyRequestChannel2["EMAIL"] = "email";
815
+ OTPVerifyRequestChannel2["PHONE"] = "phone";
816
+ return OTPVerifyRequestChannel2;
817
+ })(OTPVerifyRequestChannel || {});
818
+
819
+ // src/generated/cfg_accounts/_utils/schemas/CentrifugoToken.schema.ts
820
+ import { z } from "zod";
821
+ var CentrifugoTokenSchema = z.object({
822
+ token: z.string(),
823
+ centrifugo_url: z.union([z.url(), z.literal("")]),
824
+ expires_at: z.iso.datetime(),
825
+ channels: z.array(z.string())
826
+ });
827
+
828
+ // src/generated/cfg_accounts/_utils/schemas/OAuthAuthorizeRequestRequest.schema.ts
829
+ import { z as z2 } from "zod";
830
+ var OAuthAuthorizeRequestRequestSchema = z2.object({
831
+ redirect_uri: z2.union([z2.url(), z2.literal("")]).optional(),
832
+ source_url: z2.union([z2.url(), z2.literal("")]).optional()
833
+ });
834
+
835
+ // src/generated/cfg_accounts/_utils/schemas/OAuthAuthorizeResponse.schema.ts
836
+ import { z as z3 } from "zod";
837
+ var OAuthAuthorizeResponseSchema = z3.object({
838
+ authorization_url: z3.union([z3.url(), z3.literal("")]),
839
+ state: z3.string()
840
+ });
841
+
842
+ // src/generated/cfg_accounts/_utils/schemas/OAuthCallbackRequestRequest.schema.ts
843
+ import { z as z4 } from "zod";
844
+ var OAuthCallbackRequestRequestSchema = z4.object({
845
+ code: z4.string().min(10).max(500),
846
+ state: z4.string().min(20).max(100),
847
+ redirect_uri: z4.union([z4.url(), z4.literal("")]).optional()
848
+ });
849
+
850
+ // src/generated/cfg_accounts/_utils/schemas/OAuthConnection.schema.ts
851
+ import { z as z5 } from "zod";
852
+ var OAuthConnectionSchema = z5.object({
853
+ id: z5.int(),
854
+ provider: z5.nativeEnum(OAuthConnectionProvider),
855
+ provider_display: z5.string(),
856
+ provider_username: z5.string(),
857
+ provider_email: z5.email(),
858
+ provider_avatar_url: z5.union([z5.url(), z5.literal("")]),
859
+ connected_at: z5.iso.datetime(),
860
+ last_login_at: z5.iso.datetime()
861
+ });
862
+
863
+ // src/generated/cfg_accounts/_utils/schemas/OAuthDisconnectRequestRequest.schema.ts
864
+ import { z as z6 } from "zod";
865
+ var OAuthDisconnectRequestRequestSchema = z6.object({
866
+ provider: z6.nativeEnum(OAuthDisconnectRequestRequestProvider)
867
+ });
868
+
869
+ // src/generated/cfg_accounts/_utils/schemas/OAuthError.schema.ts
870
+ import { z as z7 } from "zod";
871
+ var OAuthErrorSchema = z7.object({
872
+ error: z7.string(),
873
+ error_description: z7.string().optional()
874
+ });
875
+
876
+ // src/generated/cfg_accounts/_utils/schemas/OAuthProvidersResponse.schema.ts
877
+ import { z as z8 } from "zod";
878
+ var OAuthProvidersResponseSchema = z8.object({
879
+ providers: z8.array(z8.record(z8.string(), z8.any()))
880
+ });
881
+
882
+ // src/generated/cfg_accounts/_utils/schemas/OAuthTokenResponse.schema.ts
883
+ import { z as z9 } from "zod";
884
+ var OAuthTokenResponseSchema = z9.object({
885
+ requires_2fa: z9.boolean().optional(),
886
+ session_id: z9.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i).nullable().optional(),
887
+ access: z9.string().nullable().optional(),
888
+ refresh: z9.string().nullable().optional(),
889
+ user: z9.record(z9.string(), z9.any()).nullable().optional(),
890
+ is_new_user: z9.boolean(),
891
+ is_new_connection: z9.boolean(),
892
+ should_prompt_2fa: z9.boolean().optional()
893
+ });
894
+
895
+ // src/generated/cfg_accounts/_utils/schemas/OTPErrorResponse.schema.ts
896
+ import { z as z10 } from "zod";
897
+ var OTPErrorResponseSchema = z10.object({
898
+ error: z10.string()
899
+ });
900
+
901
+ // src/generated/cfg_accounts/_utils/schemas/OTPRequestRequest.schema.ts
902
+ import { z as z11 } from "zod";
903
+ var OTPRequestRequestSchema = z11.object({
904
+ identifier: z11.string().min(1),
905
+ channel: z11.nativeEnum(OTPRequestRequestChannel).optional(),
906
+ source_url: z11.union([z11.url(), z11.literal("")]).optional()
907
+ });
908
+
909
+ // src/generated/cfg_accounts/_utils/schemas/OTPRequestResponse.schema.ts
910
+ import { z as z12 } from "zod";
911
+ var OTPRequestResponseSchema = z12.object({
912
+ message: z12.string()
913
+ });
914
+
915
+ // src/generated/cfg_accounts/_utils/schemas/OTPVerifyRequest.schema.ts
916
+ import { z as z13 } from "zod";
917
+ var OTPVerifyRequestSchema = z13.object({
918
+ identifier: z13.string().min(1),
919
+ otp: z13.string().min(6).max(6),
920
+ channel: z13.nativeEnum(OTPVerifyRequestChannel).optional(),
921
+ source_url: z13.union([z13.url(), z13.literal("")]).optional()
922
+ });
923
+
924
+ // src/generated/cfg_accounts/_utils/schemas/OTPVerifyResponse.schema.ts
925
+ import { z as z15 } from "zod";
926
+
927
+ // src/generated/cfg_accounts/_utils/schemas/User.schema.ts
928
+ import { z as z14 } from "zod";
929
+ var UserSchema = z14.object({
930
+ id: z14.int(),
931
+ email: z14.email(),
932
+ first_name: z14.string().max(50).optional(),
933
+ last_name: z14.string().max(50).optional(),
934
+ full_name: z14.string(),
935
+ initials: z14.string(),
936
+ display_username: z14.string(),
937
+ company: z14.string().max(100).optional(),
938
+ phone: z14.string().max(20).optional(),
939
+ position: z14.string().max(100).optional(),
940
+ avatar: z14.union([z14.url(), z14.literal("")]).nullable(),
941
+ is_staff: z14.boolean(),
942
+ is_superuser: z14.boolean(),
943
+ date_joined: z14.iso.datetime(),
944
+ last_login: z14.iso.datetime().nullable(),
945
+ unanswered_messages_count: z14.int(),
946
+ centrifugo: CentrifugoTokenSchema.nullable()
947
+ });
948
+
949
+ // src/generated/cfg_accounts/_utils/schemas/OTPVerifyResponse.schema.ts
950
+ var OTPVerifyResponseSchema = z15.object({
951
+ requires_2fa: z15.boolean().optional(),
952
+ session_id: z15.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i).nullable().optional(),
953
+ refresh: z15.string().nullable().optional(),
954
+ access: z15.string().nullable().optional(),
955
+ user: UserSchema.nullable().optional(),
956
+ should_prompt_2fa: z15.boolean().optional()
957
+ });
958
+
959
+ // src/generated/cfg_accounts/_utils/schemas/PatchedUserProfileUpdateRequest.schema.ts
960
+ import { z as z16 } from "zod";
961
+ var PatchedUserProfileUpdateRequestSchema = z16.object({
962
+ first_name: z16.string().max(50).optional(),
963
+ last_name: z16.string().max(50).optional(),
964
+ company: z16.string().max(100).optional(),
965
+ phone: z16.string().max(20).optional(),
966
+ position: z16.string().max(100).optional()
967
+ });
968
+
969
+ // src/generated/cfg_accounts/_utils/schemas/TokenRefresh.schema.ts
970
+ import { z as z17 } from "zod";
971
+ var TokenRefreshSchema = z17.object({
972
+ access: z17.string(),
973
+ refresh: z17.string()
974
+ });
975
+
976
+ // src/generated/cfg_accounts/_utils/schemas/TokenRefreshRequest.schema.ts
977
+ import { z as z18 } from "zod";
978
+ var TokenRefreshRequestSchema = z18.object({
979
+ refresh: z18.string().min(1)
980
+ });
981
+
982
+ // src/generated/cfg_accounts/_utils/schemas/UserProfileUpdateRequest.schema.ts
983
+ import { z as z19 } from "zod";
984
+ var UserProfileUpdateRequestSchema = z19.object({
985
+ first_name: z19.string().max(50).optional(),
986
+ last_name: z19.string().max(50).optional(),
987
+ company: z19.string().max(100).optional(),
988
+ phone: z19.string().max(20).optional(),
989
+ position: z19.string().max(100).optional()
990
+ });
991
+
992
+ // src/generated/cfg_accounts/_utils/fetchers/accounts.ts
993
+ import { consola } from "consola";
994
+
995
+ // src/generated/cfg_accounts/_utils/fetchers/accounts__auth.ts
996
+ import { consola as consola2 } from "consola";
997
+
998
+ // src/generated/cfg_accounts/_utils/fetchers/accounts__oauth.ts
999
+ import { consola as consola3 } from "consola";
1000
+
1001
+ // src/generated/cfg_accounts/_utils/fetchers/accounts__user_profile.ts
1002
+ import { consola as consola4 } from "consola";
1003
+
1004
+ // src/generated/cfg_accounts/index.ts
1005
+ var TOKEN_KEY = "auth_token";
1006
+ var REFRESH_TOKEN_KEY = "refresh_token";
1007
+ var API = class {
1008
+ constructor(baseUrl, options) {
1009
+ this._token = null;
1010
+ this._refreshToken = null;
1011
+ this.baseUrl = baseUrl;
1012
+ this.options = options;
1013
+ const logger2 = options?.loggerConfig ? new APILogger(options.loggerConfig) : void 0;
1014
+ this.storage = options?.storage || new LocalStorageAdapter(logger2);
1015
+ this._loadTokensFromStorage();
1016
+ this._client = new APIClient(this.baseUrl, {
1017
+ retryConfig: this.options?.retryConfig,
1018
+ loggerConfig: this.options?.loggerConfig
1019
+ });
1020
+ this._injectAuthHeader();
1021
+ this.auth = this._client.auth;
1022
+ this.oauth = this._client.oauth;
1023
+ this.user_profile = this._client.user_profile;
1024
+ this.accounts = this._client.accounts;
1025
+ }
1026
+ static {
1027
+ __name(this, "API");
1028
+ }
1029
+ _loadTokensFromStorage() {
1030
+ this._token = this.storage.getItem(TOKEN_KEY);
1031
+ this._refreshToken = this.storage.getItem(REFRESH_TOKEN_KEY);
1032
+ }
1033
+ _reinitClients() {
1034
+ this._client = new APIClient(this.baseUrl, {
1035
+ retryConfig: this.options?.retryConfig,
1036
+ loggerConfig: this.options?.loggerConfig
1037
+ });
1038
+ this._injectAuthHeader();
1039
+ this.auth = this._client.auth;
1040
+ this.oauth = this._client.oauth;
1041
+ this.user_profile = this._client.user_profile;
1042
+ this.accounts = this._client.accounts;
1043
+ }
1044
+ _injectAuthHeader() {
1045
+ const originalRequest = this._client.request.bind(this._client);
1046
+ this._client.request = async (method, path, options) => {
1047
+ const token = this.getToken();
1048
+ const mergedOptions = {
1049
+ ...options,
1050
+ headers: {
1051
+ ...options?.headers || {},
1052
+ ...token ? { "Authorization": `Bearer ${token}` } : {}
1053
+ }
1054
+ };
1055
+ return originalRequest(method, path, mergedOptions);
1056
+ };
1057
+ }
1058
+ /**
1059
+ * Get current JWT token
1060
+ */
1061
+ getToken() {
1062
+ return this.storage.getItem(TOKEN_KEY);
1063
+ }
1064
+ /**
1065
+ * Get current refresh token
1066
+ */
1067
+ getRefreshToken() {
1068
+ return this.storage.getItem(REFRESH_TOKEN_KEY);
1069
+ }
1070
+ /**
1071
+ * Set JWT token and refresh token
1072
+ * @param token - JWT access token
1073
+ * @param refreshToken - JWT refresh token (optional)
1074
+ */
1075
+ setToken(token, refreshToken) {
1076
+ this._token = token;
1077
+ this.storage.setItem(TOKEN_KEY, token);
1078
+ if (refreshToken) {
1079
+ this._refreshToken = refreshToken;
1080
+ this.storage.setItem(REFRESH_TOKEN_KEY, refreshToken);
1081
+ }
1082
+ this._reinitClients();
1083
+ }
1084
+ /**
1085
+ * Clear all tokens
1086
+ */
1087
+ clearTokens() {
1088
+ this._token = null;
1089
+ this._refreshToken = null;
1090
+ this.storage.removeItem(TOKEN_KEY);
1091
+ this.storage.removeItem(REFRESH_TOKEN_KEY);
1092
+ this._reinitClients();
1093
+ }
1094
+ /**
1095
+ * Check if user is authenticated
1096
+ */
1097
+ isAuthenticated() {
1098
+ return !!this.getToken();
1099
+ }
1100
+ /**
1101
+ * Update base URL and reinitialize clients
1102
+ * @param url - New base URL
1103
+ */
1104
+ setBaseUrl(url) {
1105
+ this.baseUrl = url;
1106
+ this._reinitClients();
1107
+ }
1108
+ /**
1109
+ * Get current base URL
1110
+ */
1111
+ getBaseUrl() {
1112
+ return this.baseUrl;
1113
+ }
1114
+ /**
1115
+ * Get OpenAPI schema path
1116
+ * @returns Path to the OpenAPI schema JSON file
1117
+ *
1118
+ * Note: The OpenAPI schema is available in the schema.json file.
1119
+ * You can load it dynamically using:
1120
+ * ```typescript
1121
+ * const schema = await fetch('./schema.json').then(r => r.json());
1122
+ * // or using fs in Node.js:
1123
+ * // const schema = JSON.parse(fs.readFileSync('./schema.json', 'utf-8'));
1124
+ * ```
1125
+ */
1126
+ getSchemaPath() {
1127
+ return "./schema.json";
1128
+ }
1129
+ };
1130
+
1131
+ // src/generated/cfg_centrifugo/logger.ts
1132
+ import { createConsola as createConsola2 } from "consola";
1133
+ var DEFAULT_CONFIG2 = {
1134
+ enabled: process.env.NODE_ENV !== "production",
1135
+ logRequests: true,
1136
+ logResponses: true,
1137
+ logErrors: true,
1138
+ logBodies: true,
1139
+ logHeaders: false
1140
+ };
1141
+ var SENSITIVE_HEADERS2 = [
1142
+ "authorization",
1143
+ "cookie",
1144
+ "set-cookie",
1145
+ "x-api-key",
1146
+ "x-csrf-token"
1147
+ ];
1148
+ var APILogger2 = class {
1149
+ static {
1150
+ __name(this, "APILogger");
1151
+ }
1152
+ constructor(config = {}) {
1153
+ this.config = { ...DEFAULT_CONFIG2, ...config };
1154
+ this.consola = config.consola || createConsola2({
1155
+ level: this.config.enabled ? 4 : 0
1156
+ });
1157
+ }
1158
+ /**
1159
+ * Enable logging
1160
+ */
1161
+ enable() {
1162
+ this.config.enabled = true;
1163
+ }
1164
+ /**
1165
+ * Disable logging
1166
+ */
1167
+ disable() {
1168
+ this.config.enabled = false;
1169
+ }
1170
+ /**
1171
+ * Update configuration
1172
+ */
1173
+ setConfig(config) {
1174
+ this.config = { ...this.config, ...config };
1175
+ }
1176
+ /**
1177
+ * Filter sensitive headers
1178
+ */
1179
+ filterHeaders(headers) {
1180
+ if (!headers) return {};
1181
+ const filtered = {};
1182
+ Object.keys(headers).forEach((key) => {
1183
+ const lowerKey = key.toLowerCase();
1184
+ if (SENSITIVE_HEADERS2.includes(lowerKey)) {
1185
+ filtered[key] = "***";
1186
+ } else {
1187
+ filtered[key] = headers[key] || "";
1188
+ }
1189
+ });
1190
+ return filtered;
1191
+ }
1192
+ /**
1193
+ * Log request
1194
+ */
1195
+ logRequest(request) {
1196
+ if (!this.config.enabled || !this.config.logRequests) return;
1197
+ const { method, url, headers, body } = request;
1198
+ this.consola.start(`${method} ${url}`);
1199
+ if (this.config.logHeaders && headers) {
1200
+ this.consola.debug("Headers:", this.filterHeaders(headers));
1201
+ }
1202
+ if (this.config.logBodies && body) {
1203
+ this.consola.debug("Body:", body);
1204
+ }
1205
+ }
1206
+ /**
1207
+ * Log response
1208
+ */
1209
+ logResponse(request, response) {
1210
+ if (!this.config.enabled || !this.config.logResponses) return;
1211
+ const { method, url } = request;
1212
+ const { status, statusText, data, duration } = response;
1213
+ const statusColor = status >= 500 ? "red" : status >= 400 ? "yellow" : status >= 300 ? "cyan" : "green";
1214
+ this.consola.success(
1215
+ `${method} ${url} ${status} ${statusText} (${duration}ms)`
1216
+ );
1217
+ if (this.config.logBodies && data) {
1218
+ this.consola.debug("Response:", data);
1219
+ }
1220
+ }
1221
+ /**
1222
+ * Log error
1223
+ */
1224
+ logError(request, error) {
1225
+ if (!this.config.enabled || !this.config.logErrors) return;
1226
+ const { method, url } = request;
1227
+ const { message, statusCode, fieldErrors, duration } = error;
1228
+ this.consola.error(
1229
+ `${method} ${url} ${statusCode || "Network"} Error (${duration}ms)`
1230
+ );
1231
+ this.consola.error("Message:", message);
1232
+ if (fieldErrors && Object.keys(fieldErrors).length > 0) {
1233
+ this.consola.error("Field Errors:");
1234
+ Object.entries(fieldErrors).forEach(([field, errors]) => {
1235
+ errors.forEach((err) => {
1236
+ this.consola.error(` \u2022 ${field}: ${err}`);
1237
+ });
1238
+ });
1239
+ }
1240
+ }
1241
+ /**
1242
+ * Log general info
1243
+ */
1244
+ info(message, ...args) {
1245
+ if (!this.config.enabled) return;
1246
+ this.consola.info(message, ...args);
1247
+ }
1248
+ /**
1249
+ * Log warning
1250
+ */
1251
+ warn(message, ...args) {
1252
+ if (!this.config.enabled) return;
1253
+ this.consola.warn(message, ...args);
1254
+ }
1255
+ /**
1256
+ * Log error
1257
+ */
1258
+ error(message, ...args) {
1259
+ if (!this.config.enabled) return;
1260
+ this.consola.error(message, ...args);
1261
+ }
1262
+ /**
1263
+ * Log debug
1264
+ */
1265
+ debug(message, ...args) {
1266
+ if (!this.config.enabled) return;
1267
+ this.consola.debug(message, ...args);
1268
+ }
1269
+ /**
1270
+ * Log success
1271
+ */
1272
+ success(message, ...args) {
1273
+ if (!this.config.enabled) return;
1274
+ this.consola.success(message, ...args);
1275
+ }
1276
+ /**
1277
+ * Create a sub-logger with prefix
1278
+ */
1279
+ withTag(tag) {
1280
+ return this.consola.withTag(tag);
1281
+ }
1282
+ };
1283
+ var defaultLogger2 = new APILogger2();
1284
+
1285
+ // src/generated/cfg_centrifugo/retry.ts
1286
+ import pRetry2, { AbortError as AbortError2 } from "p-retry";
1287
+
1288
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoChannelInfo.schema.ts
1289
+ import { z as z20 } from "zod";
1290
+ var CentrifugoChannelInfoSchema = z20.object({
1291
+ num_clients: z20.int()
1292
+ });
1293
+
1294
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoChannelsRequestRequest.schema.ts
1295
+ import { z as z21 } from "zod";
1296
+ var CentrifugoChannelsRequestRequestSchema = z21.object({
1297
+ pattern: z21.string().nullable().optional()
1298
+ });
1299
+
1300
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoChannelsResponse.schema.ts
1301
+ import { z as z24 } from "zod";
1302
+
1303
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoChannelsResult.schema.ts
1304
+ import { z as z22 } from "zod";
1305
+ var CentrifugoChannelsResultSchema = z22.object({
1306
+ channels: z22.record(z22.string(), CentrifugoChannelInfoSchema)
1307
+ });
1308
+
1309
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoError.schema.ts
1310
+ import { z as z23 } from "zod";
1311
+ var CentrifugoErrorSchema = z23.object({
1312
+ code: z23.int().optional(),
1313
+ message: z23.string().optional()
1314
+ });
1315
+
1316
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoChannelsResponse.schema.ts
1317
+ var CentrifugoChannelsResponseSchema = z24.object({
1318
+ error: CentrifugoErrorSchema.optional(),
1319
+ result: CentrifugoChannelsResultSchema.optional()
1320
+ });
1321
+
1322
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoClientInfo.schema.ts
1323
+ import { z as z25 } from "zod";
1324
+ var CentrifugoClientInfoSchema = z25.object({
1325
+ user: z25.string(),
1326
+ client: z25.string(),
1327
+ conn_info: z25.record(z25.string(), z25.any()).nullable().optional(),
1328
+ chan_info: z25.record(z25.string(), z25.any()).nullable().optional()
1329
+ });
1330
+
1331
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoHealthCheck.schema.ts
1332
+ import { z as z26 } from "zod";
1333
+ var CentrifugoHealthCheckSchema = z26.object({
1334
+ status: z26.string(),
1335
+ wrapper_url: z26.string(),
1336
+ has_api_key: z26.boolean(),
1337
+ timestamp: z26.string()
1338
+ });
1339
+
1340
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoHistoryRequestRequest.schema.ts
1341
+ import { z as z28 } from "zod";
1342
+
1343
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoStreamPosition.schema.ts
1344
+ import { z as z27 } from "zod";
1345
+ var CentrifugoStreamPositionSchema = z27.object({
1346
+ offset: z27.int(),
1347
+ epoch: z27.string()
1348
+ });
1349
+
1350
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoHistoryRequestRequest.schema.ts
1351
+ var CentrifugoHistoryRequestRequestSchema = z28.object({
1352
+ channel: z28.string(),
1353
+ limit: z28.int().nullable().optional(),
1354
+ since: CentrifugoStreamPositionSchema.optional(),
1355
+ reverse: z28.boolean().nullable().optional()
1356
+ });
1357
+
1358
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoHistoryResponse.schema.ts
1359
+ import { z as z31 } from "zod";
1360
+
1361
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoHistoryResult.schema.ts
1362
+ import { z as z30 } from "zod";
1363
+
1364
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoPublication.schema.ts
1365
+ import { z as z29 } from "zod";
1366
+ var CentrifugoPublicationSchema = z29.object({
1367
+ data: z29.record(z29.string(), z29.any()),
1368
+ info: CentrifugoClientInfoSchema.optional(),
1369
+ offset: z29.int(),
1370
+ tags: z29.record(z29.string(), z29.any()).nullable().optional()
1371
+ });
1372
+
1373
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoHistoryResult.schema.ts
1374
+ var CentrifugoHistoryResultSchema = z30.object({
1375
+ publications: z30.array(CentrifugoPublicationSchema),
1376
+ epoch: z30.string(),
1377
+ offset: z30.int()
1378
+ });
1379
+
1380
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoHistoryResponse.schema.ts
1381
+ var CentrifugoHistoryResponseSchema = z31.object({
1382
+ error: CentrifugoErrorSchema.optional(),
1383
+ result: CentrifugoHistoryResultSchema.optional()
1384
+ });
1385
+
1386
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoInfoResponse.schema.ts
1387
+ import { z as z36 } from "zod";
1388
+
1389
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoInfoResult.schema.ts
1390
+ import { z as z35 } from "zod";
1391
+
1392
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoNodeInfo.schema.ts
1393
+ import { z as z34 } from "zod";
1394
+
1395
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoMetrics.schema.ts
1396
+ import { z as z32 } from "zod";
1397
+ var CentrifugoMetricsSchema = z32.object({
1398
+ interval: z32.number(),
1399
+ items: z32.record(z32.string(), z32.number())
1400
+ });
1401
+
1402
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoProcess.schema.ts
1403
+ import { z as z33 } from "zod";
1404
+ var CentrifugoProcessSchema = z33.object({
1405
+ cpu: z33.number(),
1406
+ rss: z33.int()
1407
+ });
1408
+
1409
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoNodeInfo.schema.ts
1410
+ var CentrifugoNodeInfoSchema = z34.object({
1411
+ uid: z34.string(),
1412
+ name: z34.string(),
1413
+ version: z34.string(),
1414
+ num_clients: z34.int(),
1415
+ num_users: z34.int(),
1416
+ num_channels: z34.int(),
1417
+ uptime: z34.int(),
1418
+ num_subs: z34.int(),
1419
+ metrics: CentrifugoMetricsSchema.optional(),
1420
+ process: CentrifugoProcessSchema.optional()
1421
+ });
1422
+
1423
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoInfoResult.schema.ts
1424
+ var CentrifugoInfoResultSchema = z35.object({
1425
+ nodes: z35.array(CentrifugoNodeInfoSchema)
1426
+ });
1427
+
1428
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoInfoResponse.schema.ts
1429
+ var CentrifugoInfoResponseSchema = z36.object({
1430
+ error: CentrifugoErrorSchema.optional(),
1431
+ result: CentrifugoInfoResultSchema.optional()
1432
+ });
1433
+
1434
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoOverviewStats.schema.ts
1435
+ import { z as z37 } from "zod";
1436
+ var CentrifugoOverviewStatsSchema = z37.object({
1437
+ total: z37.int(),
1438
+ successful: z37.int(),
1439
+ failed: z37.int(),
1440
+ timeout: z37.int(),
1441
+ success_rate: z37.number(),
1442
+ avg_duration_ms: z37.number(),
1443
+ avg_acks_received: z37.number(),
1444
+ period_hours: z37.int()
1445
+ });
1446
+
1447
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoPresenceRequestRequest.schema.ts
1448
+ import { z as z38 } from "zod";
1449
+ var CentrifugoPresenceRequestRequestSchema = z38.object({
1450
+ channel: z38.string()
1451
+ });
1452
+
1453
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoPresenceResponse.schema.ts
1454
+ import { z as z40 } from "zod";
1455
+
1456
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoPresenceResult.schema.ts
1457
+ import { z as z39 } from "zod";
1458
+ var CentrifugoPresenceResultSchema = z39.object({
1459
+ presence: z39.record(z39.string(), CentrifugoClientInfoSchema)
1460
+ });
1461
+
1462
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoPresenceResponse.schema.ts
1463
+ var CentrifugoPresenceResponseSchema = z40.object({
1464
+ error: CentrifugoErrorSchema.optional(),
1465
+ result: CentrifugoPresenceResultSchema.optional()
1466
+ });
1467
+
1468
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoPresenceStatsRequestRequest.schema.ts
1469
+ import { z as z41 } from "zod";
1470
+ var CentrifugoPresenceStatsRequestRequestSchema = z41.object({
1471
+ channel: z41.string()
1472
+ });
1473
+
1474
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoPresenceStatsResponse.schema.ts
1475
+ import { z as z43 } from "zod";
1476
+
1477
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoPresenceStatsResult.schema.ts
1478
+ import { z as z42 } from "zod";
1479
+ var CentrifugoPresenceStatsResultSchema = z42.object({
1480
+ num_clients: z42.int(),
1481
+ num_users: z42.int()
1482
+ });
1483
+
1484
+ // src/generated/cfg_centrifugo/_utils/schemas/CentrifugoPresenceStatsResponse.schema.ts
1485
+ var CentrifugoPresenceStatsResponseSchema = z43.object({
1486
+ error: CentrifugoErrorSchema.optional(),
1487
+ result: CentrifugoPresenceStatsResultSchema.optional()
1488
+ });
1489
+
1490
+ // src/generated/cfg_centrifugo/_utils/schemas/ChannelList.schema.ts
1491
+ import { z as z45 } from "zod";
1492
+
1493
+ // src/generated/cfg_centrifugo/_utils/schemas/ChannelStats.schema.ts
1494
+ import { z as z44 } from "zod";
1495
+ var ChannelStatsSchema = z44.object({
1496
+ channel: z44.string(),
1497
+ total: z44.int(),
1498
+ successful: z44.int(),
1499
+ failed: z44.int(),
1500
+ avg_duration_ms: z44.number(),
1501
+ avg_acks: z44.number(),
1502
+ last_activity_at: z44.string().nullable()
1503
+ });
1504
+
1505
+ // src/generated/cfg_centrifugo/_utils/schemas/ChannelList.schema.ts
1506
+ var ChannelListSchema = z45.object({
1507
+ channels: z45.array(ChannelStatsSchema),
1508
+ total_channels: z45.int()
1509
+ });
1510
+
1511
+ // src/generated/cfg_centrifugo/_utils/schemas/ConnectionTokenResponse.schema.ts
1512
+ import { z as z46 } from "zod";
1513
+ var ConnectionTokenResponseSchema = z46.object({
1514
+ token: z46.string(),
1515
+ centrifugo_url: z46.string(),
1516
+ expires_at: z46.string(),
1517
+ channels: z46.array(z46.string())
1518
+ });
1519
+
1520
+ // src/generated/cfg_centrifugo/_utils/schemas/ManualAckRequestRequest.schema.ts
1521
+ import { z as z47 } from "zod";
1522
+ var ManualAckRequestRequestSchema = z47.object({
1523
+ message_id: z47.string(),
1524
+ client_id: z47.string()
1525
+ });
1526
+
1527
+ // src/generated/cfg_centrifugo/_utils/schemas/ManualAckResponse.schema.ts
1528
+ import { z as z48 } from "zod";
1529
+ var ManualAckResponseSchema = z48.object({
1530
+ success: z48.boolean(),
1531
+ message_id: z48.string(),
1532
+ error: z48.string().nullable().optional()
1533
+ });
1534
+
1535
+ // src/generated/cfg_centrifugo/_utils/schemas/PaginatedPublishList.schema.ts
1536
+ import { z as z50 } from "zod";
1537
+
1538
+ // src/generated/cfg_centrifugo/_utils/schemas/Publish.schema.ts
1539
+ import { z as z49 } from "zod";
1540
+ var PublishSchema = z49.object({
1541
+ message_id: z49.string(),
1542
+ channel: z49.string(),
1543
+ status: z49.string(),
1544
+ wait_for_ack: z49.boolean(),
1545
+ acks_received: z49.int(),
1546
+ acks_expected: z49.int().nullable(),
1547
+ duration_ms: z49.number().nullable(),
1548
+ created_at: z49.iso.datetime(),
1549
+ completed_at: z49.iso.datetime().nullable(),
1550
+ error_code: z49.string().nullable(),
1551
+ error_message: z49.string().nullable()
1552
+ });
1553
+
1554
+ // src/generated/cfg_centrifugo/_utils/schemas/PaginatedPublishList.schema.ts
1555
+ var PaginatedPublishListSchema = z50.object({
1556
+ count: z50.int(),
1557
+ page: z50.int(),
1558
+ pages: z50.int(),
1559
+ page_size: z50.int(),
1560
+ has_next: z50.boolean(),
1561
+ has_previous: z50.boolean(),
1562
+ next_page: z50.int().nullable().optional(),
1563
+ previous_page: z50.int().nullable().optional(),
1564
+ results: z50.array(PublishSchema)
1565
+ });
1566
+
1567
+ // src/generated/cfg_centrifugo/_utils/schemas/PublishTestRequestRequest.schema.ts
1568
+ import { z as z51 } from "zod";
1569
+ var PublishTestRequestRequestSchema = z51.object({
1570
+ channel: z51.string(),
1571
+ data: z51.record(z51.string(), z51.any()),
1572
+ wait_for_ack: z51.boolean().optional(),
1573
+ ack_timeout: z51.int().min(1).max(60).optional()
1574
+ });
1575
+
1576
+ // src/generated/cfg_centrifugo/_utils/schemas/PublishTestResponse.schema.ts
1577
+ import { z as z52 } from "zod";
1578
+ var PublishTestResponseSchema = z52.object({
1579
+ success: z52.boolean(),
1580
+ message_id: z52.string(),
1581
+ channel: z52.string(),
1582
+ acks_received: z52.int().optional(),
1583
+ delivered: z52.boolean().optional(),
1584
+ error: z52.string().nullable().optional()
1585
+ });
1586
+
1587
+ // src/generated/cfg_centrifugo/_utils/schemas/TimelineItem.schema.ts
1588
+ import { z as z53 } from "zod";
1589
+ var TimelineItemSchema = z53.object({
1590
+ timestamp: z53.string(),
1591
+ count: z53.int(),
1592
+ successful: z53.int(),
1593
+ failed: z53.int(),
1594
+ timeout: z53.int()
1595
+ });
1596
+
1597
+ // src/generated/cfg_centrifugo/_utils/schemas/TimelineResponse.schema.ts
1598
+ import { z as z54 } from "zod";
1599
+ var TimelineResponseSchema = z54.object({
1600
+ timeline: z54.array(TimelineItemSchema),
1601
+ period_hours: z54.int(),
1602
+ interval: z54.string()
1603
+ });
1604
+
1605
+ // src/generated/cfg_centrifugo/_utils/fetchers/centrifugo__centrifugo_admin_api.ts
1606
+ import { consola as consola5 } from "consola";
1607
+
1608
+ // src/generated/cfg_centrifugo/_utils/fetchers/centrifugo__centrifugo_auth.ts
1609
+ import { consola as consola6 } from "consola";
1610
+
1611
+ // src/generated/cfg_centrifugo/_utils/fetchers/centrifugo__centrifugo_monitoring.ts
1612
+ import { consola as consola7 } from "consola";
1613
+
1614
+ // src/generated/cfg_centrifugo/_utils/fetchers/centrifugo__centrifugo_testing.ts
1615
+ import { consola as consola8 } from "consola";
1616
+
1617
+ // src/generated/cfg_webpush/logger.ts
1618
+ import { createConsola as createConsola3 } from "consola";
1619
+ var DEFAULT_CONFIG3 = {
1620
+ enabled: process.env.NODE_ENV !== "production",
1621
+ logRequests: true,
1622
+ logResponses: true,
1623
+ logErrors: true,
1624
+ logBodies: true,
1625
+ logHeaders: false
1626
+ };
1627
+ var SENSITIVE_HEADERS3 = [
1628
+ "authorization",
1629
+ "cookie",
1630
+ "set-cookie",
1631
+ "x-api-key",
1632
+ "x-csrf-token"
1633
+ ];
1634
+ var APILogger3 = class {
1635
+ static {
1636
+ __name(this, "APILogger");
1637
+ }
1638
+ constructor(config = {}) {
1639
+ this.config = { ...DEFAULT_CONFIG3, ...config };
1640
+ this.consola = config.consola || createConsola3({
1641
+ level: this.config.enabled ? 4 : 0
1642
+ });
1643
+ }
1644
+ /**
1645
+ * Enable logging
1646
+ */
1647
+ enable() {
1648
+ this.config.enabled = true;
1649
+ }
1650
+ /**
1651
+ * Disable logging
1652
+ */
1653
+ disable() {
1654
+ this.config.enabled = false;
1655
+ }
1656
+ /**
1657
+ * Update configuration
1658
+ */
1659
+ setConfig(config) {
1660
+ this.config = { ...this.config, ...config };
1661
+ }
1662
+ /**
1663
+ * Filter sensitive headers
1664
+ */
1665
+ filterHeaders(headers) {
1666
+ if (!headers) return {};
1667
+ const filtered = {};
1668
+ Object.keys(headers).forEach((key) => {
1669
+ const lowerKey = key.toLowerCase();
1670
+ if (SENSITIVE_HEADERS3.includes(lowerKey)) {
1671
+ filtered[key] = "***";
1672
+ } else {
1673
+ filtered[key] = headers[key] || "";
1674
+ }
1675
+ });
1676
+ return filtered;
1677
+ }
1678
+ /**
1679
+ * Log request
1680
+ */
1681
+ logRequest(request) {
1682
+ if (!this.config.enabled || !this.config.logRequests) return;
1683
+ const { method, url, headers, body } = request;
1684
+ this.consola.start(`${method} ${url}`);
1685
+ if (this.config.logHeaders && headers) {
1686
+ this.consola.debug("Headers:", this.filterHeaders(headers));
1687
+ }
1688
+ if (this.config.logBodies && body) {
1689
+ this.consola.debug("Body:", body);
1690
+ }
1691
+ }
1692
+ /**
1693
+ * Log response
1694
+ */
1695
+ logResponse(request, response) {
1696
+ if (!this.config.enabled || !this.config.logResponses) return;
1697
+ const { method, url } = request;
1698
+ const { status, statusText, data, duration } = response;
1699
+ const statusColor = status >= 500 ? "red" : status >= 400 ? "yellow" : status >= 300 ? "cyan" : "green";
1700
+ this.consola.success(
1701
+ `${method} ${url} ${status} ${statusText} (${duration}ms)`
1702
+ );
1703
+ if (this.config.logBodies && data) {
1704
+ this.consola.debug("Response:", data);
1705
+ }
1706
+ }
1707
+ /**
1708
+ * Log error
1709
+ */
1710
+ logError(request, error) {
1711
+ if (!this.config.enabled || !this.config.logErrors) return;
1712
+ const { method, url } = request;
1713
+ const { message, statusCode, fieldErrors, duration } = error;
1714
+ this.consola.error(
1715
+ `${method} ${url} ${statusCode || "Network"} Error (${duration}ms)`
1716
+ );
1717
+ this.consola.error("Message:", message);
1718
+ if (fieldErrors && Object.keys(fieldErrors).length > 0) {
1719
+ this.consola.error("Field Errors:");
1720
+ Object.entries(fieldErrors).forEach(([field, errors]) => {
1721
+ errors.forEach((err) => {
1722
+ this.consola.error(` \u2022 ${field}: ${err}`);
1723
+ });
1724
+ });
1725
+ }
1726
+ }
1727
+ /**
1728
+ * Log general info
1729
+ */
1730
+ info(message, ...args) {
1731
+ if (!this.config.enabled) return;
1732
+ this.consola.info(message, ...args);
1733
+ }
1734
+ /**
1735
+ * Log warning
1736
+ */
1737
+ warn(message, ...args) {
1738
+ if (!this.config.enabled) return;
1739
+ this.consola.warn(message, ...args);
1740
+ }
1741
+ /**
1742
+ * Log error
1743
+ */
1744
+ error(message, ...args) {
1745
+ if (!this.config.enabled) return;
1746
+ this.consola.error(message, ...args);
1747
+ }
1748
+ /**
1749
+ * Log debug
1750
+ */
1751
+ debug(message, ...args) {
1752
+ if (!this.config.enabled) return;
1753
+ this.consola.debug(message, ...args);
1754
+ }
1755
+ /**
1756
+ * Log success
1757
+ */
1758
+ success(message, ...args) {
1759
+ if (!this.config.enabled) return;
1760
+ this.consola.success(message, ...args);
1761
+ }
1762
+ /**
1763
+ * Create a sub-logger with prefix
1764
+ */
1765
+ withTag(tag) {
1766
+ return this.consola.withTag(tag);
1767
+ }
1768
+ };
1769
+ var defaultLogger3 = new APILogger3();
1770
+
1771
+ // src/generated/cfg_webpush/retry.ts
1772
+ import pRetry3, { AbortError as AbortError3 } from "p-retry";
1773
+
1774
+ // src/generated/cfg_webpush/_utils/schemas/SendPushRequestRequest.schema.ts
1775
+ import { z as z55 } from "zod";
1776
+ var SendPushRequestRequestSchema = z55.object({
1777
+ title: z55.string().min(1).max(255),
1778
+ body: z55.string().min(1),
1779
+ icon: z55.union([z55.url(), z55.literal("")]).nullable().optional(),
1780
+ url: z55.union([z55.url(), z55.literal("")]).nullable().optional()
1781
+ });
1782
+
1783
+ // src/generated/cfg_webpush/_utils/schemas/SendPushResponse.schema.ts
1784
+ import { z as z56 } from "zod";
1785
+ var SendPushResponseSchema = z56.object({
1786
+ success: z56.boolean(),
1787
+ sent_to: z56.int()
1788
+ });
1789
+
1790
+ // src/generated/cfg_webpush/_utils/schemas/SubscribeRequestRequest.schema.ts
1791
+ import { z as z57 } from "zod";
1792
+ var SubscribeRequestRequestSchema = z57.object({
1793
+ endpoint: z57.union([z57.url(), z57.literal("")]),
1794
+ keys: z57.record(z57.string(), z57.string().min(1))
1795
+ });
1796
+
1797
+ // src/generated/cfg_webpush/_utils/schemas/SubscribeResponse.schema.ts
1798
+ import { z as z58 } from "zod";
1799
+ var SubscribeResponseSchema = z58.object({
1800
+ success: z58.boolean(),
1801
+ subscription_id: z58.int(),
1802
+ created: z58.boolean()
1803
+ });
1804
+
1805
+ // src/generated/cfg_webpush/_utils/schemas/VapidPublicKeyResponse.schema.ts
1806
+ import { z as z59 } from "zod";
1807
+ var VapidPublicKeyResponseSchema = z59.object({
1808
+ publicKey: z59.string()
1809
+ });
1810
+
1811
+ // src/generated/cfg_webpush/_utils/fetchers/webpush__web_push.ts
1812
+ import { consola as consola9 } from "consola";
1813
+
1814
+ // src/index.ts
1815
+ var isStaticBuild = process.env.NEXT_PUBLIC_STATIC_BUILD === "true";
1816
+ var apiUrl = isStaticBuild ? "" : process.env.NEXT_PUBLIC_API_URL || "";
1817
+ var api = new API(
1818
+ apiUrl,
1819
+ {
1820
+ storage: new LocalStorageAdapter()
1821
+ }
1822
+ );
1823
+ var BaseClient = class {
1824
+ static {
1825
+ __name(this, "BaseClient");
1826
+ }
1827
+ static {
1828
+ this.api = api;
1829
+ }
1830
+ };
1831
+
1832
+ // src/auth/utils/logger.ts
1833
+ import { createConsola as createConsola4 } from "consola";
1834
+ var isDevelopment = process.env.NODE_ENV === "development";
1835
+ var isStaticBuild2 = process.env.NEXT_PUBLIC_STATIC_BUILD === "true";
1836
+ var showLogs = isDevelopment || isStaticBuild2;
1837
+ var logger = createConsola4({
1838
+ level: showLogs ? 4 : 1
1839
+ // dev: debug, production: errors only
1840
+ }).withTag("api");
1841
+ var authLogger = logger.withTag("auth");
1842
+
1843
+ // src/auth/middlewares/tokenRefresh.ts
1844
+ var isRefreshing = false;
1845
+ var refreshSubscribers = [];
1846
+ function subscribeTokenRefresh(callback) {
1847
+ refreshSubscribers.push(callback);
1848
+ }
1849
+ __name(subscribeTokenRefresh, "subscribeTokenRefresh");
1850
+ function onTokenRefreshed(token) {
1851
+ refreshSubscribers.forEach((callback) => callback(token));
1852
+ refreshSubscribers = [];
1853
+ }
1854
+ __name(onTokenRefreshed, "onTokenRefreshed");
1855
+ async function refreshAccessToken() {
1856
+ if (isRefreshing) {
1857
+ return new Promise((resolve) => {
1858
+ subscribeTokenRefresh((token) => resolve(token));
1859
+ });
1860
+ }
1861
+ isRefreshing = true;
1862
+ authLogger.info("Starting token refresh...");
1863
+ try {
1864
+ const refreshToken = api.getRefreshToken();
1865
+ if (!refreshToken) {
1866
+ authLogger.warn("No refresh token available for refresh");
1867
+ onTokenRefreshed(null);
1868
+ return null;
1869
+ }
1870
+ const response = await fetch("/api/accounts/token/refresh/", {
1871
+ method: "POST",
1872
+ headers: {
1873
+ "Content-Type": "application/json"
1874
+ },
1875
+ body: JSON.stringify({ refresh: refreshToken })
1876
+ });
1877
+ if (!response.ok) {
1878
+ authLogger.error("Token refresh failed with status:", response.status);
1879
+ onTokenRefreshed(null);
1880
+ return null;
1881
+ }
1882
+ const data = await response.json();
1883
+ const newAccessToken = data.access;
1884
+ if (!newAccessToken) {
1885
+ authLogger.error("Token refresh response missing access token");
1886
+ onTokenRefreshed(null);
1887
+ return null;
1888
+ }
1889
+ api.setToken(newAccessToken, refreshToken);
1890
+ authLogger.info("Token refreshed successfully");
1891
+ onTokenRefreshed(newAccessToken);
1892
+ return newAccessToken;
1893
+ } catch (error) {
1894
+ authLogger.error("Token refresh error:", error);
1895
+ onTokenRefreshed(null);
1896
+ return null;
1897
+ } finally {
1898
+ isRefreshing = false;
1899
+ }
1900
+ }
1901
+ __name(refreshAccessToken, "refreshAccessToken");
1902
+ function isAuthenticationError(response) {
1903
+ return response.status === 401;
1904
+ }
1905
+ __name(isAuthenticationError, "isAuthenticationError");
1906
+ function createAutoRefreshFetch(originalFetch) {
1907
+ return async (input, init) => {
1908
+ let response = await originalFetch(input, init);
1909
+ if (isAuthenticationError(response) && api.getRefreshToken()) {
1910
+ authLogger.info("Received 401, attempting token refresh...");
1911
+ const newToken = await refreshAccessToken();
1912
+ if (newToken) {
1913
+ const newInit = {
1914
+ ...init,
1915
+ headers: {
1916
+ ...init?.headers,
1917
+ Authorization: `Bearer ${newToken}`
1918
+ }
1919
+ };
1920
+ authLogger.info("Retrying request with new token...");
1921
+ response = await originalFetch(input, newInit);
1922
+ } else {
1923
+ authLogger.warn("Token refresh failed, returning original 401 response");
1924
+ }
1925
+ }
1926
+ return response;
1927
+ };
1928
+ }
1929
+ __name(createAutoRefreshFetch, "createAutoRefreshFetch");
1930
+ function isTokenExpiringSoon(thresholdMs = 5 * 60 * 1e3) {
1931
+ const token = api.getToken();
1932
+ if (!token) return false;
1933
+ try {
1934
+ const payload = JSON.parse(atob(token.split(".")[1]));
1935
+ const expiresAt = payload.exp * 1e3;
1936
+ const now = Date.now();
1937
+ const timeUntilExpiry = expiresAt - now;
1938
+ return timeUntilExpiry < thresholdMs;
1939
+ } catch (error) {
1940
+ authLogger.error("Error checking token expiry:", error);
1941
+ return false;
1942
+ }
1943
+ }
1944
+ __name(isTokenExpiringSoon, "isTokenExpiringSoon");
1945
+ async function refreshIfExpiringSoon(thresholdMs = 5 * 60 * 1e3) {
1946
+ if (isTokenExpiringSoon(thresholdMs)) {
1947
+ authLogger.info("Token expiring soon, proactively refreshing...");
1948
+ await refreshAccessToken();
1949
+ }
1950
+ }
1951
+ __name(refreshIfExpiringSoon, "refreshIfExpiringSoon");
23
1952
  export {
1953
+ createAutoRefreshFetch,
1954
+ isAuthenticationError,
1955
+ isTokenExpiringSoon,
24
1956
  proxyMiddleware,
25
- proxyMiddlewareConfig
1957
+ proxyMiddlewareConfig,
1958
+ refreshAccessToken,
1959
+ refreshIfExpiringSoon
26
1960
  };
27
1961
  //# sourceMappingURL=auth-server.mjs.map