@djangocfg/api 2.1.87 → 2.1.89

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